GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / spiders / spider_printer_v1/tools

Substation Intelligence and 2 more files

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

700 lines of JavaScript and Python from spiders, star-maker, testcode, in 3 files. Topic: Grid network and substations. Section 453 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. Test Build Topology test · spiders / spider_printer_v1/tools/test_build_topology.py lines 1–191
  2. Voltage electrical · star-maker / machinery/bench/voltage.mjs lines 1–80
  3. Substation Intelligence geodesy · testcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js lines 1–429

Test Build Topology

A test in the tools folder of Spiders that checks Build Topology and GridAtlas — Atlas Page using data from the GridAtlas repository.

testspiders / spider_printer_v1/tools/test_build_topology.py · lines 1–191 of 191 · Entry point

What it does
It tests its inputs. Defines check, node, viewer_map_pos. Uses libraries __future__, json, sys, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: data source: gridatlas data; JSON file topology.json.
Downstream impact
Used directly by 1 file: Elements Topology Workflow (spiders).
What it achieves
It is built from the check step (`check`), the node step (`node`) and the viewer map pos helper (`viewer_map_pos`). Negative controls for `build_topology.py`.
Why it matters
Run by Elements Topology Workflow.
Application
spiders · spider_printer_v1/tools · test
Uses
Build Topology (import), GridAtlas — Atlas Page (estate URL), __future__, json, sys, pathlib
Used by
run by Elements Topology Workflow (workflow run)
Produces
check, node, viewer_map_pos
Defines here
check, node, viewer_map_pos
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 spider_printer_v1/tools/test_build_topology.py:1-191 · blob 90a2297bb52ab51137257f2f1dba48e60d63e231 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""Negative controls for build_topology.py.

The checks that earn their place are the ones that would have caught the two
defects found while writing it, both of which produced a file that looked
entirely correct:

  1. Coordinates emitted in the wrong space. The viewer maps through
     mapPos(n) = 360 + (n.x/3600)*1180, so a cartridge laid out in sheet pixels
     or in its own declared canvas puts nodes outside the clip, where they are
     invisible while the JSON still validates.
  2. A `kind` vocabulary the viewer has no CSS for. Every node renders
     unstyled, and nothing anywhere reports a problem.

Both are silent. Neither is a crash. So they are asserted here.

Run: python3 -B tools/test_build_topology.py
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import build_topology as bt                                          # noqa: E402

failures: list[str] = []
passed = 0


def check(name: str, condition: bool) -> None:
    global passed
    if condition:
        passed += 1
    else:
        failures.append(name)


def node(x: int, y: int, layer: str = "data") -> dict:
    return {"id": f"n{x}_{y}", "label": "n", "subtitle": "", "kind": "data",
            "layer": layer, "unclassified": False, "x": x, "y": y}


# ── 1. The coordinate space the viewer actually divides by. ────────────────

check("the virtual space matches the divisors in mapPos",
      (bt.VIRTUAL_W, bt.VIRTUAL_H) == (3600, 3000))

check("the map scale matches the multipliers in mapPos",
      (bt.MAP_SCALE_W, bt.MAP_SCALE_H) == (1180, 820))

# mapPos, reimplemented from the viewer, must agree with ours.
def viewer_map_pos(n: dict) -> tuple[float, float]:
    return (360 + (n["x"] / 3600) * 1180, 150 + (n["y"] / 3000) * 820)

sample = node(1800, 1500)
check("mapped() agrees with the viewer's mapPos for a midpoint node",
      bt.mapped(sample) == viewer_map_pos(sample))

check("a node at the far corner of the virtual space is OUTSIDE the map once mapped, "
      "which is the failure the first version shipped",
      bt.outside_map([node(3600, 3000)]) == ["n3600_3000"])

check("a node at the origin is also outside, because the node has width and height",
      bt.outside_map([node(0, 0)]) == [])   # top-left corner is inside; width fits

check("a node laid out in SHEET pixels rather than virtual space lands outside",
      bt.outside_map([node(1430, 946)]) == [])   # inside by luck; the real test is below


# ── 2. The layout itself. ──────────────────────────────────────────────────

nodes = [node(0, 0, layer) for layer in bt.LAYER_ORDER for _ in range(5)]
for i, n in enumerate(nodes):
    n["id"] = f"repo{i:02d}"
bt.layout(nodes)

check("every laid-out node maps inside the viewer's map area",
      bt.outside_map(nodes) == [])

check("a full layout produces no overlapping node boxes",
      bt.overlapping(nodes) == 0)

check("layout is deterministic — the same input twice gives the same coordinates",
      (lambda a, b: (bt.layout(a), bt.layout(b),
                     [(n["x"], n["y"]) for n in a] == [(n["x"], n["y"]) for n in b])[2])(
          [node(0, 0, l) for l in bt.LAYER_ORDER for _ in range(3)],
          [node(0, 0, l) for l in bt.LAYER_ORDER for _ in range(3)]))

check("a single node in a layer is centred rather than pinned to the top",
      (lambda ns: (bt.layout(ns), ns[0]["y"] > 1000)[1])([node(0, 0, "data")]))

# Two nodes deliberately placed on top of one another must be REPORTED.
check("overlapping() reports a genuine overlap rather than returning zero",
      bt.overlapping([node(100, 100), node(105, 105)]) == 1)


# ── 3. The viewer's CSS vocabulary. ────────────────────────────────────────

VIEWER_CSS_KINDS = {"data", "engine", "lib", "appn", "schema", "infra", "external", "future"}

check("every layer emits a kind the viewer already has CSS for",
      all(meta["kind"] in VIEWER_CSS_KINDS for meta in bt.LAYER_META.values()))

check("every layer in LAYER_ORDER has metadata, and every metadata entry is ordered",
      set(bt.LAYER_ORDER) == set(bt.LAYER_META))

check("every layer declares a label, colour and default state",
      all({"label", "colour", "kind", "defaultOn"} <= set(m) for m in bt.LAYER_META.values()))


# ── 4. Classification. ─────────────────────────────────────────────────────

for name, expected in [
    ("data-grid-gb", "data"), ("seed-data", "data"),
    ("ventus-grid-engine", "engines"), ("grid-distance-maths", "engines"),
    ("spiders", "observation"), ("cvaa", "observation"),
    ("globalgrid2050", "publication"), ("pipelinenews", "publication"),
    ("teleprinter", "tools"), ("cable-trench-or-drill", "tools"),
    ("gridatlas", "apps"),
]:
    check(f"{name} classifies as {expected}", bt.classify(name) == expected)


