GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/08-space-and-time

Iterations — 09 Deeplink Receiver and 3 more files

A JavaScript module in Galaxies Wafers that draws lines meta and families, using SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/.

700 lines of JavaScript and CSS and HTML from galaxies-wafers, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1186 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. Iterations — 08 Space and Time Page render · galaxies-wafers / iterations/08-space-and-time/index.html lines 1–50
  2. Questions render · galaxies-wafers / iterations/08-space-and-time/questions.mjs lines 1–118
  3. Iterations — 08 Space and Time Style Sheet render · galaxies-wafers / iterations/08-space-and-time/style.css lines 1–94
  4. Iterations — 09 Deeplink Receiver render · galaxies-wafers / iterations/09-deeplink-receiver/app.mjs lines 1–438

Iterations — 08 Space and Time Page

A web page in Galaxies Wafers that reads inputs for tslider. Published at https://ventusltd.github.io/galaxies-wafers/iterations/08-space-and-time/.

rendergalaxies-wafers / iterations/08-space-and-time/index.html · lines 1–50 of 50 · Entry point

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

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

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

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

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

<section id="clock" aria-label="the discovery clock: keys are the order lines were discovered, not the time they were written">
  <button id="tplay" type="button">PLAY</button>
  <input id="tslider" type="range" aria-label="discovery position: how many keys have been issued">
  <span id="tread"><span id="tkey" class="dim"></span> · <span id="tdate">dates loading…</span><span id="tsince" class="dim"></span></span>
</section>

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

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

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

Questions

A JavaScript module in the iterations folder of Galaxies Wafers that works with layer tags (`layerTags`) and single-line diagram (SLD) sentence (`sldSentence`). Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/08-space-and-time/.

rendergalaxies-wafers / iterations/08-space-and-time/questions.mjs · lines 1–118 of 118 · Entry point · pattern sldSentence (shared by 8 files)

What it does
It draws its content. Defines 11 functions or classes, including $, fmt, answer, fill, readJSON. Side effects: changes the web page (DOM); makes network requests.
Downstream impact
Used directly by 1 file: Iterations — 08 Space and Time Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/08-space-and-time/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/08-space-and-time/.
What it achieves
It reads JSON (`readJSON`) and is built from the fmt step (`fmt`) and the answer step (`answer`). Iteration 08, Space and Time: the owner's three questions and the machine detail line. It reads `../../layers/manifest.json`. It responds to resize and toggle events.
Why it matters
Loaded by the 08 Space and Time page at https://ventusltd.github.io/galaxies-wafers/iterations/08-space-and-time/.
Application
galaxies-wafers · iterations/08-space-and-time · JavaScript module
Uses
Clock (import)
Used by
loaded by Iterations — 08 Space and Time Page (script src)
Produces
$, fmt, answer, fill, readJSON, layerTags, sldSentence, text, mount, fit, paint
Defines here
$, fmt, answer, fill, readJSON, layerTags, sldSentence, text, mount, fit, paint
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/08-space-and-time/questions.mjs:1-118 · blob ecbf62341232f3c9c1ea4292e04007c83728afde · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: duplicate_candidate
/* questions.mjs — iteration 08, Space and Time: the owner's three questions and
 * the machine detail line. The clock is read at run time from clock.mjs (the
 * same module instance app.mjs and layers-panel.mjs import); layer counts from
 * layers/manifest.json; functions are cited to file and line.
 */
import { clock, GLOW_SHARE, GLOW_GROWTH } from './clock.mjs';

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

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

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

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

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

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

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

const COMMIT = 'f5de7a8';   /* the last commit to this page before the Questions panel */

