GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/04-400kv-engine

Table and 5 more files

A JavaScript module in the iterations folder of Galaxies Wafers that draws blocks and uses data from the stars repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.

698 lines of JavaScript and CSS and HTML from galaxies-wafers, in 6 files. Topic: Kuiper, cosmos and drawing engines. Section 1181 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Questions render · galaxies-wafers / iterations/04-400kv-engine/questions.mjs lines 1–133
  2. Iterations — 04 400kV Engine Style Sheet render · galaxies-wafers / iterations/04-400kv-engine/style.css lines 1–97
  3. Iterations — 05 Periodic Table Page render · galaxies-wafers / iterations/05-periodic-table/index.html lines 1–46
  4. Questions render · galaxies-wafers / iterations/05-periodic-table/questions.mjs lines 1–136
  5. Iterations — 05 Periodic Table Style Sheet render · galaxies-wafers / iterations/05-periodic-table/style.css lines 1–114
  6. Table interaction · galaxies-wafers / iterations/05-periodic-table/table.mjs lines 1–172

Questions

A JavaScript module in the iterations folder of Galaxies Wafers that paints machine (`paintMachine`), covering substations. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/.

rendergalaxies-wafers / iterations/04-400kv-engine/questions.mjs · lines 1–133 of 133 · Entry point · pattern paintMachine (shared by 6 files)

What it does
It draws substations. Defines 11 functions or classes, including $, fmt, place, text, lineOf. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word '400kv'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: substations, 400kV.
Inputs & outputs
Voltage levels named: 400kV.
Downstream impact
Used directly by 1 file: Iterations — 04 400kV Engine Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/). Reached from 88 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/.
What it achieves
It paints machine (`paintMachine`) and is built from the fmt step (`fmt`) and the place step (`place`). Iteration 04: the owner's three questions and the machine detail line, added after the page was built. It responds to resize and toggle events.
Why it matters
Loaded by the 04 400kV Engine page at https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/.
Application
galaxies-wafers · iterations/04-400kv-engine · JavaScript module
Uses
Layers Panel (import)
Used by
loaded by Iterations — 04 400kV Engine Page (script src)
Produces
$, fmt, place, text, lineOf, answer, bandsPrinted, build, get, at, paintMachine
Defines here
$, fmt, place, text, lineOf, answer, bandsPrinted, build, get, at, paintMachine
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/04-400kv-engine/questions.mjs:1-133 · blob 8f1d082fd25dcdd13ca0246149a90609ebc9ca0d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
/* questions.mjs — iteration 04: the owner's three questions and the machine
 * detail line, added after the page was built. It changes nothing the page
 * does: it fetches nothing until the reader opens the panel, then reads
 * layers/manifest.json, atlas/index.html (the Topology group of GROUPS) and this
 * directory's own layers-panel.mjs, so every count, style and line number below
 * is measured at run time. Band lower bounds are read from the engine panel the
 * page already prints (#engineThresholds), never recomputed here.
 */
import { FEATURE_CAP, FETCH_TIMEOUT_MS, MAX_FETCH } from './layers-panel.mjs';

const ROOT = '../../';
const BASE_COMMIT = '6d17227';   /* the branch commit this panel was added on */
const $ = id => document.getElementById(id);
const fmt = n => Number(n).toLocaleString('en-GB');

const box = $('questions'), body = $('qbody');

/* The open panel sits between the engine panel and the FLY form, under both. */
function place() {
  if (!box.open) return;
  const e = $('engine')?.getBoundingClientRect(), f = $('beam')?.getBoundingClientRect();
  const top = Math.ceil((e ? e.bottom : 40) + 8), bottom = Math.floor(f ? f.top - 8 : innerHeight - 90);
  body.style.top = top + 'px';
  body.style.maxHeight = Math.max(120, bottom - top) + 'px';
}
addEventListener('resize', place);

async function text(url) {
  const ctl = new AbortController(), t = setTimeout(() => ctl.abort(), FETCH_TIMEOUT_MS);
  try {
    const r = await fetch(url, { cache: 'default', signal: ctl.signal });
    if (!r.ok) throw new Error(url.replace(ROOT, '') + ' HTTP ' + r.status);
    return await r.text();
  } finally { clearTimeout(t); }
}

/* The 1-based line on which a declaration starts in a source text, or null. */
const lineOf = (src, re) => { const i = src.search(re); return i < 0 ? null : src.slice(0, i).split('\n').length; };

function answer(dl, q, a) {
  const dt = document.createElement('dt'); dt.textContent = q;
  const dd = document.createElement('dd'); dd.textContent = a;
  dl.append(dt, dd);
}

const bandsPrinted = () => [...document.querySelectorAll('#engineThresholds .ethreshold')]
  .map(e => e.textContent.replace(/\s+/g, ' ').replace(/ lines from q\d+/, '').trim());