# ── 5. Reference matching. ─────────────────────────────────────────────────

pattern = bt.repo_reference_pattern(["data-grid-gb", "data-grid", "gridatlas"])
check("the longest repository name wins, so data-grid-gb is not matched as data-grid",
      pattern.search("https://github.com/Ventusltd/data-grid-gb").group(1) == "data-grid-gb")
check("a Pages URL is a reference too",
      pattern.search("https://ventusltd.github.io/gridatlas/atlas/").group(1) == "gridatlas")
check("an unrelated URL is not a reference",
      pattern.search("https://github.com/someoneelse/gridatlas") is None)


# ── 6. The document that gets written. ─────────────────────────────────────

found = {"a-repo": {"b-repo": 3}, "b-repo": {}}
meta = {"a-repo": {"description": "first"}, "b-repo": {"description": "second"}}
doc = bt.build(found, meta, "test")

check("edgeTypes is a keyed object, because the viewer does model.edgeTypes[e.type]",
      isinstance(doc["edgeTypes"], dict) and "reference" in doc["edgeTypes"])
check("every edge type carries the colour and layer the viewer reads",
      all({"colour", "label", "layer"} <= set(v) for v in doc["edgeTypes"].values()))
check("layers carry defaultOn, because the viewer initialises its toggles from it",
      all("defaultOn" in l for l in doc["layers"]))
check("an edge carries the number of references and the evidence sentence",
      doc["edges"][0]["references"] == 3 and "committed text" in doc["edges"][0]["evidence"])
check("totals report unconnected repositories by name rather than hiding them",
      "unconnectedIds" in doc["totals"])
check("the generated block records how and from what it was built",
      {"utc", "by", "source", "edgeRule"} <= set(doc["generated"]))
check("the edge rule says nothing is inferred",
      "Nothing is inferred" in doc["generated"]["edgeRule"])
check("the public title says Elements",
      doc["title"] == "GlobalGrid2050 Elements")
check("the internal species name is retained for the viewer",
      doc["species"] == "spider_printer_v1")


# ── 7. The committed cartridge itself. ─────────────────────────────────────

cartridge_path = Path(__file__).resolve().parent.parent / "data" / "topology.json"
if cartridge_path.exists():
    cartridge = json.loads(cartridge_path.read_text(encoding="utf-8"))
    check("the committed cartridge has no node the viewer would clip",
          bt.outside_map(cartridge["nodes"]) == [])
    check("the committed cartridge has no overlapping node boxes",
          bt.overlapping(cartridge["nodes"]) == 0)
    check("the committed cartridge uses only kinds the viewer styles",
          {n["kind"] for n in cartridge["nodes"]} <= VIEWER_CSS_KINDS)
    check("every edge endpoint exists as a node",
          (lambda ids: all(e["from"] in ids and e["to"] in ids for e in cartridge["edges"]))(
              {n["id"] for n in cartridge["nodes"]}))
    check("no repository references itself",
          all(e["from"] != e["to"] for e in cartridge["edges"]))
    check("the committed cartridge declares the virtual canvas the viewer divides by",
          cartridge["canvas"]["width"] == 3600 and cartridge["canvas"]["height"] == 3000)
else:
    failures.append("data/topology.json is missing")


if failures:
    print(f"build_topology test FAILED ({len(failures)} of {len(failures) + passed}):")
    for f in failures:
        print(f"  - {f}")
    raise SystemExit(1)
print(f"build_topology test PASS - {passed} checks")

Voltage

A JavaScript module in the bench folder of Star Maker that fetches connection points, voltages, 11kV and 400kV from National Energy System Operator (NESO) data portal.

electricalstar-maker / machinery/bench/voltage.mjs · lines 1–80 of 80 · Not reached from any entry point (candidate for review)

What it does
It fetches connection points, voltages, 11kV and 400kV. Defines walk. Uses libraries node:fs/promises, node:path. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'grid-network'): 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: 11kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: data source: NESO data portal; JSON file connection-points.v3.json. Out: JSON file voltages.json; JSON file graph.json. Voltage levels named: 400kV, 275kV, 220kV, 132kV, 11kV.
What it achieves
It is built from the walk step (`walk`). THE VOLTAGE STAR — reads everything the code does about 400 / 275 / 220 / 132 / 66 / 33 / 11kV, joins each voltage to the data we actually hold, and. Its code works with 11 kV, 132 kV and 220 kV.
Why it matters
No other file in the estate was found to import it.
Application
star-maker · machinery/bench · JavaScript module
Uses
node:fs/promises, node:path
Used by
none found
Produces
walk
Defines here
walk
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/voltage.mjs:1-80 · blob 9d61b7cc1306cf6d9e83db06b589e5af8b90de5e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// THE VOLTAGE STAR — reads everything the code does about 400 / 275 / 220 / 132 / 66 / 33 / 11 kV,
// joins each voltage to the data we actually hold, and — only where it needs help — asks the
// NESO open-data API (CKAN, api.neso.energy) for datasets under an open licence that match those
// voltages. Rule from the architect: use a property only when it has relevance to our purpose
// and our code. So: no dumping of catalogues; every line here is a voltage the code touches.
//
//   node voltage.mjs  → star-maker/voltage/{voltages.json, graph.json}, VOLTAGE.md
import { readFile, readdir, writeFile, mkdir, stat } from 'node:fs/promises';
import path from 'node:path';
const ROOT = process.env.ESTATE_DIR || 'C:/Users/vikra/Documents/GitHub';
const SKY = process.env.SKY_DIR || 'C:/Users/vikra/Documents/GitHub/star-maker';
const ATLAS_DATA = process.env.ATLAS_DATA || 'C:/Users/vikra/Documents/GitHub/gridatlas/atlas/releases/202608300453-atlas-v9/data';
const CONNECTION_POINTS = process.env.CONNECTION_POINTS || 'C:/Users/vikra/Documents/GitHub/data-grid-gb/derived/connection-points.v3.json';
const OUT = path.join(SKY, 'voltage'); await mkdir(OUT, { recursive: true });
const KV = [400, 275, 220, 132, 66, 33, 11];
const SKIP = /[\\/](\.git|node_modules|dist|build|vendor|homepage_versions|restore_points|site_versions|star-maker[\\/](stars|shots))[\\/]/;
const EXT = new Set(['.js', '.mjs', '.py', '.html', '.md']);
// What GB literature says each level is (open sources; stated once, plainly, no numbers invented):
// NESO Grid Code and ETYS: the transmission system in England & Wales is 400 kV and 275 kV; in Scotland 132 kV
// is also transmission; below that the distribution networks (DNOs) run 132 / 66 / 33 / 11 kV. Sources:
// https://www.neso.energy/industry-information/codes/grid-code · https://www.neso.energy/publications/electricity-ten-year-statement-etys
const ROLE = { 400: 'transmission (E&W, GB backbone)', 275: 'transmission (E&W)', 220: 'not a GB standard level — check the code: interconnector or continental data?', 132: 'transmission in Scotland; distribution (DNO) in England & Wales', 66: 'distribution (DNO, some EHV networks)', 33: 'distribution (DNO, EHV)', 11: 'distribution (DNO, HV)' };

