i18n waterMe
This commit is contained in:
64
core/src/lib/i18n/i18n.service.ts
Normal file
64
core/src/lib/i18n/i18n.service.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
3
core/src/lib/i18n/index.ts
Normal file
3
core/src/lib/i18n/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { I18nService } from "lib/i18n/i18n.service";
|
||||
|
||||
export const i18nService = new I18nService();
|
||||
Reference in New Issue
Block a user