mount(dl => {
  const q1 = answer(dl, '1 · How does this help draw a system or a single-line diagram?', 'reading layers/manifest.json…');
  answer(dl, '2 · What is this code used for?',
    'Drawing the wafer in discovery order. clock.mjs holds one number, t: born() line 20 says whether a key is discovered yet, glow() line 21 how recently, setT() line 26 moves t and tells listeners, bornPrefix() line 35 cuts a route at its last discovered key, dateIndex() line 56 finds the newest recorded family date among families whole at t. ' +
    'app.mjs adds the shader\'s born and glow terms, startClock() line 572 (?t= and ?rate=) and paintClock() line 547; layers-panel.mjs draws points only once born and routes through their born prefix. ' +
    `Who else: clock.mjs is imported by this page\'s app.mjs (line 47) and layers-panel.mjs (line 27) and by no other file (${SEARCH}); lib.mjs is imported by 42 files (${SEARCH}).`);
  answer(dl, '3 · Where does it lead next?',
    `Not established: no other page imports clock.mjs or reads ?t= (${SEARCH}), so the discovery position joins no next element or page.`);
  readJSON('../../layers/manifest.json').then(m => {
    q1('It draws no electrical element; it maps code. A key is the order in which the numbered database met a line, not the time it was written (clock.mjs lines 3–5), so this page cannot show when any part of a network was designed or built. ' +
      `It shows which lines of a layer, an SLD layer included, had been discovered by position t (now ${fmt(clock.t)} of ${fmt(clock.max)}). ` + sldSentence(m, 'layers/manifest.json'));
  }).catch(e => q1(`Not established: layers/manifest.json could not be read (${e.message}). The page draws no electrical element.`));
}, () => {
  const u = new URL(location.href).searchParams;
  return `inputs: ?t= (discovery position, a key, clamped to 1…max; unreadable starts at max; app.mjs line 575; in the URL now: ${u.get('t') ?? 'absent'}), ?rate= (keys per second; default max ÷ SWEEP_SECONDS, 60 s at app.mjs line 543; read at line 576), the slider and PLAY, ?line= and ?to= (permanent line keys, readURL() line 509), ?layers= (layers-panel.mjs line 253); ` +
    `data: all-lines.meta.json, all-lines.bin, all-lines.len.bin, all-lines.family.bin, families.json and lines.bin from ${DATA_PIN} (app.mjs line 49), ${text('prov') || 'provenance not loaded yet'} · ` +
    `outputs: t ${fmt(clock.t)} of ${fmt(clock.max)} (clock.mjs, now); keys within the last ${GLOW_SHARE * 100}% of t glow and draw up to ${1 + GLOW_GROWTH}× size; date shown ${text('tdate') || 'not yet'}${text('tsince')}; ${text('count') || 'count not loaded yet'}; layer rows now ${layerTags()} · ` +
    'refusals: an unreadable ?t= or ?rate= is not used (the default applies); before the first whole family the date reads "before the first family" (line 552); a layer reads FAIL or EMPTY with its reason; unknown ?layers= ids are dropped without a warning (layers-panel.mjs line 255); refuse() app.mjs line 527 · ' +
    `source: page commit ${COMMIT}; lib.mjs and layers/ from this repository`;
});

Iterations — 08 Space and Time Style Sheet

A style sheet in Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/08-space-and-time/.

rendergalaxies-wafers / iterations/08-space-and-time/style.css · lines 1–94 of 94 · Entry point

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

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

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

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

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

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

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

/* the clock: one strip above the footer */
#clock{position:fixed;left:.5rem;right:.5rem;z-index:3;bottom:calc(var(--bot) + 6.6rem);
  display:flex;flex-wrap:wrap;gap:.3rem .6rem;align-items:center;background:#0e121bf0;
  border:1px solid var(--edge);border-radius:8px;padding:.35rem .6rem}
