Skip to content

Commit a566177

Browse files
Add i18n foundation (FR/EN) with a language switcher
Lightweight client i18n: a flat key->string dictionary per language, a t(key, vars) lookup with {var} interpolation, and a persisted language choice (localStorage, defaulting to the browser language). I18nProvider wraps the app; a FR/EN switcher sits in the sidebar and on the login screen. First surfaces converted: navigation, sidebar chrome and the login page. Remaining pages will be migrated onto the same dictionary.
1 parent 49751a0 commit a566177

5 files changed

Lines changed: 209 additions & 29 deletions

File tree

‎apps/web/src/app/(app)/layout.tsx‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,22 @@ import { usePathname, useRouter } from 'next/navigation';
55
import { useEffect, useState } from 'react';
66
import { FolderLock, Share2, Globe, Settings, ShieldCheck, LogOut, Menu, X, Trash2 } from 'lucide-react';
77
import { useAuth } from '@/lib/auth';
8+
import { useT } from '@/lib/i18n';
89
import { Wordmark } from '@/components/Wordmark';
10+
import { LanguageSwitcher } from '@/components/LanguageSwitcher';
911
import { StatusBanner } from '@/components/StatusBanner';
1012
import { formatBytes } from '@opencoperlock/shared/client';
1113

1214
const NAV = [
13-
{ href: '/drive', label: 'Mes Espaces', icon: FolderLock },
14-
{ href: '/shares', label: 'Partages', icon: Share2 },
15-
{ href: '/remote', label: 'Remote', icon: Globe },
16-
{ href: '/trash', label: 'Corbeille', icon: Trash2 },
15+
{ href: '/drive', labelKey: 'nav.spaces', icon: FolderLock },
16+
{ href: '/shares', labelKey: 'nav.shares', icon: Share2 },
17+
{ href: '/remote', labelKey: 'nav.remote', icon: Globe },
18+
{ href: '/trash', labelKey: 'nav.trash', icon: Trash2 },
1719
];
1820

