I18n: infrastruktura w aplikacji (i18next+react-i18next, detekcja jezyka PL/EN, przelacznik, testy przymuszone do PL)

This commit is contained in:
tisachi
2026-10-17 09:55:36 +02:00
parent 14dde5cb90
commit 807d2151a2
19 changed files with 335 additions and 7 deletions

77
app/package-lock.json generated
View File

@@ -16,9 +16,11 @@
"@tanstack/react-query": "^5.62.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"i18next": "^26.4.7",
"lucide-react": "^1.33.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-i18next": "^17.0.20",
"react-router-dom": "^6.28.0",
"recharts": "^2.13.3",
"tailwind-merge": "^3.6.0",
@@ -4229,6 +4231,15 @@
"node": ">=18"
}
},
"node_modules/html-parse-stringify": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-4.0.1.tgz",
"integrity": "sha512-0zHsZJrK7S3K2aucXWL6ycoYJ/iNtIcFHC/nYQgFklPtrv5LpJctIiSCroWZWeuoXvuyFdzp6KzjJQ+OT5MfFw==",
"license": "MIT",
"funding": {
"url": "https://locize.com"
}
},
"node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
@@ -4257,6 +4268,34 @@
"node": ">= 14"
}
},
"node_modules/i18next": {
"version": "26.4.7",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.4.7.tgz",
"integrity": "sha512-p/3hqy6EcuqRs6wNwBYwGGC1fzBJSMxV9zMuN814ab/7QjdZbXfjXwuPZdQbngX6KDOTxM01uUiZyqmMB8ghZg==",
"funding": [
{
"type": "individual",
"url": "https://www.locize.com/i18next"
},
{
"type": "individual",
"url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
},
{
"type": "individual",
"url": "https://www.locize.com"
}
],
"license": "MIT",
"peerDependencies": {
"typescript": "^5 || ^6 || ^7"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/iconv-lite": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
@@ -5293,6 +5332,33 @@
"react": "^18.3.1"
}
},
"node_modules/react-i18next": {
"version": "17.0.20",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.20.tgz",
"integrity": "sha512-rzSSirf0NP9vfcUXHZAksIuyMWl7L/T/7nm8S+sSIFuIzku54qcyyVAOZXbawPNpUxGkDx/eosSv4DrpzcxuOQ==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.7",
"html-parse-stringify": "^4.0.1",
"use-sync-external-store": "^1.6.0"
},
"peerDependencies": {
"i18next": ">= 26.2.0",
"react": ">= 16.8.0",
"typescript": "^5 || ^6 || ^7"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
},
"react-native": {
"optional": true
},
"typescript": {
"optional": true
}
}
},
"node_modules/react-is": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
@@ -5894,7 +5960,7 @@
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"devOptional": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -5995,6 +6061,15 @@
}
}
},
"node_modules/use-sync-external-store": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz",
"integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/victory-vendor": {
"version": "36.9.2",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz",

View File

@@ -24,9 +24,11 @@
"@tanstack/react-query": "^5.62.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"i18next": "^26.4.7",
"lucide-react": "^1.33.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-i18next": "^17.0.20",
"react-router-dom": "^6.28.0",
"recharts": "^2.13.3",
"tailwind-merge": "^3.6.0",

View File

@@ -10,6 +10,9 @@ export default defineConfig({
reporter: [['list'], ['html', { outputFolder: 'test/report', open: 'never' }]],
use: {
baseURL: 'http://localhost:5173',
// Playwright/Chromium domyślnie en-US — wymuszamy PL, bo detekcja i18n
// ustawiłaby EN i wszystkie selektory PL w e2e przestałyby pasować.
locale: 'pl-PL',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},

View File

@@ -1,6 +1,6 @@
import type { ReactNode } from 'react';
import { Dumbbell, Handshake, Ruler } from 'lucide-react';
import { Card, ThemeToggle } from './ui';
import { Card, ThemeToggle, LanguageToggle } from './ui';
import { Brandmark } from './Brandmark';
/* Layout stron auth: panel brandingowy (gradient w akcencie + wzór siatki, claim)
@@ -8,7 +8,10 @@ import { Brandmark } from './Brandmark';
export default function AuthShell({ children }: { children: ReactNode }) {
return (
<div className="relative flex min-h-dvh items-center justify-center p-4">
<ThemeToggle className="fixed right-4 top-4 z-10" />
<div className="fixed right-4 top-4 z-10 flex items-center gap-2">
<ThemeToggle />
<LanguageToggle />
</div>
<div className="grid w-full max-w-3xl overflow-hidden rounded-2xl border border-line bg-card shadow-card md:grid-cols-2">
<div
className="relative flex flex-col gap-3.5 overflow-hidden border-b border-line p-7 md:border-b-0 md:border-r md:p-8"

View File

@@ -27,7 +27,7 @@ import {
useInvitations,
useIsTrainer,
} from '../api/queries';
import { ThemeToggle, Button } from './ui';
import { ThemeToggle, LanguageToggle, Button } from './ui';
import { ToastProvider } from './toast';
import { Topbar } from '../topbar';
import { Brandmark } from './Brandmark';
@@ -256,6 +256,7 @@ export default function Layout() {
</div>
<div className="flex items-center gap-2">
<ThemeToggle />
<LanguageToggle />
<Button variant="secondary" size="sm" className="flex-1" onClick={doLogout}>
<LogOut className="w-4 h-4" />
Wyloguj
@@ -269,6 +270,7 @@ export default function Layout() {
<div className="mt-auto flex flex-col items-center gap-2.5 border-t border-line px-2 pb-4 pt-3">
<Avatar name={fullName} size={32} />
<ThemeToggle />
<LanguageToggle />
<button
type="button"
onClick={doLogout}

View File

@@ -24,6 +24,7 @@ export * from './ui/content';
export * from './ui/dialogs';
export * from './ui/week-picker';
export * from './ui/theme-toggle';
export * from './ui/language-toggle';
/* Button */
export type ButtonVariant = 'primary' | 'secondary' | 'danger' | 'ghost';

View File

@@ -0,0 +1,22 @@
import { Languages } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { changeLanguage } from '../../i18n';
import type { Language } from '../../i18n/language';
const OTHER: Record<Language, Language> = { pl: 'en', en: 'pl' };
export function LanguageToggle({ className = '' }: { className?: string }) {
const { t, i18n } = useTranslation();
const current: Language = i18n.language === 'en' ? 'en' : 'pl';
const next = OTHER[current];
return (
<button
onClick={() => changeLanguage(next)}
aria-label={`${t('common:toggleLanguage')} (${current.toUpperCase()} → ${next.toUpperCase()})`}
title={`${current.toUpperCase()} → ${next.toUpperCase()}`}
className={`inline-flex items-center justify-center p-2.5 rounded-[10px] bg-card border border-line text-dim shadow-card hover:text-ink hover:border-accent/45 cursor-pointer transition-all duration-150 ${className}`.trim()}
>
<Languages className="w-5 h-5" />
</button>
);
}

View File

@@ -1,13 +1,16 @@
import { Moon, Sun } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useTheme } from '../../store/theme';
export function ThemeToggle({ className = '' }: { className?: string }) {
const { theme, toggle } = useTheme();
const { t } = useTranslation();
const label = t('common:toggleTheme');
return (
<button
onClick={toggle}
aria-label="Przełącz motyw"
title="Przełącz motyw"
aria-label={label}
title={label}
className={`inline-flex items-center justify-center p-2.5 rounded-[10px] bg-card border border-line text-dim shadow-card hover:text-ink hover:border-accent/45 cursor-pointer transition-all duration-150 ${className}`.trim()}
>
{theme === 'dark' ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />}

49
app/src/i18n/index.ts Normal file
View File

@@ -0,0 +1,49 @@
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import {
applyDocumentLanguage,
detectInitialLanguage,
setStoredLanguage,
type Language,
} from './language';
import plCommon from './locales/pl/common.json';
import plAuth from './locales/pl/auth.json';
import plErrors from './locales/pl/errors.json';
import enCommon from './locales/en/common.json';
import enAuth from './locales/en/auth.json';
import enErrors from './locales/en/errors.json';
export const NAMESPACES = ['common', 'auth', 'errors'] as const;
export type Namespace = (typeof NAMESPACES)[number];
const resources = {
pl: { common: plCommon, auth: plAuth, errors: plErrors },
en: { common: enCommon, auth: enAuth, errors: enErrors },
} as const;
const initial = detectInitialLanguage();
applyDocumentLanguage(initial);
void i18n.use(initReactI18next).init({
lng: initial,
fallbackLng: 'pl',
supportedLngs: ['pl', 'en'],
defaultNS: 'common',
ns: [...NAMESPACES],
resources,
interpolation: { escapeValue: false },
react: { useSuspense: false },
});
// <html lang> podąża za językiem także przy zmianie przez i18n.changeLanguage
// (testy, przełącznik), nie tylko przez changeLanguage() z tego modułu.
i18n.on('languageChanged', (lng) => applyDocumentLanguage(lng === 'en' ? 'en' : 'pl'));
export function changeLanguage(lang: Language) {
setStoredLanguage(lang);
void i18n.changeLanguage(lang);
}
export { resolveLocaleTag } from './language';
export { i18n };
export default i18n;

39
app/src/i18n/language.ts Normal file
View File

@@ -0,0 +1,39 @@
export type Language = 'pl' | 'en';
const STORAGE_KEY = 'fitos-lang';
export function getStoredLanguage(): Language | null {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved === 'pl' || saved === 'en') return saved;
} catch {
// ignore
}
return null;
}
export function setStoredLanguage(lang: Language) {
try {
localStorage.setItem(STORAGE_KEY, lang);
} catch {
// ignore
}
}
/* localStorage → navigator.language (en* → en) → pl. */
export function detectInitialLanguage(): Language {
const stored = getStoredLanguage();
if (stored) return stored;
const nav = typeof navigator !== 'undefined' ? navigator.language || '' : '';
if (nav.toLowerCase().startsWith('en')) return 'en';
return 'pl';
}
/* i18n.language ('pl'|'en') → tag do Intl/toLocale*. */
export function resolveLocaleTag(lang: string): string {
return lang === 'en' ? 'en-US' : 'pl-PL';
}
export function applyDocumentLanguage(lang: Language) {
document.documentElement.lang = lang;
}

View File

@@ -0,0 +1,26 @@
{
"email": "Email",
"password": "Password",
"rememberMe": "Remember me",
"login": "Log in",
"loginLoading": "Logging in…",
"noAccount": "Don't have an account?",
"registerLink": "Sign up",
"register": "Sign up",
"registerLoading": "Signing up…",
"registerTitle": "Sign up",
"haveAccount": "Already have an account?",
"loginLink": "Log in",
"passwordMin": "Password (min. 8 characters)",
"firstName": "First name",
"lastName": "Last name",
"claimTitle": "Training that delivers.",
"claimSubtitle": "From planning to the last set.",
"featuresLabel": "Key features",
"featureCoachingTitle": "Coaching",
"featureCoachingDesc": "Under an experienced trainer's eye.",
"featureSetsTitle": "Planned sets",
"featureSetsDesc": "Week → day → session → result.",
"featureMeasuresTitle": "Body measurements",
"featureMeasuresDesc": "Weight and girths over time: stats history."
}

View File

@@ -0,0 +1,16 @@
{
"appName": "FitOS",
"cancel": "Cancel",
"confirm": "Confirm",
"save": "Save",
"close": "Close",
"closeNotification": "Close notification",
"clear": "Clear",
"deleteDigit": "Delete digit",
"input": "Enter",
"difficulty": "Difficulty",
"difficultyLow": "easy",
"difficultyHigh": "hard",
"toggleTheme": "Toggle theme",
"toggleLanguage": "Change language"
}

View File

@@ -0,0 +1,18 @@
{
"BAD_REQUEST": "Invalid request.",
"UNAUTHORIZED": "Session expired — log in again.",
"FORBIDDEN": "You don't have permission for this operation.",
"NOT_FOUND": "Resource not found.",
"CONFLICT": "The change conflicts with existing data.",
"VALIDATION_ERROR": "Please correct the form data.",
"INTERNAL_ERROR": "A server error occurred. Try again.",
"RATE_LIMITED": "Too many attempts. Try again later.",
"GONE": "Invitation expired.",
"UPLOAD_FAILED": "Failed to store files.",
"ACCOUNT_SUSPENDED": "Account suspended.",
"ACCOUNT_SUSPENDED_until": "Account suspended until {{date}}.",
"ACCOUNT_BANNED": "Account blocked by an administrator.",
"reasonSuffix": " Reason: {{reason}}",
"loginFailed": "Login failed",
"registerFailed": "Registration failed"
}

View File

@@ -0,0 +1,26 @@
{
"email": "E-mail",
"password": "Hasło",
"rememberMe": "Zapamiętaj mnie",
"login": "Zaloguj",
"loginLoading": "Logowanie…",
"noAccount": "Nie masz konta?",
"registerLink": "Zarejestruj się",
"register": "Zarejestruj",
"registerLoading": "Rejestracja…",
"registerTitle": "Zarejestruj się",
"haveAccount": "Masz konto?",
"loginLink": "Zaloguj się",
"passwordMin": "Hasło (min. 8 znaków)",
"firstName": "Imię",
"lastName": "Nazwisko",
"claimTitle": "Trening, który się dowozi.",
"claimSubtitle": "Od planowania po ostatnią serię.",
"featuresLabel": "Najważniejsze możliwości",
"featureCoachingTitle": "Coaching",
"featureCoachingDesc": "Pod okiem doświadoczonego trenera.",
"featureSetsTitle": "Serie planowe",
"featureSetsDesc": "Tydzień → dzień → sesja → wynik.",
"featureMeasuresTitle": "Pomiary ciała",
"featureMeasuresDesc": "Waga i obwody w czasie: historia statystyk."
}

View File

@@ -0,0 +1,16 @@
{
"appName": "FitOS",
"cancel": "Anuluj",
"confirm": "Potwierdź",
"save": "Zapisz",
"close": "Zamknij",
"closeNotification": "Zamknij powiadomienie",
"clear": "Wyczyść",
"deleteDigit": "Usuń cyfrę",
"input": "Wpisz",
"difficulty": "Trudność",
"difficultyLow": "łatwo",
"difficultyHigh": "trudno",
"toggleTheme": "Przełącz motyw",
"toggleLanguage": "Zmień język"
}

View File

@@ -0,0 +1,18 @@
{
"BAD_REQUEST": "Nieprawidłowe żądanie.",
"UNAUTHORIZED": "Sesja wygasła — zaloguj się ponownie.",
"FORBIDDEN": "Nie masz uprawnień do tej operacji.",
"NOT_FOUND": "Nie znaleziono zasobu.",
"CONFLICT": "Zmiana koliduje z istniejącymi danymi.",
"VALIDATION_ERROR": "Popraw dane w formularzu.",
"INTERNAL_ERROR": "Wystąpił błąd serwera. Spróbuj ponownie.",
"RATE_LIMITED": "Zbyt wiele prób. Spróbuj później.",
"GONE": "Zaproszenie wygasło.",
"UPLOAD_FAILED": "Nie udało się zapisać plików.",
"ACCOUNT_SUSPENDED": "Konto zawieszone.",
"ACCOUNT_SUSPENDED_until": "Konto zawieszone do {{date}}.",
"ACCOUNT_BANNED": "Konto zablokowane przez administratora.",
"reasonSuffix": " Powód: {{reason}}",
"loginFailed": "Błąd logowania",
"registerFailed": "Błąd rejestracji"
}

View File

@@ -11,6 +11,7 @@ import '@fontsource/space-grotesk/500.css';
import '@fontsource/space-grotesk/600.css';
import '@fontsource/space-grotesk/700.css';
import App from './App';
import './i18n';
import { ApiError } from './api/client';
import './styles.css';

View File

@@ -1,6 +1,13 @@
import '@testing-library/jest-dom/vitest';
import { afterEach } from 'vitest';
import { afterEach, beforeAll } from 'vitest';
import { cleanup } from '@testing-library/react';
import i18n from '../src/i18n';
// testy jednostowe zawsze PL (jsdom ma navigator.language en-US, więc init
// z detekcji ustawiłby EN) — wymuszamy po inicjalizacji modułu i18n.
beforeAll(async () => {
await i18n.changeLanguage('pl');
});
// recharts (ResponsiveContainer) requires ResizeObserver, which jsdom does not provide.
// Stub wywołuje callback z fikcyjnym rozmiarem — wykresy renderują się w stałym 800×600.

View File

@@ -5,6 +5,7 @@
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"resolveJsonModule": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,