GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-bess-topology-v6/gis-sld-financial-sandbox

GIS Single-Line Diagram (SLD) V5 UI (part 1)

A JavaScript file in the GIS SLD financial sandbox folder of GlobalGrid2050 covering cables and 66kV, using haversine, and uses data from OpenStreetMap Nominatim. Served with the page at https://globalgrid2050.com/solar-bess-topology-v6/gis-sld-financial-sandbox/.

370 lines of JavaScript from globalgrid2050, in 1 file. Topic: Solar and storage design. Section 91 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. GIS Single-Line Diagram (SLD) V5 UI electrical · globalgrid2050 / solar-bess-topology-v6/gis-sld-financial-sandbox/gis-sld-v5-ui.js lines 439–808

GIS Single-Line Diagram (SLD) V5 UI

A JavaScript file in the GIS SLD financial sandbox folder of GlobalGrid2050 covering cables and 66kV, using haversine, and uses data from OpenStreetMap Nominatim. 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-ui.js · lines 439–808 of 808 (continued from section 90) · Entry point · pattern updateAtlasV8OperatingAssetToggleButtons (shared by 3 files)

What it does
It draws cables, 66kV, 132kV and 275kV. Defines 55 functions or classes, including switchTab, applyLogisticsPreset, autoFillBifacial, updateExportCableLengthDisplay, updateArrayRotationDisplay. Side effects: changes the web page (DOM); makes network requests.
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: cables, 66kV, 132kV, 275kV, 400kV.
Inputs & outputs
In: data source: OpenStreetMap Nominatim; form fields (user input). Voltage levels named: 400kV, 275kV, 132kV, 66kV.
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 applies logistics preset (`applyLogisticsPreset`), updates export cable length display (`updateExportCableLengthDisplay`) and updates array rotation display (`updateArrayRotationDisplay`). Defines `switchTab`, `applyLogisticsPreset`, `autoFillBifacial` and 52 more. Its code works with 132 kV, 275 kV and 400 kV. It responds to click, keydown and change events.
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
switchTab, applyLogisticsPreset, autoFillBifacial, updateExportCableLengthDisplay, updateArrayRotationDisplay, rotateArrayBy, resetArrayRotation, getCurrentArrayCenter, getArrayNudgeStepKm, clearRouteAfterArrayShift, nudgeArray, updateCableRouteStatus
Defines here
wireMapToolOverlayButtons, wireEvents, wireMapMoveEvents, boot, sleepForPrintPack, setLayerVisibilityForPrintPack, setAtlasLayersDefaultOff, setSubsDefaultOff, enforceCleanDefaultMapLayers, getMapPrintState, restoreMapPrintState, ensurePrintMapPackContainer, addPrintMapFigure, captureCurrentMapForPrint, getTopologyBoundsForPrintPack, fitContextMapForPrint, setSatelliteForPrintPack, prepareGisSldPrintReport
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-ui.js:439-808 · blob b65b6bce00e25824d99c55aa431aeb71b4883a33 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
    const overlay = $("map_tool_overlay");
    const btn = $("btn_map_tools_toggle");
    if (!overlay || !btn) return;
    const collapsed = !overlay.classList.contains("tools-collapsed");
    overlay.classList.toggle("tools-collapsed", collapsed);
    btn.textContent = collapsed ? "TOOLS OFF" : "TOOLS ON";
    btn.classList.toggle("active", !collapsed);
}

