diff --git a/webapp/src/lang/index.ts b/webapp/src/lang/index.ts new file mode 100644 index 0000000..e05ec9e --- /dev/null +++ b/webapp/src/lang/index.ts @@ -0,0 +1,47 @@ +import { useEffect, useState } from "react"; + +const MISSING_TEXT = "<>"; +const LOADING_TEXT = "..."; + +export type LangStore = ReturnType; +export const useLang = () => { + const [langStore, setLangStore] = + useState | null>(null); + const [langEngStore, setLangEngStore] = + useState | null>(null); + + useEffect(() => { + import("./eng.json").then((data) => { + // setLangStore(data.default); + setLangEngStore(data.default); + }); + import("./eng.json").then((data) => { + setLangStore(data.default); + }); + }, []); + + const updateParams = ( + textTemplate: string, + replacements: Record = {} + ) => { + let text = textTemplate; + Object.keys(replacements).forEach((k) => { + const v = replacements[k]; + text = text.replace(`{{${k}}}`, v); + }); + return text; + }; + + return { + get: (langId: string, replacements: Record = {}) => + updateParams( + langStore === null || langEngStore === null + ? LOADING_TEXT + : langStore[langId.toLocaleUpperCase()] ?? + langEngStore[langId.toLocaleUpperCase()] ?? + `<<${langStore.MISSING_TEXT}>>` ?? + MISSING_TEXT, + { ...replacements, langId } + ), + }; +};