GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / globalgrid2050 / kuiper-grid/i0089/cartridges

Kuiper Programs (part 130)

A JavaScript file in the cartridges folder of GlobalGrid2050 that draws interconnectors, london underground, grid 66kV and motorway services, and uses data from the faraday repository.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1400 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. Kuiper Programs render · globalgrid2050 / kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js lines 554–1253

Kuiper Programs

A JavaScript file in the cartridges folder of GlobalGrid2050 that draws interconnectors, london underground, grid 66kV and motorway services, and uses data from the faraday repository.

renderglobalgrid2050 / kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js · lines 554–1253 of 4690 (continued from section 1399) · Not reached from any entry point (candidate for review) · pattern drawLocalSystem (shared by 2 files)

What it does
It draws interconnectors, london underground, grid 66kV and motorway services. Defines 253 functions or classes, including reFire, closestPair, blackSky, nameInLines, makeBody. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: interconnectors, 750kV, 400kV, 275kV, 132kV, 110kV.
Inputs & outputs
In: data source: faraday data; JSON file interconnectors.config.json; GeoJSON file london_underground.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file motorway_services.geojson; GeoJSON file railways.geojson; JSON file current.json. Out: canvas drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 110kV, 66kV, 50kV, 33kV.
What it achieves
It makes body (`makeBody`), sets tag (`setTag`) and draws tube map (`drawTubeMap`). A cartridge of the Kuiper shell. Its code works with 33 kV, 11 kV and 275 kV. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0089/cartridges · script
Uses
Faraday — Index Page (estate URL), Wafer Development Environment — Proof S0004 Page (estate URL), ./fire.js
Used by
none found
Produces
reFire, closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet
Defines here
tierOf, tubeAttribution, tubeFit, tubeFind, tubeNearest, score, tubeNation, tubeRegionSet, rad, tubeCage, tubeCard, put, localFromGraph, localSystem, localWords, localCut, localTrim, drawLocalSystem, slot, leg, say, tubeLocal, fireLocal, fireGrid, tubeOffer, mergeMenu, makeAppButtons, isolateNow, isolate, raiseTile
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js:554-1253 · blob 56db141d495fee7c1255ae88d29ac3f7a5fb8724 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
    if (!byW.has(key)) byW.set(key, []); byW.get(key).push(i); }
  // HIGHEST CLASS LAST, so a 400 kV route is never buried under a 33 kV one it crosses.
  const order2 = Array.from(byW.keys()).sort((a, b) => Number(a.split(':')[0]) - Number(b.split(':')[0]));
  for (const key of order2) { const list = byW.get(key), [kvc, par] = key.split(':').map(Number);
    ctx.beginPath();
    for (const i of list) { const lk = src[i];
      const pts = TUBE.lattice && TUBE.morph > 0.5 ? tubeRoute(S(tubeAt(lk[0])), S(tubeAt(lk[1])))
                                                   : [S(tubeAt(lk[0])), S(tubeAt(lk[1]))];
      ctx.moveTo(pts[0][0], pts[0][1]); for (let j = 1; j < pts.length; j++) ctx.lineTo(pts[j][0], pts[j][1]); }
    ctx.lineWidth = (TUBE.lattice ? 3.2 : 1.3) * (0.8 + 0.35 * par);
    ctx.strokeStyle = tubeInk(kvc); ctx.globalAlpha = caged ? 1 : 0.85; ctx.stroke(); }
  ctx.globalAlpha = 1;
  // 3. THE STATIONS. Binned by voltage class and batched; below a zoom a station is a mark and not a
  //    ring, because 5,800 rings on a telephone is a grey cloud and says nothing.
  const rad = TUBE.lattice ? 5.2 : Math.max(1.1, Math.min(4.2, px * 0.010));
  const bins = new Map(); TUBE.hit = [];
  for (let i = 0; i < TUBE_DATA.stations.length; i++) {
    const inCage = !caged || caged.has(i);
    const p = S(tubeAt(i));
    if (p[0] < -30 || p[0] > innerWidth + 30 || p[1] < -30 || p[1] > innerHeight + 30) continue;
    if (caged && !inCage) { if (TUBE.lattice) continue; }
    if (caged && inCage && !passed(p)) continue;
    const kvc = TUBE_DATA.stations[i][3], key = (caged && !inCage) ? 'dark' : String(kvc);
    if (!bins.has(key)) bins.set(key, []); bins.get(key).push([p, i]);
    if (!caged || inCage) TUBE.hit.push([p[0], p[1], i]); }
  for (const [key, list] of bins) { const dark = key === 'dark';
    ctx.beginPath();
    for (const [p] of list) { ctx.moveTo(p[0] + rad, p[1]); ctx.arc(p[0], p[1], dark ? rad * 0.6 : rad, 0, 6.2832); }
    ctx.fillStyle = dark ? TUBE_DARK : tubeInk(Number(key)); ctx.fill();
    if (!dark && rad >= 3) { ctx.lineWidth = 1.2; ctx.strokeStyle = TUBE_GROUND; ctx.stroke(); } }
  // AN INTERCHANGE RING, only where classes actually meet and only when there is room for it to be a
  // ring rather than a smudge.
  if (rad >= 3) { ctx.beginPath(); let any = false;
    for (const [, list] of bins) for (const [p, i] of list) { if (!tubeInterchange(i)) continue;
      if (caged && !caged.has(i)) continue;
      ctx.moveTo(p[0] + rad * 1.9, p[1]); ctx.arc(p[0], p[1], rad * 1.9, 0, 6.2832); any = true; }
    if (any) { ctx.lineWidth = 1.6; ctx.strokeStyle = TUBE_LIT; ctx.stroke(); } }
  // 4. THE CAGE ITSELF, a fine outline round the lit set, and the ring while it is still travelling.
  if (TUBE.hull && TUBE.phase !== 'pulse') { const h = TUBE.hull.map(q => S(q));
    if (h.length > 2) { ctx.beginPath(); ctx.moveTo(h[0][0], h[0][1]);
      for (let i = 1; i < h.length; i++) ctx.lineTo(h[i][0], h[i][1]);
      ctx.closePath(); ctx.setLineDash([5, 5]); ctx.lineWidth = 1.2; ctx.strokeStyle = TUBE_CAGE;
      ctx.globalAlpha = 0.75; ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; } }
  if (TUBE.phase === 'pulse' && centre) { ctx.beginPath(); ctx.arc(centre[0], centre[1], Math.max(1, sweep), 0, 6.2832);
    ctx.lineWidth = 2.2; ctx.strokeStyle = TUBE_CAGE; ctx.globalAlpha = 0.55; ctx.stroke(); ctx.globalAlpha = 1; }
  // 5. THE NAMES. By tier as the camera comes in, never shrunk, never overlapped, and never under
  //    nine pixels: a name too small to read is worse than no name at all.
  const tiers = TUBE_DATA.labelTiers || {};
  // TRANSMISSION IS ALWAYS TIER ONE, by the Atlas's own test, so the first names a reader sees on
  // this map are the first names they would see on that one.
  const tierOf = i => tubeIsTransmission(TUBE_DATA.stations[i][3]) ? 1
    : (tiers[1] && tiers[1].indexOf(i) >= 0) ? 1 : (tiers[2] && tiers[2].indexOf(i) >= 0) ? 2 : 3;
  const region = TUBE.view === 'region';
  const showTier = TUBE.lattice ? 3 : px < 900 ? 1 : px < 2400 ? 2 : 3;
  const size = TUBE.lattice ? 12 : px < 1600 ? 10 : 11;
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.font = '600 ' + (size * dpr) + 'px ui-monospace,Menlo,Consolas,monospace';
  ctx.textBaseline = 'middle'; ctx.textAlign = 'left';
  const put = [];
  // HOW MANY NAMES A SCREEN CAN HOLD. Dropping what clashes is not enough on its own: five thousand
  // candidates fill every gap and the result is a page of words with a map hidden under it. An
  // underground map names every stop because it has forty of them. So the nation view is given a
  // BUDGET - about one name per two thousand square pixels - spent on the biggest junctions first,
  // and the rest of the names wait for the reader to come closer. Inside a cage every station is
  // named, because that is the whole point of having drawn the cage.
  // A REGION IS NAMED LIKE THE NATION, NOT LIKE A CAGE: hundreds of stations cannot all be named at
  // nine pixels without burying the map, so the region spends the same budget of names, highest
  // voltage class first, and the rest wait for the reader to come closer.
  const budget = (TUBE.lattice && !region) ? 1e9 : Math.max(8, Math.round(innerWidth * innerHeight / 2000));
  let spent = 0;
  const cand = [];
  for (const [, list] of bins) for (const [p, i] of list) {
    if (caged && !caged.has(i)) continue;
    if (tierOf(i) > showTier) continue;
    // A STATION WITH NO NAME HAS NOTHING TO SAY ON THE NATION VIEW. The word "unnamed" written five
    // hundred times is not information; it is the picture telling the reader about the data's gaps
    // instead of about the network. Inside a cage the mark is named, because there the reader has
    // asked about that station in particular and needs to know the data does not carry its name.
    if (!TUBE_DATA.stations[i][5] && (!TUBE.lattice || region)) continue;
    cand.push([p, i]); }
  cand.sort((a, b) => (region ? (Number(TUBE_DATA.stations[b[1]][3]) - Number(TUBE_DATA.stations[a[1]][3])) : 0)
    || (tierOf(a[1]) - tierOf(b[1])) || (tubeDegree(b[1]) - tubeDegree(a[1])));
  // A NAME NEVER SITS ON A MARK, not its own and not its neighbour's. Every mark on the screen is put
  // into the same collision list the names are tested against BEFORE any name is placed, so the only
  // places left for a word are places where there is no station under it.
  for (const [, list] of bins) for (const [p] of list) {
    const r2 = (rad + 2) * dpr;
    put.push([p[0] * dpr - r2, p[1] * dpr - r2, p[0] * dpr + r2, p[1] * dpr + r2]); }
  // THE ORDER THE SLOTS ARE TRIED IN IS THE DATA'S. The runner works out which side of a mark is
  // emptiest for this layout and writes it down as label_slot_order; the page obeys it instead of
  // always reaching to the right first.
  const SLOT_ORDER = (TUBE_DATA.defaults && TUBE_DATA.defaults.label_slot_order) || [0, 1, 2, 3];
  if (size >= TUBE_TEXT_FLOOR_PX) for (const [p, i] of cand) {
    if (spent >= budget) break;
    const text = TUBE_DATA.stations[i][5] || 'unnamed station';
    const w = ctx.measureText(text).width, h2 = (size + 4) * dpr;
    const all = [[rad + 6, 0], [-(rad + 6) - w / dpr, 0], [-w / dpr / 2, -(rad + 10)], [-w / dpr / 2, rad + 10]];
    const slots = SLOT_ORDER.map(k => all[k]).filter(Boolean);
    for (const [ox, oy] of (slots.length ? slots : all)) {
      const x0 = Math.round((p[0] + ox) * dpr), y0 = Math.round((p[1] + oy) * dpr) - h2 / 2;
      const pad = (TUBE.lattice ? 2 : 6) * dpr;
      const box = [x0 - pad, y0 - pad * 0.5, x0 + w + pad, y0 + h2 + pad * 0.5];
      if (box[1] < band.top * dpr || box[3] > band.bottom * dpr) continue;
      let clash = false; for (const q of put) if (box[0] < q[2] && box[2] > q[0] && box[1] < q[3] && box[3] > q[1]) { clash = true; break; }
      if (clash) continue;
      put.push(box); spent++; ctx.fillStyle = TUBE_LIT; ctx.fillText(text, x0, y0 + h2 / 2); break; } }
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  tubeAttribution(ctx, dpr, band);
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  TUBE.drawMs = TUBE.drawMs * 0.8 + (performance.now() - t) * 0.2;
}
// WHERE THE PICTURE CAME FROM, ALWAYS, AND INSIDE ITS OWN BAND. The attribution used to be written
// upward from a guessed line and landed on top of the page's own "provided as is"; now it is wrapped
// to the width, measured, given a band of its own with a floor under it, and that band is placed
// ABOVE everything the page has already claimed - the foot, the answer window. Two sentences that
// overlap are two sentences nobody can read, and provenance that cannot be read is not provenance.
function tubeAttribution(ctx, dpr, band){
  const small = Math.max(TUBE_TEXT_FLOOR_PX, 10), lh = small + 4;
  ctx.font = '500 ' + (small * dpr) + 'px ui-monospace,Menlo,Consolas,monospace';
  ctx.textBaseline = 'middle'; ctx.textAlign = 'left';
  const maxW = (innerWidth - 24) * dpr, lines = [];
  let cur = '';
  for (const w of String(TUBE_DATA.attribution || '').split(' ')) { const t2 = cur ? cur + ' ' + w : w;
    if (ctx.measureText(t2).width > maxW && cur) { lines.push(cur); cur = w; } else cur = t2; }
  if (cur) lines.push(cur);
  const h = lines.length * lh + 8;
  const y0 = Math.max(band.top, band.bottom - h);
  ctx.fillStyle = '#04060ae8'; ctx.fillRect(0, y0 * dpr, innerWidth * dpr, h * dpr);
  ctx.fillStyle = '#2a3444'; ctx.fillRect(0, y0 * dpr, innerWidth * dpr, Math.max(1, dpr));
  ctx.fillStyle = '#8aa0b6';
  lines.forEach((ln, k) => ctx.fillText(ln, Math.round(12 * dpr), Math.round((y0 + 4 + lh * k + lh / 2) * dpr)));
  return y0; }