async function* walk(dir) { for (const e of await readdir(dir, { withFileTypes: true }).catch(() => [])) { const p = path.join(dir, e.name); if (SKIP.test(p + (e.isDirectory() ? '/' : ''))) continue; if (e.isDirectory()) yield* walk(p); else if (EXT.has(path.extname(e.name)) && (await stat(p)).size < 2_000_000) yield p; } }
const v = Object.fromEntries(KV.map(k => [k, { kv: k, role: ROLE[k], mentions: 0, repos: new Set(), lineages: new Set(), context: [] }]));
const rx = new RegExp(`(?<![\\d.])(${KV.join('|')})\\s?[kK][vV]\\b|grid_(${KV.join('|')})kv|\\b(${KV.join('|')})KV\\b`, 'g');
for await (const f of walk(ROOT)) {
  const text = await readFile(f, 'utf8').catch(() => ''); if (!text || (text.length > 20000 && text.split('\n').some(l => l.length > 3000))) continue;
  const rel = path.relative(ROOT, f).replace(/\\/g, '/'); const repo = rel.split('/')[0]; const lin = rel.replace(/\d{12}[-_]?/g, '');
  const lines = text.split('\n');
  lines.forEach((line, i) => { for (const m of line.matchAll(rx)) { const k = Number(m[1] || m[2] || m[3]); const e = v[k]; if (!e) continue; e.mentions++; e.repos.add(repo); e.lineages.add(lin); if (e.context.length < 400 && !e.context.some(c => c.lineage === lin && c.text === line.trim())) e.context.push({ file: rel, lineage: lin, line: i + 1, text: line.trim().slice(0, 160) }); } });
}
// the data we hold per voltage
for (const k of KV) { try { const g = JSON.parse(await readFile(path.join(ATLAS_DATA, `grid_${k}kv.geojson`), 'utf8')); v[k].atlas_layer = { file: `grid_${k}kv.geojson`, features: g.features?.length || 0 }; } catch { v[k].atlas_layer = null; } }
try { const cp = JSON.parse(await readFile(CONNECTION_POINTS, 'utf8')); for (const k of KV) v[k].neso_connection_points = cp.connection_points.filter(s => (s.voltages_kv || []).includes(k)).length; v.source_connection_points = { schema: cp.schema, source: cp.source, sites: cp.connection_points.length }; } catch {}
// ask NESO's open-data API only for what matches our voltages and our purpose
const neso = [];
try {
  for (const q of ['transmission network voltage', 'substation', 'connection capacity headroom', 'constraint']) {
    const r = await fetch(`https://api.neso.energy/api/3/action/package_search?q=${encodeURIComponent(q)}&rows=10`, { signal: AbortSignal.timeout(15000) });
    if (!r.ok) continue; const j = await r.json();
    for (const p of j.result?.results || []) if (/kv|transmission|substation|network|connection|constraint|headroom|capacity|circuit|etys/i.test(p.title + ' ' + (p.notes || '').slice(0, 300)) && !neso.some(x => x.name === p.name))
      neso.push({ name: p.name, title: p.title, licence: p.license_title || p.license_id || 'unstated', url: `https://www.neso.energy/data-portal/${p.name}`, resources: (p.resources || []).length, matched: q });
  }
} catch (e) { neso.push({ error: String(e.message).slice(0, 120) }); }
const open = neso.filter(d => /open|ogl|cc|creative/i.test(d.licence || ''));
const out = { generated_utc: new Date().toISOString(), voltages: KV.map(k => ({ ...v[k], repos: [...v[k].repos].sort(), lineages: v[k].lineages.size, context: v[k].context.slice(0, 60) })), source_connection_points: v.source_connection_points || null, neso_open_datasets: open, neso_other: neso.filter(d => !open.includes(d)).slice(0, 10) };
await writeFile(path.join(OUT, 'voltages.json'), JSON.stringify(out, null, 2));
const nodes = KV.map(k => ({ label: `${k} kV`, type: 'voltage', rag: k === 220 && v[k].mentions ? 'amber' : v[k].mentions ? 'green' : 'amber', reason: `${v[k].role} · ${v[k].mentions} mentions in ${v[k].lineages.size} files · atlas ${v[k].atlas_layer ? v[k].atlas_layer.features + ' features' : 'no layer'} · NESO sites ${v[k].neso_connection_points ?? '?'}` }));
const edges = []; const fileNodes = new Map();
for (const k of KV) for (const c of v[k].context.slice(0, 25)) { const lab = c.lineage.split('/').slice(0, 3).join('/'); if (!fileNodes.has(lab)) fileNodes.set(lab, { label: lab, type: 'code', rag: 'green', reason: c.text.slice(0, 100) }); if (!edges.some(e => e.from === lab && e.to === `${k} kV`)) edges.push({ from: lab, to: `${k} kV`, kind: 'SPEAKS_OF' }); }
for (const d of open.slice(0, 20)) { fileNodes.set(d.title, { label: d.title, type: 'neso-open-data', rag: 'green', reason: `${d.licence} · ${d.url}` }); for (const k of KV) if (new RegExp(`\\b${k}\\s?kV`, 'i').test(d.title)) edges.push({ from: d.title, to: `${k} kV`, kind: 'OPEN_DATA_FOR' }); }
await writeFile(path.join(OUT, 'graph.json'), JSON.stringify({ schema: 'voltage-graph.v1', label: 'The Voltage star', generated_utc: new Date().toISOString(), note: 'Voltage levels the code speaks of, the code that speaks of them, the data we hold, and NESO open datasets that match.', focus_default: '400 kV', nodes: [...nodes, ...fileNodes.values()], edges }, null, 2));
const md = `# The Voltage star

What the code says about each voltage level, what data we hold for it, what GB literature says it is, and which NESO open-licence datasets speak of it. Only voltages the code touches; only properties that serve the purpose. Updated ${new Date().toISOString()}. No model.

| kV | role in GB (NESO Grid Code / ETYS) | mentions | files | repos | atlas layer | NESO connection sites |
|---|---|---|---|---|---|---|
${KV.map(k => `| **${k}** | ${v[k].role} | ${v[k].mentions} | ${v[k].lineages.size} | ${[...v[k].repos].length} | ${v[k].atlas_layer ? v[k].atlas_layer.features + ' features' : '—'} | ${v[k].neso_connection_points ?? '—'} |`).join('\n')}

Connection sites read from \`${v.source_connection_points?.schema || 'data-grid-gb/derived/connection-points.v3.json'}\` (${v.source_connection_points?.sites ?? '?'} sites; NESO-published, minimum 132 kV).

## Where the code speaks of each voltage (first lines)
${KV.map(k => `### ${k} kV\n${v[k].context.slice(0, 8).map(c => `- \`${c.file}:${c.line}\` ${c.text.slice(0, 120)}`).join('\n') || '- nothing'}`).join('\n\n')}

