GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / code-generator / apps/substation-finder/Ps

Menu Bar and 1 more file (part 1)

A JavaScript file in the substation finder folder of Code Generator that draws engine graph and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

700 lines of JavaScript from code-generator, in 2 files. Topic: Grid network and substations. Section 270 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. Place Global Search V9 5 geodesy · code-generator / apps/substation-finder/Ps/202609071213-place-global-search-v9-5.js lines 701–923
  2. Menu Bar render · code-generator / apps/substation-finder/Si/202609031958-menu-bar.js lines 1–477

Place Global Search V9 5

A JavaScript file in the substation finder folder of Code Generator that maps Renewable Energy Planning Database (REPD) projects, using SHA-256 and uses data from the GridAtlas repository.

Set aside from the main view: 96% of its lines are the same as atlas/cartridges/202611180026-place-global-search-v9-5.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Place Global Search V9 5; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.957 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-place-global-search-v9-5.js:1-931 c3ef9b6b82b3e983feb93015b168fed3d11322b9
  • sha256 15f324e5c279050882f7e3ce83a915c070b6ed19095efcac4ae20af4ef19fdfa
  • target sha256 575721ea584187c2b9b857408a3e6136879d7f6876f1e6d7a0b925051124a49c
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesycode-generator / apps/substation-finder/Ps/202609071213-place-global-search-v9-5.js · lines 701–923 of 923 · version 2026-09-07 12:13 (continued from section 269) · pattern loadDerivedCoordinates (shared by 4 files)

