GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/35-system-journey

Journey and 1 more file

A JavaScript module in the iterations folder of Galaxies Wafers that builds rows, paints row, verifies v9 and draws on a canvas, covering cables. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.

567 lines of JavaScript from galaxies-wafers, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1213 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. Journey interaction · galaxies-wafers / iterations/35-system-journey/journey.mjs lines 490–959
  2. Actions transform · galaxies-wafers / iterations/36-elements-assembly/actions.mjs lines 1–97

Journey

A JavaScript module in the iterations folder of Galaxies Wafers that builds rows, paints row, verifies v9 and draws on a canvas, covering cables. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.

interactiongalaxies-wafers / iterations/35-system-journey/journey.mjs · lines 490–959 of 959 (continued from section 1212) · Entry point · pattern buildInputs (shared by 2 files)

What it does
It draws cables, substations, transformers and 33kV. Defines 53 functions or classes, including $, el, nf, esc, attempt. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain terms in the code: cables, substations, transformers, 33kV, 100kV, 1kV.
Inputs & outputs
Out: canvas drawing. Voltage levels named: 100kV, 33kV, 1kV.
Downstream impact
Used directly by 1 file: Iterations — 35 System Journey Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.
What it achieves
It builds rows (`buildRows`), paints row (`paintRow`) and verifies v9 (`verifyV9`). One System, Stop by Stop. Five published engine calculations chained into one illustrative system and drawn as a single-line diagram that grows stop by stop. Its code works with 33 kV, 0 kV and 0.001 MVA. It responds to click, input and pointerdown events.
Why it matters
Loaded by the 35 System Journey page at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.
Application
galaxies-wafers · iterations/35-system-journey · JavaScript module
Uses
none found
Used by
loaded by Iterations — 35 System Journey Page (script src)
Produces
$, el, nf, esc, attempt, colourOf, enqueue, pump, timed, hydrate, M, why
Defines here
val, tag, renderStop, slider, toV, toT, show, seg, paint, buildInputs, kvs, setupPlane, kmPerDeg, move, drawPlane, lab, clip, fillList, rowOf, fillWires, update, paint, publish, go, skip, start, end
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/35-system-journey/journey.mjs:490-959 · blob a773b440d5a6bf6634a4eccd674ec9e28f26661e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
  const kvCol = w.kv && w.kv.out ? colourOf(w.kv.out.value) : node ? colourOf(Math.max(...node.voltages_kv)) : GREY;
  if (n >= 3 && R.s3 && !R.s3.empty) {
    const c = R.s3.corridor, ok = c && c.km != null;
    L(FX, BUS + 2, FX, LOADY - 8, '#000', 7);
    L(FX, BUS + 2, FX, LOADY - 8, ok ? kvCol : GREY, 3, ok ? '' : '4 3');
    T(FX + 10, BUS + 16, ok ? `${nf(c.km, 4)} km corridor` : c ? 'corridor WITHHELD' : 'corridor: null', 'y b');
    T(FX + 10, BUS + 27, `forCable ×${R.s3.ce.CABLE_FACTOR}`, 'd');
    T(FX + 10, BUS + 38, `straight ${nf(R.s3.straight, 4)} km`, 'd');
    T(FX + 10, BUS + 49, `R ${R.s3.geo9.EARTH_RADIUS_KM} km sphere`, 'd');
  } else if (n >= 3) {
    L(FX, BUS + 2, FX, LOADY - 8, GREY, 2, '3 3');
    T(FX + 10, BUS + 16, 'route EMPTY', 'd');
  } else {
    L(FX, BUS + 2, FX, LOADY - 8, '#1b2030', 3, '4 4'); ghost(FX + 10, BUS + 30, 'stop 3 · cable route');
  }

  /* stop 4: the physics along it, and the wires that feed it */
  if (n >= 4 && R.s4 && !R.s4.empty) {
    const s = R.s4;
    const val = (r, f) => r.ok ? f(r.ok) : r.err ? 'REFUSED' : 'EMPTY';
    T(FX + 10, BUS + 64, `I ${val(s.I, o => nf(o.value, 4) + ' A')}`, 'y b');
    T(FX + 10, BUS + 75, `ΔV ${val(s.D, o => nf(o.value, 4) + ' V')}`, 'y');
    T(FX + 10, BUS + 86, `   ${val(s.P, o => nf(o.value, 3) + ' %')}`, 'y');
    T(FX + 10, BUS + 97, `loss ${val(s.W, o => nf(o.value, 4) + ' W')}`, 'y');
    const tag = (y, wire, text) => T(FX - 8, y, `${text} · ${wire.state}`, wire.state === 'REFUSED' || wire.state === 'EMPTY' ? 'rf' : 'd', 'end');
    tag(BUS + 50, w.kv, `${w.kv.q ? w.kv.q.value + ' kV' : 'kV'} → kv`);
    tag(BUS + 64, w.len, 'km → lengthM');
    tag(BUS + 78, w.mva, 'kVA → mva');
    tag(LOADY - 14, w.load, `${S.carry} → kw`);
  } else if (n >= 4) {
    T(FX + 10, BUS + 64, 'physics EMPTY', 'd');
  } else {
    ghost(FX + 10, BUS + 70, 'stop 4 · I, ΔV, losses');
  }

  /* stop 1: the load */
  const s1 = R.s1 && !R.s1.empty ? R.s1 : null;
  const loadRefused = n >= 4 && w.load && w.load.state !== 'ACCEPTED';
  if (s1) {
    if (loadRefused) { L(FX, LOADY - 8, FX, LOADY - 1, '#0b0d12', 4); }
    p.push(`<path d="M${FX - 8} ${LOADY} L${FX + 8} ${LOADY} L${FX} ${LOADY + 13} Z" fill="${loadRefused ? 'none' : '#ffffff'}" stroke="#ffffff" stroke-width="1.4"${loadRefused ? ' stroke-dasharray="2 2"' : ''}/>`);
    const d = s1.fleet.ok && s1.fleet.ok.diversified;
    T(FX + 14, LOADY + 7, d ? `${nf(d.value, 4)} ${d.unit}` : 'REFUSED', 'y b');
    T(FX + 14, LOADY + 18, d ? d.meaning : 'fleetDemand refused', 'd');
    T(FX - 12, LOADY + 29, `${nf(S.units)} units · scenario input`, 'd', 'end');
    if (n >= 4 && loadRefused) T(FX - 12, LOADY + 7, `load wire ${w.load.state}`, 'rf', 'end');
  } else {
    p.push(`<path d="M${FX - 8} ${LOADY} L${FX + 8} ${LOADY} L${FX} ${LOADY + 13} Z" fill="none" stroke="#3a4258" stroke-dasharray="2 2"/>`);
    T(FX + 14, LOADY + 7, R.s1 && R.s1.empty ? 'load EMPTY' : 'stop 1 · load', R.s1 && R.s1.empty ? 'd' : 'ph');
  }
  T(180, 258, 'illustration, not a connection study', 'd', 'middle');
  $('sld').innerHTML = p.join('');
}