let built = null, facts = null;
async function build() {
  const dl = $('qlist');
  facts = { mods: null, atlas: null, L: {}, atlasLine: null, groupsLine: null, why: [] };
  const [man, atlas, src] = await Promise.allSettled([text(ROOT + 'layers/manifest.json'), text(ROOT + 'atlas/index.html'), text('layers-panel.mjs')]);
  if (man.status === 'fulfilled') {
    const m = JSON.parse(man.value);
    const mods = m.layers.filter(l => l.id.startsWith('module-'));
    facts.mods = { n: mods.length, layers: m.layers.length, features: mods.reduce((s, l) => s + (Number(l.features) || 0), 0) };
  } else facts.why.push('layers/manifest.json: ' + man.reason.message);
  if (atlas.status === 'fulfilled') {
    const h = atlas.value, start = h.indexOf('group: "Topology');
    facts.groupsLine = lineOf(h, /const GROUPS\s*=/);
    if (start >= 0) {
      facts.atlasLine = h.slice(0, start).split('\n').length;
      const rows = h.slice(start, h.indexOf('] },', start)).split('\n').filter(t => /\{\s*id:/.test(t));
      const get = (t, k) => (t.match(new RegExp(k + ':\\s*"([^"]*)"')) || [])[1];
      facts.atlas = rows.map(t => ({ label: get(t, 'label'), color: get(t, 'color'), type: get(t, 'type'), width: (t.match(/width:\s*([0-9.]+)/) || [])[1] }));
    } else facts.why.push('atlas/index.html has no Topology group');
  } else facts.why.push('atlas/index.html: ' + atlas.reason.message);
  if (src.status === 'fulfilled') {
    const s = src.value;
    for (const [k, re] of Object.entries({
      evalExpr: /function evalExpr\(/, readAtlasTopology: /async function readAtlasTopology\(/, moduleStats: /function moduleStats\(/,
      computeBands: /function computeBands\(/, bandOf: /const bandOf =/, FEATURE_CAP: /export const FEATURE_CAP/, makeRoom: /function makeRoom\(/,
      viewRing: /function viewRing\(/, loadInView: /async function loadInView\(/, strokeRoute: /function strokeRoute\(/, planRaster: /function planRaster\(/,
    })) facts.L[k] = lineOf(s, re);
  } else facts.why.push('layers-panel.mjs: ' + src.reason.message);

  const at = k => facts.L[k] ? `${k}() line ${facts.L[k]}` : `${k}() (line not found)`;
  const lines = facts.atlas ? facts.atlas.filter(r => r.type === 'line') : [];
  const sub = facts.atlas ? facts.atlas.find(r => r.type === 'point') : null;
  const styles = lines.length
    ? lines.map(r => `${r.label} ${r.color} width ${r.width}`).join(', ') + (sub ? `; ${sub.label} ${sub.color} point` : '')
    : 'not read (' + facts.why.join('; ') + ')';

  answer(dl, '1 · How does this help draw a system or a single-line diagram?',
    'It draws no network and no SLD. It is a visual metaphor for code: each module\'s routes (LineString geometry.keys in its layers/module-*.json file) ' +
    'are painted as if they were transmission lines, and a module\'s "voltage" is only its quantile band of distinct numbered lines, not a voltage. ' +
    `The styles are the Grid Atlas Topology group, read now from atlas/index.html${facts.atlasLine ? ' line ' + facts.atlasLine : ''}: ${styles}. ` +
    `Each module's smallest key is drawn as the substation point, its radius from the Atlas zoom expression by ${at('evalExpr')}. ` +
    'What it enables: the feeder and cable-route line grammar (colour and width per voltage level) and the substation marker, taken from Atlas data rather than typed, ' +
    `drawn over thousands of routes by ${at('strokeRoute')} and ${at('planRaster')} in layers-panel.mjs. A later SLD layer could reuse that paint; no busbar, transformer, protection or earthing is drawn here.`);

  answer(dl, '2 · What is this code used for?',
    'Files: index.html, app.mjs (the wafer), layers-panel.mjs (layers and engine mode), style.css, questions.mjs (this panel). ' +
    `In layers-panel.mjs: loader ${at('loadInView')}, ${at('viewRing')}, ${at('makeRoom')}, FEATURE_CAP line ${facts.L.FEATURE_CAP ?? 'not found'}; ` +
    `Atlas reader ${at('readAtlasTopology')} (reads the Topology group of GROUPS${facts.groupsLine ? ', declared at atlas/index.html line ' + facts.groupsLine : ''}); ` +
    `bands ${at('moduleStats')}, ${at('computeBands')}, bandOf line ${facts.L.bandOf ?? 'not found'}. Line numbers are measured from this copy of the file at run time. ` +
    'Who else uses the same styles: iterations/33-engines-as-tools/tools.mjs states in its source that its evalExpr, parseAtlasTopology and voltageBands were lifted from this file ' +
    '(cited from its source comments, at an earlier commit with other line numbers); iterations/41-golden-angle/app.mjs lists this directory\'s app.mjs and layers-panel.mjs among importers of place() (name-match inference). ' +
    'Nothing imports this copy.');

  answer(dl, '3 · Where does it lead next?',
    'iterations/33-engines-as-tools: the same drawing logic as tools (voltageBands, strokeLikeTransmission, substationDot) applied to any layer, not only module routes. ' +
    'iterations/30-journey: the wafer by level of detail, following one thread stop by stop. ' +
    'The next electrical element of a real system is not established: this page carries none.');
  const nav = document.createElement('p');
  nav.innerHTML = '<a href="../33-engines-as-tools/">33 · engines as tools</a> · <a href="../30-journey/">30 · journey</a>';
  dl.after(nav);
}

function paintMachine() {
  const v = window.__wafer?.view, b = bandsPrinted(), F = facts;
  const held = window.__layers04?.held?.();
  const t = 'Machine detail · inputs: ' +
    (F?.mods ? `${fmt(F.mods.n)} module layers of ${fmt(F.mods.layers)} in layers/manifest.json (${fmt(F.mods.features)} features; keys are dimensionless line numbers)` : 'layers/manifest.json module layers (not read yet)') +
    `; atlas GROUPS Topology: ${F?.atlas ? F.atlas.length + ' rows' : 'not read yet'}; zoom proxy log2(pixels per wafer unit) = ${v?.zoom ? Math.log2(v.zoom).toFixed(2) : 'waiting for the wafer'} · ` +
    `outputs: band lower bounds in distinct lines per module, ${b.length ? b.join(', ') : 'none yet (no module routes loaded)'} (read live from the engine panel) · ` +
    `refusals and limits: ${fmt(FEATURE_CAP)}-feature ceiling (${held != null ? fmt(held) + ' held now' : 'held count unavailable'}), a module that does not fit is not loaded, with the reason on its row; ` +
    `each press loads only modules with a line in the ring of radii on screen; ${MAX_FETCH} fetches at a time, ${FETCH_TIMEOUT_MS / 1000} s timeout; an unreadable Atlas turns engine mode off with the reason · ` +
    `commits: this directory at ${BASE_COMMIT}; 33's tools.mjs cites 04 at 34f7a16c6677; numbered database testcode 202609142202 (app.mjs DATA)` +
    (F?.why.length ? ' · not read: ' + F.why.join('; ') : '');
  const m = $('machine');
  if (m.textContent !== t) m.textContent = t;
}

let timer = 0;
box.addEventListener('toggle', () => {
  if (!box.open) { clearInterval(timer); timer = 0; return; }
  place();
  if (!built) built = build().then(paintMachine, e => { $('machine').textContent = 'Questions could not be built: ' + e.message; });
  paintMachine();
  if (!timer) timer = setInterval(() => { place(); paintMachine(); }, 500);
});

Iterations — 04 400kV Engine Style Sheet

A style sheet in Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/.

rendergalaxies-wafers / iterations/04-400kv-engine/style.css · lines 1–97 of 97 · Entry point

What it does
Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word '400kv'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV.
Inputs & outputs
Voltage levels named: 400kV.
Downstream impact
Used directly by 1 file: Iterations — 04 400kV Engine Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/). Reached from 88 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/.
What it achieves
The Line Wafer. Designed at 430 px first; the desktop is the same layout with more room.
Why it matters
Loaded by the 04 400kV Engine page at https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/.
Application
galaxies-wafers · iterations/04-400kv-engine · style sheet
Uses
none found
Used by
loaded by Iterations — 04 400kV Engine Page (stylesheet)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/04-400kv-engine/style.css:1-97 · blob de982daff68783870eac33dfbfa46d3c62875572 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
/* The Line Wafer. Designed at 430 px first; the desktop is the same layout with
   more room. One canvas, three chrome strips, nothing that scrolls the page. */

:root{
  --ink:#d8dee9; --dim:#8b93a7; --ground:#0b0d12; --edge:#1b2030;
  --lit:#ffd54a; --beam:#5ec8f2;
  --top:env(safe-area-inset-top,0px); --bot:env(safe-area-inset-bottom,0px);
}
*{box-sizing:border-box}
html,body{height:100%}
body{
  margin:0; background:var(--ground); color:var(--ink);
  font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
  overflow:hidden; overscroll-behavior:none; -webkit-text-size-adjust:100%;
}
#stage{position:fixed; inset:0; width:100%; height:100%; display:block; touch-action:none}

#bar{
  position:fixed; left:0; right:0; top:0; z-index:2;
  display:flex; gap:.75rem; align-items:baseline; flex-wrap:wrap;
  padding:calc(var(--top) + .5rem) .75rem .5rem;
  background:linear-gradient(#0b0d12ee,#0b0d1200); pointer-events:none;
}
#wordmark{letter-spacing:.14em; font-size:11px}
.dim{color:var(--dim)}

#beam{
  position:fixed; z-index:3; left:.5rem; right:.5rem;
  bottom:calc(var(--bot) + 3.4rem);
  display:flex; gap:.4rem;
}
#beam input{
  flex:1 1 0; min-width:0; padding:.6rem .55rem;
  background:#11151f; color:var(--ink); border:1px solid var(--edge); border-radius:6px;
  font:inherit; font-size:16px; /* 16px stops iOS zooming the page on focus */
}
#beam input:focus{outline:none; border-color:var(--beam)}
#beam button{
  flex:0 0 auto; padding:.6rem .9rem; border-radius:6px; cursor:pointer;
  background:#11151f; color:var(--beam); border:1px solid var(--beam);
  font:inherit; font-size:13px; letter-spacing:.1em;
}
#beam button:active{background:#16202c}

#panel{
  position:fixed; z-index:4; left:.5rem; right:.5rem;
  bottom:calc(var(--bot) + 6.6rem);
  max-height:52vh; overflow:auto; -webkit-overflow-scrolling:touch;
  background:#0e121bf2; border:1px solid var(--edge); border-radius:8px;
  padding:.75rem .8rem 1rem;
}
#panel[hidden]{display:none!important}
#close{
  position:absolute; top:.35rem; right:.4rem; width:2rem; height:2rem;
  background:none; border:0; color:var(--dim); font:inherit; font-size:15px; cursor:pointer;
}
#panel h2{margin:0 .5rem .5rem 0; font-size:15px; font-weight:600; letter-spacing:.02em}
#panel h2 .n{color:var(--lit)}
#panel dl{display:grid; grid-template-columns:auto 1fr; gap:.15rem .6rem; margin:.5rem 0}
#panel dt{color:var(--dim)}
#panel dd{margin:0; overflow-wrap:anywhere}
#panel p{margin:.5rem 0 0}
#panel ul{margin:.35rem 0 0; padding-left:1.1rem}
#panel li{margin:.15rem 0}
.fam{color:var(--beam)}
.refuse{color:var(--lit)}

#foot{
  position:fixed; z-index:2; left:0; right:0; bottom:0;
  display:flex; gap:.15rem; flex-direction:column;
  padding:.35rem .75rem calc(var(--bot) + .35rem);
  background:linear-gradient(#0b0d1200,#0b0d12ee); pointer-events:none;
  font-size:10.5px;
}
#hint{text-align:left}
#foot a{color:var(--beam); pointer-events:auto; text-decoration:underline}

/* Questions: the summary sits in the wordmark row, right of THE LINE WAFER; the
   open body is placed by questions.mjs between the engine panel and the FLY form,
   beneath both panels and the LAYERS list so it never covers a control. */
#questions{position:fixed; z-index:4; right:.6rem; top:calc(var(--top) + .45rem); font-size:10.5px}
#questions summary{cursor:pointer; color:var(--beam); letter-spacing:.08em; width:max-content; margin-left:auto; padding:.1rem .2rem}
#qbody{position:fixed; left:.5rem; right:.5rem; top:12rem; background:#0e121bf2; border:1px solid var(--edge); border-radius:8px; padding:.4rem .55rem; max-height:45vh; overflow:auto; -webkit-overflow-scrolling:touch}
#questions dl{margin:.1rem 0 0}
#questions dt{color:var(--ink); margin-top:.35rem}
#questions dd{margin:.1rem 0 0; color:var(--dim); overflow-wrap:anywhere}
#questions p{margin:.4rem 0 0; overflow-wrap:anywhere}
#questions a{color:var(--beam)}

@media (min-width:760px){
  #qbody{left:.5rem; right:auto; width:26rem}
  #beam{left:auto; right:1rem; width:26rem; bottom:calc(var(--bot) + 2.9rem)}
  #foot{flex-direction:row; gap:.6rem; justify-content:space-between}
  #hint{text-align:right}
  #panel{left:1rem; right:auto; width:26rem; bottom:calc(var(--bot) + 2.5rem); max-height:66vh}
  #foot{font-size:11px}
}

Iterations — 05 Periodic Table Page

A web page in Galaxies Wafers. Published at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.

rendergalaxies-wafers / iterations/05-periodic-table/index.html · lines 1–46 of 46 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: form fields (user input). Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.
What it achieves
The Line Wafer — the periodic table of blocks, on the numbered surface.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
galaxies-wafers · iterations/05-periodic-table · page
Uses
Iterations — 05 Periodic Table Style Sheet (stylesheet), Questions (stylesheet), Galaxies Wafers — Proof Page (link), Iterations — 01 Route Alpha (script src), Layers Panel (script src), Table (script src), Questions (script src)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/05-periodic-table/index.html:1-46 · blob 83a6426d868fb857e9721b19b9c2c4a0a4f564fd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=5">
<meta name="color-scheme" content="dark">
<title>The Line Wafer — the periodic table of blocks, on the numbered surface</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="questions.css">
</head>
<body>

<canvas id="stage" aria-label="Every permanently numbered line of code in the estate, placed by its own number."></canvas>

<header id="bar">
  <span id="wordmark">THE LINE WAFER · PERIODIC TABLE</span>
  <span id="count" class="dim">loading the numbered database…</span>
  <details id="questions"><summary>Questions</summary><dl id="qlist"></dl><p id="machine" class="dim"></p></details>
</header>

<form id="beam" autocomplete="off">
  <input id="a" inputmode="numeric" pattern="[0-9]*" placeholder="line number" aria-label="line number to fly to">
  <input id="b" inputmode="numeric" pattern="[0-9]*" placeholder="connect to…" aria-label="second line number to connect to">
  <button id="go" type="submit">FLY</button>
</form>

<section id="panel" hidden>
  <button id="close" type="button" aria-label="close">✕</button>
  <div id="panelbody"></div>
</section>

<footer id="foot">
  <span id="prov" class="dim">provenance loading</span>
  <span id="hint" class="dim">drag to steer · pinch or scroll to focus the beam · tap a line</span>
  <a id="proofs" href="../../proof/">check every claim on this page</a>
</footer>

<noscript><p class="dim" style="padding:1rem">This surface is drawn from the numbered database at run time, so it needs JavaScript. Nothing here is typed into the page.</p></noscript>

<script type="module" src="app.mjs"></script>
<script type="module" src="layers-panel.mjs"></script>
<script type="module" src="table.mjs"></script>
<script type="module" src="questions.mjs"></script>
</body>
</html>

Questions

A JavaScript module in the iterations folder of Galaxies Wafers using data from the stars repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.

rendergalaxies-wafers / iterations/05-periodic-table/questions.mjs · lines 1–136 of 136 · Entry point · pattern cells (shared by 6 files)

What it does
It draws its content. Defines 14 functions or classes, including $, fmt, answer, fill, readJSON. Side effects: changes the web page (DOM); makes network requests.
Inputs & outputs
In: data source: stars data.
Downstream impact
Used directly by 1 file: Iterations — 05 Periodic Table Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.
What it achieves
It reads JSON (`readJSON`) and is built from the fmt step (`fmt`) and the answer step (`answer`). Iteration 05, the Periodic Table on the wafer: the owner's three questions and the machine detail line. It responds to resize and toggle events.
Why it matters
Loaded by the 05 Periodic Table page at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.
Application
galaxies-wafers · iterations/05-periodic-table · JavaScript module
Uses
none found
Used by
loaded by Iterations — 05 Periodic Table Page (script src)
Produces
$, fmt, answer, fill, readJSON, layerTags, sldSentence, text, mount, fit, paint, cells
Defines here
$, fmt, answer, fill, readJSON, layerTags, sldSentence, text, mount, fit, paint, cells, fill, by
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/05-periodic-table/questions.mjs:1-136 · blob d4c609cc13708c90fbe2a65989b400bb80a85542 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* questions.mjs — iteration 05, the Periodic Table on the wafer: the owner's
 * three questions and the machine detail line. Block and category counts are
 * read at run time from the strip table.mjs built from the live register (no
 * second fetch of it); functions are cited to file and line.
 */

const $ = id => document.getElementById(id);
const fmt = n => Number(n).toLocaleString('en-GB');
const DATA_PIN = 'https://globalgrid2050.com/testcode/202609142202/data/';
const SEARCH = 'repository search at ee082ea';   /* the commit the "who else" searches were run on */

/* One question and its answer. Parts are strings or [text, href] links; text only, never HTML. */
function answer(dl, q, parts) {
  const dt = document.createElement('dt'); dt.textContent = q;
  const dd = document.createElement('dd');
  const fill = ps => {
    dd.replaceChildren();
    for (const p of [].concat(ps)) {
      if (Array.isArray(p)) { const a = document.createElement('a'); a.textContent = p[0]; a.href = p[1]; dd.append(a); }
      else dd.append(String(p));
    }
  };
  fill(parts);
  dl.append(dt, dd);
  return fill;
}

/* One fetch, 15 s timeout, only when the reader opens the panel. */
async function readJSON(url) {
  const c = new AbortController();
  const t = setTimeout(() => c.abort(), 15000);
  try {
    const r = await fetch(url, { cache: 'default', signal: c.signal });
    if (!r.ok) throw new Error(url + ' returned HTTP ' + r.status);
    return await r.json();
  } finally { clearTimeout(t); }
}

/* The layer rows' tags as the layers panel shows them now, counted from its own DOM. */
function layerTags() {
  const c = new Map();
  for (const t of document.querySelectorAll('#layersList .ltag')) {
    const s = (t.textContent.match(/[A-Z]+/) || ['?'])[0];
    c.set(s, (c.get(s) || 0) + 1);
  }
  return c.size ? [...c].map(([s, n]) => `${fmt(n)} ${s}`).join(', ') : 'layer rows not built yet';
}

/* Layers whose id names an SLD, read from a manifest at run time (name-match inference). */
function sldSentence(m, file) {
  const hits = m.layers.filter(l => /sld/i.test(l.id));
  if (!hits.length) return `None of the ${fmt(m.layers.length)} layers in ${file} carries "sld" in its id.`;
  return `Of ${fmt(m.layers.length)} layers in ${file}, ${hits.length} carry "sld" in their id (name-match inference): ` +
    hits.map(l => `${l.id} (${fmt(l.features)} features, draws ${l.draws})`).join(', ') + '.';
}

const text = id => ($(id)?.textContent || '').trim();

/* Collapsed by default. Nothing is read or fetched until the reader opens it; the
   machine line repaints every 500 ms only while it is open. */
function mount(build, machine) {
  const box = $('questions'), dl = $('qlist'), out = $('machine');
  if (!box || !dl || !out) return;
  let built = false, timer = 0;
  /* Opened, the panel stops above whatever is drawn at the bottom (line panel, clock, strip, beam form), never over it. */
  const fit = () => {
    const top = box.getBoundingClientRect().top;
    let floor = innerHeight;
    for (const id of ['panel', 'clock', 'ptable', 'beam']) {
      const el = $(id);
      const r = el && !el.hidden ? el.getBoundingClientRect() : null;
      if (r && r.height > 0 && r.top > top) floor = Math.min(floor, r.top);
    }
    box.style.maxHeight = Math.max(96, Math.min(innerHeight * 0.45, floor - top - 8)) + 'px';
  };
  const paint = () => {
    fit();
    try { out.textContent = 'Machine detail · ' + machine(); }
    catch (e) { out.textContent = 'Machine detail · not established: ' + e.message; }
  };
  /* A bottom element that grows while the panel is open refits it at once, not at the next repaint. */
  if ('ResizeObserver' in window) {
    const ro = new ResizeObserver(() => { if (box.open) fit(); });
    for (const id of ['panel', 'clock', 'ptable', 'beam']) if ($(id)) ro.observe($(id));
  }
  addEventListener('resize', () => { if (box.open) fit(); });
  box.addEventListener('toggle', () => {
    clearInterval(timer);
    if (!box.open) return;
    if (!built) { built = true; build(dl); }
    paint();
    timer = setInterval(paint, 500);
  });
}

const COMMIT = '5a6bb0d';   /* the commit that made this page; the Questions panel is added later */

/* The strip's cells as table.mjs drew them: symbol, category and tag state. */
function cells() {
  return [...document.querySelectorAll('#ptable .pcell')].map(n => ({ sym: n.dataset.symbol, cat: n.dataset.category, status: n.dataset.status || 'WAIT' }));
}

mount(dl => {
  const q1 = answer(dl, '1 · How does this help draw a system or a single-line diagram?', 'reading the strip…');
  answer(dl, '2 · What is this code used for?',
    'Finding a register block on the wafer. table.mjs: the live register is fetched at line 123 (REGISTER line 15) and drawn as one cell per block grouped by category; paint() line 55 writes a cell\'s WAIT/LOAD/OK/EMPTY/FAIL tag; ' +
    'choose() line 105 hydrates layers/modules/module-<Sym>.json through the layers panel (hydrate() line 74) and fly() line 95 sends the block\'s first line, firstLine() line 85, through the wafer\'s own beam form to flyTo() (app.mjs line 295); queue() line 114 hydrates a ?category= three at a time. ' +
    'layers-panel.mjs is the root copy with paths from the repository root and one hook, window.__layers, at line 422; app.mjs is the root copy with only its import path changed. ' +
    `Who else: nothing imports table.mjs but this page\'s index.html (${SEARCH}); module-<Sym> layers are written by build/build_layers_modules.py (id at line 89); the register is also read by the root app.mjs and iterations 03, 26, 31, 32 and 37 (${SEARCH}, text search); lib.mjs is imported by 42 files (${SEARCH}).`);
  answer(dl, '3 · Where does it lead next?', [
    'To the block\'s first line on the wafer (fly() line 95). Links between blocks are not drawn here; ',
    ['iteration 37, Hidden Wires', '../37-hidden-wires/'],
    ' draws the register\'s declared depends_on needs between blocks (37-hidden-wires/app.mjs line 554). The strip also links out to the periodic table page it mirrors (TABLE, table.mjs line 16).']);
  const fill = () => {
    const cs = cells();
    if (!cs.length) { q1(`Not established yet: the strip has no cells (${text('ptable') || 'register not read'}). The page draws no electrical element.`); return false; }
    const by = c => cs.filter(x => x.cat === c).map(x => x.sym);
    const net = by('network'), con = by('connections');
    const cats = new Set(cs.map(x => x.cat));
    q1('It draws no electrical element; it maps register blocks to their numbered lines, so the code of a block can be found on the wafer and read. ' +
      `Measured from the strip now: ${fmt(cs.length)} blocks in ${cats.size} categories; network holds ${net.length} (${net.join(', ') || 'none'}), connections holds ${con.length} (${con.join(', ') || 'none'}). ` +
      'That these concern grid elements is name-match inference from the register\'s category names.');
    return true;
  };
  if (!fill()) { const t = setInterval(() => { if (fill()) clearInterval(t); }, 1000); setTimeout(() => clearInterval(t), 30000); }
}, () => {
  const u = new URL(location.href).searchParams;
  const st = new Map();
  for (const c of cells()) st.set(c.status, (st.get(c.status) || 0) + 1);
  return `inputs: ?block=<symbol> (table.mjs line 40; in the URL now: ${u.get('block') ?? 'absent'}) and ?category=<name> (line 41; in the URL now: ${u.get('category') ?? 'absent'}), ?line= and ?to= (permanent line keys, readURL() app.mjs line 496), ?layers= (layers-panel.mjs line 254); ` +
    `data: all-lines.meta.json, all-lines.bin, all-lines.len.bin, all-lines.family.bin, families.json and lines.bin from ${DATA_PIN} (app.mjs line 48), ${text('prov') || 'provenance not loaded yet'}; ` +
    'the block register https://ventusltd.github.io/stars/blocks/blocks.json (live, not pinned to a commit); layer files from layers/ in this repository · ' +
    `outputs: ${text('count') || 'count not loaded yet'}; cells now ${st.size ? [...st].map(([s, n]) => `${fmt(n)} ${s}`).join(', ') : 'not drawn yet'}; layer rows now ${layerTags()} · ` +
    'refusals: a cell whose block has no module layer reads EMPTY "no numbered lines in this pack" (line 23); an unreadable register replaces the strip with its reason (line 127); a layer reads FAIL or EMPTY with its reason; unknown ?layers= ids are dropped without a warning (layers-panel.mjs line 256); refuse() app.mjs line 514 · ' +
    `source: page commit ${COMMIT}; lib.mjs and layers/ from this repository`;
});

Iterations — 05 Periodic Table Style Sheet

A style sheet in Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.

rendergalaxies-wafers / iterations/05-periodic-table/style.css · lines 1–114 of 114 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Iterations — 05 Periodic Table Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.
What it achieves
The Line Wafer. Designed at 430 px first; the desktop is the same layout with more room.
Why it matters
Loaded by the 05 Periodic Table page at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.
Application
galaxies-wafers · iterations/05-periodic-table · style sheet
Uses
none found
Used by
loaded by Iterations — 05 Periodic Table Page (stylesheet)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/05-periodic-table/style.css:1-114 · blob 5442543d0a86ed5ce7cbbb1871b71acc9647a58d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* The Line Wafer. Designed at 430 px first; the desktop is the same layout with
   more room. One canvas, three chrome strips, nothing that scrolls the page. */

:root{
  --ink:#d8dee9; --dim:#8b93a7; --ground:#0b0d12; --edge:#1b2030;
  --lit:#ffd54a; --beam:#5ec8f2;
  --top:env(safe-area-inset-top,0px); --bot:env(safe-area-inset-bottom,0px);
}
*{box-sizing:border-box}
html,body{height:100%}
body{
  margin:0; background:var(--ground); color:var(--ink);
  font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
  overflow:hidden; overscroll-behavior:none; -webkit-text-size-adjust:100%;
}
#stage{position:fixed; inset:0; width:100%; height:100%; display:block; touch-action:none}

#bar{
  position:fixed; left:0; right:0; top:0; z-index:2;
  display:flex; gap:.75rem; align-items:baseline; flex-wrap:wrap;
  padding:calc(var(--top) + .5rem) .75rem .5rem;
  background:linear-gradient(#0b0d12ee,#0b0d1200); pointer-events:none;
}
#wordmark{letter-spacing:.14em; font-size:11px}
.dim{color:var(--dim)}

#beam{
  position:fixed; z-index:3; left:.5rem; right:.5rem;
  bottom:calc(var(--bot) + 3.4rem);
  display:flex; gap:.4rem;
}
#beam input{
  flex:1 1 0; min-width:0; padding:.6rem .55rem;
  background:#11151f; color:var(--ink); border:1px solid var(--edge); border-radius:6px;
  font:inherit; font-size:16px; /* 16px stops iOS zooming the page on focus */
}
#beam input:focus{outline:none; border-color:var(--beam)}
#beam button{
  flex:0 0 auto; padding:.6rem .9rem; border-radius:6px; cursor:pointer;
  background:#11151f; color:var(--beam); border:1px solid var(--beam);
  font:inherit; font-size:13px; letter-spacing:.1em;
}
#beam button:active{background:#16202c}

#panel{
  position:fixed; z-index:4; left:.5rem; right:.5rem;
  bottom:calc(var(--bot) + 6.6rem);
  max-height:52vh; overflow:auto; -webkit-overflow-scrolling:touch;
  background:#0e121bf2; border:1px solid var(--edge); border-radius:8px;
  padding:.75rem .8rem 1rem;
}
#panel[hidden]{display:none!important}
#close{
  position:absolute; top:.35rem; right:.4rem; width:2rem; height:2rem;
  background:none; border:0; color:var(--dim); font:inherit; font-size:15px; cursor:pointer;
}
#panel h2{margin:0 .5rem .5rem 0; font-size:15px; font-weight:600; letter-spacing:.02em}
#panel h2 .n{color:var(--lit)}
#panel dl{display:grid; grid-template-columns:auto 1fr; gap:.15rem .6rem; margin:.5rem 0}
#panel dt{color:var(--dim)}
#panel dd{margin:0; overflow-wrap:anywhere}
#panel p{margin:.5rem 0 0}
#panel ul{margin:.35rem 0 0; padding-left:1.1rem}
#panel li{margin:.15rem 0}
.fam{color:var(--beam)}
.refuse{color:var(--lit)}