What it does
It maps REPD projects, offshore coordinates, postcodes and the REPD register. Defines 41 functions or classes, including invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): 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: postcodes, the REPD register.
Inputs & outputs
In: data source: gridatlas data; data source: postcodes.io; data source: OpenStreetMap Nominatim; Parquet file repd_projects_202608290716.parquet; JSON file repd_v9_manifest_202608290716.json; JSON file offshore-coordinates.json; DuckDB queries. Out: interactive map. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
What it achieves
It marks deep link cancelled (`markDeepLinkCancelled`), normalises compact (`normaliseCompact`) and parses groups (`parseGroups`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. It responds to gridatlas, click and input events.
Why it matters
Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
Application
code-generator · apps/substation-finder/Ps · script
VEDIC
QUERY (GG2050-VEDIC-000046): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_predicate
VEDIC
SCORE (GG2050-VEDIC-000047): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_sort_expression
VEDIC
UK GEOCODE (GG2050-VEDIC-000048): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → uk_location_candidates
Uses
none found
Used by
linked from Code Generator — Substation Finder Page (link), mentioned in Standalone (comment link)
Produces
invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime, promise
Defines here
stillOwned, retryExactRepdDeepLink, bindSearch
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Ps/202609071213-place-global-search-v9-5.js:701-923 · blob 971baf65e1e2b012900a5cb29a0bbd3367929bad · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
      return;
    }

    const arrival = suppliedArrivalFields(params, repdRef);
    let coordinator = null;
    let ownerEpoch = null;
    try {
      invariant(/^[A-Za-z0-9-]{1,40}$/.test(repdRef), 'invalid exact REPD deep-link identity');
      coordinator = arrivalCoordinator();
      invariant(coordinator, 'shared arrival coordinator unavailable');
      if (Number.isInteger(expectedOwnerEpoch)) {
        if (!coordinator.arrivalGate.isCurrent(expectedOwnerEpoch)) return;
        ownerEpoch = expectedOwnerEpoch;
      } else {
        ownerEpoch = coordinator.claimPendingArrival(window.location.search);
      }
      state.deep_link = {
        ...arrival, owner_epoch: ownerEpoch, status: 'RECEIVING',
        resolved: false, mapped: false,
        identity_source: 'ACTIVE_REGISTER_PENDING'
      };
      const stillOwned = () => coordinator.arrivalGate.isCurrent(ownerEpoch);
      const querySerial = ++activeQuerySerial;
      input.value = repdRef;
      const results = await queryOfficialRepd(repdRef, querySerial, stillOwned);
      if (!stillOwned() || querySerial !== activeQuerySerial) return;
      const exact = results.find(result => String(result.repd_ref) === repdRef);
      if (!exact) {
        // A successful query with no exact row is evidence about this active
        // snapshot, not a network failure and not evidence that the supplied
        // project never existed. Keep the link's point and identity separate.
        renderResults(results, resultsEl);
        document.body.dataset.gridatlasRepdRef = repdRef;
        document.body.dataset.gridatlasRepdDeepLink = 'not-in-active-register';
        state.deep_link = {
          ...arrival,
          owner_epoch: ownerEpoch,
          status: 'NOT_IN_ACTIVE_REGISTER',
          resolved: false,
          mapped: false,
          supplied_point_usable: hasSafeMapPoint(arrival),
          identity_source: 'ARRIVAL_LINK',
          official_active_register_match: false,
          statement: 'No exact identity in the active-register snapshot; supplied arrival fields retained.'
        };
        return;
      }
      renderResults(results, resultsEl);
      await waitForCapturedMap();
      if (!stillOwned()) return;

      /* A ref the register does not locate used to be treated worse than a ref
         the register does not contain. The not-in-register branch above keeps
         the supplied arrival point and degrades gracefully; this branch found
         its row, could not map it, and threw - so a project present in the
         register but without a coordinate showed the user a failure card.
         Measured on the live page: between 3 and 8 of 20 MAP links carry no
         coordinate at all, so there was nothing to fall back to either.

         Offshore is where this bites. 8 of 101 offshore rows carry no easting
         or northing, and the Crown Estate leases the seabed under them, so a
         derived point exists for 6 of the 8 in atlas/data/offshore-coordinates.json.
         Using it is honest as long as the card says the coordinate is derived
         and the identity is not: the register named the project, the lease
         located it. */
      const derived = !hasSafeMapPoint(exact) ? await derivedCoordinateFor(repdRef) : null;
      if (derived) {
        exact.longitude = derived.longitude;
        exact.latitude = derived.latitude;
      }
      /* No register point and no lease point. Measured offline on v9.144:
         13432 is in the register, has no coordinate, is in no lease, and
         still reached the invariant below and showed a failure card. A name
         the register confirmed is worth more than a card that says try again,
         so the identity stands and the map does not move. If the link itself
         carried a usable point it is used and labelled as the link's, never
         as the register's. */
      const linkPoint = !hasSafeMapPoint(exact) && hasSafeMapPoint(arrival)
        ? { longitude: arrival.longitude, latitude: arrival.latitude } : null;
      if (linkPoint) {
        exact.longitude = linkPoint.longitude;
        exact.latitude = linkPoint.latitude;
      }
      if (!hasSafeMapPoint(exact)) {
        document.body.dataset.gridatlasRepdRef = repdRef;
        document.body.dataset.gridatlasRepdDeepLink = 'resolved-unmapped';
        state.deep_link = {
          ...arrival,
          owner_epoch: ownerEpoch,
          repd_ref: repdRef,
          status: 'RESOLVED_UNMAPPED',
          resolved: true,
          mapped: false,
          name: exact.name,
          technology: exact.technology,
          capacity_mw: exact.capacity_mw,
          status_value: exact.status,
          identity_source: 'OFFICIAL_ACTIVE_REGISTER',
          official_active_register_match: true,
          coordinate_source: 'NONE',
          coordinate_derived: false,
          coordinate_lease: null,
          coordinate_tenant: null,
          coordinate_statement: 'The register names this project but holds no coordinate for it, and no Crown Estate lease covers it. Identity confirmed; position unknown; the map was not moved.',
          statement: 'Exact identity in the active-register snapshot; no coordinate from any source held.'
        };
        return;
      }
      if (!selectResult(exact, { deepLinkEpoch: ownerEpoch })) return;
      if (!stillOwned()) return;
      invariant(state.last_selection?.repd_ref === repdRef, 'exact REPD selection was not retained');
      invariant(state.last_selection?.mapped === true, 'exact REPD identity did not fly to a safe map point');
      document.body.dataset.gridatlasRepdRef = repdRef;
      document.body.dataset.gridatlasRepdDeepLink = 'resolved';
      state.deep_link = {
        status: 'RESOLVED',
        owner_epoch: ownerEpoch,
        repd_ref: repdRef,
        resolved: true,
        mapped: true,
        /* Identity and coordinate have different provenance and are reported
           separately. The register named this project; where it did not locate
           it, a Crown Estate lease did, and the card must not present the two
           as one fact. */
        coordinate_source: derived ? derived.source : linkPoint ? 'ARRIVAL_LINK' : 'OFFICIAL_ACTIVE_REGISTER',
        coordinate_derived: Boolean(derived),
        coordinate_lease: derived ? derived.lease : null,
        coordinate_tenant: derived ? derived.tenant : null,
        coordinate_statement: derived
          ? 'Position derived from Crown Estate lease geometry because the register carries no coordinate for this project. The identity is the register’s; the position is not.'
          : linkPoint
            ? 'Position taken from the arrival link because the register carries no coordinate for this project and no lease covers it. The identity is the register’s; the position is the link’s.'
            : 'Position as published in the active register.',
        name: exact.name,
        postcode: exact.postcode,
        longitude: exact.longitude,
        latitude: exact.latitude,
        technology: exact.technology,
        capacity_mw: exact.capacity_mw,
        status_value: exact.status,
        identity_source: 'OFFICIAL_ACTIVE_REGISTER',
        official_active_register_match: true
      };
    } catch (error) {
      if (coordinator && Number.isInteger(ownerEpoch)
          && !coordinator.arrivalGate.isCurrent(ownerEpoch)) return;
      const message = String(error?.message || error);
      state.failures.push({ phase: 'exact_repd_deep_link', repd_ref: repdRef, message });
      state.deep_link = {
        ...arrival, owner_epoch: ownerEpoch, status: 'FAILED',
        resolved: false, mapped: false, message,
        identity_source: 'ACTIVE_REGISTER_CHECK_FAILED'
      };
      document.body.dataset.gridatlasRepdDeepLink = 'failed';
      console.error('[V9 EXACT REPD DEEP LINK]', error);
    }
  }

  async function retryExactRepdDeepLink(input, resultsEl, ownerEpoch) {
    const coordinator = arrivalCoordinator();
    invariant(coordinator, 'shared arrival coordinator unavailable for retry');
    invariant(Number.isInteger(ownerEpoch), 'identity retry requires one shared owner epoch');
    if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
    state.identity_retry_count += 1;
    await resetOfficialRuntime();
    if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
    return receiveExactRepdDeepLink(input, resultsEl, ownerEpoch);
  }

  function bindSearch() {
    const input = document.getElementById('search-input');
    const button = document.getElementById('search-btn');
    const resultsEl = document.getElementById('search-results');
    invariant(input && button && resultsEl, 'V8 search controls missing');
    input.setAttribute('placeholder', 'Search project, address, postcode or place...');
    input.setAttribute('aria-label', 'Search project, address, postcode or place');

    input.addEventListener('input', event => {
      event.stopImmediatePropagation();
      invalidatePendingDeepLink('user-search-input');
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => executeSearch(input, resultsEl, false), 180);
    }, true);

    input.addEventListener('keydown', event => {
      if (event.key === 'Enter') {
        event.preventDefault();
        event.stopImmediatePropagation();
        invalidatePendingDeepLink('user-search-submit');
        clearTimeout(debounceTimer);
        executeSearch(input, resultsEl, true);
      } else if (event.key === 'Escape') {
        event.stopImmediatePropagation();
        invalidatePendingDeepLink('user-search-dismiss');
        resultsEl.style.display = 'none';
      }
    }, true);

    button.addEventListener('click', event => {
      event.preventDefault();
      event.stopImmediatePropagation();
      invalidatePendingDeepLink('user-search-submit');
      clearTimeout(debounceTimer);
      executeSearch(input, resultsEl, true);
    }, true);

    state.retry_exact_deep_link = (ownerEpoch) =>
      retryExactRepdDeepLink(input, resultsEl, ownerEpoch);
    state.ready = true;
  }

  window.addEventListener('DOMContentLoaded', () => {
    try {
      bindSearch();
      const input = document.getElementById('search-input');
      const resultsEl = document.getElementById('search-results');
      void receiveExactRepdDeepLink(input, resultsEl);
    } catch (error) {
      state.failures.push({ phase: 'bind', message: String(error?.message || error) });
      console.error('[V9 PLACE SEARCH INIT]', error);
    }
  }, { once: true });
})();

