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.<code>, with error.unknown as the fallback
This commit is contained in:
parent
abeef4e30f
commit
7363b80ebd
5 changed files with 263 additions and 5 deletions
86
web/src/i18n/i18n.test.ts
Normal file
86
web/src/i18n/i18n.test.ts
Normal file
|
|
@ -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<string, unknown>, prefix = ''): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {}
|
||||
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<string, unknown>, 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')
|
||||
})
|
||||
67
web/src/i18n/index.ts
Normal file
67
web/src/i18n/index.ts
Normal file
|
|
@ -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<void> {
|
||||
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<void> {
|
||||
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<void> } {
|
||||
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 }
|
||||
51
web/src/i18n/locales/en.json
Normal file
51
web/src/i18n/locales/en.json
Normal file
|
|
@ -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."
|
||||
}
|
||||
}
|
||||
51
web/src/i18n/locales/it.json
Normal file
51
web/src/i18n/locales/it.json
Normal file
|
|
@ -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."
|
||||
}
|
||||
}
|
||||
|
|
@ -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(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
void initI18n().then(() => {
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in a new issue