GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / globalgrid2050 / testcode/202609052023/atlas/source

Testcode — Code Map and 9 more files

A JavaScript file in GlobalGrid2050 that draws blocks, families and names, and uses data from raw.githubusercontent.com and the stars repository. Served with the page at https://globalgrid2050.com/testcode/202609141754/code-map/.

687 lines of JavaScript and HTML from globalgrid2050, in 10 files. Topic: Maps, GIS and field navigation. Section 508 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. Menu Bar render · globalgrid2050 / testcode/202609052023/atlas/source/menu-bar.js lines 1401–1478
  2. Map Controls Layout render · globalgrid2050 / testcode/202609060228/atlas/map-controls-layout.js lines 1–48
  3. Project GeoJSON geodesy · globalgrid2050 / testcode/202609060334/pipeline/assets/202609060334-project-geojson.mjs lines 1–21
  4. Wider GeoJSON geodesy · globalgrid2050 / testcode/202609060340/pipeline/assets/202609060340-wider-geojson.mjs lines 1–18
  5. Teleprinter Bootstrap render · globalgrid2050 / testcode/202609060503/atlas/teleprinter-bootstrap.js lines 1–21
  6. Testcode — Atlas Page render · globalgrid2050 / testcode/202609060537/atlas/index.html lines 1–122
  7. Testcode — Code Map render · globalgrid2050 / testcode/202609141754/code-map/core.js lines 1–203
  8. Testcode — Code Map Page render · globalgrid2050 / testcode/202609141754/code-map/index.html lines 1–24
  9. Code Map — V02 Radial Hierarchy Page render · globalgrid2050 / testcode/202609141754/code-map/v02-radial-hierarchy/index.html lines 1–75
  10. Code Map — V03 Block Map Page render · globalgrid2050 / testcode/202609141754/code-map/v03-block-map/index.html lines 1–77

Menu Bar

A JavaScript file in the source folder of GlobalGrid2050 that draws engine graph and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

Set aside from the main view: 100% of its lines are the same as sandbox/202609052028/atlas/source/menu-bar.js (testcode), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Menu Bar; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9984 to testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609052028/atlas/source/menu-bar.js:1-1478 187a2694983ffab91c0421fb5c5d9bddf35804b7
  • sha256 3d805dc834c31366134d225d54de3120b4894bf3c5c8063a951d9f421155dce4
  • target sha256 faee41963dd9778ef1f74c220e24bd39ab3b627261701fb0d7d0ef8e972ce61b
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderglobalgrid2050 / testcode/202609052023/atlas/source/menu-bar.js · lines 1401–1478 of 1478 · version 2026-09-05 20:23 (continued from section 506) · Not reached from any entry point (candidate for review) · pattern appendEngineModules (shared by 10 files)

What it does
It draws engine graph. Defines 42 functions or classes, including array, cleanText, layerKey, layerLabel, layerGroup. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; JSON file engine-graph.json; form fields (user input). Out: downloaded file gridatlas-; canvas drawing.
What it achieves
It cleans text (`cleanText`), syncs attrib clearance (`syncAttribClearance`) and syncs layer (`syncLayer`). V9.94 proved that the conventional menu is the right shape and the wrong implementation can still strand the product. It responds to click, keydown and afterprint events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609052023/atlas/source · script
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
none found
Produces
array, cleanText, layerKey, layerLabel, layerGroup, inventory, required, installStyle, syncAttribClearance, closeAll, syncLayer, syncAll
Defines here
loudFailure, start
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609052023/atlas/source/menu-bar.js:1401-1478 · blob 1328d2ab84f9ee4003ba44715f037b036e48cd87 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: duplicate_candidate

    if (typeof MutationObserver === 'function') {
      observer = new MutationObserver(function () {
        adoptLate(doc);
        syncAll();
      });
      observer.observe(doc.body, { childList: true, subtree: true, characterData: true });
    }
    return true;
  }

  state.install = function () { return install(document); };
  state.closeAll = closeAll;

  function loudFailure(doc) {
    if (state.installed || doc.getElementById(FAILURE_ID)) return;
    var found = inventory(doc);
    state.failure = 'menu not installed: expected 60 engine + 3 Pipeline News layer controls; found '
      + found.engine.length + ' + ' + found.pipeline.length;
    if (window.console && typeof window.console.error === 'function') {
      window.console.error('[GRIDATLAS MENU] ' + state.failure);
    }
    var alert = doc.createElement('div');
    alert.id = FAILURE_ID;
    alert.setAttribute('role', 'alert');
    alert.textContent = state.failure + '. Original controls remain available.';
    alert.style.cssText = 'position:fixed;left:8px;right:8px;top:8px;z-index:10030;'
      + 'padding:8px;background:#280b0b;color:#ffd0d0;border:1px solid #b44;'
      + 'font:11px/1.4 monospace';
    (doc.body || doc.documentElement).appendChild(alert);
  }

  function start() {
    /* Cartridge proofs and prerenderers can provide a deliberately partial
       document. Treat that exactly like any other missing dependency: publish
       the refusal and leave the owner's interface untouched. In particular,
       do not start the 40-second browser retry loop against a non-DOM stub. */
    if (!document.documentElement || typeof document.createElement !== 'function') {
      state.failure = 'menu not installed: full document unavailable';
      return;
    }
    var probe = document.createElement('div');
    if (!probe || typeof probe.setAttribute !== 'function' || !probe.classList) {
      state.failure = 'menu not installed: full DOM element API unavailable';
      return;
    }
    if (install(document)) return;
    if (typeof window.setInterval !== 'function'
      || typeof window.clearInterval !== 'function') return;
    timer = window.setInterval(function () {
      state.tries += 1;
      if (install(document)) {
        window.clearInterval(timer);
        timer = null;
      } else if (state.tries >= MAX_TRIES) {
        window.clearInterval(timer);
        timer = null;
        loudFailure(document);
      }
    }, 250);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', start, { once: true });
  } else {
    start();
  }
}());

;(() => {
 const style=document.createElement('style');style.textContent=`
 .search-bar-wrapper{display:flex!important;position:absolute!important;top:64px!important;left:12px!important;right:12px!important;width:auto!important;max-width:520px!important;z-index:1100!important;margin:0!important;transform:none!important}
 .search-bar-wrapper input{min-height:48px!important;font-size:16px!important;width:100%!important;box-sizing:border-box}
 .testcode-identity{position:fixed;right:12px;bottom:64px;z-index:2000;background:#08161fee;color:#aaf6ff;padding:8px;border:1px solid #36616a;font:12px monospace;text-decoration:none}
 @media print{.testcode-identity,.search-bar-wrapper{display:none!important}}
 `;document.head.append(style);
 const link=document.createElement('a');link.className='testcode-identity';link.href='/testcode/202609052023/';link.textContent='Test Code · 202609052023';document.body.append(link);
})();

Map Controls Layout

A JavaScript module in the atlas folder of GlobalGrid2050. It is built from the mount map controls layout helper (`mountMapControlsLayout`) and the reflect step (`reflect`).

renderglobalgrid2050 / testcode/202609060228/atlas/map-controls-layout.js · lines 1–48 of 48 · version 2026-09-06 02:28 · Not reached from any entry point (candidate for review) · pattern reflect (shared by 17 files)

