|
| 1 | +/* |
| 2 | + * SPDX-FileCopyrightText: Team OpenVPI |
| 3 | + * SPDX-License-Identifier: MIT |
| 4 | + */ |
| 5 | + |
| 6 | +/** @type {readonly ['en', 'zh-Hans']} */ |
| 7 | +export const locales = ['en', 'zh-Hans']; |
| 8 | +export const defaultLocale = 'en'; |
| 9 | +export const pages = ['', 'downloads', 'features', 'contribute', 'community']; |
| 10 | +export const localePreferenceKey = 'diffscope-locale'; |
| 11 | + |
| 12 | +/** |
| 13 | + * @param {string} path |
| 14 | + * @param {typeof locales[number]} locale |
| 15 | + */ |
| 16 | +export const localizePath = (path, locale) => |
| 17 | + `${locale === defaultLocale ? '' : `/${locale}`}${path === '/' ? '/' : `/${path.replace(/^\/+|\/+$/g, '')}/`}`; |
| 18 | + |
| 19 | +/** @param {readonly string[]} languages */ |
| 20 | +export function matchBrowserLocale(languages) { |
| 21 | + for (const language of languages) { |
| 22 | + const normalized = language.toLowerCase().replaceAll('_', '-'); |
| 23 | + const exact = locales.find((locale) => locale.toLowerCase() === normalized); |
| 24 | + if (exact) return exact; |
| 25 | + const base = normalized.split('-')[0]; |
| 26 | + const related = locales.find((locale) => locale.toLowerCase().split('-')[0] === base); |
| 27 | + if (related) return related; |
| 28 | + } |
| 29 | + return defaultLocale; |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Only negotiate unprefixed page URLs; explicit locale URLs remain authoritative. |
| 34 | + * @param {string} pathname |
| 35 | + * @param {readonly string[]} languages |
| 36 | + * @param {string | null} preference |
| 37 | + */ |
| 38 | +export function getLanguageRedirect(pathname, languages, preference) { |
| 39 | + const page = pathname.replace(/^\//, '').replace(/\/$/, ''); |
| 40 | + if (!pages.includes(page)) return null; |
| 41 | + const locale = locales.find((locale) => locale === preference) ?? matchBrowserLocale(languages); |
| 42 | + return locale === defaultLocale ? null : localizePath(page || '/', locale); |
| 43 | +} |
0 commit comments