Menu Bar

A JavaScript file in the substation finder folder of Code Generator that draws engine graph and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

rendercode-generator / apps/substation-finder/Si/202609031958-menu-bar.js · lines 1–477 of 1805 · version 2026-09-03 19:58 · pattern unpinViewportSize (shared by 5 files)

What it does
It draws engine graph and substations. Defines 57 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 upstream_foresight (path word 'substation'): 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: substations.
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-; downloaded file globalgrid2050-grid-atlas-; canvas drawing.
Downstream impact
Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
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
Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
Application
code-generator · apps/substation-finder/Si · script
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
linked from Code Generator — Substation Finder Page (link)
Produces
array, cleanText, layerKey, layerLabel, layerGroup, inventory, required, installStyle, syncAttribClearance, closeAll, syncLayer, syncAll
Defines here
array, cleanText, layerKey, layerLabel, layerGroup, inventory, required, installStyle, syncAttribClearance, closeAll, syncLayer, syncAll, clampPanel, openMenu
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609031958-menu-bar.js:1-477 · blob c4b849fd72540c8a19016d94053e4d488c2829d2 · 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: unknown
/* GridAtlas menu bar.

   v9.94 proved that the conventional menu is the right shape and the wrong
   implementation can still strand the product. That version enumerated only
   direct children of .map-controls and then hid the whole owner container.
   Scope, Clear and their result surfaces were nested, so they disappeared.

   This successor has a stricter admission rule:

   - it installs nothing until the engine's 60 layer controls and the three
     Pipeline News controls are all present and uniquely identified;
   - the Grid menu proxies those 63 ORIGINAL inputs, so their delegated engine
     handlers remain the only implementation of behaviour;
   - action buttons are moved as the same DOM nodes, preserving listeners and
     state, while result panels stay with the map that owns them;
   - legacy containers collapse only after the complete inventory is built.
     A missing control leaves the old interface reachable and is published as
     a failure instead of being silently skipped.

   The six names are the architect's current vocabulary. In particular Grid
   is not exposed through the abandoned "Select layers" alias. */