// ---- firing it --------------------------------------------------------------------------------
function tubeFit(ids, laid){ if (!ids.length || typeof flyTo !== 'function') return;
  const R = Math.sqrt(SPACE) * BODY_RADIUS_MAX;
  let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;
  const f = TUBE.focus >= 0 ? TUBE_GEO[TUBE.focus] : [0, 0];
  for (const i of ids) { const l = laid && TUBE.lattice && TUBE.lattice.get(i);
    const p = l ? [l[0] + f[0], l[1] + f[1]] : tubeAt(i);
    x0 = Math.min(x0, p[0]); x1 = Math.max(x1, p[0]); y0 = Math.min(y0, p[1]); y1 = Math.max(y1, p[1]); }
  const w = Math.max(0.05, (x1 - x0) * R), h = Math.max(0.05, (y1 - y0) * R);
  // A NAME IS AS WIDE AS THE STATION IT NAMES IS SMALL, so the room left round a tube map is much
  // wider than round a scatter of marks: the widest name on this data is about 14 characters.
  const room = laid ? [2.30, 1.90] : [1.35, 1.55];
  const z = Math.min(innerWidth / (w * room[0]), innerHeight / (h * room[1]));
  flyTo((x0 + x1) / 2 * R, (y0 + y1) / 2 * R, z); }
function tubeFind(place){ const q = String(place || '').trim().toLowerCase(); if (!q) return -1;
  const S = TUBE_DATA.stations;
  for (let i = 0; i < S.length; i++) if (S[i][5] && S[i][5].toLowerCase() === q) return i;
  for (let i = 0; i < S.length; i++) if (S[i][0].toLowerCase() === q) return i;
  for (let i = 0; i < S.length; i++) if (S[i][5] && S[i][5].toLowerCase().indexOf(q) === 0) return i;
  for (let i = 0; i < S.length; i++) if (S[i][5] && S[i][5].toLowerCase().indexOf(q) >= 0) return i;
  return -1; }
