GLOBALGRID2050 / EXPLORE CODE

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

G203 Regional Native Viewport (part 8)

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

700 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 584 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. G203 Regional Native Viewport geodesy · gridatlas / atlas/modules/g203-regional-native-viewport.js lines 5301–6000

G203 Regional Native Viewport

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

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

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

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

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 241 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Downstream impact
Used directly by 1 file: G203 Swarm 06 Viewport Lifecycle Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
Checked by G203 Swarm 06 Viewport Lifecycle Test.
Application
gridatlas · atlas/modules · script
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
referenced by G203 Swarm 06 Viewport Lifecycle Test (new URL import.meta.url)
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
installPrintStyle, buildPrintMap, pinViewportSize, unpinViewportSize, printView, clean, go, looksBlank, mapHandle, captureMap, grab, saveImage, say, grab, pdfEscape, buildMapPdf, captureMapJpeg, grab, pdfFileStamp, pad, savePdf, say, appendExport, appendEstateLinks, layerCheckbox, buildLayerControls, move, trayRoute, chipStaysOnMap, adoptLate
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/g203-regional-native-viewport.js:5301-6000 · blob 013cf98a02bb6c09199c357ac96a2b588892c0f4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
  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 + ']'
        + ' /Resources << /XObject << /Im0 5 0 R >> /Font << /F1 6 0 R >>'
        + ' /ExtGState << /GsA 7 0 R >> >> /Contents 4 0 R >>',
      '<< /Length ' + content.length + ' >>\nstream\n' + content + '\nendstream',
      '<< /Type /XObject /Subtype /Image /Width ' + pixelWidth + ' /Height ' + pixelHeight
        + ' /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length '
        + jpegBinary.length + ' >>\nstream\n' + jpegBinary + '\nendstream',
      '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>',
      '<< /Type /ExtGState /ca 0.55 >>'
    ];

    var out = '%PDF-1.4\n%\u00e2\u00e3\u00cf\u00d3\n';
    var offsets = [];
    var i;
    for (i = 0; i < objects.length; i += 1) {
      offsets.push(out.length);
      out += (i + 1) + ' 0 obj\n' + objects[i] + '\nendobj\n';
    }
    var xref = out.length;
    out += 'xref\n0 ' + (objects.length + 1) + '\n0000000000 65535 f \n';
    for (i = 0; i < offsets.length; i += 1) {
      out += ('0000000000' + offsets[i]).slice(-10) + ' 00000 n \n';
    }
    out += 'trailer\n<< /Size ' + (objects.length + 1) + ' /Root 1 0 R >>\n'
      + 'startxref\n' + xref + '\n%%EOF\n';

    var bytes = new Uint8Array(out.length);
    for (i = 0; i < out.length; i += 1) bytes[i] = out.charCodeAt(i) & 0xff;
    return { bytes: bytes, pageW: pageW, pageH: pageH };
  }

  /* JPEG rather than PNG: /DCTDecode embeds the bytes verbatim, so no
     compressor is needed here, and a basemap raster is what JPEG is for.
     Same render-frame discipline as captureMap -- a canvas without
     preserveDrawingBuffer is transparent to any reader outside the frame
     that drew it. */
  function captureMapJpeg(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/jpeg', 0.92); } catch (_) { url = null; }
      if (!url || url.indexOf('data:image/jpeg') !== 0 || looksBlank(canvas)) {
        then(null, canvas);
        return;
      }
      then(url, canvas);
    };
    if (map && map.once && map.triggerRepaint) {
      map.once('render', grab);
      map.triggerRepaint();
    } else {
      grab();
    }
  }

  function pdfFileStamp() {
    var d = new Date();
    var pad = function (n) { return (n < 10 ? '0' : '') + n; };
    return d.getUTCFullYear() + pad(d.getUTCMonth() + 1) + pad(d.getUTCDate())
      + pad(d.getUTCHours()) + pad(d.getUTCMinutes());
  }

  function savePdf(doc, button) {
    var say = function (text) { button.textContent = text; };
    say('... building PDF');
    captureMapJpeg(doc, function (jpegDataUrl, canvas) {
      if (!jpegDataUrl) {
        say('\u2298 The map could not be captured \u2014 try again once it has drawn');
        return;
      }
      var binary;
      try {
        binary = atob(jpegDataUrl.slice(jpegDataUrl.indexOf(',') + 1));
      } catch (_) {
        say('\u2298 The capture could not be decoded');
        return;
      }
      var built = buildMapPdf(binary, canvas.width, canvas.height,
        'GlobalGrid2050 \u00b7 Grid Atlas', attributionText(doc), (generationText() || 'generation unknown')
          + ' · ' + new Date().toISOString().slice(0, 16).replace('T', ' ') + ' UTC');
      var blob = new Blob([built.bytes], { type: 'application/pdf' });
      var url = URL.createObjectURL(blob);
      var link = doc.createElement('a');
      link.id = 'gridatlas-pdf-download';
      link.href = url;
      link.download = 'globalgrid2050-grid-atlas-' + pdfFileStamp() + '.pdf';
      doc.body.appendChild(link);
      link.click();
      setTimeout(function () {
        URL.revokeObjectURL(url);
        if (link.parentNode) link.parentNode.removeChild(link);
      }, 30000);
      say('\u2713 PDF saved \u00b7 ' + built.pageW + '\u00d7' + built.pageH + ' px, 1:1');
    });
  }

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

    /* EACH CONTROL IS NAMED, BECAUSE ITS LABEL IS NOT A NAME.
       Both controls carried `data-gm-export="1"` and nothing else, so the only
       way anything outside this function could tell them apart was by reading
       their text. saveImage() REWRITES that text on click -- to "Image saved",
       or to the refusal -- so a caller that found the button by its words lost
       it the moment it used it. The first outcome proof written for this
       feature did exactly that, and its failures were unattributable as a
       result. An id and a typed data attribute are stable across the click,
       across a relabelling, and across translation. The attribute keeps the
       name `data-gm-export` so the "already built" guard above and every
       existing check that looks for it still see it. */
    var print = doc.createElement('button');
    print.id = 'gridatlas-export-print';
    print.setAttribute('data-gm-export', 'print');
    print.setAttribute('type', 'button');
    print.textContent = '⎙ Print · or save as PDF';
    print.addEventListener('click', function () { printView(doc); });
    panel.appendChild(print);

    var pdf = doc.createElement('button');
    pdf.id = 'gridatlas-export-pdf';
    pdf.setAttribute('data-gm-export', 'pdf');
    pdf.setAttribute('type', 'button');
    pdf.textContent = '\u2913 Save this view as a PDF';
    pdf.addEventListener('click', function () { savePdf(doc, pdf); });
    panel.appendChild(pdf);

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

    return 3;
  }

  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;
    /* DESKTOP TOO, ON THE ARCHITECT'S INSTRUCTION.
       "in mobile view the Grid and subs buttons are nice show them on desktop
       TOO". Everything measured above is still true and is deliberately still
       computed; what changed is the conclusion drawn from it for a wide
       screen. The old argument was that on desktop these two are redundant
       with a menu that is always one click away. That is correct and it is
       not the point: GRID and SUBS are the two layers a reader toggles most,
       and a control used constantly belongs under the cursor rather than one
       click inside a menu. Redundancy with a menu is a reason to keep a
       shortcut, not to remove one.

       `coarse` and `narrow` are left in place and still read, so the phone
       measurement they encode -- and the reason it was made -- stays in the
       record rather than being deleted along with its conclusion. */
    return true;
  }

  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
      });
    }