#foot{
  position:fixed; z-index:2; left:0; right:0; bottom:0;
  display:flex; gap:.15rem; flex-direction:column;
  padding:.35rem .75rem calc(var(--bot) + .35rem);
  background:linear-gradient(#0b0d1200,#0b0d12ee); pointer-events:none;
  font-size:10.5px;
}
#hint{text-align:left}
#foot a{color:var(--beam); pointer-events:auto; text-decoration:underline}

@media (min-width:760px){
  #beam{left:auto; right:1rem; width:26rem; bottom:calc(var(--bot) + 2.9rem)}
  #foot{flex-direction:row; gap:.6rem; justify-content:space-between}
  #hint{text-align:right}
  #panel{left:1rem; right:auto; width:26rem; bottom:calc(var(--bot) + 2.5rem); max-height:66vh}
  #foot{font-size:11px}
}

/* ── the periodic table strip (iteration 05) ─────────────────────────────── */
:root{ --strip:7.2rem }
#beam{bottom:calc(var(--bot) + var(--strip) + 3.4rem)}
#panel{bottom:calc(var(--bot) + var(--strip) + 6.6rem); max-height:38vh}
#foot{bottom:var(--strip)}
#ptable{
  position:fixed; z-index:6; left:0; right:0; bottom:0; height:calc(var(--strip) + var(--bot));
  padding:.3rem .5rem calc(var(--bot) + .3rem); background:#0b0d12f2; border-top:1px solid var(--edge);
  display:flex; gap:.6rem; overflow-x:auto; overflow-y:hidden; -webkit-overflow-scrolling:touch;
  font:10.5px/1.2 ui-monospace,Menlo,Consolas,monospace;
}
#ptable .pgroup{flex:0 0 auto; display:flex; flex-direction:column; gap:.2rem}
#ptable .phead{letter-spacing:.08em; font-size:9.5px; white-space:nowrap}
#ptable .pcells{display:grid; grid-auto-flow:column; grid-template-rows:repeat(2,2.7rem); gap:.2rem}
#ptable .pcell{
  width:2.7rem; height:2.7rem; padding:.1rem .15rem; border-radius:4px; cursor:pointer;
  background:#11151f; border:1px solid var(--edge); border-left:3px solid var(--c); color:var(--ink); font:inherit;
  display:flex; flex-direction:column; justify-content:space-between; align-items:stretch; text-align:left;
}
#ptable .pcell .pnum{color:var(--dim); font-size:8.5px}
#ptable .pcell .psym{color:var(--c); font-weight:700; font-size:12.5px}
#ptable .pcell .ltag{font-size:8px}
#ptable .pcell.lit{box-shadow:0 0 0 1px var(--c) inset; background:#161b28}
#ptable .pcell.sel{outline:1px solid var(--lit)}
#ptable .pnote{align-self:center; color:var(--dim); white-space:nowrap}
@media (min-width:760px){
  #beam{bottom:calc(var(--bot) + var(--strip) + 2.9rem)}
  #panel{bottom:calc(var(--bot) + var(--strip) + 2.5rem); max-height:52vh}
}

