Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/storybook/.storybook/i18n.ts
T

68 lines
2.7 KiB
TypeScript

/**
* Minimal in-Storybook i18next instance (#62 Task F).
*
* Bootstraps a real (synchronous) i18next + react-i18next instance so the
* locale toolbar global has actual effect on stories that call
* `useTranslation`. Resources are inlined at build time via Vite's
* `import.meta.glob` against the apps/web public-locales tree, so we don't
* need an i18next-http-backend (Storybook has no Express loader to serve
* them from).
*
* Only a handful of namespaces are seeded — the ones today's 21 stories
* could plausibly reference (`common`, `translations`, `auth`, `errors`).
* Adding more is a one-line resource-map change.
*/
import i18next, { type i18n as I18n } from "i18next";
import { initReactI18next } from "react-i18next";
import { defaultLocale, i18nConfig, supportedLocales, type SupportedLocale } from "@toolctrl/i18n";
type LocaleResources = Record<string, Record<string, unknown>>;
type ResourceTree = Partial<Record<SupportedLocale | "ar", LocaleResources>>;
// Eager glob — Vite inlines every matched JSON at build time, which is fine
// for a 9-file, <100kB locale tree. The pattern resolves relative to this
// file: ../../../apps/web/public/locales/<locale>/<ns>.json.
const localeModules = import.meta.glob("../../../apps/web/public/locales/*/*.json", {
eager: true,
}) as Record<string, { default: Record<string, unknown> }>;
function buildResources(): ResourceTree {
const out: ResourceTree = {};
for (const [path, mod] of Object.entries(localeModules)) {
// path looks like ".../apps/web/public/locales/en/common.json"
const match = /\/locales\/([^/]+)\/([^/]+)\.json$/.exec(path);
if (!match) continue;
const [, locale, namespace] = match;
const bucket = (out[locale as SupportedLocale] ??= {});
bucket[namespace] = mod.default;
}
return out;
}
let cached: I18n | undefined;
export function getStorybookI18n(): I18n {
if (cached) return cached;
const resources = buildResources();
const instance = i18next.createInstance();
instance.use(initReactI18next).init({
...i18nConfig,
lng: defaultLocale,
resources: resources as Record<string, Record<string, Record<string, unknown>>>,
// Storybook stories run client-only — no SSR hydration concerns, so we
// can synchronously init. `react.useSuspense: false` already set in the
// shared config blocks suspending decorators.
initImmediate: false,
});
cached = instance;
return instance;
}
export function setStorybookLocale(locale: string): void {
const instance = getStorybookI18n();
const target = supportedLocales.includes(locale as SupportedLocale) ? locale : defaultLocale;
if (instance.language !== target) {
void instance.changeLanguage(target);
}
}