In this section
- Kuiper Chrome interaction · globalgrid2050 / kuiper-grid/drawing/kuiper-chrome.js lines 1–529
- Kuiper Controls interaction · globalgrid2050 / kuiper-grid/drawing/kuiper-controls.js lines 1–104
- Kuiper Pointer transform · globalgrid2050 / kuiper-grid/drawing/kuiper-pointer.js lines 1–25
Kuiper Chrome
A JavaScript file in the drawing folder of GlobalGrid2050 that opens sheet (`openSheet`), shows systems (`showSystems`) and groups boxes (`groupBoxes`), covering cables and substations. Served with the page at https://globalgrid2050.com/kuiper-grid/drawing/.
interactionglobalgrid2050 / kuiper-grid/drawing/kuiper-chrome.js · lines 1–529 of 529 · Entry point · pattern showSystems (shared by 3 files)
- What it does
- It draws cables and substations. Defines 26 functions or classes, including PHONE, $, el, kick, relayout. Side effects: changes the web page (DOM).
- 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: cables, substations.
- Downstream impact
- Used directly by 1 file: Renderer (globalgrid2050, https://globalgrid2050.com/kuiper-grid/drawing/renderer.html). Reached from 110 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/drawing/.
- What it achieves
- It opens sheet (`openSheet`), shows systems (`showSystems`) and marks state (`markState`). A cartridge of the Kuiper shell: HOW THE PAGE IS DRESSED. It responds to click, focus and keydown events.
- Why it matters
- Loaded by the Renderer page at https://globalgrid2050.com/kuiper-grid/drawing/renderer.html.
- Application
- globalgrid2050 · kuiper-grid/drawing · script
- Uses
- none found
- Used by
- loaded by Renderer (script src)
- Produces
- PHONE, $, el, kick, relayout, judge, boot, isOpen, shut, loosen, openSheet, refire
- Defines here
- PHONE, $, el, kick, relayout, judge, boot, isOpen, shut, loosen, openSheet, refire, camera, typed, showSystems, markState, fixChips, devWatch, groupBoxes, keyOfRow, readKey, applyKey, keepMark, filterDrawing, applyMarks, hideWordy
- 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/drawing/kuiper-chrome.js:1-529 · blob 8353e7e3f32cef93b0eb2a99367ad017e5aade27 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: production_core
'use strict';
// kuiper-chrome.js - a cartridge of the Kuiper shell: HOW THE PAGE IS DRESSED. What sits over the disc,
// and how much of it. The shell is never edited, so the dressing lives here, where it can be changed.
//
// THE DRAWING FIRST. Vikram, 20 September, looking at his phone: "Can't even see the drawing!", then
// "The drawing should show first. All else should be in the pop up command selector and layout changes
// commands. Keep the view minimalist like the Kuiper, Wafer and Gridatlas", and "Module measurements in
// boxes in tools, not in the drawing". One question decides every line below: ON A 390 PIXEL PHONE, DOES
// THE PICTURE OF BOXES JOINED BY CABLES GET MORE OF THE SCREEN.
//
// WHAT IS ON THE FACE, and nothing else:
// 1. the drawing, edge to edge;
// 2. ONE scrollable row of short chips in the top left - never three rows of wrapped chips;
// 3. one thin RED line across the very top for a solar answer (the whole wording is in the pop-up);
// 4. ONE key line above the bar, with "more", instead of six pinned lines under the drawing;
// 5. one grey foot line, and one bar holding a plain name.
// Everything else - the examples picker, the presets, the declared inputs as number boxes, the answer
// and its figures, the applications, and the LAYOUT CHANGE COMMANDS - is in THE WAFER'S OWN WINDOW,
// which is the pop-up: a bottom sheet on a phone, the draggable window on a desk, CLOSED BY DEFAULT.
//
// NOTHING HERE IS A RIVAL COMPONENT. "You've killed the preset wafer lifted popup bar" was said once and
// is not going to be said again: #pilot, #pin, #eg, #egs, #presets and #say are the wafer's own parts,
// built by the programs cartridge, and this file only MOVES them, DRESSES them and HOOKS them. The
// examples picker is not rebuilt, it is carried into the sheet. The window is not replaced, it is
// restyled. The number boxes are not rebuilt, they are moved into groups, so every listener that was on
// them is still on them. Not one of the wafer's ids, classes or handlers is taken away.
//
// HOW IT HOOKS WITHOUT TOUCHING ANOTHER CARTRIDGE. Classic scripts share one global scope, so the parts
// the programs cartridge declares at the top level - sayOpen, sldShapes, fireLive, reFire, shapeBand,
// stringDrawing, stringNearView, stringWholeView - are reachable from here by name. Three are wrapped:
// sayOpen so a fired answer NEVER opens itself over the drawing; the answer chip pulses once.
// shapeBand so the band the drawing is laid into stops at the top of the sheet, not under it.
// stringDrawing so the measurements come off the picture and live in the boxes and the answer.
// Each wrapper calls the original first and changes nothing it computes.
(function () {
const PHONE = () => innerWidth <= 700;
const $ = id => document.getElementById(id);
const el = (tag, cls, t) => { const e = document.createElement(tag); if (cls) e.className = cls; if (t !== undefined) e.textContent = t; return e; };
const kick = () => { try { if (typeof dirty !== 'undefined') dirty = true; } catch (_) {} };
const relayout = () => { try { if (typeof layout === 'function') layout(); } catch (_) {} kick(); };
// ---- the look ---------------------------------------------------------------------------------
const css = document.createElement('style');
css.textContent = `
/* what 0044 took off the face, still off it */
#top{display:none !important}
#foot .long{display:none !important}
#keys{display:none !important}
#foot .short{display:block;margin-top:6px;font-size:10px;letter-spacing:.02em;line-height:1.4;color:var(--dim)}
html,body{overflow-x:hidden}
/* THE CHIPS ARE ONE BUTTON. A scrolling row of eight was still a row: it held the top of the screen
and the band the drawing is laid into started under it. There is ONE small button now, "layouts",
and the presets themselves are in the pop-up it opens - the same pop-up, no new widget. */
#presets{top:20px !important;left:10px !important;flex-wrap:nowrap !important;overflow-x:auto;overflow-y:hidden;
max-width:calc(100% - 20px) !important;padding-bottom:2px;scrollbar-width:none;-ms-overflow-style:none;
-webkit-overflow-scrolling:touch;z-index:19}
#presets::-webkit-scrollbar{display:none}
#presets button{flex:0 0 auto;white-space:nowrap}
#presets button.konly{border-color:#3b4760;color:#cfe3f2}
#chipapps{display:none}
#chipanswer{display:none !important}
#presets button{min-height:26px;padding:2px 9px;font-size:11px}
#chipmore.pulse{animation:kpulse 1s ease-out 1}
@keyframes kpulse{0%{box-shadow:0 0 0 0 #5ec8f2aa}70%{box-shadow:0 0 0 9px #5ec8f200}100%{box-shadow:0 0 0 0 #5ec8f200}}
/* THE RED LINE IS ONE THIN LINE ACROSS THE TOP, not a paragraph pinned under the picture. It carries
the short wording; the whole sentence is the first thing inside the pop-up. It is never hidden, at
any zoom and under any window, because it is the only thing on this page that must always be read. */
#sldnames span.danger{position:fixed;left:0 !important;right:0 !important;top:0 !important;
width:auto !important;max-width:none !important;transform:none !important;visibility:visible !important;
text-align:center;padding:2px 8px;font-size:9.5px !important;line-height:1.5;letter-spacing:.04em;
background:#160b0a;border-bottom:1px solid #4a2019;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
/* THE SAME RED LINE BEFORE ANYTHING IS DRAWN. The engine writes its warning beside a study, so the
first screen - the disc, nothing fired - carried no warning at all. This line is the chrome's own,
it is there from the first paint, and it steps aside the moment the engine's own line appears. */
#kdev{position:fixed;left:0;right:0;top:0;z-index:9;text-align:center;padding:2px 8px;
font:9.5px/1.5 ui-monospace,Menlo,Consolas,monospace;font-weight:600;letter-spacing:.04em;color:#ff5a4f;
background:#160b0a;border-bottom:1px solid #4a2019;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
/* THE KEY, COLLAPSED, ON EVERY SIZE. The pinned lines under the drawing become one line above the
bar with "more". On a desk they used to stay pinned, and the band the drawing is laid into was
shortened by whatever they took - eighty pixels of key under a picture that had asked for the
screen. One line above the bar says the same thing and costs fifteen. */
html.kquiet #sldnames span.pinned:not(.danger){display:none !important}
html.knokey #sldnames span.pinned:not(.danger){display:none !important}
#keyline{display:none;align-items:baseline;gap:8px;font:10px/1.35 ui-monospace,Menlo,Consolas,monospace;
color:#8b93a7;padding:0 0 3px;border-bottom:1px solid #141a26;margin-bottom:3px}
#keyline.on{display:flex}
#keyline span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#keyline button{flex:none;background:none;border:0;color:#5ec8f2;font:inherit;text-decoration:underline;cursor:pointer;padding:2px 0}
/* THE BAR, AND THE FOOT THAT HOLDS IT. Everything below the drawing - the key line, the line that
says what this is not, and the bar - is a hundred pixels, not two hundred. The drawing gets the
rest, on a telephone and on a desk. */
#pilot{margin-top:4px;padding-top:4px}
#foot{padding:5px 12px !important}
#foot .short{margin-top:3px;font-size:9px;line-height:1.3}
/* THE POP-UP. On a phone it is a bottom sheet: it covers at most the lower 60 per cent, it sits ABOVE
the bar so the bar can still be typed in, the drawing stays whole above it, and a tap outside shuts
it. Collapsed it is the title bar alone, at the bottom, where it cannot cover the chips. */
#kt{padding:.5rem .7rem;border-bottom:1px solid #1b2030;background:#0c1017;max-height:46vh;overflow:auto}
#say.min #kt{display:none}
#say #saybody{min-height:110px}
#kt #eg{margin:0 0 6px;border:0;background:none;padding:0}
#kt #eg select{align-self:stretch;width:auto;max-width:none;min-height:34px}
#kt details{border-top:1px solid #141a26;padding:4px 0 2px}
#kt summary{font:11px ui-monospace,Menlo,Consolas,monospace;letter-spacing:.08em;text-transform:uppercase;
color:#8b93a7;cursor:pointer;padding:3px 0;list-style:none}
#kt summary::-webkit-details-marker{display:none}
#kt summary::before{content:'+ ';color:#5ec8f2}
#kt details[open] summary::before{content:'− ';color:#5ec8f2}
#kt .krow{display:flex;flex-wrap:wrap;gap:5px;margin:3px 0 5px}
#kt .klab{font:10px ui-monospace,Menlo,Consolas,monospace;letter-spacing:.06em;text-transform:uppercase;
color:#5b6377;width:100%;margin:2px 0 0}
#kt button{font:11px/1.6 ui-monospace,Menlo,Consolas,monospace;color:#8b93a7;background:#0b0e14;
border:1px solid #232a3a;border-radius:4px;padding:3px 9px;cursor:pointer}
#kt button:hover,#kt button:focus-visible{color:#e6e9f0;border-color:#4a5573;outline:none}
#kt button.on{color:#eaf6ff;border-color:#5ec8f2}
#kt p.kdim{margin:.2rem 0;font-size:11px;color:#5b6377;line-height:1.45}
#kt .kkey p{margin:.25rem 0;font-size:11px;color:#8b93a7;line-height:1.45}
/* the declared inputs, grouped, so twenty-eight boxes are not one wall */
#saybody details.kbox{border-top:1px solid #141a26;padding:2px 0}
#saybody details.kbox summary{font:11px ui-monospace,Menlo,Consolas,monospace;letter-spacing:.08em;
text-transform:uppercase;color:#8b93a7;cursor:pointer;padding:4px 0;list-style:none}
#saybody details.kbox summary::-webkit-details-marker{display:none}
#saybody details.kbox summary::before{content:'+ ';color:#5ec8f2}
#saybody details.kbox[open] summary::before{content:'− ';color:#5ec8f2}
@media (max-width:700px){
#foot{padding:4px 10px !important}
#foot .short{margin-top:3px;font-size:8.5px;line-height:1.25}
#presets{top:20px !important;gap:5px}
#presets button{min-height:26px;padding:2px 9px;font-size:11px}
#pilot input{min-height:36px !important;padding:.35rem .8rem}
#say.open:not(.max){left:0 !important;right:0 !important;top:auto !important;
bottom:var(--footh) !important;width:100% !important;min-width:0;
max-height:60vh !important;height:auto !important;transform:none !important;
border-radius:10px 10px 0 0;border-left:0;border-right:0;resize:none}
#say.open:not(.max) #kt{max-height:none}
}`;
document.head.appendChild(css);
// THE WORDS GO, NOT ONLY THEIR PIXELS. A sentence set to display:none is still read back by anything
// that asks the page what it says, so the two lines nobody asked for are taken out of the page.
for (const sel of ['#use', '#foot .long']) { const e = document.querySelector(sel); if (e && e.remove) e.remove(); }
{ const keys = $('keys'); if (keys) keys.setAttribute('aria-hidden', 'true'); }
// THE CORNER IS SILENT UNTIL IT HAS SOMETHING TO REFUSE.
{ const hudEl = $('hud');
if (hudEl) {
const REFUSAL = /REFUSED|CONTEXT LOST|not available|did not load|will not invent|Nothing on screen/i;
const judge = () => { const said = hudEl.textContent || '';
hudEl.style.visibility = REFUSAL.test(said) ? 'visible' : 'hidden'; };
judge();
try { new MutationObserver(judge).observe(hudEl, { childList: true, characterData: true, subtree: true }); } catch (_) {}
} }
// ===============================================================================================
// Everything below needs the wafer's own parts, which the programs cartridge builds on
// DOMContentLoaded; its listener was registered first, so it has run by the time this one does.
// ===============================================================================================
function boot() {
const sayEl = $('say'), body2 = $('saybody'), foot = $('foot'), pin = $('pin'), eg = $('eg'), chips = $('presets');
if (!sayEl || !body2 || !pin) return; // nothing to dress: leave the page alone
// NUMBERS ARE OFF THE PICTURE. "Module measurements in boxes in tools, not in the drawing." Every
// figure is in the number boxes and in the answer; the picture carries what a wiring drawing is.
let numbersOn = false, keyOn = true, haveAnswer = false;
// ---- the pop-up is the wafer's window, and it is CLOSED unless somebody asked for it ---------
const isOpen = () => sayEl.classList.contains('open');
const shut = () => { sayEl.classList.remove('open', 'max', 'min'); relayout(); };
const loosen = () => { sayEl.style.left = ''; sayEl.style.top = ''; sayEl.style.width = '';
sayEl.style.maxHeight = ''; sayEl.style.transform = ''; };
const openSheet = (title) => {
if (title) { const t = $('saytitle'); if (t) t.textContent = title; }
sayEl.classList.remove('min');
if (PHONE()) loosen(); // the sheet's place is in the stylesheet
sayEl.classList.add('open');
relayout();
try { if (window.__placeSay && !PHONE()) window.__placeSay(); } catch (_) {}
};
// ---- THE TOOLS: the picker, the layout change commands, the key, the applications ------------
// They live BETWEEN the title bar and the body, because the body is written again on every answer
// and a tool that an answer wipes is not a tool.
const kt = el('div'); kt.id = 'kt';
sayEl.insertBefore(kt, body2);
if (eg) kt.append(eg); // the wafer's own examples picker, carried, not rebuilt
kt.append(el('p', 'kdim', 'Pick a preset below, or type a few plain words in the bar and press Enter.'));
// THE PRESETS LIVE HERE NOW. They are the page's own chips, CARRIED, not rebuilt: every listener the
// programs cartridge put on them is still on them. The face keeps one button that opens this.
const presetRow = el('div', 'krow'); presetRow.append(el('p', 'klab', 'the presets')); kt.append(presetRow);
// WHAT A LAYOUT COMMAND IS: a change to the drawing that happens AT ONCE, in place, with the camera
// where the reader left it - no flying home and gathering again for a different routing. Every one
// is a first-class entry: a plain name, a button here, and it can be typed in the bar.
const refire = (extra) => {
try {
if (typeof fireLive === 'undefined' || !fireLive || !fireLive.boxes) {
const first = chips && chips.querySelector('button'); // nothing fired yet: fire the first preset
if (!first) return false;
first.click();
setTimeout(() => { try { reFire(extra); } catch (_) {} }, 500);
return true;
}
reFire(extra);
return true;
} catch (_) { return false; }
};
const camera = (fn) => { try { fn(); } catch (_) {} kick(); return true; };
// TYPE IT AND FIRE IT, exactly as a reader would. The word goes into the bar and the bar's own
// Enter carries it, so a menu entry and a typed line take ONE path into the engine, never two.
const typed = (text) => { if (!pin) return false; pin.value = text;
pin.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); openSheet(); return true; };
const COMMANDS = [
['wiring sequential', 'the wiring', 'sequential', () => refire({ routing: 'one-after-another' })],
['wiring u', 'the wiring', 'U', () => refire({ routing: 'serpentine', turn_alternate_rows: 1 })],
['wiring leapfrog', 'the wiring', 'leapfrog', () => refire({ routing: 'leapfrog', turn_every_second: 0 })],
['wiring turned', 'the wiring', 'turned', () => refire({ routing: 'leapfrog', turn_every_second: 1 })],
['table one high', 'the table', '1 high', () => refire({ modules_high: 1 })],
['table two high', 'the table', '2 high', () => refire({ modules_high: 2 })],
['table three high', 'the table', '3 high', () => refire({ modules_high: 3 })],
['table four high', 'the table', '4 high', () => refire({ modules_high: 4 })],
['portrait', 'the table', 'portrait', () => refire({ orientation: 'portrait' })],
['landscape', 'the table', 'landscape', () => refire({ orientation: 'landscape' })],
['back of modules', 'the view', 'back of modules', () => refire({ view: 'wiring' })],
['to scale', 'the view', 'to scale', () => refire({ view: 'scale' })],
['near end', 'the view', 'near end', () => camera(() => stringNearView())],
['whole string', 'the view', 'whole string', () => camera(() => stringWholeView())],
['numbers on', 'on the picture', 'numbers on', () => { numbersOn = true; applyMarks(); return true; }],
['numbers off', 'on the picture', 'numbers off', () => { numbersOn = false; applyMarks(); return true; }],
['key on', 'on the picture', 'key on', () => { keyOn = true; applyKey(); return true; }],
['key off', 'on the picture', 'key off', () => { keyOn = false; applyKey(); return true; }],
// ONE MORE COMMAND, NO NEW WIDGET: the systems of the estate, listed in this same window. Tapping
// one fires its pulse through the engine and shuts the sheet, so the disc is what is seen.
['systems', 'the estate', 'systems', () => { showSystems(); return true; }],
['substation', 'the estate', 'substation', () => typed('fire substation')],
['neighbours', 'the estate', 'neighbours', () => typed('fire neighbours')],
['pulse', 'the estate', 'pulse', () => typed('fire pulse')]
];
// THE LIST OF SYSTEMS, built into this window's own tools the first time it is asked for.
let sysBox = null;
function showSystems() {
const S = window.KUIPER_SYSTEMS; if (!S) return false;
if (!sysBox) {
sysBox = el('details'); sysBox.append(el('summary', null, 'the systems of the estate'));
const b = el('div', 'kkey'); sysBox.append(b);
for (const s of S.all) {
const line = el('button', null, s.id + ' ' + s.system + ' · ' + s.files_total + ' files');
line.type = 'button'; line.dataset.sys = s.id;
line.style.display = 'block'; line.style.textAlign = 'left'; line.style.width = '100%';
line.addEventListener('click', e => { e.stopPropagation(); S.fire(s.id); shut(); });
b.append(line);
}
kt.append(sysBox);
}
sysBox.open = true; openSheet();
try { sysBox.scrollIntoView({ block: 'nearest' }); } catch (_) {}
return true;
}
const layoutBox = el('details'); layoutBox.open = true;
layoutBox.append(el('summary', null, 'layout change commands'));
let group = null;
for (const [name, family, words, run] of COMMANDS) {
if (!group || group.dataset.family !== family) {
group = el('div', 'krow'); group.dataset.family = family;
group.append(el('p', 'klab', family)); layoutBox.append(group);
}
const b = el('button', null, words); b.type = 'button'; b.title = name; b.dataset.cmd = name;
b.addEventListener('click', e => { e.stopPropagation(); run(); markState(); });
group.append(b);
}
kt.append(layoutBox);
// THE KEY IN FULL, where there is room to read it. One line of it stays on the face.
const keyBox = el('details'); keyBox.append(el('summary', null, 'the key'));
const keyBody = el('div', 'kkey'); keyBox.append(keyBody); kt.append(keyBox);
// THE APPLICATIONS, through the page's own chip, so there is one path to them and not two.
{ const row = el('div', 'krow');
const b = el('button', null, 'the applications'); b.type = 'button';
b.addEventListener('click', e => { e.stopPropagation(); const c = $('chipapps'); if (c) c.click(); openSheet(); });
const h = el('button', null, 'help'); h.type = 'button';
h.addEventListener('click', e => { e.stopPropagation(); pin.value = 'help';
pin.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); pin.value = ''; openSheet(); });
row.append(b, h); kt.append(row); }
function markState() {
for (const b of kt.querySelectorAll('button[data-cmd]')) {
const n = b.dataset.cmd;
const on = (n === 'numbers on' && numbersOn) || (n === 'numbers off' && !numbersOn)
|| (n === 'key on' && keyOn) || (n === 'key off' && !keyOn);
b.classList.toggle('on', !!on);
}
}
// ---- THE CHIPS: one row, a few short names, and the answer ----------------------------------
// The programs cartridge draws these, and draws them again when the published list lands, so they
// are put back after each of its redraws. Nothing of its own is removed: the applications chip is
// only taken off the face, and it is still the thing that opens the applications.
let mine = null, answerChip = null;
function fixChips() {
if (!chips) return;
if (!mine) { mine = el('button', 'konly', 'layouts'); mine.type = 'button'; mine.id = 'chipmore';
mine.title = 'every preset, every layout change and every input';
mine.addEventListener('click', e => { e.stopPropagation(); openSheet(haveAnswer ? null : 'commands'); }); }
if (!answerChip) { answerChip = el('button', 'konly', 'answer'); answerChip.type = 'button'; answerChip.id = 'chipanswer';
answerChip.style.display = 'none';
answerChip.addEventListener('click', e => { e.stopPropagation(); openSheet(); }); }
// every preset chip the page draws is MOVED into the pop-up, where the one button opens it
const own = Array.from(chips.children).filter(b => b.id !== 'chipapps' && b !== mine && b !== answerChip);
for (const b of own) { b.style.display = ''; presetRow.append(b); }
// the button is the FIRST thing in the row, and it is the only one on the face
if (chips.firstElementChild !== mine) chips.prepend(mine);
if (answerChip.parentNode !== chips) chips.append(answerChip);
}
fixChips();
// THE WARNING IS ON THE FIRST SCREEN. It is put up once, and hidden only while the engine's own
// red line is on the page, so a reader never sees the sentence twice and never sees it not at all.
const dev = el('div', null, 'Not real cable or array sizing - consult a design engineer. DEVELOPMENT ENVIRONMENT: estimates from a model, nothing measured.');
dev.id = 'kdev';
try { document.body.appendChild(dev); } catch (_) {}
const devWatch = () => { try { const own = document.querySelector('#sldnames span.danger');
dev.style.display = (own && own.getClientRects().length) ? 'none' : 'block'; } catch (_) {} };
devWatch();
try { setInterval(devWatch, 1000); } catch (_) {}
try { new MutationObserver(fixChips).observe(chips, { childList: true }); } catch (_) {}
// ---- THE BAR: a plain name, and the way into the pop-up --------------------------------------
pin.placeholder = 'tap here for the commands'; // no JSON, no pre-typed sentence
pin.addEventListener('focus', () => openSheet(haveAnswer ? null : 'commands'));
// A LAYOUT COMMAND CAN BE TYPED. The bar's own Enter searches the published list, so this listener
// is on the foot, in the capture phase, where it runs first and can keep the press for itself.
if (foot) foot.addEventListener('keydown', e => {
if (e.key !== 'Enter' || e.target !== pin) return;
const q = String(pin.value || '').trim().toLowerCase();
if (!q) return;
// "system <id or name>" fires that one system's pulse at once. "systems" alone opens the list,
// through the ordinary command below, so there is one way in and not two.
if (/^system\s+\S/.test(q) && window.KUIPER_SYSTEMS) {
e.stopPropagation(); e.preventDefault();
window.KUIPER_SYSTEMS.fire(q.replace(/^system\s+/, '')); shut(); pin.value = '';
return;
}
const hit = COMMANDS.find(c => c[0] === q) || (q.length >= 4 ? COMMANDS.find(c => c[0].startsWith(q)) : null);
if (!hit) return;
e.stopPropagation(); e.preventDefault();
pin.value = hit[0];
hit[3](); markState();
}, true);
// A TAP OUTSIDE SHUTS THE SHEET. Inside it, on the chips and on the bar, nothing is shut.
addEventListener('pointerdown', e => {
if (!isOpen()) return;
const t = e.target;
if (sayEl.contains(t) || (chips && chips.contains(t)) || (foot && foot.contains(t))) return;
shut();
}, true);
// ---- A FIRED ANSWER DOES NOT OPEN ITSELF OVER THE DRAWING -------------------------------------
// The wafer's window is still the window and the answer is still written into it; what changes is
// WHEN it is seen. On a phone an answer that opens itself is the drawing gone. The answer chip
// pulses once instead, and one tap opens it. A reader who already has the pop-up open keeps it.
try {
if (typeof sayOpen === 'function') {
const orig = sayOpen;
sayOpen = function (title, nodes, beside) {
const wasOpen = isOpen();
orig(title, nodes, false);
haveAnswer = true;
groupBoxes();
readKey();
if (mine) { mine.classList.remove('pulse'); void mine.offsetWidth; mine.classList.add('pulse'); }
if (!wasOpen) { sayEl.classList.remove('open', 'max', 'min'); relayout(); }
else if (PHONE()) loosen();
markState();
};
}
} catch (_) {}
// THE DECLARED INPUTS IN COLLAPSIBLE GROUPS. The window builds a labelled box for every input the
// command declares, which for a string is twenty-eight: one wall of boxes on a phone. The boxes are
// not rebuilt - they are MOVED, so every listener the programs cartridge put on them is still on
// them - into four groups, of which one is open.
const GROUPS = [
['the table', ['mounting', 'orientation', 'modules_high', 'modules', 'routing', 'turn_alternate_rows', 'turn_every_second', 'jumpers', 'view']],
['the module, in metres', ['width_m', 'module_height_m', 'gap_m', 'gap_up_m', 'ridge_gap_m', 'tube_gap_m', 'box_spacing_m', 'cell_cols', 'cell_rows']],
['the cables', ['lead_plus_m', 'lead_minus_m', 'lead_mm2', 'cable_mm2', 'near_end_m', 'slack_m', 'home_separation_m']],
['the electrical figures', ['amps', 't_lead_c', 't_site_c', 'rating_c', 'module_vmp', 'module_voc']]
];
function groupBoxes() {
const wrap = body2.querySelector('.boxes');
if (!wrap || wrap.dataset.kgrouped) return;
const rows = Array.from(wrap.querySelectorAll('.boxrow'));
if (!rows.length) return;
const keyOfRow = r => { const f = r.querySelector('input,select'); const id = f ? (f.id || '') : '';
const at = id.indexOf('-', 4); return at > 0 ? id.slice(at + 1) : ''; };
const left = new Set(rows), made = [];
for (const [name, keys] of GROUPS) {
const want = rows.filter(r => keys.includes(keyOfRow(r)));
if (!want.length) continue;
const d = el('details', 'kbox'); d.append(el('summary', null, name));
for (const r of want) { d.append(r); left.delete(r); }
made.push(d);
}
if (left.size) { const d = el('details', 'kbox'); d.append(el('summary', null, 'the rest'));
for (const r of left) d.append(r); made.push(d); }
if (made.length) { made[0].open = true; wrap.prepend(...made); }
wrap.dataset.kgrouped = '1';
}
// ---- THE KEY: one line on the face, all of it in the pop-up ----------------------------------
// The programs cartridge pins the key under the drawing, which is right on a desk and is half a
// phone screen on a phone. The lines are READ from its own layer - never rewritten here - the one
// that carries the arithmetic stays on the face, and the rest are behind "more".
const keyRow = el('div'); keyRow.id = 'keyline';
const keyText = el('span'), keyMore = el('button', null, 'more'); keyMore.type = 'button';
keyMore.addEventListener('click', e => { e.stopPropagation(); keyBox.open = true; openSheet('the key'); });
keyRow.append(keyText, keyMore);
if (foot) foot.prepend(keyRow);
function readKey() {
const layer = $('sldnames');
const lines = layer ? Array.from(layer.querySelectorAll('span.pinned'))
.filter(s => !s.classList.contains('danger'))
.map(s => (s.textContent || '').trim()).filter(Boolean) : [];
keyBody.replaceChildren(...(lines.length ? lines.map(t => el('p', null, t))
: [el('p', null, 'The key appears with the drawing.')]));
keyText.textContent = lines.find(t => /ohm/.test(t)) || lines[0] || '';
applyKey();
}
function applyKey() {
const has = keyText.textContent !== '';
const root = document.documentElement;
root.classList.toggle('knokey', !keyOn);
root.classList.toggle('kquiet', keyOn && PHONE());
keyRow.classList.toggle('on', has && keyOn);
relayout();
}
// ---- THE MEASUREMENTS COME OFF THE PICTURE ----------------------------------------------------
// Every figure the drawing used to carry along its cables is in the number boxes and in the answer.
// What stays on the picture is what a wiring drawing IS: the boxes, the cables, which is + and
// which is -, and which module is which. "numbers on" puts them back for anybody who wants them.
const keepMark = m => { const t = String((m && m.text) || '');
return !/\d/.test(t) || /^M\d+$/.test(t) || /^INV/.test(t); };
function filterDrawing(d) {
if (!d || !d.marks) return d;
if (!d.__marksAll) d.__marksAll = d.marks;
d.marks = numbersOn ? d.__marksAll : d.__marksAll.filter(keepMark);
return d;
}
function applyMarks() {
try { if (typeof sldShapes !== 'undefined' && sldShapes) filterDrawing(sldShapes); } catch (_) {}
hideWordy(); kick();
}
// the few loose words that carry a length go with the numbers; they are all in the answer
function hideWordy() {
const layer = $('sldnames'); if (!layer) return;
for (const s of layer.querySelectorAll('span:not(.pinned)')) {
const hide = !numbersOn && /\d/.test(s.textContent || '') && /\bm\b|\bV\b/.test(s.textContent || '');
s.style.display = hide ? 'none' : '';
}
}
try {
if (typeof stringDrawing === 'function') {
const origDraw = stringDrawing;
window.stringDrawing = function (g) { return filterDrawing(origDraw(g)); };
}
} catch (_) {}
// ---- THE BAND STOPS AT THE TOP OF THE SHEET ---------------------------------------------------
// The programs cartridge measures the free part of the screen and lays the row into it. Its rule
// for a window across the width is "go under it", which is right for a window at the top and would
// put the whole drawing behind a sheet at the bottom. One line is added: a sheet takes the bottom.
try {
if (typeof shapeBand === 'function') {
const origBand = shapeBand;
window.shapeBand = function (reserve) {
const b = origBand(reserve);
// THE DRAWING STARTS AT THE TOP OF THE SCREEN. The band used to begin under the chip row; the
// row is one small button now, so the picture runs to just under the red line and the button
// sits over its corner. Nothing else is up there to hide.
const s = isOpen() ? sayEl.getBoundingClientRect() : null;
const across = !!s && s.width > innerWidth * 0.7 && s.top < innerHeight * 0.5;
if (!across) { const red = document.querySelector('#sldnames span.danger');
const rb = red ? red.getBoundingClientRect().bottom : 0;
b.top = Math.max(6, Math.round(rb) + 4); }
// AT LEAST 85 PER CENT OF THE SCREEN IS THE DRAWING'S. What the key reserves under the picture
// is given back, because the key is one line above the bar now and not a block under it.
const want = Math.round(innerHeight * 0.85);
if (b.bottom - b.top < want) b.top = Math.max(6, b.bottom - want);
if (isOpen() && PHONE()) { const r = sayEl.getBoundingClientRect();
if (r.height > 8 && r.top > 80) b.bottom = Math.min(b.bottom, r.top - 8); }
if (b.bottom - b.top < 120) b.top = Math.max(14, b.bottom - 120);
return b;
};
}
} catch (_) {}
// THE KEY AND THE LOOSE WORDS ARE READ AFTER THE PAGE HAS DRAWN, which is when that layer exists.
try { if (window.__wafer && window.__wafer.onDraw) window.__wafer.onDraw.add(function () {
try { const layer = $('sldnames');
if (layer && layer.childElementCount !== (layer.dataset.kseen | 0)) {
layer.dataset.kseen = layer.childElementCount; readKey(); hideWordy(); }
} catch (_) {}
}); } catch (_) {}
addEventListener('resize', () => { applyKey(); fixChips(); });
addEventListener('orientationchange', () => { applyKey(); fixChips(); });
markState(); applyKey(); relayout();
// the foot is a different height now, so the disc is fitted into what is left, not left as it was
try { if (typeof atHome !== 'undefined' && atHome && typeof homeCamera === 'function' && typeof SPACE !== 'undefined' && SPACE) {
const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; tween = null; } } catch (_) {}
kick();
}
if (document.readyState === 'loading') addEventListener('DOMContentLoaded', () => { try { boot(); } catch (e) { console.error('the dressing did not go on: ' + (e && e.stack ? e.stack : e)); } });
else { try { boot(); } catch (e) { console.error('the dressing did not go on: ' + (e && e.stack ? e.stack : e)); } }
})();Kuiper Controls
A JavaScript file in the drawing folder of GlobalGrid2050 that loads tracked (`loadTracked`) and calculates planar distances. Served with the page at https://globalgrid2050.com/kuiper-grid/drawing/.
interactionglobalgrid2050 / kuiper-grid/drawing/kuiper-controls.js · lines 1–104 of 104 · Entry point · pattern goToKey (shared by 13 files)
- What it does
- It draws its content. Defines loadTracked, raiseFlags, lightPath, goToKey. Side effects: changes the web page (DOM).
- 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).
- Downstream impact
- Used directly by 2 files: Renderer (globalgrid2050, https://globalgrid2050.com/kuiper-grid/drawing/renderer.html); Releases — Kuiper Shell Page (globalgrid2050, https://globalgrid2050.com/kuiper-grid/i0073/releases/003100000000-kuiper-shell/). Reached from 111 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/drawing/.
- What it achieves
- It loads tracked (`loadTracked`) and is built from the raise flags helper (`raiseFlags`) and the light path helper (`lightPath`). A cartridge of the Kuiper shell. It responds to pointerup, pointercancel and wheel events.
- Why it matters
- Loaded by the Renderer page at https://globalgrid2050.com/kuiper-grid/drawing/renderer.html and 1 other page.
- Application
- globalgrid2050 · kuiper-grid/drawing · script
- Uses
- none found
- Used by
- loaded by Renderer (script src), loaded by Releases — Kuiper Shell Page (script src)
- Produces
- loadTracked, raiseFlags, lightPath, goToKey
- Defines here
- loadTracked, raiseFlags, lightPath, goToKey
- 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/drawing/kuiper-controls.js:1-104 · blob 9d16ee46815e7c140cedb26bc45461f985942945 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: production_core
'use strict';
// kuiper-controls.js - a cartridge of the Kuiper shell. Cut from the whole page with no change of behaviour;
// replaced, when it is, by a newer file the pointer names and the composer checks by its hash.
// ------------------------------------------------------------------ where a page is on the wafer
// A PAGE IS NOT A PLACE. tools/where.py asks git which commits touched a path and cosmos/wafer.tsv
// where each of those commits landed, and writes both files this reads. The page then does the same
// key arithmetic over its own commit table and the test is that the two agree exactly, commit by
// commit, key by key. Neither is trusted: they are made to contradict each other or agree.
async function loadTracked(){
if (tracked) return tracked;
const [tt, cc] = await Promise.all([tsv('cosmos/tracked.tsv'), tsv('cosmos/tracked-commits.tsv')]);
tracked = { paths:tt.map(p => ({ repo:p[0], path:p[1], use:p[2], in_git:+p[3], on_wafer:+p[4],
lines_in_those_commits:+p[5], k0:+p[6], k1:+p[7], first:p[8], last:p[9] })),
commits:cc.map(p => ({ path:p[0], sha:p[1], unix:+p[2], lines:+p[3], k0:+p[4], k1:+p[5] })) };
return tracked;
}
function raiseFlags(idx){
pathFlags.fill(0); for (const i of idx) pathFlags[i] = 1;
gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, pathTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, TW, pathRows, 0, gl.RED, gl.FLOAT, pathFlags);
gl.activeTexture(gl.TEXTURE0);
}
async function lightPath(name, quiet){
endIsolate();
const T = await loadTracked();
const row = T.paths.find(p => p.path.toLowerCase() === String(name).toLowerCase());
if (!row) return { error:'no tracked page of that name: run tools/where.py --five', asked_for:name };
const want = T.commits.filter(c => c.path === row.path);
const idx = [], missing = [], disagreed = [];
for (const c of want) { const i = bySha.get(c.sha);
if (i === undefined) { missing.push(c.sha); continue; }
if (commits[i].k0 !== c.k0 || commits[i].k1 !== c.k1) disagreed.push({ sha:c.sha, page:[commits[i].k0, commits[i].k1], tool:[c.k0, c.k1] });
idx.push(i); }
idx.sort((a, b) => a - b);
litRepo = -1; litK = [-1,-1]; litCi = null; newFrom = -1; flash = 0; pulse = -1; target = null;
litPath = { row, idx }; raiseFlags(idx);
tween = null; cx = 0; cy = 0; zoom = (Math.min(cv.width, cv.height)/2)*0.80/Math.sqrt(SPACE); draw();
if (!quiet) { card.style.display = 'block';
card.classList.remove('sheet'), card.innerHTML = 'PATH:' + row.path + '\n' + row.repo + '\n\n' + fmt(row.on_wafer) + ' commits touched it, of ' + fmt(row.in_git)
+ ' git knows\nfirst ' + row.first + ', last ' + row.last
+ '\n\nkeys ' + fmt(row.k0) + ' .. ' + fmt(row.k1)
+ '\n' + fmt(row.lines_in_those_commits) + ' lines in those commits, which is the commits, not the page'
+ '\n\nuse: ' + row.use; }
return { row, idx, want:want.length, missing, disagreed };
}
// THE TEST. ?selftest=path:<name>. The count the page lit must be the count the tool counted, every
// sha the tool named must be a commit this wafer holds, and every key must match to the digit. Then
// the picture: at a zoom where one of those commits is more than a pixel wide, that pixel must
// actually carry the path's light, or the page is lighting a set it never drew.
addEventListener('pointerup', e => {
// A DOT OF THE BODY IS STILL A PIECE OF WORK. It has moved; what it is has not.
if (drag && moved < 4 && iso && body && body.shown && !bodyAnim) { let bj = -1, bd = Math.max(12, bodyDotPx() + 8);
for (let j = 0; j < body.n; j++) { const x = (body.pos[2*j] - cx) * zoom + innerWidth / 2, y = innerHeight / 2 - (body.pos[2*j+1] - cy) * zoom;
const d = Math.hypot(x - e.clientX, y - e.clientY); if (d < bd) { bd = d; bj = j; } }
if (bj >= 0) { const c0 = commits[iso.idx[bj]]; show(address(c0.k0 + Math.floor((c0.k1 - c0.k0) / 2))); pointerGone(e); return; } }
if (drag && moved < 4 && N) { const [wx, wy] = toWorld(e.clientX, e.clientY), r = Math.hypot(wx, wy);
if (r*r < SPACE) { let k = zoom >= POINTS_FROM ? keyAt(wx, wy) : -1; const exact = k >= 0; if (!exact) k = Math.floor(r*r);
target = exact ? { x:keyPlace(k)[0], y:keyPlace(k)[1] } : null; show(address(k)); } }
pointerGone(e); });
addEventListener('pointercancel', pointerGone);
addEventListener('wheel', e => { const [wx, wy] = toWorld(e.clientX, e.clientY), f = e.deltaY < 0 ? 1.18 : 1/1.18;
zoom = Math.max(1e-4, Math.min(ZMAX, zoom*f)); cx = wx - (e.clientX - innerWidth/2)/zoom; cy = wy + (e.clientY - innerHeight/2)/zoom;
atHome = false; tween = null; dirty = true; }, { passive:true });
// the tap targets, so a phone can do everything the keyboard can
document.getElementById('keys').addEventListener('click', e => {
if (e.target.classList.contains('q')) { e.stopPropagation(); elFoot.classList.toggle('hints'); layout(); dirty = true; return; }
const k = e.target.getAttribute('data-k'); if (!k) return;
e.stopPropagation(); dispatchEvent(new KeyboardEvent('keydown', { key:k })); });
elTop.addEventListener('click', () => elTop.classList.toggle('open')); // the long subtitle, collapsed by default
// A LINK INSIDE THE CARD IS NOT A DISMISSAL, and neither is reading it: the card is put away with
// its own cross or with Escape, the way the wafer's card is.
card.addEventListener('click', e => {
const a = e.target.closest ? e.target.closest('a') : null;
if (a && a.hasAttribute('data-key')) { e.preventDefault(); goToKey(+a.getAttribute('data-key')); }
});
// GOING TO A KEY, from a link inside a card or from an address a reader arrived with. The camera
// flies, the dot is marked and its card opens: one way of arriving, however the reader got here.
function goToKey(k){
const a = address(k);
if (!a) return;
const p = keyPlace(k);
litK = [k, k + 1]; litCi = null; target = { x:p[0], y:p[1] };
show(a); flyTo(p[0], p[1], Math.max(zoom, 14)); dirty = true;
}
const gbox = document.getElementById('goto'), gin = document.getElementById('gotoin');
gin.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Escape') { gbox.style.display = 'none'; return; }
if (e.key !== 'Enter') return; gbox.style.display = 'none'; const raw = gin.value.trim(), q = raw.replace(/[ ,_]/g,'');
const mt = raw.match(/^(20\d\d)(?:-(\d\d))?(?:-(\d\d))?$/);
if (mt) { lightTime(+mt[1], mt[2] ? +mt[2] : 0, mt[3] ? +mt[3] : 0); return; }
const mnew = raw.toLowerCase().match(/^(?:show\s+)?new(?:\s+code)?(?:\s+(\d+)\s*h?)?$/);
if (mnew) { showNew(mnew[1] ? Number(mnew[1]) : 24); return; }
if (/^\d+$/.test(q)) goKey(Math.min(SPACE-1, Number(q)));
else { const r = repos.find(x => x.name.toLowerCase() === raw.toLowerCase()) || repos.find(x => x.name.toLowerCase().includes(raw.toLowerCase()));
if (r) { litRepo = r.i; target = null; card.style.display = 'none'; home(); dirty = true; } } });
addEventListener('keydown', e => { if (gbox.style.display === 'block') return;
if (e.key === 'd') { detail = !detail; dirty = true; }
else if (e.key === 'r' && N) { const j = Math.floor(Math.random()*N), c = commits[findBy('cum', j)]; goKey(c.k0 + (j - c.cum)); } // uniform over issued lines
else if (e.key === 'n' && N) showNew(24);
else if (e.key === '/') { e.preventDefault(); gbox.style.display = 'block'; gin.value = ''; gin.focus(); }
else if (e.key === 'Backspace') { e.preventDefault(); target = null; litRepo = -1; newFrom = -1; flash = 0; pulse = -1; litK = [-1,-1]; litCi = null; litPath = null; card.style.display = 'none';
// GATHERED WORK GOES HOME BEFORE THE LIGHT COMES BACK: the same rule run the other way, so a
// visitor sees that the body was made of work from all over the record and nothing else.
if (iso && body && body.shown && ASM && !(bodyAnim && bodyAnim.home)) { bodyAnim = { k:Math.max(0, body.k), t0:performance.now(), from:new Float32Array(body.pos), gap0:body.gap, phase:'move', home:true }; isoAnim = null; dirty = true; }
else { unisolate(true); home(); } } });Kuiper Pointer
A JavaScript file in the drawing folder of GlobalGrid2050 that works with pointer gone (`pointerGone`) and calculates planar distances. Served with the page at https://globalgrid2050.com/kuiper-grid/drawing/.
transformglobalgrid2050 / kuiper-grid/drawing/kuiper-pointer.js · lines 1–25 of 25 · Entry point · pattern pointerGone (shared by 28 files)
- What it does
- It calculates its inputs. Defines pinchNow, pointerGone.
- 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).
- Downstream impact
- Used directly by 1 file: Renderer (globalgrid2050, https://globalgrid2050.com/kuiper-grid/drawing/renderer.html). Reached from 110 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/drawing/.
- What it achieves
- It is built from the pinch now helper (`pinchNow`) and the pointer gone helper (`pointerGone`). Native Kuiper pointer runtime, extracted from the public tests cartridge. It responds to pointerdown and pointermove events.
- Why it matters
- Loaded by the Renderer page at https://globalgrid2050.com/kuiper-grid/drawing/renderer.html.
- Application
- globalgrid2050 · kuiper-grid/drawing · script
- Uses
- none found
- Used by
- loaded by Renderer (script src)
- Produces
- pinchNow, pointerGone
- Defines here
- pinchNow, pointerGone
- 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/drawing/kuiper-pointer.js:1-25 · blob f80b108a8a3718cfaa0aadd187cd9b3f12668bd6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: production_core
// Native Kuiper pointer runtime, extracted from the public tests cartridge. See SOURCE-PROVENANCE.json.
// TOUCH. Every pointer that is down is held in one map, so one finger drags and two pinch, and a
// mouse is just a pointer with one finger. The pinch keeps the world point between the fingers
// under the fingers, which is the same rule the wheel already obeys, so zooming in on a phone and
// on a desktop land on the same key.
const ZMAX = 60;
let drag = null, moved = 0, pinch = null;
const pts = new Map();
function pinchNow(){ const v = [...pts.values()], a = v[0], b = v[1];
return { d:Math.hypot(a.x-b.x, a.y-b.y), mx:(a.x+b.x)/2, my:(a.y+b.y)/2 }; }
cv.addEventListener('pointerdown', e => {
pts.set(e.pointerId, { x:e.clientX, y:e.clientY });
if (pts.size === 2) { const s = pinchNow(), w = toWorld(s.mx, s.my); pinch = { d0:s.d, z0:zoom, wx:w[0], wy:w[1] }; drag = null; moved = 99; }
else if (pts.size === 1) { drag = [e.clientX, e.clientY]; moved = 0; }
});
addEventListener('pointermove', e => {
if (pts.has(e.pointerId)) pts.set(e.pointerId, { x:e.clientX, y:e.clientY });
if (pinch && pts.size >= 2) { const s = pinchNow(); if (pinch.d0 > 1) {
zoom = Math.max(1e-4, Math.min(ZMAX, pinch.z0 * s.d / pinch.d0));
cx = pinch.wx - (s.mx - innerWidth/2)/zoom; cy = pinch.wy + (s.my - innerHeight/2)/zoom;
atHome = false; tween = null; dirty = true; } return; }
if (!drag) return; moved += Math.abs(e.clientX-drag[0]) + Math.abs(e.clientY-drag[1]);
cx -= (e.clientX-drag[0])/zoom; cy += (e.clientY-drag[1])/zoom; drag = [e.clientX, e.clientY];
atHome = false; tween = null; dirty = true; });
function pointerGone(e){ pts.delete(e.pointerId); if (pts.size < 2) pinch = null; if (pts.size === 0) drag = null; }