peppa/apps/web/components/I18n.tsx
Асель b9232c9e64 PEP-136: language switcher in the menu on every page
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 09:20:54 +05:00

75 lines
2.6 KiB
TypeScript

"use client";
// Interface language in client components (PEP-98): the root layout passes the locale,
// `useT()` gives a translator over the bundled dictionaries.
import { createContext, useContext, useMemo, useTransition, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import { LOCALE_LABELS, LOCALES, translator, type Locale, type Translator } from "@peppa/shared/i18n";
import { setLanguage } from "@/app/locale-actions";
import { cn } from "@/lib/utils";
const LocaleContext = createContext<Locale>("ru");
export function I18nProvider({ locale, children }: { locale: Locale; children: ReactNode }) {
return <LocaleContext.Provider value={locale}>{children}</LocaleContext.Provider>;
}
export function useLocale(): Locale {
return useContext(LocaleContext);
}
export function useT(): Translator {
const locale = useLocale();
return useMemo(() => translator(locale), [locale]);
}
/**
* RU / EN / KZ: saves the cookie (and the user's choice when logged in), then re-renders.
* `compact` (PEP-136) is a native list for the phone top bar, where three buttons do not fit.
*/
export function LanguageSwitcher({ className, compact = false }: { className?: string; compact?: boolean }) {
const current = useLocale();
const t = useT();
const router = useRouter();
const [pending, start] = useTransition();
const choose = (l: string) =>
start(async () => {
await setLanguage(l);
router.refresh();
});
if (compact) {
return (
<select
aria-label={t("Язык интерфейса")}
title={t("Язык интерфейса")}
value={current}
disabled={pending}
onChange={(e) => choose(e.target.value)}
className={cn("h-8 rounded-md border bg-background/60 px-1 font-mono text-xs text-muted-foreground hover:text-foreground", className)}
>
{LOCALES.map((l) => (
<option key={l} value={l}>
{LOCALE_LABELS[l]}
</option>
))}
</select>
);
}
return (
<div role="group" aria-label={t("Язык интерфейса")} className={cn("inline-flex rounded-md border p-0.5", className)}>
{LOCALES.map((l) => (
<button
key={l}
type="button"
disabled={pending}
aria-pressed={l === current}
onClick={() => choose(l)}
className={cn("rounded px-2 py-0.5 font-mono text-xs transition-colors", l === current ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground")}
>
{LOCALE_LABELS[l]}
</button>
))}
</div>
);
}