GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-bess-topology-v6/dc-ac-lv-topology-review

GIS Single-Line Diagram (SLD) V5 Map and 4 more files

A JavaScript file in the GIS SLD financial sandbox folder of GlobalGrid2050 that maps atlas grid 66kV line and atlas grid 132kV line. Served with the page at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.

700 lines of JavaScript and HTML and YAML from globalgrid2050, in 5 files. Topic: Solar and storage design. Section 89 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. Solar Battery Energy Storage System (BESS) Topology V6 — DC AC LV Topology Review Page render · globalgrid2050 / solar-bess-topology-v6/dc-ac-lv-topology-review/index.html lines 1–118
  2. 05 V6 Module Relevance docs-config · globalgrid2050 / solar-bess-topology-v6/docs/training/05_v6_module_relevance.yml lines 1–80
  3. GIS Single-Line Diagram (SLD) V5 Config electrical · globalgrid2050 / solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-config.js lines 1–24
  4. GIS Single-Line Diagram (SLD) V5 Helpers geodesy · globalgrid2050 / solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-helpers.js lines 1–75
  5. GIS Single-Line Diagram (SLD) V5 Map electrical · globalgrid2050 / solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-map.js lines 1–403

Solar Battery Energy Storage System (BESS) Topology V6 — DC AC LV Topology Review Page

A web page in GlobalGrid2050 that draws SVG graphics and reads inputs for mod wp, voc and vmp (units: MVA, °C, MW). Published at https://globalgrid2050.com/solar-bess-topology-v6/dc-ac-lv-topology-review/.

Set aside from the main view: Near copy of solar-bess-topology-v7/dc-ac-lv-topology-review/index.html (globalgrid2050), which stays: reachable first, then the higher version. (near-copy-of, proposed by families.py). 92% of lines shared with Solar Battery Energy Storage System (BESS) Topology V7 — DC AC LV Topology Review Page; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9231 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-bess-topology-v6/dc-ac-lv-topology-review/index.html:1-118 b41890abbcae51b737dfd79910c44b58e09c94ef
  • sha256 0f71dc665916d68e568fd5bdeb20148e40f3f28928909a355694a89912034b23
  • target sha256 39fcc13ae386ea5faab3abfbd4d09b701d42e9b74b7dc791b4f46d2042fd1248
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines
  • re-pointed by apply.py version rule (was canonical)

renderglobalgrid2050 / solar-bess-topology-v6/dc-ac-lv-topology-review/index.html · lines 1–118 of 118 · Entry point

What it does
It draws cables, 33kV, solar and transformers. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'ac'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 33kV, solar, transformers.
Inputs & outputs
In: form fields (user input). Out: web page; SVG drawing. Voltage levels named: 33kV.
Downstream impact
Used directly by 3 files: Solar Battery Energy Storage System (BESS) Topology V6 — Cable Geometry Visualiser Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/cable-geometry-visualiser/); GlobalGrid2050 — Solar Battery Energy Storage System (BESS) Topology V6 Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/); Solar Battery Energy Storage System (BESS) Topology V6 — Module Layout Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/module-layout/). It is itself an entry point, published at https://globalgrid2050.com/solar-bess-topology-v6/dc-ac-lv-topology-review/.
What it achieves
Its code works with 33 kV and 0 MVA.
Why it matters
Loaded by the Cable Geometry Visualiser page at https://globalgrid2050.com/solar-bess-topology-v6/cable-geometry-visualiser/ and 2 other pages.
Application
globalgrid2050 · solar-bess-topology-v6/dc-ac-lv-topology-review · page
Uses
GIS Single-Line Diagram (SLD) V4 (stylesheet), Module Layout V5 (stylesheet), DC AC LV Topology Review V5 (stylesheet), Solar Battery Energy Storage System (BESS) Topology V6 — Module Layout Page (link), Solar Battery Energy Storage System (BESS) Topology V6 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (link), DC AC LV Topology Review V5 (script src)
Used by
linked from Solar Battery Energy Storage System (BESS) Topology V6 — Cable Geometry Visualiser Page (link), linked from GlobalGrid2050 — Solar Battery Energy Storage System (BESS) Topology V6 Page (link), linked from Solar Battery Energy Storage System (BESS) Topology V6 — Module Layout Page (link)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-bess-topology-v6/dc-ac-lv-topology-review/index.html:1-118 · blob b41890abbcae51b737dfd79910c44b58e09c94ef · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>DC AC LV Topology Review V6 | GlobalGrid2050</title>
    <link rel="stylesheet" href="./gis-sld-v5.css" />
    <link rel="stylesheet" href="./module-layout-v5.css" />
    <link rel="stylesheet" href="./dc-ac-lv-topology-review-v5.css" />
</head>
<body>
    <div class="module-app-shell topo-app-shell">
        <header class="module-header topo-header">
            <div>
                <div class="module-kicker">GlobalGrid2050 V6</div>
                <h1>DC AC LV Topology Review</h1>
                <p>Separate low voltage and DC engineering app for solar PV cable topology, string sizing, inverter aggregation, skid loading and SCADA style topology review.</p>
            </div>
            <div class="topo-header-links">
