mirror of
https://github.com/zoriya/Kyoo.git
synced 2025-07-09 03:04:20 -04:00
Custom translation backend
This commit is contained in:
parent
96a38e0c65
commit
14cf634815
@ -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);
|
||||
|
@ -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>;
|
||||
|
Loading…
x
Reference in New Issue
Block a user