All files / src/lib metadata-language.ts

97.67% Statements 42/43
88.23% Branches 45/51
100% Functions 9/9
97.36% Lines 37/38

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169                        114x         114x                           114x           15x 15x 60x 60x 60x 60x 60x 60x 60x     60x 2x   60x   15x                                                 115x 115x                           83x     18x                     114x       18391x 18391x 18391x 618x         17773x                               17778x 17780x 17780x 17775x     3x                           18394x 18394x 18392x 17773x       64x 64x          
/**
 * Dataset descriptions in more than one language (#782, phase 1).
 *
 * English is the source language of every description. A translation sits on
 * the HealthDataset node as a property with the language as suffix (titleDe,
 * descriptionDe, hdcatapKeywordsDe), written by
 * neo4j/seed-catalog-translations.cypher; the proxy's HealthDCAT-AP
 * serialiser tags each with its language. Only the description of a dataset
 * is translated here, never what a person entered (an application, a permit).
 */
 
/** The languages a description can carry besides English, as in the proxy. */
const METADATA_LANGUAGES = ["de", "fr", "nl", "es"] as const;
export type MetadataLanguage = (typeof METADATA_LANGUAGES)[number];
export type CatalogLanguage = "en" | MetadataLanguage;
 
/** What the language switch shows, in each language's own name. */
export const LANGUAGE_NAMES: Record<CatalogLanguage, string> = {
  en: "English",
  de: "Deutsch",
  fr: "Français",
  nl: "Nederlands",
  es: "Español",
};
 
export interface Translation {
  title?: string;
  description?: string;
  keywords?: string[];
}
 
const suffix = (lang: string) => lang[0].toUpperCase() + lang.slice(1);
 
/** The translations among a node's properties, as a map by language. */
export function translationsOf(
  props: Record<string, unknown> | null | undefined,
): Partial<Record<MetadataLanguage, Translation>> {
  const out: Partial<Record<MetadataLanguage, Translation>> = {};
  for (const lang of METADATA_LANGUAGES) {
    const s = suffix(lang);
    const title = props?.[`title${s}`];
    const description = props?.[`description${s}`];
    const keywords = props?.[`hdcatapKeywords${s}`];
    const t: Translation = {};
    if (typeof title === "string" && title) t.title = title;
    Iif (typeof description === "string" && description) {
      t.description = description;
    }
    if (Array.isArray(keywords) && keywords.length) {
      t.keywords = keywords.map(String);
    }
    if (Object.keys(t).length) out[lang] = t;
  }
  return out;
}
 
export interface Localised {
  title: string;
  description: string;
  /** The language each text is actually in: the chosen one, or English. */
  titleLang: CatalogLanguage;
  descriptionLang: CatalogLanguage;
}
 
/**
 * A dataset's title and description in the chosen language, each falling
 * back to English on its own when that language has none. A description in
 * the chosen language is not replaced by its title, as the serialiser does:
 * the page has the English description to show instead.
 */
export function localise(
  d: {
    title?: string;
    description?: string;
    translations?: Partial<Record<MetadataLanguage, Translation>>;
  },
  lang: CatalogLanguage,
): Localised {
  const t = lang === "en" ? undefined : d.translations?.[lang];
  return {
    title: t?.title ?? d.title ?? "",
    description: t?.description ?? d.description ?? "",
    titleLang: t?.title ? lang : "en",
    descriptionLang: t?.description ? lang : "en",
  };
}
 
/** Every text of a dataset in every language, for a search in any of them. */
export function searchableText(d: {
  title?: string;
  description?: string;
  translations?: Partial<Record<MetadataLanguage, Translation>>;
}): string {
  return [
    d.title,
    d.description,
    ...Object.values(d.translations ?? {}).flatMap((t) => [
      t?.title,
      t?.description,
      ...(t?.keywords ?? []),
    ]),
  ]
    .filter(Boolean)
    .join(" ")
    .toLowerCase();
}
 
const STORAGE_KEY = "catalog-metadata-language";
 
/** The language the visitor chose before, or null when they never chose. */
export function storedLanguage(): CatalogLanguage | null {
  try {
    const v = localStorage.getItem(STORAGE_KEY);
    if (v === "en" || METADATA_LANGUAGES.includes(v as MetadataLanguage)) {
      return v as CatalogLanguage;
    }
  } catch {
    // no storage (private window): no choice on record
  }
  return null;
}
 
/**
 * The first of the browser's languages the catalogue has descriptions in,
 * by its primary subtag (de-AT is German), else English. Only a default:
 * a choice the visitor made, or ?lang= in the address, wins over it.
 */
export function browserLanguage(
  available: CatalogLanguage[],
  preferred: readonly string[] = typeof navigator === "undefined"
    ? []
    : navigator.languages?.length
      ? navigator.languages
      : [navigator.language],
): CatalogLanguage {
  for (const tag of preferred) {
    const primary = (tag ?? "").toLowerCase().split("-")[0];
    if (available.includes(primary as CatalogLanguage)) {
      return primary as CatalogLanguage;
    }
  }
  return "en";
}
 
/**
 * The language to show: ?lang= in the address (a shared link), else the
 * visitor's stored choice, else the browser's language, else English. A
 * language the catalogue has no descriptions in falls through to the next.
 */
export function initialLanguage(
  available: CatalogLanguage[],
  fromUrl: string | null,
  stored: CatalogLanguage | null,
  preferred?: readonly string[],
): CatalogLanguage {
  const url = (fromUrl ?? "").toLowerCase() as CatalogLanguage;
  if (available.includes(url)) return url;
  if (stored && available.includes(stored)) return stored;
  return browserLanguage(available, preferred);
}
 
export function storeLanguage(lang: CatalogLanguage): void {
  try {
    localStorage.setItem(STORAGE_KEY, lang);
  } catch {
    // the choice holds for this page only
  }
}