nomadro/src/modules/social/lib/useSocialI18n.ts
2026-11-04 16:59:32 +08:00

63 lines
1.8 KiB
TypeScript

"use client";
import { useCallback, useMemo } from "react";
import { useLocale } from "~/components/locale-provider";
import type { Locale } from "~/lib/i18n";
import {
getSocialDictionary,
toSocialLocale,
type SocialDictionary,
type SocialLocale,
} from "./i18n";
import { socialTx, setSocialTxLocale } from "./socialTx";
const UNLOCK_KEY = "nomadro-lang-unlock";
export type TranslateFn = (zh: string, en?: string) => string;
export function useSocialI18n(): {
locale: SocialLocale;
portalLocale: Locale;
ready: boolean;
dict: SocialDictionary;
/** Dictionary fields + callable translator (legacy). Prefer dict / socialTx. */
t: SocialDictionary & TranslateFn;
tx: TranslateFn;
setLocale: (locale: SocialLocale) => void;
} {
const { locale: portalLocale, setLocale: setPortalLocale, ready } = useLocale();
// Match the portal's server fallback until audience detection is ready.
// Browser language/font signals can differ from the server on first render.
const locale: SocialLocale = ready ? toSocialLocale(portalLocale) : "zh";
const dict = useMemo(() => getSocialDictionary(locale), [locale]);
// Keep module-level translator in sync for nested non-hook call sites.
setSocialTxLocale(locale);
const tx = useCallback<TranslateFn>(
(zh, en) => socialTx(zh, en),
[locale],
);
const setLocale = useCallback(
(next: SocialLocale) => {
try {
window.sessionStorage.setItem(UNLOCK_KEY, "1");
} catch {
// ignore
}
setSocialTxLocale(next);
setPortalLocale(next);
},
[setPortalLocale],
);
const t = useMemo(() => {
const fn = ((zh: string, en?: string) => socialTx(zh, en)) as SocialDictionary &
TranslateFn;
return Object.assign(fn, dict);
}, [dict, locale]);
return { locale, portalLocale, ready, dict, t, tx, setLocale };
}