function wireMapToolOverlayButtons() {
    $("btn_map_tools_toggle")?.addEventListener("click", toggleMapToolsOverlay);
    $("btn_map_draw")?.addEventListener("click", triggerDrawAtCenter);
    $("btn_map_pick_array")?.addEventListener("click", toggleArrayMoveMode);
    $("btn_map_drop_pins")?.addEventListener("click", toggleCablePinMode);
    $("btn_map_draw_route")?.addEventListener("click", commitCablePinRoute);
    $("btn_map_rotate_left")?.addEventListener("click", () => rotateArrayBy(-30));
    $("btn_map_rotate_right")?.addEventListener("click", () => rotateArrayBy(30));
    $("btn_map_rotate_90")?.addEventListener("click", () => rotateArrayBy(90));
    $("btn_map_reset_rotation")?.addEventListener("click", resetArrayRotation);
    $("btn_map_reset_array")?.addEventListener("click", resetArrayLocation);
    $("btn_map_nudge_up")?.addEventListener("click", () => nudgeArray(0));
    $("btn_map_nudge_right")?.addEventListener("click", () => nudgeArray(90));
    $("btn_map_nudge_down")?.addEventListener("click", () => nudgeArray(180));
    $("btn_map_nudge_left")?.addEventListener("click", () => nudgeArray(270));
    $("btn_map_undo_pin")?.addEventListener("click", undoCablePin);
    $("btn_map_clear_route")?.addEventListener("click", clearCableRoute);
}
// ============================================================
// WIRE EVERYTHING UP
// ============================================================
function wireEvents() {
    injectExportCableLengthControl();

    // Tab buttons
    document.querySelectorAll(".tab-btn").forEach(btn => {
        btn.addEventListener("click", () => switchTab(btn.dataset.tab));
    });

    // Map toggles
    $("btn_basemap")?.addEventListener("click", toggleBasemap);
    $("btn_subs_toggle")?.addEventListener("click", toggleSubs);
wireAtlasV8GridToggleButtons();
wireAtlasV8OperatingAssetToggleButtons();
$("btn_map_expand")?.addEventListener("click", toggleMapExpand);
$("btn_key_toggle")?.addEventListener("click", toggleKeyCollapse);
$("btn_print_report")?.addEventListener("click", () => window.print());
wireMapToolOverlayButtons();




    // Draw / Export
    $("btn_draw")?.addEventListener("click", triggerDrawAtCenter);
    $("btn_export")?.addEventListener("click", exportGeoJSON);

    // Array rotation
    $("btn_rotate_left_30")?.addEventListener("click", () => rotateArrayBy(-30));
    $("btn_rotate_right_30")?.addEventListener("click", () => rotateArrayBy(30));
    $("btn_rotate_right_90")?.addEventListener("click", () => rotateArrayBy(90));
    $("btn_reset_rotation")?.addEventListener("click", resetArrayRotation);

    // Array movement
    $("btn_pick_array")?.addEventListener("click", toggleArrayMoveMode);
    $("btn_reset_array_move")?.addEventListener("click", resetArrayLocation);
    $("btn_nudge_up")?.addEventListener("click", () => nudgeArray(0));
    $("btn_nudge_right")?.addEventListener("click", () => nudgeArray(90));
    $("btn_nudge_down")?.addEventListener("click", () => nudgeArray(180));
    $("btn_nudge_left")?.addEventListener("click", () => nudgeArray(270));

    // Cable route pins
    $("btn_drop_cable_pins")?.addEventListener("click", toggleCablePinMode);
    $("btn_draw_cable_route")?.addEventListener("click", commitCablePinRoute);
    $("btn_undo_cable_pin")?.addEventListener("click", undoCablePin);
    $("btn_clear_cable_route")?.addEventListener("click", clearCableRoute);

    // Search
    $("btn_search")?.addEventListener("click", searchLocation);
    $("loc_search")?.addEventListener("keydown", (e) => { if (e.key === "Enter") searchLocation(); });

    // Logistics presets
    document.querySelectorAll("[data-suffix]").forEach(sel => {
        sel.addEventListener("change", () => applyLogisticsPreset(sel.value, sel.dataset.suffix));
    });

    // Bifacial auto-fill

// Development stage defaults
document.querySelectorAll("[data-dev-stage-prefix]").forEach(sel => {
    sel.addEventListener("change", () => {
        applyDevelopmentStageDefaults(sel.dataset.devStagePrefix);
        recalcAll();
    });
});
    $("mounting_type")?.addEventListener("change", (e) => autoFillBifacial(e.target.value, "fin_string_bifacial"));
    $("mounting_type_c")?.addEventListener("change", (e) => autoFillBifacial(e.target.value, "fin_central_bifacial"));

    // Safe export cable length adjustment
    $("layout_export_extra_km")?.addEventListener("input", () => {
        state.arrayOverrideCenter = null;
        clearRouteAfterArrayShift();
        redrawIfTopologyExists();
    });
    $("layout_export_extra_km")?.addEventListener("change", () => {
        state.arrayOverrideCenter = null;
        clearRouteAfterArrayShift();
        redrawIfTopologyExists();
    });

    // Global recalc on input changes (debounced)
    document.querySelectorAll("input, select").forEach(el => {
        el.addEventListener("input", recalcDebounced);
        el.addEventListener("change", recalcDebounced);
    });
}

function wireMapMoveEvents() {
    if (!map || map.__arrayMoveWired) return;
    map.__arrayMoveWired = true;
    map.on("click", (e) => {
        if (state.cableRoutePinMode) addCableRoutePin(e);
        else placeArrayAtMapPoint(e);
    });
}