// A PLACE THAT MATCHES NOTHING IS REFUSED IN WORDS, with five names to try instead. A picture that
// quietly shows the wrong station is worse than one that says it does not know.
function tubeNearest(place){ const q = String(place || '').trim().toLowerCase();
  const names = TUBE_DATA.stations.map(s => s[5]).filter(Boolean).sort();
  const score = n => { const a = n.toLowerCase(); let k = 0; for (let i = 0; i < Math.min(a.length, q.length); i++) { if (a[i] !== q[i]) break; k++; } return -k; };
  return names.slice().sort((a, b) => score(a) - score(b) || a.localeCompare(b)).slice(0, 5).sort();
}
function tubeNation(){ TUBE.on = true; TUBE.local = null; TUBE.hitLocal = [];
  TUBE.view = 'nation'; TUBE.focus = -1; TUBE.phase = 'nation';
  TUBE.lit = null; TUBE.litLinks = null; TUBE.hull = null; TUBE.lattice = null; TUBE.morph = 0;
  tubeLayer(); try { document.body.classList.add('tube-on'); } catch (_) {}
  tubeFit(TUBE_DATA.stations.map((_, i) => i));
  try { dirty = true; } catch (_) {} }
// A REGION IS MILES, NOT HOPS. The cage answers "what is two stops from here along the wires"; a
// council officer asks "what is in my district", which is a circle on the ground and includes the
// stations this data does not yet know how to join up. Both are real questions and they are not the
// same question, so the region view is its own selection and says so in its own words.
function tubeRegionSet(i, km){ const S = TUBE_DATA.stations, a = S[i];
  const set = new Map(), R = 6371;
  const rad = d => d * Math.PI / 180;
  for (let j = 0; j < S.length; j++) { const dLat = rad(S[j][2] - a[2]), dLon = rad(S[j][1] - a[1]);
    const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a[2])) * Math.cos(rad(S[j][2])) * Math.sin(dLon / 2) ** 2;
    if (2 * R * Math.asin(Math.min(1, Math.sqrt(h))) <= km) set.set(j, 1); }
  set.set(i, 0);
  const links = new Set();
  TUBE_DATA.links132.forEach((L, k) => { if (set.has(L[0]) && set.has(L[1])) links.add(k); });
  return { set, links }; }
function tubeCage(i, hops, kv, given){
  const r = given || tubeBFS(i, Math.max(1, Math.min(3, hops || 2)), kv || 0);
  TUBE.on = true; TUBE.local = null; TUBE.hitLocal = [];
  TUBE.view = (given && given.view) || 'station'; TUBE.focus = i; TUBE.hops = hops; TUBE.kv = kv || 0;
  TUBE.lit = r.set; TUBE.litLinks = r.links; TUBE.morph = 0;
  const ids = Array.from(r.set.keys());
  TUBE.lattice = tubeLattice(ids, i);
  const pre = TUBE_DATA.cages && TUBE_DATA.cages[i];
  TUBE.hull = null;
  TUBE.phase = 'pulse'; TUBE.t0 = performance.now();
  tubeLayer(); try { document.body.classList.add('tube-on'); } catch (_) {}
  // FIT THE LATTICE, NOT THE GEOGRAPHY: the picture the reader ends on is the tube map, so the room
  // made for it is the room the tube map needs, names and all.
  tubeFit(ids, true);
  // the outline is taken from the data when the runner has worked it out, else wrapped here
  setTimeout(() => { if (TUBE.focus !== i) return;
    const pts = ids.map(j => { const l = TUBE.lattice.get(j); return [l[0] + TUBE_GEO[i][0], l[1] + TUBE_GEO[i][1]]; });
    TUBE.hull = tubeSwell(pre && pre.hull ? pre.hull : tubeHullOf(pts), 0.07); }, 0);
  try { dirty = true; } catch (_) {}
  return ids.length; }
// ---- TWO CLICKS: the card ---------------------------------------------------------------------
// The engine's own card element and its own classes; every figure says where it came from, and the
// one sentence that keeps a reader honest is at the foot of it.
function tubeCard(i){
  if (typeof card === 'undefined' || !card) return;
  cardToken++; cardShown = null; card.replaceChildren(); card.style.display = 'block'; card.scrollTop = 0;
  card.classList.add('short');
  const x = el('button', 'cc-x', '×'); x.type = 'button'; x.setAttribute('aria-label', 'close');
  x.addEventListener('click', () => { card.style.display = 'none'; try { dirty = true; } catch (_) {} });
  card.append(x);
  const put = (s, cls) => card.append(el('div', cls || 'cc-plain', s));
  const S = TUBE_DATA.stations[i];
  put(S[5] || 'unnamed station', 'cc-title');
  const classes = new Set([S[3]]); for (const [b] of TUBE_ADJ[i]) classes.add(TUBE_DATA.stations[b][3]);
  const cls = Array.from(classes).map(v => tubeClassOf(v) === null ? v + ' kV (unclassified)' : tubeClassOf(v) + ' kV');
  put('voltage classes here: ' + cls.join(', ') + ' · from open data'
    + (tubeIsTransmission(S[3]) ? ' · transmission' : ''));
  const deg = tubeDegree(i);
  const bridge = TUBE_ADJ[i].some(([, li]) => TUBE_BRIDGES.has(li));
  put(deg === 0 ? 'no lines are mapped to this station · from open data'
    : deg === 1 ? 'SINGLE FED on this map: one link in and out. Losing it loses this station on this map. · from open data'
    : bridge ? 'On a BRIDGE link on this map: one of its links, if lost, cuts this map in two. · from open data'
             : deg + ' links, none of them a bridge on this map · from open data');
  // THE WAY INTO THE STATION'S OWN SYSTEM, from the card the reader already has open, because that is
  // where the question "and what does it actually feed?" is asked.
  { const go = el('div', 'cc-plain', 'open the local system →');
    go.style.cursor = 'pointer'; go.style.textDecoration = 'underline'; go.style.color = '#7ff0ff';
    go.addEventListener('click', () => { try { fireLocal({ station: S[0] }); card.style.display = 'none'; } catch (_) {} });
    card.append(go); }
  if (deg === 0) put('no lines are mapped to this station · from open data', 'cc-plain');
  else put('links from here · from open data', 'cc-plain');
  for (const [b, li] of TUBE_ADJ[i]) { const lk = TUBE_DATA.links132[li];
    const row = el('div', 'cc-plain', (TUBE_DATA.stations[b][5] || 'unnamed station') + '  · ' + lk[2] + ' km · '
      + (lk[3] > 1 ? lk[3] + ' circuits' : '1 circuit') + (TUBE_BRIDGES.has(li) ? ' · BRIDGE' : ''));
    row.style.cursor = 'pointer'; row.style.textDecoration = 'underline';
    row.setAttribute('data-tube-to', String(b));
    row.addEventListener('click', () => { tubeCage(b, TUBE.hops, TUBE.kv); tubeCard(b); });
    card.append(row); }
  const n1 = tubeBFS(i, 1, 0).set.size - 1, n2 = tubeBFS(i, 2, 0).set.size - 1, n3 = tubeBFS(i, 3, 0).set.size - 1;
  put('within 1 hop: ' + n1 + ' · within 2: ' + n2 + ' · within 3: ' + n3 + ' · from open data');
  put('Topology from open map data; says nothing about capacity or headroom.', 'cc-refuse');
  put(TUBE_NOT + ' Queue position, committed connections, thermal and fault headroom, consent and commercial terms decide that, and none of them is in this data.', 'cc-plain');
  put(TUBE_DATA.attribution);
  if (typeof layout === 'function') layout(); }