<button id="topo_print_report" class="module-link print-btn" type="button" onclick="window.print()">Print</button>
                <a class="module-link" href="../module-layout/index.html">Module Layout V6</a>
                <a class="module-link" href="../gis-sld-financial-sandbox/index.html">Back to GIS SLD V6</a>
            </div>
        </header>

        <main class="module-main topo-main">
            <section class="module-panel topo-panel">
                <div class="topo-tabs">
                    <button id="topo_tab_string" class="topo-tab active" data-mode="string">String Inverter</button>
                    <button id="topo_tab_central" class="topo-tab" data-mode="central">Central Inverter</button>
                </div>

                <div class="topo-mode active" data-mode-panel="string">
                    <h2>Module Electrical Data</h2>
                    <label>Module Rating Wp</label><input id="s_mod_wp" type="number" value="660" step="1" />
                    <label>Module Voc V</label><input id="s_voc" type="number" value="45.9" step="0.01" />
                    <label>Module Vmp V</label><input id="s_vmp" type="number" value="38.1" step="0.01" />
                    <label>Module Isc A</label><input id="s_isc" type="number" value="18.45" step="0.01" />
                    <label>Module Imp A</label><input id="s_imp" type="number" value="17.35" step="0.01" />
                    <label>Maximum Series Fuse A</label><input id="s_fuse_a" type="number" value="35" step="1" />
                    <label>Maximum System Voltage Vdc</label><input id="s_system_v" type="number" value="1500" step="10" />
                    <label>Voc Temperature Coefficient % per °C</label><input id="s_voc_coeff" type="number" value="-0.25" step="0.01" />
                    <label>Isc Temperature Coefficient % per °C</label><input id="s_isc_coeff" type="number" value="0.04" step="0.01" />
                    <label>Minimum Design Temperature °C</label><input id="s_min_temp" type="number" value="-10" step="1" />
                    <label>Current Correction Factor</label><input id="s_current_factor" type="number" value="1.25" step="0.01" />
                    <label>Bifacial Current Uplift %</label><input id="s_bifacial_current" type="number" value="10" step="1" />

                    <h2>String Inverter Topology</h2>
                    <label>Modules per String</label><input id="s_modules_per_string" type="number" value="30" min="1" step="1" />
                    <label>Strings per String Inverter</label><input id="s_strings_per_inverter" type="number" value="21" min="1" step="1" />
                    <label>String Inverter Rating kVA</label><input id="s_inverter_kva" type="number" value="352" min="1" step="1" />
                    <label>String Inverters per Skid</label><input id="s_inverters_per_skid" type="number" value="28" min="1" step="1" />
                    <label>Skid Transformer Rating MVA</label><input id="s_skid_mva" type="number" value="8.96" min="0.1" step="0.01" />
                    <label>Skids per 33 kV Ring</label><input id="s_skids_per_ring" type="number" value="5" min="1" step="1" />

                    <h2>DC Cable Review</h2>
                    <label>DC String Cable Length m</label><input id="s_dc_length_m" type="number" value="300" min="1" step="1" />
                    <label>DC Cable CSA mm²</label><input id="s_dc_csa" type="number" value="6" min="1" step="1" />
                    <label>DC Cable Material</label><select id="s_dc_material"><option value="cu" selected>Copper</option><option value="al">Aluminium</option></select>
                    <label>Allowable DC Voltage Drop %</label><input id="s_dc_vdrop_limit" type="number" value="1.0" step="0.1" />
                </div>

                <div class="topo-mode" data-mode-panel="central">
                    <h2>Module Electrical Data</h2>
                    <label>Module Rating Wp</label><input id="c_mod_wp" type="number" value="660" step="1" />
                    <label>Module Voc V</label><input id="c_voc" type="number" value="45.9" step="0.01" />
                    <label>Module Vmp V</label><input id="c_vmp" type="number" value="38.1" step="0.01" />
                    <label>Module Isc A</label><input id="c_isc" type="number" value="18.45" step="0.01" />
                    <label>Maximum System Voltage Vdc</label><input id="c_system_v" type="number" value="1500" step="10" />
                    <label>Voc Temperature Coefficient % per °C</label><input id="c_voc_coeff" type="number" value="-0.25" step="0.01" />
                    <label>Minimum Design Temperature °C</label><input id="c_min_temp" type="number" value="-10" step="1" />
                    <label>Current Correction Factor</label><input id="c_current_factor" type="number" value="1.25" step="0.01" />
                    <label>Bifacial Current Uplift %</label><input id="c_bifacial_current" type="number" value="10" step="1" />

                    <h2>Central Inverter Topology</h2>
                    <label>Modules per String</label><input id="c_modules_per_string" type="number" value="30" min="1" step="1" />
                    <label>Strings per Combiner Box</label><input id="c_strings_per_combiner" type="number" value="24" min="1" step="1" />
                    <label>Combiner Box Design Limit kWdc</label><input id="c_combiner_limit_kw" type="number" value="500" min="1" step="10" />
                    <label>Central Inverter DC Input Rating MWdc</label><input id="c_inv_dc_mw" type="number" value="5.28" min="0.1" step="0.01" />
                    <label>Central Inverter AC Output Rating MWac</label><input id="c_inv_ac_mw" type="number" value="4.40" min="0.1" step="0.01" />
                    <label>Central Skid Transformer Rating MVA</label><input id="c_skid_mva" type="number" value="4.40" min="0.1" step="0.01" />
                    <label>Central Inverter Units per Skid</label><input id="c_inverters_per_skid" type="number" value="1" min="1" step="1" />
                    <label>Central Skids per 33 kV Ring</label><input id="c_skids_per_ring" type="number" value="5" min="1" step="1" />

                    <h2>DC Cable Review</h2>
                    <label>Home Run Cable Length m</label><input id="c_dc_length_m" type="number" value="300" min="1" step="1" />
                    <label>DC Cable CSA mm²</label><input id="c_dc_csa" type="number" value="6" min="1" step="1" />
                    <label>DC Cable Material</label><select id="c_dc_material"><option value="cu" selected>Copper</option><option value="al">Aluminium</option></select>
                    <label>Allowable DC Voltage Drop %</label><input id="c_dc_vdrop_limit" type="number" value="1.0" step="0.1" />
                </div>

                <h2>Topology Results</h2>
                <div class="module-stat"><span>String kWp</span><strong id="out_string_kwp">0</strong></div>
                <div class="module-stat"><span>String Vmp</span><strong id="out_string_vmp">0 V</strong></div>
                <div class="module-stat"><span>String Voc STC</span><strong id="out_string_voc_stc">0 V</strong></div>
                <div class="module-stat"><span>Cold String Voc</span><strong id="out_string_voc_cold">0 V</strong></div>
                <div class="module-stat"><span>Max Modules per String</span><strong id="out_max_modules">0</strong></div>
                <div class="module-stat"><span>Design String Current</span><strong id="out_design_current">0 A</strong></div>
                <div class="module-stat"><span>DC per Inverter</span><strong id="out_dc_per_inv">0 kWp</strong></div>
                <div class="module-stat"><span>Inverter DC/AC</span><strong id="out_dcac">0</strong></div>
                <div class="module-stat"><span>Skid DC / AC</span><strong id="out_skid_block">0</strong></div>
                <div class="module-stat"><span>Ring AC Rating</span><strong id="out_ring_ac">0 MVA</strong></div>
                <div class="module-stat"><span>DC Cable Loss</span><strong id="out_dc_loss">0%</strong></div>
                <div id="topo_status" class="module-status">Ready.</div>

                <div class="module-note">Screening tool only. It does not replace manufacturer checks, cable schedules, load flow, fault studies, insulation coordination, SPD coordination, protection grading, earthing design or IFC drawings.</div>
            </section>

            <section class="topo-scada-card">
                <div class="topo-scada-title">SCADA Style Cable Topology Panel</div>
                <svg id="topo_scada" viewBox="0 0 1200 760" role="img" aria-label="SCADA style topology drawing"></svg>
                <div class="topo-scada-footer"><span id="topo_footer_left">String inverter topology</span><span>Values recalculate live from left panel</span></div>
            </section>
        </main>
    </div>
    <script src="./dc-ac-lv-topology-review-v5.js?v=v6-migration-1"></script>