#tplay{background:#11151f;color:var(--lit);border:1px solid var(--lit);border-radius:6px;padding:.25rem .7rem;font:inherit;letter-spacing:.1em;cursor:pointer}
#tslider{flex:1 1 12rem;min-width:0;accent-color:var(--lit)}
#tread{flex:1 1 100%;font-size:12px}
#tdate{color:var(--lit)}
@media (min-width:760px){#tread{flex:0 1 auto}}

Iterations — 09 Deeplink Receiver

A JavaScript module in Galaxies Wafers that draws lines meta and families, using SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/.

rendergalaxies-wafers / iterations/09-deeplink-receiver/app.mjs · lines 1–438 of 700 · Entry point · pattern visibleRange (shared by 3 files)

What it does
It draws lines meta and families. Defines 39 functions or classes, including $, snapshot, motion, indexOfKey, bin. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: JSON file all-lines.meta.json; JSON file families.json. Out: WebGL/WebGPU drawing.
Downstream impact
Used directly by 1 file: Iterations — 09 Deeplink Receiver Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/). Reached from 1 other entry point, including Iterations — 45 Deeplink Round Trip Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/.
What it achieves
It indexes key (`indexOfKey`), builds gl (`buildGL`) and draws marks (`drawMarks`). The Line Wafer. It responds to pointerdown, pointermove and pointerup events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/.
Application
galaxies-wafers · iterations/09-deeplink-receiver · JavaScript module
Uses
Galaxies Wafers — Lib (import), Receiver (import)
Used by
loaded by Iterations — 09 Deeplink Receiver Page (script src)
Produces
$, snapshot, motion, indexOfKey, bin, tier1, tier2, compile, initGL, fallback2d, buildGL, put
Defines here
$, snapshot, motion, indexOfKey, bin, tier1, tier2, compile, initGL, fallback2d, buildGL, put, resize, ensureOverlay, drawMarks, toScreen, lowerBound, visibleRange, drawPoints, ensureCache, cacheRect, rasterCache, blitCache, render, draw, home
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/09-deeplink-receiver/app.mjs:1-438 · blob 467d8e1299b1df05aaf085b45bb48cb32d835f27 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* The Line Wafer.
 *
 * WHAT THIS IS. Every line of code in the estate that has been given a
 * permanent number is one point on one surface. There are 250,174 of them and
 * they are numbered 1 to 342,795: the number is the line's permanent key, it
 * never changes and it is never reused, and numbers missing from the sequence
 * were never issued. Those gaps are drawn as gaps.
 *
 * WHY THE NUMBER IS THE ADDRESS. A point's position here is a pure function of
 * its own permanent key and of nothing else:
 *
 *     r = SPACING * sqrt(key)        theta = key * GOLDEN
 *
 * so line 8,285 is in the same place on every device, in every session, for
 * ever, and the surface can be reconstituted from the numbers alone. Nothing
 * about a position is stored, fetched or remembered. That is what makes the
 * surface unbounded rather than large: the estate can issue line 400,000
 * tomorrow and the wafer already has somewhere to put it.
 *
 * THE BEAM. The camera is a beam. It steers over the wafer and focuses, and
 * where it focuses the structure resolves — one line, its length, whether any
 * function family carries it, and which. Focus is the only instrument; there
 * are no levels and nothing is pre-rendered.
 *
 * THE RULE THIS PAGE EXISTS TO MEET. It must be able to connect any two
 * uniquely numbered lines in the estate. Type two numbers and it answers: the
 * families that carry both, or a refusal naming which of the two no family
 * carries.
 *
 * TWO RELATIONS, AND THE FIRST VERSION OF THIS PAGE CONFUSED THEM.
 * FANOUT is one number appearing in several families: the same text sitting in
 * several places, which is duplication. CO-MEMBERSHIP is two different numbers
 * appearing in one family: two lines of the same function, which is
 * neighbourhood and is NOT the same text. Connecting uses co-membership, so a
 * line carried by exactly one family is perfectly connectable — to another line
 * of that family. The page originally claimed the opposite and a reviewer was
 * right to reject it. See lib.mjs.
 *
 * WHAT IS NOT CLAIMED. Neither relation is a dependency and neither means one
 * line calls the other. Triviality is visible rather than hidden: a line's
 * fanout is printed, so line 2, an empty line in 2,281 families, looks exactly
 * as meaningless as it is.
 */

