velxio/frontend/src/components/layout/LanguageSwitcher.tsx

107 lines
3.2 KiB
TypeScript
Raw Normal View History

feat(i18n): react-i18next foundation + 9-locale support for header / footer This is Phase 1 of multi-language support: the visible chrome (header, footer, language switcher) and routing are wired up for all 9 locales (en, es, pt-br, it, fr, zh-cn, de, ja, ru) — same set the blog at velxio.dev/blog/ already supports. The Editor and the long-form landing-page copy are still English-only and will be translated in a follow-up. Infrastructure - frontend/src/i18n/config.ts: locale registry + LOCALE_META (htmlLang, native name, og locale, dir). Mirrors pro/blog/src/i18n/config.ts so cookie sync stays consistent. - frontend/src/i18n/cookie.ts: read/write the velxio_locale cookie at Path=/; Max-Age=1y; SameSite=Lax (Secure on HTTPS). The blog reads the same cookie via an inline script in its Layout.astro. - frontend/src/i18n/path.ts: getLocaleFromPath / stripLocaleFromPath / localizedPath / switchLocale / blogUrlFor — match the blog's helpers one-to-one. - frontend/src/i18n/index.ts: i18next bootstrap. English bundle is inlined synchronously for first paint; non-default locales are lazy-loaded via dynamic import on demand. Initial locale is decided in priority order URL > cookie > navigator > en. - frontend/src/i18n/LocaleSync.tsx: top-level wrapper inside <Router>. On every URL change loads the matching locale bundle, calls i18n.changeLanguage, writes the cookie, and mirrors the locale onto <html lang> and dir. - frontend/src/i18n/useLocalizedNavigate.ts: useCurrentLocale, useLocalizedHref, useLocalizedNavigate hooks for components that build internal links. Routing - App.tsx: route table extracted to a single ROUTES array, then registered twice — once at the root (default English) and once nested under each non-default locale (`/<locale>/...`). Explicit per-locale parent routes (rather than a generic `:lang` param) so React Router never accidentally swallows a real top-level path like `/circuit-simulator` as a locale segment. Header / Footer - LanguageSwitcher.tsx + .css: dropdown matching the blog's LanguageSwitcher.astro. Globe icon + locale code on the trigger, native names + ISO codes in the menu. Click → `switchLocale()` rewrites the URL under the new locale; LocaleSync handles the rest (load bundle, change language, write cookie). - AppHeader.tsx: every nav label and the auth dropdown copy now goes through `t('header.nav.*')`, `t('header.auth.*')`. All internal Links wrapped with localize() so navigation stays inside the active locale. Added a "Blog" link computed via `blogUrlFor(currentLocale)` so /es/ → /blog/es/, etc. - LandingPage.tsx: footer About-Velxio paragraph reads from t('footer.about'). Translations (Phase 1 strings) - frontend/src/i18n/locales/<locale>/common.json: nav labels, auth buttons, footer About copy. Hand-translated for all 9 locales, AGPLv3 / brand names preserved as-is. Tooling - frontend/scripts/translate-i18n.mjs: standalone Node script that takes the en.json bundles and auto-translates them to the 8 other locales via DeepSeek (primary) + Gemini (fallback). One LLM call per (locale, namespace) pair. Run after extracting new strings with `npm run translate:i18n`. Phase 2 (deferred) - Editor (toolbar, file explorer, simulator canvas, component picker, library manager, error toasts) — hundreds of strings. - Examples / Docs / About / Profile pages. - The translate-i18n.mjs script is ready to handle these once the strings have been extracted into JSON keys.
2026-05-09 10:40:37 +07:00
/**
* Language switcher dropdown — mirrors the blog's
* `pro/blog/src/components/LanguageSwitcher.astro`. Clicking a locale
* rewrites the current URL under the chosen locale's prefix; the
* `LocaleSync` wrapper at the top of the router picks up the change,
* lazy-loads the resource bundle, and persists the choice to the
* `velxio_locale` cookie shared with the blog.
*/
import { useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Globe } from 'lucide-react';
import {
LOCALES,
LOCALE_META,
type Locale,
} from '../../i18n/config';
import {
getLocaleFromPath,
switchLocale,
} from '../../i18n/path';
export const LanguageSwitcher: React.FC = () => {
const location = useLocation();
const navigate = useNavigate();
const rootRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
const current: Locale = getLocaleFromPath(location.pathname);
useEffect(() => {
const handler = (e: MouseEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node)) {
setOpen(false);
}
};
const keyHandler = (e: KeyboardEvent) => {
if (e.key === 'Escape') setOpen(false);
};
document.addEventListener('mousedown', handler);
document.addEventListener('keydown', keyHandler);
return () => {
document.removeEventListener('mousedown', handler);
document.removeEventListener('keydown', keyHandler);
};
}, []);
const choose = (target: Locale) => {
setOpen(false);
if (target === current) return;
const nextPath = switchLocale(location.pathname, target);
navigate(nextPath + location.search + location.hash);
};
return (
<div ref={rootRef} className="velxio-language-switcher">
<button
type="button"
className="velxio-language-btn"
aria-haspopup="listbox"
aria-expanded={open}
aria-label="Language"
title="Language"
onClick={() => setOpen((v) => !v)}
>
<Globe size={16} strokeWidth={1.8} aria-hidden="true" />
<span className="velxio-language-current">{current.toUpperCase()}</span>
</button>
{open && (
<ul
className="velxio-language-menu"
role="listbox"
aria-label="Language"
>
{LOCALES.map((loc) => {
const meta = LOCALE_META[loc];
const active = loc === current;
return (
<li
key={loc}
role="option"
aria-selected={active}
>
<button
type="button"
className={
'velxio-language-item' +
(active ? ' velxio-language-item-active' : '')
}
onClick={() => choose(loc)}
lang={meta.htmlLang}
>
<span className="velxio-language-native">
{meta.nativeName}
</span>
<span className="velxio-language-code">
{loc.toUpperCase()}
</span>
</button>
</li>
);
})}
</ul>
)}
</div>
);
};