</body>
</html>

05 V6 Module Relevance

A configuration file in the training folder of GlobalGrid2050 covering battery storage (BESS), solar and cables.

docs-configglobalgrid2050 / solar-bess-topology-v6/docs/training/05_v6_module_relevance.yml · lines 1–80 of 80 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'bess'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: battery storage (BESS), solar, cables.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-bess-topology-v6/docs/training · configuration
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-bess-topology-v6/docs/training/05_v6_module_relevance.yml:1-80 · blob cdf170990c86ab0c6ec8c516a00bb8c44219dd59 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
training_folder: solar-bess-topology-v6/docs/training
public_homepage_link: false
confidentiality_rule: >
  Do not include project names, client names, site names, contractor names,
  supplier names, consultant names or confidential source document titles.
  Convert source material into generic engineering lessons only.

governing_rule:
  - Geometry first
  - Assumptions second
  - Screening third
  - Formal design only when verified

v6_modules:
  cable_geometry_visualiser:
    path: solar-bess-topology-v6/cable-geometry-visualiser
    relevant_training:
      - 01_cable_route_assumptions.md
      - 02_sld_topology_validation.md
      - 04_electrical_risk_controls.md
    future_feature_priority:
      - V6 cable route assumption schema phase 1
      - Export missing assumption flags
      - Add thermal and protection placeholder status
    do_not:
      - claim cable rating
      - claim compliance
      - add IEC thermal calculation before assumptions are stable

  gis_sld_financial_sandbox:
    path: solar-bess-topology-v6/gis-sld-financial-sandbox
    relevant_training:
      - 02_sld_topology_validation.md
      - 03_bess_grid_resilience.md
      - 04_electrical_risk_controls.md
    future_feature_priority:
      - Electrical topology validation phase 1
      - Feeder load aggregation
      - Transformer and inverter count cross checks
      - BESS availability and redundancy visibility
    do_not:
      - allow manual totals to override child object totals
      - treat SLD symbols as electrical validity
      - hide temperature rating basis

  dc_ac_lv_topology_review:
    path: solar-bess-topology-v6/dc-ac-lv-topology-review
    relevant_training:
      - 02_sld_topology_validation.md
      - 04_electrical_risk_controls.md
    future_feature_priority:
      - DC string voltage check placeholders
      - LV AC insulation coordination placeholders
      - Inverter feeder and protection status fields
      - Harmonic and reactive power assumption fields
    do_not:
      - assume unity power factor without explicit basis
      - assume cable voltage rating is valid without earthing basis
      - draw protection without protection data

  module_layout:
    path: solar-bess-topology-v6/module-layout
    relevant_training:
      - 02_sld_topology_validation.md
    future_feature_priority:
      - Link module count to SLD hierarchy later
      - Track module rating and mixed module flag later
      - Preserve physical layout as visual assumption level
    do_not:
      - treat physical module layout as verified electrical design
      - mix module geometry with full SLD logic too early

future_training_expansion:
  - employer_requirements_delivery_logic
  - commissioning_and_acceptance_logic
  - formal_testing_status_logic

current_recommendation: >
  Work on the tool first. Keep training modules short and generic.
  Do not encode contractual delivery logic until the V6 electrical layers are ready.

GIS Single-Line Diagram (SLD) V5 Config

A JavaScript file in the GIS SLD financial sandbox folder of GlobalGrid2050 covering grid substations. Served with the page at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.

