GLOBALGRID2050 / EXPLORE CODE

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

Menu Bar (part 4)

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.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Maps, GIS and field navigation. Section 507 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 701–1400

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 701–1400 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
done, appendStudies, exportStamp, attributionText, generationText, buildPrintFurniture, installPrintStyle, printView, capture, clean, looksBlank, saveImage, say, grab, appendExport, appendEstateLinks, layerCheckbox, buildLayerControls, move, trayRoute, chipStaysOnMap, adoptLate, install
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:701-1400 · 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
      /* 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) {
      coarse = false;
    }
    var width = Number(window.innerWidth);
    var narrow = isFinite(width) && width > 0 && width <= 700;
    return coarse || narrow;
  }

  function adoptLate(doc) {
    if (!bar) return;
    move(panels.View, doc.getElementById('gridatlas-gb-conditions'));
    move(panels.About, doc.getElementById('gridatlas-version-ledger'));
    move(panels.View, doc.getElementById('btn-fullscreen-exit'), 'Exit full screen');

    var curtain = doc.getElementById('fs-curtain-tab');
    if (curtain && !bar.contains(curtain)) {
      curtain.setAttribute('role', 'button');
      curtain.setAttribute('tabindex', '0');
      curtain.setAttribute('aria-label', 'Open the fullscreen layer curtain');
      move(panels.Grid, curtain);
    }

    var tray = doc.getElementById('gridatlas-mobile-tray');
    if (tray) {
      array(tray.querySelectorAll('button')).forEach(function (button) {
        if (chipStaysOnMap(button)) return;   // one tap on a phone, not two
        var route = trayRoute(button);
        if (route) move(panels[route], button);
        else button.hidden = true;       // Tools only revealed the controls now in menus
      });
    }

    move(panels.Scope, doc.getElementById('btn-gridpoint'));

    var disclaimer = doc.querySelector('.disclaimer-box');
    var shoutout = doc.querySelector('.podcast-shoutout');
    move(panels.About, disclaimer);
    move(panels.About, shoutout);

    state.estate_links = appendEstateLinks(panels.About);
    appendEngineModules(panels.File);
    state.export_controls = appendExport(panels.File, doc);
    state.studies = appendStudies(panels.View);

    /* The map attribution moves off the map and into About, LAST, in small
       print.
       ----------------------------------------------------------------------
       Measured live at generation 202609042123, 2026-09-05: .custom-map-attrib
       rendered at x=15 y=47, 401x24 px -- a boxed band immediately under the
       menu bar, over the top-left of the map, which is where a reader arriving
       on a deep link looks first. On a 393x852 phone it wrapped to two lines
       and the architect photographed the consequence: opening EDIT drew
       "Status Colours" UNDERNEATH the attribution box, the two overlapping in
       the same space. His instruction, verbatim: "Attribution bar clashes move
       that to about and in small print at the bottom".

       The credit is owed and is not dropped: it is the same node, moved once,
       text intact, so OpenStreetMap, CARTO and Open Charge Map are still named
       on the page and one tap away. It is appended AFTER the estate links, and
       re-appended on every later adoption pass, so a late DOM rebuild cannot
       leave it above the controls again. appendChild on a node already in the
       panel moves it to the end rather than duplicating it. */
    var attrib = doc.querySelector('.custom-map-attrib');
    if (attrib) {
      if (!bar || !bar.contains(attrib)) move(panels.About, attrib);
      else if (panels.About.lastElementChild !== attrib) panels.About.appendChild(attrib);
      /* The `lastElementChild` test is not tidiness, it is the difference
         between this working and crashing the tab. adoptLate runs from a
         MutationObserver, so an unconditional appendChild here IS a mutation,
         which re-enters adoptLate, which appends again: a feedback loop that
         crashed the renderer outright under the 393x852 arrival gate, while
         the previous generation passed the same gate in the same harness.
         Once the node is already last, this is a no-op and the loop closes. */
    }

    /* The real .scada-brand (VENTUS, again) and .status-legend move once,
       into the restored SCADA panel's head, during install() below -- not
       hidden as a "duplicate" and not here, so a late DOM rebuild cannot
       repeatedly fight over one node's location. */

    /* The panel's own show/hide control stays REACHABLE. It was hidden here as
       "superseded; measured inert", and it is neither: the stylesheet rule
       above was hiding the panel it moved, so its effect could not be seen.
       With the panel restored this is the only control that opens and closes
       it, and hiding it would leave a phone with a collapsed panel and nothing
       to open it with -- which is the fault this generation exists to end. */
    var dashToggle = doc.getElementById('gridatlas-dash-toggle');
    if (dashToggle) dashToggle.hidden = false;

    var stack = doc.querySelector('.map-controls');
    if (stack) {
      var leftovers = array(stack.querySelectorAll('button,input,select,textarea,a'))
        .filter(function (node) { return !node.hidden; });
      if (leftovers.length === 0) stack.setAttribute('data-gridatlas-menu-emptied', '1');
    }

    MENUS.forEach(function (name) {
      state.panel_counts[name] = panels[name] ? panels[name].children.length : 0;
    });
  }

  function install(doc) {
    if (state.installed || doc.getElementById(BAR_ID)) return true;
    var ready = required(doc);
    state.engine_layer_controls = ready.found.engine.length;
    state.pipeline_layer_controls = ready.found.pipeline.length;
    state.layer_controls = ready.found.controls.length;
    if (ready.missing.length) {
      state.waiting_for = ready.missing.slice();
      return false;
    }

    installStyle(doc);
    bar = buildBar(doc);
    buildLayerControls(ready.found);

    // Search stays on the map throughout initialization.
    if (ready.nodes.search) ready.nodes.search.setAttribute("data-testcode-search", "persistent");
    move(panels.File, ready.nodes.exportButton);
    move(panels.Edit, ready.nodes.statusButton);
    move(panels.View, ready.nodes.fullscreenButton);
    move(panels.Scope, ready.nodes.radiusButton);
    move(panels.Scope, ready.nodes.radiusAreaButton);
    move(panels.Scope, ready.nodes.zoneButton);
    move(panels.Scope, ready.nodes.measureButton);

    /* The VENTUS masthead: fused into the bar's own centre (see buildBar),
       never a closed panel -- the architect's "VENTUS branding has been
       lost" was this node being moved into a collapsed About panel, and
       the measured "flash then vanish" (present for ~1.5s, then torn out)
       was that same move happening after the raw v8 page had already
       painted it once. Moving it here, into brandSlot, keeps it visible
       through the whole transition: raw markup, then fused into the bar,
       never hidden in between. */
    move(brandSlot, ready.nodes.header);

    /* The restored SCADA panel's head: the real .scada-brand (VENTUS,
       again, exactly as v8 rendered it) and .status-legend, moved once --
       not cloned, not hidden as a duplicate. gridHead sits above gridBody
       (built by buildLayerControls) and never enters its column flow. */
    move(gridHead, doc.querySelector('.scada-brand'));
    move(gridHead, doc.querySelector('.status-legend'));

    ready.nodes.host.insertBefore(bar, ready.nodes.host.firstChild);
    doc.documentElement.classList.add('gridatlas-menu-hosted');
    syncAttribClearance(doc);
    if (typeof ResizeObserver === 'function') {
      var barResize = new ResizeObserver(function () {
        syncAttribClearance(doc);
        if (openPanelRefs) clampPanel(doc, openPanelRefs.menu, openPanelRefs.panel);
      });
      barResize.observe(bar);
      state.attrib_clearance_source = 'ResizeObserver';
    } else if (doc.defaultView && typeof doc.defaultView.addEventListener === 'function') {
      /* No ResizeObserver: a viewport resize is the only other way the
         bar's own height changes (the @media breakpoint), so fall back to
         watching that. */
      doc.defaultView.addEventListener('resize', function () {
        syncAttribClearance(doc);
        if (openPanelRefs) clampPanel(doc, openPanelRefs.menu, openPanelRefs.panel);
      });
      state.attrib_clearance_source = 'resize-listener';
    }

    /* One document click listener and one change listener, installed once.
       The retry path cannot multiply effects. */
    doc.addEventListener('click', function (event) {
      if (!bar.contains(event.target)) {
        if (!forwardingLayerChoice) closeAll();
      }
      else if (event.target && /^(BUTTON|INPUT)$/.test(event.target.tagName || '')) {
        if (event.target.type !== 'text'
          && !event.target.classList.contains('gm-title')
          && !event.target.hasAttribute('data-gridatlas-layer-proxy')) {
          window.setTimeout ? window.setTimeout(closeAll, 0) : closeAll();
        }
      }
    });
    doc.addEventListener('change', function (event) {
      var key = layerKey(event.target);
      if (key && layerProxies[key]) syncLayer(key);
    });
    state.listeners = 2;

    adoptLate(doc);
    closeAll();
    state.installed = true;
    state.waiting_for = [];
    state.failure = null;
    state.one_identity_surface = true;
    state.mobile_sheet_hit_target_guard = true;
    state.layer_status_mirrored = true;
    state.layer_menu_stays_open = true;