(function gridAtlasMenuBar() {
  'use strict';

  if (typeof window === 'undefined' || typeof document === 'undefined') return;

  var SCHEMA = 'gridatlas.menu-bar.v2';
  var BAR_ID = 'gridatlas-menu-bar';
  var STYLE_ID = BAR_ID + '-css';
  var FAILURE_ID = BAR_ID + '-failure';
  var MENUS = ['File', 'Edit', 'View', 'Scope', 'Grid', 'About'];
  var EXPECTED_ENGINE_LAYERS = 60;
  var EXPECTED_PIPELINE_LAYERS = 3;
  var EXPECTED_LAYER_CONTROLS = 63;
  var MAX_TRIES = 160;             // 40 s: the register UI is built after map load

  var NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  if (NS.menuBar && NS.menuBar.schema === SCHEMA) return;

  var state = {
    schema: SCHEMA,
    menus: MENUS.slice(),
    bar_id: BAR_ID,
    installed: false,
    controls_moved: 0,
    layer_controls: 0,
    engine_layer_controls: 0,
    pipeline_layer_controls: 0,
    expected_layer_controls: EXPECTED_LAYER_CONTROLS,
    panel_counts: {},
    failure: null,
    tries: 0,
    listeners: 0,
    closed_at_rest: true,
    one_identity_surface: false
  };
  NS.menuBar = state;

  var bar = null;
  var panels = {};
  var titles = [];
  var layerTargets = Object.create(null);
  var layerProxies = Object.create(null);
  var forwardingLayerChoice = false;
  var observer = null;
  var timer = null;
  var brandSlot = null;    // holds the v8 .hud-header (VENTUS wordmark), fused into the bar itself
  var gridHead = null;     // holds the v8 .scada-brand + .status-legend, restored at the top of Grid
  var gridBody = null;     // holds the layer groups, so gridHead never enters the 2-column flow

  function array(value) {
    return Array.prototype.slice.call(value || []);
  }

  function cleanText(value) {
    return String(value == null ? '' : value).replace(/\s+/g, ' ').trim();
  }

  function layerKey(input) {
    if (!input || !input.getAttribute) return '';
    var engine = input.getAttribute('data-layer-id');
    if (engine) return 'engine:' + engine;
    var pipeline = input.getAttribute('data-pn-layer');
    return pipeline ? 'pipeline:' + pipeline : '';
  }

  function layerLabel(input) {
    var label = input && input.closest ? input.closest('label') : null;
    var span = label && label.querySelector
      ? label.querySelector('[data-base-label], [data-pn-label], span') : null;
    var base = span && span.getAttribute ? span.getAttribute('data-base-label') : '';
    /* The V8 panel exposes WAIT/LOAD/OK/FAIL beside every layer.  The first
       menu implementation preferred data-base-label, which deliberately
       strips that live suffix.  That made a successful load and a failed
       load indistinguishable in the only layer surface left on a phone. */
    var text = cleanText((span && span.textContent) || base
      || (label && label.textContent) || layerKey(input).split(':').slice(1).join(':'));
    return text || layerKey(input);
  }

  function layerGroup(input) {
    var group = input && input.closest ? input.closest('.key-group') : null;
    var title = group && group.querySelector ? group.querySelector('.key-title') : null;
    return cleanText(title && title.textContent) || 'Other layers';
  }

  function inventory(doc) {
    var host = doc.getElementById('scada-ui-container');
    var engine = host ? array(host.querySelectorAll(
      'input[type="checkbox"][data-layer-id]')) : [];
    var pipeline = host ? array(host.querySelectorAll(
      'input[type="checkbox"][data-pn-layer]')) : [];
    var controls = engine.concat(pipeline);
    var keys = controls.map(layerKey);
    var unique = new Set(keys);
    return {
      host: host,
      engine: engine,
      pipeline: pipeline,
      controls: controls,
      keys: keys,
      complete: engine.length === EXPECTED_ENGINE_LAYERS
        && pipeline.length === EXPECTED_PIPELINE_LAYERS
        && controls.length === EXPECTED_LAYER_CONTROLS
        && unique.size === EXPECTED_LAYER_CONTROLS
        && !keys.includes('')
    };
  }

  state.inspect = function () {
    var found = inventory(document);
    return {
      engine: found.engine.length,
      pipeline: found.pipeline.length,
      total: found.controls.length,
      unique: new Set(found.keys).size,
      complete: found.complete
    };
  };

  function required(doc) {
    var found = inventory(doc);
    var nodes = {
      host: doc.querySelector('.map-container'),
      stack: doc.querySelector('.map-controls'),
      search: doc.querySelector('.search-bar-wrapper'),
      header: doc.querySelector('.hud-header'),
      exportButton: doc.getElementById('btn-export'),
      statusButton: doc.getElementById('btn-status'),
      fullscreenButton: doc.getElementById('btn-fullscreen'),
      radiusButton: doc.getElementById('btn-radius'),
      radiusAreaButton: doc.getElementById('btn-radius-area'),
      zoneButton: doc.getElementById('btn-zonedraw'),
      measureButton: doc.getElementById('btn-measure')
    };
    var missing = Object.keys(nodes).filter(function (key) { return !nodes[key]; });
    if (!found.complete) missing.push('63 unique layer controls');
    return { found: found, nodes: nodes, missing: missing };
  }

  function installStyle(doc) {
    if (doc.getElementById(STYLE_ID)) return;
    var style = doc.createElement('style');
    style.id = STYLE_ID;
    style.textContent = [
      '#' + BAR_ID + '{position:absolute;top:0;left:0;right:0;height:36px;z-index:10020;',
      'display:flex;align-items:stretch;gap:0;padding-left:env(safe-area-inset-left);',
      'padding-right:env(safe-area-inset-right);box-sizing:border-box;',
      'background:rgba(4,10,13,.95);border-bottom:1px solid rgba(80,220,240,.3);',
      'font:11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;',
      '-webkit-backdrop-filter:blur(7px);backdrop-filter:blur(7px);',
      'isolation:isolate;pointer-events:auto}',
      '#' + BAR_ID + ' .gm-menu{position:relative;min-width:0}',
      '#' + BAR_ID + ' .gm-title{appearance:none;border:0;background:transparent;color:#cfeef6;',
      'min-height:36px;padding:0 11px;cursor:pointer;font:inherit;letter-spacing:.05em;',
      'text-transform:uppercase;white-space:nowrap}',
      '#' + BAR_ID + ' .gm-title:hover,#' + BAR_ID + ' .gm-title:focus-visible,',
      '#' + 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 };