What it does
It draws its content. Defines mountMapControlsLayout, reflect. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 2 files: Teleprinter Bootstrap (globalgrid2050); Teleprinter Bootstrap (testcode).
What it achieves
Layout-only successor: preserve the existing tool, Layers and menu handlers.
Why it matters
Imported by Teleprinter Bootstrap, from Testcode.
Application
globalgrid2050 · testcode/202609060228/atlas · JavaScript module
Uses
none found
Used by
imported by Teleprinter Bootstrap (import), imported by Teleprinter Bootstrap (import)
Produces
mountMapControlsLayout
Defines here
mountMapControlsLayout, reflect
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060228/atlas/map-controls-layout.js:1-48 · blob 2d118ba5bf8fcfff25623d823eec021ecc4385c6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
/** Layout-only successor: preserve the existing tool, Layers and menu handlers. */
export function mountMapControlsLayout(doc = document) {
  const style = doc.createElement('style');
  style.id = 'atlas-map-controls-layout';
  style.textContent = `
#codex-tool-layers{top:auto!important;right:12px!important;bottom:calc(max(12px,env(safe-area-inset-bottom)) + 52px)!important;z-index:1000!important;gap:6px!important;max-width:calc(100vw - 24px)!important}
#codex-tool-layers>button{background:var(--atlas-control-bg,#0d1117)!important;color:var(--atlas-control-fg,#7fe3d0)!important;border:1px solid var(--atlas-control-border,#2b3a44)!important;border-radius:3px;font:600 12px/1.25 ui-monospace,SFMono-Regular,Menlo,monospace!important;min-height:44px;cursor:pointer}
#codex-tool-layers>button:hover{filter:brightness(1.2)}
#codex-tool-layers>button:focus-visible{outline:2px solid var(--atlas-control-fg,#7fe3d0);outline-offset:2px}
body:has(#gridatlas-menu-bar button[aria-expanded="true"]) #codex-tool-layers{visibility:hidden!important;pointer-events:none!important}
html body .search-bar-wrapper[data-testcode-search="persistent"]{width:min(640px,calc(100vw - 32px))!important;max-width:calc(100vw - 32px)!important}
html body .search-bar-wrapper[data-testcode-search="persistent"]>div{flex:1!important;min-width:0!important}
html body .search-bar-wrapper[data-testcode-search="persistent"] #search-input{width:100%!important;box-sizing:border-box!important}
@media(max-width:768px){
 #gridatlas-menu-bar .gm-panel{top:54px!important;max-height:calc(100dvh - 60px)!important;box-sizing:border-box;z-index:1}
 #codex-tool-layers{flex-direction:column!important;align-items:stretch!important;max-width:min(250px,calc(100vw - 24px))!important}
 html body .search-bar-wrapper[data-testcode-search="persistent"]{width:calc(100vw - 24px)!important;max-width:calc(100vw - 24px)!important}
}
`;
  doc.head.append(style);
  function reflect() {
    const tray = doc.getElementById('codex-tool-layers');
    const layers = doc.getElementById('gridatlas-dash-toggle');
    if (tray && layers) {
      const colors = getComputedStyle(layers);
      tray.style.setProperty('--atlas-control-bg', colors.backgroundColor);
      tray.style.setProperty('--atlas-control-fg', colors.color);
      tray.style.setProperty('--atlas-control-border', colors.borderTopColor);
    }
    for (const link of doc.querySelectorAll('a[href*="/spider_printer"]')) {
      if (/spider\s*printer/i.test(link.textContent)) link.textContent = 'Elements';
    }
    const generation = window.location.pathname.match(/\/testcode\/(\d{12})\/atlas\//)?.[1];
    if (generation) for (const link of doc.querySelectorAll('a[href]')) {
      if (/^Test Code\s*·\s*\d{12}$/.test(link.textContent.trim()) && !link.textContent.includes(generation)) {
        const instant = new Date(`${generation.slice(0,4)}-${generation.slice(4,6)}-${generation.slice(6,8)}T${generation.slice(8,10)}:${generation.slice(10,12)}:00Z`);
        const ukTime = new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',hour:'2-digit',minute:'2-digit',timeZoneName:'short'}).format(instant);
        link.textContent = 'Codex Atlas · ' + generation + ' UTC · ' + ukTime;
        link.title = 'Clear menus, tools above Layers, wider search, Elements';
        link.href = '/testcode/' + generation + '/';
      }
    }
  }
  const observer = new MutationObserver(reflect);
  observer.observe(doc.body, {childList:true,subtree:true});
  reflect();
  return () => { observer.disconnect(); style.remove(); };
}

Project GeoJSON

A JavaScript module in the assets folder of GlobalGrid2050 that works with the Renewable Energy Planning Database (REPD) register. It is built from the project geo JSON helper (`projectGeoJSON`).

geodesyglobalgrid2050 / testcode/202609060334/pipeline/assets/202609060334-project-geojson.mjs · lines 1–21 of 21 · version 2026-09-06 03:34

What it does
It calculates the REPD register. Defines projectGeoJSON.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register.
Inputs & outputs
Coordinate systems named: WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: Testcode — Pipeline (globalgrid2050). Reached from 21 other entry points, including Homepage V073 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v073.html); Homepage V074 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v074.html); Homepage V075 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v075.html).
What it achieves
Defines `projectGeoJSON`.
Why it matters
Imported by Testcode — Pipeline.
Application
globalgrid2050 · testcode/202609060334/pipeline/assets · JavaScript module
Uses
none found
Used by
imported by Testcode — Pipeline (import)
Produces
projectGeoJSON
Defines here
projectGeoJSON
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060334/pipeline/assets/202609060334-project-geojson.mjs:1-21 · blob 42d3480d5545123800b76a09a827600cc6c9a773 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: production_core
export function projectGeoJSON(projects, metadata = {}) {
  const seen=new Set(),positions=[];
  const features=projects.map(project=>{
    const ref=String(project.repd_ref ?? '');
    if(!/^\d+$/.test(ref)||seen.has(ref))throw Error('Export requires unique exact REPD identities.');
    if(typeof project.gg_project_id!=='string'||!project.gg_project_id)throw Error('Canonical project identity missing for REPD '+ref);
    seen.add(ref);
    const lon=project.longitude,lat=project.latitude;
    const located=project.geometry_status==='valid'&&Number.isFinite(lon)&&Number.isFinite(lat)&&Math.abs(lon)<=180&&Math.abs(lat)<=90;
    if(located)positions.push([lon,lat]);
    return {type:'Feature',id:project.gg_project_id,geometry:located?{type:'Point',coordinates:[lon,lat]}:null,properties:{
      repd_ref:ref,gg_project_id:project.gg_project_id,name:project.name,technology:project.technology,status:project.status,
      capacity:project.capacity_mw,capacity_unit:project.capacity_unit,operator:project.operator,county:project.county,
      repd_record_updated:project.repd_record_updated,geometry_status:project.geometry_status,
      geometry_note:located?'Published register coordinate; not a surveyed boundary.':'No usable register coordinate. The record is retained with null geometry.'
    }};
  });
  const result={type:'FeatureCollection',metadata:{...metadata,coordinate_reference:'WGS84 longitude, latitude',records:features.length,located:positions.length,null_geometry:features.length-positions.length,boundary:'Register map context only; not evidence of a grid connection or cadastral boundary.'},features};
  if(positions.length)result.bbox=[Math.min(...positions.map(p=>p[0])),Math.min(...positions.map(p=>p[1])),Math.max(...positions.map(p=>p[0])),Math.max(...positions.map(p=>p[1]))];
  return result;
}

Wider GeoJSON

A JavaScript module in the assets folder of GlobalGrid2050. It is built from the wider geo JSON helper (`widerGeoJSON`).

geodesyglobalgrid2050 / testcode/202609060340/pipeline/assets/202609060340-wider-geojson.mjs · lines 1–18 of 18 · version 2026-09-06 03:40 · Not reached from any entry point (candidate for review) · pattern numeric (shared by 5 files)

What it does
It calculates its inputs. Defines widerGeoJSON, numeric.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
Coordinate systems named: WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: Wider Fleet (globalgrid2050).
What it achieves
Defines `widerGeoJSON` and `numeric`.
Why it matters
Imported by Wider Fleet.
Application
globalgrid2050 · testcode/202609060340/pipeline/assets · JavaScript module
Uses
none found
Used by
imported by Wider Fleet (import)
Produces
widerGeoJSON
Defines here
widerGeoJSON, numeric
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060340/pipeline/assets/202609060340-wider-geojson.mjs:1-18 · blob ca0263e78e1b3dc2180287a6249bc38c67322914 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
export function widerGeoJSON(rows,metricLookup,metadata={}) {
  const numeric=value=>Number.isFinite(value)&&value>=0?value:null;
  const features=rows.map(row=>{
    const records=Array.isArray(row.repd_records)?row.repd_records.map(record=>({...record})):
      row.ref?[{ref:String(row.ref),status:row.s,operator:row.o}]:[];
    const refs=[...new Set(records.map(record=>String(record.ref??'')).filter(ref=>/^\d+$/.test(ref)))];
    const point=Array.isArray(row.ll)&&row.ll.length===2&&row.ll.every(Number.isFinite)&&Math.abs(row.ll[0])<=180&&Math.abs(row.ll[1])<=90;
    return {type:'Feature',geometry:point?{type:'Point',coordinates:row.ll.slice()}:null,properties:{
      site_name:row.n,technology:row.rt,capacity_mw:row.c,operator:row.o,county:row.cty,postcode:row.pc,
      repd_refs:refs,repd_records:records,statuses:[...new Set(records.map(record=>record.status).filter(Boolean))],
      observations:refs.map(ref=>({repd_ref:ref,grid_km:numeric(metricLookup(ref,'GRID')),sub_km:numeric(metricLookup(ref,'SUB'))})),
      geometry_note:point?'Published wider-fleet site point; shared group location is not a cadastral boundary.':'No published site point; null geometry retained.'
    }};
  });
  return {type:'FeatureCollection',metadata:{...metadata,site_groups:features.length,located:features.filter(feature=>feature.geometry).length,
    identity_scope:'Published wider-fleet site groups with exact REPD memberships. No core-spine joins or canonical GlobalGrid identity inferred.',
    coordinate_reference:'WGS84 longitude, latitude',distance_units:'km',boundary:'Mapped straight-line observations, not a cable route, connection offer or headroom.'},features};
}

Teleprinter Bootstrap

A JavaScript module in the atlas folder of GlobalGrid2050 that draws atlas pin, atlas code, solar and battery storage (BESS).

renderglobalgrid2050 / testcode/202609060503/atlas/teleprinter-bootstrap.js · lines 1–21 of 21 · version 2026-09-06 05:03 · Not reached from any entry point (candidate for review)