// ---- ONE CLICK on the picture -----------------------------------------------------------------
// The layer takes no pointer events at all; the window listens, exactly as the shapes layer does,
// so the shell's own tap on a dot is untouched when this picture is not up.
addEventListener('pointerdown', function (e) {
  if (!TUBE.on || !TUBE.hit.length) return;
  let best = -1, bd = 22;
  for (const [x, y, i] of TUBE.hit) { const d = Math.hypot(e.clientX - x, e.clientY - y); if (d < bd) { bd = d; best = i; } }
  if (best < 0) return;
  if (TUBE.view !== 'nation' && TUBE.lit && TUBE.lit.has(best)) tubeCard(best);     // two clicks: the card
  else tubeCage(best, TUBE.hops, TUBE.kv);                                          // one click: the cage
}, { passive: true });
// INSIDE A LOCAL SYSTEM every mark is a station, and tapping one asks the same question of it: show
// me THAT station's system. One gesture, one meaning, wherever the reader is standing.
addEventListener('pointerdown', function (e) {
  if (!TUBE.on || TUBE.view !== 'local' || !TUBE.hitLocal.length) return;
  let best = null, bd = 28;
  for (const [x, y, id] of TUBE.hitLocal) { const d = Math.hypot(e.clientX - x, e.clientY - y);
    if (d < bd) { bd = d; best = id; } }
  if (best) { try { fireLocal({ station: best }); } catch (_) {} }
}, { passive: true });
addEventListener('keydown', function (e) { if (e.key === 'Escape' && TUBE.on) tubeGone(); });