Set aside from the main view: 90% of its lines are the same as feature_requests/002_extract_v2_config/files/solar-bess-topology-v2/gis-sld-v2-config.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 90% of lines shared with GIS Single-Line Diagram (SLD) V5 Config; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 feature_requests/002_extract_v2_config/files/solar-bess-topology-v2/gis-sld-v2-config.js:1-24 16f6bd9326da4b37595e2387875688de764ea254
  • sha256 c1c6c2054d5cdf124b487dafd73d4316cf52d1f58bf690ca1bc51dba3527f473
  • target sha256 65b623d4bf62135a3f36e5c0ead7648018db95602b369dfb519cc19542ab22c6
  • group of 8 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines
  • re-pointed by apply.py version rule from file 133 to file 254; similarity was measured to file 133

electricalglobalgrid2050 / solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-config.js · lines 1–24 of 24 · Entry point

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.
Downstream impact
Used directly by 1 file: Solar Battery Energy Storage System (BESS) Topology V6 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/). Reached from 4 other entry points, including GlobalGrid2050 — Solar Battery Energy Storage System (BESS) Topology V6 Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/); Solar Battery Energy Storage System (BESS) Topology V6 — Cable Geometry Visualiser Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/cable-geometry-visualiser/); Solar Battery Energy Storage System (BESS) Topology V6 — DC AC LV Topology Review Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/dc-ac-lv-topology-review/). It is itself an entry point, published at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.
What it achieves
GIS SLD Financial Sandbox V6. Config extracted by GridBot feature 002.
Why it matters
Loaded by the GIS Single-Line Diagram (SLD) Financial Sandbox page at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.
Application
globalgrid2050 · solar-bess-topology-v6/gis-sld-financial-sandbox · script
Uses
none found
Used by
loaded by Solar Battery Energy Storage System (BESS) Topology V6 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (script src)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-config.js:1-24 · blob 90a4214aa5fcbd7209b8495d2fd6f825f9dcb66c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: production_core
"use strict";

// GIS SLD Financial Sandbox V6
// Config extracted by GridBot feature 002.
// TODO: migrate config into the shared GISSLD namespace at feature 007.

const SUBSTATIONS_URL = "/grid_substations.geojson";

const CONSTANTS = {
    M2_PER_ACRE: 4046.86,
    BESS_M2_PER_MWH: 85,
    BESS_ASPECT: 2.5,
    BLOCK_SPACING_KM: 0.01,
    BOUNDARY_BUFFER_KM: 0.02,
    ARRAY_OFFSET_KM: 0.2,
    DEFAULT_CENTER: [-0.1276, 51.5072],
    DEFAULT_ZOOM: 13,
    RECALC_DEBOUNCE_MS: 80,
    BIFACIAL_BY_GCR: { "0.35": 8, "0.45": 5, "0.75": 2 },
    LOGISTICS_PRESETS: {
        high_density: { pallet: 33, container: 594 },
        legacy: { pallet: 31, container: 620 }
    }
};

GIS Single-Line Diagram (SLD) V5 Helpers

A JavaScript file in the GIS SLD financial sandbox folder of GlobalGrid2050 that sets class (`setClass`), picks prop (`pickProp`) and sets fetch status (`setFetchStatus`). Served with the page at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.

Set aside from the main view: 91% of its lines are the same as feature_requests/003_extract_v2_helpers/files/solar-bess-topology-v2/gis-sld-v2-helpers.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 91% of lines shared with GIS Single-Line Diagram (SLD) V5 Helpers; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.913 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 feature_requests/003_extract_v2_helpers/files/solar-bess-topology-v2/gis-sld-v2-helpers.js:1-75 3fe3702efbfab7b20e83e2e2f8113e55b3da2324
  • sha256 39038c6183f92fe8924411b76e859dd51e2d6a2f046dc411e03aead1245758ce
  • target sha256 ecacdadc1dcdda92a551a0ec31344c4b9cb96958f8e35bf92a2896355fdd49b6
  • group of 6 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines
  • re-pointed by apply.py version rule from file 134 to file 256; similarity was measured to file 134

geodesyglobalgrid2050 / solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-helpers.js · lines 1–75 of 75 · Entry point · pattern setFetchStatus (shared by 7 files)

What it does
Defines 11 functions or classes, including $, num, intVal, checked, setText. Side effects: changes the web page (DOM).
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.
Downstream impact
Used directly by 2 files: Solar Battery Energy Storage System (BESS) Topology V6 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/); Solar Battery Energy Storage System (BESS) Topology V6 — Module Layout Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/module-layout/). Reached from 3 other entry points, including GlobalGrid2050 — Solar Battery Energy Storage System (BESS) Topology V6 Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/); Solar Battery Energy Storage System (BESS) Topology V6 — Cable Geometry Visualiser Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/cable-geometry-visualiser/); Solar Battery Energy Storage System (BESS) Topology V6 — DC AC LV Topology Review Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/dc-ac-lv-topology-review/). It is itself an entry point, published at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.
What it achieves
It sets text (`setText`), sets class (`setClass`) and picks prop (`pickProp`). GIS SLD Financial Sandbox V6. Helpers extracted by GridBot feature 003.
Why it matters
Loaded by the GIS Single-Line Diagram (SLD) Financial Sandbox page at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/ and 1 other page.
Application
globalgrid2050 · solar-bess-topology-v6/gis-sld-financial-sandbox · script
Uses
none found
Used by
loaded by Solar Battery Energy Storage System (BESS) Topology V6 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (script src), loaded by Solar Battery Energy Storage System (BESS) Topology V6 — Module Layout Page (script src)
Produces
$, num, intVal, checked, setText, setClass, money, debounce, isValidLngLat, pickProp, setFetchStatus
Defines here
$, num, intVal, checked, setText, setClass, money, debounce, isValidLngLat, pickProp, setFetchStatus
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-helpers.js:1-75 · blob ef110bd577feea506cfc7aa05d5a58f7680a010a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: production_core
"use strict";

// GIS SLD Financial Sandbox V6
// Helpers extracted by GridBot feature 003.
// Must load after gis-sld-v5-config.js and before the inline app script.