import { place, placeAll, parseKey, indexOfKey as findKey, ownersOf, fanoutCount,
         connectAnswer, esc, fmt, SPACING } from '../../lib.mjs';
/* Iteration 09: the URL is read once, by the engine's parseDeepLink, in receiver.mjs. */
import { LINK } from './receiver.mjs';

/* The zoom the link asked for; applied on arrival, forgotten once the user flies elsewhere. */
let linkZoom = LINK.ok ? LINK.zoom : undefined;

const DATA = 'https://globalgrid2050.com/testcode/202609142202/data/';

const $ = id => document.getElementById(id);
let stage = $("stage");

const U = {
  fanout: null,        /* lines carried by MORE THAN ONE family; counted, never typed */
  keys: null,        /* Uint32Array, sorted: every permanent line number issued */
  lens: null,        /* Uint16Array: characters in that line */
  inFam: null,       /* Uint8Array: 1 when at least one family carries it */
  pos: null,         /* Float32Array 2N: the pure function of the key */
  n: 0,
  families: null,    /* tier 2 */
  famLines: null,
  ownerOf: null,     /* Map<key, number[]> family indexes, built once on demand */
  meta: null
};

const view = { x: 0, y: 0, zoom: 1, w: 0, h: 0, dpr: 1, focus: -1, link: null };
/* The one read-only hook for layers: the live camera, and listeners called after every frame. */
/* Listeners get a frozen scalar snapshot, never the live object: a listener that
   mutates what it received cannot move the wafer's camera. (Codex review.) */
const snapshot = () => Object.freeze({ x: view.x, y: view.y, zoom: view.zoom, w: view.w, h: view.h, dpr: view.dpr, moving: MOTION.moving });

/* SMOOTH ZOOM (09b), ported from the root page (app.mjs, "Merge 38") and
   iterations/22-fast-zoom/app.mjs. While a gesture is moving the camera the
   wafer is not re-rasterised: its points are drawn once into an offscreen
   texture CACHE_SPAN times the screen in each direction, and each moving frame
   draws only that texture as one transformed quad. The texture is redrawn when
   the camera leaves it (panned past its margin, zoomed out past it, or
   magnified more than CACHE_MAGNIFY times), and full detail returns SETTLE_MS
   after the last gesture event. Layers read `moving` from the snapshot. */
const SETTLE_MS = 150;
const CACHE_SPAN = 1.5;
const CACHE_MAGNIFY = 2;
const MOTION = { moving: false, timer: 0 };
function motion() {
  MOTION.moving = true;
  clearTimeout(MOTION.timer);
  MOTION.timer = setTimeout(() => { MOTION.moving = false; draw(); }, SETTLE_MS);
}

window.__wafer = Object.freeze({ get view() { return snapshot(); }, onDraw: new Set(),
  get moving() { return MOTION.moving; }, get settleMs() { return SETTLE_MS; },
  get stats() { return Object.freeze({ drawn: frameStats.drawn, total: U.n, rasters: cache.rasters }); } });

/* ── the surface ─────────────────────────────────────────────────────────── */

const placeOne = place;                       /* where a number sits, issued or not */
const indexOfKey = key => findKey(U.keys, key);

/* ── loading ─────────────────────────────────────────────────────────────── */

async function bin(name, Kind) {
  const r = await fetch(DATA + name, { cache: 'default' });
  if (!r.ok) throw new Error(DATA + name + ' returned HTTP ' + r.status);
  return new Kind(await r.arrayBuffer());
}

async function tier1() {
  const [meta, keys, lens, inFam] = await Promise.all([
    fetch(DATA + 'all-lines.meta.json').then(r => r.json()),
    bin('all-lines.bin', Uint32Array),
    bin('all-lines.len.bin', Uint16Array),
    bin('all-lines.family.bin', Uint8Array)
  ]);
  U.meta = meta; U.keys = keys; U.lens = lens; U.inFam = inFam; U.n = keys.length;
  U.pos = placeAll(keys);

  let carried = 0;
  for (let i = 0; i < inFam.length; i++) carried += inFam[i];
  $('count').textContent =
    `${fmt(U.n)} numbered lines · 1 to ${fmt(meta.max)} · ${fmt(carried)} carried by a family`;
  $('prov').textContent =
    `numbered database built ${meta.built_utc.slice(0, 16).replace('T', ' ')} UTC · pack ${meta.source.sha256.slice(0, 12)}`;
}

