Skip to content
This repository was archived by the owner on Dec 27, 2024. It is now read-only.

Commit e984918

Browse files
committed
feat: auto detect preferred locale
1 parent f4a2dda commit e984918

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

docs/.vitepress/config.mts

+37
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,43 @@ export default defineConfig({
112112
},
113113
];
114114
}),
115+
[
116+
'script',
117+
{},
118+
`
119+
const initialVisit = localStorage.getItem('initialVisit') !== 'false'
120+
121+
if (initialVisit) {
122+
const langs = [${localeOptions.map((l) => `"${camelToKebabCase(l.value)}"`)}]
123+
124+
function mapLang(lang) {
125+
switch (lang) {
126+
case 'zh':
127+
case 'zh-CN':
128+
case 'zh-TW':
129+
return 'cmn-hans';
130+
default:
131+
return lang.toLowerCase();
132+
}
133+
}
134+
135+
let match;
136+
navigator.languages.forEach((lang) => {
137+
const mapped = mapLang(lang);
138+
if (!match) match = langs.find((l) => l === mapped);
139+
if (!match) match = langs.find((l) => l === mapped.split('-')[0]);
140+
})
141+
142+
if (match) {
143+
localStorage.setItem('initialVisit', false);
144+
const parts = window.location.pathname.split('/');
145+
const isEnglish = parts.length === 3;
146+
const page = isEnglish ? parts[2] : parts[3]
147+
window.location.pathname = "${base}" + (match !== 'en' ? match + '/' : '') + page
148+
}
149+
}
150+
`,
151+
],
115152
);
116153
},
117154
locales: mapLocales(),

0 commit comments

Comments
 (0)