All files / app-leaderboard/src/pages/i18n locale.ts

100% Statements 23/23
94.73% Branches 18/19
100% Functions 9/9
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49    14x   14x     14x     14x     591x                         287x 277x 267x 25x 25x   244x         267x     279x 279x 279x   279x 11x 35x    
/** The languages the Leaderboard pages come in, and how a request picks one. */
 
export const LOCALES = ['en', 'ja'] as const;
export type Locale = (typeof LOCALES)[number];
export const DEFAULT_LOCALE: Locale = 'en';
 
/** Each language by its own name, for the language menu. */
export const LOCALE_NAMES: Readonly<Record<Locale, string>> = { en: 'English', ja: '日本語' };
 
/** Cookie holding the language the viewer picked. */
export const LOCALE_COOKIE = 'lb-lang';
 
export function isLocale(value: string | undefined | null): value is Locale {
  return value !== undefined && value !== null && (LOCALES as readonly string[]).includes(value);
}
 
/**
 * The language of a page: `?lang=` first (a shared link can carry one, and link previews have no cookie), then the
 * language the viewer picked (the cookie), then the browser's `Accept-Language` in its order of preference, then
 * English.
 */
export function resolveLocale(request: {
  query?: string | undefined;
  cookie?: string | undefined;
  acceptLanguage?: string | undefined;
}): Locale {
  if (isLocale(request.query)) return request.query;
  if (isLocale(request.cookie)) return request.cookie;
  for (const tag of parseAcceptLanguage(request.acceptLanguage ?? '')) {
    const primary = tag.split('-')[0]!.toLowerCase();
    if (isLocale(primary)) return primary;
  }
  return DEFAULT_LOCALE;
}
 
/** The language tags of an `Accept-Language` header, most wanted first (`q=0` ones dropped). */
function parseAcceptLanguage(header: string): string[] {
  return header
    .split(',')
    .map((part, index) => {
      const [tag = '', ...params] = part.trim().split(';');
      const q = params.map((param) => /^\s*q=([\d.]+)\s*$/.exec(param)?.[1]).find((value) => value !== undefined);
      return { tag: tag.trim(), q: q === undefined ? 1 : Number(q), index };
    })
    .filter((entry) => entry.tag !== '' && entry.tag !== '*' && entry.q > 0)
    .sort((a, b) => b.q - a.q || a.index - b.index)
    .map((entry) => entry.tag);
}