Table

A JavaScript module in the iterations folder of Galaxies Wafers that draws blocks and uses data from the stars repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.

interactiongalaxies-wafers / iterations/05-periodic-table/table.mjs · lines 1–172 of 172 · Entry point · pattern firstLine (shared by 2 files)

What it does
It draws blocks. Defines 13 functions or classes, including $, el, layers, waferReady, layerId. Side effects: changes the web page (DOM); makes network requests.
Inputs & outputs
In: data source: stars data; JSON file blocks.json.
Downstream impact
Used directly by 1 file: Iterations — 05 Periodic Table Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.
What it achieves
It is built from the layers step (`layers`), the wafer ready helper (`waferReady`) and the layer id helper (`layerId`). The periodic table, as a strip along the bottom of the wafer. It responds to layers and click events.
Why it matters
Loaded by the 05 Periodic Table page at https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/.
Application
galaxies-wafers · iterations/05-periodic-table · JavaScript module
Uses
Table (estate URL)
Used by
loaded by Iterations — 05 Periodic Table Page (script src)
Produces
$, el, layers, waferReady, layerId, paint, paintAll, hydrate, firstLine, fly, choose, queue
Defines here
$, el, layers, waferReady, layerId, paint, paintAll, hydrate, firstLine, fly, choose, queue, worker
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/05-periodic-table/table.mjs:1-172 · blob 29ee7056195556991d6ade2d0a520e17042aeebf · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* table.mjs — the periodic table, as a strip along the bottom of the wafer.
 *
 * One cell per block of the live register, grouped by category in the order the
 * register first uses each category, coloured by category. A cell's tag is the
 * Atlas's layer grammar for that block's module layer: WAIT until asked, LOAD
 * while fetching, OK when drawn, EMPTY with its reason, FAIL with its reason.
 *
 * Tapping a cell hydrates layers/modules/module-<Sym>.json through the layers
 * panel (so it draws on the wafer like any other layer) and flies the wafer to
 * the block's first line through the wafer's own beam form, whose handler calls
 * the wafer's own flyTo. The periodic table page's two parameters travel here:
 * ?block=Vd does the same on arrival; ?category=network lights every cell of
 * that category and hydrates their layers three at a time.
 */