async function tier2() {
  const [families, famLines] = await Promise.all([
    fetch(DATA + 'families.json').then(r => r.json()),
    bin('lines.bin', Uint32Array)
  ]);
  U.families = families; U.famLines = famLines;
  const owner = ownersOf(families, famLines);
  U.ownerOf = owner;
  U.fanout = fanoutCount(owner);
  if (view.focus >= 0) paintPanel(view.focus);
  if (view.link) connect(view.link[0], view.link[1]);
}

/* ── drawing ─────────────────────────────────────────────────────────────── */

const VS = `#version 300 es
precision highp float;
in vec2 a_pos; in float a_len; in float a_fam;
uniform vec2 u_res; uniform vec2 u_cam; uniform float u_zoom; uniform float u_dpr;
uniform float u_focusKey;
out float v_fam; out float v_len; out float v_focus;
void main(){
  vec2 p = (a_pos - u_cam) * u_zoom;
  gl_Position = vec4(p / (u_res * 0.5), 0.0, 1.0);
  float base = 1.0 + min(a_len, 120.0) * 0.012;
  gl_PointSize = clamp(base * sqrt(u_zoom) * u_dpr, 1.0, 26.0 * u_dpr);
  v_fam = a_fam; v_len = a_len; v_focus = 0.0;
}`;

const FS = `#version 300 es
precision highp float;
in float v_fam; in float v_len; in float v_focus;
out vec4 o;
void main(){
  vec2 d = gl_PointCoord - 0.5;
  float r = length(d);
  if (r > 0.5) discard;
  float edge = smoothstep(0.5, 0.42, r);
  vec3 carried = vec3(0.84, 0.87, 0.94);
  vec3 alone   = vec3(0.30, 0.34, 0.44);
  vec3 c = mix(alone, carried, v_fam);
  o = vec4(c, edge * (0.30 + 0.70 * v_fam));
}`;

let gl = null, prog = null, loc = {}, vao = null, ctx2d = null;

function compile(g, type, src) {
  const s = g.createShader(type); g.shaderSource(s, src); g.compileShader(s);
  if (!g.getShaderParameter(s, g.COMPILE_STATUS)) throw new Error(g.getShaderInfoLog(s));
  return s;
}

/* If anything after acquiring the context fails — a shader that will not compile
   on some driver, a program that will not link — the page must fall back, not
   half-run. A canvas cannot hand out a 2D context once it has given out a WebGL
   one, so the canvas itself is replaced. The first version left `gl` non-null on
   failure and then asked the same canvas for a 2D context, which returns null:
   the fallback it advertised did not exist. */
function initGL() {
  /* 09b: antialias off (iterations/22-fast-zoom). Each point already fades its own
     edge in the fragment shader; multisampling a full-screen buffer is GPU cost. */
  gl = stage.getContext('webgl2', { antialias: false, alpha: false });
  if (!gl) { gl = null; return fallback2d(); }
  try { return buildGL(); }
  catch (e) { gl = null; console.warn('WebGL setup failed, falling back:', e.message); return fallback2d(); }
}

function fallback2d() {
  const fresh = stage.cloneNode(false);
  stage.replaceWith(fresh);
  stage = fresh;
  ctx2d = stage.getContext('2d');
  $('hint').textContent = ctx2d
    ? 'drawn without the GPU: at low zoom one line in seven is plotted'
    : 'this browser gave neither a GPU nor a 2D canvas; nothing can be drawn';
  return false;
}

