GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / testcode / sandbox/202609052028/atlas/source

Menu Bar (part 5)

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

700 lines of JavaScript from testcode, in 1 file. Topic: Maps, GIS and field navigation. Section 722 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 · testcode / sandbox/202609052028/atlas/source/menu-bar.js lines 509–1208

Menu Bar

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

rendertestcode / sandbox/202609052028/atlas/source/menu-bar.js · lines 509–1208 of 1478 · version 2026-09-05 20:28 (continued from section 721) · 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 'sandbox'): 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
testcode · sandbox/202609052028/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
appendGroup, appendEngineModules, done, appendStudies, exportStamp, attributionText, generationText, buildPrintFurniture, installPrintStyle, printView, capture, clean, looksBlank, saveImage, say, grab, appendExport, appendEstateLinks, layerCheckbox, buildLayerControls, move, trayRoute, chipStaysOnMap
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609052028/atlas/source/menu-bar.js:509-1208 · blob 187a2694983ffab91c0421fb5c5d9bddf35804b7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
      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. */
  function buildPrintFurniture(doc) {
    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;
  }

  function installPrintStyle(doc) {
    if (doc.getElementById('gridatlas-print-css')) return;
    var style = doc.createElement('style');
    style.id = 'gridatlas-print-css';
    style.textContent = [
      '#gridatlas-print-furniture{display:none}',
      '@media print{',
      /* The bar and every open panel are interface, not content. The map and
         the furniture are the slide. */
      '  #' + BAR_ID + '{display:none!important}',
      '  #gridatlas-print-furniture{display:block;position:fixed;inset:0;',
      '    padding:8mm;box-sizing:border-box;pointer-events:none;z-index:9;',
      '    font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;color:#0b1416}',
      '  #gridatlas-print-furniture .gpf-head{letter-spacing:.28em;font-size:13px}',
      '  #gridatlas-print-furniture .gpf-brand{font-weight:700;margin-right:10px}',
      '  #gridatlas-print-furniture .gpf-sub{opacity:.65;letter-spacing:.16em}',
      '  #gridatlas-print-furniture .gpf-title{margin-top:4mm;font-size:20px;',
      '    letter-spacing:.02em;max-width:70%}',
      '  #gridatlas-print-furniture .gpf-foot{position:absolute;left:10mm;right:10mm;',
      '    bottom:8mm;display:flex;justify-content:space-between;gap:8mm;',
      '    font-size:9px;opacity:.75}',
      /* FIT THE PAGE, whatever the page is.
         "make sure print always fits to page in landscape or portrait on
         mobile, or desktop and sizes to fit the page" -- the architect.

         The first version of this forced A4 landscape, which is the opposite
         of fitting: it overrides the reader's own paper and orientation, and
         on a phone printing to A5 or Letter it clips. `size:auto` accepts
         whatever the reader chose, and the layout then fills that page rather
         than assuming its shape.

         WHICH BOX FLEXES, AND WHICH BOX MUST NOT.
         v9.121 put `flex:1 1 auto;min-height:0;height:auto` on
         `.map-container, .maplibregl-map, .maplibregl-canvas-container`
         together, reasoning that body becomes a flex column so the map takes
         the remaining height. THAT PREMISE WAS FALSE FOR THIS DOM. The shell
         is `body > .dashboard > .map-container > #map`, and `.dashboard` is
         already the flex column (`display:flex;flex-direction:column;
         height:100dvh` in ventusv8.css). Making body a flex column therefore
         reaches `.dashboard`, never the map. `.map-container` is
         `position:relative;display:block`, so `flex:1 1 auto` on `#map` is
         inert -- and `height:auto!important` overrode `#map{height:100%}` and
         collapsed it, because its only child is `position:absolute` and
         contributes no height.

         Measured at 202609050354 under print emulation: `.maplibregl-canvas`
         was 385x0 on a 393x852 phone and 1392x0 on a 1400x900 desktop, and
         `Page.printToPDF` produced ZERO image XObjects on both. A sheet with
         no map on it.

         So `.map-container` keeps the flex line -- that part is correct and
         is what makes the sheet fit the paper, since it IS a flex child of
         `.dashboard` -- while the map chain is given an EXPLICIT print height
         instead of `auto`. Same measurement after: 385x838 and 1392x518, two
         full-resolution image XObjects, one page, both viewports. */
      '  @page{size:auto;margin:8mm}',
      '  html,body{background:#fff!important;height:100%!important;',
      '    margin:0!important;padding:0!important;overflow:hidden!important}',
      '  body{display:flex!important;flex-direction:column!important}',
      '  .map-container{',
      '    flex:1 1 auto!important;min-height:0!important;width:100%!important;',
      '    max-height:100%!important}',
      '  #map,.maplibregl-map,.maplibregl-canvas-container{',
      '    height:100%!important;width:100%!important;max-height:100%!important}',
      '  .maplibregl-canvas{width:100%!important;height:100%!important;',
      '    object-fit:contain}',
      /* Nothing may spill onto a second sheet: a slide is one page. */
      '  body>*{break-inside:avoid;page-break-inside:avoid}',
      '  body{page-break-after:avoid}',
      '}'
    ].join('');
    doc.head.appendChild(style);
  }

  function printView(doc) {
    var map = window.__GRIDATLAS_V9_MAP__;
    var canvas = map && map.getCanvas && map.getCanvas();
    if (!canvas) return;
    var capture = function () {
      var url;
      try { url = canvas.toDataURL('image/png'); } catch (_) { return; }
      if (looksBlank(canvas)) return;
      var old = doc.getElementById('gridatlas-print-furniture');
      if (old) old.remove();
      var furniture = buildPrintFurniture(doc);
      var image = doc.createElement('img');
      image.className = 'gpf-map'; image.alt = 'Current Grid Atlas map'; image.src = url;
      furniture.appendChild(image);
      var style = doc.getElementById('gridatlas-print-css');
      if (!style) { style = doc.createElement('style'); style.id = 'gridatlas-print-css'; doc.head.appendChild(style); }
      style.textContent = '#gridatlas-print-furniture{display:none}' +
        '@media print{@page{size:auto;margin:8mm}html,body{margin:0!important;padding:0!important;height:auto!important;overflow:visible!important;background:white!important}' +
        'body>*:not(#gridatlas-print-furniture){display:none!important}' +
        '#gridatlas-print-furniture{display:block!important;position:fixed;inset:0;box-sizing:border-box;padding:4mm;background:white;color:#101c22;font:11px/1.4 system-ui}' +
        '.gpf-head{font-size:12px;letter-spacing:2px}.gpf-brand{font-weight:bold;margin-right:10px}.gpf-title{font-size:18px;margin-top:3mm}' +
        '.gpf-map{position:absolute;left:4mm;top:22mm;width:calc(100% - 8mm);height:calc(100% - 42mm);object-fit:contain}' +
        '.gpf-foot{position:absolute;left:4mm;right:4mm;bottom:3mm;display:flex;gap:12px;justify-content:space-between;font-size:9px}.gpf-stamp{white-space:nowrap}}';
      var clean = function () { furniture.remove(); window.removeEventListener('afterprint', clean); };
      window.addEventListener('afterprint', clean);
      image.decode().then(function () { window.print(); }).catch(clean);
      // Keep the snapshot while a mobile print/share dialog is open.
      window.setTimeout(clean, 300000);
    };
    map.once('render', capture); map.triggerRepaint();
  }


  /* Was anything actually drawn? A canvas read outside a render frame returns
     a fully transparent image, which encodes to a small PNG and downloads
     perfectly happily. Sample it rather than trust it. */
  function looksBlank(canvas) {
    try {
      var probe = document.createElement('canvas');
      probe.width = 40; probe.height = 40;
      var context = probe.getContext('2d');
      context.drawImage(canvas, 0, 0, 40, 40);
      var data = context.getImageData(0, 0, 40, 40).data;
      for (var i = 3; i < data.length; i += 4) if (data[i] !== 0) return false;
      return true;
    } catch (_) {
      /* A tainted canvas throws here. That is not blank, and treating it as
         blank would send the reader to print for no reason. */
      return false;
    }
  }

  function saveImage(doc, button) {
    /* THE MAP HANDLE IS THE ONE THE ESTATE ACTUALLY PUBLISHES.
       v9.121 read `window.__GRIDATLAS_MAP__ || (window.map && ...)`. Neither
       resolves: `__GRIDATLAS_MAP__` is assigned nowhere in this estate, and
       `window.map` is the DIV `<div id="map">` by named-element reflection,
       whose `.getCanvas` is undefined. `map` was therefore null on every
       attempt, the render-frame guard below was skipped, and the canvas was
       read OUTSIDE a frame -- the exact failure the guard exists to prevent.
       Every save on both viewports refused with "the map could not be
       captured". The search cartridge publishes
       `window.__GRIDATLAS_V9_MAP__`, and that is the handle. With it, inside
       `map.once('render')`, looksBlank() is false and toDataURL returns a
       real image. The guard was sound; only the lookup was wrong. */
    var map = window.__GRIDATLAS_V9_MAP__;
    if (!map || !map.getCanvas) {
      map = (window.map && window.map.getCanvas) ? window.map : null;
    }
    var canvas = doc.querySelector('.maplibregl-canvas')
      || (map && map.getCanvas ? map.getCanvas() : null);
    var say = function (text) { button.textContent = text; };

    if (!canvas) { say('⊘ No map canvas to save — use Print'); return; }

    var grab = function () {
      var url;
      try { url = canvas.toDataURL('image/png'); } catch (_) { url = null; }
      if (!url || looksBlank(canvas)) {
        /* Refused, and the reason is said out loud. The alternative is a file
           that opens as an empty rectangle an hour later, in front of someone
           else. */
        say('⊘ The map could not be captured — use Print instead');
        return;
      }
      var link = doc.createElement('a');
      link.href = url;
      link.download = 'gridatlas-' + exportStamp().replace(/[^0-9]/g, '').slice(0, 12) + '.png';
      doc.body.appendChild(link);
      link.click();
      doc.body.removeChild(link);
      say('✓ Image saved');
      window.setTimeout(function () { say('⤓ Save an image of this view'); }, 4000);
    };

    /* Inside a render frame, which is what makes the read non-blank on a
       canvas created without preserveDrawingBuffer. */
    if (map && map.once && map.triggerRepaint) {
      map.once('render', grab);
      map.triggerRepaint();
    } else {
      grab();
    }
  }

  function appendExport(panel, doc) {
    if (!panel || panel.querySelector('[data-gm-export]')) return 0;
    appendGroup(panel, 'Export this view');

    var print = doc.createElement('button');
    print.setAttribute('data-gm-export', '1');
    print.setAttribute('type', 'button');
    print.textContent = '⎙ Print · or save as PDF';
    print.addEventListener('click', function () { printView(doc); });
    panel.appendChild(print);

    var image = doc.createElement('button');
    image.setAttribute('data-gm-export', '1');
    image.setAttribute('type', 'button');
    image.textContent = '⤓ Save an image of this view';
    image.addEventListener('click', function () { saveImage(doc, image); });
    panel.appendChild(image);

    return 2;
  }

  function appendEstateLinks(panel) {
    if (!panel || panel.querySelector('[data-gm-estate]')) return 0;
    appendGroup(panel, 'Estate');
    var added = 0;
    ESTATE_LINKS.forEach(function (item) {
      var a = document.createElement('a');
      a.setAttribute('data-gm-estate', '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;
  }

  /* A measured audit found the v8 panel's own checkboxes at 17x17 px --
     the input element itself, not just its label. A label with a tall
     min-height passes a hit-test at its centre but still measures 17x17
     if something re-measures the <input> node's own rect, the way the
     live audit did. So the proxy <input> here is stretched, invisible,
     over the FULL label (position:absolute;inset:0) -- its own
     getBoundingClientRect() is therefore the whole >=44px control, under
     any measurement method -- and a separate, normally-sized box (built
     from CSS alone, no image) carries the visible tick. */
  function layerCheckbox(kind) {
    var proxy = document.createElement('input');
    proxy.type = kind;
    var box = document.createElement('span');
    box.className = 'gm-layer-box';
    box.setAttribute('aria-hidden', 'true');
    return { proxy: proxy, box: box };
  }

  function buildLayerControls(found) {
    var lastGroup = '';
    found.controls.forEach(function (original) {
      var key = layerKey(original);
      var group = layerGroup(original);
      if (group !== lastGroup) {
        appendGroup(gridBody, group);
        lastGroup = group;
      }
      var label = document.createElement('label');
      label.className = 'gm-layer';
      label.setAttribute('data-gridatlas-layer-key', key);
      var built = layerCheckbox('checkbox');
      var proxy = built.proxy;
      proxy.setAttribute('data-gridatlas-layer-proxy', key);
      var name = document.createElement('span');
      name.className = 'gm-layer-name';
      label.appendChild(proxy);
      label.appendChild(built.box);
      label.appendChild(name);
      gridBody.appendChild(label);
      layerTargets[key] = original;
      layerProxies[key] = proxy;
      proxy.addEventListener('change', function () {
        if (!!original.checked !== !!proxy.checked && typeof original.click === 'function') {
          /* original.click() must remain the implementation: its delegated
             engine listener owns hydration.  Suppress only the document-level
             outside-click closer while that synchronous forwarding runs, so
             the reader can see the tick and its live load state. */
          forwardingLayerChoice = true;
          try { original.click(); }
          finally { forwardingLayerChoice = false; }
        }
        syncLayer(key);
      });
      syncLayer(key);
    });

    var basemaps = array(found.host.querySelectorAll('input[type="radio"][name="bm"]'));
    if (basemaps.length) appendGroup(gridBody, 'Basemap');
    basemaps.forEach(function (original) {
      var label = document.createElement('label');
      label.className = 'gm-layer';
      var built = layerCheckbox('radio');
      var proxy = built.proxy;
      proxy.name = 'gridatlas-menu-basemap';
      proxy.value = original.value;
      proxy.checked = !!original.checked;
      var name = document.createElement('span');
      name.className = 'gm-layer-name';
      name.textContent = cleanText(original.closest('label').textContent) || original.value;
      proxy.addEventListener('change', function () {
        if (proxy.checked && !original.checked && typeof original.click === 'function') original.click();
        closeAll();
      });
      label.appendChild(proxy);
      label.appendChild(built.box);
      label.appendChild(name);
      gridBody.appendChild(label);
    });
  }

  function move(panel, node, label) {
    if (!node || !panel || (bar && bar.contains(node))) return false;
    if (label && node.setAttribute) node.setAttribute('aria-label', label);
    panel.appendChild(node);             // same node: its original listener survives
    if (node.removeAttribute) node.removeAttribute('hidden');
    state.controls_moved += 1;
    return true;
  }

  function trayRoute(node) {
    var text = cleanText(node && node.textContent).toLowerCase();
    if (/\bclear\b|\bscope\b/.test(text)) return 'Scope';
    if (/\bgrid\b|\bsubs\b/.test(text)) return 'Grid';
    return '';
  }

  /* The two chips that must NOT be swallowed by a menu on a phone.
     ------------------------------------------------------------------------
     GRID and SUBS were put on the map deliberately, and the reason is on the
     record: the grid-line and substation switches live in the SCADA panel
     below the map, "which a phone never scrolls to; activation looked
     broken" (composition manifest, mobile_tray, from phone acceptance on
     2026-09-01). Moving every tray button into a dropdown re-created a milder
     form of exactly that fault - measured at an iPhone 13 viewport on
     202609041330, zero layer controls were reachable without first opening a
     menu.

     So on a touch screen or a narrow window these two stay where they were
     designed to be. Everything else still routes into the menus, and desktop
     is unchanged: there the chips are redundant with a menu that is already
     one click away and always visible. */
  function chipStaysOnMap(node) {
    var text = cleanText(node && node.textContent).toLowerCase();
    if (!/\bgrid\b|\bsubs\b/.test(text)) return false;
    /* An UNKNOWN width is not a phone. Reading `(window.innerWidth || 0) <= 700`
       makes a missing or zero width report narrow, which is the wrong way for
       a default to fail: it would strand these chips on the map in any host
       that does not publish a width, including a headless proof fixture. The
       width has to be a real positive number before it argues for a phone. */
    var coarse = false;
    try {
      coarse = !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
    } catch (error) {