-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
69 lines (57 loc) · 1.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { getUrlParams, getForPath } from "../utils";
import { LEETCODE_CN_URL, LEETCODE_URL } from "../constant";
import zh from "./zh";
import en from "./en";
const DEV_URL_LANG =
process.env.NODE_ENV === "development"
? getUrlParams(window.location.href)?.lang
: undefined;
// 支持在 url 中传入 lang 参数,否则本地开发刷新页面后会恢复为默认语言
const DEFAULT_LANG = DEV_URL_LANG || "zh";
let isInit = false;
export let lang = DEFAULT_LANG;
const ALL_LANGS = {
zh,
en,
};
// export const ALL_LANG_OPTIONS = {
// zh: "简体中文",
// en: "English",
// };
export const setLang = (_lang) => {
lang = _lang || DEFAULT_LANG;
};
export const initLang = async (currentUrl) => {
if (isInit) return;
const isEnHref = currentUrl.includes(LEETCODE_URL);
setLang(isEnHref ? "en":"zh");
isInit = true;
};
export const getLeetcodeUrlForLang = () => {
return lang === "zh" ? LEETCODE_CN_URL : LEETCODE_URL;
};
/**
* @param {string} keypath
* @param {string | string[]} slotText
* @param {string} l lang
* @returns {string}
*/
export const t = (keypath, slotText, l) => {
const langData = { Locale: ALL_LANGS[l || lang] };
if (!keypath) return "";
if (!keypath.includes("Locale")) {
keypath = "Locale." + keypath;
}
let content = getForPath(langData, keypath);
if (slotText) {
if (Array.isArray(slotText)) {
slotText.forEach((item, idx) => {
content = content.replace(`{${idx}}`, item);
});
} else {
content = content.replace("{slotText}", slotText);
}
}
return content;
};
export default ALL_LANGS[lang];