const REGISTER = 'https://ventusltd.github.io/stars/blocks/blocks.json';
const TABLE = 'https://ventusltd.github.io/stars/table.html';
const CONCURRENCY = 3;
const COLOUR = {
  geodesy: '#00cc00', network: '#0054ff', connections: '#ff0000', constants: '#ff9900',
  cartridges: '#ffff00', layers: '#b200ff', arrival: '#ff00ff', news: '#ff4500',
  solar: '#ffd700', interface: '#00ffff', proofs: '#39ff14', other: '#8b93a7',
};
const NO_LAYER = 'no numbered lines in this pack';

const $ = id => document.getElementById(id);
const el = (tag, cls, text) => {
  const n = document.createElement(tag);
  if (cls) n.className = cls;
  if (text != null) n.textContent = String(text);
  return n;
};

const strip = el('section'); strip.id = 'ptable';
strip.setAttribute('aria-label', 'the periodic table of blocks');
strip.appendChild(el('span', 'pnote', 'loading the live block register…'));
document.body.appendChild(strip);

const cells = new Map();      /* symbol -> {block, node, tag} */
const params = new URLSearchParams(location.search);
const wantBlock = params.get('block');
const wantCategory = params.get('category');

const layers = () => new Promise(res => {
  if (window.__layers) return res(window.__layers);
  document.addEventListener('layers-ready', () => res(window.__layers), { once: true });
});

