peppa/apps/web/components/I18n.tsx
2026-11-15 14:25:03 +05:00

54 lines
1.9 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. */
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>
);
}