What it does
It draws atlas pin, atlas code, solar and battery storage (BESS). Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: solar, battery storage (BESS).
Inputs & outputs
In: JSON file atlas-source-pin.json; JSON file atlas-source-code.manifest.json.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609060503/atlas · JavaScript module
Uses
Controls (import), Layer Quick Controls (import), Layers Panel Policy (import), Layout Command (import), Host (import), Map Controls Layout (import)
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
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060503/atlas/teleprinter-bootstrap.js:1-21 · blob b3829f682e4f189f62dcaf6499f4efb8b5277678 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
import { mountTeleprinter } from '/testcode/202609051906/teleprinter/controls.js';
import { mountLayerQuickControls } from '/testcode/202609051906/teleprinter/layer-quick-controls.js';
mountLayerQuickControls();
import { mountLayersPanelPolicy } from '/testcode/202609051906/teleprinter/layers-panel-policy.js';
mountLayersPanelPolicy();
import { mountLayoutCommand } from '/testcode/202609051906/teleprinter/layout-command.js';
import { mountToolLayers } from '/testcode/202609052015/tool-layers/host.js';
mountToolLayers([{"id":"gis-sld-financial-sandbox","title":"GIS SLD Financial Sandbox","entry":"../layer-apps/solar-bess-topology-v7/gis-sld-financial-sandbox/index.html","owner":{"repository":"https://github.com/Ventusltd/gis-sld-sandbox.git","commit":"9fe7b2d920aaa11e95380de39b33fd98f04e9696","release":"202609051855","manifestSha256":"90190a0846717b5203305a8c08301fb26ed58e015b992272e0999272091a0  … [line shortened here: 2,720 characters; full line on GitHub]
const base = new URL('/testcode/202609051906/teleprinter/', location.origin);
try {
  const response = await fetch(new URL('atlas-source-pin.json', base), { cache: 'no-store', credentials: 'same-origin', redirect: 'error' });
  if (!response.ok) throw new Error('Source code is still being prepared.');
  const pin = await response.json();
  if (pin.generation !== '202609051906' || pin.app !== 'atlas' || !/^[a-f0-9]{40}$/.test(pin.commit) || pin.repository !== 'https://github.com/Ventusltd/testcode') throw new Error('The source code version could not be checked.');
  mountTeleprinter({ printButtons: 'button[data-gm-export]', appName: "GridAtlas", manifestUrl: new URL('atlas-source-code.manifest.json', base), textUrl: new URL('atlas-source-code.txt', base), expectedCommit: pin.commit, expectedRepository: pin.repository });
} catch (error) {
  const note = document.createElement('p'); note.setAttribute('role', 'status'); note.textContent = 'Print options: ' + error.message; document.body.append(note);
}

import {mountMapControlsLayout} from './map-controls-layout.js';
mountMapControlsLayout();

Testcode — Atlas Page

A web page in GlobalGrid2050 that validates atlas composition (`validateAtlasComposition`), using SHA-256. Published at https://globalgrid2050.com/testcode/202609060537/atlas/.

renderglobalgrid2050 / testcode/202609060537/atlas/index.html · lines 1–122 of 122 · version 2026-09-06 05:37 · Entry point · pattern validateAtlasComposition (shared by 2 files)

What it does
It draws its content. Defines invariant, escapeAttribute, sha256Hex, fail, validateAtlasComposition. Uses libraries ${escapeAttribute(blobUrl)}, ' + escapeAttribute(teleprinterUrl) + '. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file current.json. Out: web page.
Downstream impact
Used directly by 6 files: Homepage V088 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v088.html); Homepage V089 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v089.html); Homepage V090 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v090.html); Homepage V091 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v091.html); and 2 more. It is itself an entry point, published at https://globalgrid2050.com/testcode/202609060537/atlas/.
What it achieves
It validates atlas composition (`validateAtlasComposition`) and is built from the invariant step (`invariant`) and the escape attribute helper (`escapeAttribute`). Test Code Atlas. It reads `./current.json`.
Why it matters
Loaded by the Homepage V088 page at https://globalgrid2050.com/homepage_versions/homepage_v088.html and 5 other pages.
Application
globalgrid2050 · testcode/202609060537/atlas · page
Uses
${escapeAttribute(blobUrl)}, ' + escapeAttribute(teleprinterUrl) + '
Used by
linked from Homepage V088 (link), linked from Homepage V089 (link), linked from Homepage V090 (link), linked from Homepage V091 (link), linked from Homepage V093 (link), linked from Homepage V096 (link)
Produces
invariant, escapeAttribute, sha256Hex, fail, validateAtlasComposition
Defines here
invariant, escapeAttribute, sha256Hex, fail, validateAtlasComposition
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060537/atlas/index.html:1-122 · blob 0e893c50ec1d1a8f0317716521da0ec4894f4ed5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
<!doctype html>
<html lang="en">
<head><link rel="icon" href="data:,">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Test Code Atlas 202609060537</title>
  <style>
    html,body{height:100%;margin:0;background:#000;color:#00ffff;font:13px monospace}
    #gridatlas-loader{display:grid;place-items:center;height:100%;padding:24px;text-align:center}
    #gridatlas-loader strong{color:#ffae00}
  </style>
</head>
<body data-gridatlas-router="loading">
  <main id="gridatlas-loader"><div><strong>GRIDATLAS</strong><br>verifying immutable shell and cartridges…</div></main>
  <script type="module">
    const SCRIPT_CLOSE = '</scr' + 'ipt>';
    const loader = document.getElementById('gridatlas-loader');

    function invariant(condition, message) {
      if (!condition) throw new Error(message);
    }

    function escapeAttribute(value) {
      return String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
    }

    async function sha256Hex(bytes) {
      const digest = await crypto.subtle.digest('SHA-256', bytes);
      return [...new Uint8Array(digest)].map(value => value.toString(16).padStart(2, '0')).join('');
    }

    function fail(error) {
      console.error('[GRIDATLAS COMPOSER]', error);
      document.body.dataset.gridatlasRouter = 'failed';
      loader.innerHTML = `<div><strong>GRIDATLAS COMPOSITION FAILED</strong><br>${String(error?.message || error).replace(/[<>&]/g, '')}<br><small>The immutable shell was not changed.</small></div>`;
    }

    try {
      const currentResponse = await fetch('./current.json', { cache: 'no-store' });
      invariant(currentResponse.ok, `current.json HTTP ${currentResponse.status}`);
      const current = await currentResponse.json();
      invariant(current?.schema === 'gridatlas.current.v2', 'unsupported current.json schema');
      invariant(current?.architecture === 'IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES', 'architecture contract mismatch');
      invariant(Array.isArray(current.cartridge_order) && Array.isArray(current.cartridges), 'cartridge registry malformed');
/** A composition must name every core cartridge exactly once before loading the shell. */
function validateAtlasComposition(current) {
  const required=['streaming-parquet-bridge','uk-gazetteer-flyto','substation-intelligence','sld-sandbox'];
  const registry=current?.cartridges,order=current?.cartridge_order;
  if(!Array.isArray(registry)||!Array.isArray(order))throw Error('Cartridge registry and order must be arrays');
  const ids=registry.map(cartridge=>cartridge?.id);
  if(ids.some(id=>typeof id!=='string'||!id.trim())||order.some(id=>typeof id!=='string'||!id.trim()))throw Error('Every cartridge must have a non-empty ID');
  if(new Set(ids).size!==ids.length||new Set(order).size!==order.length)throw Error('Duplicate cartridge IDs are not allowed');
  if(ids.length!==order.length||order.some(id=>!ids.includes(id)))throw Error('Cartridge registry and execution order must contain the same IDs');
  for(const id of required)if(!ids.includes(id))throw Error('Required cartridge missing: '+id);
  return true;
}

      validateAtlasComposition(current);

      const shellUrl = new URL(current.shell.index, window.location.href);
      const shellBase = new URL(current.shell.base, window.location.href).href;
      const shellResponse = await fetch(shellUrl, { cache: 'no-store' });
      invariant(shellResponse.ok, `immutable shell HTTP ${shellResponse.status}`);
      let html = await shellResponse.text();
      invariant(/<head\b/i.test(html) && /<body\b/i.test(html), 'immutable shell is not HTML');
      html = html.replace(/<head([^>]*)>/i, match => `${match}\n<base href="${escapeAttribute(shellBase)}">`);

      const byId = new Map(current.cartridges.map(item => [item.id, item]));
      const loaded = [];
      const scriptTagPattern = new RegExp('<script\\b[^>]*\\bsrc=(["\\\'])([^"\\\']+)\\1[^>]*>\\s*<\\/script>', 'gi');

      for (const id of current.cartridge_order) {
        const cartridge = byId.get(id);
        invariant(cartridge, `missing cartridge ${id}`);
        invariant(cartridge.type === 'script', `${id}: unsupported cartridge type`);
        invariant(cartridge.slot === 'replace-script', `${id}: unsupported cartridge slot`);
        invariant(typeof cartridge.replace_script === 'string' && cartridge.replace_script, `${id}: replace_script missing`);
        invariant(/^[a-f0-9]{64}$/.test(cartridge.sha256 || ''), `${id}: invalid SHA-256`);

        const cartridgeUrl = new URL(cartridge.path, window.location.href);
        const response = await fetch(cartridgeUrl, { cache: 'no-store' });
        invariant(response.ok, `${id}: HTTP ${response.status}`);
        const bytes = await response.arrayBuffer();
        invariant(await sha256Hex(bytes) === cartridge.sha256, `${id}: SHA-256 mismatch`);
        const blobUrl = URL.createObjectURL(new Blob([bytes], { type: 'text/javascript' }));

        let replaced = false;
        html = html.replace(scriptTagPattern, (full, quote, src) => {
          if (replaced || String(src).split('/').pop() !== cartridge.replace_script) return full;
          replaced = true;
          return `<script data-gridatlas-cartridge="${escapeAttribute(id)}" src="${escapeAttribute(blobUrl)}">${SCRIPT_CLOSE}`;
        });
        invariant(replaced, `${id}: shell slot ${cartridge.replace_script} not found`);
        loaded.push({ id, sha256: cartridge.sha256, blob_url: blobUrl });
      }

      const publicState = JSON.stringify({
        schema: current.schema,
        generation: current.generation,
        release_id: current.release_id,
        architecture: current.architecture,
        shell: current.shell,
        cartridge_order: current.cartridge_order,
        loaded_cartridges: loaded.map(item => ({ id: item.id, sha256: item.sha256 }))
      }).replace(/</g, '\\u003c');
      const stateScript = `<script>window.__GRIDATLAS_ATLAS__=${publicState};document.documentElement.dataset.gridatlasGeneration=${JSON.stringify(current.generation)};${SCRIPT_CLOSE}`;
      html = html.replace(/<body([^>]*)>/i, match => `${match}\n${stateScript}`);

      html = html.replace(/<head>/i, '<head><link rel="icon" href="data:,">');
      const teleprinterUrl = new URL('./teleprinter-bootstrap.js', window.location.href).href;
      const teleprinterScript = '<script type="module" src="' + escapeAttribute(teleprinterUrl) + '">' + SCRIPT_CLOSE;
      html = /<\/body>/i.test(html) ? html.replace(/<\/body>/i, teleprinterScript + '$&') : html + teleprinterScript;

      document.open();
      document.write(html);
      document.close();
    } catch (error) {
      fail(error);
    }
  </script>
</body>
</html>

Testcode — Code Map

A JavaScript file in GlobalGrid2050 that draws blocks, families and names, and uses data from raw.githubusercontent.com and the stars repository. Served with the page at https://globalgrid2050.com/testcode/202609141754/code-map/.

renderglobalgrid2050 / testcode/202609141754/code-map/core.js · lines 1–203 of 203 · version 2026-09-14 17:54 · Entry point · pattern showFamilyPanel (shared by 2 files)

What it does
It draws blocks, families and names. Defines 38 functions or classes, including CORP_BASE, say, sayType, pageLink, $. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "Wording: every data-derived string passes through `../corporate.js` (via `say()`, `sayType()` and `pageLink()` in `core.js`)."
Inputs & outputs
In: data source: raw.githubusercontent.com; data source: stars data; JSON file blocks.json; JSON file families.json; JSON file index.json; JSON file names.json.
Downstream impact
Used directly by 10 files: Code Map — V01 Dependency Drill Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-map/v01-dependency-drill/); Code Map — V02 Radial Hierarchy Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-map/v02-radial-hierarchy/); Code Map — V03 Block Map Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-map/v03-block-map/); Code Map — V04 Block Register Links Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-map/v04-block-register-links/); and 6 more. Reached from 2 other entry points, including Testcode — Code Map Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-map/); Testcode — Code Navigation Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-navigation/). It is itself an entry point, published at https://globalgrid2050.com/testcode/202609141754/code-map/.
What it achieves
It gets JSON (`getJSON`), loads universe (`loadUniverse`) and sets address (`setAddress`). GlobalGrid2050 code map core, shared by the ten views (public copy of `testcode/202609141522/core.js`). It responds to click, popstate and input events.
Why it matters
Loaded by the V01 Dependency Drill page at https://globalgrid2050.com/testcode/202609141754/code-map/v01-dependency-drill/ and 9 other pages.
Application
globalgrid2050 · testcode/202609141754/code-map · script
Uses
Stars — Index Page (estate URL)
Used by
loaded by Code Map — V01 Dependency Drill Page (script src), loaded by Code Map — V02 Radial Hierarchy Page (script src), loaded by Code Map — V03 Block Map Page (script src), loaded by Code Map — V04 Block Register Links Page (script src), loaded by Code Map — V05 Chord Dependencies Page (script src), loaded by Code Map — V06 Treemap Page (script src), loaded by Code Map — V07 Flow Page (script src), loaded by Code Map — V08 Ring Navigation Page (script src), and 2 more
Produces
CORP_BASE, say, sayType, pageLink, $, esc, el, getJSON, fail, loadUniverse, catColour, catTitle
Defines here
CORP_BASE, say, sayType, pageLink, $, esc, el, getJSON, fail, loadUniverse, catColour, catTitle, catName, blockTitle, blockDesc, blockLabel, blockFamilies, blockDeps, blockUsers, blockPage, countsLine, family, familyLines, familyLinks, famName, famKind, pageList, fill, setAddress, readAddress
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609141754/code-map/core.js:1-203 · blob f4b7d1e1dda203a44985a36dffcfadd01c81eacb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
/* GlobalGrid2050 code map core, shared by the ten views (public copy of testcode/202609141522/core.js).
 * Reads live data (all served with Access-Control-Allow-Origin: *):
 *   <data>/blocks/blocks.json     named blocks and categories
 *   <data>/blocks/families.json   block or unnamed group -> family numbers
 *   <data>/code/index.json        counts
 *   <data>/code/f/<n/500>.json    family records (lines[], uses[], used_by[], places[])
 *   <data>/code/names.json        name -> family numbers
 *   raw.githubusercontent.com     the text of a family's lines at its pinned commit
 * A view supplies the picture; this file supplies data, the navigation trail, the family panel and search.
 * Wording: ../corporate.js (or ../../corporate.js) is loaded before this file. Every data-derived string that
 * reaches the screen goes through say() / sayType(), and every origin page link through pageLink(), below.
 */
