Custom translation backend

This commit is contained in:
Zoe Roux 2025-02-24 23:57:03 +01:00
parent 96a38e0c65
commit 14cf634815
No known key found for this signature in database
2 changed files with 28 additions and 12 deletions

View File

@ -3,7 +3,7 @@ import { Platform } from "react-native";
import { MMKV, useMMKVString } from "react-native-mmkv";
import type { ZodTypeAny, z } from "zod";
const storage = new MMKV();
export const storage = new MMKV();
function toBase64(utf8: string) {
if (typeof window !== "undefined") return window.btoa(utf8);

View File

@ -1,17 +1,39 @@
import i18next from "i18next";
import AsyncStorageBackend, {
type AsyncStorageBackendOptions,
} from "i18next-async-storage-backend";
import ChainedBackend, { type ChainedBackendOptions } from "i18next-chained-backend";
import HttpApi, { type HttpBackendOptions } from "i18next-http-backend";
import { getServerData } from "one";
import type { RefObject } from "react";
import { type ReactNode, useMemo } from "react";
import { I18nextProvider } from "react-i18next";
import { storage } from "./settings";
class Backend {
private url: RefObject<string | null>;
static type = "backend" as const;
constructor(_services: any, opts: { url: RefObject<string | null> }) {
this.url = opts.url;
}
init(_services: any, opts: { url: RefObject<string | null> }) {
this.url = opts.url;
}
async read(language: string, namespace: string) {
const key = `translation.${namespace}.${language}`;
const cached = storage.getString(key);
if (cached) return JSON.parse(cached);
const ghUrl = "https://raw.githubusercontent.com/zoriya/Kyoo/refs/heads/master/front/public";
const data = await fetch(`${this.url.current ?? ghUrl}/translations/${language}.json`);
storage.set(key, JSON.stringify(await data.json()));
return data;
}
}
export const TranslationsProvider = ({ children }: { children: ReactNode }) => {
const val = useMemo(() => {
const i18n = i18next.createInstance();
i18n.use(ChainedBackend).init<ChainedBackendOptions>({
i18n.use(Backend).init({
interpolation: {
escapeValue: false,
},
@ -20,15 +42,9 @@ export const TranslationsProvider = ({ children }: { children: ReactNode }) => {
load: "currentOnly",
supportedLngs: getServerData("supportedLngs"),
backend: {
backends: [AsyncStorageBackend, HttpApi],
backendOptions: [
{
loadPath: "/translations/{{lng}}.json",
} satisfies HttpBackendOptions,
],
url,
},
});
i18n.services.resourceStore.data = getServerData("translations");
return i18n;
}, []);
return <I18nextProvider i18n={val}>{children}</I18nextProvider>;