// ============================================================
// BOOT
// ============================================================
function boot() {
    wireEvents();
    initMap();
    if (map) map.on("load", wireMapMoveEvents);
    wireMapMoveEvents();
    updateSelectedSubstationDisplay();
    renderBenchmark();
    setArrayMoveStatus("Draw a grid first. Then use Pick Up Array or nudge arrows to relocate the array centre.", false);
    updateExportCableLengthDisplay();
    updateArrayRotationDisplay();
    updateCableRouteStatus();
}

// Libraries loaded via defer, so DOMContentLoaded is the right signal.
if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", boot);
} else {
    boot();
}

// GLOBALGRID2050 GIS SLD PRINT MAP PACK
function sleepForPrintPack(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function setLayerVisibilityForPrintPack(layerId, visible) {
    if (!map || !map.getLayer(layerId)) return;
    map.setLayoutProperty(layerId, "visibility", visible ? "visible" : "none");
}

function setAtlasLayersDefaultOff() {
    if (typeof atlasV8GridLayerVisibility === "undefined") return;
    Object.keys(atlasV8GridLayerVisibility).forEach(voltageKey => {
        atlasV8GridLayerVisibility[voltageKey] = false;
        const layerId = atlasV8GridLayerIds?.[voltageKey];
        if (layerId) setLayerVisibilityForPrintPack(layerId, false);
    });
    updateAtlasV8GridToggleButtons?.();
    updateLegend?.();
}

function setSubsDefaultOff() {
    if (typeof state === "undefined") return;
    state.subsVisible = false;
    setLayerVisibilityForPrintPack("l-subs", false);
    updateSubsToggleButton?.();
    updateLegend?.();
}

function enforceCleanDefaultMapLayers() {
    setAtlasLayersDefaultOff();
    setSubsDefaultOff();
}

function getMapPrintState() {
    if (!map) return null;
    return {
        center: map.getCenter(),
        zoom: map.getZoom(),
        bearing: map.getBearing(),
        pitch: map.getPitch(),
        satActive: !!state.satActive,
        subsVisible: !!state.subsVisible,
        atlas: typeof atlasV8GridLayerVisibility !== "undefined" ? { ...atlasV8GridLayerVisibility } : {},
        keyCollapsed: $("map_legend")?.classList.contains("key-collapsed") || false,
        toolsCollapsed: $("map_tool_overlay")?.classList.contains("tools-collapsed") || false,
        mapExpanded: document.body.classList.contains("map-expanded")
    };
}

async function restoreMapPrintState(saved) {
    if (!map || !saved) return;

    if (typeof state !== "undefined") {
        state.satActive = saved.satActive;
        state.subsVisible = saved.subsVisible;
    }

    setLayerVisibilityForPrintPack("l-sat", saved.satActive);
    setLayerVisibilityForPrintPack("l-subs", saved.subsVisible);

    if (typeof atlasV8GridLayerVisibility !== "undefined") {
        Object.keys(saved.atlas || {}).forEach(voltageKey => {
            atlasV8GridLayerVisibility[voltageKey] = saved.atlas[voltageKey];
            const layerId = atlasV8GridLayerIds?.[voltageKey];
            if (layerId) setLayerVisibilityForPrintPack(layerId, saved.atlas[voltageKey]);
        });
    }

    const legend = $("map_legend");
    if (legend) legend.classList.toggle("key-collapsed", saved.keyCollapsed);
    const keyBtn = $("btn_key_toggle");
    if (keyBtn) {
        keyBtn.textContent = saved.keyCollapsed ? "KEY OFF" : "KEY ON";
        keyBtn.classList.toggle("active", !saved.keyCollapsed);
    }

    const overlay = $("map_tool_overlay");
    if (overlay) overlay.classList.toggle("tools-collapsed", saved.toolsCollapsed);
    const toolsBtn = $("btn_map_tools_toggle");
    if (toolsBtn) {
        toolsBtn.textContent = saved.toolsCollapsed ? "TOOLS OFF" : "TOOLS ON";
        toolsBtn.classList.toggle("active", !saved.toolsCollapsed);
    }

    document.body.classList.toggle("map-expanded", saved.mapExpanded);
    document.querySelector(".panel-right")?.classList.toggle("map-expanded", saved.mapExpanded);

    map.jumpTo({ center: saved.center, zoom: saved.zoom, bearing: saved.bearing, pitch: saved.pitch });
    updateSubsToggleButton?.();
    updateAtlasV8GridToggleButtons?.();
    updateLegend?.();
    map.resize();
    await sleepForPrintPack(350);
}

function ensurePrintMapPackContainer() {
    let pack = document.getElementById("print_map_pack");
    if (!pack) {
        pack = document.createElement("section");
        pack.id = "print_map_pack";
        pack.className = "print-map-pack";
        document.body.appendChild(pack);
    }
    pack.innerHTML = "";
    return pack;
}

function addPrintMapFigure(pack, title, dataUrl, note, landscape = false) {
    const page = document.createElement("section");
    page.className = landscape ? "print-map-page print-map-page-landscape" : "print-map-page";

    const heading = document.createElement("h2");
    heading.textContent = title;

    const img = document.createElement("img");
    img.src = dataUrl;
    img.alt = title;

    const caption = document.createElement("p");
    caption.textContent = note || "Map figure generated from current GIS SLD sandbox view. Indicative only.";

    page.appendChild(heading);
    page.appendChild(img);
    page.appendChild(caption);
    pack.appendChild(page);
}

async function captureCurrentMapForPrint() {
    if (!map) return "";
    map.resize();
    await sleepForPrintPack(650);
    return map.getCanvas().toDataURL("image/png");
}

function getTopologyBoundsForPrintPack() {
    if (typeof turf === "undefined" || !state?.currentGeoJSON?.features?.length) return null;
    try {
        const bbox = turf.bbox(state.currentGeoJSON);
        if (!bbox || bbox.length !== 4 || bbox.some(v => !Number.isFinite(v))) return null;
        return [[bbox[0], bbox[1]], [bbox[2], bbox[3]]];
    } catch (err) {
        console.warn("Print pack bbox failed", err);
        return null;
    }
}

async function fitContextMapForPrint() {
    const bounds = getTopologyBoundsForPrintPack();
    if (bounds) {
        map.fitBounds(bounds, { padding: 90, duration: 0, maxZoom: 12 });
    } else {
        const currentZoom = map.getZoom();
        map.setZoom(Math.max(currentZoom - 4, 7));
    }
    await sleepForPrintPack(750);
}

async function setSatelliteForPrintPack(active) {
    if (!map) return;
    if (typeof state !== "undefined") state.satActive = !!active;
    setLayerVisibilityForPrintPack("l-sat", !!active);
    const btn = $("btn_basemap");
    if (btn) {
        btn.textContent = active ? "DARK MATTER VIEW" : "SATELLITE VIEW";
        btn.classList.toggle("active", !!active);
    }
    await sleepForPrintPack(500);
}

async function prepareGisSldPrintReport() {
    if (!map) {
        window.print();
        return;
    }

    const btn = $("btn_print_report");
    const oldText = btn ? btn.textContent : "";
    if (btn) btn.textContent = "PREPARING";

    const saved = getMapPrintState();
    const pack = ensurePrintMapPackContainer();

    try {
        document.body.classList.add("preparing-print-pack");
        document.body.classList.remove("map-expanded");
        document.querySelector(".panel-right")?.classList.remove("map-expanded");
        $("map_tool_overlay")?.classList.add("tools-collapsed");
        $("map_legend")?.classList.add("key-collapsed");

        // Page 1 map: current working view, but clean with user selected layers retained.
        map.resize();
        await sleepForPrintPack(600);
        const currentMap = await captureCurrentMapForPrint();
        addPrintMapFigure(pack, "Map Figure 1: Current Project View", currentMap, "Current GIS SLD project view. Interactive controls are removed from print output.");

        // Page 2 map: zoomed out context. Keep current basemap and layer settings.
        await fitContextMapForPrint();
        const contextMap = await captureCurrentMapForPrint();
        addPrintMapFigure(pack, "Map Figure 2: Wider Grid And Route Context", contextMap, "Zoomed out context view showing wider relationship between project, route assumptions and grid geography.");

        // Page 3 map: satellite view, clean and full page.
        await setSatelliteForPrintPack(true);
        await fitContextMapForPrint();
        const satelliteMap = await captureCurrentMapForPrint();
        addPrintMapFigure(pack, "Map Figure 3: Satellite Context View", satelliteMap, "Satellite context view for visual land, route and surrounding area review. Indicative only.", true);

        await restoreMapPrintState(saved);
        document.body.classList.remove("preparing-print-pack");
        if (btn) btn.textContent = oldText || "PRINT";
        window.print();
    } catch (err) {
        console.error("GIS SLD print pack failed", err);
        await restoreMapPrintState(saved);
        document.body.classList.remove("preparing-print-pack");
        if (btn) btn.textContent = oldText || "PRINT";
        window.print();
    }
}

// Clean map defaults after the map and controls have loaded.
// setTimeout(enforceCleanDefaultMapLayers, 1200); // disabled by simple safe print fix