const noLocaleTranslate = (str) => { let res = [], tres = ""; let matchStr = "", enableMatch = false; for (const char of str) { if (char === "$" && !enableMatch) { enableMatch = true; res.push(tres); tres = ""; } else if (enableMatch && char === "{") { continue; } else if (enableMatch && char === "}") { res.push(matchStr); enableMatch = false; matchStr = ""; } else if (enableMatch) matchStr += char; else tres += char; } res.push(tres); return res.join(""); }; const translate = (str) => { const locale = window.localStorage.getItem("locale"); const langPkg = JSON.parse(window.localStorage.getItem("langPkg")); if (!locale || !langPkg) return noLocaleTranslate(str); let res = [], resMp = [], flag = false, tres = ""; let matchStr = "", enableMatch = false; for (const char of str) { if (char === "$" && !enableMatch) { enableMatch = true; if (tres !== "") { res.push(tres); tres = ""; resMp.push(false); } } else if (enableMatch && char === "{") { continue; } else if (enableMatch && char === "}") { const tStr = langPkg[locale] === undefined ? undefined : langPkg[locale][matchStr]; if (tStr === undefined) { flag = true; } res.push(matchStr); resMp.push(true); enableMatch = false; matchStr = ""; } else if (enableMatch) matchStr += char; else tres += char; } if (tres !== "") { res.push(tres); resMp.push(false); } if (flag) return res.join(""); let resStr = ""; for (let i = 0; i < res.length; i++) { if (resMp[i]) resStr += (i !== 0 ? " " : "") + langPkg[locale][res[i]]; else resStr += res[i]; } return resStr; }; export default translate;