/* ── the stop cards: skeleton built once per stop, results re-filled ─────── */
const STOPS = [null,
  { title: 'DEMAND', lead: 'A scenario load, computed by the electrification model with its meaning kept: electricity drawn after diversity. The model refuses to read one meaning as another, and never adds two meanings together.' },
  { title: 'SITE POINT · NEAREST MAPPED NODE', lead: 'A site point and the proof\'s own fixture nodes. The nearest-search module scans every node and returns the nearest one at or above a voltage floor. Fixture nodes only: no real grid data is read.' },
  { title: 'ROUTE LENGTH', lead: 'The straight-line distance from the site to that node on the engine\'s sphere, and the cable corridor estimate the corridor module makes from it.' },
  { title: 'FEEDER PHYSICS', lead: 'The load from stop 1, carried over the route length from stop 3, at a voltage the node from stop 2 declares: apparent power, current, voltage drop and losses, each from its own module.' },
  { title: 'RATING LABELS', lead: 'Per-circuit rating labels at a busbar, from the rating-envelope module and its proof fixture. Each circuit keeps its own label. The module has no code that sums them, and a rating is not spare capacity.' }
];

const QUESTIONS = [null,
  [
    'It draws the <b>load</b> at the far end of the feeder. <code>fleetDemand({ units, perUnitNameplate, perUnitAfterDiversity }).diversified</code> supplies it: <code>value</code> in kW, <code>meaning</code> "after_diversity", <code>label</code>. That object crosses the wire to stop 4 as <code>kw</code>. <code>simultaneous</code> (nameplate, a stress test) is shown but not drawn on the feeder.',
    `Module <code>engine/electrification-model.js</code>, ventus-grid-engine commit ${PIN}; functions <code>quantity</code>, <code>electricalInputFromHeat</code>, <code>fleetDemand</code> and <code>combinedPeak</code> are called here. Callers at that commit, read from import lines: <code>proofs/electrification-model.proof.mjs</code> only; it is not in <code>package.json</code> exports. In this gal  … [line shortened here: 506 characters; full line on GitHub]
    'To the feeder: <code>power-factor.js apparentPowerKva({ kw, powerFactor })</code> at stop 4, through a wire that accepts only kW with meaning "after_diversity". Whether a network can carry it is not established: the module\'s own <code>NOT_COMPUTED.networkCapacity</code> says so.'
  ],
  [
    'It draws the <b>busbar at the network end</b>: the nearest mapped node. <code>index(points).nearest(lon, lat, { minimumKv })</code> returns <code>{ point, km }</code>; <code>point.name</code> labels the busbar, <code>point.voltages_kv</code> gives the voltages it declares (the voltage wire to stop 4), <code>point.location</code> is the far end of the route (the wire to stop 3).',
    `Module <code>engine/v9-nearest-search.js</code> at ${PIN}, exports <code>normalise</code>, <code>index</code>, <code>schema</code>; it imports <code>distanceKm</code> from <code>engine/v9-geodesy.js</code> (line 35). Callers at that commit, from import lines: <code>proofs/v9-engine.proof.mjs</code> (the fixture used here) and <code>proofs/compute-observer.proof.mjs</code>. Its own header reco  … [line shortened here: 544 characters; full line on GitHub]
    'To the <b>cable route</b> from the site to <code>point.location</code> (stop 3). A rating for that node is not established: the rating proof fixture has no site of that name, which stop 5 shows as a refused wire.'
  ],
  [
    'It draws the <b>cable route</b> length. <code>distanceKm(lon1, lat1, lon2, lat2)</code> gives the straight line on a sphere of <code>EARTH_RADIUS_KM</code>; <code>forCable(km)</code> returns <code>{ km, factor, straight_km, withheld }</code>, and <code>km</code> is the corridor length that crosses to stop 4. It draws no geometry of the route: a corridor estimate is a length, not a path.',
    `Modules at ${PIN}: <code>engine/v9-geodesy.js</code> <code>distanceKm</code> (imported by <code>v9-nearest-search.js</code> line 35 and <code>compute-observer.js</code> line 2); <code>engine/geo-core.js</code> <code>haversine</code>, <code>haversineUK</code> (imported by <code>geo-area.js</code> line 30); <code>engine/corridor-estimate.js</code> <code>forCable</code> (imported by <code>proofs  … [line shortened here: 729 characters; full line on GitHub]
    'To the feeder: <code>voltage-drop.js voltageDropVolts({ lengthM })</code> and <code>lossesWatts({ lengthM })</code> at stop 4, which take metres. The km does not cross directly; see the wire below.'
  ],
  [
    'It draws the <b>feeder annotations</b>: current on the line (<code>currentFromMvaAtKv().value</code>, A), voltage drop (<code>voltageDropVolts().value</code>, V, with <code>resistiveVolts</code> and <code>reactiveVolts</code>), drop as a percentage of nominal (<code>dropPercent().value</code>) and losses (<code>lossesWatts().value</code>, W). It draws no protection and no earthing: <code>volt  … [line shortened here: 464 characters; full line on GitHub]
    `Modules at ${PIN}: <code>engine/power-factor.js</code> (<code>apparentPowerKva</code>, <code>reactivePowerKvar</code>), <code>engine/current-from-power.js</code> (<code>currentFromMvaAtKv</code>), <code>engine/voltage-drop.js</code> (<code>voltageDropVolts</code>, <code>dropPercent</code>, <code>lossesWatts</code>). Callers at that commit, from import lines: their proofs; <code>proofs/current  … [line shortened here: 789 characters; full line on GitHub]
    'To the <b>rating labels</b> at a busbar (stop 5). current-from-power.js lines 131 to 133 say <code>currentFromMvaAtKv</code> is "the call a rating-envelope result feeds"; no code at this commit wires the two, and this page draws no comparison between a current and a rating.'
  ],
  [
    'It draws the <b>per-circuit rating labels</b> on circuits leaving a busbar. <code>at(index, key, { voltageKv })</code> supplies <code>circuits[].ratings_mva</code> (MVA per season), <code>circuits[].flags</code> (placeholders) and <code>circuits[].seasons_not_published</code>. No busbar total is drawn, because the module has none: <code>NEVER_SUMMED</code>.',
    `Module <code>engine/rating-envelope.js</code> at ${PIN}, function <code>at</code>; it requires a <code>engine/network-topology.js</code> <code>index(product).graph()</code>. Callers at that commit, from import lines: <code>proofs/rating-envelope.proof.mjs</code> (the fixture used here). iterations/29-rating-envelope records, from gridatlas source, a caller in the SLD sandbox cartridge <code>a  … [line shortened here: 502 characters; full line on GitHub]
    'Not established. The next elements a single-line diagram needs here, a transformer between two busbar voltages and the protection on each circuit, are not in any module used on this page. The fixture\'s transformer record is not read by <code>at()</code>, which reads circuits only.'
  ]
];

let built = 0;
function renderStop() {
  const n = S.stop, card = $('card');
  card.textContent = '';
  card.dataset.stop = n;
  const st = STOPS[n];
  card.append(el('div', 'tag', `STOP ${n} OF 5`), el('h2', null, st.title), el('p', 'dim small', st.lead));
  const inputs = el('div', 'inputs'); card.append(inputs);
  buildInputs(n, inputs);
  const bd = el('p', 'boundary', BOUNDARY);
  if (n === 2 || n === 3) bd.textContent = 'A distance is a distance: this reports the nearest mapped node to a point and how far away it is, never whether anything can be joined to it. ' + BOUNDARY;
  card.append(el('h3', null, 'Results, as the modules return them'), bd, el('p', 'dim small', PRIMARY_ONLY));
  const res = el('ol', 'results'); res.id = 'res'; card.append(res);
  card.append(el('h3', null, 'Wires into and out of this stop'));
  const wires = el('ol', 'wires'); wires.id = 'wires'; card.append(wires);
  const extra = el('div'); extra.id = 'extra'; card.append(extra);
  const det = el('details', 'questions'); det.id = 'questions';
  det.append(el('summary', null, 'Questions'));
  const dl = el('dl');
  const qs = ['1. How does this help draw a system or a single-line diagram?', '2. What is this code used for?', '3. Where does it lead next?'];
  QUESTIONS[n].forEach((a, i) => { const dd = el('dd'); dd.innerHTML = a; dl.append(el('dt', null, qs[i]), dd); });
  det.append(dl);
  try { if (matchMedia('(min-width: 900px)').matches) det.open = true; } catch (_) { /* stays collapsed */ }
  card.append(det);
  const mach = el('p', 'machine'); mach.id = 'machine'; card.append(mach);
  if (n === 5) card.append(el('p', 'final', FINAL));
  built = n;

  /* dots and nav */
  const dots = $('dots');
  if (!dots.childElementCount) for (let i = 1; i <= 5; i++) {
    const b = el('button', null, String(i)); b.type = 'button'; b.dataset.stop = i;
    b.setAttribute('aria-label', `stop ${i} · ${STOPS[i].title}`);
    b.addEventListener('click', () => go(i));
    dots.append(b);
  }
  for (const b of dots.children) {
    if (+b.dataset.stop === n) b.setAttribute('aria-current', 'step'); else b.removeAttribute('aria-current');
  }
  $('prev').disabled = n === 1; $('next').disabled = n === 5;
  $('where').textContent = `${n} / 5 · ${st.title.split(' ·')[0].toLowerCase()}`;
  for (let i = 1; i <= n; i++) for (const id of STOP_SRC[i]) hydrate(id);
  update();
}

function slider(box, { key, label, unit, min, max, step, log, fmt, note }) {
  const d = el('div', 'in');
  const r1 = el('div', 'row'); const lab = el('label', null, label); lab.htmlFor = 'in-' + key;
  r1.append(lab, el('span', 'tag', 'SCENARIO INPUT'));
  const r2 = el('div', 'row'); const out = el('output'); r2.append(el('span', 'dim small', note || ''), out);
  const inp = document.createElement('input'); inp.type = 'range'; inp.id = 'in-' + key;
  const toV = t => log ? Number((min * Math.pow(max / min, t / 1000)).toPrecision(2)) : t;
  const toT = v => log ? Math.round(1000 * Math.log(v / min) / Math.log(max / min)) : v;
  if (log) { inp.min = 0; inp.max = 1000; inp.step = 1; } else { inp.min = min; inp.max = max; inp.step = step; }
  inp.value = toT(S[key]);
  const show = () => { out.textContent = (fmt ? fmt(S[key]) : nf(S[key])) + (unit ? ' ' + unit : ''); };
  inp.addEventListener('input', () => { S[key] = log ? Math.round(toV(+inp.value)) : +inp.value; show(); update(); });
  show(); d.append(r1, r2, inp); box.append(d);
}
function seg(box, label, key, opts, after) {
  const d = el('div', 'in'); const r = el('div', 'row'); r.append(el('span', null, label), el('span', 'tag', 'SCENARIO INPUT'));
  const s = el('div', 'seg'); s.dataset.key = key;
  const paint = () => { for (const b of s.children) b.setAttribute('aria-pressed', String(String(S[key]) === b.dataset.v)); };
  for (const o of opts) {
    const b = el('button', null, o.label); b.type = 'button'; b.dataset.v = String(o.v);
    b.addEventListener('click', () => { S[key] = o.v; if (after) after(o); paint(); update(); });
    s.append(b);
  }
  paint(); d.append(r, s); box.append(d);
  return { paint, s };
}

let plane = null;
function buildInputs(n, box) {
  if (n === 1) {
    slider(box, { key: 'heat', label: 'heat delivered per home', unit: 'kW thermal', min: 1, max: 20, step: 0.25, note: 'meaning thermal_output' });
    slider(box, { key: 'scop', label: 'SCOP', unit: '', min: 0.5, max: 6, step: 0.05, note: 'the module carries none; 1 or less is refused' });
    slider(box, { key: 'div', label: 'after-diversity demand per home', unit: 'kW', min: 0.1, max: 8, step: 0.1, note: 'stated synthetic scenario assumption, not a measurement; the module chooses none' });
    slider(box, { key: 'units', label: 'homes with a heat pump', unit: 'units', min: 1, max: 100000, log: true, note: 'log scale' });
    seg(box, 'which quantity is put on the wire to the feeder', 'carry', [
      { v: 'after_diversity', label: 'after diversity' }, { v: 'nameplate', label: 'nameplate' }, { v: 'thermal_output', label: 'thermal output' }]);
    const b = el('button', 'act', 'try to add the nameplate total to the after-diversity total'); b.type = 'button'; b.id = 'tryAdd';
    b.addEventListener('click', () => { S.tryAdd = true; update(); });
    box.append(b);
  } else if (n === 2) {
    const cv = el('canvas', 'plane'); cv.id = 'plane';
    cv.setAttribute('role', 'img'); cv.setAttribute('aria-label', 'Plane with the proof\'s fixture nodes and the site point; tap to move the site');
    box.append(cv, el('p', 'dim small', 'Tap or drag on the plane to move the site point. Drawn in a flat local projection for display only; no distance is read off the drawing.'));
    const reset = el('button', 'act', 'site back to the proof\'s query point'); reset.type = 'button'; reset.id = 'resetSite';
    reset.addEventListener('click', () => { S.lon = QUERY[0]; S.lat = QUERY[1]; S.kvFollow = true; update(); });
    box.append(reset);
    seg(box, 'minimumKv passed to nearest()', 'minKv', [{ v: 100, label: '100 kV (the proof\'s)' }, { v: 0, label: '0 kV' }], () => { S.kvFollow = true; });
    plane = setupPlane(cv);
  } else if (n === 3) {
    box.append(el('p', 'dim small', 'No input of its own: the two ends are the site and the node from stop 2.'));
  } else if (n === 4) {
    const kvs = () => {
      const node = lastR && lastR.s2 && lastR.s2.best ? lastR.s2.best.point : null;
      return [...new Set([...(node ? node.voltages_kv : []), ...ATLAS.map(a => a.kv)])].sort((a, b) => b - a);
    };
    const kvBox = el('div'); kvBox.id = 'kvBox'; box.append(kvBox);
    kvBox.rebuild = () => {
      const list = kvs().join(',');
      if (kvBox.dataset.list === list) { kvBox.seg && kvBox.seg.paint(); return; }
      kvBox.dataset.list = list; kvBox.textContent = '';
      kvBox.seg = seg(kvBox, 'nominal voltage of the feeder (the node\'s declared voltages and the levels the Grid Atlas draws)', 'kv', kvs().map(kv => ({ v: kv, label: kv + ' kV' })), () => { S.kvFollow = false; });
    };
    slider(box, { key: 'pf', label: 'power factor', unit: '', min: 0.5, max: 1, step: 0.01, fmt: v => v.toFixed(2) });
    slider(box, { key: 'r', label: 'conductor resistance', unit: 'ohm/km', min: 0.01, max: 1, step: 0.01, note: 'the module carries no R or X' });
    slider(box, { key: 'x', label: 'conductor reactance', unit: 'ohm/km', min: 0, max: 0.5, step: 0.01 });
    seg(box, 'phases (three takes a line-to-line kV, single a line-to-neutral kV; the node declares line-to-line only, so single is refused on the joined wire)', 'phases', [{ v: 'three', label: 'three' }, { v: 'single', label: 'single' }]);
    seg(box, 'stated unit conversions on the wires (km→m, kVA→MVA, kV→V)', 'convert', [{ v: true, label: 'on' }, { v: false, label: 'off: see the refusals' }]);
  } else if (n === 5) {
    const siteBox = el('div'); siteBox.id = 'siteBox'; box.append(siteBox);
    const seasonBox = el('div'); seasonBox.id = 'seasonBox'; box.append(seasonBox);
  }
}

/* ── stop 2 plane ─────────────────────────────────────────────────────────── */
const GRID = { lonMin: -0.2, lonMax: 0.2, latMin: 54.9, latMax: 55.1 };
function setupPlane(cv) {
  const P = { cv, W: 0, H: 0, dpr: 1, scale: 1, cx: 0, cy: 0 };
  const kmPerDeg = () => (M('geo9') ? M('geo9').EARTH_RADIUS_KM : NaN) * Math.PI / 180;
  const cos0 = Math.cos(QUERY[1] * Math.PI / 180);
  P.px = (lon, lat) => [P.cx + (lon - QUERY[0]) * kmPerDeg() * cos0 * P.scale, P.cy - (lat - QUERY[1]) * kmPerDeg() * P.scale];
  P.unpx = (x, y) => [QUERY[0] + (x - P.cx) / (kmPerDeg() * cos0 * P.scale), QUERY[1] - (y - P.cy) / (kmPerDeg() * P.scale)];
  P.fit = () => {
    const r = cv.getBoundingClientRect(); P.dpr = Math.min(devicePixelRatio || 1, 3); P.W = r.width; P.H = r.height;
    cv.width = Math.round(P.W * P.dpr); cv.height = Math.round(P.H * P.dpr);
    const hw = (GRID.lonMax - GRID.lonMin) / 2 * kmPerDeg() * cos0 + 0.6, hh = (GRID.latMax - GRID.latMin) / 2 * kmPerDeg() + 0.6;
    P.scale = Math.min(P.W / (2 * hw), P.H / (2 * hh)); P.cx = P.W / 2; P.cy = P.H / 2;
  };
  let drag = false, raf = 0, pend = null;
  const move = e => {
    if (!M('geo9')) return;
    const r = cv.getBoundingClientRect();
    const [lon, lat] = P.unpx(e.clientX - r.left, e.clientY - r.top);
    pend = [Math.min(GRID.lonMax, Math.max(GRID.lonMin, +lon.toFixed(5))), Math.min(GRID.latMax, Math.max(GRID.latMin, +lat.toFixed(5)))];
    if (!raf) raf = requestAnimationFrame(() => { raf = 0; [S.lon, S.lat] = pend; S.kvFollow = true; update(); });
  };
  cv.addEventListener('pointerdown', e => { drag = true; try { cv.setPointerCapture(e.pointerId); } catch (_) { /* optional */ } move(e); e.preventDefault(); });
  cv.addEventListener('pointermove', e => { if (drag) { move(e); e.preventDefault(); } });
  cv.addEventListener('pointerup', () => { drag = false; });
  cv.addEventListener('pointercancel', () => { drag = false; });
  return P;
}
function drawPlane(R) {
  const P = plane; if (!P || !P.cv.isConnected) return;
  const g = P.cv.getContext('2d');
  if (!M('geo9')) { const r = P.cv.getBoundingClientRect(); P.cv.width = Math.round(r.width); P.cv.height = Math.round(r.height); g.fillStyle = '#8b93a7'; g.font = '12px ui-monospace,monospace'; g.fillText('WAIT — engine/v9-geodesy.js', 12, 24); return; }
  P.fit(); g.setTransform(P.dpr, 0, 0, P.dpr, 0, 0); g.clearRect(0, 0, P.W, P.H);
  const lab = (t, x, y, c, a = 'left') => { g.font = '11px ui-monospace,Menlo,Consolas,monospace'; g.textAlign = a; g.textBaseline = 'middle'; g.lineWidth = 3; g.strokeStyle = '#05060a'; g.strokeText(t, x, y); g.fillStyle = c; g.fillText(t, x, y); };
  const clip = (x, y) => { const m = 14; const cx = Math.max(m, Math.min(P.W - m, x)), cy = Math.max(m, Math.min(P.H - m, y)); return [cx, cy, cx !== x || cy !== y]; };
  g.strokeStyle = '#161b28'; g.lineWidth = 1;
  for (let k = -10; k <= 10; k++) { const [x] = P.px(k * 0.02, 55); g.beginPath(); g.moveTo(x, 0); g.lineTo(x, P.H); g.stroke(); const [, y] = P.px(0, 55 + k * 0.02); g.beginPath(); g.moveTo(0, y); g.lineTo(P.W, y); g.stroke(); }
  lab('graticule 0.02° · display projection', P.W - 8, P.H - 10, '#5c6580', 'right');
  const [sx, sy] = P.px(S.lon, S.lat);
  const best = R.s2 && R.s2.best;
  if (best) { const [x, y] = clip(...P.px(best.point.location.lon, best.point.location.lat)); g.strokeStyle = '#fff'; g.lineWidth = 2; g.beginPath(); g.moveTo(sx, sy); g.lineTo(x, y); g.stroke(); }
  for (const nd of NODES) {
    const [x, y, off] = clip(...P.px(nd.location.lon, nd.location.lat));
    const below = Math.max(...nd.voltages_kv) < S.minKv;
    g.beginPath(); g.arc(x, y, below ? 3.5 : 5, 0, 7);
    if (below) { g.strokeStyle = GREY; g.lineWidth = 1.5; g.stroke(); } else { g.fillStyle = '#fff'; g.fill(); }
    const hit = R.s2 && R.s2.list ? R.s2.list.find(h => h.point === nd) : null;
    const t = `${nd.name.replace(' Grid Substation', '').replace(' Substation', '')}${hit ? ' ' + nf(hit.km, 4) + ' km' : below ? ' · below floor' : ''}${off ? ' (off plane)' : ''}`;
    g.font = '11px ui-monospace,Menlo,Consolas,monospace';
    const tw = g.measureText(t).width;
    const ly = nd === LOW_VOLTAGE ? y - 16 : nd === TRUE_EAST ? y + 16 : y + (y < P.H / 2 ? 16 : -14);
    lab(t, Math.max(6, Math.min(P.W - 6 - tw, x - tw / 2)), Math.max(10, Math.min(P.H - 26, ly)), below ? GREY : '#fff');
  }
  g.strokeStyle = '#fff'; g.lineWidth = 1.5; g.beginPath();
  g.moveTo(sx - 14, sy); g.lineTo(sx - 6, sy); g.moveTo(sx + 6, sy); g.lineTo(sx + 14, sy); g.moveTo(sx, sy - 14); g.lineTo(sx, sy - 6); g.moveTo(sx, sy + 6); g.lineTo(sx, sy + 14); g.stroke();
  lab('site', sx - 10, sy + 20, '#fff', 'right');
}

/* ── re-fill the open card ────────────────────────────────────────────────── */
function fillList(ol, items) {
  /* one li per result row; rows are reused, only their text changes */
  while (ol.children.length > items.length) ol.lastChild.remove();
  items.forEach((it, i) => {
    let li = ol.children[i];
    if (!li) { li = el('li'); li.append(el('div', 'k'), el('div', 'fn'), el('div', 'basis')); li.firstChild.append(el('span'), el('span', 'v')); ol.append(li); }
    const [lab, v] = li.firstChild.children;
    if (lab.textContent !== it[0]) lab.textContent = it[0];
    if (v.textContent !== it[1]) v.textContent = it[1];
    if (li.children[1].textContent !== (it[2] || '')) li.children[1].textContent = it[2] || '';
    if (li.children[2].textContent !== (it[3] || '')) li.children[2].textContent = it[3] || '';
    li.classList.toggle('empty', !!it[4]);
  });
}
const rowOf = (label, r, fmt, fn, basisOf) => r.ok ? [label, fmt(r.ok), fn, basisOf ? basisOf(r.ok) : r.ok.basis || '']
  : r.err ? [label, 'REFUSED', fn, `the module refused: ${r.err}`, true] : [label, 'EMPTY', fn, r.empty || '', true];
function fillWires(ol, list) {
  ol.textContent = '';
  for (const w of list) {
    if (!w) continue;
    const li = el('li', 'wire ' + w.state.toLowerCase()); li.dataset.wire = w.id; li.dataset.state = w.state;
    li.append(el('div', 'ends', `${w.from}  →  ${w.to}`));
    if (w.q) li.append(el('div', 'q', `carries: ${w.q.show || (typeof w.q.value === 'number' ? nf(w.q.value, 6) : w.q.value)} ${w.q.show ? '' : w.q.unit} · meaning "${w.q.meaning}"${w.q.basis ? ` · basis ${w.q.basis}` : ''}`.replace(/\s+·/, ' ·')));
    if (w.accepts) li.append(el('div', 'q dim', `input takes: ${w.accepts.unit}${w.accepts.meanings ? ' · meaning ' + w.accepts.meanings.map(m => `"${m}"`).join(' or ') : ''}${w.accepts.basis ? ` · basis ${w.accepts.basis}` + (w.id === 'kv' ? ` (phases "${S.phases}")` : '') : ''}`));
    if (w.direct) li.append(el('div', 'why', w.direct));
    const st = el('div', 'why'); st.append(el('span', 'st', w.state), ' ', w.reason); li.append(st);
    ol.append(li);
  }
}

let lastR = null;
let upd = 0;
function update() {
  if (upd) return;
  upd = requestAnimationFrame(() => { upd = 0; paint(); });
}
function paint() {
  const R = chain(); lastR = R;
  drawSld(R);
  const n = S.stop;
  if (built !== n) return;
  const res = $('res'), wires = $('wires'), extra = $('extra'), mach = $('machine');
  const w = R.wires;
  if (n === 1) {
    const s = R.s1;
    if (s.empty) { fillList(res, [['electrification-model', 'EMPTY', '', s.empty, true]]); fillWires(wires, []); }
    else {
      fillList(res, [
        rowOf('thermal output per home', s.thermal, o => `${nf(o.value)} ${o.unit}`, "quantity(heat, 'kW', MEANING.THERMAL_OUTPUT)", o => `meaning ${o.meaning} · scenario input`),
        rowOf('electrical input per home', s.elec, o => `${nf(o.value, 5)} ${o.unit}`, 'electricalInputFromHeat({ thermal, scop })'),
        rowOf('fleet, flat out (nameplate)', s.fleet, o => `${nf(o.simultaneous.value, 5)} ${o.simultaneous.unit}`, 'fleetDemand(...).simultaneous', o => `meaning ${o.simultaneous.meaning} · label: ${o.simultaneous.label}`),
        rowOf('fleet, after diversity', s.fleet, o => o.diversified ? `${nf(o.diversified.value, 5)} ${o.diversified.unit}` : 'EMPTY', 'fleetDemand(...).diversified', o => `meaning ${o.diversified.meaning} · label: ${o.diversified.label} · ${o.basis}`),
        rowOf('never added', s.fleet, o => 'NEVER_ADDED', 'fleetDemand(...).never_added', o => o.never_added),
        ...(S.tryAdd ? [rowOf('nameplate total + after-diversity total', s.added, o => `${nf(o.value)} ${o.unit}`, 'combinedPeak({ fleets: [nameplate-only fleet, fleet] })')] : []),
        ...(S.carry === 'thermal_output' ? [rowOf('thermal output handed to fleetDemand as a nameplate', s.thermalFleet, o => `${nf(o.simultaneous.value)} kW`, 'fleetDemand({ units, perUnitNameplate: thermal })')] : []),
        ['not a forecast', 'NOT_A_FORECAST', 'electrification-model.js', s.em.NOT_A_FORECAST]
      ]);
      fillWires(wires, [w.load]);
      const lw = wires.querySelector('[data-wire=load]');
      if (lw && S.stop < 4) lw.append(el('div', 'why dim', 'The receiving calculation runs at stop 4; the check above is made now, from what stop 1 returns.'));
    }
    mach.textContent = `Machine detail · inputs: heat ${S.heat} kW (meaning thermal_output, scenario input), scop ${S.scop} (dimensionless, scenario input), perUnitAfterDiversity ${S.div} kW (meaning after_diversity, a stated synthetic scenario assumption, not a measurement), units ${S.units} (count, scenario input) · outputs: electricalInputFromHeat → value kW, meaning electrical_input; fleetDema  … [line shortened here: 1,001 characters; full line on GitHub]
  }
  if (n === 2) {
    const s = R.s2;
    if (s.empty) fillList(res, [['nearest mapped node', 'EMPTY', '', s.empty, true]]);
    else {
      const items = [[`fixture verified`, `lines ${s.chk.first}–${s.chk.last}`, SRC.pv9.path, `${V9_LINES.length} declaration lines of the proof's trap fixture found verbatim in the served proof. Fixture nodes, fictional, not real grid data.`]];
      items.push(['site point', `${nf(S.lon, 6)}°, ${nf(S.lat, 6)}°`, 'lon, lat (scenario input)', S.lon === QUERY[0] && S.lat === QUERY[1] ? 'the proof\'s own query point' : 'moved from the proof\'s query point']);
      items.push(s.best ? ['nearest mapped node', s.best.point.name, `index(nodes).nearest(${nf(S.lon, 6)}, ${nf(S.lat, 6)}, { minimumKv: ${S.minKv} })`, `${nf(s.best.km, 6)} km on a sphere of ${s.radius} km · declares ${s.best.point.voltages_kv.join(', ')} kV`]
        : ['nearest mapped node', 'EMPTY', `nearest(..., { minimumKv: ${S.minKv} })`, `the module returned null: no located node declares a voltage at or above ${S.minKv} kV`, true]);
      for (const nd of NODES) {
        const hit = s.list.find(h => h.point === nd);
        items.push([`  ${nd.name}`, hit ? `${nf(hit.km, 6)} km` : 'skipped', hit ? `rank ${s.list.indexOf(hit) + 1} of ${s.list.length}` : 'nearest() skips it', hit ? (hit === s.list[0] ? 'why chosen: the smallest km of every node the module scanned' : `why not chosen: ${nf(hit.km - s.list[0].km, 4)} km farther than the chosen node`) : `why not chosen: its highest declared voltage, ${Math.max(...n  … [line shortened here: 459 characters; full line on GitHub]
      }
      fillList(res, items);
    }
    fillWires(wires, [w.loc, w.kv, w.name]);
    mach.textContent = `Machine detail · inputs: points [{ name, voltages_kv [kV], location { lon °, lat ° } }] (the proof's fixture), lon ${S.lon}° and lat ${S.lat}° (decimal degrees, scenario input), minimumKv ${S.minKv} kV (floor on the highest declared voltage), limit (count) · outputs: { point, km } or null for limit 1, else an array sorted by km; km is haversine on EARTH_RADIUS_KM ${R.s2 &&   … [line shortened here: 1,087 characters; full line on GitHub]
    drawPlane(R);
  }
  if (n === 3) {
    const s = R.s3;
    if (s.empty) fillList(res, [['route length', 'EMPTY', '', s.empty, true]]);
    else {
      const c = s.corridor;
      fillList(res, [
        ['straight line, site to node', `${nf(s.straight, 8)} km`, `v9-geodesy distanceKm(${nf(S.lon, 6)}, ${nf(S.lat, 6)}, ${nf(R.s2.best.point.location.lon, 7)}, ${nf(R.s2.best.point.location.lat, 7)})`, `radius used: EARTH_RADIUS_KM = ${s.geo9.EARTH_RADIUS_KM} km (v9-geodesy.js), a sphere. ${s.agrees ? 'Identical to the km nearest() returned at stop 2.' : `Differs from the km nearest() returned  … [line shortened here: 441 characters; full line on GitHub]
        ['same line, geo-core default', `${nf(s.atlas, 8)} km`, 'geo-core haversine(lon1, lat1, lon2, lat2)', `radius R_ATLAS = ${s.gc.R_ATLAS} km; difference from distanceKm ${nf(s.atlas - s.straight, 3)} km`],
        ['same line, UK radius', `${nf(s.uk, 8)} km`, 'geo-core haversineUK(...)', `radius R_UK = ${s.gc.R_UK} km; ${nf((s.uk - s.straight) * 1000, 4)} m longer. Not used on the wire: the chain stays on the radius nearest() used.`],
        c == null ? ['cable corridor estimate', 'EMPTY', 'corridor-estimate forCable(km)', 'forCable returned null: no finite distance above zero', true]
          : c.km == null ? ['cable corridor estimate', 'WITHHELD', `forCable(${nf(c.straight_km, 6)})`, `the module withheld it: ${c.withheld}`, true]
            : ['cable corridor estimate', `${nf(c.km, 8)} km`, `forCable(${nf(c.straight_km, 8)})`, `factor ${c.factor} (CABLE_FACTOR). ${s.ce.CAVEAT}`],
        ['not for overhead line', 'NOT_FOR_OVERHEAD', 'corridor-estimate.js', s.ce.NOT_FOR_OVERHEAD],
        ['not an assessment', 'not_an_assessment', 'corridor-estimate.js', s.ce.not_an_assessment]
      ]);
    }
    fillWires(wires, [w.loc, w.len]);
    mach.textContent = `Machine detail · inputs: lon1, lat1 (site, degrees, scenario input), lon2, lat2 (node location from stop 2, degrees), in (lon, lat) order; forCable takes km (straight line) · outputs: distanceKm, haversine, haversineUK → km on a sphere of 6378.137, ${R.s3 && R.s3.gc ? R.s3.gc.R_ATLAS : 'R_ATLAS'} and ${R.s3 && R.s3.gc ? R.s3.gc.R_UK : 'R_UK'} km respectively; forCable → { k  … [line shortened here: 825 characters; full line on GitHub]
  }
  if (n === 4) {
    const kvBox = $('kvBox'); if (kvBox && kvBox.rebuild) kvBox.rebuild();
    const s = R.s4;
    if (s.empty) fillList(res, [['feeder physics', 'EMPTY', '', s.empty, true]]);
    else {
      fillList(res, [
        rowOf('apparent power S', s.S, o => `${nf(o.value, 5)} ${o.unit}`, 'power-factor apparentPowerKva({ kw, powerFactor })'),
        rowOf('reactive power Q', s.Q, o => `${nf(o.value, 5)} ${o.unit}`, 'power-factor reactivePowerKvar({ kw, powerFactor })'),
        rowOf('current', s.I, o => `${nf(o.value, 5)} ${o.unit}`, 'current-from-power currentFromMvaAtKv({ mva, kv, phases })', o => `${o.basis} ${o.not_computed}`),
        rowOf('voltage drop along the route', s.D, o => `${nf(o.value, 5)} ${o.unit}`, 'voltage-drop voltageDropVolts({ currentA, lengthM, R, X, powerFactor, phases })', o => `resistive ${nf(o.resistiveVolts, 4)} V, reactive ${nf(o.reactiveVolts, 4)} V. ${o.basis}`),
        rowOf('drop as a percentage of nominal', s.P, o => `${nf(o.value, 4)} ${o.unit}`, 'voltage-drop dropPercent({ dropVolts, nominalVolts })'),
        rowOf('losses', s.W, o => `${nf(o.value, 5)} ${o.unit}`, 'voltage-drop lossesWatts({ currentA, lengthM, R, phases })'),
        ['not a headroom', 'NOT_A_HEADROOM', 'current-from-power.js', s.cfp.NOT_A_HEADROOM],
        ['no cable is chosen', 'NOT_COMPUTED', 'voltage-drop.js', `${s.vd.NOT_COMPUTED.cableSelection} ${s.vd.NOT_COMPUTED.permittedDrop}`],
        ['no protection drawn', 'NOT_COMPUTED', 'voltage-drop.js faultWithstand', s.vd.NOT_COMPUTED.faultWithstand]
      ]);
    }
    fillWires(wires, [w.load, w.len, w.kv, w.mva, w.amps, w.nom]);
    mach.textContent = `Machine detail · inputs: kw (kW real power, from the stop 1 wire, meaning after_diversity), powerFactor ${S.pf} (in the interval (0, 1], scenario input), kv (kV, basis line-to-line, from the stop 2 wire), mva (MVA, from apparentPowerKva via kVA→MVA), phases "${S.phases}" (current-from-power.js takes a line-to-line voltage for "three" and a line-to-neutral voltage for "singl  … [line shortened here: 1,685 characters; full line on GitHub]
  }
  if (n === 5) {
    const s = R.s5;
    const siteBox = $('siteBox'), seasonBox = $('seasonBox');
    if (!s.empty && siteBox && !siteBox.childElementCount) {
      seg(siteBox, `stand-in site from the rating proof fixture (lines ${s.fx.firstLine}–${s.fx.lastLine})`, 'site', s.sites.map(c => ({ v: c, label: c })));
      seg(seasonBox, 'season shown on the labels', 'season', s.re.SEASONS.map(x => ({ v: x, label: x })));
    }
    if (s.empty) fillList(res, [['rating labels', 'EMPTY', '', s.empty, true]]);
    else if (!s.result) fillList(res, [['rating labels', 'EMPTY', `at(index, ${JSON.stringify(S.site)})`, 'at() returned null', true]]);
    else {
      const r = s.result;
      const items = [['call', `${r.circuits.length} circuit${r.circuits.length === 1 ? '' : 's'}`, `at(index, ${JSON.stringify(S.site)}${s.opts ? ', ' + JSON.stringify(s.opts) : ''})`, `scope: ${r.scope}. Fixture: ${SRC.pre.path} lines ${s.fx.firstLine}–${s.fx.lastLine}; test records written for the proof, not real network data.`]];
      if (!r.circuits.length) items.push(['labels', 'EMPTY', 'circuits: []', `no circuit lands on ${S.site}'s ${s.opts ? s.opts.voltageKv + ' kV ' : ''}nodes; every season reads ${JSON.stringify(r.by_season[S.season])}`, true]);
      for (const c of r.circuits) {
        const v = c.ratings_mva[S.season];
        const fl = c.flags.find(f => f.season === S.season);
        items.push([`label ${c.from_node} → ${c.to_node}`, v == null ? 'not published' : fl ? `${v} · flagged` : `${v} MVA`, `circuits[].ratings_mva.${S.season} · ${c.circuit_type || 'type not given'} · ${c.voltage_kv} kV`,
          fl ? `module flag: ${fl.reason}` : `all seasons as published: ${JSON.stringify(c.ratings_mva)}`, v == null || !!fl]);
      }
      items.push(['range, not a total', r.by_season[S.season].published === false ? 'published: false' : `${r.by_season[S.season].lowest_circuit_mva} to ${r.by_season[S.season].highest_circuit_mva} MVA`, `by_season.${S.season}`, `two real per-circuit values, lowest and highest; ${r.by_season[S.season].excluded_as_implausible} excluded as implausible. No headroom is drawn.`]);
      items.push(['never summed', 'NEVER_SUMMED', 'rating-envelope.js', s.re.NEVER_SUMMED]);
      items.push(['not a capacity', 'NOT_A_CAPACITY', 'rating-envelope.js', s.re.NOT_A_CAPACITY]);
      fillList(res, items);
    }
    fillWires(wires, [w.name, w.rkv, w.head]);
    mach.textContent = `Machine detail · inputs: index (network-topology index(product) of the proof fixture; graph().schema must be "${s.re ? s.re.requires : 'gridatlas.module.network-topology.graph.v1'}"), key (site code or exact site name: first the node name from stop 2, then the stand-in "${S.site}"), options.voltageKv (kV, from the stop 4 wire) · outputs: circuits[] with ratings_mva (MVA per  … [line shortened here: 1,012 characters; full line on GitHub]
  }
  publish(R);
}

function publish(R) {
  const w = {};
  for (const [k, v] of Object.entries(R.wires)) if (v) w[k] = v.state;
  window.__journey = {
    stop: S.stop, phases: S.phases, nan: S.nan, queuePeak: queue.peak,
    reasons: Object.fromEntries(Object.entries(R.wires).filter(([, v]) => v).map(([k, v]) => [k, v.reason])), status: Object.fromEntries(Object.entries(RT).map(([k, v]) => [k, v.status])), wires: w,
    s1: R.s1 && R.s1.fleet && R.s1.fleet.ok ? { diversifiedKw: R.s1.fleet.ok.diversified.value, meaning: R.s1.fleet.ok.diversified.meaning } : null,
    s2: R.s2 && R.s2.best ? { name: R.s2.best.point.name, km: R.s2.best.km } : null,
    s3: R.s3 && !R.s3.empty ? { straight: R.s3.straight, corridor: R.s3.corridor && R.s3.corridor.km } : null,
    s4: R.s4 && !R.s4.empty ? { I: R.s4.I.ok && R.s4.I.ok.value, D: R.s4.D.ok && R.s4.D.ok.value, P: R.s4.P.ok && R.s4.P.ok.value, W: R.s4.W.ok && R.s4.W.ok.value } : null,
    s5: R.s5 && R.s5.result ? { circuits: R.s5.result.circuits.length, byName: R.wires.name && R.wires.name.state } : null,
    dom: document.getElementsByTagName('*').length
  };
}

/* ── navigation: buttons, dots, keys, swipe ──────────────────────────────── */
function go(n) {
  n = Math.max(1, Math.min(5, n));
  if (n === S.stop && built === n) return;
  S.stop = n;
  try { history.replaceState(null, '', '#stop=' + n); } catch (_) { /* file or sandbox */ }
  renderStop();
  window.scrollTo({ top: 0 });
}
$('prev').addEventListener('click', () => go(S.stop - 1));
$('next').addEventListener('click', () => go(S.stop + 1));
addEventListener('keydown', e => {
  if (e.target && /INPUT|TEXTAREA/.test(e.target.tagName)) return;
  if (e.key === 'ArrowRight') go(S.stop + 1);
  if (e.key === 'ArrowLeft') go(S.stop - 1);
});
{
  let sw = null;
  const zone = $('card');
  const skip = t => t && t.closest && t.closest('input,canvas,button,summary,pre,.seg');
  const start = (x, y, t) => { sw = skip(t) ? null : { x, y }; };
  const end = (x, y) => {
    if (!sw) return;
    const dx = x - sw.x, dy = y - sw.y; sw = null;
    if (Math.abs(dx) > 60 && Math.abs(dx) > 1.6 * Math.abs(dy)) { window.__journeySwipes = (window.__journeySwipes || 0) + 1; go(S.stop + (dx < 0 ? 1 : -1)); }
  };
  for (const z of [zone, $('sldwrap')]) {
    z.addEventListener('pointerdown', e => start(e.clientX, e.clientY, e.target));
    z.addEventListener('pointerup', e => end(e.clientX, e.clientY));
    z.addEventListener('pointercancel', () => { sw = null; });
  }
}
addEventListener('resize', update);

$('pin').textContent = PIN;
buildRows();
renderStop();

Actions

A JavaScript module in the iterations folder of Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.

transformgalaxies-wafers / iterations/36-elements-assembly/actions.mjs · lines 1–97 of 97 · pattern press (shared by 6 files)

What it does
It calculates its inputs. Defines press, firstFn, reason, link, internal.
Downstream impact
Used directly by 1 file: Assembly (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/). Reached from 1 other entry point, including Iterations — 36 Elements Assembly Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/).
What it achieves
It is built from the press step (`press`), the first fn helper (`firstFn`) and the reason step (`reason`). The button row on every card: WAFER, RUN, APP, SPIDER, CODE, TOOLS.
Why it matters
Imported by Assembly.
Application
galaxies-wafers · iterations/36-elements-assembly · JavaScript module
Uses
none found
Used by
imported by Assembly (dynamic import)
Produces
ACTIONS_CONTRACT, NAMES, press
Defines here
press, firstFn, reason, link, internal
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/36-elements-assembly/actions.mjs:1-97 · blob f3223f50f5e404f557da050b5f53c31ff8a88360 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
/* actions.mjs — the button row on every card: WAFER, RUN, APP, SPIDER, CODE, TOOLS.
 *
 * Patterns copied from the estate:
 *   GRID button (pipelinenews grid-proximity cartridge): this module is imported
 *     only when a reader first presses a button ("dynamic-import-on-user-open"),
 *     it is additive only, and nothing it may need is fetched until the press
 *     that needs it. The page counts imports and fetches in a visible line.
 *   MAP button (pipelinenews atlasUrlV9_5_1): the hand-off is a deep link built
 *     from the record's permanent identity, opened by the reader as a link.
 *   No dead ends (cvaa vaccine dead-ends-explained): a button that cannot act for
 *     this card is still shown, and pressing it gives a one-line reason and
 *     where to go instead.
 */

export const ACTIONS_CONTRACT = Object.freeze({ generation: '36-assembly-actions-1', additive_only: true, activation: 'dynamic-import-on-user-open; fetch-on-press' });
export const NAMES = ['WAFER', 'RUN', 'APP', 'SPIDER', 'CODE', 'TOOLS'];

const INVENTORY_GRAPH = 'periodic-table';   /* the spider manifest's "Inventory" graph: node ids are block:<Sym> */

/* ctx: { I, D, engineFiles, FIXTURES, NOT_RECORDED, getJSON(url), SPIDER_MANIFEST, LAYERS_URL } */
export async function press(name, t, ctx) {
  const e = t.element, s = t.surface;
  const firstFn = el => el ? el.function_keys.map(k => ctx.I.fn && ctx.I.fn.get(k)).find(Boolean) : null;
  switch (name) {
    case 'WAFER': {
      if (t.type === 'surface') return reason(`${s.key} is a served folder: it holds no numbered lines of its own. Tap one of its elements, then WAFER.`);
      if (t.type === 'function') return internal({ level: 1, family: t.family }, `family:${t.family}'s lines, lit in sequence order on the dark wafer`, `?key=family:${t.family}&level=1`);
      if (!e.function_keys.length) return reason(`${e.key} lists no function key in the register, so no lines can be lit. Try APP or SPIDER.`);
      const fam = +String((firstFn(e) || { key: e.function_keys[0] }).key).split(':')[1];
      return internal({ level: 1, family: fam }, `the first catalogued function of ${e.key}, family:${fam}, on the dark wafer`, `?key=family:${fam}&level=1`);
    }
    case 'RUN': {
      const el = t.type === 'surface' ? null : e;
      if (!el) return reason(`${s.key} is a served folder; only an engine element can run. Tap an element with an engine module.`);
      const eng = ctx.engineFiles(el);
      if (!eng.length) return reason(`no runnable input recorded: ${el.key} records no ventus-grid-engine engine module at the pinned commit. Try CODE to read it instead.`);
      const fx = eng.find(x => ctx.FIXTURES[x.path]);
      if (!fx) return reason(`no runnable input recorded: ${eng.map(x => `${x.path}: ${ctx.NOT_RECORDED[x.path] || 'no fixture held'}`).join('; ')}. Try CODE.`);
      return internal({ level: 4, element: el.key, engineFile: fx.path, run: true }, `${ctx.FIXTURES[fx.path].fn}() from ${fx.path} running in a worker`, `?key=${el.key}&level=4`);
    }
    case 'APP': {
      let href = null, from = '';
      if (t.type === 'surface') { href = s.url; from = `the served folder ${s.key}`; }
      else {
        const el = e;
        if (!el) return reason(`family:${t.family} names a pack block that is not in the register, so no live address is recorded. Try CODE.`);
        const live = el.live || [];
        const page = live.find(u => /\.html?$|\/$/.test(u));
        href = page || (live[0] ? live[0].slice(0, live[0].lastIndexOf('/') + 1) : null);
        from = page ? `the live address the register records for ${el.key}` : href ? `the folder of ${el.key}'s first recorded live address (${live[0]})` : '';
        if (!href) return reason(`${el.key} records no live address in the register, so there is no surface to open. Try SPIDER to see where it sits.`);
      }
      return link(href, `opens ${from}`);
    }
    case 'SPIDER': {
      if (t.type === 'surface') return reason(`${s.key} is not a node of the spider's Inventory graph; its elements are. Tap one, then SPIDER.`);
      if (!e) return reason(`family:${t.family} names a pack block that is not in the register, so no spider node is known.`);
      const man = await ctx.getJSON(ctx.SPIDER_MANIFEST);
      const entry = (man.graphs || []).find(x => x.id === INVENTORY_GRAPH);
      if (!entry) return reason(`the spider manifest lists no ${INVENTORY_GRAPH} graph, so no node can be checked for ${e.key}.`);
      const g = await ctx.getJSON(new URL(entry.path, ctx.SPIDER_MANIFEST).href);
      const node = (g.nodes || []).find(n => n.id === e.key);
      if (!node) return reason(`${e.key} is not a node of the Inventory graph (${(g.nodes || []).length} nodes read); nothing to open at it. Try CODE.`);
      const file = (e.files || [])[0];
      const q = new URLSearchParams({ graph: INVENTORY_GRAPH, key: e.key });
      if (file) { q.set('repo', file.repo); q.set('path', file.path); }
      return link(`../32-spider-and-galaxy/?${q}`, `iteration 32 at the Inventory graph, where node ${e.key} "${node.label}" exists (read from the graph). It reads ?graph=; key, repo and path ride in the link.`);
    }
    case 'CODE': {
      let line = null, which = '';
      if (t.type === 'function') {
        if (!t.firstLine) return reason(`family:${t.family} is not in the catalogue (10 lines or fewer), so its first line is not known until WAFER reads the numbered database. Press WAFER.`);
        line = t.firstLine; which = `family:${t.family}`;
      }
      else if (t.type !== 'surface') {
        const ff = firstFn(e);
        if (ff) { line = +ff.first_line.split(':')[1]; which = ff.key; }
      }
      if (t.type === 'surface') return reason(`${s.key} is a folder address, not a line. Tap one of its elements, then CODE.`);
      if (!line) return reason(`${e.key} has no function in the catalogue (none over 10 lines), so no first line is known here. Try WAFER for its keys.`);
      return link(`../31-code-card-everywhere/?line=${line}`, `iteration 31's code card at line:${line}, the first entry of ${which}'s line sequence`);
    }
    case 'TOOLS': {
      if (t.type === 'surface') return reason(`${s.key} has no layer of its own; module layers are per element. Tap one, then TOOLS.`);
      if (!e) return reason(`family:${t.family} names a pack block that is not in the register, so no module layer is known.`);
      const m = await ctx.getJSON(ctx.LAYERS_URL);
      const id = `module-${e.symbol}`;
      const layer = (m.layers || []).find(l => l.id === id);
      if (!layer) return reason(`layers/manifest.json lists no ${id} layer (${(m.layers || []).length} layers read), so iteration 33 has nothing to draw for ${e.key}. Try SPIDER.`);
      return link(`../33-engines-as-tools/?layer=modules&tool=transmission&key=${encodeURIComponent(e.key)}`, `iteration 33's module routes layer, which includes ${id} (${layer.features} features, read from the manifest)`);
    }
  }
  return reason(`${name} is not a button this page knows.`);
}
const reason = text => ({ kind: 'reason', text });
const link = (href, text) => ({ kind: 'link', href, text });
const internal = (go, text, deep) => ({ kind: 'internal', go, text, deep });