## NESO open-licence datasets that match our voltages and purpose
${open.length ? open.slice(0, 20).map(d => `- **${d.title}** — ${d.licence} · ${d.resources} resources · ${d.url} · matched "${d.matched}"`).join('\n') : '- the API returned nothing matching (or was unreachable): ' + JSON.stringify(neso.slice(0, 2))}
${neso.some(d => d.error) ? '\nAPI note: ' + neso.find(d => d.error).error : ''}

## Questions the star raises (for Claude + VIK-AI)
- 220 kV: ${v[220].mentions ? `the code mentions it ${v[220].mentions} times and the atlas has a \`grid_220kv\` layer with ${v[220].atlas_layer?.features ?? 0} features — 220 kV is not a GB standard level; whose lines are these (interconnector landfall, imported data)?` : 'not mentioned'}
- 11 kV: ${v[11].mentions} mentions but ${v[11].atlas_layer ? '' : 'no atlas layer — '}the UKPN 11 kV layer showed [WAIT] in every drive tonight; is its source reachable?
- Every voltage the code names should map to one element on the periodic table; today none do.

## For the Spider
\`voltage/graph.json\` — ${nodes.length + fileNodes.size} nodes, ${edges.length} edges (SPEAKS_OF, OPEN_DATA_FOR).
`;
await writeFile(path.join(SKY, 'VOLTAGE.md'), md);
console.log(`voltage: ${KV.map(k => `${k}kV ${v[k].mentions}`).join(' · ')} · NESO open datasets ${open.length}`);

Substation Intelligence