1921
export default function AppLayout({ children }: { children: React.ReactNode }) {
2022
const { user, loading, logout } = useAuth();
23+
const { t } = useT();
2124
const router = useRouter();
2225
const pathname = usePathname();
2326
const [drawer, setDrawer] = useState(false);
@@ -36,15 +39,15 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {
3639
}
3740

3841
const items = [...NAV];
39-
if (user.role === 'ADMIN') items.push({ href: '/admin', label: 'Administration', icon: ShieldCheck });
42+
if (user.role === 'ADMIN') items.push({ href: '/admin', labelKey: 'nav.admin', icon: ShieldCheck });
4043

4144
const quotaPct =
4245
user.quotaBytes && user.quotaBytes > 0
4346
? Math.min(100, Math.round((user.usedBytes / user.quotaBytes) * 100))
4447
: 0;
4548
const initials = user.email.slice(0, 2).toUpperCase();
4649

47-
const NavLink = ({ href, label, icon: Icon }: (typeof items)[number]) => {
50+
const NavLink = ({ href, labelKey, icon: Icon }: (typeof items)[number]) => {
4851
const active = pathname === href || pathname.startsWith(href + '/');
4952
return (
5053
<Link
@@ -54,7 +57,7 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {
5457
}`}
5558
>
5659
<Icon size={18} strokeWidth={2} />
57-
{label}
60+
{t(labelKey)}
5861
</Link>
5962
);
6063
};
@@ -85,14 +88,17 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {
8588
}`}
8689
>
8790
<Settings size={18} strokeWidth={2} />
88-
Paramètres
91+
{t('nav.settings')}
8992
</Link>
9093
</nav>
9194

9295
<div className="space-y-3 px-3 pb-4">
96+
<div className="flex justify-end px-2">
97+
<LanguageSwitcher />
98+
</div>
9399
<div className="px-2">
94100
<div className="mb-1 flex justify-between text-[11px] text-zinc-500">
95-
<span>Stockage</span>
101+
<span>{t('nav.storage')}</span>
96102
<span>
97103
{formatBytes(user.usedBytes)}
98104
{user.quotaBytes ? ` / ${formatBytes(user.quotaBytes)}` : ''}
@@ -110,11 +116,11 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {
110116
<div className="min-w-0 flex-1">
111117
<p className="truncate text-sm font-medium text-zinc-100">{user.email}</p>
112118
<p className="text-[11px] text-zinc-500">
113-
{user.role === 'ADMIN' ? 'Administrateur' : 'Utilisateur'}
119+
{user.role === 'ADMIN' ? t('role.admin') : t('role.user')}
114120
</p>
115121
</div>
116122
<button
117-
title="Se déconnecter"
123+
title={t('common.signout')}
118124
className="rounded-lg p-1.5 text-zinc-400 transition hover:bg-white/5 hover:text-zinc-100"
119125
onClick={async () => {
120126
await logout();

‎apps/web/src/app/layout.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { Metadata, Viewport } from 'next';
22
import './globals.css';
33
import { AuthProvider } from '@/lib/auth';
4+
import { I18nProvider } from '@/lib/i18n';
45
import { Overlays } from '@/components/ui/overlays';
56
import { PwaRegister } from '@/components/PwaRegister';
67

@@ -51,7 +52,9 @@ export default function RootLayout({ children }: { children: React.ReactNode })
5152
return (
5253
<html lang="fr" className="dark">
5354
<body className="min-h-screen font-sans">
54-
<AuthProvider>{children}</AuthProvider>
55+
<I18nProvider>
56+
<AuthProvider>{children}</AuthProvider>
57+
</I18nProvider>
5558
<Overlays />
5659
<PwaRegister />
5760
</body>

‎apps/web/src/app/login/page.tsx‎

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,15 @@ import Link from 'next/link';
55
import { useRouter } from 'next/navigation';
66
import { ArrowUpRight, ShieldCheck } from 'lucide-react';
77
import { useAuth } from '@/lib/auth';
8+
import { useT } from '@/lib/i18n';
89
import { ApiError } from '@/lib/api';
910
import { Logo } from '@/components/Logo';
1011
import { Wordmark } from '@/components/Wordmark';
12+
import { LanguageSwitcher } from '@/components/LanguageSwitcher';
1113

1214
export default function LoginPage() {
1315
const { login } = useAuth();
16+
const { t } = useT();
1417
const router = useRouter();
1518
const [email, setEmail] = useState('');
1619
const [password, setPassword] = useState('');
@@ -29,9 +32,9 @@ export default function LoginPage() {
2932
} catch (err) {
3033
if (err instanceof ApiError && (err.code === 'TOTP_REQUIRED' || err.code === 'TOTP_INVALID')) {
3134
setNeedTotp(true);
32-
setError(err.code === 'TOTP_INVALID' ? 'Code incorrect. Réessayez.' : null);
35+
setError(err.code === 'TOTP_INVALID' ? t('login.codeIncorrect') : null);
3336
} else {
34-
setError(err instanceof ApiError ? err.message : 'Connexion impossible');
37+
setError(err instanceof ApiError ? err.message : t('login.failed'));
3538
}
3639
} finally {
3740
setBusy(false);
@@ -46,14 +49,14 @@ export default function LoginPage() {
4649
<Logo size={52} />
4750
<div>
4851
<Wordmark className="text-2xl" />
49-
<p className="mt-2 text-sm text-zinc-500">Connectez-vous à votre cloud privé</p>
52+
<p className="mt-2 text-sm text-zinc-500">{t('login.subtitle')}</p>
5053
</div>
5154
</div>
5255

5356
<form onSubmit={onSubmit} className="card space-y-4">
5457
<div>
5558
<label className="label" htmlFor="email">
56-
Email
59+
{t('login.email')}
5760
</label>
5861
<input
5962
id="email"
@@ -67,7 +70,7 @@ export default function LoginPage() {
6770
</div>
6871
<div>
6972
<label className="label" htmlFor="password">
70-
Mot de passe
73+
{t('login.password')}
7174
</label>
7275
<input
7376
id="password"
@@ -82,28 +85,26 @@ export default function LoginPage() {
8285
{needTotp && (
8386
<div>
8487
<label className="label" htmlFor="totp">
85-
Code à deux facteurs
88+
{t('login.totp')}
8689
</label>
8790
<input
8891
id="totp"
8992
inputMode="numeric"
9093
autoComplete="one-time-code"
9194
className="input tracking-widest"
92-
placeholder="123456 ou code de secours"
95+
placeholder={t('login.totpPlaceholder')}
9396
value={totp}
9497
onChange={(e) => setTotp(e.target.value)}
9598
autoFocus
9699
/>
97-
<p className="mt-1.5 text-xs text-zinc-500">
98-
Saisissez le code à 6 chiffres de votre application, ou un code de secours.
99-
</p>
100+
<p className="mt-1.5 text-xs text-zinc-500">{t('login.totpHint')}</p>
100101
</div>
101102
)}
102103
{error && (
103104
<p className="rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-sm text-red-300">{error}</p>
104105
)}
105106
<button type="submit" className="btn-primary w-full" disabled={busy}>
106-
{busy ? 'Connexion…' : needTotp ? 'Vérifier' : 'Se connecter'}
107+
{busy ? t('login.signingIn') : needTotp ? t('login.verify') : t('common.signin')}
107108
</button>
108109
</form>
109110

@@ -113,7 +114,7 @@ export default function LoginPage() {
113114
>
114115
<span className="flex items-center gap-2">
115116
<ShieldCheck size={16} className="text-violet-300" />
116-
Vous avez un code Quick-Upload ?
117+
{t('login.quickPrompt')}
117118
</span>
118119
<ArrowUpRight size={16} className="text-zinc-500" />
119120
</Link>
@@ -122,14 +123,15 @@ export default function LoginPage() {
122123

123124
<footer className="border-t border-white/[0.06] px-4 py-5">
124125
<div className="mx-auto flex max-w-sm flex-col items-center gap-2 text-center text-xs text-zinc-500">
126+
<LanguageSwitcher className="mb-1" />
125127
<nav className="flex flex-wrap justify-center gap-x-4 gap-y-1">
126-
<Link href="/legal" className="hover:text-zinc-300">À propos</Link>
127-
<Link href="/legal/terms" className="hover:text-zinc-300">Conditions</Link>
128-
<Link href="/legal/privacy" className="hover:text-zinc-300">Confidentialité</Link>
129-
<Link href="/legal/license" className="hover:text-zinc-300">Licence</Link>
128+
<Link href="/legal" className="hover:text-zinc-300">{t('legal.about')}</Link>
129+
<Link href="/legal/terms" className="hover:text-zinc-300">{t('legal.terms')}</Link>
130+
<Link href="/legal/privacy" className="hover:text-zinc-300">{t('legal.privacy')}</Link>
131+
<Link href="/legal/license" className="hover:text-zinc-300">{t('legal.license')}</Link>
130132
</nav>
131133
<p>
132-
Open-source (AGPLv3) · par{' '}
134+
{t('login.openSource')}{' '}
133135
<a href="https://forgenet.fr" target="_blank" rel="noreferrer" className="text-violet-300 hover:underline">
134136
Forge Network
135137
</a>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use client';
2+
3+
import { Languages } from 'lucide-react';
4+
import { useT, type Lang } from '@/lib/i18n';
5+
6+
/** Compact FR / EN toggle. */
7+
export function LanguageSwitcher({ className = '' }: { className?: string }) {
8+
const { lang, setLang } = useT();
9+
const next: Lang = lang === 'fr' ? 'en' : 'fr';
10+
return (
11+
<button
12+
type="button"
13+
onClick={() => setLang(next)}
14+
title={lang === 'fr' ? 'Switch to English' : 'Passer en français'}
15+
className={`inline-flex items-center gap-1.5 rounded-lg border border-white/10 px-2 py-1 text-xs font-medium text-zinc-400 transition hover:bg-white/5 hover:text-zinc-100 ${className}`}
16+
>
17+
<Languages size={14} />
18+
{lang.toUpperCase()}
19+
</button>
20+
);
21+
}

‎apps/web/src/lib/i18n.tsx‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
'use client';
2+
3+
/**
4+
* Lightweight i18n for the web client (French + English). A flat key → string dictionary per
5+
* language, a `t(key, vars?)` lookup with `{var}` interpolation, and a persisted language
6+
* choice (localStorage, defaulting to the browser language). Server components that can't use
7+
* the hook keep their own copy; this covers the interactive app surfaces.
8+
*/
9+
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
10+
11+
export type Lang = 'fr' | 'en';
12+
13+
type Dict = Record<string, string>;
14+
15+
const fr: Dict = {
16+
// common
17+
'common.cancel': 'Annuler',
18+
'common.confirm': 'Confirmer',
19+
'common.save': 'Enregistrer',
20+
'common.delete': 'Supprimer',
21+
'common.download': 'Télécharger',
22+
'common.open': 'Ouvrir',
23+
'common.rename': 'Renommer',
24+
'common.move': 'Déplacer',
25+
'common.share': 'Partager',
26+
'common.restore': 'Restaurer',
27+
'common.loading': 'Chargement…',
28+
'common.signin': 'Se connecter',
29+
'common.signout': 'Se déconnecter',
30+
// nav
31+
'nav.spaces': 'Mes Espaces',
32+
'nav.shares': 'Partages',
33+
'nav.remote': 'Remote',
34+
'nav.trash': 'Corbeille',
35+
'nav.admin': 'Administration',
36+
'nav.settings': 'Paramètres',
37+
'nav.storage': 'Stockage',
38+
'role.admin': 'Administrateur',
39+
'role.user': 'Utilisateur',
40+
// login
41+
'login.subtitle': 'Connectez-vous à votre cloud privé',
42+
'login.email': 'Email',
43+
'login.password': 'Mot de passe',
44+
'login.totp': 'Code à deux facteurs',
45+
'login.totpHint': 'Saisissez le code à 6 chiffres de votre application, ou un code de secours.',
46+
'login.totpPlaceholder': '123456 ou code de secours',
47+
'login.signingIn': 'Connexion…',
48+
'login.verify': 'Vérifier',
49+
'login.failed': 'Connexion impossible',
50+
'login.codeIncorrect': 'Code incorrect. Réessayez.',
51+
'login.quickPrompt': 'Vous avez un code Quick-Upload ?',
52+
'login.openSource': 'Open-source (AGPLv3) · par',
53+
'legal.about': 'À propos',
54+
'legal.terms': 'Conditions',
55+
'legal.privacy': 'Confidentialité',
56+
'legal.license': 'Licence',
57+
};
58+
59+
const en: Dict = {
60+
'common.cancel': 'Cancel',
61+
'common.confirm': 'Confirm',
62+
'common.save': 'Save',
63+
'common.delete': 'Delete',
64+
'common.download': 'Download',
65+
'common.open': 'Open',
66+
'common.rename': 'Rename',
67+
'common.move': 'Move',
68+
'common.share': 'Share',
69+
'common.restore': 'Restore',
70+
'common.loading': 'Loading…',
71+
'common.signin': 'Sign in',
72+
'common.signout': 'Sign out',
73+
'nav.spaces': 'My Spaces',
74+
'nav.shares': 'Shares',
75+
'nav.remote': 'Remote',
76+
'nav.trash': 'Trash',
77+
'nav.admin': 'Administration',
78+
'nav.settings': 'Settings',
79+
'nav.storage': 'Storage',
80+
'role.admin': 'Administrator',
81+
'role.user': 'User',
82+
'login.subtitle': 'Sign in to your private cloud',
83+
'login.email': 'Email',
84+
'login.password': 'Password',
85+
'login.totp': 'Two-factor code',
86+
'login.totpHint': 'Enter the 6-digit code from your authenticator app, or a recovery code.',
87+
'login.totpPlaceholder': '123456 or recovery code',
88+
'login.signingIn': 'Signing in…',
89+
'login.verify': 'Verify',
90+
'login.failed': 'Sign-in failed',
91+
'login.codeIncorrect': 'Incorrect code. Try again.',
92+
'login.quickPrompt': 'Have a Quick-Upload code?',
93+
'login.openSource': 'Open-source (AGPLv3) · by',
94+
'legal.about': 'About',
95+
'legal.terms': 'Terms',
96+
'legal.privacy': 'Privacy',
97+
'legal.license': 'License',
98+
};
99+
100+
const dictionaries: Record<Lang, Dict> = { fr, en };
101+
102+
interface I18nCtx {
103+
lang: Lang;
104+
setLang: (l: Lang) => void;
105+
t: (key: string, vars?: Record<string, string | number>) => string;
106+
}
107+
108+
const I18nContext = createContext<I18nCtx | null>(null);
109+
110+
export function I18nProvider({ children }: { children: React.ReactNode }) {
111+
// Default to French on first render (matches the server) to avoid a hydration mismatch,
112+
// then adopt the saved / browser preference on mount.
113+
const [lang, setLangState] = useState<Lang>('fr');
114+
115+
useEffect(() => {
116+
const saved = localStorage.getItem('ocl_lang');
117+
if (saved === 'fr' || saved === 'en') setLangState(saved);
118+
else if (navigator.language?.toLowerCase().startsWith('en')) setLangState('en');
119+
}, []);
120+
121+
const setLang = useCallback((l: Lang) => {
122+
setLangState(l);
123+
try {
124+
localStorage.setItem('ocl_lang', l);
125+
} catch {
126+
/* ignore */
127+
}
128+
document.documentElement.lang = l;
129+
}, []);
130+
131+
const t = useCallback(
132+
(key: string, vars?: Record<string, string | number>) => {
133+
let s = dictionaries[lang][key] ?? dictionaries.fr[key] ?? key;
134+
if (vars) for (const k of Object.keys(vars)) s = s.replaceAll(`{${k}}`, String(vars[k]));
135+
return s;
136+
},
137+
[lang],
138+
);
139+
140+
const value = useMemo(() => ({ lang, setLang, t }), [lang, setLang, t]);
141+
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
142+
}
143+
144+
export function useT(): I18nCtx {
145+
const ctx = useContext(I18nContext);
146+
if (!ctx) throw new Error('useT must be used within I18nProvider');
147+
return ctx;
148+
}

0 commit comments

Comments
 (0)