/* The wafer attaches its beam form's listener in the same task that first sizes its view. */
const waferReady = () => new Promise(res => {
  (function poll() { const v = window.__wafer?.view; v && v.w > 0 ? res() : setTimeout(poll, 120); })();
});

const layerId = sym => 'module-' + sym;

function paint(sym) {
  const c = cells.get(sym);
  const L = window.__layers;
  let status, why = '';
  if (!L) { status = 'WAIT'; why = 'layers loading'; }
  else if (!L.has(layerId(sym))) { status = 'EMPTY'; why = NO_LAYER; }
  else {
    const s = L.stateOf(layerId(sym));
    status = String(s.status).split(' ')[0];
    why = s.why || '';
  }
  c.tag.className = 'ltag ' + status;
  c.tag.textContent = status;
  c.node.dataset.status = status;
  c.node.title = `${c.block.symbol} · ${c.block.title} · ${c.block.category}${why ? ' · ' + why : ''}`;
}
const paintAll = () => { for (const s of cells.keys()) paint(s); };
document.addEventListener('layers-change', paintAll);

async function hydrate(sym) {
  const L = await layers();
  if (!L.has(layerId(sym))) { paint(sym); return null; }
  await L.hydrate(layerId(sym));
  paint(sym);
  return L.stateOf(layerId(sym));
}

