i18n waterMe

This commit is contained in:
mo
2026-02-21 00:20:12 +01:00
parent d2e88f15ea
commit 453577f1b2
13 changed files with 144 additions and 78 deletions

View File

@@ -0,0 +1,64 @@
import i18next, { type ParseKeys } from "i18next";
// import { createLogger } from "lib/logger";
import waterMeDe from "locales/de/water-me";
import waterMeEn from "locales/en/water-me";
export class I18nService {
// private logger = createLogger("I18nService");
private initialized: Promise<void>;
constructor() {
this.initialized = this.init();
// this.logger.debug(`language ${lang}`);
}
randomVariantPlugin = {
type: "postProcessor" as const,
name: "randomVariant",
process(value: string) {
return value;
},
};
async init() {
await i18next.init({
lng: "en",
fallbackLng: "en",
resources: {
en: { waterMe: waterMeEn },
de: { waterMe: waterMeDe },
},
});
}
randomItem<T>(arr: T[]): T {
return arr[Math.floor(Math.random() * arr.length)];
}
async t(
key: ParseKeys,
locale: string,
ns: string,
interpolations?: Record<string, string | number>,
): Promise<string> {
await this.initialized; // wait for init before translating
const fixedT = i18next.getFixedT(
locale.startsWith("de") ? "de" : "en",
ns ?? "waterMe",
);
const value = fixedT(key, { returnObjects: true, ...interpolations });
if (Array.isArray(value)) {
// pick random variant and interpolate manually if needed
const picked = this.randomItem(value as string[]);
// i18next won't interpolate when returnObjects is true, so we do it here
return picked.replace(/\{\{(\w+)\}\}/g, (_, k) =>
interpolations?.[k] !== undefined
? String(interpolations[k])
: `{{${k}}}`,
);
}
return value as unknown as string;
}
}

View File

@@ -0,0 +1,3 @@
import { I18nService } from "lib/i18n/i18n.service";
export const i18nService = new I18nService();