feat(i18n): language foundation with en and pt-BR
Nothing in the project was translatable — every string sat inline in English. en.ts is the source dictionary and its type is derived from it, so a typo or a missing key fails typecheck instead of rendering the raw key at runtime. pt-BR.ts is deliberately Partial: translation proceeds one system per update and anything absent falls back to English, so a half-migrated interface is never broken, only partly English. Locale is persisted, guessed from the browser on first run, and kept in sync with <html lang> through a subscription — persisted state rehydrates after first paint, so a one-off assignment would miss it. Translates the voice input panel (including the mic test shipped earlier today) and the profile card as this round's system. Language options are labelled in the active language, so a wrong pick can always be undone.
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { translate } from './index';
|
||||
import { en } from './locales/en';
|
||||
import { ptBR } from './locales/pt-BR';
|
||||
|
||||
describe('translate', () => {
|
||||
it('returns the translation for the active locale', () => {
|
||||
expect(translate('pt-BR', 'settings.tab.account')).toBe('Conta');
|
||||
});
|
||||
|
||||
it('falls back to English for a key the locale has not translated yet', () => {
|
||||
// The whole migration strategy depends on this: pt-BR is deliberately
|
||||
// partial, and an untranslated screen must read in English rather than
|
||||
// break.
|
||||
const untranslated = (Object.keys(en) as (keyof typeof en)[]).find((k) => !(k in ptBR));
|
||||
if (!untranslated) return; // pt-BR fully caught up — nothing to assert
|
||||
expect(translate('pt-BR', untranslated)).toBe(en[untranslated]);
|
||||
});
|
||||
|
||||
it('substitutes named parameters', () => {
|
||||
expect(translate('en', 'profile.activity.elapsed', { time: '3:20' })).toBe('3:20 elapsed');
|
||||
expect(translate('pt-BR', 'profile.activity.elapsed', { time: '3:20' })).toBe('3:20 decorrido');
|
||||
});
|
||||
|
||||
it('leaves a placeholder alone when no value is supplied', () => {
|
||||
expect(translate('en', 'profile.activity.elapsed')).toBe('{time} elapsed');
|
||||
});
|
||||
|
||||
it('keeps every pt-BR key present in the source dictionary', () => {
|
||||
// Guards against a key being renamed in en.ts while pt-BR keeps the old
|
||||
// one, which would silently fall back forever.
|
||||
for (const key of Object.keys(ptBR)) {
|
||||
expect(en).toHaveProperty(key);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
import { en, type TranslationKey } from './locales/en';
|
||||
import { ptBR } from './locales/pt-BR';
|
||||
|
||||
export const LOCALES = ['en', 'pt-BR'] as const;
|
||||
export type Locale = (typeof LOCALES)[number];
|
||||
|
||||
const DICTIONARIES: Record<Locale, Partial<Record<TranslationKey, string>>> = {
|
||||
en,
|
||||
'pt-BR': ptBR,
|
||||
};
|
||||
|
||||
/**
|
||||
* First-run guess from the browser. Persisted afterwards, so an explicit
|
||||
* choice always wins over the browser's setting on later visits.
|
||||
*/
|
||||
function detectLocale(): Locale {
|
||||
if (typeof navigator === 'undefined') return 'en';
|
||||
return navigator.language?.toLowerCase().startsWith('pt') ? 'pt-BR' : 'en';
|
||||
}
|
||||
|
||||
interface LocaleState {
|
||||
locale: Locale;
|
||||
setLocale: (locale: Locale) => void;
|
||||
}
|
||||
|
||||
export const useLocaleStore = create<LocaleState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
locale: detectLocale(),
|
||||
setLocale: (locale) => set({ locale }),
|
||||
}),
|
||||
{ name: 'backspace-locale' },
|
||||
),
|
||||
);
|
||||
|
||||
// Keep <html lang> in sync: screen readers, spellcheck and hyphenation all read
|
||||
// it, and persisted state rehydrates after the first paint — hence the
|
||||
// subscription rather than a one-off assignment.
|
||||
if (typeof document !== 'undefined') {
|
||||
document.documentElement.lang = useLocaleStore.getState().locale;
|
||||
useLocaleStore.subscribe((state) => {
|
||||
document.documentElement.lang = state.locale;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a key, substituting `{name}` placeholders.
|
||||
*
|
||||
* Falls back to English, then to the key itself. The key is a deliberate last
|
||||
* resort: it is ugly on screen, which makes a missing entry obvious in review
|
||||
* instead of silently rendering an empty string.
|
||||
*/
|
||||
export function translate(
|
||||
locale: Locale,
|
||||
key: TranslationKey,
|
||||
params?: Record<string, string | number>,
|
||||
): string {
|
||||
const template = DICTIONARIES[locale]?.[key] ?? en[key] ?? key;
|
||||
if (!params) return template;
|
||||
return template.replace(/\{(\w+)\}/g, (match, name: string) =>
|
||||
name in params ? String(params[name]) : match,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes the calling component to the active locale, so switching language
|
||||
* re-renders it. Components that only need the string once (outside React) can
|
||||
* call `translate` with `useLocaleStore.getState().locale` instead.
|
||||
*/
|
||||
export function useT() {
|
||||
const locale = useLocaleStore((s) => s.locale);
|
||||
return (key: TranslationKey, params?: Record<string, string | number>) =>
|
||||
translate(locale, key, params);
|
||||
}
|
||||
|
||||
export type { TranslationKey };
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Source dictionary. Every key the app can translate is declared here, and its
|
||||
* type is derived from this object — a typo or a missing key fails typecheck
|
||||
* rather than silently rendering the raw key at runtime.
|
||||
*
|
||||
* Keys are flat and dot-namespaced by system (`settings.voice.*`), so a
|
||||
* translation pass can take one system at a time.
|
||||
*/
|
||||
export const en = {
|
||||
// Settings — navigation
|
||||
'settings.tab.account': 'Account',
|
||||
'settings.tab.voice': 'Voice & Video',
|
||||
'settings.tab.privacy': 'Privacy',
|
||||
'settings.tab.connections': 'Connections',
|
||||
'settings.tab.keybinds': 'Keybinds',
|
||||
'settings.tab.desktop': 'Desktop',
|
||||
'settings.tab.instance': 'Instance',
|
||||
'settings.tab.language': 'Language',
|
||||
|
||||
// Settings — language
|
||||
'settings.language.title': 'Language',
|
||||
'settings.language.description': 'Choose the language for the interface. Anything not yet translated stays in English.',
|
||||
'settings.language.en': 'English',
|
||||
'settings.language.ptBR': 'Portuguese (Brazil)',
|
||||
|
||||
// Settings — voice: input
|
||||
'settings.voice.input.title': 'Input Device',
|
||||
'settings.voice.input.volume': 'Input Volume',
|
||||
'settings.voice.micTest.start': "Let's Check",
|
||||
'settings.voice.micTest.stop': 'Stop Testing',
|
||||
'settings.voice.micTest.playing': 'Playing your mic back to you — say something.',
|
||||
'settings.voice.micTest.inCall': 'The level meter is live while you are in a call.',
|
||||
'settings.voice.micTest.idle': 'Test your mic without joining a call.',
|
||||
'settings.voice.micTest.failed': 'Could not open the microphone. Check the device and its permission.',
|
||||
|
||||
// Profile card
|
||||
'profile.aboutMe': 'About Me',
|
||||
'profile.memberSince': 'Member Since',
|
||||
'profile.sendMessage': 'Send Message',
|
||||
'profile.activity.playing': 'Playing',
|
||||
'profile.activity.listening': 'Listening to',
|
||||
'profile.activity.watching': 'Watching',
|
||||
'profile.activity.streaming': 'Streaming',
|
||||
'profile.activity.elapsed': '{time} elapsed',
|
||||
} as const;
|
||||
|
||||
export type TranslationKey = keyof typeof en;
|
||||
export type Dictionary = Record<TranslationKey, string>;
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { Dictionary } from './en';
|
||||
|
||||
/**
|
||||
* Partial on purpose. Translation happens one system per update, and anything
|
||||
* absent here falls back to English — so a half-migrated interface is never
|
||||
* broken, just partly in English.
|
||||
*/
|
||||
export const ptBR: Partial<Dictionary> = {
|
||||
// Configurações — navegação
|
||||
'settings.tab.account': 'Conta',
|
||||
'settings.tab.voice': 'Voz e Vídeo',
|
||||
'settings.tab.privacy': 'Privacidade',
|
||||
'settings.tab.connections': 'Conexões',
|
||||
'settings.tab.keybinds': 'Atalhos',
|
||||
'settings.tab.desktop': 'Desktop',
|
||||
'settings.tab.instance': 'Instância',
|
||||
'settings.tab.language': 'Idioma',
|
||||
|
||||
// Configurações — idioma
|
||||
'settings.language.title': 'Idioma',
|
||||
'settings.language.description': 'Escolha o idioma da interface. O que ainda não foi traduzido continua em inglês.',
|
||||
'settings.language.en': 'Inglês',
|
||||
'settings.language.ptBR': 'Português (Brasil)',
|
||||
|
||||
// Configurações — voz: entrada
|
||||
'settings.voice.input.title': 'Dispositivo de entrada',
|
||||
'settings.voice.input.volume': 'Volume de entrada',
|
||||
'settings.voice.micTest.start': 'Testar microfone',
|
||||
'settings.voice.micTest.stop': 'Parar teste',
|
||||
'settings.voice.micTest.playing': 'Devolvendo seu microfone para você — fale alguma coisa.',
|
||||
'settings.voice.micTest.inCall': 'O medidor fica ativo enquanto você está numa call.',
|
||||
'settings.voice.micTest.idle': 'Teste seu microfone sem entrar numa call.',
|
||||
'settings.voice.micTest.failed': 'Não foi possível abrir o microfone. Verifique o dispositivo e a permissão.',
|
||||
|
||||
// Cartão de perfil
|
||||
'profile.aboutMe': 'Sobre mim',
|
||||
'profile.memberSince': 'Membro desde',
|
||||
'profile.sendMessage': 'Enviar mensagem',
|
||||
'profile.activity.playing': 'Jogando',
|
||||
'profile.activity.listening': 'Ouvindo',
|
||||
'profile.activity.watching': 'Assistindo',
|
||||
'profile.activity.streaming': 'Transmitindo',
|
||||
'profile.activity.elapsed': '{time} decorrido',
|
||||
};
|
||||
Reference in New Issue
Block a user