const $ = (id) => document.getElementById(id);

const num = (id) => {
    const el = $(id);
    return el ? (parseFloat(el.value) || 0) : 0;
};

const intVal = (id, fallback = 0) => {
    const el = $(id);
    return el ? (parseInt(el.value, 10) || fallback) : fallback;
};

const checked = (id) => {
    const el = $(id);
    return el ? !!el.checked : false;
};

const setText = (id, val) => {
    const el = $(id);
    if (el) el.textContent = val;
};

const setClass = (id, cls) => {
    const el = $(id);
    if (el) el.className = cls;
};

function money(v) {
    const rounded = Math.round(v);
    if (rounded < 0) return "-£" + Math.abs(rounded).toLocaleString();
    return "£" + rounded.toLocaleString();
}

function debounce(fn, ms) {
    let t = null;
    return function(...args) {
        clearTimeout(t);
        t = setTimeout(() => fn.apply(this, args), ms);
    };
}

function isValidLngLat(c) {
    return Array.isArray(c) && c.length >= 2
        && Number.isFinite(+c[0]) && Number.isFinite(+c[1])
        && +c[0] >= -180 && +c[0] <= 180 && +c[1] >= -90 && +c[1] <= 90;
}

function pickProp(obj, keys, fallback = null) {
    for (const k of keys) {
        if (obj && obj[k] !== undefined && obj[k] !== null && obj[k] !== "") return obj[k];
    }
    return fallback;
}

function setFetchStatus(msg, isError) {
    const el = $("fetch_status");
    if (!el) return;

    if (!msg) {
        el.style.display = "none";
        el.textContent = "";
        el.classList.remove("error");
        return;
    }

    el.textContent = msg;
    el.style.display = "block";
    el.classList.toggle("error", !!isError);
}

GIS Single-Line Diagram (SLD) V5 Map

A JavaScript file in the GIS SLD financial sandbox folder of GlobalGrid2050 that maps atlas grid 66kV line and atlas grid 132kV line. Served with the page at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.

electricalglobalgrid2050 / solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-map.js · lines 1–403 of 427 · Entry point · pattern toggleAtlasV8OperatingAssetLayer (shared by 2 files)

What it does
It maps atlas grid 66kV line, atlas grid 132kV line, atlas grid 275kV line and atlas grid 400kV line. Defines 10 functions or classes, including toggleAtlasV8OperatingAssetLayer, toggleAtlasV8GridLayer, initMap, onMapLoad, showPopup. Side effects: changes the web page (DOM).
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.
Inputs & outputs
In: JSON file style.json; GeoJSON file grid_66kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_400kv.geojson; JSON file repd_master.json. Out: interactive map. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV.
Downstream impact
Used directly by 1 file: Solar Battery Energy Storage System (BESS) Topology V6 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/). Reached from 4 other entry points, including GlobalGrid2050 — Solar Battery Energy Storage System (BESS) Topology V6 Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/); Solar Battery Energy Storage System (BESS) Topology V6 — Cable Geometry Visualiser Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/cable-geometry-visualiser/); Solar Battery Energy Storage System (BESS) Topology V6 — DC AC LV Topology Review Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v6/dc-ac-lv-topology-review/). It is itself an entry point, published at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.
What it achieves
It toggles atlas v8 grid layer (`toggleAtlasV8GridLayer`) and shows popup (`showPopup`). Defines `toggleAtlasV8OperatingAssetLayer`, `toggleAtlasV8GridLayer`, `initMap` and 7 more.
Why it matters
Loaded by the GIS Single-Line Diagram (SLD) Financial Sandbox page at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.
Application
globalgrid2050 · solar-bess-topology-v6/gis-sld-financial-sandbox · script
Uses
none found
Used by
loaded by Solar Battery Energy Storage System (BESS) Topology V6 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (script src)
Produces
toggleAtlasV8OperatingAssetLayer, toggleAtlasV8GridLayer, initMap, onMapLoad, showPopup, onSubstationClick, onInverterClick, onCableRoutePinClick, onOperatingAssetClick, onPoiClick
Defines here
toggleAtlasV8OperatingAssetLayer, toggleAtlasV8GridLayer, initMap, onMapLoad, showPopup, onSubstationClick, onInverterClick, onCableRoutePinClick, onOperatingAssetClick
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-map.js:1-403 · blob 57b562ff006c7098451eb446d54a979999b2ac1a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: production_core
"use strict";

// MAP
// ============================================================
let map = null;
const atlasV8GridLayerVisibility = {
    "66kv": false,
    "132kv": false,
    "275kv": false,
    "400kv": false
};

const atlasV8GridLayerIds = {
    "66kv": "atlas-v8-grid-66kv-line",
    "132kv": "atlas-v8-grid-132kv-line",
    "275kv": "atlas-v8-grid-275kv-line",
    "400kv": "atlas-v8-grid-400kv-line"
};

const atlasV8OperatingAssetVisibility = {
    "solar_operational": false,
    "wind_onshore_operational": false,
    "wind_offshore_operational": false,
    "bess_operational": false
};

const atlasV8OperatingAssetLayerIds = {
    "solar_operational": "atlas-v8-asset-solar-operational",
    "wind_onshore_operational": "atlas-v8-asset-wind-onshore-operational",
    "wind_offshore_operational": "atlas-v8-asset-wind-offshore-operational",
    "bess_operational": "atlas-v8-asset-bess-operational"
};

function toggleAtlasV8OperatingAssetLayer(assetKey) {
    if (!atlasV8OperatingAssetLayerIds[assetKey]) return;
    atlasV8OperatingAssetVisibility[assetKey] = !atlasV8OperatingAssetVisibility[assetKey];
    const layerId = atlasV8OperatingAssetLayerIds[assetKey];
    if (map && map.getLayer(layerId)) {
        map.setLayoutProperty(layerId, "visibility", atlasV8OperatingAssetVisibility[assetKey] ? "visible" : "none");
    }
    updateLegend?.();
}

