Skip to content

Commit

Permalink
Merge pull request tangly1024#2926 from dongzhenye/fix/url-based-lang…
Browse files Browse the repository at this point in the history
…-switch-upstream

fix: language switching now strictly follows URL path
  • Loading branch information
tangly1024 authored Nov 8, 2024
2 parents adeb4b2 + 4d7b0f5 commit ceaa9f9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 26 deletions.
6 changes: 5 additions & 1 deletion lib/global.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,13 @@ export function GlobalContextProvider(props) {
}
}

// 添加路由变化时的语言处理
useEffect(() => {
initLocale(router.locale, changeLang, updateLocale)
}, [router])

useEffect(() => {
initDarkMode(updateDarkMode, defaultDarkMode)
initLocale(lang, locale, updateLang, updateLocale)
if (
NOTION_CONFIG?.REDIRECT_LANG &&
JSON.parse(NOTION_CONFIG?.REDIRECT_LANG)
Expand Down
43 changes: 18 additions & 25 deletions lib/lang.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,39 +65,32 @@ export function generateLocaleDict(langString) {
}

/**
* 初始化站点翻译
* 根据用户当前浏览器语言进行切换
* 站点翻译
* 借助router中的locale机制,根据locale自动切换对应的语言
*/
export function initLocale(lang, locale, changeLang, changeLocale) {
export function initLocale(locale, changeLang, updateLocale) {
if (isBrowser) {
// 用户请求的语言
let queryLang =
getQueryVariable('locale') ||
getQueryVariable('lang') ||
loadLangFromLocalStorage()
// 根据router中的locale对象判断当前语言:表现为前缀中包含 zh、en 等。
let pathLocaleLang = null
if (locale === 'en' || locale === 'zh') {
pathLocaleLang = locale === 'en' ? 'en-US' : 'zh-CN'
}
// 如果有query参数切换语言则优先
const queryLang =
getQueryVariable('locale') || getQueryVariable('lang') || pathLocaleLang

if (queryLang) {
// 用正则表达式匹配有效的语言标识符例如zh-CN(可选的 -CN 部分)
queryLang = queryLang.match(/[a-zA-Z]{2}(?:-[a-zA-Z]{2})?/)
if (queryLang) {
queryLang = queryLang[0]
const match = queryLang.match(/[a-zA-Z]{2}(?:-[a-zA-Z]{2})?/)
if (match) {
const targetLang = match[0]
changeLang(targetLang)
const targetLocale = generateLocaleDict(targetLang)
updateLocale(targetLocale)
}
}

let currentLang = lang
if (queryLang && queryLang !== lang) {
currentLang = queryLang
}

changeLang(currentLang)
saveLangToLocalStorage(currentLang)

const targetLocale = generateLocaleDict(currentLang)
if (JSON.stringify(locale) !== JSON.stringify(currentLang)) {
changeLocale(targetLocale)
}
}
}

/**
* 读取语言
* @returns {*}
Expand Down

0 comments on commit ceaa9f9

Please sign in to comment.