File size: 1,361 Bytes
6f28f9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// The page's words: data/copy.json. Every string the levels, the confidence and the checks show comes from here by
// key; {name} marks a value the page fills in.
let COPY = {};

/** Read a JSON file, or fail with its name and status (shown in the lede, as for the measurements). */
export async function getJson(url) {
  const res = await fetch(url, { cache: 'no-cache' });
  if (!res.ok) throw new Error(`${url}: ${res.status}`);
  return res.json();
}

export async function loadCopy(url) {
  COPY = await getJson(url);
}

function lookup(key) {
  return key.split('.').reduce((node, k) => (node && typeof node === 'object' ? node[k] : undefined), COPY);
}

/** The string at key with its {placeholders} filled from vars; '' when the key or any of its values is missing, so
 *  the caller leaves the element out rather than show a gap. */
export function t(key, vars = {}) {
  const s = lookup(key);
  if (typeof s !== 'string') return '';
  let gap = false;
  const out = s.replace(/\{(\w+)\}/g, (_, name) => {
    const v = vars[name];
    if (v == null || v === '') gap = true;
    return gap ? '' : String(v);
  });
  return gap ? '' : out;
}

/** The strings of a list key (such as try.general), without empty ones. */
export function list(key) {
  const v = lookup(key);
  return Array.isArray(v) ? v.filter((s) => typeof s === 'string' && s) : [];
}