peppa/apps/web/components/I18n.tsx
peppa-bot d8a37833f3
All checks were successful
peppa/build build: success за 16с
peppa/bundle bundle: success за 0с
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 21с
PEP-217: Web Vitals пользователей, проверка веса JS в CI, словари не в браузерном бандле
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 17:03:07 +05:00

57 lines
2.2 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, registerDictionary, translator, type Dict, type Locale, type Translator } from "@peppa/shared/i18n";
import { setLanguage } from "@/app/locale-actions";
import { cn } from "@/lib/utils";
const LocaleContext = createContext<Locale>("ru");
/** `dict` — the dictionary of `locale` (not for Russian): the browser bundle carries none (PEP-217). */
export function I18nProvider({ locale, dict, children }: { locale: Locale; dict?: Dict; children: ReactNode }) {
// Before the children render, on the server and on hydration alike; idempotent.
if (dict) registerDictionary(locale, dict);
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. */
export function LanguageSwitcher({ className }: { className?: string }) {
const current = useLocale();
const t = useT();
const router = useRouter();
const [pending, start] = useTransition();
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={() =>
start(async () => {
await setLanguage(l);
router.refresh();
})
}
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>
);
}