function buildGL() {
  prog = gl.createProgram();
  gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, VS));
  gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, FS));
  gl.linkProgram(prog);
  if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog));
  gl.useProgram(prog);
  for (const u of ['u_res', 'u_cam', 'u_zoom', 'u_dpr', 'u_focusKey']) loc[u] = gl.getUniformLocation(prog, u);

  vao = gl.createVertexArray(); gl.bindVertexArray(vao);
  const put = (data, name, size, Kind, norm) => {
    const b = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, b);
    gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
    const l = gl.getAttribLocation(prog, name);
    gl.enableVertexAttribArray(l);
    gl.vertexAttribPointer(l, size, Kind, !!norm, 0, 0);
  };
  put(U.pos, 'a_pos', 2, gl.FLOAT, false);
  put(U.lens, 'a_len', 1, gl.UNSIGNED_SHORT, false);
  put(U.inFam, 'a_fam', 1, gl.UNSIGNED_BYTE, false);
  gl.enable(gl.BLEND);
  gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  return true;
}

function resize() {
  view.dpr = Math.min(window.devicePixelRatio || 1, 2);
  view.w = stage.clientWidth; view.h = stage.clientHeight;
  stage.width = Math.round(view.w * view.dpr);
  stage.height = Math.round(view.h * view.dpr);
  if (gl) gl.viewport(0, 0, stage.width, stage.height);
}

let overlay = null;
function ensureOverlay() {
  if (overlay) return overlay;
  overlay = document.createElement('canvas');
  overlay.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:1';
  document.body.appendChild(overlay);
  return overlay;
}

/* 09b: the marks canvas is resized only when the stage changes size and cleared
   only when it holds something; assigning canvas.width every frame reallocated a
   full-screen backing store on every frame. */
let marksDirty = true;
function drawMarks() {
  const o = ensureOverlay();
  const has = !!view.link || view.focus >= 0;
  if (o.width !== stage.width || o.height !== stage.height) { o.width = stage.width; o.height = stage.height; marksDirty = true; }
  if (!has && !marksDirty) return;
  const c = o.getContext('2d');
  c.setTransform(view.dpr, 0, 0, view.dpr, 0, 0);
  c.clearRect(0, 0, view.w, view.h);
  marksDirty = has;
  if (!has) return;
  const toScreen = ([x, y]) => [
    (x - view.x) * view.zoom + view.w / 2,
    view.h / 2 - ((y - view.y) * view.zoom)
  ];
  if (view.link) {
    const [ka, kb] = view.link;
    const A = toScreen(placeOne(ka)), B = toScreen(placeOne(kb));
    c.strokeStyle = '#5ec8f2'; c.lineWidth = 1.2; c.setLineDash([5, 4]);
    c.beginPath(); c.moveTo(A[0], A[1]);
    c.quadraticCurveTo((A[0] + B[0]) / 2, (A[1] + B[1]) / 2 - 40, B[0], B[1]);
    c.stroke(); c.setLineDash([]);
    for (const P of [A, B]) {
      c.strokeStyle = '#5ec8f2'; c.beginPath(); c.arc(P[0], P[1], 9, 0, 6.2832); c.stroke();
    }
  }
  if (view.focus >= 0) {
    const P = toScreen(placeOne(view.focus));
    c.strokeStyle = '#ffd54a'; c.lineWidth = 1.4;
    c.beginPath(); c.arc(P[0], P[1], 11, 0, 6.2832); c.stroke();
    c.beginPath(); c.moveTo(P[0] - 18, P[1]); c.lineTo(P[0] - 13, P[1]);
    c.moveTo(P[0] + 13, P[1]); c.lineTo(P[0] + 18, P[1]);
    c.moveTo(P[0], P[1] - 18); c.lineTo(P[0], P[1] - 13);
    c.moveTo(P[0], P[1] + 13); c.lineTo(P[0], P[1] + 18);
    c.stroke();
  }
}

/* ── the moving-frame cache (from the root app.mjs / iterations/22-fast-zoom) ── */