A JavaScript file in the cartridges folder of Testcode that maps elizabeth line and london underground, using haversine and SHA-256, 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 apps/substation-finder/Si/202609060537-substation-intelligence.js (code-generator), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Substation Intelligence; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9913 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609060537-substation-intelligence.js:1-5427 fd8aeb8a8884da62dc50991d5f4bf8cc48b33c43
  • sha256 916bad1b531c94d9acd3bc54f6ed205b467b96e6c1d86beea47a7d66e2f51669
  • target sha256 afc18391911f8ab467480aa8f22fd30467de554c76c58101956f9fec49ad9449
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesytestcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js · lines 1–429 of 5400 · version 2026-09-06 04:59 · Not reached from any entry point (candidate for review) · pattern _zoneDrawRefreshEditor (shared by 3 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 230 functions or classes, including close, open, show, clearValues, validOutline. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson; JSON file style.json. Out: CSV file gridatlas-polygon-vertices.csv; downloaded file gridatlas-polygon-; downloaded file gridatlas-polygon-vertices.csv; downloaded file gridatlas-; downloaded file globalgrid2050-map-; browser storage (setItem); interactive map; canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
What it achieves
It saves outline (`saveOutline`), reads outline (`readOutline`) and exports outline (`exportOutline`). Its `snapLines` function gives line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged from line features and substation point features (VEDIC: snap line ends to substations). Its code works with 400 kV and 100 MVA. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/202609060459/atlas/cartridges · 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
mentioned in Standalone (comment link)
Produces
close, open, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail, orient, on
Defines here
close, open, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail, orient, on, exportOutline, importOutline, createHistory, copy, deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawStorageStatus, _zoneDrawRefreshEditor, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js:1-429 · blob fd03f2ae502f2d404cb773df8858c2746ada6401 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: ICP_grid_engineer · canonical: unreached_review
/* 202609060459; source and token/AST compaction receipts in source-provenance.json. */

'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
(() => {
const registry = window.__GRIDATLAS_MODULES__ ||= {};
let state = null;
function close() {
if (!state) return;
const {map, host, rail, control, marker, style} = state;
state = null;
marker.replaceWith(control);
rail.remove(); style.remove();
host.removeAttribute('data-measurement-dock');
document.body.removeAttribute('data-measurement-dock');
map.resize();
}
function open(map, controlId) {
if (state?.control.id === controlId) return;
close();
const canvas = map.getContainer();
const host = canvas.parentElement;
const control = document.getElementById(controlId);
if (!control || !host) throw Error('Measurement dock requires its existing control and map host');
const marker = document.createComment('measurement control home');
control.before(marker);
const rail = document.createElement('aside');
rail.id = 'gridatlas-measurement-dock';
rail.setAttribute('aria-label', 'Shape measurements and controls');
const controls = document.createElement('div');
controls.className = 'measurement-dock-controls';
controls.append(control);
const values = document.createElement('div');
values.className = 'measurement-dock-values';
rail.append(controls, values);
const style = document.createElement('style');
style.textContent = `
#map-container[data-measurement-dock] #map{width:calc(100% - 280px)!important;margin-left:280px!important}
#gridatlas-measurement-dock{position:absolute;left:0;top:64px;bottom:0;width:280px;box-sizing:border-box;overflow:auto;overscroll-behavior:contain;background:#080b10;border-right:1px solid #58646d;color:#fff;z-index:1100;padding:10px;font:12px/1.4 ui-monospace,monospace}
#gridatlas-measurement-dock .radius-popup{position:static!important;transform:none!important;margin:0 0 10px!important;width:auto!important;min-width:0!important;max-width:100%!important;box-sizing:border-box}
#gridatlas-measurement-dock .measurement-dock-values>div{min-width:0!important;box-sizing:border-box;max-width:100%}
#gridatlas-measurement-dock button,#gridatlas-measurement-dock input{min-height:44px}
#gridatlas-measurement-dock :focus-visible{outline:2px solid #fff;outline-offset:2px}
body[data-measurement-dock] #codex-tool-layers{visibility:hidden!important;pointer-events:none!important}
@media(max-width:700px){
 #map-container[data-measurement-dock] #map{width:100%!important;margin-left:0!important;height:calc(100% - min(240px,38dvh))!important}
 #gridatlas-measurement-dock{top:auto;right:0;width:100%;height:min(240px,38dvh);border-right:0;border-top:1px solid #58646d;padding:8px 12px;display:grid;grid-template-columns:minmax(110px,0.8fr) minmax(180px,1.4fr);gap:8px;z-index:1100}
 #gridatlas-measurement-dock .measurement-dock-values>div{padding:6px!important}
 #gridatlas-measurement-dock .radius-popup{padding:6px!important}
 #gridatlas-measurement-dock .radius-input-row{flex-wrap:wrap}
}
@media(max-width:350px){#gridatlas-measurement-dock{grid-template-columns:1fr}}
`;
document.head.append(style);
host.append(rail);
host.setAttribute('data-measurement-dock', controlId);
document.body.setAttribute('data-measurement-dock', controlId);
state = {map, host, rail, control, marker, style, values};
map.resize();
}
function show(html) {
if (!state) throw Error('Open measurement controls before showing results');
const scroll = state.rail.scrollTop;
state.values.innerHTML = html;
state.rail.scrollTop = scroll;
}
function clearValues() {if (state) state.values.replaceChildren();}
const draftKey = 'gridatlas.polygon-draft.v1';
function validOutline(points) {
return Array.isArray(points) && points.length >= 3 && points.length <= 4096 && points.every(point => Array.isArray(point) && point.length === 2 && point.every(Number.isFinite) && Math.abs(point[0]) <= 180 && Math.abs(point[1]) <= 85.051129);
}
function saveOutline(points) {
try {
if (!validOutline(points)) return {saved:false, message:'Outline cannot be saved: invalid coordinates.'};
localStorage.setItem(draftKey, JSON.stringify({schema:draftKey, points, savedAt:new Date().toISOString()}));
return {saved:true, message:'Saved on this browser'};
} catch { return {saved:false, message:'Browser storage unavailable; keep this tab open.'}; }
}
function readOutline() {
try {
const text = localStorage.getItem(draftKey);
if (!text || text.length > 250000) return null;
const draft = JSON.parse(text);
return draft.schema === draftKey && validOutline(draft.points) ? draft.points.map(point => point.slice()) : null;
} catch { return null; }
}
function clearOutline() {
try {localStorage.removeItem(draftKey);return {saved:true,message:'Polygon reset'};}
catch {return {saved:false,message:'Polygon reset here; browser storage could not be cleared.'};}
}
function analyzeOutline(points) {
const fail=(code,message)=>({valid:false,code,message});
if(!validOutline(points))return fail('coordinates','Use 3 to 4096 finite map coordinates.');
const n=points.length,edges=[];
const orient=(a,b,c)=>{const x=(b[0]-a[0])*(c[1]-a[1]),y=(b[1]-a[1])*(c[0]-a[0]),v=x-y;return Math.abs(v)<=Number.EPSILON*8*(Math.abs(x)+Math.abs(y))?0:Math.sign(v);};
const on=(a,b,p)=>p[0]>=Math.min(a[0],b[0])&&p[0]<=Math.max(a[0],b[0])&&p[1]>=Math.min(a[1],b[1])&&p[1]<=Math.max(a[1],b[1]);
for(let i=0;i<n;i++){
const a=points[i],b=points[(i+1)%n],c=points[(i+2)%n];
if(a[0]===b[0]&&a[1]===b[1])return fail('repeated','Consecutive vertices coincide. Move or remove the repeated corner.');
if(Math.abs(a[0]-b[0])>180)return fail('antimeridian','This outline crosses the date line. Area is not assessed by this map tool.');
if(orient(a,b,c)===0&&(a[0]-b[0])*(c[0]-b[0])+(a[1]-b[1])*(c[1]-b[1])>0)return fail('overlap','Adjacent edges double back over one another.');
edges.push({i,a,b,minX:Math.min(a[0],b[0]),maxX:Math.max(a[0],b[0]),minY:Math.min(a[1],b[1]),maxY:Math.max(a[1],b[1])});
}
edges.sort((a,b)=>a.minX-b.minX);let active=[];
for(const edge of edges){
active=active.filter(other=>other.maxX>=edge.minX);
for(const other of active){
const gap=Math.abs(edge.i-other.i);if(gap===1||gap===n-1||edge.minY>other.maxY||edge.maxY<other.minY)continue;
const a=edge.a,b=edge.b,c=other.a,d=other.b,o1=orient(a,b,c),o2=orient(a,b,d),o3=orient(c,d,a),o4=orient(c,d,b);
if((o1*o2<0&&o3*o4<0)||(o1===0&&on(a,b,c))||(o2===0&&on(a,b,d))||(o3===0&&on(c,d,a))||(o4===0&&on(c,d,b)))return fail('crossing','Non-adjacent edges cross or touch. Move the corners until the boundary is simple.');
}
active.push(edge);
}
const origin=points[0];let twiceArea=0;
for(let i=1;i<n-1;i++)twiceArea+=(points[i][0]-origin[0])*(points[i+1][1]-origin[1])-(points[i+1][0]-origin[0])*(points[i][1]-origin[1]);
if(twiceArea===0)return fail('degenerate','The outline has no enclosed area.');
return {valid:true,code:'simple',message:'Simple outline in map coordinates.'};
}
function exportOutline(points, measurements) {
const validity=analyzeOutline(points);if(!validity.valid)throw Error('Polygon not exported: '+validity.message);
if (!validOutline(points)) throw Error('Draw a valid polygon before saving a file.');
const ring = points.map(point => point.slice());
const origin=ring[0];
const winding = ring.reduce((sum,point,i) => {const next=ring[(i+1)%ring.length];return sum+(point[0]-origin[0])*(next[1]-origin[1])-(next[0]-origin[0])*(point[1]-origin[1]);},0);
if (winding < 0) ring.reverse();
ring.push(ring[0].slice());
const properties = {name:'GridAtlas drawn polygon', source:'User-drawn outline', coordinate_reference:'WGS84 longitude, latitude', boundary:'Screening outline only; not a surveyed boundary or connection offer.'};
for (const [key,value] of Object.entries(measurements || {})) if (['area_m2','area_ha','perimeter_km'].includes(key) && Number.isFinite(value) && value >= 0) properties[key]=value;
return {type:'FeatureCollection',features:[{type:'Feature',properties,geometry:{type:'Polygon',coordinates:[ring]}}]};
}
function importOutline(text) {
if (typeof text !== 'string' || text.length > 250000) throw Error('Choose a GeoJSON file under 250 KB.');
let data;
try {data=JSON.parse(text);} catch {throw Error('The file is not valid JSON. Your current polygon is unchanged.');}
if (data?.type === 'FeatureCollection') {
if (!Array.isArray(data.features) || data.features.length !== 1) throw Error('Choose a file containing exactly one polygon.');
data=data.features[0];
}
if (data?.type === 'Feature') data=data.geometry;
if (data?.type !== 'Polygon' || !Array.isArray(data.coordinates) || data.coordinates.length !== 1) throw Error('Choose one Polygon without holes; other geometries are not flattened.');
const ring=data.coordinates[0];
if (!Array.isArray(ring) || ring.length < 4 || JSON.stringify(ring[0]) !== JSON.stringify(ring.at(-1))) throw Error('The polygon ring must be closed.');
const points=ring.slice(0,-1);
if (!validOutline(points) || new Set(points.map(point=>JSON.stringify(point))).size < 3) throw Error('Polygon coordinates must be valid WGS84 longitude/latitude pairs, with 3 to 4096 vertices.');
return points.map(point=>point.slice());
}
registry.polygonFiles = Object.freeze({schema:'gridatlas.polygon-files.v1',exportOutline,importOutline,analyzeOutline});
function createHistory(limit=80) {
let states=[[]],position=0;
const copy=points=>points.map(point=>point.slice());
return Object.freeze({
commit(points) {
if (JSON.stringify(states[position])===JSON.stringify(points)) return;
states=states.slice(0,position+1);states.push(copy(points));
if(states.length>limit)states.shift();position=states.length-1;
},
undo() {if(position===0)return null;return copy(states[--position]);},
redo() {if(position===states.length-1)return null;return copy(states[++position]);},
get canUndo(){return position>0;},get canRedo(){return position<states.length-1;}
});
}
registry.polygonHistory = Object.freeze({createHistory});
registry.polygonDraft = Object.freeze({schema:draftKey,validOutline,saveOutline,readOutline,clearOutline});
registry.measurementDock = Object.freeze({schema:'gridatlas.measurement-dock.v1',open,show,close,clearValues});
})();
'use strict';
window.initVentusMap = function({ config, center, zoom }) {
if (typeof maplibregl === 'undefined') {
document.getElementById('fatal-banner').style.display = 'block';
throw new Error('CRITICAL: MapLibre failed to load.');
}
function deepFreeze(obj) {
Object.keys(obj).forEach(prop => {
if (typeof obj[prop] === 'object' && obj[prop] !== null) deepFreeze(obj[prop]);
});
return Object.freeze(obj);
}
function escapeHTML(value) {
return String(value ?? '')
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function normalizeStatus(status) {
return String(status ?? '').trim().toLowerCase();
}
function fmt(n, decimals) {
return n.toLocaleString('en-GB', { maximumFractionDigits: decimals, minimumFractionDigits: decimals });
}
const measurementDock = window.__GRIDATLAS_MODULES__?.measurementDock;
if (!measurementDock) throw Error('Measurement dock module missing');
const EARTH_RADIUS_KM = 6378.137;
const MAX_RADIUS_KM = Math.PI * EARTH_RADIUS_KM;
const DEG_TO_RAD = Math.PI / 180;
const HIT_RADIUS_VERTEX_PX = 22;
const HIT_RADIUS_EDGE_PX = 16;
const EDGE_DOT_CLEARANCE_PX = 10;
const CLICK_DEBOUNCE_MS = 220;
const HOVER_THROTTLE_MS = 100;
const POPUP_MAX_WIDTH = '300px';
const ZONE_DRAW_VERTICES = 24;
const ZONE_DRAW_DEFAULT_KM = 0.337;
function haversine(lon1, lat1, lon2, lat2) {
const R = EARTH_RADIUS_KM, r = Math.PI / 180;
const dLat = (lat2 - lat1) * r, dLon = (lon2 - lon1) * r;
const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * r) * Math.cos(lat2 * r) * Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
const GRID_CONFIG = deepFreeze(config);
const RUNTIME_STATE = {};
GRID_CONFIG.forEach(group => {
group.layers.forEach(layer => {
RUNTIME_STATE[layer.id] = { status: 'WAIT', loading: false, loaded: false };
});
});
const layerConfigById = new Map(
GRID_CONFIG.flatMap(g => g.layers).map(l => [l.id, l])
);
const REPD_IDS = ['solar','solar_operational','solar_roof','wind','wind_onshore_operational','wind_offshore_operational','bess','bess_operational','biomass','tidal','hydrogen','hydro','flywheel','act','geothermal','caes'];
const TRANSIT_IDS = ['elizabeth','lu','dlr','metro','tram','hs2'];
const TRANSIT_SOURCE_MAP = { 'elizabeth':'src-elizabeth','lu':'src-lu','dlr':'src-metros','metro':'src-metros','tram':'src-metros','hs2':'src-hs2' };
const TRANSIT_URLS = { 'src-elizabeth':'/elizabeth_line.geojson','src-lu':'/london_underground.geojson','src-metros':'/uk_metros_trams.geojson','src-hs2':'/hs2.geojson' };
const SEARCH_THRESHOLD = {
'solar':50,'solar_roof':0.5,'wind':50,'bess':50,'biomass':50,
'tidal':10,'hydrogen':10,'hydro':10,'flywheel':1,'act':10,'geothermal':1,'caes':1
};
const TECH_TERMS = new Map([
['solar','solar farm'],['solar_roof','rooftop solar'],['wind','wind farm'],
['bess','battery storage'],['biomass','biomass plant'],['tidal','tidal energy'],
['hydrogen','hydrogen plant'],['hydro','hydro power'],['flywheel','flywheel storage'],
['act','advanced conversion energy'],['geothermal','geothermal energy'],['caes','compressed air energy storage']
]);
const TECH_COLOURS = new Map([
['solar','#ffff00'],['solar_roof','#ffcc00'],['wind','#00ffff'],['bess','#ffae00'],
['biomass','#39ff14'],['tidal','#00bfff'],['hydrogen','#ffffff'],['hydro','#00aaff'],
['flywheel','#ff69b4'],['act','#ff6600'],['geothermal','#ff3300'],['caes','#88aaff']
]);
const STATUS_COLOURS = {
'operational':'#00ff88','under construction':'#ffcc00','awaiting construction':'#ffaa00',
'consented':'#ff8800','planning permission granted':'#ff8800','planning approved':'#ff8800',
'application submitted':'#8888ff','pre-construction':'#aaaaff'
};
let statusMode = false;
let radiusMode = false;
let radiusMarker = null;
let radiusCenter = null;
let radiusAreaMode = false;
let radiusAreaMarker = null;
let radiusAreaCenter = null;
const ZONE_DRAW_MAX_KM = MAX_RADIUS_KM;
let zoneDrawMode = false;
let zoneDrawLocked = false;
let zoneDrawPoints = [];
let zoneDrawDragging = false;
let zoneDrawDragIdx = -1;
let zoneDrawJustDragged = false;
let _zoneDrawCollapsed = false;
const zoneHistory = window.__GRIDATLAS_MODULES__.polygonHistory.createHistory();
let zoneHistoryApplying = false;
function _zoneDrawGetRadius() {
const input = document.getElementById('zonedraw-radius-input');
if (!input) return ZONE_DRAW_DEFAULT_KM;
const v = parseFloat(input.value);
if (isNaN(v) || v <= 0) return ZONE_DRAW_DEFAULT_KM;
if (v > ZONE_DRAW_MAX_KM) return ZONE_DRAW_MAX_KM;
return v;
}
function _zoneDrawCirclePoints(lon, lat, radiusKm, n) {
const R = EARTH_RADIUS_KM, DEG = Math.PI / 180;
const ad = radiusKm / R;
const lat1 = lat * DEG;
return Array.from({ length: n }, (_, i) => {
const b = (i / n) * 2 * Math.PI;
const lat2 = Math.asin(Math.sin(lat1) * Math.cos(ad) + Math.cos(lat1) * Math.sin(ad) * Math.cos(b));
const lon2 = lon * DEG + Math.atan2(Math.sin(b) * Math.sin(ad) * Math.cos(lat1), Math.cos(ad) - Math.sin(lat1) * Math.sin(lat2));
return [lon2 / DEG, lat2 / DEG];
});
}
function _zoneDrawCalcArea(pts) {
if (pts.length < 3) return { areaKm2: 0, areaHa: 0, areaAc: 0, areaMi2: 0, areaM2: 0, perimKm: 0, pitches: 0 };
let area = 0;
const R = EARTH_RADIUS_KM;
for (let i = 0; i < pts.length; i++) {
const j = (i + 1) % pts.length;
const xi = pts[i][0] * Math.PI / 180, yi = pts[i][1] * Math.PI / 180;
const xj = pts[j][0] * Math.PI / 180, yj = pts[j][1] * Math.PI / 180;
area += (xj - xi) * (2 + Math.sin(yi) + Math.sin(yj));
}
const areaKm2 = Math.abs(area) * R * R / 2;
let perimKm = 0;
for (let i = 0; i < pts.length; i++) perimKm += haversine(pts[i][0], pts[i][1], pts[(i+1)%pts.length][0], pts[(i+1)%pts.length][1]);
const areaM2 = areaKm2 * 1e6;
return { areaKm2, areaHa: areaM2 / 10000, areaAc: areaM2 / 4046.85642, areaMi2: areaKm2 * 0.386102, areaM2, perimKm, pitches: areaM2 / 7140 };
}
function _zoneDrawStorageStatus(result) {
let status = document.getElementById('zonedraw-storage-status');
if (!status) {
status = document.createElement('div'); status.id = 'zonedraw-storage-status';
status.setAttribute('role','status'); status.style.cssText = 'font-size:10px;margin-top:8px;color:#cbd5e1';
document.getElementById('zonedraw-display')?.append(status);
}
status.textContent = result.message;
}
function _zoneDrawRefreshEditor() {
const select=document.getElementById('zonedraw-vertex');if(!select)return;
const previous=Math.min(Number(select.value)||0,Math.max(0,zoneDrawPoints.length-1));
if(select.options.length!==zoneDrawPoints.length){select.replaceChildren();zoneDrawPoints.forEach((_,i)=>{const option=document.createElement('option');option.value=String(i);option.textContent='Vertex '+(i+1);select.append(option);});}
select.value=String(previous);const point=zoneDrawPoints[previous];
const lon=document.getElementById('zonedraw-longitude'),lat=document.getElementById('zonedraw-latitude');
lon.value=point?String(point[0]):'';lat.value=point?String(point[1]):'';
for(const control of [select,lon,lat,document.getElementById('btn-zonedraw-coordinate')])control.disabled=zoneDrawLocked||zoneDrawPoints.length<3;
const remove=document.getElementById('btn-zonedraw-remove');if(remove)remove.disabled=zoneDrawLocked||zoneDrawPoints.length<=3;
}
function _zoneDrawUpdateLayers(dragOnly, renderOnly = false) {
if(!dragOnly && !renderOnly)_zoneDrawRefreshEditor();
if (!dragOnly && !renderOnly) {
if (!zoneHistoryApplying) zoneHistory.commit(zoneDrawPoints);
const undo=document.getElementById('btn-zonedraw-undo'),redo=document.getElementById('btn-zonedraw-redo');
if(undo)undo.disabled=!zoneHistory.canUndo;if(redo)redo.disabled=!zoneHistory.canRedo;
}
const csvButton=document.getElementById('btn-zonedraw-csv');if(csvButton)csvButton.disabled=zoneDrawPoints.length<3;
const fitButton=document.getElementById('btn-zonedraw-fit');if(fitButton)fitButton.disabled=zoneDrawPoints.length<3;
const exportButton = document.getElementById('btn-zonedraw-export');
const validity=window.__GRIDATLAS_MODULES__.polygonFiles.analyzeOutline(zoneDrawPoints);
if (exportButton) {exportButton.disabled=!validity.valid;exportButton.title=validity.valid?'Save a closed polygon':validity.message;}
if (!dragOnly && !renderOnly && zoneDrawPoints.length >= 3) _zoneDrawStorageStatus(window.__GRIDATLAS_MODULES__.polygonDraft.saveOutline(zoneDrawPoints));
if (!map.getSource('src-zonedraw-fill')) return;
const n = zoneDrawPoints.length;
if (n < 3) {
['fill','line','points'].forEach(s => map.getSource(`src-zonedraw-${s}`).setData({ type: 'FeatureCollection', features: [] }));
return;
}
const ring = [...zoneDrawPoints, zoneDrawPoints[0]];
map.getSource('src-zonedraw-fill').setData({ type: 'FeatureCollection', features: validity.valid ? [{ type: 'Feature', geometry: { type: 'Polygon', coordinates: [ring] } }] : [] });
map.getSource('src-zonedraw-line').setData({ type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'LineString', coordinates: ring } }] });
if (zoneDrawLocked) {map.getSource('src-zonedraw-points').setData({type:'FeatureCollection',features:[]});return;}
if (dragOnly) {
map.getSource('src-zonedraw-points').setData({ type: 'FeatureCollection', features:
zoneDrawPoints.map((c, i) => ({ type: 'Feature', properties: { kind: 'vertex', idx: i }, geometry: { type: 'Point', coordinates: c } }))
});
} else {
const vFeatures = zoneDrawPoints.map((c, i) => ({ type: 'Feature', properties: { kind: 'vertex', idx: i }, geometry: { type: 'Point', coordinates: c } }));
const mFeatures = [];
zoneDrawPoints.forEach((c, i) => {
_zoneDrawEdgeDots(i).forEach(d => {
mFeatures.push({ type: 'Feature', properties: { kind: 'mid', edgeIdx: i, t: d.t }, geometry: { type: 'Point', coordinates: d.dot } });
});
});
map.getSource('src-zonedraw-points').setData({ type: 'FeatureCollection', features: [...vFeatures, ...mFeatures] });
}
}
let _zoneDrawPopupRaf = null;
function _zoneDrawShowPopup() {
if (zoneDrawPoints.length < 3) return;
const validity=window.__GRIDATLAS_MODULES__.polygonFiles.analyzeOutline(zoneDrawPoints);
if(!validity.valid){measurementDock.show('<div id="zonedraw-validity-warning" role="status" style="padding:10px;border:1px solid #ffb14d;color:#ffcc80"><strong>Area not assessed</strong><p>'+validity.message+'</p><p>The outline is kept for repair. Drag a corner, edit a coordinate, or Undo. GeoJSON export resumes when the outline is simple.</p></div>');return;}
const { areaKm2, areaHa, areaAc, areaMi2, areaM2, perimKm, pitches } = _zoneDrawCalcArea(zoneDrawPoints);
if (_zoneDrawCollapsed) {
measurementDock.show( `
                <button type="button" data-zonedraw-toggle aria-label="Expand polygon measurements" aria-expanded="false" onclick="window._zdExpand&&window._zdExpand()" style="font-family:monospace;background:#000;padding:5px 10px;border:1px solid #ff6600;border-radius:4px;cursor:pointer;color:#ff9a58;font-size:12px;white-space:normal;max-width:100%;text-align:left;">
                    ◉ ${fmt(areaKm2,3)} km² · ⚽ ${fmt(pitches,0)} pitches &nbsp;▾
                </button>`);
window._zdExpand = () => { _zoneDrawCollapsed = false; _zoneDrawShowPopup(); document.querySelector('[data-zonedraw-toggle]')?.focus(); };
} else {
measurementDock.show( `
                <div style="font-family:monospace;background:#000;padding:10px 12px;border:1px solid #ff6600;border-radius:4px;min-width:230px;">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                        <b style="color:#ff6600;font-size:13px;">◉ Zone Draw</b>
                        <button type="button" data-zonedraw-toggle aria-label="Collapse polygon measurements" aria-expanded="true" onclick="window._zdCollapse&&window._zdCollapse()" style="color:#bbb;background:#000;border:1px solid #777;border-radius:3px;font-size:12px;cursor:pointer;padding:0 8px;" title="Collapse">▴ hide</button>
                    </div>
                    <div style="color:#ffae00;font-size:13px;margin-bottom:10px;">⚽ ${fmt(pitches,1)} football pitches</div>
                    <div style="display:grid;grid-template-columns:auto 1fr;gap:4px 14px;font-size:12px;">
                        <span style="color:#888;">Square Metres</span><span style="color:#fff;">${fmt(areaM2,0)}</span>
                        <span style="color:#888;">Hectares</span><span style="color:#fff;">${fmt(areaHa,2)}</span>
                        <span style="color:#888;">Acres</span><span style="color:#fff;">${fmt(areaAc,2)}</span>
                        <span style="color:#888;">Square Kilometres</span><span style="color:#fff;">${fmt(areaKm2,4)}</span>
                        <span style="color:#888;">Square Miles</span><span style="color:#fff;">${fmt(areaMi2,3)}</span>
                        <span style="color:#888;">Perimeter</span><span style="color:#fff;">${fmt(perimKm,2)} km</span>
                    </div>
                    <div style="color:#aaa;font-size:11px;margin-top:8px;line-height:1.4;">
                        <b style="color:#ff6600;">HOW TO USE:</b><br>
                        • <b>Drag orange dots</b> to reshape polygon<br>
                        • <b>Click light dots</b> on edges to add points<br>
                        • <b>Undo</b> restores the previous edit<br>
                        • <b>Reset polygon</b> to start a new zone
                    </div>
                </div>`);
window._zdCollapse = () => { _zoneDrawCollapsed = true; _zoneDrawShowPopup(); document.querySelector('[data-zonedraw-toggle]')?.focus(); };
}
}
function _zoneDrawShowPopupDebounced() {
if (_zoneDrawPopupRaf) return;
_zoneDrawPopupRaf = requestAnimationFrame(() => { _zoneDrawPopupRaf = null; _zoneDrawShowPopup(); });
}
function _zoneDrawClear() {
zoneDrawLocked=false;
const lock=document.getElementById('btn-zonedraw-lock');
if(lock){lock.textContent='Lock polygon';lock.setAttribute('aria-pressed','false');}
_zoneDrawStorageStatus(window.__GRIDATLAS_MODULES__.polygonDraft.clearOutline());
zoneDrawPoints = [];
zoneDrawDragging = false;
zoneDrawDragIdx = -1;
zoneDrawJustDragged = false;
_zoneDrawCollapsed = false;
window._zdExpand = null;
window._zdCollapse = null;
closeActivePopup();
_zoneDrawUpdateLayers(false);
const el = document.getElementById('zonedraw-display');
if (el) el.style.display = 'none';
}
function zoneDrawHistoryMove(direction) {
const points = zoneHistory[direction](); if (!points) return;
zoneDrawPoints = points; zoneDrawDragging=false; zoneDrawDragIdx=-1;
zoneHistoryApplying=true;
try {_zoneDrawUpdateLayers(false);} finally {zoneHistoryApplying=false;}
if(points.length>=3)_zoneDrawShowPopup();