GLOBALGRID2050 / EXPLORE CODE

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

Substation Intelligence V9 63 (part 8)

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line 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 1 file. Topic: Grid network and substations. Section 290 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. Substation Intelligence V9 63 geodesy · code-generator / apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js lines 4901–5600

Substation Intelligence V9 63

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

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

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

geodesycode-generator / apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js · lines 4901–5600 of 8590 · version 2026-09-06 23:58 (continued from section 283) · Not reached from any entry point (candidate for review) · pattern switchOn (shared by 4 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 238 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word '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: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
No other file in the estate was found to import it.
Application
code-generator · apps/substation-finder/Si · script
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
none found
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
appendGroup, appendEngineModules, done, appendStudies, exportStamp, attributionText, generationText, dropById, buildPrintFurniture, installPrintStyle, buildPrintMap, pinViewportSize, unpinViewportSize, printView, clean, go, looksBlank, mapHandle, captureMap, grab, saveImage, say, grab, pdfEscape, buildMapPdf
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/202609062358-substation-intelligence-v9-63.js:4901-5600 · blob 2c8121b277e1b152a96688f6a2e0d7ef83471376 · 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: duplicate_candidate
    nav.appendChild(right);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  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}',
      '#gridatlas-print-map{display:none}',
      /* A SCREEN GRAB, NOT A SLIDE.
         ------------------------------------------------------------------------
         This block used to hide the entire page -- `body > *{display:none}` --
         and print the map raster edge to edge, as a presentation slide. The
         architect printed one and the layer panel was gone: "The layers are
         vital otherwise the reader doesnt know what is being shown on the map",
         and then the contract itself: "Keep EVERYTHING IN THE PRINT, DONT TRY TO
         BE CLEVER, JUST A SCREEN GRAP OF WHAT THE USER SEES ... just print what
         is already being rendered on the display".

         So nothing is hidden any more. The one substitution that remains is not
         a choice: a WebGL canvas built without preserveDrawingBuffer is
         transparent to every rasteriser outside the frame that drew it, so its
         OWN captured pixels are laid in its OWN box. Everything else on the
         sheet is the live DOM at the size it had on screen. */
      '@media print{',
      '  @page{size:auto;margin:0}',
      /* The reader's paper is not a layout instruction. The view keeps the
         width and height it had on screen -- published by printView() as
         --gpf-vw / --gpf-vh -- so nothing reflows to paper width, which is
         what turned a 1390px-wide desktop view into a phone-shaped column. */
      '  html{background:#fff!important;height:auto!important;',
      '    overflow:visible!important}',
      '  body{background:#0b1416!important;margin:0!important;padding:0!important;',
      '    width:var(--gpf-vw,100%)!important;height:auto!important;',
      '    min-height:0!important;overflow:visible!important;display:block!important}',
      '  body>.dashboard{width:var(--gpf-vw,100%)!important;',
      '    height:var(--gpf-vh,100vh)!important;max-height:none!important;',
      '    min-height:0!important;overflow:hidden!important}',
      /* The captured raster sits in the canvas's own box, at its own size.
         Only ever shown when a capture actually succeeded: the body class is
         added by printView() after the PNG decodes, so a failed capture prints
         the live canvas exactly as before rather than a hole. */
      '  #gridatlas-print-map{display:block!important;position:absolute!important;',
      '    left:0!important;top:0!important;width:100%!important;height:100%!important;',
      '    max-width:none!important;max-height:none!important;object-fit:fill;',
      '    z-index:1;pointer-events:none}',
      '  body.gridatlas-print-raster .maplibregl-canvas{visibility:hidden!important}',
      /* PROVENANCE BELOW THE RECORD, NEVER ON TOP OF IT.
         The furniture used to be position:fixed;inset:0 with scrim bands at
         both ends, painted over the map -- which was fine when the map WAS the
         sheet, and is not fine now that the sheet is the reader's screen: a
         band over the top covers the menu bar and a band over the bottom covers
         the legend. "I like the headers and footers thats nice ... KEEP THAT",
         so it is kept, as a strip AFTER the view. Nothing the reader was
         looking at is obscured, and the stamp is still on the sheet. */
      '  #gridatlas-print-furniture{display:block!important;position:static!important;',
      '    width:var(--gpf-vw,100%)!important;box-sizing:border-box!important;',
      '    inset:auto!important;padding:5mm 7mm 6mm!important;background:#040a0c!important;',
      '    color:#eaf4f6!important;z-index:auto!important;',
      '    font:11px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace!important}',
      '  #gridatlas-print-furniture::before,#gridatlas-print-furniture::after{',
      '    content:none!important}',
      '  #gridatlas-print-furniture .gpf-head{letter-spacing:.28em;font-size:11px}',
      '  #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:2mm;font-size:15px;',
      '    letter-spacing:.02em}',
      '  #gridatlas-print-furniture .gpf-foot{position:static;margin-top:2mm;',
      '    display:flex;justify-content:space-between;gap:6mm;',
      '    font-size:8.5px;opacity:.75}',
      /* The map chain is given an explicit print height rather than `auto`.
         Measured at 202609050354: with `height:auto` the canvas was 385x0 on a
         393x852 phone and 1392x0 on a 1400x900 desktop, and Page.printToPDF
         produced ZERO image XObjects -- a sheet with no map on it. The height
         has to be stated. */
      '  .map-container{position:relative!important;width:100%!important;',
      '    height:100%!important;max-height:100%!important;min-height:0!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}',
      /* One sheet. The view plus its strip is the record; nothing may spill. */
      '  body>*{break-inside:avoid;page-break-inside:avoid}',
      '  body{page-break-after:avoid}',
      '}'
    ].join('');
    doc.head.appendChild(style);
  }

  /* THE SHEET NEEDS A RASTER, NOT A LIVE CANVAS.
     ------------------------------------------------------------------------
     Giving the map chain a print height was necessary and not sufficient. With
     the height restored, `Page.printToPDF` on the pinned candidate emitted an
     image XObject of exactly the map's size -- 383x838 -- and every one of its
     962,862 inflated bytes was (0,0,0), behind an /SMask whose 320,954 bytes
     were all zero. A fully transparent rectangle the shape of the map. The
     reader still gets a blank sheet; the only difference is that the blankness
     now has dimensions.

     The cause is the one saveImage() already knew about. The map is a WebGL
     canvas created without preserveDrawingBuffer, so its drawing buffer is
     gone by the time anything outside the frame that drew it goes looking --
     and the print rasteriser is outside that frame, exactly as toDataURL was.
     No stylesheet can fix that, because it is not a layout problem.

     So printing captures the map the same way saving does: inside a render
     frame, into a PNG, which is placed over the map for print media only and
     removed afterwards. A raster survives rasterisation. If the capture fails
     -- a tainted canvas, no handle, a blank read -- the sheet is printed
     anyway with the live canvas, which is no worse than before and still
     carries the furniture, title and credit. */
  /* The raster goes in the CANVAS'S OWN BOX, not over the page.
     ------------------------------------------------------------------------
     It used to be appended to <body> and stretched `position:fixed;inset:0`,
     because everything else was hidden and the map WAS the sheet. Now that the
     sheet is the reader's screen, a full-viewport image would cover the menu
     bar, the layer panel and the legend -- the very things the architect said
     were missing. So it is inserted as a sibling of the canvas, inside the
     positioned canvas container, and fills exactly that box.

     Falls back to <body> only if the container cannot be found, which keeps a
     sheet with a map on it rather than none. */
  function buildPrintMap(doc, dataUrl) {
    dropById(doc, 'gridatlas-print-map');
    var image = doc.createElement('img');
    image.id = 'gridatlas-print-map';
    image.alt = '';
    image.src = dataUrl;
    var canvas = doc.querySelector('.maplibregl-canvas');
    var host = canvas && canvas.parentNode;
    if (host && host.appendChild) host.appendChild(image);
    else doc.body.appendChild(image);
    return image;
  }

  /* PUBLISH THE SCREEN'S OWN SIZE TO THE STYLESHEET.
     ------------------------------------------------------------------------
     A print stylesheet cannot read the viewport: @media print measures the
     PAPER, so `100vw` inside it is the sheet, not the screen. Without these
     two custom properties the layout reflows to paper width, which is what
     turned a 1390px-wide desktop view into a phone-shaped column on the sheet.
     Read once, at the moment Print is pressed, from the box the reader is
     actually looking at. */
  function pinViewportSize(doc) {
    var root = doc.documentElement;
    if (!root || !root.style || !root.style.setProperty) return;
    var width = Number(window.innerWidth) || (root.clientWidth || 0);
    var height = Number(window.innerHeight) || (root.clientHeight || 0);
    if (width > 0) root.style.setProperty('--gpf-vw', width + 'px');
    if (height > 0) root.style.setProperty('--gpf-vh', height + 'px');
  }

  function unpinViewportSize(doc) {
    var root = doc.documentElement;
    if (!root || !root.style || !root.style.removeProperty) return;
    root.style.removeProperty('--gpf-vw');
    root.style.removeProperty('--gpf-vh');
  }

  function printView(doc) {
    installPrintStyle(doc);
    pinViewportSize(doc);
    var furniture = buildPrintFurniture(doc);
    var shot = null;
    var clean = function () {
      if (furniture && furniture.parentNode) furniture.parentNode.removeChild(furniture);
      if (shot && shot.parentNode) shot.parentNode.removeChild(shot);
      /* The canvas is only hidden while a raster stands in for it. Removing
         the class with the image keeps the two facts in one place: a failed
         capture never leaves an invisible map behind. */
      if (doc.body && doc.body.classList) {
        doc.body.classList.remove('gridatlas-print-raster');
      }
      unpinViewportSize(doc);
      window.removeEventListener('afterprint', clean);
    };
    window.addEventListener('afterprint', clean);
    var go = function () {
      /* Give the browser a frame to apply the print stylesheet before the
         dialog measures the page; without it the map is measured at its
         screen size. */
      window.setTimeout(function () { window.print(); }, 60);
      /* afterprint is not fired by every browser, notably some mobile ones,
         so the furniture is removed on a timer as well. It is display:none
         off print anyway, so a late removal changes nothing a reader sees. */
      window.setTimeout(clean, 20000);
    };
    captureMap(doc, function (dataUrl) {
      if (dataUrl) {
        shot = buildPrintMap(doc, dataUrl);
        if (doc.body && doc.body.classList) {
          doc.body.classList.add('gridatlas-print-raster');
        }
        /* Wait for the browser to decode it: printing a raster it has not
           finished reading is the same blank sheet by another route. */
        if (shot.decode) { shot.decode().then(go, go); return; }
        shot.onload = go;
        shot.onerror = go;
        return;
      }
      go();
    });
  }

  /* 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;
    }
  }

  /* 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 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. The guard was sound; only the lookup was wrong.

     Both export paths need it, so it is looked up in one place. */
  function mapHandle() {
    var map = window.__GRIDATLAS_V9_MAP__;
    if (map && map.getCanvas) return map;
    return (window.map && window.map.getCanvas) ? window.map : null;
  }

  /* Capture the map INSIDE a render frame and hand the result to `then`.
     A canvas created without preserveDrawingBuffer is transparent to every
     reader outside the frame that drew it -- the browser's own print
     rasteriser included. */
  function captureMap(doc, then) {
    var map = mapHandle();
    var canvas = doc.querySelector('.maplibregl-canvas')
      || (map && map.getCanvas ? map.getCanvas() : null);
    if (!canvas) { then(null, null); return; }
    var grab = function () {
      var url = null;
      try { url = canvas.toDataURL('image/png'); } catch (_) { url = null; }
      if (!url || looksBlank(canvas)) { then(null, canvas); return; }
      then(url, canvas);
    };
    if (map && map.once && map.triggerRepaint) {
      map.once('render', grab);
      map.triggerRepaint();
    } else {
      grab();
    }
  }

  function saveImage(doc, button) {
    var map = mapHandle();
    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();
    }
  }

  /* A PDF THE PAGE WRITES ITSELF.
     ------------------------------------------------------------------------
     "get the PDF PRINTER UP AND RUNNING so the WORLD CAN TAKE THE DATA" --
     the architect, after Firefox rendered the print preview correctly and
     then produced NO FILE AT ALL when Print was pressed with a physical
     printer selected.

     Every route to a PDF before this one went through the browser print
     pipeline: window.print(), a dialog, a destination, a driver. That
     pipeline differs in every browser, it is the part this code does not
     own, and on his machine it is the part that failed. So this does not use
     it at all. It writes the PDF bytes here and hands the reader a file.

     ONE PAGE, SIZED TO THE IMAGE. The MediaBox takes the captured raster's
     own aspect ratio, so the map covers the sheet corner to corner with no
     margin AND nothing is cropped -- the brochure that object-fit:cover can
     only approximate on paper, done exactly.

     The image is embedded as JPEG with /DCTDecode, which is why there is no
     compressor in this file: the canvas already produces JPEG bytes and PDF
     reads that stream natively. */
  function pdfEscape(text) {
    return String(text == null ? '' : text)
      .replace(/\\/g, '\\\\')
      .replace(/\(/g, '\\(')
      .replace(/\)/g, '\\)')
      .replace(/[^\x20-\x7e]/g, '');
  }

  function buildMapPdf(jpegBinary, pixelWidth, pixelHeight, heading, leftFoot, rightFoot) {
    /* ONE PAGE UNIT PER CAPTURED PIXEL. NO PAPER, NO REDUCTION.
       -------------------------------------------------------------------
       This scaled the long edge to 1190pt, "A3-ish". That is a paper
       assumption, and on a 1390x518 desktop capture it emitted a 1190x443
       page -- a 14% REDUCTION of the record. "THE PRINT MUST BE HIGH RES OF
       WHAT THE USER SEES NOT A REDUCED CRAP VERSION", "WE ARE NOT USING
       PAPER", "THIS IS A CALL FOR A 2026 era TELEPRINTER".

       A teleprinter emits the record as it was. So the page is exactly the
       captured raster: one PDF unit per pixel, no scaling in either
       direction, and the canvas is captured at devicePixelRatio -- 1149x2514
       on a phone at dpr 3, native on a desktop at dpr 1. Nothing is resampled
       on the way out, and a viewer showing it at 100% shows the reader's own
       pixels. */
    var pageW = pixelWidth;
    var pageH = pixelHeight;
    /* Furniture scaled to the record rather than to an assumed sheet, so a
       2514px-tall phone capture and a 518px-tall desktop one both carry a
       legible credit rather than one sized for A3. */
    var unit = Math.max(1, Math.min(pageW, pageH) / 520);
    var band = Math.round(Math.min(pageH * 0.14, 46 * unit));
    var headSize = Math.round(13 * unit);
    var footSize = Math.round(8 * unit);
    var pad = Math.round(14 * unit);
    var rightX = Math.max(pad, pageW - pad - String(rightFoot).length * footSize * 0.56);

    var content = [
      'q', pageW + ' 0 0 ' + pageH + ' 0 0 cm', '/Im0 Do', 'Q',
      /* Scrim bands at 55% alpha so the text reads over a dark basemap
         without dimming the map itself. */
      'q', '/GsA gs', '0.02 0.06 0.07 rg',
      '0 ' + (pageH - band) + ' ' + pageW + ' ' + band + ' re f',
      '0 0 ' + pageW + ' ' + band + ' re f', 'Q',
      'BT /F1 ' + headSize + ' Tf 1 1 1 rg ' + pad + ' ' + (pageH - pad - headSize)
        + ' Td (' + pdfEscape(heading) + ') Tj ET',
      'BT /F1 ' + footSize + ' Tf 0.86 0.93 0.94 rg ' + pad + ' ' + Math.round(pad * 0.7)
        + ' Td (' + pdfEscape(leftFoot) + ') Tj ET',
      'BT /F1 ' + footSize + ' Tf 0.86 0.93 0.94 rg ' + rightX + ' ' + Math.round(pad * 0.7)
        + ' Td (' + pdfEscape(rightFoot) + ') Tj ET'
    ].join('\n');

    var objects = [
      '<< /Type /Catalog /Pages 2 0 R >>',
      '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
      '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ' + pageW + ' ' + pageH + ']'