const BLIT_VS = `#version 300 es
in vec2 a_q; uniform vec4 u_rect; out vec2 v_uv;
void main(){ v_uv = a_q; gl_Position = vec4(mix(u_rect.xy, u_rect.zw, a_q), 0.0, 1.0); }`;
const BLIT_FS = `#version 300 es
precision mediump float; in vec2 v_uv; uniform sampler2D u_tex; out vec4 o;
void main(){ o = texture(u_tex, v_uv); }`;

const cache = { fbo: null, tex: null, w: 0, h: 0, prog: null, vao: null, rect: null, valid: false, x: 0, y: 0, zoom: 1, rasters: 0, broken: false };

/* CULLING BY THE LAW. r = sqrt(key), so the keys that can appear in a world
   rectangle are exactly those whose radius lies between the rectangle's nearest
   and farthest distance from the origin: keys in [r0^2, r1^2]. U.keys is sorted,
   so that is one contiguous index range, found by two binary searches, and one
   drawArrays call over it. POINT_MARGIN_PX widens the rectangle by the largest
   point radius so a point straddling the edge is not cut. */
const POINT_MARGIN_PX = 14;
const frameStats = { drawn: 0 };
function lowerBound(a, v) { let lo = 0, hi = a.length; while (lo < hi) { const m = (lo + hi) >>> 1; if (a[m] < v) lo = m + 1; else hi = m; } return lo; }
function visibleRange(halfWpx, halfHpx, cx, cy) {
  const k = view.zoom * view.dpr;
  const hw = halfWpx / k + POINT_MARGIN_PX / view.zoom, hh = halfHpx / k + POINT_MARGIN_PX / view.zoom;
  const ax = Math.abs(cx), ay = Math.abs(cy);
  const dx = Math.max(ax - hw, 0), dy = Math.max(ay - hh, 0);
  const r0 = Math.hypot(dx, dy) / SPACING, r1 = Math.hypot(ax + hw, ay + hh) / SPACING;
  return [lowerBound(U.keys, Math.floor(r0 * r0)), lowerBound(U.keys, Math.ceil(r1 * r1) + 1)];
}

function drawPoints(w, h, cx, cy) {
  gl.clearColor(0.043, 0.051, 0.071, 1); gl.clear(gl.COLOR_BUFFER_BIT);
  gl.useProgram(prog); gl.bindVertexArray(vao);
  gl.uniform2f(loc.u_res, w, h);
  gl.uniform2f(loc.u_cam, cx, cy);
  gl.uniform1f(loc.u_zoom, view.zoom * view.dpr);
  gl.uniform1f(loc.u_dpr, view.dpr);
  gl.uniform1f(loc.u_focusKey, view.focus);
  const [lo, hi] = visibleRange(w / 2, h / 2, cx, cy);
  if (hi > lo) gl.drawArrays(gl.POINTS, lo, hi - lo);
  frameStats.drawn = Math.max(0, hi - lo);
}

/* Returns false when this GPU cannot give a render target; the page then draws
   every moving frame in full, as before. */
function ensureCache() {
  if (cache.broken) return false;
  const max = Math.min(gl.getParameter(gl.MAX_TEXTURE_SIZE), gl.getParameter(gl.MAX_RENDERBUFFER_SIZE));
  const w = Math.min(max, Math.ceil(stage.width * CACHE_SPAN)), h = Math.min(max, Math.ceil(stage.height * CACHE_SPAN));
  if (cache.tex && cache.w === w && cache.h === h) return true;
  try {
    if (!cache.prog) {
      const p = gl.createProgram();
      gl.attachShader(p, compile(gl, gl.VERTEX_SHADER, BLIT_VS));
      gl.attachShader(p, compile(gl, gl.FRAGMENT_SHADER, BLIT_FS));
      gl.linkProgram(p);
      if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
      cache.prog = p; cache.rect = gl.getUniformLocation(p, 'u_rect');
      cache.vao = gl.createVertexArray(); gl.bindVertexArray(cache.vao);
      const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b);
      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);
      const l = gl.getAttribLocation(p, 'a_q'); gl.enableVertexAttribArray(l); gl.vertexAttribPointer(l, 2, gl.FLOAT, false, 0, 0);
    }
    if (cache.tex) { gl.deleteTexture(cache.tex); gl.deleteFramebuffer(cache.fbo); }
    cache.tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, cache.tex);
    gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, w, h);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    cache.fbo = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, cache.fbo);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, cache.tex, 0);
    const ok = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    if (!ok) throw new Error('framebuffer incomplete');
    cache.w = w; cache.h = h; cache.valid = false;
    return true;
  } catch (e) {
    console.warn('moving-frame cache unavailable, drawing every frame in full:', e.message);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    cache.broken = true;
    return false;
  }
}

