File size: 1,940 Bytes
25af026
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Minimal data loader and drawing scheduler for this static page.
// Loads data/<id>.json ({rows}), evaluates declared calcs, and runs each drawing on load, resize and tab change.
(function () {
  const store = {}, draws = {}, calcs = {};
  const empty = {status: 'loading', data: [], columns: []};
  window.dash = {
    colors: ['#2563eb', '#0891b2', '#7c3aed', '#ea580c', '#16a34a'],
    data(id) { return store[id] || empty; },
    draw(name, fn) { draws[name] = fn; },
    calc(id, spec) { calcs[id] = spec; },
    setLink(name) { history.replaceState(null, '', '#' + name); },
    redraw() {
      for (const [name, fn] of Object.entries(draws)) {
        document.querySelectorAll(`[data-draw="${name}"]`).forEach((el) => {
          if (el.closest('[hidden]')) return;              // drawn when its tab is shown
          try { fn(el); } catch (e) { console.error(name, e); }
        });
      }
    },
    async load(ids) {
      await Promise.all(ids.map(async (id) => {
        try {
          const r = await fetch(`data/${id}.json`);
          if (!r.ok) throw new Error(r.status);
          const rows = (await r.json()).rows;
          store[id] = {status: 'ok', data: rows, columns: rows.length ? Object.keys(rows[0]) : []};
        } catch (e) { store[id] = {status: 'error', data: [], message: String(e)}; }
      }));
      for (const [id, spec] of Object.entries(calcs)) {
        const inputs = spec.inputs.map((i) => store[i] || empty);
        store[id] = inputs.every((d) => d.status === 'ok')
          ? {status: 'ok', data: spec.fn(...inputs.map((d) => d.data))} : {status: 'error', data: null};
      }
      window.dash.redraw();
      window.scrollTo(0, 0);   // tabs share their names with sections: don't jump past the header
    },
  };
  let t;
  window.addEventListener('resize', () => { clearTimeout(t); t = setTimeout(() => window.dash.redraw(), 150); });
})();