In this section
- Kuiper Programs render · globalgrid2050 / kuiper-grid/i0073/cartridges/005200000000-kuiper-programs.js lines 701–1249
Kuiper Programs
A JavaScript module in the cartridges folder of GlobalGrid2050 covering solar, cables, substations and transformers, using SHA-256, and uses data from the faraday repository.
renderglobalgrid2050 / kuiper-grid/i0073/cartridges/005200000000-kuiper-programs.js · lines 701–1249 of 1249 (continued from section 1257) · Not reached from any entry point (candidate for review) · pattern findByCommand (shared by 45 files)
- What it does
- It draws solar, cables, substations and transformers. Defines 106 functions or classes, including closestPair, blackSky, nameInLines, makeBody, bodyTo. 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: solar, cables, substations, transformers, 400kV.
- Inputs & outputs
- In: data source: faraday data; JSON file current.json. Voltage levels named: 400kV.
- What it achieves
- It makes body (`makeBody`), sets tag (`setTag`) and merges menu (`mergeMenu`). A cartridge of the Kuiper shell. Its code works with 400 kV, 50 kW and 500 kW. It responds to click, keydown and pointerdown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · kuiper-grid/i0073/cartridges · JavaScript module
- Uses
- Faraday — Index Page (estate URL), Wafer Development Environment — Proof S0004 Page (estate URL), ./fire.js
- Used by
- none found
- Produces
- closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet, setTag
- Defines here
- $, showSay, shutSay, setStack, runsHere, fill, shownList, refresh, drawChips, findByCommand, runIt, openApps, stop, c0, fireCommand, el, bold, open, label, table, sldNetwork, sldPieces, line, ring, sldLayout, SYMBOL, sldFinal, makeSldBody, nameLayer, amberName
- 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/i0073/cartridges/005200000000-kuiper-programs.js:701-1249 · blob ab147308adb799a89cc04caed0a50561b4270798 · 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 (!document.body) return;
const st = document.createElement('style');
// The wafer's own rules, kept: the bottom of the screen is a stack, not a pile.
st.textContent = ':root{--cmd:56px;--footh:34px;--stack:calc(var(--cmd) + var(--footh) + 8px);--egh:0px;--above:calc(var(--stack) + 8px)}'
// THE BAR IS INSIDE THE SHELL'S OWN FOOT, not fixed on top of it. The wafer's bar is the last thing at
// the bottom of its page, under the one line that says what the page is not, and the Kuiper's shell
// measures its foot to decide how big the disc is and where the work card sits. A bar fixed over the
// foot was a bar the shell could not see: the card checks read the card as off the screen at 390. So
// the same component is built as the last child of #foot, and the picker as its first, and everything
// the shell does about height goes on working.
+ '#pilot{display:flex;gap:8px;margin-top:7px;padding-top:7px;border-top:1px solid #1b2030}'
+ '#pilot input{flex:1;min-width:0;font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#11151f;color:#cfe3f2;'
+ 'border:1px solid #1b2030;border-radius:6px;padding:.6rem .9rem}'
+ '#pilot input:focus{outline:1px solid #5ec8f2}'
+ '#pilot input::placeholder{color:#5b6377}'
+ '#eg{margin:0 0 6px auto;width:fit-content;max-width:min(30rem,88vw);background:#0e121b;border:1px solid #1b2030;'
+ 'border-radius:8px;padding:.45rem .7rem;display:flex;flex-direction:column;gap:4px}'
+ '#eg label{font:11px ui-monospace,Menlo,Consolas,monospace;letter-spacing:.08em;text-transform:uppercase;color:#8b93a7}'
+ '#eg select{font:12px ui-monospace,Menlo,Consolas,monospace;background:#11151f;color:#cfe3f2;border:1px solid #1b2030;border-radius:6px;padding:.45rem .7rem;max-width:44vw}'
+ '#presets{position:fixed;left:12px;top:12px;z-index:19;display:flex;gap:6px;flex-wrap:wrap;max-width:min(62vw,calc(100% - 24px))}'
+ '#presets button{font:11px/1.6 ui-monospace,Menlo,Consolas,monospace;color:#8b93a7;background:#0b0e14;border:1px solid #232a3a;'
+ 'border-radius:4px;padding:2px 9px;cursor:pointer}'
+ '#presets button:hover,#presets button:focus-visible{color:#e6e9f0;border-color:#4a5573;outline:none}'
+ '#say{position:fixed;left:50%;top:20px;transform:translateX(-50%);width:min(72ch,84vw);'
+ 'max-height:calc(100vh - var(--footh) - 56px);min-width:280px;min-height:64px;background:#0e121bf2;'
+ 'border:1px solid #1b2030;border-radius:8px;padding:0;font:14px/1.5 ui-monospace,Menlo,Consolas,monospace;color:#cfe3f2;'
+ 'z-index:21;resize:both;overflow:hidden;display:none;flex-direction:column}'
+ '#say.open{display:flex}'
+ '#say.max{left:12px;top:12px;right:12px;bottom:calc(var(--footh) + 12px);transform:none;width:auto;max-height:none;height:auto}'
+ '#say.min{height:auto!important;max-height:none;resize:none;width:min(48ch,84vw)} #say.min #saybody{display:none}'
+ '#saybar{display:flex;align-items:center;gap:6px;padding:4px 8px;border-bottom:1px solid #1b2030;background:#11151f;'
+ 'cursor:move;user-select:none;font-size:11px;color:#8b93a7;letter-spacing:.06em;text-transform:uppercase}'
+ '#saybar span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}'
+ '#saybar button{font:12px ui-monospace,Menlo,Consolas,monospace;background:#0e121b;color:#cfe3f2;border:1px solid #1b2030;'
+ 'border-radius:4px;width:24px;height:22px;cursor:pointer;padding:0}'
+ '#saybar button:hover,#saybar button:focus-visible{border-color:#5ec8f2;outline:none}'
+ '#saybody{padding:.8rem 1.1rem;overflow:auto;flex:1}'
+ '#saybody b{color:#5ec8f2;font-weight:600}#saybody i{color:#f2b05e;font-style:normal}'
+ '#saybody p{margin:.45rem 0}#saybody .dimtext{color:#8b93a7;font-size:12px;line-height:1.45}'
+ '#saybody table{border-collapse:collapse;width:100%;margin:.5rem 0}'
+ '#saybody td{padding:2px 0;border-bottom:1px solid #1b2030;font-size:12.5px}#saybody td+td{text-align:right;color:#fff}'
+ '#saybody code{display:block;background:#11151f;border:1px solid #1b2030;border-radius:4px;padding:4px 7px;color:#cfe3f2;'
+ 'margin:6px 0;font-size:11.5px;word-break:break-all}'
+ '#saybody .more,#saybody .edit{background:none;border:0;color:#8b93a7;font:inherit;font-size:11.5px;text-decoration:underline;cursor:pointer;padding:4px 0}'
+ '#saybody .more:hover,#saybody .edit:hover{color:#5ec8f2}'
+ '#saybody #apps{display:flex;flex-wrap:wrap;gap:6px;margin:.4rem 0 .2rem}'
+ '#saybody .viewrow{display:flex;flex-wrap:wrap;gap:6px;margin:.4rem 0 .2rem}'
+ '#saybody .viewrow 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}'
// THE BOTTOM OF THE SCREEN IS A STACK, NOT A PILE - the wafer's own rule, and the Kuiper's card has to
// obey it too. On a phone the shell puts its work card at the very bottom, where the bar and the
// examples picker now are, and the page's own card checks caught it: four of them read the card as
// off the screen. The card is lifted to the top of the measured stack instead.
+ '@media (max-width:700px){#pilot input{font-size:16px;min-height:44px}'
+ '#eg{margin-left:0;width:auto;max-width:none;padding:.35rem .6rem}#eg label{font-size:10px}#eg select{max-width:none;min-height:40px}'
+ '#presets{max-width:calc(100% - 24px)}#presets button{min-height:32px;padding:4px 9px}'
+ '#say{left:8px;right:8px;transform:none;width:auto;max-height:52vh}'
+ '#saybar button{width:32px;height:30px}}';
document.head.append(st);
// ---- the window ------------------------------------------------------------------------------
const sayEl = document.createElement('div'); sayEl.id = 'say';
sayEl.setAttribute('role', 'dialog'); sayEl.setAttribute('aria-label', 'the answer');
sayEl.innerHTML = '<div id="saybar"><span id="saytitle">card</span>'
+ '<button id="saymin" type="button" title="minimise" aria-label="minimise">–</button>'
+ '<button id="saymax" type="button" title="maximise" aria-label="maximise">▢</button>'
+ '<button id="sayclose" type="button" title="close" aria-label="close">×</button></div>'
+ '<div id="saybody"></div>';
document.body.append(sayEl);
const $ = id => document.getElementById(id);
const sayBody = $('saybody');
const showSay = (title, nodes) => { $('saytitle').textContent = title;
sayBody.replaceChildren(...nodes); sayEl.classList.remove('min'); sayEl.classList.add('open'); };
const shutSay = () => sayEl.classList.remove('open', 'max', 'min');
sayOpen = showSay;
$('saymin').onclick = e => { e.stopPropagation(); sayEl.classList.toggle('min'); };
$('saymax').onclick = e => { e.stopPropagation(); sayEl.classList.remove('min'); sayEl.classList.toggle('max'); };
$('sayclose').onclick = e => { e.stopPropagation(); shutSay(); };
$('saybar').ondblclick = () => sayEl.classList.toggle('min');
(() => { let d = null; const bar = $('saybar');
bar.addEventListener('pointerdown', e => { if (e.target.tagName === 'BUTTON' || sayEl.classList.contains('max')) return;
const r = sayEl.getBoundingClientRect(); d = { x:e.clientX - r.left, y:e.clientY - r.top };
sayEl.style.transform = 'none'; sayEl.style.left = r.left + 'px'; sayEl.style.top = r.top + 'px';
try { bar.setPointerCapture(e.pointerId); } catch (_) {} });
bar.addEventListener('pointermove', e => { if (!d) return;
sayEl.style.left = Math.max(0, Math.min(innerWidth - 60, e.clientX - d.x)) + 'px';
sayEl.style.top = Math.max(0, Math.min(innerHeight - 40, e.clientY - d.y)) + 'px'; });
// THE WINDOW LETS GO. The wafer's own bar releases on pointerup; it is released on cancel and on a
// lost capture too, because a window that keeps the mouse is the fault this night began with.
for (const ev of ['pointerup', 'pointercancel', 'lostpointercapture']) bar.addEventListener(ev, () => { d = null; });
})();
// ---- the chips, the picker and the bar -------------------------------------------------------
const chips = document.createElement('nav'); chips.id = 'presets'; chips.setAttribute('aria-label', 'presets');
const eg = document.createElement('div'); eg.id = 'eg';
const egLabel = document.createElement('label'); egLabel.htmlFor = 'egs';
egLabel.textContent = 'examples: pick one, it fires, the bar keeps its name';
const egs = document.createElement('select'); egs.id = 'egs'; egs.setAttribute('aria-label', 'choose an example sentence');
eg.append(egLabel, egs);
const pilot = document.createElement('div'); pilot.id = 'pilot';
const pin = document.createElement('input'); pin.id = 'pin'; pin.type = 'text'; pin.autocomplete = 'off'; pin.spellcheck = false;
pin.placeholder = 'type a sentence or a command: tree of 12 · on its export limit · the most solar that fits · apps · help';
pin.setAttribute('aria-label', 'type a sentence or a command');
pilot.append(pin);
const foot = document.getElementById('foot');
document.body.append(chips);
if (foot) { foot.prepend(eg); foot.append(pilot); } else document.body.append(eg, pilot);
// the applications and the four view commands keep their own elements; they are not on the face,
// they are what the window shows when it is asked for them
const appsEl = document.getElementById('apps');
const holder = document.createElement('div'); holder.style.display = 'none'; document.body.append(holder);
if (appsEl) holder.append(appsEl);
const viewRow = document.createElement('div'); viewRow.className = 'viewrow';
for (const [k, words] of [['n', 'new code'], ['r', 'random line'], ['/', 'find'], ['Backspace', 'whole view']]) {
const b = document.createElement('button'); b.type = 'button'; b.textContent = words; b.setAttribute('data-k', k);
b.addEventListener('click', () => { shutSay(); dispatchEvent(new KeyboardEvent('keydown', { key:k })); });
viewRow.append(b);
}
holder.append(viewRow);
// THE STACK IS MEASURED, NOT GUESSED, exactly as the wafer measures it, so the picker never sits on
// the bar and the window never sits on the picker.
const setStack = () => { const r = document.documentElement.style;
r.setProperty('--footh', Math.ceil((foot ? foot.getBoundingClientRect().height : 0)) + 'px');
if (typeof layout === 'function') layout(); };
setStack();
try { if (foot) new ResizeObserver(setStack).observe(foot); } catch (_) {}
addEventListener('resize', setStack); addEventListener('orientationchange', setStack);
// ---- the list itself -------------------------------------------------------------------------
// WHETHER A COMMAND DRAWS, WITHOUT WAITING FOR THE ENGINE TO BE THERE. The bar is built as soon as this
// file runs, which can be before window.FIRE exists; asking the engine and giving up on the exception
// left the chips and the picker empty, and the page's own check caught it. The engine answers when it
// is there, and the name is read off the command itself when it is not.
function runsHere(c){
try { if (window.FIRE && window.FIRE.parse) return FIRE_DRAWS.includes(window.FIRE.parse(c.command).name); } catch (_) {}
const m = /^fire\s+([a-z][a-z-]*)/i.exec(String((c && c.command) || ''));
return !!m && FIRE_DRAWS.includes(m[1].toLowerCase());
}
let ALL = dedupeCommands(FIRE_FALLBACK.filter(runsHere)), PINS = curateCommands(ALL, PICKER_SHOWN);
let SAID = 'the few tests kept inside this page are listed while the published list is read';
const fill = list => { egs.replaceChildren(new Option(list.length ? '— choose an example sentence —' : '— nothing matches —', ''));
for (const c of list) { const o = new Option(plainName(c), c.command); o.title = c.sentence || ''; egs.append(o); } };
const shownList = () => { const q = pin.value.trim();
if (!q || /^fire\s+\S/i.test(q)) return PINS.slice(0, PICKER_SHOWN);
return dedupeCommands(searchCommands(ALL, q)).slice(0, PICKER_SHOWN); };
const refresh = () => { fill(shownList()); };
const drawChips = () => { chips.replaceChildren();
for (const c of PINS.slice(0, CHIPS_SHOWN)) { const b = document.createElement('button'); b.type = 'button';
b.textContent = chipWords(c); b.title = c.sentence || plainName(c);
b.addEventListener('click', e => { e.stopPropagation(); runIt(c); }); chips.append(b); }
const a = document.createElement('button'); a.type = 'button'; a.textContent = 'apps'; a.id = 'chipapps';
a.addEventListener('click', e => { e.stopPropagation(); openApps(); }); chips.append(a); };
function findByCommand(cmd){ return ALL.find(c => c.command === cmd) || PINS.find(c => c.command === cmd) || null; }
// CHOOSING A PRESET FIRES IT, AND THE BAR KEEPS ITS NAME, NOT ITS JSON.
function runIt(c){ const cmd = typeof c === 'string' ? c : c.command;
const rec = typeof c === 'string' ? findByCommand(cmd) : c;
pin.value = rec ? plainName(rec) : '';
fireCommand(cmd, rec);
}
closeFireMenu = () => { egs.selectedIndex = 0; };
function openApps(){
const wrap = [];
const h = document.createElement('p'); h.innerHTML = '<b>The applications</b>'; wrap.push(h);
if (appsEl) wrap.push(appsEl);
const p2 = document.createElement('p'); p2.innerHTML = '<b>The view</b>'; wrap.push(p2, viewRow);
const note = document.createElement('p'); note.className = 'dimtext'; note.textContent = SAID; wrap.push(note);
showSay('apps', wrap);
}
loadFireConfig(FIRE_CONFIG).then(r => {
if (r.ok) {
const listed = dedupeCommands(r.commands.filter(runsHere));
if (listed.length) {
const dropped = r.commands.filter(runsHere).length - listed.length;
ALL = listed;
const pinned = listed.filter(c => typeof c.pin === 'number').sort((a, b) => a.pin - b.pin);
PINS = pinned.length ? pinned : curateCommands(listed, PICKER_SHOWN);
SAID = listed.length + ' tests, list ' + r.generation + ', fetched with no cache and hashed here'
+ (dropped ? '; ' + dropped + ' repeats of another test left out' : '');
} else SAID = 'the published list holds nothing this device can run, so the few kept in this page are listed';
} else SAID = 'the published list was not used (' + r.reason + '), so the few kept in this page are listed';
drawChips(); refresh();
}).catch(e => { SAID = 'the published list was not used (' + (e && e.message ? e.message : e) + '), so the few kept in this page are listed';
drawChips(); refresh(); });
drawChips(); refresh();
// KEYS TYPED IN THE BAR STAY IN THE BAR, and a press inside the window never reaches the disc behind
// it. Escape is not a key they keep: it closes the window and hands the keyboard back.
const stop = e => {
if (e.type === 'keydown' && e.key === 'Escape') { e.stopPropagation(); shutSay(); pin.blur(); return; }
e.stopPropagation();
};
for (const x of [pin, eg, chips, sayEl]) for (const ev of ['keydown', 'keyup', 'keypress', 'pointerdown', 'mousedown', 'touchstart', 'wheel', 'click']) x.addEventListener(ev, stop);
egs.addEventListener('change', e => { const v = e.target.value; if (v) runIt(v); e.target.selectedIndex = 0; });
pin.addEventListener('input', refresh);
pin.addEventListener('keydown', e => {
if (e.key === 'Escape') { shutSay(); pin.blur(); return; }
if (e.key !== 'Enter') return;
const q = pin.value.trim(); if (!q) return;
if (/^fire\s+\S/i.test(q)) { fireCommand(q, findByCommand(q)); return; }
if (/^apps?$/i.test(q)) { openApps(); return; }
if (/^help$/i.test(q)) { const p = document.createElement('p');
p.innerHTML = '<b>How this bar works</b>'; const q2 = document.createElement('p'); q2.className = 'dimtext';
q2.textContent = 'Type what you want to see in plain words - "tree of 12", "on its export limit", "the most solar that fits" - and press Enter: the first test that matches runs here, on your device, and the dots draw its network. Or pick one from the examples above. Type "apps" for the applications. Every command can be typed in full; press "show the command" in any answer to see and change … [line shortened here: 419 characters; full line on GitHub]
showSay('help', [p, q2]); return; }
const first = shownList()[0];
if (first) runIt(first);
else { const p = document.createElement('p'); p.innerHTML = '<b>Nothing matches</b>';
const d = document.createElement('p'); d.className = 'dimtext';
d.textContent = 'No test in the published list has all of those words in it. Try fewer words, or a shape: chain, star, tree, sub-board.';
showSay('nothing matches', [p, d]); }
});
addEventListener('keydown', e => { if (e.key === 'Escape' && sayEl.classList.contains('open')) { e.preventDefault(); shutSay(); pin.blur(); } });
if (typeof layout === 'function') layout();
// ?fire=<command> still runs a command on arrival: every firing is a link
try { const q = new URLSearchParams(location.search).get('fire'); if (q) setTimeout(() => fireCommand(/^fire\s/i.test(q) ? q : 'fire ' + q), 600); } catch (_) {}
}
// SOMETHING IS ON THE SCREEN AT ONCE. The bar is built as soon as this file runs, not after the whole
// record has arrived, so a visitor on a slow line has the bar and the chips while the megabyte loads.
if (document.readyState === 'loading') addEventListener('DOMContentLoaded', () => { try { makeFireBar(); } catch (e) { console.error('the bar was not built: ' + (e && e.stack ? e.stack : e)); } });
else { try { makeFireBar(); } catch (e) { console.error('the bar was not built: ' + (e && e.stack ? e.stack : e)); } }
let lastFire = null;
const c0 = text => { try { return window.FIRE.parse(text).inputs; } catch (_) { return {}; } };
// THE FIGURES A READER ACTUALLY WANTS, in the order an engineer would read them out. Everything else is
// behind MORE: the card used to be a table of fourteen rows and a paragraph, which is a page, not an answer.
const CARD_FIRST = ['connection point kw', 'lowest volts pu', 'highest volts pu', 'worst transformer pct', 'busiest cable amps',
'p poc kw', 'worst tx pct', 'export limit kw'];
function fireCommand(text, rec){
if (closeFireMenu) { try { closeFireMenu(); } catch (_) {} }
const F = (typeof window !== 'undefined' && window.FIRE) || null;
const el = (tag, cls, t) => { const e = document.createElement(tag); if (cls) e.className = cls; if (t !== undefined) e.textContent = t; return e; };
const bold = t => { const p = document.createElement('p'); const b = document.createElement('b'); b.textContent = t; p.append(b); return p; };
const open = (title, nodes) => { if (sayOpen) sayOpen(title, nodes); };
let out;
try { if (!F) throw new Error('the commands did not load'); out = F.fire(text); }
catch (e) { open('not run', [bold('Not run'), el('p', 'dimtext', String(e.message || e))]);
lastFire = { ran:false, error:String(e.message || e) }; return lastFire; }
if (!out.ran) { open('not run', [bold('Not run'),
el('p', 'dimtext', 'No command called "' + out.name + '" runs here yet. These do: ' + F.names.join(', ') + '.')]);
lastFire = { ran:false, name:out.name }; return lastFire; }
const title = rec ? plainName(rec) : out.family;
const nodes = [bold(rec ? plainName(rec) : out.family), el('p', null, out.said)];
const rows = [];
for (const [k, v] of Object.entries(out.numbers)) { if (v && typeof v === 'object') for (const [k2, v2] of Object.entries(v)) rows.push([k + ' ' + k2, v2]); else rows.push([k, v]); }
const label = k => k.replace(/_/g, ' ');
const lead = [], rest = [];
for (const r of rows) (CARD_FIRST.includes(label(r[0])) ? lead : rest).push(r);
while (lead.length < 4 && rest.length) lead.push(rest.shift());
const table = list => { const tb = document.createElement('table');
for (const [k, v] of list) { const tr = document.createElement('tr');
tr.append(el('td', null, label(k)), el('td', null, v === null ? 'none' : String(v))); tb.append(tr); }
return tb; };
nodes.push(table(lead.slice(0, 4)));
// THE COMMAND IS SHOWN ONLY WHEN IT IS ASKED FOR, and then it can be changed and fired again.
const hidden = document.createElement('div'); hidden.style.display = 'none';
hidden.append(table(lead.slice(4).concat(rest)), el('p', 'dimtext', 'How: ' + out.how));
const code = el('code', null, text); hidden.append(el('p', 'dimtext', 'The command that ran:'), code);
const edit = el('button', 'edit', 'put this command in the bar, to change a number and fire it again'); edit.type = 'button';
edit.addEventListener('click', () => { const b = document.getElementById('pin'); if (b) { b.value = text; b.focus(); } });
hidden.append(edit);
hidden.append(el('p', 'dimtext', 'Every input is a public estimate. It runs here and nothing you type leaves this device. An estimate, not a study; provided as is, without warranty of any kind.'));
const more = el('button', 'more', 'more, and show the command'); more.type = 'button';
more.addEventListener('click', () => { const on = hidden.style.display === 'none';
hidden.style.display = on ? 'block' : 'none'; more.textContent = on ? 'less' : 'more, and show the command'; });
nodes.push(more, hidden);
open(title, nodes);
lastFire = { ran:true, name:out.name, family:out.family, numbers:out.numbers };
try { const fp = FIRE_PROGRAM;
if (out.name === 'site-pulse' || out.name === 'network') { fp.sld = out.name === 'network' ? { kind:'network', net:out.net, solved:out.solved, inputs:c0(text) } : c0(text); if (typeof unisolate === 'function' && iso) unisolate(true);
programs.push(fp); try { isolate('fire'); } finally { const at = programs.indexOf(fp); if (at >= 0) programs.splice(at, 1); } } // THE DOTS DRAW THE NETWORK OF THIS COMMAND
else if (programs.find(p => p.name === 'tests')) isolate('tests'); } catch (e) { console.warn('fire: the dots did not respond', e); }
return lastFire;
}
// ===== THE SINGLE LINE DIAGRAM, DRAWN BY THE DOTS ================================================
// A site pulse has a real network: grid, connection point, intake cable, busbar, generator, feeders, transformers, loads, solar.
// The lines of the repository that holds the tests leave their places and BECOME that diagram: one dot a line of code, placed along
// the busbar, the feeders and the transformer rings. Then the two pulses of the method run on it: currents summed back to the
// grid, volts out from it; what is over a limit ends amber; what is disconnected ends dark. The engine computes (FIRE.sitePulse.solve);
// the dots show and switch. Values ride in a uniform array read by dot number, so the shell's one draw call is unchanged.
const SLD_MAX = 896; // 224 four-number uniforms: inside what every WebGL 2 device must offer
let sldNow = null, sldLoop = 0;
function sldNetwork(inputs){
const SP = window.FIRE && window.FIRE.sitePulse; if (!SP) return null;
const sc = SP.SCENARIOS[inputs.scenario]; if (!sc) return null;
const site = inputs.site || SP.standardSite(), share = inputs.load_share === undefined ? 1 : inputs.load_share;
const r = SP.solve(site, sc[1], sc[2], sc[3], share), c = SP.CANDIDATE;
return { site, r, c, pvShare:sc[1], genOn:sc[2], off:sc[3], over: Math.max(0, -r.p_poc_kw) > site.export_limit_kw };
}
// every piece of the drawing: a list of [x0,y0,x1,y1] lines and [cx,cy,r] rings, each with a tag and its distance from the grid
function sldPieces(net){
const P = [], subs = net.site.subs, n = subs.length, kmMax = Math.max(...subs.map(s => s.km));
const line = (tag, d, x0, y0, x1, y1) => P.push({ tag, d, kind:'line', x0, y0, x1, y1, len:Math.hypot(x1 - x0, y1 - y0) });
const ring = (tag, d, cx, cy, r) => P.push({ tag, d, kind:'ring', cx, cy, r, len:2 * Math.PI * r });
ring('grid', 0, 0, 0.88, 0.07);
line('poc', 0.07, 0, 0.80, 0, 0.62); line('poc', 0.25, -0.07, 0.61, 0.07, 0.61);
line('board', 0.27, 0, 0.59, 0, 0.44);
line('bus', 0.45, -0.92, 0.42, 0.92, 0.42); line('bus', 0.45, -0.92, 0.395, 0.92, 0.395);
line('gen', 0.45, -0.62, 0.445, -0.62, 0.57); ring('gen', 0.6, -0.62, 0.65, 0.075);
subs.forEach((s, i) => { const x = n === 1 ? 0 : -0.8 + 1.6 * i / (n - 1), dx = 0.45 + Math.abs(x), L = 0.12 + 0.2 * s.km / kmMax;
const t = 'f' + s.n, yT = 0.37 - L;
line(t, dx, x, 0.37, x, yT);
ring(t, dx + L, x, yT - 0.06, 0.05); ring(t, dx + L + 0.1, x, yT - 0.175, 0.05);
const yL = yT - 0.235; line(t, dx + L + 0.2, x, yL, x, yL - 0.12);
line('load' + s.n, dx + L + 0.32, x - 0.045, yL - 0.13, x, yL - 0.2); line('load' + s.n, dx + L + 0.32, x + 0.045, yL - 0.13, x, yL - 0.2);
if (s.n === net.site.pv_on) { const sx = x + (x > 0.5 ? -0.13 : 0.13); line('pv', dx + L + 0.26, x + Math.sign(sx - x) * 0.015, yL - 0.05, sx - Math.sign(sx - x) * 0.05, yL - 0.05);
ring('pv', dx + L + 0.4, sx, yL - 0.05, 0.045); ring('pv', dx + L + 0.4, sx, yL - 0.05, 0.016); } });
return P;
}
function sldLayout(net, m){
const P = net.kind === 'network' ? netPieces(net.net) : sldPieces(net), total = P.reduce((t, p) => t + p.len, 0), s = total / m;
// A SYMBOL IS NOT A LENGTH. Dots were handed out in proportion to how long each piece is, so a cable
// hundreds of units long took hundreds of dots and the generator - one short stub and a circle two
// hundredths of the drawing across - got the floor of five, which is a faint pentagon nobody can find.
// The Supervisor looked at a tree of twelve with its generator RUNNING and could not see a generator.
// The pieces that are SYMBOLS (the grid, the generator, the solar) are given enough dots to read as the
// thing they are; the long cables give them up, which costs a cable nothing.
const SYMBOL = t => t === 'grid' || t === 'gen' || t.startsWith('pv');
let counts = P.map(p => Math.max(SYMBOL(p.tag) ? (p.kind === 'ring' ? 16 : 6) : (p.kind === 'ring' ? 5 : 2), Math.round(p.len / s)));
let diff = m - counts.reduce((a, b) => a + b, 0);
const order = P.map((p, i) => i).sort((a, b) => P[b].len - P[a].len); // the rounding is taken up by the longest pieces
for (let q = 0; diff !== 0 && q < 10 * m; q++) { const i = order[q % order.length]; if (diff > 0) { counts[i]++; diff--; }
else if (counts[i] > (SYMBOL(P[i].tag) ? (P[i].kind === 'ring' ? 16 : 6) : 3)) { counts[i]--; diff++; } }
const unit = new Float32Array(2 * m), tag = new Array(m), dist = new Float32Array(m); let j = 0, dMax = 0;
P.forEach((p, i) => { for (let q = 0; q < counts[i] && j < m; q++, j++) { const u = (q + 0.5) / counts[i];
if (p.kind === 'line') { unit[2*j] = p.x0 + (p.x1 - p.x0) * u; unit[2*j+1] = p.y0 + (p.y1 - p.y0) * u; dist[j] = p.d + p.len * u; }
else { const a = 2 * Math.PI * u + i; unit[2*j] = p.cx + p.r * Math.cos(a); unit[2*j+1] = p.cy + p.r * Math.sin(a); dist[j] = p.d + p.r; }
tag[j] = p.tag; dMax = Math.max(dMax, dist[j]); } });
for (; j < m; j++) { unit[2*j] = unit[0]; unit[2*j+1] = unit[1]; tag[j] = 'grid'; }
return { unit, tag, dist, dMax, spacing:s };
}
// what each dot ends as: 0..1 brightness, 2 = over a limit (amber), -1 = disconnected (dark)
function sldFinal(net, tag){
const r = net.r, c = net.c, vs = Object.values(r.V), vBad = Math.max(...vs) > c.volts_high_pu || Math.min(...vs) < c.volts_low_pu;
return tag.map(t => {
if (t === 'grid') return 0.95; if (t === 'poc') return net.over ? 2 : 0.95; if (t === 'board') return 0.9; if (t === 'bus') return vBad ? 2 : 0.95;
if (t === 'gen') return net.genOn ? 1 : -1; if (t === 'pv') return net.pvShare > 0 ? 1 : -1;
const k = +t.replace(/\D/g, ''), load = r.tx_loading_pct['lv' + k];
if (load === undefined) return -1; // a disconnected substation
if (t[0] === 'l') return (net.off.includes('pvload') && k === net.site.pv_on) ? -1 : 0.85;
return load > 100 ? 2 : 0.3 + 0.65 * Math.min(1, load / 100); });
}
function makeSldBody(st){
const net = (st.prog.sld && st.prog.sld.kind === 'network') ? st.prog.sld : sldNetwork(st.prog.sld || {}); if (!net) return null;
// EVERY DOT OF THE SKY CAN BE CALLED: the diagram's dots are lines of code from the whole record, evenly through all the keys,
// so they leave from everywhere on the disc at once.
// EVERY DOT OF THE DIAGRAM IS A REAL LINE OF CODE, AND SAYS WHOSE. The shell answers a tap on dot j with the piece of work
// st.idx[j]; a diagram has more dots than the application has pieces of work, so a tap found nothing, threw, and never let the
// mouse go. So dot j is given the piece of work that issued its key (commits are in key order: a halving search), its place is
// that work's own middle line, and a tap on the diagram opens that work.
const m = SLD_MAX, from = new Float32Array(2 * m), owner = new Array(m);
for (let j = 0; j < m; j++) { const key = Math.floor((j + 0.5) * SPACE / m); let lo = 0, hi = commits.length - 1;
while (lo < hi) { const mid = (lo + hi) >> 1; if (commits[mid].k1 > key) hi = mid; else lo = mid + 1; }
owner[j] = lo; const c0 = commits[lo], p = keyPlace(Math.min(Math.max(key, c0.k0), Math.max(c0.k0, c0.k1 - 1))); from[2*j] = p[0]; from[2*j+1] = p[1]; }
st.idx = owner;
const lay = sldLayout(net, m), R = Math.sqrt(SPACE), frac = BODY_RADIUS_MAX, to = new Float32Array(2 * m);
// THE DRAWING FILLS THE DISC. Each drawing was laid out in its own units and then scaled by how far its
// farthest point lay FROM THE ORIGIN, which is not where the drawing is: a network whose busbar sits high
// and whose loads hang low was pushed off centre and left using about half the disc, with a ring of empty
// dark around it. Its own extent is found, its middle is moved to the middle of the disc, and it is blown
// up until its farthest dot is at the rim. Nothing about the drawing changes but its size and its place.
{ let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
for (let j = 0; j < m; j++) { const x = lay.unit[2*j], y = lay.unit[2*j+1];
if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }
const mx = (x0 + x1) / 2, my = (y0 + y1) / 2;
let far = 0;
for (let j = 0; j < m; j++) { const d = Math.hypot(lay.unit[2*j] - mx, lay.unit[2*j+1] - my); if (d > far) far = d; }
const k = far > 1e-9 ? 0.97 / far : 1;
for (let j = 0; j < m; j++) { lay.unit[2*j] = (lay.unit[2*j] - mx) * k; lay.unit[2*j+1] = (lay.unit[2*j+1] - my) * k; }
lay.spacing *= k; }
for (let q = 0; q < 2 * m; q++) to[q] = lay.unit[q] * R * frac;
const gap = closestPair(lay.unit) * R * frac;
sldNow = { net, lay, final:net.kind === 'network' ? netFinal(net, lay.tag) : sldFinal(net, lay.tag), t0:0, vals:new Float32Array(SLD_MAX) };
nameLayer();
sldNames = makeSldNames(lay, net);
{ const amber = addAmberName(lay, sldNow.final); if (amber) sldNames.push(amber); }
return { n:m, from, pos:new Float32Array(from), states:[{ shape:'sld', to, gap, frac, hold:0, unresolved:false }], k:-1, gap:0, shown:false, sld:true, sldGap:lay.spacing * R * frac };
}
// ===== THE FEWEST WORDS A DIAGRAM NEEDS ==========================================================
// A picture of nine substations with no word on it anywhere is a pattern, not a single line diagram, to
// anybody who is not an engineer. Three words are added, and no more: GRID where the grid is, what the
// connection point is doing (exports 50 kW, or imports 1,649 kW) where the connection point is, and the
// name of whatever ended AMBER, because amber is the only thing on the picture that is a warning and a
// colour nobody can look up. They are drawn as plain text over the canvas, no boxes and no lines, at the
// place the drawing itself puts them, and they appear only once the dots have landed.
let sldNames = null;
function nameLayer(){
let el = document.getElementById('sldnames');
if (!el) { el = document.createElement('div'); el.id = 'sldnames';
const st = document.createElement('style');
st.textContent = '#sldnames{position:fixed;inset:0;z-index:4;pointer-events:none}'
+ '#sldnames span{position:absolute;transform:translate(-50%,-50%);color:#cfeaf2;font-size:10.5px;letter-spacing:.06em;'
+ 'white-space:nowrap;text-shadow:0 0 6px #000,0 0 3px #000}'
+ '#sldnames span.warn{color:#ffb454}'
+ '@media (max-width:700px){#sldnames span{font-size:9.5px}}';
document.head.append(st); document.body.append(el); }
return el;
}
const AMBER_WORDS = { bus:'volts outside the band', poc:'over the export limit', grid:'', board:'' };
function amberName(tag){
if (!tag) return '';
if (AMBER_WORDS[tag] !== undefined) return AMBER_WORDS[tag];
if (tag.startsWith('tx')) return 'transformer over its rating';
if (tag.startsWith('load')) return 'volts outside the band at the load';
if (tag.startsWith('hv')) return 'volts outside the band on this cable';
if (tag.startsWith('f')) return 'transformer over its rating';
return '';
}
// WHAT THE CONNECTION POINT IS DOING, in the words the bench itself uses: minus is out to the grid.
function pocWords(net){
let kw = null;
if (net.kind === 'network' && net.solved) kw = net.solved.p;
else if (net.r && net.r.p_poc_kw !== undefined) kw = net.r.p_poc_kw;
if (kw === null || kw === undefined || !isFinite(kw)) return '';
const n = Math.abs(Math.round(kw));
return (kw < 0 ? 'exports ' : 'imports ') + (typeof fmt === 'function' ? fmt(n) : String(n)) + ' kW';
}
// the places, in the drawing's own units AFTER it has been fitted to the disc, so they follow the dots
function makeSldNames(lay, net){
const want = [], first = tag => { for (let j = 0; j < lay.tag.length; j++) if (lay.tag[j] === tag) return j; return -1; };
const at = j => ({ x:lay.unit[2*j], y:lay.unit[2*j+1] });
const g = first('grid'); if (g >= 0) want.push(Object.assign(at(g), { text:'GRID', dy:-0.10, warn:false }));
const pc = first('poc'), words = pocWords(net);
if (pc >= 0 && words) want.push(Object.assign(at(pc), { text:words, dy:0, dx:0.22, warn:false }));
return want;
}
function addAmberName(lay, final){
const seen = new Set();
for (let j = 0; j < final.length; j++) {
if (final[j] !== 2) continue;
const words = amberName(lay.tag[j]);
if (!words || seen.has(words)) continue;
seen.add(words);
return { x:lay.unit[2*j], y:lay.unit[2*j+1], text:words, dy:-0.06, warn:true };
}
return null;
}
// THE WORDS FOLLOW THE PICTURE. They are put where they belong every time the camera moves, and nowhere
// else: no animation loop of their own is started, because a loop that runs for ever to move three words
// is a loop that runs for ever.
function placeSldNames(){
const el = document.getElementById('sldnames');
if (!el) return;
if (!sldNames || !body || !body.sld || !body.shown || bodyAnim || !sldNow) { el.replaceChildren(); return; }
const R = Math.sqrt(SPACE), frac = BODY_RADIUS_MAX;
if (el.childElementCount !== sldNames.length) {
el.replaceChildren(...sldNames.map(n => { const sp = document.createElement('span');
sp.textContent = n.text; if (n.warn) sp.className = 'warn'; return sp; }));
}
sldNames.forEach((n, i) => { const sp = el.children[i]; if (!sp) return;
const wx = (n.x + (n.dx || 0)) * R * frac, wy = (n.y + (n.dy || 0)) * R * frac;
sp.style.left = ((wx - cx) * zoom + innerWidth / 2) + 'px';
sp.style.top = (innerHeight / 2 - (wy - cy) * zoom) + 'px'; });
}
addEventListener('wheel', placeSldNames, { passive:true });
addEventListener('pointermove', placeSldNames);
addEventListener('pointerup', placeSldNames);
addEventListener('resize', placeSldNames);
addEventListener('orientationchange', placeSldNames);
function sldUniforms(){
if (!BP) return; gl.useProgram(BP);
const on = !!(body && body.sld && sldNow);
gl.uniform1f(gl.getUniformLocation(BP, 'u_sld'), on ? 1 : 0);
if (on) gl.uniform4fv(gl.getUniformLocation(BP, 'u_val[0]'), sldNow.vals);
}
function sldTick(now){
sldLoop = 0; if (!(body && body.sld && sldNow)) return;
const S = sldNow, m = body.n, arrived = !bodyAnim && body.shown;
if (arrived && !S.t0) S.t0 = now;
const t = S.t0 ? (now - S.t0) / 1000 : -1, T = 1.5, D = S.lay.dMax, w = D * 0.06;
for (let j = 0; j < m; j++) { const d = S.lay.dist[j], f = S.final[j]; let v;
if (t < 0) v = 0.55; // in flight: every dot alike
else if (t < T) { const front = D * (1 - t / T); v = Math.abs(d - front) < w ? 1.25 : (d > front ? 0.5 : 0.22); } // PULSE ONE: back toward the grid
else if (t < 2 * T) { const front = D * (t / T - 1); v = Math.abs(d - front) < w ? 1.25 : (d < front ? f : 0.22); } // PULSE TWO: out from the grid, leaving the answer
else v = f;
S.vals[j] = v; }
sldUniforms(); placeSldNames(); dirty = true;
if (t < 2 * T + 0.2) sldLoop = requestAnimationFrame(sldTick);
}
function sldStart(){ if (!sldLoop) sldLoop = requestAnimationFrame(sldTick); }
// ===== ANY RADIAL NETWORK, DRAWN BY THE DOTS: fire network {"seed":N} ==========================
// The generator's network (a star, a chain, a tree, sub-boards) laid out as a single line diagram: the busbar on top, every
// substation in its own column, a branch leaving its parent's tee sideways and then down, so no two lines ever share a place.
function netPieces(net){
const P = [], subs = net.subs, n = subs.length, kids = {}; subs.forEach(s => (kids[s.parent] = kids[s.parent] || []).push(s.n));
const col = {}, depth = {}; let c = 0;
(function walk(p, d){ for (const k of (kids[p] || [])) { col[k] = c++; depth[k] = d; walk(k, d + 1); } })(0, 1);
const maxD = Math.max(...Object.values(depth)), dy = Math.min(0.17, 1.05 / maxD), X = k => n === 1 ? 0 : -0.9 + 1.8 * col[k] / (n - 1), Y = k => 0.37 - dy * (depth[k] - 1) - 0.05;
const line = (tag, d, x0, y0, x1, y1) => { const len = Math.hypot(x1 - x0, y1 - y0); if (len > 1e-6) P.push({ tag, d, kind:'line', x0, y0, x1, y1, len }); return d + len; };
const ring = (tag, d, cx, cy, r) => P.push({ tag, d, kind:'ring', cx, cy, r, len:2 * Math.PI * r });
ring('grid', 0, 0, 0.9, 0.06); let d0 = line('poc', 0.06, 0, 0.83, 0, 0.66); line('poc', d0, -0.06, 0.65, 0.06, 0.65); d0 = line('board', d0, 0, 0.63, 0, 0.45);
line('bus', d0, -0.95, 0.43, 0.95, 0.43); line('bus', d0, -0.95, 0.405, 0.95, 0.405);
const teeD = { 0: d0 };
const sym = (tagT, tagL, tagP, d, x, y, s, r) => { // transformer, load and any solar, hanging from (x, y)
let dd = line(tagT, d, x, y - 0.012, x, y - 0.04); ring(tagT, dd, x, y - 0.04 - r, r); ring(tagT, dd + 0.05, x, y - 0.04 - 3 * r - 0.012, r);
const yl = y - 0.04 - 4 * r - 0.024; dd = line(tagT, dd + 0.1, x, yl, x, yl - 0.05);
line(tagL, dd, x - 0.03, yl - 0.06, x, yl - 0.105); line(tagL, dd, x + 0.03, yl - 0.06, x, yl - 0.105);
if (s.pv_kw > 0) { const sx = x + 0.06; line(tagP, dd, x + 0.012, yl - 0.025, sx - 0.03, yl - 0.025); ring(tagP, dd + 0.05, sx, yl - 0.025, 0.026); ring(tagP, dd + 0.05, sx, yl - 0.025, 0.009); }
if (net.generator_at === s.n && net.generator_kw > 0) { const gx = x - 0.06; line('gen', dd, x - 0.012, yl - 0.025, gx + 0.03, yl - 0.025); ring('gen', dd + 0.05, gx, yl - 0.025, 0.028); } };
if (net.generator_at === 0 && net.generator_kw > 0) { line('gen', d0, -0.75, 0.455, -0.75, 0.56); ring('gen', d0 + 0.15, -0.75, 0.62, 0.06); }
const r = Math.min(0.032, 0.6 / n / 2.4 + 0.012);
(function walk(p){ for (const k of (kids[p] || [])) { const s = subs[k - 1], x = X(k), y = Y(k), t = 'hv' + k; let d;
if (p === 0) d = line(t, teeD[0] + Math.abs(x), x, 0.393, x, y);
else { d = line(t, teeD[p], X(p) + 0.012, Y(p), x, Y(p)); d = line(t, d, x, Y(p) - 0.012, x, y); }
teeD[k] = d; sym('tx' + k, 'load' + k, 'pv' + k, d, x, y, s, r); walk(k); } })(0);
let far = 0; for (const p of P) far = Math.max(far, p.kind === 'ring' ? Math.hypot(p.cx, p.cy) + p.r : Math.max(Math.hypot(p.x0, p.y0), Math.hypot(p.x1, p.y1)));
const k = 0.98 / Math.max(0.98, far); // the whole drawing inside the disc
for (const p of P) { if (p.kind === 'ring') { p.cx *= k; p.cy *= k; p.r *= k; } else { p.x0 *= k; p.y0 *= k; p.x1 *= k; p.y1 *= k; } p.len *= k; }
return P;
}
function netFinal(model, tag){
const net = model.net, r = model.solved, e = r.each, c = window.FIRE.topo.C, over = Math.max(0, -r.p) > net.export_limit_kw, aMax = Math.max(1e-9, r.amps);
const bad = v => v > c.volts_high_pu || v < c.volts_low_pu;
return tag.map(t => { if (t === 'grid') return 0.95; if (t === 'poc') return over ? 2 : 0.95; if (t === 'board') return 0.9; if (t === 'bus') return bad(e.volts.board) ? 2 : 0.95;
if (t === 'gen') return model.inputs.generator ? 1 : -1;
const k = t.replace(/\D/g, '');
if (t.startsWith('pv')) return (model.inputs.solar === undefined ? 1 : model.inputs.solar) > 0 ? 1 : -1;
if (t.startsWith('load')) return bad(e.volts['lv' + k]) ? 2 : 0.85;
if (t.startsWith('tx')) return e.tx['lv' + k] > 100 ? 2 : 0.3 + 0.65 * Math.min(1, e.tx['lv' + k] / 100);
return bad(e.volts['hv' + k]) ? 2 : 0.3 + 0.65 * Math.min(1, e.amps['hv' + k] / aMax); });
}
// ===== THE POINTER IS ALWAYS LET GO ==============================================================
// THE FAULT: the shell answers a tap on body dot j with commits[iso.idx[j]] and calls pointerGone(e)
// AFTERWARDS. A drawn diagram has 896 dots and an application has however many pieces of work it has,
// so for most dots iso.idx[j] was undefined, reading .k0 of undefined threw, pointerGone never ran,
// the pointer stayed in the map and the disc went on following a mouse whose button was up. The cure
// above gives every diagram dot its own piece of work, so nothing throws. THIS is the second belt:
// whatever any handler does, the pointer is let go. A listener added here runs AFTER the shell's own
// (they are on the same target in the same phase, and an exception in one listener never stops the
// next), so a throw anywhere in the shell's answer can no longer leave a button pressed for ever.
// It is registered from a timer so that it is registered after the shell's, whatever the load order.
setTimeout(function(){
var net = function(e){ try { if (typeof pointerGone === 'function') pointerGone(e); } catch (_) {} };
addEventListener('pointerup', net);
addEventListener('pointercancel', net);
addEventListener('pointerout', function(e){ if (e.pointerType === 'mouse' && !e.relatedTarget && e.buttons === 0) net(e); });
addEventListener('blur', function(){ try { if (typeof pts !== 'undefined' && pts.clear) pts.clear();
if (typeof drag !== 'undefined') drag = null; if (typeof pinch !== 'undefined') pinch = null; } catch (_) {} });
}, 0);