forked from tangly1024/NotionNext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lang.js
96 lines (85 loc) · 2.49 KB
/
lang.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import zhCN from './lang/zh-CN'
import enUS from './lang/en-US'
import zhHK from './lang/zh-HK'
import zhTW from './lang/zh-TW'
import frFR from './lang/fr-FR'
import trTR from './lang/tr-TR'
import jaJP from './lang/ja-JP'
import cookie from 'react-cookies'
import { getQueryVariable, isBrowser, mergeDeep } from './utils'
/**
* 在这里配置所有支持的语言
* 国家-地区
*/
const lang = {
'en-US': enUS,
'zh-CN': zhCN,
'zh-HK': zhHK,
'zh-TW': zhTW,
'fr-FR': frFR,
'tr-TR': trTR,
'ja-JP': jaJP
}
export default lang
/**
* 获取当前语言字典
* 如果匹配到完整的“国家-地区”语言,则显示国家的语言
* @returns 不同语言对应字典
*/
export function generateLocaleDict(langString) {
const supportedLocales = Object.keys(lang)
let userLocale
// 将语言字符串拆分为语言和地区代码,例如将 "zh-CN" 拆分为 "zh" 和 "CN"
const [language, region] = langString.split(/[-_]/)
// 优先匹配语言和地区都匹配的情况
const specificLocale = `${language}-${region}`
if (supportedLocales.includes(specificLocale)) {
userLocale = lang[specificLocale]
}
// 然后尝试匹配只有语言匹配的情况
if (!userLocale) {
const languageOnlyLocales = supportedLocales.filter(locale => locale.startsWith(language))
if (languageOnlyLocales.length > 0) {
userLocale = lang[languageOnlyLocales[0]]
}
}
// 如果还没匹配到,则返回最接近的语言包
if (!userLocale) {
const fallbackLocale = supportedLocales.find(locale => locale.startsWith('en'))
userLocale = lang[fallbackLocale]
}
return mergeDeep({}, lang['en-US'], userLocale)
}
/**
* 初始化站点翻译
* 根据用户当前浏览器语言进行切换
*/
export function initLocale(lang, locale, changeLang, changeLocale) {
if (isBrowser()) {
const queryLang = getQueryVariable('lang') || loadLangFromCookies() || window.navigator.language
let currentLang = lang
if (queryLang !== lang) {
currentLang = queryLang
}
changeLang(currentLang)
saveLangToCookies(currentLang)
const targetLocale = generateLocaleDict(currentLang)
if (JSON.stringify(locale) !== JSON.stringify(currentLang)) {
changeLocale(targetLocale)
}
}
}
/**
* 读取语言
* @returns {*}
*/
export const loadLangFromCookies = () => {
return cookie.load('lang')
}
/**
* 保存语言
* @param newTheme
*/
export const saveLangToCookies = (lang) => {
cookie.save('lang', lang, { path: '/' })
}