/* The block's first line: the layer marks each function's first line with a
   Point; the first such mark is the first function's first line. (The lowest key
   is not it: that is usually a blank or a brace shared by thousands of families.) */
function firstLine(doc) {
  const feats = doc?.features || [];
  const mark = feats.find(f => f.geometry.type === 'Point' && f.properties?.mark === 'first line');
  if (mark) return mark.geometry.key;
  const route = feats.find(f => f.geometry.type === 'LineString' && f.geometry.keys?.length);
  return route ? route.geometry.keys[0] : null;
}

/* Fly with the wafer's own flyTo, reached through its own form; then put this
   page's parameters back, since the wafer's writeURL keeps only ?line and ?to. */
async function fly(key) {
  await waferReady();
  $('a').value = String(key); $('b').value = '';
  $('beam').requestSubmit();
  const u = new URL(location.href);
  for (const k of ['block', 'category']) { const v = params.get(k); if (v) u.searchParams.set(k, v); }
  history.replaceState(history.state, '', u.pathname + u.search + u.hash);
  window.__layers?.writeURL();
}

async function choose(sym) {
  for (const c of cells.values()) c.node.classList.toggle('sel', c.block.symbol === sym);
  params.set('block', sym);
  const s = await hydrate(sym);
  if (!s || s.status !== 'OK') return;
  const key = firstLine(s.doc);
  if (key !== null) await fly(key);
}