/* Where the cached texture lands on screen, in clip space: [x0, y0, x1, y1]. */
function cacheRect() {
  const hw = cache.w / (cache.zoom * view.dpr * 2), hh = cache.h / (cache.zoom * view.dpr * 2);
  const kx = view.zoom * view.dpr * 2 / stage.width, ky = view.zoom * view.dpr * 2 / stage.height;
  return [(cache.x - hw - view.x) * kx, (cache.y - hh - view.y) * ky,
          (cache.x + hw - view.x) * kx, (cache.y + hh - view.y) * ky];
}

function rasterCache() {
  gl.bindFramebuffer(gl.FRAMEBUFFER, cache.fbo);
  gl.viewport(0, 0, cache.w, cache.h);
  drawPoints(cache.w, cache.h, view.x, view.y);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  gl.viewport(0, 0, stage.width, stage.height);
  cache.x = view.x; cache.y = view.y; cache.zoom = view.zoom; cache.valid = true; cache.rasters++;
}

function blitCache() {
  let r = cacheRect();
  const covers = r[0] <= -1 && r[1] <= -1 && r[2] >= 1 && r[3] >= 1 && view.zoom / cache.zoom <= CACHE_MAGNIFY;
  if (!cache.valid || !covers) { rasterCache(); r = cacheRect(); }
  gl.clearColor(0.043, 0.051, 0.071, 1); gl.clear(gl.COLOR_BUFFER_BIT);
  gl.disable(gl.BLEND);
  gl.useProgram(cache.prog); gl.bindVertexArray(cache.vao);
  gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, cache.tex);
  gl.uniform4f(cache.rect, r[0], r[1], r[2], r[3]);
  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  gl.enable(gl.BLEND);
}

function render() {
  if (gl) {
    if (MOTION.moving && ensureCache()) blitCache();
    else { cache.valid = false; drawPoints(stage.width, stage.height, view.x, view.y); }
  } else if (ctx2d) {
    const c = ctx2d;
    c.setTransform(1, 0, 0, 1, 0, 0);
    c.fillStyle = '#0b0d12'; c.fillRect(0, 0, stage.width, stage.height);
    c.fillStyle = '#7d8598';
    const step = view.zoom < 0.5 ? 7 : 1;
    for (let i = 0; i < U.n; i += step) {
      const x = (U.pos[i * 2] - view.x) * view.zoom * view.dpr + stage.width / 2;
      const y = stage.height / 2 - (U.pos[i * 2 + 1] - view.y) * view.zoom * view.dpr;
      if (x < 0 || y < 0 || x > stage.width || y > stage.height) continue;
      c.fillRect(x, y, view.dpr, view.dpr);
    }
  }
  drawMarks();
  { const snap = snapshot(); for (const f of window.__wafer.onDraw) { try { f(snap); } catch (e) { console.warn('onDraw listener failed:', e); } } }
}

let pending = false;
function draw() { if (!pending) { pending = true; requestAnimationFrame(() => { pending = false; render(); }); } }

/* ── the beam: steering and focusing ─────────────────────────────────────── */

function home() {
  const maxR = SPACING * Math.sqrt(U.meta.max);
  view.x = 0; view.y = 0;
  view.zoom = Math.min(view.w, view.h) / (maxR * 2.15);
  draw();
}