function toggleAtlasV8GridLayer(voltageKey) {
    if (!atlasV8GridLayerIds[voltageKey]) return;
    atlasV8GridLayerVisibility[voltageKey] = !atlasV8GridLayerVisibility[voltageKey];
    const layerId = atlasV8GridLayerIds[voltageKey];
    if (map && map.getLayer(layerId)) {
        map.setLayoutProperty(layerId, "visibility", atlasV8GridLayerVisibility[voltageKey] ? "visible" : "none");
    }
    updateLegend();
}


function initMap() {
    if (typeof maplibregl === "undefined") {
        setFetchStatus("MapLibre failed to load. Check network.", true);
        console.error("maplibregl is undefined");
        return;
    }
    if (typeof turf === "undefined") {
        setFetchStatus("Turf failed to load. Check network.", true);
        console.error("turf is undefined");
        return;
    }

    map = new maplibregl.Map({
        container: "map",
        style: "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",
        center: CONSTANTS.DEFAULT_CENTER,
        zoom: CONSTANTS.DEFAULT_ZOOM
    });

    map.on("error", (e) => console.error("MapLibre error:", e && e.error ? e.error : e));
    map.on("load", onMapLoad);
}

function onMapLoad() {
    map.addSource("sat-s", {
        type: "raster",
        tiles: ["https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"],
        tileSize: 256
    });
    map.addLayer({ id: "l-sat", type: "raster", source: "sat-s", layout: { visibility: "none" } });
// Atlas V8 transmission visibility layers
// These layers are read from the existing Atlas V8 data folder.
// They are visual context only and do not imply confirmed grid headroom.
map.addSource("atlas-v8-grid-66kv", {
    type: "geojson",
    data: "../../repd_grid_atlasv8/data/grid_66kv.geojson"
});
map.addLayer({
    id: "atlas-v8-grid-66kv-line",
    type: "line",
    source: "atlas-v8-grid-66kv",
    layout: { visibility: atlasV8GridLayerVisibility["66kv"] ? "visible" : "none" },
    paint: {
        "line-color": "#66ff66",
        "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0.8, 10, 1.4, 14, 2.4],
        "line-opacity": 0.62
    }
});

map.addSource("atlas-v8-grid-132kv", {
    type: "geojson",
    data: "../../repd_grid_atlasv8/data/grid_132kv.geojson"
});
map.addLayer({
    id: "atlas-v8-grid-132kv-line",
    type: "line",
    source: "atlas-v8-grid-132kv",
    layout: { visibility: atlasV8GridLayerVisibility["132kv"] ? "visible" : "none" },
    paint: {
        "line-color": "#ffcc00",
        "line-width": ["interpolate", ["linear"], ["zoom"], 5, 1.0, 10, 1.8, 14, 3.0],
        "line-opacity": 0.72
    }
});

map.addSource("atlas-v8-grid-275kv", {
    type: "geojson",
    data: "../../repd_grid_atlasv8/data/grid_275kv.geojson"
});
map.addLayer({
    id: "atlas-v8-grid-275kv-line",
    type: "line",
    source: "atlas-v8-grid-275kv",
    layout: { visibility: atlasV8GridLayerVisibility["275kv"] ? "visible" : "none" },
    paint: {
        "line-color": "#ff66ff",
        "line-width": ["interpolate", ["linear"], ["zoom"], 5, 1.3, 10, 2.4, 14, 3.7],
        "line-opacity": 0.76
    }
});

map.addSource("atlas-v8-grid-400kv", {
    type: "geojson",
    data: "../../repd_grid_atlasv8/data/grid_400kv.geojson"
});
map.addLayer({
    id: "atlas-v8-grid-400kv-line",
    type: "line",
    source: "atlas-v8-grid-400kv",
    layout: { visibility: atlasV8GridLayerVisibility["400kv"] ? "visible" : "none" },
    paint: {
        "line-color": "#ff3333",
        "line-width": ["interpolate", ["linear"], ["zoom"], 5, 1.6, 10, 2.8, 14, 4.2],
        "line-opacity": 0.82
    }
});



    map.addSource("src-subs", { type: "geojson", data: { type: "FeatureCollection", features: [] } });
    map.addLayer({
        id: "l-subs", type: "circle", source: "src-subs",
        paint: {
            "circle-color": "#ffffff",
            "circle-radius": ["interpolate", ["linear"], ["zoom"], 5, 3, 10, 5, 14, 10, 18, 22],
            "circle-stroke-width": 1, "circle-stroke-color": "#ff3333", "circle-opacity": 0.8
        }
    });



    // Atlas V8 operating asset visibility layers from REPD master data.
    // These are existing operating asset context layers only.
    // They help users inspect nearby operating solar, wind and battery assets before drawing a new array.
    map.addSource("atlas-v8-repd-operating-assets", {
        type: "geojson",
        data: "/dist/repd_master.json"
    });

    map.addLayer({
        id: "atlas-v8-asset-solar-operational",
        type: "circle",
        source: "atlas-v8-repd-operating-assets",
        filter: ["all", ["==", ["get", "tech"], "solar"], ["==", ["get", "status"], "operational"]],
        layout: { visibility: atlasV8OperatingAssetVisibility["solar_operational"] ? "visible" : "none" },
        paint: {
            "circle-color": "#00ff88",
            "circle-radius": ["interpolate", ["linear"], ["coalesce", ["get", "capacity"], 0], 0, 5, 10, 7, 50, 10, 100, 13, 200, 16, 350, 20, 500, 24],
            "circle-stroke-color": "#111111",
            "circle-stroke-width": 1,
            "circle-opacity": 0.88
        }
    });

    map.addLayer({
        id: "atlas-v8-asset-wind-onshore-operational",
        type: "circle",
        source: "atlas-v8-repd-operating-assets",
        filter: ["all", ["==", ["get", "raw_tech"], "Wind Onshore"], ["==", ["get", "status"], "operational"]],
        layout: { visibility: atlasV8OperatingAssetVisibility["wind_onshore_operational"] ? "visible" : "none" },
        paint: {
            "circle-color": "#00ffcc",
            "circle-radius": ["interpolate", ["linear"], ["coalesce", ["get", "capacity"], 0], 0, 5, 10, 7, 50, 10, 100, 13, 200, 16, 350, 20, 500, 24],
            "circle-stroke-color": "#111111",
            "circle-stroke-width": 1,
            "circle-opacity": 0.88
        }
    });

    map.addLayer({
        id: "atlas-v8-asset-wind-offshore-operational",
        type: "circle",
        source: "atlas-v8-repd-operating-assets",
        filter: ["all", ["==", ["get", "raw_tech"], "Wind Offshore"], ["==", ["get", "status"], "operational"]],
        layout: { visibility: atlasV8OperatingAssetVisibility["wind_offshore_operational"] ? "visible" : "none" },
        paint: {
            "circle-color": "#0066ff",
            "circle-radius": ["interpolate", ["linear"], ["coalesce", ["get", "capacity"], 0], 0, 5, 10, 7, 50, 10, 100, 13, 200, 16, 350, 20, 500, 24],
            "circle-stroke-color": "#ffffff",
            "circle-stroke-width": 1,
            "circle-opacity": 0.88
        }
    });

    map.addLayer({
        id: "atlas-v8-asset-bess-operational",
        type: "circle",
        source: "atlas-v8-repd-operating-assets",
        filter: ["all", ["==", ["get", "tech"], "bess"], ["==", ["get", "status"], "operational"]],
        layout: { visibility: atlasV8OperatingAssetVisibility["bess_operational"] ? "visible" : "none" },
        paint: {
            "circle-color": "#ff69b4",
            "circle-radius": ["interpolate", ["linear"], ["coalesce", ["get", "capacity"], 0], 0, 5, 10, 7, 50, 10, 100, 13, 200, 16, 350, 20, 500, 24],
            "circle-stroke-color": "#111111",
            "circle-stroke-width": 1,
            "circle-opacity": 0.9
        }
    });

    map.addSource("topology", { type: "geojson", data: state.currentGeoJSON });

    map.addLayer({
        id: "overall_boundary_fill", type: "fill", source: "topology",
        filter: ["==", "type", "array_boundary"],
        paint: { "fill-color": "#0066ff", "fill-opacity": 0.25 }
    });
    map.addLayer({
        id: "overall_boundary_line", type: "line", source: "topology",
        filter: ["==", "type", "array_boundary"],
        paint: { "line-color": "#0066ff", "line-width": 2, "line-dasharray": [4, 4] }
    });
    map.addLayer({
        id: "footprints", type: "fill", source: "topology",
        filter: ["in", ["get", "type"], ["literal", ["skid_footprint", "central_footprint", "bess_footprint"]]],
        paint: {
            "fill-color": ["match", ["get", "type"],
                "skid_footprint", "#00ffff", "central_footprint", "#ff9900", "bess_footprint", "#ff00aa", "#000"],
            "fill-opacity": 0.15
        }
    });
    map.addLayer({
        id: "footprints_outline", type: "line", source: "topology",
        filter: ["in", ["get", "type"], ["literal", ["skid_footprint", "central_footprint", "bess_footprint"]]],
        paint: {
            "line-color": ["match", ["get", "type"],
                "skid_footprint", "#00ffff", "central_footprint", "#ff9900", "bess_footprint", "#ff00aa", "#000"],
            "line-width": 1
        }
    });
    map.addLayer({
        id: "export_cable", type: "line", source: "topology",
        filter: ["==", "type", "export_cable"],
        paint: { "line-color": "#ff3333", "line-width": 2, "line-dasharray": [4, 4] }
    });
    map.addLayer({
        id: "radial_spine", type: "line", source: "topology",
        filter: ["==", "type", "33kv_radial"],
        paint: { "line-color": "#00ffff", "line-width": 2 }
    });
    map.addLayer({
        id: "export_cable_pins", type: "circle", source: "topology",
        filter: ["==", "type", "export_cable_pin"],
        paint: {
            "circle-color": ["case", ["==", ["get", "committed_to_route"], true], "#ff3333", "#ff9900"],
            "circle-radius": ["interpolate", ["linear"], ["zoom"], 8, 4, 14, 6, 18, 10],
            "circle-stroke-color": "#ffffff",
            "circle-stroke-width": 1.5,
            "circle-opacity": 0.95
        }
    });
    map.addLayer({
        id: "inverters", type: "circle", source: "topology",
        filter: ["in", ["get", "type"], ["literal", ["string_substation", "central_inverter", "mv_station", "bess_compound"]]],
        paint: {
            "circle-color": ["match", ["get", "type"],
                "string_substation", "#ffff00", "central_inverter", "#ff9900",
                "mv_station", "#6633ff", "bess_compound", "#ff00aa", "#fff"],
            "circle-radius": ["match", ["get", "type"],
                "string_substation", 4, "central_inverter", 6, "mv_station", 4, "bess_compound", 6, 3],
            "circle-stroke-color": "#000", "circle-stroke-width": 1
        }
    });
    map.addLayer({
        id: "substation", type: "circle", source: "topology",
        filter: ["in", ["get", "type"], ["literal", ["poi", "private_sub"]]],
        paint: {
            "circle-color": ["match", ["get", "type"], "poi", "#ff3333", "private_sub", "#00ff88", "#fff"],
            "circle-radius": 8, "circle-stroke-color": "#fff", "circle-stroke-width": 2
        }
    });

    // Map clicks
    map.on("click", "l-subs", onSubstationClick);
    map.on("mouseenter", "l-subs", () => map.getCanvas().style.cursor = "pointer");
    map.on("mouseleave", "l-subs", () => map.getCanvas().style.cursor = "");

    map.on("click", "inverters", onInverterClick);
    map.on("mouseenter", "inverters", () => map.getCanvas().style.cursor = "pointer");
    map.on("mouseleave", "inverters", () => map.getCanvas().style.cursor = "");

    map.on("click", "export_cable_pins", onCableRoutePinClick);
    map.on("mouseenter", "export_cable_pins", () => map.getCanvas().style.cursor = "pointer");
    map.on("mouseleave", "export_cable_pins", () => map.getCanvas().style.cursor = "");

    map.on("click", "substation", onPoiClick);
    map.on("mouseenter", "substation", () => map.getCanvas().style.cursor = "pointer");
    map.on("mouseleave", "substation", () => map.getCanvas().style.cursor = "");

    ["atlas-v8-asset-solar-operational", "atlas-v8-asset-wind-onshore-operational", "atlas-v8-asset-wind-offshore-operational", "atlas-v8-asset-bess-operational"].forEach(layerId => {
        map.on("click", layerId, onOperatingAssetClick);
        map.on("mouseenter", layerId, () => map.getCanvas().style.cursor = "pointer");
        map.on("mouseleave", layerId, () => map.getCanvas().style.cursor = "");
    });

    loadSubstations();
    updateLegend();
    recalcAll();
}