const STARS = 'https://ventusltd.github.io/stars/';
const U = { blocks: null, cats: [], groups: null, index: null, names: null, famToGroup: new Map(), buckets: new Map(), texts: new Map(), trail: [] };
const REL = { contains: '#8b93a7', 'depends on': '#ffd54a', uses: '#00e5ff', 'used by': '#ff7ab6', 'shared line': '#39d353' };

/* ---- public wording choke point ---- */
const CORP = (typeof window !== 'undefined' && window.Corporate) || null;
// Corporate.link() returns page addresses relative to a page one folder below corporate.js; resolve them from there.
const CORP_BASE = (() => { const s = [...document.scripts].find(x => /(^|\/)corporate\.js([?#]|$)/.test(x.src)); return s ? new URL('page/', s.src).href : location.href; })();
const say = (s, type) => (CORP && s != null ? CORP.label(String(s), type) : s);
const sayType = t => (CORP && t != null ? CORP.type(t) : t);
function pageLink(url) { if (!url) return url; const v = CORP ? CORP.link(url) : url; try { return new URL(v, CORP_BASE).href; } catch { return v; } }

const $ = (s, r = document) => r.querySelector(s);
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
function el(tag, attrs = {}, ...kids) {
  const e = document.createElement(tag);
  for (const [k, v] of Object.entries(attrs)) { if (k === 'on') for (const [ev, fn] of Object.entries(v)) e.addEventListener(ev, fn); else if (k === 'html') e.innerHTML = v; else if (v != null) e.setAttribute(k, v); }
  for (const k of kids.flat()) if (k != null) e.append(k.nodeType ? k : document.createTextNode(k));
  return e;
}
async function getJSON(url) {
  const r = await fetch(url, { cache: 'default' });
  if (!r.ok) throw new Error(`${url} returned HTTP ${r.status}`);
  return r.json();
}
function fail(where, err) {
  const box = $(where) || document.body;
  box.prepend(el('div', { class: 'u-fail' }, `Could not load live data: ${err.message}. Check the internet connection and reload.`));
}

/* ---- data ---- */
async function loadUniverse() {
  const [b, groups, index, names] = await Promise.all([getJSON(STARS + 'blocks/blocks.json'), getJSON(STARS + 'blocks/families.json'), getJSON(STARS + 'code/index.json'), getJSON(STARS + 'code/names.json')]);
  U.blocks = b.blocks; U.cats = b.categories; U.groups = groups; U.index = index; U.names = names;
  U.bySym = new Map(U.blocks.map(x => [x.symbol, x]));
  // a family can belong to more than one group: famToGroup keeps the first named block (or first group) for the trail,
  // and famGroups keeps every membership (review, 2026-09-14: plural membership must be shown)
  U.famGroups = new Map();
  for (const [g, fams] of Object.entries(groups)) for (const n of fams) { if (!U.famGroups.has(n)) U.famGroups.set(n, []); U.famGroups.get(n).push(g); }
  for (const [n, gs] of U.famGroups) U.famToGroup.set(n, gs.find(g => U.bySym.has(g)) || gs[0]);
  U.catOf = new Map(U.cats.map(c => [c.id, c]));
  U.unnamed = Object.keys(groups).filter(g => !U.bySym.has(g));
  return U;
}
const catColour = id => (U.catOf.get(id) || {}).colour || '#8b93a7';
const catTitle = id => say((U.catOf.get(id) || {}).title || id);
const catName = c => say(c && c.title);
const blockTitle = b => say(b && b.title);
const blockDesc = b => say((b && b.description) || '');
function blockLabel(sym) { const b = U.bySym.get(sym); return b ? `${sym} · ${blockTitle(b)}` : `Group ${sym} (not yet named)`; }
function blockFamilies(sym) { return U.groups[sym] || []; }
function blockDeps(sym) { const b = U.bySym.get(sym); return b ? (b.depends_on || []).map(d => d.symbol || d).filter(s => U.bySym.has(s) || U.groups[s]) : []; }
function blockUsers(sym) { const b = U.bySym.get(sym); return b ? (b.used_by || []).filter(s => U.bySym.has(s) || U.groups[s]) : []; }
function blockPage(sym) { return pageLink(`${STARS}table.html?block=${encodeURIComponent(sym)}`); }
function countsLine() { return `${U.blocks.length} named blocks · ${U.unnamed.length} unnamed groups · ${U.index.families.toLocaleString('en-GB')} function families · ${U.index.lines.toLocaleString('en-GB')} unique numbered lines`; }

async function family(n) {
  const b = Math.floor(n / (U.index.bucket_size || 500));
  if (!U.buckets.has(b)) U.buckets.set(b, getJSON(`${STARS}code/f/${b}.json`));
  const bucket = await U.buckets.get(b);
  return bucket[String(n)] || null;
}
async function familyLines(rec) {
  const p = (rec.places || [])[0];
  if (!p) return rec.lines.map(k => ({ key: k, text: '(source not yet known: no place recorded)' }));
  const id = `${p.repo}@${p.commit}:${p.path}`;
  if (!U.texts.has(id)) U.texts.set(id, fetch(`https://raw.githubusercontent.com/${p.repo}/${p.commit}/${p.path.split('/').map(encodeURIComponent).join('/')}`).then(r => { if (!r.ok) throw new Error(`GitHub returned HTTP ${r.status}`); return r.text(); }).then(t => t.split('\n')));
  const all = await U.texts.get(id);
  const src = all.slice(p.first - 1, p.last);
  return rec.lines.map((k, i) => ({ key: k, text: src[i] ?? '' }));
}
function familyLinks(rec, n) {
  const p = (rec.places || [])[0];
  return {
    page: pageLink(`${STARS}code.html?family=${n}`),
    gh: p ? `https://github.com/${p.repo}/blob/${p.commit}/${p.path}#L${p.first}-L${p.last}` : null,
    live: pageLink((rec.places || []).map(x => x.live).find(Boolean) || null),
  };
}
const famName = rec => (rec && rec.names && rec.names[0]) || '(name not yet known)';  // function names are code identifiers: shown as recorded
const famKind = rec => sayType((rec && rec.kind) || 'code');


/* ---- paging: a list is never cut; it shows a page and a "show N more" control, so the last item is always reachable ---- */
function pageList(host, items, render, step = 60, label = 'more') {
  let shown = 0; const more = el('button', { class: 'u-chip u-more' });
  const fill = () => { const next = items.slice(shown, shown + step); next.forEach(it => host.insertBefore(render(it), more)); shown += next.length; if (shown >= items.length) more.remove(); else more.textContent = `show ${Math.min(step, items.length - shown)} ${label} (${items.length - shown} left)`; };
  host.append(more); more.addEventListener('click', fill); fill();
  return host;
}


/* ---- deep links: every family and block has an address, and browser Back walks the navigation history ---- */
function setAddress(kind, id) { const h = `#${kind}=${encodeURIComponent(id)}`; if (location.hash !== h) history.pushState({ kind, id }, '', h); }
function readAddress() { const m = location.hash.match(/^#(family|block)=(.+)$/); return m ? { kind: m[1], id: m[1] === 'family' ? Number(decodeURIComponent(m[2])) : decodeURIComponent(m[2]) } : null; }
addEventListener('popstate', () => { const a = readAddress(); if (a && window.goTo) { U.trail = U.trail.filter(s => !(s.kind === a.kind && s.id === a.id)); window.goTo(a.kind, a.id); } else if (!a && window.goHome) { U.trail = []; renderTrail(); window.goHome(); } });
function openAddress() { const a = readAddress(); if (a && window.goTo) { window.goTo(a.kind, a.id); return true; } return false; }

/* ---- navigation trail: every view shows where the reader has been ---- */
function trailPush(kind, id, label) {
  const last = U.trail[U.trail.length - 1];
  if (last && last.kind === kind && last.id === id) return;
  U.trail.push({ kind, id, label }); renderTrail(); if (kind === 'family' || kind === 'block') setAddress(kind, id);
}
function renderTrail() {
  const t = $('#trail'); if (!t) return;
  t.innerHTML = '';
  t.append(el('a', { href: '#', on: { click: e => { e.preventDefault(); U.trail = []; renderTrail(); window.goHome && window.goHome(); } } }, 'GLOBALGRID2050'));
  U.trail.forEach((s, i) => {
    t.append(' › ', el('a', { href: '#', on: { click: e => { e.preventDefault(); U.trail = U.trail.slice(0, i + 1); renderTrail(); window.goTo && window.goTo(s.kind, s.id); } } }, s.label));
  });
}

/* ---- the shared family panel: numbered lines and every relationship ---- */
async function showFamilyPanel(n, host, onFamily, onBlock) {
  host.innerHTML = '<div class="u-muted">Loading family #' + n + '…</div>';
  let rec;
  try { rec = await family(n); } catch (e) { host.innerHTML = ''; host.append(el('div', { class: 'u-fail' }, `Could not load family #${n}: ${e.message}`)); return; }
  if (!rec) { host.innerHTML = `<div class="u-fail">Family #${n} is not in the published records.</div>`; return; }
  trailPush('family', n, `#${n} ${famName(rec)}`);
  const g = U.famToGroup.get(n); const L = familyLinks(rec, n);
  host.innerHTML = '';
  host.append(
    el('div', { class: 'u-h' }, `#${n} ${famName(rec)}`),
    el('div', { class: 'u-muted' }, `${famKind(rec)} · ${rec.lines.length} numbered lines · in ${rec.repos.length} repositories · ${rec.standalone ? 'self-contained' : 'needs context'}`),
    el('div', { class: 'u-links' },
      ...((U.famGroups.get(n) || (g ? [g] : [])).map(gg => el('button', { class: 'u-chip', style: `border-color:${REL.contains}`, on: { click: () => onBlock(gg) } }, `◂ contained in ${blockLabel(gg)}`))),
      el('a', { class: 'u-chip', href: L.page, target: '_blank', rel: 'noopener' }, 'Function page ↗'),
      L.gh ? el('a', { class: 'u-chip', href: L.gh, target: '_blank', rel: 'noopener' }, 'File at commit ↗') : null,
      L.live ? el('a', { class: 'u-chip live', href: L.live, target: '_blank', rel: 'noopener' }, 'Live page ↗') : null),
  );
  const rel = (title, list, colour) => {
    if (!list.length) return;
    host.append(el('div', { class: 'u-sub', style: `color:${colour}` }, `${title} (${list.length})`));
    host.append(pageList(el('div', { class: 'u-links' }), list, u => el('button', { class: 'u-chip', style: `border-color:${colour}`, on: { click: () => onFamily(u.family) } }, `#${u.family} ${u.name || ''}`), 40, 'families'));
  };
  rel('→ uses', rec.uses || [], REL.uses);
  rel('← used by', rec.used_by || [], REL['used by']);
  host.append(el('div', { class: 'u-sub' }, 'Numbered lines (permanent keys)'));
  const pre = el('div', { class: 'u-code' }, 'Fetching the code at its pinned commit…'); host.append(pre);
  try {
    const rows = await familyLines(rec);
    pre.innerHTML = rows.map(r => `<div class="u-line"><span class="u-key">${r.key}</span> │ ${esc(r.text)}</div>`).join('');
  } catch (e) { pre.textContent = `The code could not be fetched (${e.message}); the line keys are ${rec.lines.join(', ')}.`; }
  // shared lines: other families in already-loaded buckets that carry the same line numbers
  const keys = new Set(rec.lines); const shared = new Map();
  for (const p of U.buckets.values()) { const bucket = await p.catch(() => ({})); for (const [m, r] of Object.entries(bucket)) { if (+m === n) continue; const hit = (r.lines || []).filter(k => keys.has(k)).length; if (hit) shared.set(+m, { family: +m, name: `${famName(r)} (${hit} shared)` }); } }
  rel('≡ shares numbered lines with (loaded records only)', [...shared.values()], REL['shared line']);
  return rec;
}

/* ---- search: a function name jumps to its family ---- */
function mountSearch(host, onFamily) {
  const input = el('input', { class: 'u-search', placeholder: 'Search a function name…', 'aria-label': 'Search a function name' });
  const hits = el('div', { class: 'u-hits' });
  input.addEventListener('input', () => {
    const q = input.value.trim().toLowerCase(); hits.innerHTML = '';
    if (q.length < 2) return;
    const found = Object.keys(U.names).filter(k => k.toLowerCase().includes(q)).sort((a, b) => a.length - b.length).slice(0, 12);
    for (const k of found) for (const n of U.names[k].slice(0, 3)) hits.append(el('button', { class: 'u-chip', on: { click: () => { hits.innerHTML = ''; input.value = ''; onFamily(n); } } }, `#${n} ${k}`));
    if (!found.length) hits.append(el('span', { class: 'u-muted' }, 'No function name contains that text.'));
  });
  host.append(input, hits);
}

function legend(host) {
  host.append(el('div', { class: 'u-legend' }, Object.entries(REL).map(([k, c]) => el('span', {}, el('i', { style: `background:${c}` }), sayType(k)))));
}
function footer(id) {
  document.body.append(el('footer', { class: 'u-foot' }, `${id} · built ${window.BUILT || ''} UTC · live data: ${STARS}blocks/, ${STARS}code/, raw.githubusercontent.com · GLOBALGRID2050`));
}

/* ---- shared look ---- */
document.head.append(el('style', { html: `
:root{color-scheme:dark}
body{margin:0;padding:12px 16px 40px;background:#0b0d12;color:#d8dee9;font:14px/1.5 ui-monospace,Menlo,Consolas,monospace}
a{color:#00e5ff} h1{font-size:20px;margin:0;letter-spacing:.06em} .u-count{color:#7da0c8;font-size:12px;margin:2px 0 8px}
#trail{font-size:12px;margin:6px 0 10px;color:#8b93a7;overflow-wrap:anywhere} #trail a{color:#9fd8ff;text-decoration:none}
.u-fail{border:1px solid #ff5c5c;color:#ffb3b3;padding:8px 10px;border-radius:8px;margin:8px 0}
.u-muted{color:#8b93a7;font-size:12px} .u-h{font-size:16px;color:#eef2fb;margin:4px 0} .u-sub{margin:12px 0 4px;font-size:12px;text-transform:uppercase;letter-spacing:.06em}
.u-links{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0}
.u-chip{background:#12151c;border:1px solid #385464;color:#eef2fb;padding:5px 9px;border-radius:14px;font:inherit;font-size:12px;cursor:pointer;text-decoration:none}
.u-chip:hover{border-color:#00e5ff} .u-chip.live{border-color:#39d353}
.u-code{background:#07090d;border:1px solid #1f2633;border-radius:8px;padding:8px;overflow:auto;max-height:55vh;font-size:12px}
.u-line{white-space:pre} .u-key{color:#ffd54a}
.u-search{width:100%;box-sizing:border-box;background:#12151c;border:1px solid #385464;color:#eef2fb;padding:8px 10px;border-radius:8px;font:inherit}
.u-hits{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0}
.u-legend{display:flex;flex-wrap:wrap;gap:10px;font-size:11px;color:#8b93a7;margin:6px 0} .u-legend i{display:inline-block;width:14px;height:3px;margin-right:4px;vertical-align:middle}
.u-foot{margin-top:24px;color:#566079;font-size:11px;overflow-wrap:anywhere}
.u-panel{border:1px solid #2a3140;border-radius:10px;padding:10px;background:#0f1218;margin:10px 0}
` }));

Testcode — Code Map Page

A web page in GlobalGrid2050. Published at https://globalgrid2050.com/testcode/202609141754/code-map/.

renderglobalgrid2050 / testcode/202609141754/code-map/index.html · lines 1–24 of 24 · version 2026-09-14 17:54 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
Out: web page.
Downstream impact
Used directly by 1 file: Testcode — Code Navigation Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-navigation/). It is itself an entry point, published at https://globalgrid2050.com/testcode/202609141754/code-map/.
What it achieves
Code map, ten views.
Why it matters
Loaded by the Code Navigation page at https://globalgrid2050.com/testcode/202609141754/code-navigation/.
Application
globalgrid2050 · testcode/202609141754/code-map · page
Uses
Code Map — V08 Ring Navigation Page (link), Code Map — V10 Code Browser Page (link), Code Map — V01 Dependency Drill Page (link), Code Map — V04 Block Register Links Page (link), Code Map — V09 Line View Page (link), Code Map — V02 Radial Hierarchy Page (link), Code Map — V03 Block Map Page (link), Code Map — V05 Chord Dependencies Page (link), and 2 more
Used by
linked from Testcode — Code Navigation Page (link)
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
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609141754/code-map/index.html:1-24 · blob 90e46533847033448710fee0fd02f022c329033d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: production_core
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>GlobalGrid2050 · Code map, ten views</title>
<style>
:root{color-scheme:dark}
body{margin:0;padding:16px 18px 40px;background:#0b0d12;color:#d8dee9;font:15px/1.55 ui-monospace,Menlo,Consolas,monospace;max-width:860px}
h1{font-size:22px;margin:0;letter-spacing:.06em}a{color:#00e5ff}
.muted{color:#8b93a7;font-size:13px}
.v{display:block;border:1px solid #2a3140;border-radius:10px;padding:12px 14px;margin:10px 0;background:#0f1218;text-decoration:none;color:#eef2fb}
.v:hover{border-color:#00e5ff}.v small{display:block;color:#8b93a7;font-size:12.5px;margin-top:2px}.v b{color:#00e5ff}
</style>
<h1>GLOBALGRID2050</h1>
<p class="muted">Code map: every function family and numbered line of the unique code across the GlobalGrid2050 repositories, organised by block. Ten views of the same live data, each read-only (the counts on each page are read from the data when it opens; 209 named blocks, 10,912 families and 249,347 numbered lines at 15:25 UTC on 14 September 2026). Each view opens on its own; the code is fetche  … [line shortened here: 484 characters; full line on GitHub]
<a class="v" href="v08-ring-navigation/index.html"><b>v08 · Ring navigation</b><small>Every block placed round a 360° circle with arrows across it; a block opens an inner ring of its families; a family opens its numbered lines; the path you have taken is drawn as you navigate.</small></a>
<a class="v" href="v10-code-browser/index.html"><b>v10 · Read-only code browser</b><small>Block navigator, numbered code, and relationships drawn like a single-line diagram (the block as busbar, each relationship a feeder).</small></a>
<a class="v" href="v01-dependency-drill/index.html"><b>v01 · Dependency drill</b><small>The dashboard layout: the selected item in the centre, what it depends on on the left, what uses it on the right; tap to go in.</small></a>
<a class="v" href="v04-block-register-links/index.html"><b>v04 · Block register with dependencies</b><small>The 207 blocks as tiles by category; tap one and arrows show what it depends on and what uses it.</small></a>
<a class="v" href="v09-line-view/index.html"><b>v09 · Line view</b><small>A family's numbered lines in sequence, lines shared with other families marked, every relationship alongside.</small></a>
<a class="v" href="v02-radial-hierarchy/index.html"><b>v02 · Radial hierarchy</b><small>Categories and blocks as rings; tap to zoom from category to block to families.</small></a>
<a class="v" href="v03-block-map/index.html"><b>v03 · Block map</b><small>Blocks placed by category; a selected block's function families are grouped around it and its dependencies are highlighted.</small></a>
<a class="v" href="v05-chord-dependencies/index.html"><b>v05 · Chord dependencies</b><small>Every depends-on relationship between named blocks as a chord across one circle.</small></a>
<a class="v" href="v06-treemap/index.html"><b>v06 · Treemap</b><small>Area by function families, then by numbered lines inside a block.</small></a>
<a class="v" href="v07-flow/index.html"><b>v07 · Flow</b><small>Repositories into categories into blocks, as bands you can follow.</small></a>
<p class="muted">All ten are read-only: they show relationships; changes are made in terminals, chat and GitHub Actions. Data: ventusltd.github.io/stars (blocks/, code/) and raw.githubusercontent.com.</p>

Code Map — V02 Radial Hierarchy Page

A web page in the testcode folder of GlobalGrid2050 that shows cat (`showCat`) and block (`showBlock`), opens family (`openFamily`) and draws SVG graphics. Published at https://globalgrid2050.com/testcode/202609141754/code-map/v02-radial-hierarchy/.

renderglobalgrid2050 / testcode/202609141754/code-map/v02-radial-hierarchy/index.html · lines 1–75 of 75 · version 2026-09-14 17:54 · Entry point · pattern showCat (shared by 6 files)

What it does
It draws its content. Defines 8 functions or classes, including sv, arc, p, ring, centre. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
Out: web page; SVG drawing.
Downstream impact
Used directly by 1 file: Testcode — Code Map Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-map/). Reached from 1 other entry point, including Testcode — Code Navigation Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-navigation/). It is itself an entry point, published at https://globalgrid2050.com/testcode/202609141754/code-map/v02-radial-hierarchy/.
What it achieves
It shows cat (`showCat`), shows block (`showBlock`) and opens family (`openFamily`). Defines `arc`, `ring`, `centre` and 3 more. It responds to click events.
Why it matters
Loaded by the Code Map page at https://globalgrid2050.com/testcode/202609141754/code-map/.
Application
globalgrid2050 · testcode/202609141754/code-map/v02-radial-hierarchy · page
Uses
Corporate (script src), Testcode — Code Map (script src)
Used by
linked from Testcode — Code Map Page (link)
Produces
sv, arc, p, ring, centre, showCat, showBlock, openFamily
Defines here
sv, arc, p, ring, centre, showCat, showBlock, openFamily
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609141754/code-map/v02-radial-hierarchy/index.html:1-75 · blob 82cbb26a9b53b0169edb87b1102da01aefd63af8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: production_core
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>GlobalGrid2050 · v02 radial hierarchy</title>
<script>window.BUILT='2026-09-14 17:54'</script>
<script src="../../corporate.js"></script>
<script src="../core.js"></script>
<style>
#wrap{display:flex;flex-wrap:wrap;gap:12px;align-items:flex-start}
svg{width:min(92vw,640px);height:auto;touch-action:manipulation}
.seg{cursor:pointer;stroke:#0b0d12;stroke-width:1}.seg:hover{filter:brightness(1.35)}
.lbl{fill:#d8dee9;font-size:10px;pointer-events:none}
#side{flex:1;min-width:280px}
</style>
<h1>GLOBALGRID2050</h1><div class="u-count" id="count">Loading the code map…</div>
<div id="search"></div><div id="trail"></div><div id="legend"></div>
<div id="wrap"><svg id="sun" viewBox="-320 -320 640 640"></svg><div id="side"><div class="u-panel" id="panel">Tap a ring segment. The centre goes back one level.</div></div></div>
<script>
const NS = 'http://www.w3.org/2000/svg', S = $('#sun'), P = $('#panel');
const sv = (t, a) => { const e = document.createElementNS(NS, t); for (const k in a) e.setAttribute(k, a[k]); return e; };
function arc(r0, r1, a0, a1) {
  const p = (r, a) => [r * Math.cos(a - Math.PI / 2), r * Math.sin(a - Math.PI / 2)];
  const big = a1 - a0 > Math.PI ? 1 : 0; const [x0, y0] = p(r1, a0), [x1, y1] = p(r1, a1), [x2, y2] = p(r0, a1), [x3, y3] = p(r0, a0);
  return `M${x0},${y0}A${r1},${r1} 0 ${big} 1 ${x1},${y1}L${x2},${y2}A${r0},${r0} 0 ${big} 0 ${x3},${y3}Z`;
}
/* one ring of weighted items; min share so small items stay tappable; labels only when the segment is wide enough */
function ring(items, r0, r1, onClick) {
  const tot = items.reduce((s, x) => s + Math.max(x.w, 0.004 * items.reduce((q, y) => q + y.w, 0)), 0); let a = 0;
  for (const it of items) {
    const w = Math.max(it.w, 0.004 * items.reduce((q, y) => q + y.w, 0)); const da = (w / tot) * Math.PI * 2;
    const g = sv('path', { d: arc(r0, r1, a, a + da - 0.002), fill: it.colour, class: 'seg' });
    g.append(sv('title', {})); g.firstChild.textContent = `${it.label} (${it.sub})`;
    g.addEventListener('click', () => onClick(it)); S.append(g);
    if (da > 0.09) { const m = a + da / 2, rr = (r0 + r1) / 2; const t = sv('text', { x: rr * Math.cos(m - Math.PI / 2), y: rr * Math.sin(m - Math.PI / 2), class: 'lbl', 'text-anchor': 'middle', 'dominant-baseline': 'middle' }); t.textContent = it.short || it.label.slice(0, 14); S.append(t); }
    it.mid = a + da / 2; a += da;
  }
}
function centre(title, sub, onClick) {
  const c = sv('circle', { r: 95, fill: '#12151c', stroke: '#00e5ff', 'stroke-width': 2, class: 'seg' }); c.addEventListener('click', onClick); S.append(c);
  const t = sv('text', { y: -8, class: 'lbl', 'text-anchor': 'middle', style: 'font-size:15px;fill:#eef2fb' }); t.textContent = title; S.append(t);
  const s = sv('text', { y: 14, class: 'lbl', 'text-anchor': 'middle', style: 'fill:#8b93a7' }); s.textContent = sub; S.append(s);
}
window.goHome = function () {
  S.innerHTML = '';
  const cats = U.cats.map(c => ({ id: c.id, label: catName(c), short: c.id, colour: c.colour, w: U.blocks.filter(b => b.category === c.id).length, sub: 'blocks' }));
  cats.push({ id: '_unnamed', label: 'Not yet named', short: 'unnamed', colour: '#566079', w: U.unnamed.length / 4, sub: `${U.unnamed.length} groups` });
  centre('GLOBALGRID2050', '12 categories · tap a ring', () => {});
  ring(cats, 100, 190, c => { trailPush('cat', c.id, c.label); showCat(c.id); });
  const outer = []; for (const c of cats) { if (c.id === '_unnamed') continue; for (const b of U.blocks.filter(x => x.category === c.id)) outer.push({ id: b.symbol, label: blockLabel(b.symbol), short: b.symbol, colour: c.colour, w: 1, sub: `${blockFamilies(b.symbol).length} families` }); }
  ring(outer, 196, 300, b => showBlock(b.id));
  P.innerHTML = `<div class="u-h">GLOBALGRID2050</div><div class="u-muted">${countsLine()}</div><p>Inner ring: categories of blocks. Outer ring: the 207 named blocks. Tap either to go in.</p>`;
};
window.goTo = (k, id) => k === 'cat' ? showCat(id) : k === 'block' ? showBlock(id) : openFamily(id);
function showCat(id) {
  S.innerHTML = '';
  const list = id === '_unnamed' ? U.unnamed.slice(0, 180).map(g => ({ symbol: g })) : U.blocks.filter(b => b.category === id);
  centre(id === '_unnamed' ? 'Not yet named' : catTitle(id), `${list.length} shown · centre = back`, () => { U.trail.pop(); renderTrail(); goHome(); });
  ring(list.map(b => ({ id: b.symbol, label: blockLabel(b.symbol), short: b.symbol, colour: catColour(id), w: Math.max(1, Math.sqrt(blockFamilies(b.symbol).length)), sub: `${blockFamilies(b.symbol).length} families` })), 110, 300, b => showBlock(b.id));
  P.innerHTML = `<div class="u-h">${esc(id === '_unnamed' ? 'Not yet named' : catTitle(id))}</div><div class="u-muted">Segment size: square root of the family count.</div>`;
}
function showBlock(sym) {
  S.innerHTML = ''; trailPush('block', sym, blockLabel(sym));
  const b = U.bySym.get(sym) || {}; const fams = blockFamilies(sym); const col = catColour(b.category);
  centre(sym, `${fams.length} families · centre = back`, () => { U.trail.pop(); renderTrail(); b.category ? showCat(b.category) : goHome(); });
  const shown = fams.slice(0, 180);
  ring(shown.map(n => ({ id: n, label: `#${n}`, short: `#${n}`, colour: col, w: 1, sub: 'family' })), 110, 220, f => openFamily(f.id));
  const deps = blockDeps(sym).map(s => ({ id: s, label: blockLabel(s), short: s, colour: REL['depends on'], w: 1, sub: 'depends on' }));
  const users = blockUsers(sym).slice(0, 60).map(s => ({ id: s, label: blockLabel(s), short: s, colour: REL['used by'], w: 1, sub: 'used by' }));
  if (deps.length + users.length) ring([...deps, ...users], 228, 300, x => showBlock(x.id));
  P.innerHTML = '';
  P.append(el('div', { class: 'u-h' }, blockLabel(sym)), el('div', { class: 'u-muted' }, `${blockDesc(b)} Inner ring: ${shown.length} of ${fams.length} families. Outer ring: blocks it depends on (yellow) and blocks that use it (pink).`),
    b.symbol ? el('a', { class: 'u-chip', href: blockPage(sym), target: '_blank', rel: 'noopener' }, 'Block page ↗') : null);
}
async function openFamily(n) { await showFamilyPanel(n, P, openFamily, showBlock); P.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); }
loadUniverse().then(() => { $('#count').textContent = countsLine(); legend($('#legend')); mountSearch($('#search'), openFamily); renderTrail(); goHome(); openAddress(); footer('v02-radial-hierarchy'); }).catch(e => fail('#count', e));
</script>

Code Map — V03 Block Map Page

A web page in the testcode folder of GlobalGrid2050 that selects star (`selectStar`), opens family (`openFamily`), calculates planar distances and draws on a canvas. Published at https://globalgrid2050.com/testcode/202609141754/code-map/v03-block-map/.

renderglobalgrid2050 / testcode/202609141754/code-map/v03-block-map/index.html · lines 1–77 of 77 · version 2026-09-14 17:54 · Entry point · pattern selectStar (shared by 2 files)

What it does
It draws its content. Defines 7 functions or classes, including size, layout, scr, draw, hit. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
Out: web page; canvas drawing.
Downstream impact
Used directly by 1 file: Testcode — Code Map Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-map/). Reached from 1 other entry point, including Testcode — Code Navigation Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-navigation/). It is itself an entry point, published at https://globalgrid2050.com/testcode/202609141754/code-map/v03-block-map/.
What it achieves
It selects star (`selectStar`) and opens family (`openFamily`). Defines `size`, `layout`, `scr` and 4 more. It responds to pointerdown, pointermove and pointerup events.
Why it matters
Loaded by the Code Map page at https://globalgrid2050.com/testcode/202609141754/code-map/.
Application
globalgrid2050 · testcode/202609141754/code-map/v03-block-map · page
Uses
Corporate (script src), Testcode — Code Map (script src)
Used by
linked from Testcode — Code Map Page (link)
Produces
size, layout, scr, draw, hit, selectStar, openFamily
Defines here
size, layout, scr, draw, hit, selectStar, openFamily
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609141754/code-map/v03-block-map/index.html:1-77 · blob 247c903c9772598bea882f82b165794a0f01d749 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: production_core
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>GlobalGrid2050 · v03 block map</title>
<script>window.BUILT='2026-09-14 17:54'</script>
<script src="../../corporate.js"></script>
<script src="../core.js"></script>
<style>
canvas{width:100%;height:min(70vh,720px);background:radial-gradient(circle at 50% 50%,#101624,#07090d 70%);border:1px solid #1f2633;border-radius:10px;touch-action:none;display:block}
#tip{position:fixed;pointer-events:none;background:#12151c;border:1px solid #385464;padding:4px 8px;border-radius:6px;font-size:12px;display:none;z-index:5}
</style>
<h1>GLOBALGRID2050</h1><div class="u-count" id="count">Loading the code map…</div>
<div id="search"></div><div id="trail"></div><div id="legend"></div>
<canvas id="sky"></canvas><div id="tip"></div>
<div class="u-muted">Each point is one of the 207 named blocks, sized by its function families and placed by category. Tap a block: its function families are grouped around it and its dependencies are highlighted as connecting lines. Tap a family marker to read its numbered lines. Drag to pan.</div>
<div class="u-panel" id="panel" hidden></div>
<script>
const cv = $('#sky'), ctx = cv.getContext('2d'), tip = $('#tip'), P = $('#panel');
let W, H, dpr, stars = [], parts = [], sel = null, pan = { x: 0, y: 0 }, t0 = performance.now();
function size() { dpr = devicePixelRatio || 1; W = cv.clientWidth; H = cv.clientHeight; cv.width = W * dpr; cv.height = H * dpr; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }
function layout() {
  const cats = U.cats; stars = [];
  cats.forEach((c, ci) => {
    const list = U.blocks.filter(b => b.category === c.id);
    const a0 = (ci / cats.length) * Math.PI * 2, span = (Math.PI * 2) / cats.length;
    list.forEach((b, i) => {
      const f = blockFamilies(b.symbol).length; const r = 0.12 + 0.36 * ((i + 1) / (list.length + 1)) ** 0.8;
      const a = a0 + span * (0.15 + 0.7 * ((i * 0.618) % 1));
      stars.push({ sym: b.symbol, label: blockLabel(b.symbol), colour: c.colour, rx: r * Math.cos(a), ry: r * Math.sin(a), rad: 2 + Math.sqrt(f) * 0.55, fams: f });
    });
  });
}
const scr = s => ({ x: W / 2 + pan.x + s.rx * Math.min(W, H) * 1.05, y: H / 2 + pan.y + s.ry * Math.min(W, H) * 1.05 });
function draw(now) {
  ctx.clearRect(0, 0, W, H); const t = (now - t0) / 1000;
  if (sel) {  // connecting lines: depends on (yellow) and used by (pink)
    const a = scr(sel);
    for (const [list, col] of [[blockDeps(sel.sym), REL['depends on']], [blockUsers(sel.sym), REL['used by']]]) for (const s of list) { const o = stars.find(x => x.sym === s); if (!o) continue; const b = scr(o); ctx.strokeStyle = col; ctx.globalAlpha = .55; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.quadraticCurveTo((a.x + b.x) / 2 + (a.y - b.y) * .2, (a.y + b.y) / 2 + (b.x -   … [line shortened here: 458 characters; full line on GitHub]
  }
  for (const s of stars) {
    const p = scr(s); const on = sel === s; ctx.fillStyle = s.colour; ctx.globalAlpha = sel && !on ? .45 : 1;
    ctx.beginPath(); ctx.arc(p.x, p.y, s.rad + (on ? 3 : 0), 0, 7); ctx.fill(); ctx.globalAlpha = 1;
    if (on || s.rad > 9) { ctx.fillStyle = '#d8dee9'; ctx.font = '11px ui-monospace,monospace'; ctx.fillText(s.sym, p.x + s.rad + 3, p.y + 4); }
  }
  if (sel) { // family markers circle the selected block
    const c = scr(sel); parts.forEach((q, i) => { const ring = 1 + (i % 4); const a = q.a + t * (0.25 / ring); q.x = c.x + Math.cos(a) * (sel.rad + 16 + ring * 18); q.y = c.y + Math.sin(a) * (sel.rad + 16 + ring * 18); ctx.fillStyle = REL.contains; ctx.beginPath(); ctx.arc(q.x, q.y, 2.6, 0, 7); ctx.fill(); });
  }
  requestAnimationFrame(draw);
}
function hit(x, y) {
  for (const q of parts) if (Math.hypot(q.x - x, q.y - y) < 7) return { part: q };
  let best = null, bd = 1e9; for (const s of stars) { const p = scr(s); const d = Math.hypot(p.x - x, p.y - y); if (d < Math.max(10, s.rad + 4) && d < bd) { best = s; bd = d; } }
  return best ? { star: best } : null;
}
let drag = null;
cv.addEventListener('pointerdown', e => { drag = { x: e.clientX, y: e.clientY, px: pan.x, py: pan.y, moved: false }; });
cv.addEventListener('pointermove', e => {
  const r = cv.getBoundingClientRect(); const h = hit(e.clientX - r.left, e.clientY - r.top);
  if (drag) { const dx = e.clientX - drag.x, dy = e.clientY - drag.y; if (Math.abs(dx) + Math.abs(dy) > 6) drag.moved = true; if (drag.moved) { pan.x = drag.px + dx; pan.y = drag.py + dy; } }
  if (h) { tip.style.display = 'block'; tip.style.left = e.clientX + 12 + 'px'; tip.style.top = e.clientY + 12 + 'px'; tip.textContent = h.star ? `${h.star.label} · ${h.star.fams} families` : `family #${h.part.n}`; } else tip.style.display = 'none';
});
cv.addEventListener('pointerup', e => { const d = drag; drag = null; if (d && d.moved) return; const r = cv.getBoundingClientRect(); const h = hit(e.clientX - r.left, e.clientY - r.top); if (!h) return; if (h.star) selectStar(h.star.sym); else openFamily(h.part.n); });
function selectStar(sym) {
  const s = stars.find(x => x.sym === sym);
  if (!s) { P.hidden = false; P.innerHTML = `<div class="u-muted">${esc(blockLabel(sym))} is an unnamed group: it is not placed on the map. Its ${blockFamilies(sym).length} families: </div>`; P.append(pageList(el('div', { class: 'u-links' }), blockFamilies(sym), n => el('button', { class: 'u-chip', on: { click: () => openFamily(n) } }, `#${n}`), 80, 'families')); return; }
  sel = s; trailPush('block', sym, s.label);
  parts = blockFamilies(sym).slice(0, 120).map((n, i) => ({ n, a: (i / Math.min(120, s.fams)) * Math.PI * 2, x: 0, y: 0 }));
  P.hidden = false; P.innerHTML = '';
  const b = U.bySym.get(sym) || {};
  P.append(el('div', { class: 'u-h' }, s.label), el('div', { class: 'u-muted' }, `${blockDesc(b)} ${s.fams} families (${parts.length} shown around the block). Lines: yellow = depends on, pink = used by.`),
    el('div', { class: 'u-links' }, el('a', { class: 'u-chip', href: blockPage(sym), target: '_blank', rel: 'noopener' }, 'Block page ↗'), ...blockDeps(sym).map(d => el('button', { class: 'u-chip', style: `border-color:${REL['depends on']}`, on: { click: () => selectStar(d) } }, `→ ${d}`)), ...blockUsers(sym).slice(0, 20).map(d => el('button', { class: 'u-chip', style: `border-color:${REL['used by  … [line shortened here: 457 characters; full line on GitHub]
}
async function openFamily(n) { P.hidden = false; await showFamilyPanel(n, P, openFamily, selectStar); P.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
window.goHome = () => { sel = null; parts = []; pan = { x: 0, y: 0 }; P.hidden = true; };
window.goTo = (k, id) => k === 'block' ? selectStar(id) : k === 'family' ? openFamily(id) : goHome();
addEventListener('resize', size);
loadUniverse().then(() => { $('#count').textContent = countsLine(); legend($('#legend')); mountSearch($('#search'), openFamily); renderTrail(); size(); layout(); requestAnimationFrame(draw); openAddress(); footer('v03-block-map'); }).catch(e => fail('#count', e));
</script>