async function queue(symbols, n) {
  let i = 0;
  const worker = async () => { while (i < symbols.length) await hydrate(symbols[i++]); };
  await Promise.all(Array.from({ length: Math.min(n, symbols.length) }, worker));
}

(async () => {
  let reg;
  try {
    const r = await fetch(REGISTER, { cache: 'no-cache' });
    if (!r.ok) throw new Error('HTTP ' + r.status);
    reg = await r.json();
  } catch (e) {
    strip.replaceChildren(el('span', 'pnote', 'The live block register could not be read: ' + e.message));
    return;
  }
  const order = [];
  const byCat = new Map();
  for (const b of reg.blocks) {
    if (!byCat.has(b.category)) { byCat.set(b.category, []); order.push(b.category); }
    byCat.get(b.category).push(b);
  }
  strip.replaceChildren();
  for (const cat of order) {
    const colour = COLOUR[cat] || COLOUR.other;
    const g = el('div', 'pgroup'); g.style.setProperty('--c', colour);
    const head = el('div', 'phead', `${cat} · ${byCat.get(cat).length}`); head.style.color = colour;
    const grid = el('div', 'pcells');
    for (const b of byCat.get(cat)) {
      const node = el('button', 'pcell'); node.type = 'button';
      node.dataset.symbol = b.symbol; node.dataset.category = cat;
      const tag = el('span', 'ltag WAIT', 'WAIT');
      node.append(el('span', 'pnum', b.number), el('span', 'psym', b.symbol), tag);
      node.addEventListener('click', () => choose(b.symbol));
      cells.set(b.symbol, { block: b, node, tag });
      grid.appendChild(node);
    }
    g.append(head, grid);
    strip.appendChild(g);
  }
  const src = el('a', 'pnote', 'the periodic table ↗');
  src.href = TABLE + (wantBlock ? '?block=' + encodeURIComponent(wantBlock)
    : wantCategory ? '?category=' + encodeURIComponent(wantCategory) : '');
  src.target = '_blank'; src.rel = 'noopener noreferrer'; src.style.color = 'var(--beam)';
  strip.appendChild(src);
  await layers();
  paintAll();

  if (wantCategory && byCat.has(wantCategory)) {
    const syms = byCat.get(wantCategory).map(b => b.symbol);
    for (const s of syms) cells.get(s).node.classList.add('lit');
    cells.get(syms[0]).node.scrollIntoView({ inline: 'start', block: 'nearest' });
    queue(syms, CONCURRENCY);
  }
  if (wantBlock && cells.has(wantBlock)) {
    cells.get(wantBlock).node.scrollIntoView({ inline: 'center', block: 'nearest' });
    choose(wantBlock);
  }
})();