function showPopup(coords, html) {
    if (state.activePopup) state.activePopup.remove();
    state.activePopup = new maplibregl.Popup().setLngLat(coords).setHTML(html).addTo(map);
    state.activePopup.on("close", () => { state.activePopup = null; });
}

// ============================================================
// MAP CLICK HANDLERS
// ============================================================
function onSubstationClick(e) {
    const f = e.features && e.features[0];
    if (!f || !f.geometry) return;
    const coords = f.geometry.coordinates.slice();
    const p = f.properties || {};

    state.selectedSubstation = {
        name: p.name_clean || pickProp(p, ["name","Name","SiteName","Site Name","substation","Substation"], "Selected Substation"),
        voltage: p.voltage_clean || pickProp(p, ["voltage","Voltage","kv","kV","KV"], "Unknown"),
        properties: p,
        coordinates: coords
    };
    state.activeDrawCenter = coords;
    updateSelectedSubstationDisplay();
    computeAndDraw();

    showPopup(coords, `
        <div style="margin-bottom:5px;color:#ff3333;font-weight:bold;font-size:13px;text-transform:uppercase;">Grid Node</div>
        <div class="popup-row"><span>Name:</span><span class="popup-val" style="color:#fff;">${state.selectedSubstation.name}</span></div>
        <div class="popup-row"><span>Voltage:</span><span class="popup-val" style="color:#fff;">${state.selectedSubstation.voltage}</span></div>
        <div class="popup-row"><span>Lon:</span><span class="popup-val" style="color:#fff;">${Number(coords[0]).toFixed(6)}</span></div>
        <div class="popup-row"><span>Lat:</span><span class="popup-val" style="color:#fff;">${Number(coords[1]).toFixed(6)}</span></div>
    `);
}

