GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/modules

G203 Regional Native Viewport (part 7)

A JavaScript file in the atlas folder of GridAtlas that maps elizabeth line and london underground, using haversine, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 583 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. G203 Regional Native Viewport geodesy · gridatlas / atlas/modules/g203-regional-native-viewport.js lines 4601–5300

G203 Regional Native Viewport

A JavaScript file in the atlas folder of GridAtlas that maps elizabeth line and london underground, using haversine, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

Set aside from the main view: 99% of its lines are the same as atlas/cartridges/202611180026-substation-intelligence-v9-63.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Substation Intelligence V9 63; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.987 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
  • sha256 7645828021ee561333c34c0ecaad2b46bd87029ca9101601714d7e520bb680b1
  • target sha256 88c538b97bf426776cda436151741f17500a2136867d28362407550d72f9038f
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/g203-regional-native-viewport.js · lines 4601–5300 of 8664 (continued from section 576) · pattern regionalEligible (shared by 3 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 241 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Downstream impact
Used directly by 1 file: G203 Swarm 06 Viewport Lifecycle Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
Checked by G203 Swarm 06 Viewport Lifecycle Test.
Application
gridatlas · atlas/modules · script
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
referenced by G203 Swarm 06 Viewport Lifecycle Test (new URL import.meta.url)
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
syncAttribClearance, closeAll, syncLayer, syncAll, clampPanel, openMenu, buildBar, appendGroup, appendEngineModules, done, appendStudies, exportStamp, attributionText, generationText, dropById, buildPrintFurniture
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/g203-regional-native-viewport.js:4601-5300 · blob 013cf98a02bb6c09199c357ac96a2b588892c0f4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
      '#' + BAR_ID + ' .gm-menu.gm-open>.gm-title{background:rgba(80,220,240,.16);color:#fff}',
      '#' + BAR_ID + ' .gm-title:focus-visible,#' + BAR_ID + ' .gm-panel :focus-visible{',
      'outline:2px solid #6bebff;outline-offset:-2px}',
      '#' + BAR_ID + ' .gm-side{display:flex;align-items:stretch;flex:1 1 0;min-width:0}',
      '#' + BAR_ID + ' .gm-side-left{justify-content:flex-start}',
      '#' + BAR_ID + ' .gm-side-right{justify-content:flex-end}',
      /* The VENTUS masthead, fused into the centre of this same 36px strip
         (see buildBar) rather than a second row, so it costs no map height
         on a phone and can never be torn out into a closed panel again. */
      /* "The VENTUS logo is the best part" -- the architect's own words.
         It is the hero of this strip: sized and weighted to outrank the
         six menu titles either side of it, not a corner credit shrunk to
         fit. Same face, tracking and two-line lockup as the v8 masthead
         and the fullscreen letterhead it is carried from verbatim. */
      '#' + BAR_ID + ' .gm-brand-slot{flex:0 1 auto;min-width:0;max-width:64%;',
      'display:flex;align-items:center;justify-content:center;overflow:hidden;',
      'padding:0 6px;text-align:center}',
      '#' + BAR_ID + ' .gm-brand-slot .hud-header{display:flex!important;',
      'position:static!important;width:auto!important;align-items:center;',
      'justify-content:center;gap:11px;margin:0!important;padding:0!important;',
      'background:none!important;border:0!important}',
      '#' + BAR_ID + ' .gm-brand-slot .hud-header>div{flex:0 0 auto;line-height:1.05}',
      '#' + BAR_ID + ' .gm-brand-slot .hud-header small{font-size:6.5px;white-space:nowrap}',
      '#' + BAR_ID + ' .gm-brand-slot .hud-header .hud-val{font-size:10.5px;',
      'text-shadow:none}',
      '#' + BAR_ID + ' .gm-brand-slot .ventus-main{font-size:14px;font-weight:800;',
      'letter-spacing:.2em;margin:0;color:#fff}',
      '#' + BAR_ID + ' .gm-brand-slot .ventus-sub{font-size:5.5px;letter-spacing:.14em}',
      '#' + BAR_ID + ' .gm-panel{position:absolute;top:100%;left:0;min-width:240px;',
      'max-width:min(92vw,420px);max-height:min(72dvh,620px);overflow:auto;',
      'overscroll-behavior:contain;padding:6px;background:rgba(4,10,13,.98);',
      'border:1px solid rgba(80,220,240,.32);border-top:0;',
      'box-shadow:0 12px 34px rgba(0,0,0,.68);box-sizing:border-box}',
      '#' + BAR_ID + ' .gm-panel[hidden]{display:none!important}',
      /* Right-align every panel whose title lives in the right-hand group,
         not "the last two of six flat siblings" -- that positional rule is
         what let the About panel resolve to a negative x once the six
         titles stopped being one undifferentiated row (measured live:
         x=-95 at 1568px, a quarter of its own Versions control
         unreachable). clampPanel() below is the second, JS-measured
         guarantee: this CSS is the common case, not the only defence. */
      '#' + BAR_ID + ' .gm-side-right .gm-panel{left:auto;right:0}',
      '#' + BAR_ID + ' .gm-panel button,#' + BAR_ID + ' .gm-panel [role="button"]{',
      'display:flex;align-items:center;width:100%;min-height:44px;box-sizing:border-box;',
      'position:static!important;inset:auto!important;transform:none!important;margin:0 0 3px;',
      'padding:7px 10px;border:0;border-radius:2px;background:transparent;color:#cfeef6;',
      'font:11px/1.35 ui-monospace,SFMono-Regular,Menlo,monospace;text-align:left;',
      'letter-spacing:.03em;text-transform:none;cursor:pointer}',
      '#' + BAR_ID + ' .gm-panel button:hover,#' + BAR_ID + ' .gm-panel [role="button"]:hover{',
      'background:rgba(80,220,240,.14);color:#fff}',
      /* The estate links are anchors so they are real links -- middle-click,
         copy, open in a new tab all work -- and they take the panel's own
         button look rather than a second one. Only the underline has to go. */
      '#' + BAR_ID + ' .gm-panel a[data-gm-estate],#' + BAR_ID + ' .gm-panel a[data-gm-engine],',
      '#' + BAR_ID + ' .gm-panel a[data-gm-study]',
      '{text-decoration:none}',
      /* Module paths are long. They stay on one row and lose their middle
         rather than wrapping a 44px control into three lines on a phone. */
      '#' + BAR_ID + ' .gm-panel a[data-gm-engine]{white-space:nowrap;overflow:hidden;',
      'text-overflow:ellipsis;display:block;line-height:30px;min-height:44px}',
      /* The attribution, once moved into About, is prose in a panel of
         controls: it keeps its own small type and wraps rather than being
         clipped to one 44px row. */
      '#' + BAR_ID + ' .gm-panel .custom-map-attrib{position:static!important;',
      'inset:auto!important;margin:4px 0 2px;padding:6px 8px;max-width:none;',
      'background:transparent;border:0;white-space:normal;line-height:1.45;',
      'font:10px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;color:#8fb6c0}',
      '#' + BAR_ID + ' .gm-layer-group{margin:5px 0 2px;padding:6px 8px 3px;',
      'border-top:1px solid #19343b;color:#6fa2ae;font-size:10px;letter-spacing:.08em;',
      'text-transform:uppercase}',
      /* Every layer control's OWN <input> covers its whole label (see
         layerCheckbox / buildLayerControls): a measured audit found the raw
         v8 checkboxes at 17x17px, the input element itself and not just a
         padded label, so a re-measurement of the input's own rect is the
         bar this has to clear, not only a centre-point hit test. */
      '#' + BAR_ID + ' .gm-layer{position:relative;display:flex;align-items:center;gap:10px;',
      'min-height:44px;box-sizing:border-box;padding:7px 9px;color:#cfeef6;cursor:pointer;',
      'line-height:1.35}',
      '#' + BAR_ID + ' .gm-layer:hover{background:rgba(80,220,240,.12)}',
      '#' + BAR_ID + ' .gm-layer input{position:absolute;inset:0;width:100%;height:100%;',
      'margin:0;opacity:0;cursor:pointer;z-index:1}',
      '#' + BAR_ID + ' .gm-layer-box{width:20px;height:20px;flex:0 0 auto;',
      'border:1.5px solid #4a8b96;border-radius:4px;position:relative;',
      'background:rgba(255,255,255,.04)}',
      '#' + BAR_ID + ' .gm-layer input:checked~.gm-layer-box{background:#4fd7ee;',
      'border-color:#4fd7ee}',
      '#' + BAR_ID + ' .gm-layer input:checked~.gm-layer-box::after{content:"";',
      'position:absolute;left:6px;top:2px;width:5px;height:10px;',
      'border:solid #04141a;border-width:0 2px 2px 0;transform:rotate(38deg)}',
      '#' + BAR_ID + ' .gm-layer input:focus-visible~.gm-layer-box{outline:2px solid #6bebff;',
      'outline-offset:2px}',
      '#' + BAR_ID + ' .gm-layer-name{overflow-wrap:anywhere}',
      /* The restored SCADA panel: a branded head (the real .scada-brand and
         .status-legend nodes, moved in once -- see install()) above a
         scrollable body that never mixes with the head's own layout. */
      '#' + BAR_ID + ' .gm-panel-grid{padding:0;overflow:hidden;display:flex;',
      'flex-direction:column;min-width:min(94vw,360px);max-width:min(96vw,900px)}',
      '#' + BAR_ID + ' .gm-panel-head{flex:0 0 auto;padding:8px 8px 0}',
      '#' + BAR_ID + ' .gm-panel-head .scada-brand{padding:0 0 6px;margin:0 0 6px}',
      '#' + BAR_ID + ' .gm-panel-head .status-legend{padding:0 0 8px;margin:0;border:0}',
      '#' + BAR_ID + ' .gm-panel-body{flex:1 1 auto;overflow:auto;',
      'overscroll-behavior:contain;padding:6px;min-height:0}',
      '@media(min-width:560px){#' + BAR_ID + ' .gm-panel-body{column-count:2;',
      'column-gap:14px}',
      '#' + BAR_ID + ' .gm-panel-body .gm-layer-group{break-inside:avoid}',
      '#' + BAR_ID + ' .gm-panel-body .gm-layer{break-inside:avoid}}',
      '@media(min-width:900px){#' + BAR_ID + ' .gm-panel-body{column-count:3}}',
      '#' + BAR_ID + ' .search-bar-wrapper{position:static!important;display:grid!important;',
      'grid-template-columns:minmax(150px,1fr) auto;width:min(82vw,390px);gap:5px;margin:2px 0 6px}',
      '#' + BAR_ID + ' .search-bar-wrapper>div{position:relative}',
      '#' + BAR_ID + ' .search-input{width:100%!important;min-height:44px;box-sizing:border-box}',
      '#' + BAR_ID + ' .search-results{position:static!important;max-height:42vh;overflow:auto}',
      '#' + BAR_ID + ' .disclaimer-box,#' + BAR_ID + ' .podcast-shoutout{',
      'display:block!important;position:static!important;max-width:380px;padding:8px;',
      'box-sizing:border-box;text-align:left;pointer-events:auto}',
      '.gridatlas-menu-hosted .map-controls[data-gridatlas-menu-emptied="1"]{display:none!important}',
      /* The v8 SCADA layers panel STAYS. It was hidden here unconditionally,
         and the reasoning that justified it was circular: this rule set
         display:none!important, which is why "the container height never
         changes", which was then cited as evidence the panel's own toggle was
         inert, which justified the rule. Measured on the live page at
         202609041957, with the toggle un-hidden and clicked: the label does
         flip (LAYERS -> HIDE LAYERS) and data-gridatlas-collapsed does clear.
         The toggle was never inert. Only its effect was invisible.

         The cost of the rule was the whole product surface: all 60 engine
         layer switches sat in a container measured at 0x0, on desktop AND
         phone, with the page unable to scroll to it -- zero of 120 layer
         controls reachable without opening a menu. The register, the
         voltages, the supermarkets, the transit and the EV layers were all
         still in the DOM and none of them could be touched.

         "One identity surface" is still honoured, and it was always about the
         VENTUS wordmark rather than the switches: the real .scada-brand node
         is MOVED into the Grid panel head by install(), not cloned, so the
         restored panel has no second wordmark to show. The Grid dropdown and
         this panel drive the SAME 63 original inputs -- the dropdown proxies
         them -- so the two cannot disagree about what is on.

         Requested directly by the architect, whose product this is, on
         2026-09-04: "restore v8 panels but keep dropdowns file, edit, scope,
         grid, about". Both, not either. */
      '.gridatlas-menu-hosted .scada-wrapper{display:flex!important}',
      /* At phone widths the panel starts collapsed and the toggle opens it:
         measured, an expanded panel held 31.6% of a 393x852 screen against
         the map's 29.3%, which is the wrong trade on the surface most
         readers arrive on. Desktop has the room and gets the panel open, as
         v8 always did. Either way the toggle is now visible, so the reader
         decides rather than the stylesheet. */
      '#gridatlas-dash-toggle{display:inline-flex!important}',
      /* v9.90 made the mobile project card a fixed, full-width bottom sheet.
         The old SCADA layer panel remained underneath it, so a visible layer
         checkbox could lose the hit test to text in the project card. Keep the
         conventional menu and its fixed phone panel in the higher, interactive
         stacking context whenever that sheet is open. */
      'html.gridatlas-sheet-open #' + BAR_ID + '{z-index:10020!important;pointer-events:auto!important}',
      'html.gridatlas-sheet-open #' + BAR_ID + ' .gm-panel{pointer-events:auto!important}',
      'body:not(.fs-active) #' + BAR_ID + ' #btn-fullscreen-exit{display:none!important}',
      'body.fs-active #' + BAR_ID + ' #btn-fullscreen-exit{display:flex!important}',
      /* The shell's own .custom-map-attrib (OpenStreetMap / CARTO / Open
         Charge Map credit) only ever cleared this bar while body.fs-active
         was set. At rest -- and on every Pipeline News deep-link arrival,
         which does not always reach fs-active -- the credit painted at its
         default top:10px and sat directly under the bar, invisible under
         the ABOUT title. A licence credit that is painted but covered is
         not attribution. Clear it whenever this bar is hosted, not only in
         fullscreen; --gridatlas-menu-bar-clear is kept in step with the
         bar's own rendered height (see syncAttribClearance) rather than a
         second hard-coded constant, because the bar itself drops from 36px
         to 34px under the @media rule below and a fixed number sized for
         one breakpoint would leave the credit covered, or needlessly far
         down, at the other. 44px is only the pre-JS fallback. Z-INDEX, not
         only top: measured live, an open dropdown panel painted over the
         credit's right two-thirds (elementFromPoint at 50/70/90% of its
         width resolved to the panel's own button) even though the credit's
         TOP already cleared the bar -- the two are siblings in the same
         stacking context and the panel simply painted after it. The credit
         must outrank every panel this bar can ever open, present or future,
         so its z-index is set once here rather than chased per panel. */
      '.gridatlas-menu-hosted .custom-map-attrib{',
      'top:var(--gridatlas-menu-bar-clear,44px)!important;z-index:10025!important}',
      /* The v8 fullscreen letterhead stands down once this bar hosts the
         brand. #fs-letterhead is painted only under body.fs-active, and
         fs-active is set by exactly one caller: the deep-link arrival's
         enterFullscreen(), which runs when trayTarget() is true. That is
         every phone and no desktop -- so the duplicate was invisible to
         every desktop check and present on every phone arrival. Measured
         on an iPhone 13 viewport at 202609041250: the fused masthead sat
         correctly at x=165 (11px) while this one painted at x=254 (15px),
         over the SCOPE, GRID and ABOUT titles in the right side group.
         The brand is not lost by hiding it -- it is the same wordmark,
         still on screen, now in the bar at every width and in every
         fullscreen state, which is what fusing it there was for. */
      '.gridatlas-menu-hosted #fs-letterhead{display:none!important}',
      '@media(max-width:700px){#' + BAR_ID + '{height:34px}',
      '#' + BAR_ID + ' .gm-title{min-height:34px;padding:0 6px;font-size:9px;letter-spacing:.025em}',
      '#' + BAR_ID + ' .gm-brand-slot{max-width:48%;padding:0 2px}',
      '#' + BAR_ID + ' .gm-brand-slot .hud-header>div:first-child,',
      '#' + BAR_ID + ' .gm-brand-slot .hud-header>div:last-child{display:none}',
      '#' + BAR_ID + ' .gm-brand-slot .ventus-main{font-size:11px;letter-spacing:.14em}',
      '#' + BAR_ID + ' .gm-brand-slot .ventus-sub{font-size:4.5px}',
      '#' + BAR_ID + ' .gm-panel{position:fixed;top:34px;left:4px!important;right:4px!important;',
      'width:auto;max-width:none;max-height:calc(100dvh - 40px);padding-bottom:',
      'calc(6px + env(safe-area-inset-bottom))}',
      '#' + BAR_ID + ' .gm-panel-grid{max-width:none}}'
    ].join('');
    (doc.head || doc.documentElement).appendChild(style);
  }

  function syncAttribClearance(doc) {
    /* Measured, not asserted: the bar is 36px at rest and 34px under the
       @media(max-width:700px) rule in installStyle, and either number could
       change again. Reading the live box keeps the credit clear of the bar
       at whatever height it actually rendered, on the phone width the
       fixture failed on as much as on desktop. Guarded so the DOM-fixture
       proof, which stubs neither getBoundingClientRect nor a CSSOM style
       object, runs through this as a no-op. */
    if (!bar || typeof bar.getBoundingClientRect !== 'function') return;
    var root = doc.documentElement;
    if (!root || !root.style || typeof root.style.setProperty !== 'function') return;
    var rect = bar.getBoundingClientRect();
    var height = Math.ceil(rect.height) || 36;
    var clearance = height + 8;   // clear of the bar's own border-bottom, not flush against it
    root.style.setProperty('--gridatlas-menu-bar-clear', clearance + 'px');
    state.attrib_clearance_px = clearance;
  }

  function closeAll(focusTitle) {
    if (!bar) return;
    array(bar.querySelectorAll('.gm-menu.gm-open')).forEach(function (menu) {
      menu.classList.remove('gm-open');
      var title = menu.querySelector('.gm-title');
      var panel = menu.querySelector('.gm-panel');
      if (title) title.setAttribute('aria-expanded', 'false');
      if (panel) panel.hidden = true;
    });
    state.closed_at_rest = true;
    openPanelRefs = null;
    if (focusTitle && typeof focusTitle.focus === 'function') focusTitle.focus();
  }

  function syncLayer(key) {
    var original = layerTargets[key];
    var proxy = layerProxies[key];
    if (!original || !proxy) return;
    proxy.checked = !!original.checked;
    proxy.disabled = !!original.disabled;
    proxy.setAttribute('aria-label', layerLabel(original));
    var name = proxy.parentNode && proxy.parentNode.querySelector
      ? proxy.parentNode.querySelector('.gm-layer-name') : null;
    if (name) {
      var nextLabel = layerLabel(original);
      if (name.textContent !== nextLabel) name.textContent = nextLabel;
    }
  }

  function syncAll() {
    Object.keys(layerTargets).forEach(syncLayer);
  }

  /* Measured live: the About panel resolved to x=-95 at 1568px width, a
     quarter of its own control off the left edge of the window -- the CSS
     right:0 anchor (now scoped to the right-hand group, see installStyle)
     covers the common case, but this is the second, JS-measured guarantee
     that no panel this bar ever opens can resolve outside the viewport,
     regardless of how its title happens to be positioned. Runs after the
     panel is laid out (post layout, not pre-measured), clears any earlier
     override before measuring so a panel that no longer overflows is not
     left pinned from a previous, narrower viewport. */
  function clampPanel(doc, menu, panel) {
    if (!panel || typeof panel.getBoundingClientRect !== 'function') return;
    if (!menu || typeof menu.getBoundingClientRect !== 'function') return;
    panel.style.left = '';
    panel.style.right = '';
    var view = doc.defaultView || (typeof window !== 'undefined' ? window : null);
    var vw = (view && view.innerWidth) || doc.documentElement.clientWidth;
    if (!vw) return;
    var margin = 4;
    var panelRect = panel.getBoundingClientRect();
    var desiredLeft = panelRect.left;
    if (panelRect.left < margin) desiredLeft = margin;
    else if (panelRect.right > vw - margin) desiredLeft = Math.max(margin, vw - margin - panelRect.width);
    if (Math.round(desiredLeft) === Math.round(panelRect.left)) return;
    var menuRect = menu.getBoundingClientRect();
    panel.style.left = (desiredLeft - menuRect.left) + 'px';
    panel.style.right = 'auto';
  }

  var openPanelRefs = null;    // {menu, panel} while a panel is open, so a resize can re-clamp it

  function openMenu(menu, title, panel) {
    var wasOpen = menu.classList.contains('gm-open');
    closeAll();
    if (wasOpen) { openPanelRefs = null; return; }
    if (title.textContent === 'Grid') syncAll();
    menu.classList.add('gm-open');
    title.setAttribute('aria-expanded', 'true');
    panel.hidden = false;
    state.closed_at_rest = false;
    openPanelRefs = { menu: menu, panel: panel };
    clampPanel(title.ownerDocument || document, menu, panel);
  }

  function buildBar(doc) {
    var nav = doc.createElement('nav');
    nav.id = BAR_ID;
    nav.setAttribute('aria-label', 'Atlas menu');

    /* Three zones, not six flat siblings. The architect's complaint was
       that the VENTUS identity had been torn out of view -- moved into a
       closed About panel, so the reader saw the v8 masthead for the first
       ~1.5s of every arrival and then watched it vanish. Fusing the brand
       into the CENTRE of the same 36px strip the menu titles already live
       in restores it permanently, at every width, with no extra row and
       therefore no map height stolen on a phone. Two flex:1 side groups
       keep the brand visually centred regardless of the (unequal) width
       of "File Edit View" versus "Scope Grid About", and give every panel
       a real left- or right-hand anchor to resolve against -- the flat
       row's "last two of six" rule is what let the About panel resolve to
       a negative x once the titles no longer filled the bar edge to edge. */
    var left = doc.createElement('div');
    left.className = 'gm-side gm-side-left';
    var right = doc.createElement('div');
    right.className = 'gm-side gm-side-right';
    var brand = doc.createElement('div');
    brand.className = 'gm-brand-slot';
    brandSlot = brand;

    MENUS.forEach(function (name, index) {
      var menu = doc.createElement('div');
      menu.className = 'gm-menu';
      var title = doc.createElement('button');
      title.type = 'button';
      title.className = 'gm-title';
      title.textContent = name;
      title.id = BAR_ID + '-title-' + index;
      title.setAttribute('aria-haspopup', 'menu');
      title.setAttribute('aria-expanded', 'false');
      title.setAttribute('aria-controls', BAR_ID + '-panel-' + index);
      var panel = doc.createElement('div');
      panel.className = 'gm-panel';
      panel.id = BAR_ID + '-panel-' + index;
      panel.hidden = true;
      panel.setAttribute('role', 'group');
      panel.setAttribute('aria-labelledby', title.id);
      if (name === 'Grid') {
        /* The real v8 SCADA panel, restored: a branded head (Ventus /
           Cables & Connectivity(r) / the status legend -- the exact shell
           nodes, moved in rather than cloned) above a scrollable body that
           carries the layer groups in the two-column shape v8 used. The
           head never enters that column flow. */
        var head = doc.createElement('div');
        head.className = 'gm-panel-head';
        var body = doc.createElement('div');
        body.className = 'gm-panel-body';
        panel.appendChild(head);
        panel.appendChild(body);
        panel.classList.add('gm-panel-grid');
        gridHead = head;
        gridBody = body;
      }
      title.addEventListener('click', function (event) {
        event.stopPropagation();
        openMenu(menu, title, panel);
      });
      menu.appendChild(title);
      menu.appendChild(panel);
      (index < 3 ? left : right).appendChild(menu);
      panels[name] = panel;
      titles.push(title);
    });

    nav.appendChild(left);
    nav.appendChild(brand);
    nav.appendChild(right);

    nav.addEventListener('keydown', function (event) {
      var active = doc.activeElement;
      var index = titles.indexOf(active);
      if (event.key === 'Escape') {
        var owner = active && active.closest ? active.closest('.gm-menu') : null;
        var ownerTitle = owner && owner.querySelector ? owner.querySelector('.gm-title') : null;
        closeAll(ownerTitle);
        event.preventDefault();
        return;
      }
      if (index < 0) return;
      if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') {
        var delta = event.key === 'ArrowRight' ? 1 : -1;
        titles[(index + delta + titles.length) % titles.length].focus();
        event.preventDefault();
      } else if (event.key === 'Home' || event.key === 'End') {
        titles[event.key === 'Home' ? 0 : titles.length - 1].focus();
        event.preventDefault();
      } else if (event.key === 'ArrowDown') {
        var ownerMenu = active.closest('.gm-menu');
        var ownerPanel = ownerMenu.querySelector('.gm-panel');
        openMenu(ownerMenu, active, ownerPanel);
        var first = ownerPanel.querySelector('button,input,[role="button"]');
        if (first && first.focus) first.focus();
        event.preventDefault();
      }
    });
    return nav;
  }

  function appendGroup(panel, text) {
    var heading = document.createElement('div');
    heading.className = 'gm-layer-group';
    heading.textContent = text;
    panel.appendChild(heading);
  }

  /* The estate's other published surfaces, reachable from About.
     ------------------------------------------------------------------------
     These are method, not client material, and the publication boundary is
     explicit that method is never withheld: "the mathematics, the method and
     the derivations; the schemas, the object models and the contracts; the
     code, the solvers and the validation suites" are published openly in all
     cases (seed-data/07_CRITICALITY_AND_PUBLICATION_BOUNDARY.md, section 6).
     The engine graph is the first of them: it is where a reader, human or
     machine, sees which engine owns a calculation and which copies of it
     exist elsewhere in the estate.

     They are anchors carrying role="button" so they inherit the panel's own
     button styling rather than introducing a second look, and they open in a
     new tab so a reader never loses the map they were reading. */
  var ESTATE_LINKS = [
    { href: 'https://ventusltd.github.io/ventus-grid-engine/?graph=engine-graph',
      text: 'Grid engine · the maths' },
    { href: 'https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/sandbox/spider_full_po_test.html',
      text: 'Federation map' },
    { href: 'https://ventusltd.github.io/spiders/spider_printer_v1/',
      text: 'Spider printer' }
  ];

  /* The engine's own modules, listed in File, each linking into the graph.
     ------------------------------------------------------------------------
     "we are heading towards a grid OS in our website the menus must be neat,
     it should allow AI and humans to develop and use" -- the architect,
     2026-09-05. A File menu that lists the mathematics an application runs on,
     and opens each one, is the first honest step towards that: it is what an
     IDE's File menu is for, and the publication boundary already says the
     method is published in all cases.

     The list is FETCHED from the engine's own published graph, never restated
     here. Both surfaces are served from ventusltd.github.io, so this is a
     same-origin request. If it fails -- offline, or the engine moved -- no
     group is added and the menu is exactly what it was; a File panel that
     silently lacks one group is a far better failure than a menu bar that
     throws during install. */
  var ENGINE_GRAPH_URL =
    'https://ventusltd.github.io/ventus-grid-engine/genome/engine-graph.json';
  var ENGINE_VIEW_URL =
    'https://ventusltd.github.io/ventus-grid-engine/?graph=engine-graph&focus=';

  /* Set SYNCHRONOUSLY, before the fetch is issued. The DOM marker below cannot
     do this job on its own: adoptLate runs from a MutationObserver, so between
     the request going out and the rows arriving there are hundreds of further
     calls, and a guard that only checks the DOM starts a request on every one
     of them. */
  var engineFetchStarted = false;

  function appendEngineModules(panel) {
    if (!panel || !window.fetch || engineFetchStarted) return;
    if (panel.querySelector('[data-gm-engine]')) return;
    engineFetchStarted = true;
    fetch(ENGINE_GRAPH_URL, { cache: 'no-cache' }).then(function (response) {
      if (!response.ok) throw new Error('HTTP ' + response.status);
      return response.json();
    }).then(function (graph) {
      var nodes = (graph && graph.nodes) || [];
      if (!nodes.length || panel.querySelector('[data-gm-engine]')) return;

      /* EVERY node, not only the canonical eleven.
         ------------------------------------------------------------------
         The first version of this listed `type === 'canonical'` and the
         architect caught it in one line: "Why are the mjs files not there?"
         The graph publishes 44 nodes -- 11 canonical, 1 extract, 1 reference
         and 31 fragments -- and every .mjs in the estate is in the three
         groups the filter had thrown away: sizing-arithmetic.mjs is an
         extract, grid-distance-maths/src/geodesy.mjs a reference,
         atlas-pointer-deep-link.mjs and wider-fleet.mjs are fragments.

         The fragments are the most useful rows here, not the least: they are
         where a calculation has been copied and left to drift, which is the
         defect class this estate keeps paying for. A File menu that hides
         them shows the tidy half of the truth. Groups are ordered canonical
         first, then the rest, and the graph's own kind_labels are used for
         the headings where it publishes them, so this menu does not invent a
         vocabulary the graph does not use. */
      var ORDER = ['canonical', 'extract', 'reference', 'fragment'];
      var FALLBACK_LABEL = {
        canonical: 'Engine · the maths this runs on',
        extract: 'Extracts',
        reference: 'References',
        fragment: 'Copies elsewhere in the estate'
      };
      var kindLabels = (graph && graph.kind_labels) || {};
      var byKind = {};
      nodes.forEach(function (node) {
        if (!node || !node.label) return;
        var kind = node.type || 'other';
        if (!byKind[kind]) byKind[kind] = [];
        byKind[kind].push(node);
      });
      var kinds = ORDER.filter(function (k) { return byKind[k]; })
        .concat(Object.keys(byKind).filter(function (k) { return ORDER.indexOf(k) < 0; }).sort());

      /* Hand over something that RUNS, not only something that reads.
         ------------------------------------------------------------------
         "The MJS apps that AI and humans can deploy as an IDE via menu ...
         or text they could execute with AI in approved terminals or
         powershells or IDE lets hand power to the people" -- the architect,
         2026-09-05.

         This is one command, and it is one that actually works today: it
         clones the engine, installs it and runs its own fail-closed gate,
         which currently reports 8 proofs and 133 checks. It is copied to the
         clipboard rather than executed -- nothing here runs anything on
         anyone's machine, and the person or agent that pastes it into a
         terminal is the one who decides to. That is the whole of the
         approval step, and it belongs to them. */
      /* No `npm install`. Measured 202609050250: the engine declares no
         dependencies and no proof in it opens a socket, so `node verify.mjs`
         runs its whole fail-closed gate -- 8 proofs, 133 checks -- from a
         clone, offline, on any machine with node. The earlier version of this
         command included an install step, which implied a network dependency
         that does not exist and would have made the offline claim false. */
      var RUN_COMMAND =
        'git clone https://github.com/Ventusltd/ventus-grid-engine'
        + ' && cd ventus-grid-engine && node verify.mjs';

      appendGroup(panel, 'Run the engine yourself · offline, no dependencies');
      var run = document.createElement('button');
      run.setAttribute('data-gm-engine', '1');
      run.setAttribute('type', 'button');
      run.title = RUN_COMMAND;
      run.textContent = '⧉ Copy: clone the engine and run its 133 checks';
      run.addEventListener('click', function () {
        var done = function (ok) {
          run.textContent = ok
            ? '✓ Copied — paste it into a terminal'
            : '⧉ ' + RUN_COMMAND;
        };
        try {
          if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(RUN_COMMAND).then(function () { done(true); },
              function () { done(false); });
          } else {
            /* No clipboard permission: show the command in full so it can
               still be selected by hand. A control that silently does
               nothing is worse than one that shows its own payload. */
            done(false);
          }
        } catch (_) { done(false); }
      });
      panel.appendChild(run);

      var total = 0;
      kinds.forEach(function (kind) {
        var group = byKind[kind];
        /* Alphabetical, as every non-version group in this estate is. */
        group.sort(function (a, b) { return String(a.label).localeCompare(String(b.label), 'en-GB'); });
        appendGroup(panel, (FALLBACK_LABEL[kind] || kindLabels[kind] || kind) + ' · ' + group.length);
        group.forEach(function (node) {
          var a = document.createElement('a');
          a.setAttribute('data-gm-engine', '1');
          a.setAttribute('role', 'button');
          a.href = ENGINE_VIEW_URL + encodeURIComponent(node.label);
          a.target = '_blank';
          a.rel = 'noopener';
          a.textContent = node.label;
          /* The node's own one-line reason, as the graph publishes it. */
          if (node.reason) a.title = node.reason;
          panel.appendChild(a);
          total += 1;
        });
      });
      state.engine_modules = total;
    }).catch(function () {
      /* Deliberately silent. See the note above: the menu must survive the
         engine being unreachable, and a reader who cannot reach it is not
         helped by an error row in a File menu. */
      state.engine_modules = 0;
    });
  }

  /* Published studies, in View, beside the price control the reader is already
     using. A study is a reading of the network over time, and View is where
     this application keeps readings -- GB prices · historic is already there.
     Putting it in About would file it as provenance, which it is not: it is
     something to look at. */
  var STUDY_LINKS = [
    { href: 'https://globalgrid2050.com/data/grid_studies_public/'
        + 'great_britain_electricity_price_grid_constraint_trends_2016_2026.html',
      text: 'GB electricity price & grid constraint trends · 2016–2026' }
  ];

  function appendStudies(panel) {
    if (!panel || panel.querySelector('[data-gm-study]')) return 0;
    appendGroup(panel, 'Studies');
    var added = 0;
    STUDY_LINKS.forEach(function (item) {
      var a = document.createElement('a');
      a.setAttribute('data-gm-study', '1');
      a.setAttribute('role', 'button');
      a.href = item.href;
      a.target = '_blank';
      a.rel = 'noopener';
      a.textContent = item.text;
      panel.appendChild(a);
      added += 1;
    });
    return added;
  }

  /* Export: print a slide, or save an image of exactly what is on screen.
     ------------------------------------------------------------------------
     "allow the user to export screenshot prints via file save or file print
     and they should produce beautiful slides of what's on display be it mobile
     or desktop" -- the architect, 2026-09-05.

     Two things this must get right, and both are failure modes this estate has
     already paid for:

     1. THE IMAGE MUST NOT BE BLANK. The map is a WebGL canvas created without
        preserveDrawingBuffer, so reading it after the frame is composited
        returns an empty image. The capture therefore happens INSIDE a render
        frame, and the result is then CHECKED -- decoded and sampled for
        non-transparent pixels -- before it is offered. If it comes back blank
        the reader is told and sent to print instead. Handing someone an empty
        PNG that looks like a successful save is worse than refusing.

     2. THE CREDIT MUST TRAVEL WITH THE ARTEFACT. This generation moved the
        attribution into About, which is right for the screen and wrong for an
        export: OpenStreetMap, CARTO and Open Charge Map require attribution on
        the thing that leaves the building. Both paths re-place it, visibly, on
        the exported artefact. */
  function exportStamp() {
    var now = new Date();
    return now.toISOString().replace('T', ' ').slice(0, 16) + ' UTC';
  }

  function attributionText(doc) {
    var node = doc.querySelector('.custom-map-attrib');
    return cleanText(node && node.textContent)
      || 'Data © OpenStreetMap contributors | © CARTO | EV data © Open Charge Map';
  }

  /* THE GENERATION IS READ FROM WHAT THE COMPOSER ACTUALLY PUBLISHES.
     v9.121 read `window.__GRIDATLAS_CURRENT__`, which exists nowhere in this
     estate: the loader in atlas/index.html writes
     `window.__GRIDATLAS_ATLAS__` and stamps
     `document.documentElement.dataset.gridatlasGeneration`. So the stamp on
     every printed sheet silently lost the build it came from -- measured at
     202609050354, the furniture read "2026-09-05 10:35 UTC" and nothing else.
     A slide that cannot be traced back to a composition is not evidence.
     Both published sources are read, because the dataset attribute survives a
     later document.write while a global would not. */
  function generationText() {
    var atlas = window.__GRIDATLAS_ATLAS__;
    var generation = (atlas && atlas.generation)
      || (document.documentElement && document.documentElement.dataset
        && document.documentElement.dataset.gridatlasGeneration);
    return generation ? 'generation ' + generation : '';
  }

  /* The slide furniture: a title, the identity of whatever is on screen, the
     credit, and the stamp. Created only while printing and removed after, so
     nothing about the live page changes. */
  /* Printing twice must not leave two of anything. Both export overlays are
     addressed by id, and a second Print before the first one's cleanup timer
     has run would otherwise append a duplicate id and stack two stamps on the
     sheet. */
  function dropById(doc, id) {
    var existing = doc.getElementById(id);
    if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
  }

  function buildPrintFurniture(doc) {
    dropById(doc, 'gridatlas-print-furniture');
    var box = doc.createElement('div');
    box.id = 'gridatlas-print-furniture';
    var selected = doc.querySelector('.project-popup .name, .gm-panel .project-name');
    var title = cleanText(selected && selected.textContent) || 'GlobalGrid2050 · Grid Atlas';
    box.innerHTML =
      '<div class="gpf-head"><span class="gpf-brand">VENTUS</span>'
      + '<span class="gpf-sub">GLOBAL GRID 2050 · GRID ATLAS</span></div>'
      + '<div class="gpf-title"></div>'
      + '<div class="gpf-foot"><span class="gpf-attrib"></span>'
      + '<span class="gpf-stamp"></span></div>';
    box.querySelector('.gpf-title').textContent = title;
    box.querySelector('.gpf-attrib').textContent = attributionText(doc);
    box.querySelector('.gpf-stamp').textContent =
      [generationText(), exportStamp()].filter(Boolean).join(' · ');
    doc.body.appendChild(box);
    return box;
  }