Files
fristydev/lib/i18n/locales.ts
T
fristy ad943fff8c
Build & Push / Lint & Build (push) Successful in 1m15s
Build & Push / Build & Push Image (push) Successful in 52s
Initial commit: fristy.net personal site
2026-09-10 04:59:12 +03:00

49 lines
1.3 KiB
TypeScript

export const LOCALES = ["tr", "en", "de"] as const;
export type Locale = (typeof LOCALES)[number];
export const DEFAULT_LOCALE: Locale = "tr";
export const LOCALE_COOKIE = "locale";
export const LOCALE_LABELS: Record<Locale, string> = {
tr: "TR",
en: "EN",
de: "DE",
};
export function isLocale(value: string): value is Locale {
return (LOCALES as readonly string[]).includes(value);
}
export function matchLocale(acceptLanguage: string | null): Locale {
if (!acceptLanguage) {
return DEFAULT_LOCALE;
}
const preferences = acceptLanguage
.split(",")
.map((part) => {
const [range, ...params] = part.trim().split(";");
let q = 1;
for (const param of params) {
const match = param.trim().match(/^q=([0-9.]+)$/);
if (match) {
q = Number(match[1]);
}
}
return { range: range.toLowerCase(), q };
})
.sort((a, b) => b.q - a.q);
for (const { range } of preferences) {
if (range === "*") {
return DEFAULT_LOCALE;
}
const base = range.split("-")[0];
if (isLocale(base)) {
return base;
}
}
return DEFAULT_LOCALE;
}