SPB Git

Repository Public

core.ts 2.3 KB 54 lines typescript

1import type { Locale } from "@/lib/format";2import type { Dict, Shape, TKey, TPluralKey, Vars } from "./types";3import { fr } from "./fr";4import { en } from "./en";56export const dictionaries: Record<Locale, Shape<Dict>> = { fr, en };7export const LOCALES: readonly Locale[] = ["fr", "en"];8export const DEFAULT_LOCALE: Locale = "fr";910function lookup(dict: unknown, key: string): unknown {11  let node: unknown = dict;12  for (const part of key.split(".")) {13    if (typeof node !== "object" || node === null) return undefined;14    node = (node as Record<string, unknown>)[part];15  }16  return node;17}1819function interpolate(template: string, vars?: Vars): string {20  if (!vars) return template;21  return template.replace(/\{(\w+)\}/g, (m, name: string) => (name in vars ? String(vars[name]) : m));22}2324export function translate(locale: Locale, key: TKey, vars?: Vars): string {25  const v = lookup(dictionaries[locale], key);26  // Typed keys + the parity test guarantee presence; the key itself is returned only if a caller defeats the types.27  return typeof v === "string" ? interpolate(v, vars) : key;28}2930const pluralRules = new Map<Locale, Intl.PluralRules>();31export function translatePlural(locale: Locale, key: TPluralKey, count: number, vars?: Vars): string {32  let rules = pluralRules.get(locale);33  if (!rules) pluralRules.set(locale, (rules = new Intl.PluralRules(locale)));34  const v = lookup(dictionaries[locale], key) as { one?: string; other?: string } | undefined;35  const form = rules.select(count) === "one" ? v?.one : v?.other;36  return typeof form === "string" ? interpolate(form, { count, ...vars }) : key;37}3839/** Flattened key list of a dictionary (used by the parity test). */40export function flatKeys(dict: unknown, prefix = ""): string[] {41  if (typeof dict !== "object" || dict === null) return [prefix];42  return Object.entries(dict as Record<string, unknown>).flatMap(([k, v]) => flatKeys(v, prefix ? `${prefix}.${k}` : k));43}4445/** Locale from a cookie value and an Accept-Language header (before sign-in). */46export function pickLocale(cookie: string | undefined, acceptLanguage: string | null | undefined): Locale {47  if (cookie === "fr" || cookie === "en") return cookie;48  for (const part of (acceptLanguage ?? "").split(",")) {49    const lang = part.trim().slice(0, 2).toLowerCase();50    if (lang === "fr" || lang === "en") return lang;51  }52  return DEFAULT_LOCALE;53}54
Files main
Menu

Theme