32 lines
1.5 KiB
TypeScript
32 lines
1.5 KiB
TypeScript
// Sprachen der App. Die Sprache gehört der Person (CLAUDE.md, Regel 1):
|
|
// gewählt im Profil (Keks `lunch_locale`), sonst aus dem Browser, sonst Deutsch.
|
|
export const LOCALES = ["de", "en", "fr", "es"] as const;
|
|
export type Locale = (typeof LOCALES)[number];
|
|
export const DEFAULT_LOCALE: Locale = "de";
|
|
export const LOCALE_COOKIE = "lunch_locale";
|
|
|
|
export function isLocale(value: unknown): value is Locale {
|
|
return typeof value === "string" && (LOCALES as readonly string[]).includes(value);
|
|
}
|
|
|
|
/** Wählt aus einem Accept-Language-Kopf die beste unterstützte Sprache. */
|
|
export function negotiateLocale(acceptLanguage: string | null | undefined): Locale {
|
|
if (!acceptLanguage) return DEFAULT_LOCALE;
|
|
const candidates = acceptLanguage
|
|
.split(",")
|
|
.map((part, index) => {
|
|
const [tag = "", ...params] = part.trim().split(";");
|
|
const q = params.map((p) => p.trim()).find((p) => p.startsWith("q="));
|
|
const weight = q ? Number(q.slice(2)) : 1;
|
|
return { lang: tag.toLowerCase().split("-")[0] ?? "", weight: Number.isFinite(weight) ? weight : 0, index };
|
|
})
|
|
.filter((c) => c.lang && c.weight > 0)
|
|
.sort((a, b) => b.weight - a.weight || a.index - b.index);
|
|
for (const c of candidates) if (isLocale(c.lang)) return c.lang;
|
|
return DEFAULT_LOCALE;
|
|
}
|
|
|
|
export function resolveLocale(cookieValue: string | undefined, acceptLanguage: string | null): Locale {
|
|
return isLocale(cookieValue) ? cookieValue : negotiateLocale(acceptLanguage);
|
|
}
|