From 7363b80ebdbe9a020f4dc13cfdd720e610c9b9f8 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 11:18:34 +0100 Subject: [PATCH] feat(web): English and Italian UI text - i18next with en and it, language from the stored choice, then the browser, then English - a test keeps both files on the same keys with no empty text - API error codes map to error., with error.unknown as the fallback --- web/src/i18n/i18n.test.ts | 86 ++++++++++++++++++++++++++++++++++++ web/src/i18n/index.ts | 67 ++++++++++++++++++++++++++++ web/src/i18n/locales/en.json | 51 +++++++++++++++++++++ web/src/i18n/locales/it.json | 51 +++++++++++++++++++++ web/src/main.tsx | 13 +++--- 5 files changed, 263 insertions(+), 5 deletions(-) create mode 100644 web/src/i18n/i18n.test.ts create mode 100644 web/src/i18n/index.ts create mode 100644 web/src/i18n/locales/en.json create mode 100644 web/src/i18n/locales/it.json diff --git a/web/src/i18n/i18n.test.ts b/web/src/i18n/i18n.test.ts new file mode 100644 index 0000000..7a1bf07 --- /dev/null +++ b/web/src/i18n/i18n.test.ts @@ -0,0 +1,86 @@ +import { afterEach, expect, test, vi } from 'vitest' +import i18n from 'i18next' +import en from './locales/en.json' +import it from './locales/it.json' +import { errorMessageKey, initI18n, setLanguage } from './index' + +function flatten(obj: Record, prefix = ''): Record { + const out: Record = {} + for (const [key, value] of Object.entries(obj)) { + const path = prefix ? `${prefix}.${key}` : key + if (value && typeof value === 'object') Object.assign(out, flatten(value as Record, path)) + else out[path] = value + } + return out +} + +function browserLanguage(value: string) { + vi.spyOn(navigator, 'language', 'get').mockReturnValue(value) +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +test('English and Italian have exactly the same keys', () => { + expect(Object.keys(flatten(it)).sort()).toEqual(Object.keys(flatten(en)).sort()) +}) + +test('no text is empty', () => { + for (const messages of [en, it]) { + for (const [key, value] of Object.entries(flatten(messages))) { + expect(String(value).trim(), key).not.toBe('') + } + } +}) + +test('an Italian browser gets Italian', async () => { + browserLanguage('it-IT') + await initI18n() + expect(i18n.language).toBe('it') + expect(i18n.t('nav.home')).toBe(flatten(it)['nav.home']) +}) + +test('any other browser language gets English', async () => { + browserLanguage('fr-FR') + await initI18n() + expect(i18n.language).toBe('en') +}) + +test('a stored language beats the browser language', async () => { + browserLanguage('it-IT') + localStorage.setItem('sonda.lang', 'en') + await initI18n() + expect(i18n.language).toBe('en') +}) + +test('a stored value that is not a language is ignored', async () => { + browserLanguage('en-US') + localStorage.setItem('sonda.lang', 'klingon') + await initI18n() + expect(i18n.language).toBe('en') +}) + +test('setLanguage changes the page language and remembers it', async () => { + browserLanguage('en-US') + await initI18n() + await setLanguage('it') + expect(document.documentElement.lang).toBe('it') + expect(localStorage.getItem('sonda.lang')).toBe('it') + expect(i18n.language).toBe('it') +}) + +test('setLanguage still works when storage throws', async () => { + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('blocked') + }) + await expect(setLanguage('en')).resolves.toBeUndefined() + expect(document.documentElement.lang).toBe('en') +}) + +test('an API error code maps to its text, or to the generic one', async () => { + browserLanguage('en-US') + await initI18n() + expect(errorMessageKey('invalid_credentials')).toBe('error.invalid_credentials') + expect(errorMessageKey('something_new_the_server_added')).toBe('error.unknown') +}) diff --git a/web/src/i18n/index.ts b/web/src/i18n/index.ts new file mode 100644 index 0000000..3e4ea17 --- /dev/null +++ b/web/src/i18n/index.ts @@ -0,0 +1,67 @@ +import i18n from 'i18next' +import { initReactI18next, useTranslation } from 'react-i18next' +import en from './locales/en.json' +import it from './locales/it.json' + +export type Lang = 'en' | 'it' + +const KEY = 'sonda.lang' +const LANGS: readonly Lang[] = ['en', 'it'] + +function isLang(value: unknown): value is Lang { + return LANGS.includes(value as Lang) +} + +function readStored(): string | null { + try { + return localStorage.getItem(KEY) + } catch { + return null + } +} + +/** The stored choice, else Italian for an Italian browser, else English. */ +function detect(): Lang { + const stored = readStored() + if (isLang(stored)) return stored + return navigator.language.toLowerCase().startsWith('it') ? 'it' : 'en' +} + +export async function initI18n(): Promise { + const lng = detect() + if (i18n.isInitialized) { + await i18n.changeLanguage(lng) + } else { + await i18n.use(initReactI18next).init({ + resources: { en: { translation: en }, it: { translation: it } }, + lng, + fallbackLng: 'en', + interpolation: { escapeValue: false }, + }) + } + document.documentElement.lang = lng +} + +export async function setLanguage(lang: Lang): Promise { + if (!i18n.isInitialized) await initI18n() + await i18n.changeLanguage(lang) + document.documentElement.lang = lang + try { + localStorage.setItem(KEY, lang) + } catch { + // The choice still applies for this page view. + } +} + +export function useLanguage(): { lang: Lang; setLanguage: (lang: Lang) => Promise } { + const { i18n: instance } = useTranslation() + return { lang: isLang(instance.language) ? instance.language : 'en', setLanguage } +} + +/** The text key for an API error code, or the generic one when the code is not known here. */ +export function errorMessageKey(code: string): string { + const key = `error.${code}` + return i18n.exists(key) ? key : 'error.unknown' +} + +export { i18n } diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json new file mode 100644 index 0000000..8689d8c --- /dev/null +++ b/web/src/i18n/locales/en.json @@ -0,0 +1,51 @@ +{ + "app": { + "name": "Sonda", + "privacy": "Nothing leaves this server unless an admin turns a provider on." + }, + "nav": { + "main": "Main", + "home": "Home", + "search": "Search", + "artists": "Artists", + "albums": "Albums", + "songs": "Songs", + "settings": "Settings" + }, + "common": { + "loading": "Loading", + "retry": "Try again", + "showMore": "Show more", + "notFound": "This page does not exist", + "backHome": "Back to Home" + }, + "theme": { + "sonda": "Sonda", + "tokyo-night": "Tokyo Night", + "gruvbox-dark": "Gruvbox dark", + "gruvbox-light": "Gruvbox light" + }, + "lang": { + "en": "English", + "it": "Italiano" + }, + "auth": { + "signInTitle": "Sign in", + "registerTitle": "Create the first account", + "username": "Username", + "password": "Password", + "signIn": "Sign in", + "createAccount": "Create account", + "firstUser": "This is a new server: create the first account", + "haveAccount": "I already have an account" + }, + "error": { + "invalid_credentials": "Wrong username or password.", + "registration_closed": "An account already exists. Ask an admin to create yours.", + "username_taken": "That username is taken.", + "invalid_input": "Check what you typed and try again.", + "unauthorized": "Your session has ended. Sign in again.", + "network": "Cannot reach the server. Check your connection and try again.", + "unknown": "Something went wrong. Try again." + } +} diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json new file mode 100644 index 0000000..eb35cae --- /dev/null +++ b/web/src/i18n/locales/it.json @@ -0,0 +1,51 @@ +{ + "app": { + "name": "Sonda", + "privacy": "Niente esce da questo server finché un admin non accende un provider." + }, + "nav": { + "main": "Principale", + "home": "Home", + "search": "Cerca", + "artists": "Artisti", + "albums": "Album", + "songs": "Brani", + "settings": "Impostazioni" + }, + "common": { + "loading": "Caricamento", + "retry": "Riprova", + "showMore": "Mostra altro", + "notFound": "Questa pagina non esiste", + "backHome": "Torna alla Home" + }, + "theme": { + "sonda": "Sonda", + "tokyo-night": "Tokyo Night", + "gruvbox-dark": "Gruvbox scuro", + "gruvbox-light": "Gruvbox chiaro" + }, + "lang": { + "en": "English", + "it": "Italiano" + }, + "auth": { + "signInTitle": "Accedi", + "registerTitle": "Crea il primo account", + "username": "Nome utente", + "password": "Password", + "signIn": "Accedi", + "createAccount": "Crea account", + "firstUser": "Questo server è nuovo: crea il primo account", + "haveAccount": "Ho già un account" + }, + "error": { + "invalid_credentials": "Nome utente o password sbagliati.", + "registration_closed": "Esiste già un account. Chiedi a un admin di creare il tuo.", + "username_taken": "Questo nome utente è già preso.", + "invalid_input": "Controlla quello che hai scritto e riprova.", + "unauthorized": "La sessione è terminata. Accedi di nuovo.", + "network": "Il server non risponde. Controlla la connessione e riprova.", + "unknown": "Qualcosa è andato storto. Riprova." + } +} diff --git a/web/src/main.tsx b/web/src/main.tsx index 255bac5..17a15a0 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -2,12 +2,15 @@ import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css' import App from './App.tsx' +import { initI18n } from './i18n' import { initTheme } from './theme/theme' initTheme() -createRoot(document.getElementById('root')!).render( - - - , -) +void initI18n().then(() => { + createRoot(document.getElementById('root')!).render( + + + , + ) +})