function onInverterClick(e) {
    const prop = e.features[0].properties;
    const coords = e.features[0].geometry.coordinates.slice();
    const colourMap = {
        central_inverter: "#ff9900", string_substation: "#ffff00",
        bess_compound: "#ff00aa", mv_station: "#6633ff"
    };
    const colour = colourMap[prop.type] || "#00ffff";
    let html = `<div style="margin-bottom:5px;color:${colour};font-weight:bold;font-size:13px;text-transform:uppercase;">Block Info</div>
                <div class="popup-row"><span>Type:</span><span class="popup-val" style="color:#fff;">${prop.type}</span></div>`;
    if (prop.type === "bess_compound" && prop.mwh !== undefined) {
        html += `<div class="popup-row"><span>Capacity:</span><span class="popup-val" style="color:#fff;">${prop.mwh} MWh</span></div>`;
    }
    showPopup(coords, html);
}

function onCableRoutePinClick(e) {
    const prop = e.features[0].properties;
    const coords = e.features[0].geometry.coordinates.slice();
    const idx = prop.pin_index || "?";
    showPopup(coords, `
        <div style="margin-bottom:5px;color:#ff9900;font-weight:bold;font-size:13px;text-transform:uppercase;">Cable Route Pin</div>
        <div class="popup-row"><span>Pin:</span><span class="popup-val" style="color:#fff;">${idx}</span></div>
        <div class="popup-row"><span>Status:</span><span class="popup-val" style="color:#fff;">${prop.committed_to_route ? "Committed to cable route" : "Dropped but not drawn"}</span></div>
        <div class="popup-row"><span>Lon:</span><span class="popup-val" style="color:#fff;">${Number(coords[0]).toFixed(6)}</span></div>
        <div class="popup-row"><span>Lat:</span><span class="popup-val" style="color:#fff;">${Number(coords[1]).toFixed(6)}</span></div>
    `);
}


function onOperatingAssetClick(e) {
    const feature = e.features && e.features[0];
    if (!feature || !feature.geometry) return;
    const prop = feature.properties || {};
    const coords = feature.geometry.coordinates.slice();
    const name = pickProp(prop, ["name", "project", "Project Name", "site", "Site Name", "ref_name"], "Operating asset");