// ===== THE LOCAL SYSTEM =========================================================================
// WHAT THIS IS FOR. The nation view answers "where is it". This answers the only question a council
// officer actually has to answer: WHAT IS THIS STATION'S SYSTEM. It is the same tube map drawn at
// one station's scale - the supply comes in from the top, the station sits in the middle, and the
// loads hang below it - so a reader who has learnt the nation view has nothing new to learn here.
// IT REFUSES TO PRETEND. Anything the data guessed is DASHED, anything that runs off the edge of what
// we know is drawn as an open terminus, and a line in plain words says how much of the system is
// actually on the page. A picture that quietly closes its own gaps is worse than no picture.
/* LOCAL-DATA:START */
const LOCAL_DATA = {
 "attribution": "Contains open map data © OpenStreetMap contributors, available under the Open Database License (ODbL) v1.0. https://www.openstreetmap.org/copyright",
 "made": "2026-09-20T18:00:00Z",
 "note": "A HAND-MADE FIXTURE of three systems, here so the picture can be built and judged before the real runs land. Every id beginning fix- is invented. It is not a real network and no real station is described by it.",
 "systems": {
  "fix-hartmoor": {
   "station": { "id": "fix-hartmoor", "name": "Hartmoor (fixture)", "kv": [132, 33] },
   "gsp": { "id": "fix-westcombe", "name": "Westcombe grid supply point (fixture)" },
   "incomers": [
    { "corridor": "fix-c1", "kv": 132, "km": 12.4, "circuits": 2, "from": { "id": "fix-westcombe", "name": "Westcombe GSP (fixture)" }, "guessed": false },
    { "corridor": "fix-c2", "kv": 132, "km": 18.9, "circuits": 1, "from": { "id": "fix-northhay", "name": "North Hay (fixture)" }, "guessed": false }
   ],
   "outgoers": [
    { "corridor": "fix-o1", "kv": 33, "km": 4.1, "circuits": 2, "to": { "id": "fix-millbank", "name": "Millbank primary (fixture)" }, "ends": "station", "loads": [], "guessed": false },
    { "corridor": "fix-o2", "kv": 33, "km": 6.6, "circuits": 1, "to": { "id": "fix-corran", "name": "Corran spur end (fixture)" }, "ends": "station", "loads": [], "guessed": false },
    { "corridor": "fix-o3", "kv": 33, "km": 2.2, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l1", "kind": "works", "name": "Quarry works (fixture)" }], "guessed": false },
    { "corridor": "fix-o4", "kv": 33, "km": 9.8, "circuits": 1, "to": null, "ends": "edge-of-map", "loads": [], "guessed": false },
    { "corridor": "fix-o5", "kv": 33, "km": 5.0, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l2", "kind": "primary", "name": null }], "guessed": true }
   ],
   "ties": [
    { "corridor": "fix-t1", "kv": 132, "km": 7.3, "circuits": 1, "to": { "id": "fix-eastlea", "name": "Eastlea (fixture)" }, "ends": "station", "loads": [], "guessed": false }
   ],
   "completeness": { "score": 0.62, "missing": ["one outgoer runs off the edge of the map", "one join is guessed", "no circuit count on three corridors"] }
  },
  "fix-millbank": {
   "station": { "id": "fix-millbank", "name": "Millbank primary (fixture)", "kv": [33, 11] },
   "gsp": { "id": "fix-westcombe", "name": "Westcombe grid supply point (fixture)" },
   "incomers": [
    { "corridor": "fix-o1", "kv": 33, "km": 4.1, "circuits": 2, "from": { "id": "fix-hartmoor", "name": "Hartmoor (fixture)" }, "guessed": false }
   ],
   "outgoers": [
    { "corridor": "fix-m1", "kv": 11, "km": 1.8, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l3", "kind": "town", "name": "Millbank town (fixture)" }], "guessed": false },
    { "corridor": "fix-m2", "kv": 11, "km": 3.4, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l4", "kind": "industrial", "name": "Cold store (fixture)" }], "guessed": false },
    { "corridor": "fix-m3", "kv": 11, "km": 2.9, "circuits": 1, "to": null, "ends": "edge-of-map", "loads": [], "guessed": true }
   ],
   "ties": [
    { "corridor": "fix-m4", "kv": 33, "km": 5.5, "circuits": 1, "to": { "id": "fix-eastlea", "name": "Eastlea (fixture)" }, "ends": "station", "loads": [], "guessed": false },
    { "corridor": "fix-m5", "kv": 33, "km": 6.1, "circuits": 1, "to": { "id": "fix-corran", "name": "Corran spur end (fixture)" }, "ends": "station", "loads": [], "guessed": false }
   ],
   "completeness": { "score": 0.78, "missing": ["one outgoer runs off the edge of the map", "the ring is closed on a guess"] }
  },
  "fix-corran": {
   "station": { "id": "fix-corran", "name": "Corran spur end (fixture)", "kv": [33, 11] },
   "gsp": { "id": "fix-westcombe", "name": "Westcombe grid supply point (fixture)" },
   "incomers": [
    { "corridor": "fix-o2", "kv": 33, "km": 6.6, "circuits": 1, "from": { "id": "fix-hartmoor", "name": "Hartmoor (fixture)" }, "guessed": false }
   ],
   "outgoers": [
    { "corridor": "fix-r1", "kv": 11, "km": 2.4, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l5", "kind": "village", "name": "Corran village (fixture)" }], "guessed": false }
   ],
   "ties": [],
   "completeness": { "score": 0.9, "missing": ["nothing joins the far end: this is where the wires stop"] }
  }
 }
};
/* LOCAL-DATA:END */

const LOCAL_TERM = { station: '#eaf6ff', load: '#ffd27f', 'edge-of-map': '#7ff0ff' };
// EVERY STATION HAS A SYSTEM, even the ones nobody has written up yet. When the data carries a real
// one it is used; otherwise the picture is BUILT FROM THE GRAPH ITSELF - higher voltage in, lower
// voltage out, the same class to the side - and every line of it is marked guessed, because that is
// exactly what it is. A reader is never told "no data"; they are told what is known and how.
function localFromGraph(i){ const S = TUBE_DATA.stations, me = S[i];
  const here = me[3];
  const inc = [], out = [], ties = [];
  for (const [b, li] of TUBE_ADJ[i]) { const lk = TUBE_DATA.links132[li], o = S[b];
    const leg = { corridor: 'g' + li, kv: Math.max(here, o[3]), km: lk[2], circuits: lk[3] || 1,
      ends: 'station', loads: [], guessed: true };
    if (o[3] > here) inc.push(Object.assign({ from: { id: o[0], name: o[5] || 'unnamed station' } }, leg));
    else if (o[3] < here) out.push(Object.assign({ to: { id: o[0], name: o[5] || 'unnamed station' } }, leg));
    else ties.push(Object.assign({ to: { id: o[0], name: o[5] || 'unnamed station' } }, leg)); }
  // WITH NOTHING ABOVE IT, the first tie is read as the incomer: a station fed at its own class is
  // still fed from somewhere, and drawing no supply at all would say something untrue.
  if (!inc.length && ties.length) { const t2 = ties.shift();
    inc.push({ corridor: t2.corridor, kv: t2.kv, km: t2.km, circuits: t2.circuits,
      from: { id: t2.to.id, name: t2.to.name }, guessed: true }); }
  const missing = ['every join here is read off the map, not from a register'];
  if (!out.length) missing.push('no outgoers are known: the load side of this station is not in the data');
  if (!inc.length) missing.push('no supply is known: nothing higher than ' + here + ' kV reaches this station in the data');
  return { station: { id: me[0], name: me[5] || 'unnamed station', kv: [here] },
    gsp: null, incomers: inc, outgoers: out, ties,
    completeness: { score: 0.25, missing }, derived: true }; }
function localSystem(key){ const k = String(key || '').trim();
  const sys = LOCAL_DATA.systems || {};
  if (sys[k]) return sys[k];
  const lower = k.toLowerCase();
  for (const id in sys) if (sys[id].station && String(sys[id].station.name || '').toLowerCase() === lower) return sys[id];
  for (const id in sys) if (sys[id].station && String(sys[id].station.name || '').toLowerCase().indexOf(lower) === 0) return sys[id];
  const i = tubeFind(k);
  if (i >= 0) { const byId = sys[TUBE_DATA.stations[i][0]]; return byId || localFromGraph(i); }
  return null; }
// THE COMPLETENESS LINE, IN PLAIN WORDS AND COUNTED, NOT ASSERTED. The numbers are read off the very
// legs that were drawn, so the sentence can never drift away from the picture above it.
function localWords(sys){ const o = sys.outgoers || [], all = o.concat(sys.incomers || [], sys.ties || []);
  const edge = o.filter(L => L.ends === 'edge-of-map').length;
  const guessed = all.filter(L => L.guessed).length;
  const bits = [];
  if (o.length) bits.push(edge + ' of ' + o.length + ' outgoers end at the edge of the map');
  else bits.push('no outgoers are drawn');
  bits.push(guessed === 1 ? '1 join is guessed' : guessed + ' joins are guessed');
  const miss = (sys.completeness && sys.completeness.missing) || [];
  return bits.join('; ') + (miss.length ? '. ' + miss.join('; ') + '.' : '.'); }
// A LINE CUT AT THE FRONT. The pulse is the engine's own front travelling the corridor, so a length of
// the corridor is lit and the rest is not; this returns the lit length of an octilinear route.
function localCut(pts, f){ if (f >= 1) return pts.slice();
  if (f <= 0) return [];
  let total = 0; for (let i = 1; i < pts.length; i++) total += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
  let want = total * f, out = [pts[0]];
  for (let i = 1; i < pts.length; i++) { const d = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
    if (want >= d) { out.push(pts[i]); want -= d; continue; }
    const u = d > 1e-9 ? want / d : 0;
    out.push([pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * u, pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * u]);
    return out; }
  return out; }
function localTrim(ctx, s, maxW){ if (ctx.measureText(s).width <= maxW) return s;
  let t2 = s; while (t2.length > 3 && ctx.measureText(t2 + '…').width > maxW) t2 = t2.slice(0, -1);
  return t2 + '…'; }
function drawLocalSystem(ctx, dpr, band, t){
  const sys = TUBE.local; if (!sys) return;
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  const W = innerWidth * dpr, top = band.top * dpr, foot = tubeAttribution(ctx, dpr, band) * dpr;
  // THE COMPLETENESS LINE IS MEASURED BEFORE ANYTHING IS PLACED, and the room it needs is taken out
  // of the picture rather than written over the top of it. A sentence about what is missing, laid
  // across the names of the things that ARE there, loses both.
  const cfs = Math.max(TUBE_TEXT_FLOOR_PX * dpr, Math.max(TUBE_TEXT_FLOOR_PX, innerWidth < 520 ? 9.5 : 11) * dpr - dpr);
  ctx.font = '500 ' + cfs + 'px ui-monospace,Menlo,Consolas,monospace';
  const cLines = []; { let c2 = '';
    for (const w of localWords(sys).split(' ')) { const t3 = c2 ? c2 + ' ' + w : w;
      if (ctx.measureText(t3).width > W - 24 * dpr && c2) { cLines.push(c2); c2 = w; } else c2 = t3; }
    if (c2) cLines.push(c2); }
  while (cLines.length > 3) cLines.pop();
  const bot = foot - (18 + 14 * cLines.length) * dpr;
  const fs = Math.max(TUBE_TEXT_FLOOR_PX, innerWidth < 520 ? 9.5 : 11) * dpr;
  ctx.textBaseline = 'middle'; ctx.textAlign = 'center'; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
  const inc = sys.incomers || [], out = sys.outgoers || [], ties = sys.ties || [];
  const yIn = top + 44 * dpr, yMid = top + (bot - top) * 0.46, yOut = bot - 46 * dpr;
  const cx = W / 2;
  const slot = (n, k) => W * (k + 1) / (n + 1);
  // THE PULSE: one front, from the grid supply point at the top, through the station, out to the
  // loads. It is the engine's own front and it advances on the shell's frames, not a loop of ours.
  let u = 1;
  if (TUBE.phase === 'localpulse') { u = Math.min(1, (performance.now() - TUBE.t0) / 1900);
    if (u >= 1) TUBE.phase = 'local'; try { dirty = true; } catch (_) {} }
  const fIn = Math.max(0, Math.min(1, u / 0.38));
  const fSt = u >= 0.38 ? Math.min(1, (u - 0.38) / 0.10) : 0;
  const fOut = u >= 0.48 ? Math.min(1, (u - 0.48) / 0.46) : 0;
  TUBE.hitLocal = [];
  const stW = Math.min(W * 0.52, 240 * dpr), stH = 42 * dpr;
  const port = [cx, yMid];
  const leg = (pts, L, lit) => {
    const w = 2.2 * dpr * (0.8 + 0.35 * Math.min(4, L.circuits || 1));
    ctx.beginPath(); ctx.moveTo(pts[0][0], pts[0][1]);
    for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i][0], pts[i][1]);
    // ANYTHING GUESSED IS DASHED. A solid line on this picture is a claim; a dashed one is a question.
    ctx.setLineDash(L.guessed ? [6 * dpr, 5 * dpr] : []);
    ctx.lineWidth = w; ctx.strokeStyle = TUBE_DARK; ctx.globalAlpha = 1; ctx.stroke();
    const cut = localCut(pts, lit);
    if (cut.length > 1) { ctx.beginPath(); ctx.moveTo(cut[0][0], cut[0][1]);
      for (let i = 1; i < cut.length; i++) ctx.lineTo(cut[i][0], cut[i][1]);
      ctx.lineWidth = w; ctx.strokeStyle = tubeInk(L.kv); ctx.stroke(); }
    ctx.setLineDash([]); };
  const say = (s, x, y, col, maxW) => { ctx.font = '600 ' + fs + 'px ui-monospace,Menlo,Consolas,monospace';
    ctx.fillStyle = col || '#9fb3c8'; ctx.fillText(localTrim(ctx, s, maxW || W / 3.2), x, y); };
  // THE GRID SUPPLY POINT, named across the top, because every incomer on this page comes from that
  // side of the system and a reader must be told which side that is.
  ctx.font = '600 ' + fs + 'px ui-monospace,Menlo,Consolas,monospace';
  ctx.fillStyle = '#7f8899';
  ctx.fillText(sys.gsp ? ('from the grid supply point · ' + sys.gsp.name)
                       : 'from the higher voltage side', cx, top + 14 * dpr);
  // 1. THE INCOMERS, entering from the top.
  inc.forEach((L, k) => { const x = slot(inc.length, k), a = [x, yIn], b = [cx + (x > cx ? 1 : x < cx ? -1 : 0) * stW * 0.3, yMid - stH / 2];
    leg(tubeRoute(a, b), L, fIn);
    ctx.beginPath(); ctx.arc(x, yIn, 5.5 * dpr, 0, 6.2832);
    ctx.fillStyle = fIn > 0.02 ? tubeInk(L.kv) : TUBE_DARK; ctx.fill();
    ctx.lineWidth = 1.4 * dpr; ctx.strokeStyle = TUBE_GROUND; ctx.stroke();
    say((L.from && L.from.name) || 'unnamed station', x, yIn - 15 * dpr, '#eaf6ff', (W / (inc.length + 1)) - 14 * dpr);
    say(L.kv + ' kV · ' + (L.km != null ? L.km.toFixed(1) + ' km · ' : '')
      + ((L.circuits || 1) > 1 ? L.circuits + ' circuits' : '1 circuit'),
      x, yIn + 16 * dpr, '#7f8899', (W / (inc.length + 1)) - 14 * dpr);
    if (L.from && L.from.id) TUBE.hitLocal.push([x / dpr, yIn / dpr, L.from.id]); });
  // 2. THE TIES, to the side, because a tie is neither supply nor load: it is the other way round.
  ties.forEach((L, k) => { const right = k % 2 === 0;
    const x = right ? W - 26 * dpr : 26 * dpr, y = yMid + (Math.floor(k / 2) * 38 + 30) * dpr;
    leg(tubeRoute([x, y], [cx + (right ? stW / 2 : -stW / 2), yMid]), L, fSt);
    ctx.beginPath(); ctx.arc(x, y, 5 * dpr, 0, 6.2832); ctx.fillStyle = tubeInk(L.kv); ctx.fill();
    ctx.textAlign = right ? 'right' : 'left';
    say('tie · ' + ((L.to && L.to.name) || 'unnamed') + ' · ' + L.kv + ' kV',
      right ? x - 10 * dpr : x + 10 * dpr, y - 14 * dpr, '#9fb3c8', W * 0.42);
    ctx.textAlign = 'center';
    if (L.to && L.to.id) TUBE.hitLocal.push([x / dpr, y / dpr, L.to.id]); });
  // 3. THE OUTGOERS, leaving downward to their load points.
  out.forEach((L, k) => { const x = slot(out.length, k), b = [x, yOut];
    const a = [cx + (x > cx ? 1 : x < cx ? -1 : 0) * stW * 0.3, yMid + stH / 2];
    leg(tubeRoute(a, b), L, fOut);
    const kind = L.ends || 'station', col = LOCAL_TERM[kind] || '#eaf6ff';
    const on = fOut > 0.98;
    // THE TERMINUS SAYS WHAT KIND OF END IT IS: a filled mark is another station, a small square is a
    // load point, and an open mark with the wire running past it is the EDGE OF WHAT WE KNOW.
    if (kind === 'edge-of-map') { ctx.beginPath(); ctx.arc(x, yOut, 6 * dpr, 0, 6.2832);
      ctx.setLineDash([3 * dpr, 3 * dpr]); ctx.lineWidth = 1.6 * dpr; ctx.strokeStyle = col; ctx.stroke(); ctx.setLineDash([]); }
    else if (kind === 'load') { ctx.fillStyle = on ? col : TUBE_DARK;
      ctx.fillRect(x - 5 * dpr, yOut - 5 * dpr, 10 * dpr, 10 * dpr);
      ctx.lineWidth = 1.3 * dpr; ctx.strokeStyle = col; ctx.strokeRect(x - 5 * dpr, yOut - 5 * dpr, 10 * dpr, 10 * dpr); }
    else { ctx.beginPath(); ctx.arc(x, yOut, 6 * dpr, 0, 6.2832); ctx.fillStyle = on ? col : TUBE_DARK; ctx.fill();
      ctx.lineWidth = 1.4 * dpr; ctx.strokeStyle = col; ctx.stroke(); }
    const wide = (W / (out.length + 1)) - 10 * dpr;
    const nm = kind === 'edge-of-map' ? 'edge of the map'
      : (L.to && L.to.name) || (L.loads && L.loads[0] && (L.loads[0].name || L.loads[0].kind)) || 'load point';
    say(nm, x, yOut + 17 * dpr, col, wide);
    say(L.kv + ' kV · ' + (L.km != null ? L.km.toFixed(1) + ' km' : 'length unknown')
      + (L.guessed ? ' · guessed' : ''), x, yOut + 30 * dpr, '#7f8899', wide);
    if (L.to && L.to.id) TUBE.hitLocal.push([x / dpr, yOut / dpr, L.to.id]); });
  // 4. THE STATION ITSELF, in the middle, where the reader's eye starts.
  ctx.beginPath();
  const r2 = 8 * dpr, x0 = cx - stW / 2, y0 = yMid - stH / 2;
  ctx.moveTo(x0 + r2, y0); ctx.lineTo(x0 + stW - r2, y0); ctx.quadraticCurveTo(x0 + stW, y0, x0 + stW, y0 + r2);
  ctx.lineTo(x0 + stW, y0 + stH - r2); ctx.quadraticCurveTo(x0 + stW, y0 + stH, x0 + stW - r2, y0 + stH);
  ctx.lineTo(x0 + r2, y0 + stH); ctx.quadraticCurveTo(x0, y0 + stH, x0, y0 + stH - r2);
  ctx.lineTo(x0, y0 + r2); ctx.quadraticCurveTo(x0, y0, x0 + r2, y0); ctx.closePath();
  ctx.fillStyle = fSt > 0.5 ? '#0d1a26' : '#0a1018'; ctx.fill();
  ctx.lineWidth = 2 * dpr; ctx.strokeStyle = fSt > 0.5 ? TUBE_CAGE : '#2a3444'; ctx.stroke();
  const kvs = (sys.station.kv || []).filter(v => v != null);
  say(sys.station.name || 'unnamed station', cx, yMid - 7 * dpr, '#eaf6ff', stW - 16 * dpr);
  say(kvs.length ? kvs.join('/') + ' kV' : 'voltage not in the data', cx, yMid + 9 * dpr, '#9fb3c8', stW - 16 * dpr);
  TUBE.hitLocal.push([cx / dpr, yMid / dpr, sys.station.id]);
  // 5. HOW MUCH OF THE SYSTEM IS ACTUALLY ON THIS PAGE, in plain words, above the provenance.
  ctx.font = '500 ' + cfs + 'px ui-monospace,Menlo,Consolas,monospace';
  ctx.fillStyle = '#ffb454'; ctx.textAlign = 'left';
  cLines.forEach((ln, k) => ctx.fillText(ln, 12 * dpr, foot - (cLines.length - k) * 14 * dpr - 2 * dpr));
  ctx.textAlign = 'center'; }
function tubeLocal(sys){ TUBE.on = true; TUBE.view = 'local'; TUBE.local = sys; TUBE.lattice = null;
  TUBE.lit = null; TUBE.litLinks = null; TUBE.hull = null; TUBE.hit = [];
  TUBE.phase = 'localpulse'; TUBE.t0 = performance.now();
  tubeLayer(); try { document.body.classList.add('tube-on'); } catch (_) {}
  try { dirty = true; } catch (_) {} }
function fireLocal(i){ i = i || {};
  const key = i.station === undefined ? '' : String(i.station);
  if (!key.trim()) throw new Error('name a station: fire local {station:"Hartmoor (fixture)"}. '
    + 'Written-up systems here: ' + Object.keys(LOCAL_DATA.systems).join(', '));
  if (typeof endIsolate === 'function') { try { endIsolate(); } catch (_) {} }
  const sys = localSystem(key);
  if (!sys) throw new Error('no station of that name is in this data. Nearest names to try: '
    + tubeNearest(key).join(', '));
  tubeLocal(sys);
  const o = sys.outgoers || [];
  return { numbers: { incomers: (sys.incomers || []).length, outgoers: o.length, ties: (sys.ties || []).length,
      ends_at_the_edge_of_the_map: o.filter(L => L.ends === 'edge-of-map').length },
    said: sys.station.name + ': ' + localWords(sys),
    how: sys.derived
      ? 'built here from the open map graph - higher voltage in, lower voltage out, same class to the side - so every join is drawn dashed and marked guessed'
      : 'from the local system data; ' + LOCAL_DATA.attribution }; }
const LOCAL_INPUTS = [{ key: 'station', label: 'station', kind: 'text' }];
// ===== THE LOCAL SYSTEM: END ====================================================================

// ---- the typed command ------------------------------------------------------------------------
const TUBE_INPUTS = [
  { key: 'view', label: 'view', kind: 'choice', choices: [['nation', 'the whole network'], ['region', 'a region'], ['station', 'one station and its cage']] },
  { key: 'place', label: 'place', kind: 'text' },
  { key: 'hops', label: 'hops along the network', unit: 'stops', kind: 'number', min: 1, max: 3, step: 1 },
  { key: 'km', label: 'how far a region reaches', unit: 'km', kind: 'number', min: 5, max: 120, step: 5 },
  { key: 'kv', label: 'voltage class', kind: 'choice', choices: [[0, 'all']].concat(TUBE_CLASSES_KV.map(v => [v, v + ' kV'])) }
];
function fireGrid(i){ i = i || {};
  const hops = Math.max(1, Math.min(3, i.hops === undefined ? 2 : Number(i.hops) || 2));
  const kv = i.kv === undefined || Number(i.kv) === 0 ? 0 : tubeClassOf(Number(i.kv));
  if (i.kv !== undefined && Number(i.kv) !== 0 && kv === null)
    throw new Error('that is not one of the voltage classes this grid is drawn in: ' + TUBE_CLASSES_KV.join(', ') + ' kV');
  if (typeof endIsolate === 'function') { try { endIsolate(); } catch (_) {} }
  const view = i.view === 'region' ? 'region' : (i.place ? 'station' : (i.view || 'nation'));
  // A REGION IS ASKED FOR IN MILES AND IS ANSWERED IN MILES. Asked for without a place it used to fall
  // silently back to the nation, which is a different answer wearing the name of the one requested.
  if (view === 'region') {
    const at = tubeFind(i.place);
    if (at < 0) throw new Error('a region is a circle drawn round a place, so it needs one: '
      + 'fire grid {view:"region", place:"..."}. ' + (i.place
        ? 'No station of that name is in this data. Nearest names to try: ' + tubeNearest(i.place).join(', ')
        : 'No place was given.'));
    const km = Math.max(5, Math.min(120, Number(i.km) || 45));
    const r = tubeRegionSet(at, km); r.view = 'region';
    TUBE.hops = hops; TUBE.kv = kv;
    tubeCage(at, hops, kv, r);
    return { numbers: { stations_in_the_region: r.set.size, radius_km: km, links: r.links.size },
      said: 'the region within ' + km + ' km of ' + tubeName(at) + ': ' + r.set.size
        + ' stations, laid out as a tube map',
      how: 'a circle measured on the ground, not hops along the network; stations from open map data' }; }
  if (view === 'station' || i.place) {
    const at = tubeFind(i.place);
    if (at < 0) throw new Error('no station of that name is in this data. Nearest names to try: '
      + tubeNearest(i.place).join(', '));
    TUBE.hops = hops; TUBE.kv = kv;
    const n = tubeCage(at, hops, kv);
    return { numbers: { stations_in_the_cage: n, hops, links: TUBE.litLinks.size },
      said: 'the cage is around ' + tubeName(at) + ': ' + n + ' stations within ' + hops + ' hops, laid out as a tube map',
      how: 'hops counted along the network from open map data; the outline is the convex hull of the caged set' }; }
  tubeNation(); TUBE.hops = hops; TUBE.kv = kv;
  return { numbers: { stations: TUBE_DATA.stations.length, links: TUBE_DATA.links132.length },
    said: 'the whole network: tap a station, or type a place, to throw the cage around it',
    how: 'stations and links from open map data, ' + TUBE_DATA.attribution }; }
if (typeof window !== 'undefined') {
  window.KUIPER_TUBE = { data: TUBE_DATA, state: TUBE, fire: fireGrid, cage: tubeCage, card: tubeCard,
                         nation: tubeNation, find: tubeFind, bridges: TUBE_BRIDGES, drawMs: () => TUBE.drawMs,
                         local: LOCAL_DATA, fireLocal, system: localSystem, words: localWords };
  // THE REGISTRY IS DEFINED FURTHER DOWN THIS SAME FILE. At this line window.FIRE does not exist yet,
  // so a plain register() was thrown away in silence and a typed `fire grid` answered "no command
  // called grid", while the picture itself worked perfectly when driven from the console. The commands
  // are OFFERED AGAIN, on a short beat, until the registry is there to take them.
  const tubeOffer = () => { try { if (window.FIRE && window.FIRE.register) {
      window.FIRE.register('grid', 'THE GRID', fireGrid, TUBE_INPUTS);
      window.FIRE.register('local', 'THE LOCAL SYSTEM', fireLocal, LOCAL_INPUTS);
      return true; } } catch (_) {} return false; };
  if (!tubeOffer()) { let n = 0; const iv = setInterval(() => { if (tubeOffer() || ++n > 400) clearInterval(iv); }, 20); }
  // THE SHELL'S OWN FRAME, not a loop of this file's: the same hook the shapes layer uses.
  try { if (window.__wafer && window.__wafer.onDraw) window.__wafer.onDraw.add(function(){ try { drawTubeMap(); } catch (_) {} }); } catch (_) {}
}
// ===== GRID TUBE MAP: END =======================================================================

function mergeMenu(){
  for (const m of MENU) {
    if (m.override) { const a = apps.find(x => x.app === m.app.app), p = programs.find(x => x.name === m.program.name);
      if (a) Object.assign(a, m.app); if (p && m.program.end) p.end = m.program.end;
      if (a && m.program.says) whatItDoes[a.live] = m.program.says.replace(/\.$/, ''); continue; }
    if (!apps.find(x => x.app === m.app.app)) apps.push(m.app);
    if (!programs.find(x => x.name === m.program.name)) programs.push(m.program);
    if (m.program.says && !whatItDoes[m.app.live]) whatItDoes[m.app.live] = m.program.says.replace(/\.$/, '');
    if (!(appWork[m.app.app] || []).length) { const ri = repos.findIndex(r => r.name === m.program.select.repository);
      appWork[m.app.app] = ri < 0 ? [] : commits.filter(c => c.repo === ri).map(c => c.sha); }
  }
}
function makeAppButtons(){
  mergeMenu();
  const bar = document.getElementById('apps'); bar.replaceChildren();
  for (const pr of programs) { const ap = apps.find(x => x.app === pr.select.app);
    if (!ap || !(appWork[ap.app] || []).length) continue;        // nothing of it on this record: no button
    const b = el('button', null, pr.button); b.type = 'button'; b.setAttribute('data-app', pr.name);
    b.addEventListener('click', e => { e.stopPropagation(); tubeQuiet = false; isolate(pr.name); }); bar.append(b); }
  if (typeof layout === 'function') layout();
  makeFireBar();
}
// THE STATE ITSELF, with no animation, so it can be arrived at by a link and asked for by a test.
function isolateNow(name, front){
  const asData = programs.find(x => x.name === name); if (!asData) return null;
  const prog = Object.assign({}, asData, { on:Object.assign({}, asData.on, { colour:FARADAY }) });
  const ap = apps.find(x => x.app === prog.select.app); if (!ap) return null;
  name = ap.app;
  const idx = []; for (const sha of (appWork[name] || [])) { const i = bySha.get(sha); if (i !== undefined) idx.push(i); }
  idx.sort((x, y) => x - y);
  litRepo = -1; litK = [-1,-1]; litCi = null; newFrom = -1; flash = 0; litPath = null; target = null; arrow = null;
  iso = { app:ap, prog, front:front === undefined ? 1e30 : front, idx, set:new Set(idx), lit:idx.length, dark:commits.length - idx.length,
          first:idx.length ? commits[idx[0]].unix : 0, last:idx.length ? commits[idx[idx.length - 1]].unix : 0 };
  raiseFlags(idx);
  { // A FEW SPARKS FOR EVERY PIECE OF WORK, spread through its own lines so a big piece of work is a
    // scatter around its ring and a small one a point or two. Never more than the program allows.
    const per = Math.max(1, Math.min(24, (prog.on.sparks | 0) || 8)), pts = [];
    for (const i of idx) { const c0 = commits[i], len = Math.max(1, c0.k1 - c0.k0), take = Math.min(per, len);
      for (let j = 0; j < take; j++) { const p = keyPlace(c0.k0 + Math.floor((j + 0.5) * len / take)); pts.push(p[0], p[1]); } }
    ensureGlow();
    iso.from = new Float32Array(pts); iso.pos = iso.from; iso.to = null;
    glowCount = pts.length / 2; iso.sparks = glowCount; sparksTo(iso.from); }
  body = makeBody(iso);
  // arrived at by a link, or asked for outright: the END of the program, with no waiting
  if (front === undefined && body) bodyJump(body.states.length - 1);
  for (const b of document.querySelectorAll('#apps button')) b.classList.toggle('on', b.getAttribute('data-app') === prog.name);
  if (front === undefined) raiseTile();
  dirty = true;
  return iso;
}
// PRESS: the pulse runs out through the record, which on this picture is forward through time, and
// where it has passed the rest goes dark. The pulse is the page's own; nothing new is animated.
function isolate(name){
  const prog = programs.find(x => x.name === name); if (!prog) return;
  closeCard(); { const fc = document.getElementById('firecard'); if (fc && name !== 'fire') fc.style.display = 'none'; }   // the answer of a fired command leaves with it
  unisolate(true); anim = null; flash = 0; newFrom = -1; target = null; arrow = null;
  { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; tween = null; atHome = true; }
  // the selection is made at once and the FRONT starts at the origin with nothing switched; each dot
  // switches when the front reaches it, so the darkening is seen to travel
  if (!isolateNow(name, 0)) return;
  bodyAnim = null; if (body) body.shown = false;
  isoAnim = { name, t0:performance.now(), R:Math.sqrt(SPACE), ms:Math.max(200, (prog.pulse.seconds || 1.5) * 1000) }; dirty = true;
}
// A GRID VIEW IS NOT ASKING FOR THE WELCOME CARD. When a fired grid command runs the record's own
// pulse behind the tube map, the card that pulse would raise is one nobody asked for, and on a phone
// it sits over the bottom third of the map. One shot, set where that pulse is started, and cleared by
// the reader's own press, so pressing a program still opens its card exactly as before.
let tubeQuiet = false;
function raiseTile(){ if (tubeQuiet) { tubeQuiet = false; closeCard(); return; }
  if (!iso || !(iso.prog.end && iso.prog.end.tile)) return;
  // A SYSTEM ENDS ON THE SAME CARD with its own plain words under it; everything else is unchanged.
  if (iso.prog.end.tile === 'system' && systemShown) { systemCard(iso, systemShown);
    if (atHome) { const h = homeCamera(); flyTo(h.x, h.y, h.z); } dirty = true; return; }
  appCard(iso); if (atHome) { const h = homeCamera(); flyTo(h.x, h.y, h.z); } dirty = true; }
// ANY OTHER ACTION FIRST ENDS THE ISOLATE. Called by everything that shows something else, before it
// does anything, so the darkening can never outlive the thing it was for.
function endIsolate(){ if (iso || isoAnim || bodyAnim) { unisolate(true); closeCard(); } }
function unisolate(quiet){ labels(true); sldNow = null; sldNames = null; { const el = document.getElementById('sldnames'); if (el) el.replaceChildren(); }
  if (typeof shapesGone === 'function') shapesGone();
  if (sldLoop) { cancelAnimationFrame(sldLoop); sldLoop = 0; } iso = null; isoAnim = null; gatherAnim = null; homeAnim = null; body = null; bodyAnim = null; pulse = -1;
  for (const b of document.querySelectorAll('#apps button')) b.classList.remove('on');
  if (!quiet) dirty = true; }
// THE TILE OF AN ISOLATED APPLICATION: its name, what it does for a project, OPEN. Then how much of
// the record is lit and how much has gone dark, because the two must make the whole.
function appCard(st){
  cardToken++; cardShown = null; card.replaceChildren(); card.style.display = 'block'; card.scrollTop = 0;
  card.classList.add('short');
  const x = el('button', 'cc-x', '\u00d7'); x.type = 'button'; x.setAttribute('aria-label', 'close');
  x.addEventListener('click', () => { card.style.display = 'none'; dirty = true; });
  const t = el('a', 'cc-tile cc-app'); t.href = st.app.live; t.target = '_blank'; t.rel = 'noopener'; t.setAttribute('data-app', st.app.app);
  t.append(el('div', 'cc-tile-name', st.app.button));
  if (whatItDoes[st.app.live]) t.append(el('div', 'cc-tile-what', whatItDoes[st.app.live] + '.'));
  t.append(el('span', 'cc-tile-open', 'OPEN ' + st.app.button));
  const brand = el('div', 'scada-brand'), inner = el('div');
  inner.append(el('div', 'scada-brand-main', 'Ventus'), el('div', 'scada-brand-sub', 'Cables & Connectivity\u00ae')); brand.append(inner);
  const plain = el('div', 'cc-plain cc-count', fmt(st.lit) + ' pieces of work lit, ' + fmt(st.dark) + ' gone dark, '
    + fmt(st.lit + st.dark) + ' in all \u00b7 ' + day(st.first) + ' to ' + day(st.last));
  card.append(x, t, brand, plain);
  if (!ASM && asmWhy) card.append(el('div', 'cc-refuse', 'The gathering could not be loaded, so this work stays where it is: ' + asmWhy));
  if (typeof layout === 'function') layout();
}
function closeCard(){ cardToken++; card.style.display = 'none'; card.replaceChildren();
  target = null; cardShown = null; dirty = true; }
addEventListener('keydown', e => {
  if (e.key === 'Escape' && card.style.display !== 'none') { e.preventDefault(); closeCard(); } });

function codeWindow(lines, a, b, at){