GLOBALGRID2050 / EXPLORE CODE

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

Grid Vicinity

A JavaScript file in the atlas folder of GridAtlas that maps notice, grid substations, the Renewable Energy Planning Database (REPD) register and transformers, using SHA-256.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 534 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. Grid Vicinity geodesy · gridatlas / atlas/modules/202611180026-grid-vicinity.js lines 542–1241

Grid Vicinity

A JavaScript file in the atlas folder of GridAtlas that maps notice, grid substations, the Renewable Energy Planning Database (REPD) register and transformers, using SHA-256.

geodesygridatlas / atlas/modules/202611180026-grid-vicinity.js · lines 542–1241 of 1277 · version 2026-11-18 00:26 (continued from section 533) · Not reached from any entry point (candidate for review) · pattern createScenarioStationStore (shared by 2 files)

What it does
It maps notice, grid substations, the REPD register and transformers. Defines 127 functions or classes, including validCoordinate, radiusKm, normaliseOrigin, parseVicinityIntent, numberText. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, transformers, 400kV, 275kV, 132kV, 66kV.
Inputs & outputs
In: JSON file notice.json; GeoJSON file grid_substations.geojson. Out: interactive map. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
What it achieves
It normalises origin (`normaliseOrigin`), parses vicinity intent (`parseVicinityIntent`) and validates news context base (`validateNewsContextBase`). GridAtlas vicinity : source-built spatial context, no inferred circuits. Its code works with 33 kV, 11 kV and 132 kV. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
Declared Connections (estate URL)
Used by
mentioned in Standalone (comment link)
Produces
validCoordinate, radiusKm, normaliseOrigin, parseVicinityIntent, numberText, validateNewsContextBase, normaliseNewsTopic, newsContextHref, voltageBands, stationRecords, exploreVicinity, vicinityGeoJSON
Defines here
planTrainBuses, binding, voltages, statesAt, order, trainExactBusPath, createEligibleTrainIndex, permitted, same, validLine, createTrainRide, state, notify, collection, point, cancel, schedule, pause, cancelRetry, waitForStyle, ensure, add, position, paint, paintCursor, tick, setPlan, play, seekStop, step
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202611180026-grid-vicinity.js:542-1241 · blob 419758cc50731538e44cf604067a2ef2ecf67950 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/** Keep every reachable arrival bus, not just the cheapest arrival at a station. */
function planTrainBuses(stops, eligible, network, allowed, simulate,other) {
  const graph = eligible?.graph();
  const binding = stop => {
    if (stop.proposed) return null;
    const row = network?.stationBindings?.[stop.id];
    return row?.stationId === stop.id && row.reviewed === true && row.source && typeof row.siteCode === 'string'
      && eligible?.site(row.siteCode)?.code === row.siteCode ? row : null;
  };
  const voltages = stop => (stop.selectedVoltageKv == null ? stop.kv : [stop.selectedVoltageKv])
    .filter(kv => trainVoltageAllowed(kv, allowed,other)).sort((a,b) => a-b);
  const statesAt = stop => {
    const bind = binding(stop), kv = voltages(stop);
    const buses = bind ? graph.nodesOfSite(bind.siteCode).filter(bus => kv.includes(graph.nodeVoltageKv(bus))).sort() : [];
    return buses.length ? buses.map(bus => ({bus, kv: graph.nodeVoltageKv(bus), binding: bind}))
      : kv.map(voltage => ({bus: null, kv: voltage, binding: null}));
  };
  const order = (a,b) => a.cost-b.cost || a.key.localeCompare(b.key,'en');
  let states = statesAt(stops[0]).map(s => ({...s,cost:0,key:s.bus || 'virtual:'+s.kv,choices:[]}));
  for (let i=0;i<stops.length-1;i++) {
    const targets = statesAt(stops[i+1]), candidates = new Map();
    for (const previous of states) for (const target of targets) {
      let choice = null;
      if (previous.bus && target.bus && typeof network?.electricalDistance?.between === 'function') {
        const topology = trainExactBusPath(eligible, network, previous, target);
        if (topology) choice = {topology,source:{from:previous.binding.source,to:target.binding.source},fromBus:previous.bus,toBus:target.bus};
      }
      if (!choice && simulate === true && previous.kv === target.kv) choice = {
        simulated:true,kv:previous.kv,fromBus:previous.bus,toBus:target.bus};
      if (!choice) continue;
      const fingerprint = choice.topology?.path.map(h=>h.from_node+'>'+h.to_node+':'+h.kind).join('|') || 'hypothetical';
      const candidate = {...target,cost:previous.cost+(choice.simulated?1000000:choice.topology.path.length),
        key:previous.key+'|'+(target.bus || 'virtual:'+target.kv)+'|'+fingerprint,choices:[...previous.choices,choice]};
      const key = target.bus || 'virtual:'+target.kv;
      if (!candidates.has(key) || order(candidate,candidates.get(key))<0) candidates.set(key,candidate);
    }
    if (!candidates.size) {
      const prefix = states.sort(order)[0]?.choices || [];
      return [...prefix,...Array(stops.length-1-prefix.length).fill(null)];
    }
    states = [...candidates.values()];
  }
  return states.sort(order)[0]?.choices || Array(stops.length-1).fill(null);
}
function trainExactBusPath(eligible, network, from, to) {
  const graph = eligible.graph(), START='@train-exact-start', END='@train-exact-end';
  // Query aliases avoid electrical-distance's same-SITE zero-hop shortcut.
  // They are not source nodes or graph edges: exact source bus IDs remain unchanged.
  const queryGraph = {...graph,nodesOfSite:code => code===START?[from.bus]:code===END?[to.bus]:graph.nodesOfSite(code)};
  const index = {graph:()=>queryGraph,site:key=>key===START?{code:START,name:from.binding.siteCode}
    :key===END?{code:END,name:to.binding.siteCode}:null};
  const result = network.electricalDistance.between(index,START,END,{voltageKv:from.kv,
    maxHops:Number.isInteger(network.maxHops)&&network.maxHops>0?Math.min(10000,network.maxHops):10000});
  if (result?.schema!=='gridatlas.module.electrical-distance.v1'||result.reached!==true
    ||result.from?.code!==START||result.to?.code!==END||!Array.isArray(result.path)) return null;
  const path=result.path;
  if (path.length ? path[0].from_node!==from.bus||path.at(-1).to_node!==to.bus : from.bus!==to.bus) return null;
  if (!path.every((hop,n)=>graph.has(hop.from_node)&&graph.has(hop.to_node)
    &&(!n||path[n-1].to_node===hop.from_node)
    &&graph.edgesAt(hop.from_node).some(edge=>edge.kind===hop.kind&&edge.row[edge.far]===hop.to_node))) return null;
  return {...result,from:{code:from.binding.siteCode},to:{code:to.binding.siteCode},arrival_node:to.bus,
    path:path.map(hop=>{const rows=graph.edgesAt(hop.from_node).filter(edge=>edge.kind===hop.kind&&edge.row[edge.far]===hop.to_node);
      return {...hop,circuit_id:rows.length===1?rows[0].row.circuit_id||rows[0].row.id||null:null};})};
}
/** A view over the existing graph, never a new graph or a mutation of it. */
function createEligibleTrainIndex(index, {allowedVoltages, allowOtherVoltage=false, allowTransformers}, isReviewedEdge) {
  const graph = index.graph();
  if (graph?.schema !== 'gridatlas.module.network-topology.graph.v1') throw Error('Unsupported network graph.');
  const permitted = node => graph.has(node) && trainVoltageAllowed(graph.nodeVoltageKv(node), allowedVoltages,allowOtherVoltage);
  const view = {...graph,
    has: permitted,
    nodesOfSite: code => graph.nodesOfSite(code).filter(permitted),
    edgesAt: node => !permitted(node) ? [] : graph.edgesAt(node).filter(edge => {
      const far = edge.row[edge.far];
      if (!permitted(far) || typeof isReviewedEdge !== 'function' || isReviewedEdge(edge) !== true) return false;
      const changes = graph.nodeVoltageKv(node) !== graph.nodeVoltageKv(far);
      return edge.kind === 'circuit' ? !changes : edge.kind === 'transformer' && allowTransformers === true;
    })};
  return {graph: () => view, site: key => index.site(key)};
}
function same(a, b) { return a[0] === b[0] && a[1] === b[1]; }
function validLine(line) {
  return Array.isArray(line) && line.length >= 2 && line.length <= 10000 && line.every(at =>
    Array.isArray(at) && at.length === 2 && at.every(Number.isFinite) && Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90);
}

/** Native MapLibre learning cursor. Travel direction is never electrical flow. */
function createTrainRide({map, geodesy, palette = {}, onState = () => {}, reducedMotion = false, readPlanEpoch = null,
  requestFrame = globalThis.requestAnimationFrame?.bind(globalThis),
  cancelFrame = globalThis.cancelAnimationFrame?.bind(globalThis),
  setTimer = globalThis.setTimeout?.bind(globalThis), clearTimer = globalThis.clearTimeout?.bind(globalThis)} = {}) {
  if (!map || typeof geodesy?.distanceKm !== 'function') throw Error('Map and canonical geodesy required.');
  const prefix = 'gridatlas-train-', sources = new Map(), layers = new Map();
  const colour = palette.SUBSTATION_COLOUR || palette.substation || '#5fbdc2'; // Existing SLD substation colour.
  const flowColour = palette.FLOW_COLOUR || '#bfe9ee';
  const customerColour = palette.CUSTOMER_SUBSTATION_COLOUR || '#e0b050'; // Existing SLD_COLOUR.node customer_substation glyph.
  // Same 24 cached dash patterns as the existing SLD neon renderer; no atlas growth per frame.
  const flowPatterns = Array.from({length: 24}, (_, i) => Object.freeze([0.001,
    Math.max(0.001, i / 24 * 1.5), 0.42, Math.max(0.001, 1.5 - i / 24 * 1.5)]));
  let lastDashIndex = -1;
  let alive = true, plan = null, pinStops = [], playing = false, handle = null, legIndex = 0, fraction = 0, epoch = 0, measures = [], prefixStop = 0;
  let lastTime = null, lastPaint = -Infinity, cameraFollow = false, durationMs = 2400, unavailable = null;
  let retryHandle = null, retryCount = 0;
  const state = () => ({schema: 'gridatlas.train.motion.v1', alive, playing, legIndex, fraction,
    stopIndex: fraction === 1 ? legIndex + 1 : legIndex, reducedMotion: !!reducedMotion,
    cameraFollow, unavailable, approvedThroughStop: prefixStop, evidence: plan?.legs[legIndex]?.evidence || null,
    electricalFlow: 'UNKNOWN', simulated: !!plan?.simulated, stops: plan?.stops.length || pinStops.length});
  const notify = () => onState(state());
  const collection = features => ({type: 'FeatureCollection', features});
  const point = (at, properties = {}) => ({type: 'Feature', properties, geometry: {type: 'Point', coordinates: at}});
  function cancel() { epoch++; if (handle !== null) cancelFrame?.(handle); handle = null; lastTime = null; }
  function schedule() { const token = epoch; handle = requestFrame(time => { if (token === epoch) tick(time); }); }
  function pause() { playing = false; cancel(); notify(); return state(); }
  function cancelRetry() { if(retryHandle!==null)clearTimer?.(retryHandle);retryHandle=null;retryCount=0; }
  function waitForStyle() {
    unavailable = retryCount < 12 ? 'Map style is loading; drawing will retry briefly.' : 'Map style is not ready. Retry Draw when the map is ready.';
    if(retryHandle===null && retryCount<12 && typeof setTimer==='function') {
      retryCount++;retryHandle=setTimer(()=>{retryHandle=null;if(alive)paint();},250);
    }
    notify();return false;
  }
  function ensure() {
    if (!alive || !plan && !pinStops.length) return false;
    const sourceIds = ['routes', 'stops', 'cursor'].map(id => prefix + id);
    const layerIds = ['route-gis', 'route-topology', 'route-simulated', 'flow', 'stops', 'proposals', 'cursor'].map(id => prefix + id);
    for (const id of sourceIds) {
      const existing = map.getSource(id);
      if (existing && existing !== sources.get(id)) { unavailable = 'Source ID belongs to another module'; pause(); return false; }
    }
    for (const id of layerIds) {
      const existing = map.getLayer(id);
      if (existing && existing !== layers.get(id)) { unavailable = 'Layer ID belongs to another module'; pause(); return false; }
    }
    // Existing verified sources remain writable while their own setData is
    // pending. Global isStyleLoaded also includes that work; it is not a
    // readiness test for an owned source or for each animation frame.
    if(sourceIds.some(id=>!map.getSource(id)) && map.isStyleLoaded?.()===false) return waitForStyle();
    for (const id of sourceIds) if (!map.getSource(id)) {
      map.addSource(id, {type: 'geojson', data: collection([])}); sources.set(id, map.getSource(id));
    }
    const add = spec => { if (!map.getLayer(spec.id)) { map.addLayer(spec); layers.set(spec.id, map.getLayer(spec.id)); if (spec.id === prefix + 'flow') lastDashIndex = -1; } };
    const line = {type: 'line', source: prefix + 'routes', layout: {'line-cap': 'round', 'line-join': 'round'}};
    add({...line, id: prefix + 'route-gis', filter: ['==', ['get', 'evidence'], 'GIS_REVIEWED'],
      paint: {'line-color': colour, 'line-width': 1.8, 'line-opacity': 0.8}});
    add({...line, id: prefix + 'route-topology', filter: ['==', ['get', 'evidence'], 'TOPOLOGY_ONLY'],
      paint: {'line-color': colour, 'line-width': 1.4, 'line-opacity': 0.65, 'line-dasharray': [5, 2]}});
    add({...line, id: prefix + 'route-simulated', filter: ['==', ['get', 'evidence'], 'SIMULATED'],
      paint: {'line-color': colour, 'line-width': 1.4, 'line-opacity': 0.65, 'line-dasharray': [1, 3]}});
    // Existing l-neon-flow rhythm, confined to our own overlay.
    add({...line, id: prefix + 'flow',filter:['==',['get','evidence'],'GIS_REVIEWED'], paint: {'line-color': flowColour, 'line-width': 1.2,
      'line-opacity': reducedMotion ? 0 : 0.45, 'line-dasharray': [0.2, 3.2]}});
    add({id: prefix + 'stops', type: 'circle', source: prefix + 'stops', filter:['!=',['get','proposed'],true],paint: {
      'circle-color': colour, 'circle-radius': 3, 'circle-opacity': 0.8}});
    add({id:prefix+'proposals',type:'circle',source:prefix+'stops',filter:['==',['get','proposed'],true],paint:{
      'circle-color':customerColour,'circle-radius':5,'circle-stroke-color':'#000c10','circle-stroke-width':1.5,'circle-opacity':0.9}});
    add({id: prefix + 'cursor', type: 'circle', source: prefix + 'cursor', paint: {
      'circle-color': colour, 'circle-radius': 5, 'circle-stroke-color': '#000c10', 'circle-stroke-width': 1.5}});
    cancelRetry();unavailable = null; return true;
  }
  function position() {
    const line = plan?.legs[legIndex]?.coordinates;
    if (!line) return plan?.stops[legIndex]?.at || null;
    if (fraction === 1) return line.at(-1);
    const cumulative = measures[legIndex], wanted = cumulative.at(-1) * fraction;
    let lo = 1, hi = cumulative.length - 1;
    while (lo < hi) { const mid = (lo + hi) >> 1; if (cumulative[mid] < wanted) lo = mid + 1; else hi = mid; }
    const i = lo - 1, span = cumulative[lo] - cumulative[i], t = span ? (wanted - cumulative[i]) / span : 0;
    return [line[i][0] + (line[lo][0] - line[i][0]) * t, line[i][1] + (line[lo][1] - line[i][1]) * t];
  }
  function paint() {
    if(plan && readPlanEpoch && readPlanEpoch()!==plan.planEpoch){clearPlan();return;}
    if (!ensure()) return;
    sources.get(prefix + 'routes').setData(collection((plan?.legs||[]).slice(0,prefixStop).filter(l => l.coordinates).map(l => ({type: 'Feature',
      properties: {evidence: l.evidence, label: l.label}, geometry: {type: 'LineString', coordinates: l.coordinates}}))));
    sources.get(prefix + 'stops').setData(stopData(plan?.stops||pinStops));
    paintCursor();
  }
  function paintCursor() {
    if (!alive || !plan || !sources.has(prefix + 'cursor') || map.getSource(prefix + 'cursor') !== sources.get(prefix + 'cursor')) return;
    const at = position(); sources.get(prefix + 'cursor').setData(collection(at ? [point(at, {meaning: 'User journey heading; electrical flow unknown'})] : []));
    if (cameraFollow && playing && at) map.easeTo?.({center: at, duration: 0});
  }
  function tick(time) {
    handle = null; if (!alive || !playing) return;
    if (readPlanEpoch && readPlanEpoch() !== plan.planEpoch) { clearPlan(); return; }
    if(!sources.has(prefix+'cursor') || map.getSource(prefix+'cursor')!==sources.get(prefix+'cursor')) {pause();return;}
    if (lastTime === null) lastTime = time;
    fraction += Math.max(0, Math.min(250, time - lastTime)) / durationMs; lastTime = time;
    if (fraction >= 1) {
      if (legIndex < plan.legs.length - 1) { legIndex++; fraction = 0; } else { fraction = 1; playing = false; }
    }
    if (time - lastPaint >= 33 || !playing) {
      lastPaint = time; paintCursor();
      const layer = map.getLayer(prefix + 'cursor');
      if (layer === layers.get(prefix + 'cursor')) map.setPaintProperty(prefix + 'cursor', 'circle-radius', 5 + Math.sin(fraction * Math.PI) * 1.5);
      const dashIndex = Math.floor(fraction * 24) % 24;
      if (dashIndex !== lastDashIndex && map.getLayer(prefix + 'flow') === layers.get(prefix + 'flow')) {
        lastDashIndex = dashIndex; map.setPaintProperty(prefix + 'flow', 'line-dasharray', flowPatterns[dashIndex]);
      }
      notify();
    }
    if (playing) schedule();
  }
  function setPlan(next) {
    if (!alive) throw Error('Train ride is destroyed.');
    // Reject stale asynchronous results before clearing or painting any current ride.
    if(readPlanEpoch && next?.planEpoch!==readPlanEpoch())throw Error('Stale journey plan epoch.');
    clearPlan({stops:pinStops});
    if (next?.schema !== 'gridatlas.train.route-plan.v1' || !Array.isArray(next.legs) || !next.legs.length
      || !Array.isArray(next.stops) || next.stops.length !== next.legs.length + 1
      || next.legs.reduce((n, leg) => n + (leg.coordinates?.length || 0), 0) > 20000) throw Error('Invalid or oversized journey plan.');
    // Snapshot input so later UI edits cannot mutate an active ride.
    const copy = JSON.parse(JSON.stringify(next)); plan = copy; pinStops = copy.stops;
    const gap = plan.legs.findIndex(leg => !leg.coordinates || leg.evidence === 'MISSING');
    prefixStop = gap < 0 ? plan.legs.length : gap;
    measures = plan.legs.map(leg => { const cumulative = [0];
      for (let i = 1; i < (leg.coordinates?.length || 0); i++) cumulative.push(cumulative.at(-1) + geodesy.distanceKm(...leg.coordinates[i - 1], ...leg.coordinates[i]));
      return cumulative; });
    legIndex = 0; fraction = 0; paint(); notify(); return state();
  }
  function play(options = {}) {
    if (readPlanEpoch && plan && readPlanEpoch() !== plan.planEpoch) { clearPlan(); return false; }
    if (!alive || !plan?.playable || prefixStop !== plan.legs.length || unavailable) return false;
    cameraFollow = options.cameraFollow === true;
    if (Number.isFinite(options.durationMs)) durationMs = Math.max(500, Math.min(30000, options.durationMs));
    if (reducedMotion) { step(); return false; }
    if (typeof requestFrame !== 'function') return false;
    if (playing) return true;
    if (legIndex === plan.legs.length - 1 && fraction === 1) { legIndex = 0; fraction = 0; }
    playing = true; lastTime = null; schedule(); notify(); return true;
  }
  function seekStop(index) {
    if (readPlanEpoch && plan && readPlanEpoch() !== plan.planEpoch) { clearPlan(); return false; }
    if (!alive || !plan || !Number.isInteger(index) || index < 0 || index > prefixStop || index >= plan.stops.length) return false;
    pause(); legIndex = index === prefixStop && index > 0 ? index - 1 : index;
    fraction = index === prefixStop && index > 0 ? 1 : 0;
    paintCursor(); notify(); return true;
  }
  function step() { const next = state().stopIndex + 1; return next <= prefixStop && seekStop(next); }
  function stopData(stops) { return collection(stops.map((stop,i)=>point(stop.at,{stationId:stop.id||stop.stationId,stopIndex:i,
    proposed:stop.proposed===true,kind:stop.proposed?'customer_substation':'source_substation',label:stop.proposed?'PROPOSED SESSION ONLY':stop.name||''}))); }
  function clearPlan({stops=[]}={}) {
    if (!alive) return false;
    if (!Array.isArray(stops) || stops.length>90 || stops.some(stop=>!Array.isArray(stop.at)||stop.at.length!==2
      ||!stop.at.every(Number.isFinite)||Math.abs(stop.at[0])>180||Math.abs(stop.at[1])>90)) throw Error('Invalid selected station pins.');
    cameraFollow=false;cancelRetry();pause();plan=null;measures=[];prefixStop=0;legIndex=0;fraction=0;
    pinStops=JSON.parse(JSON.stringify(stops.filter(stop=>!stop.invalid)));
    if(ensure()) for(const [suffix,data]of [['routes',collection([])],['cursor',collection([])],['stops',stopData(pinStops)]]) {
      const id=prefix+suffix;if(map.getSource(id)===sources.get(id))sources.get(id).setData(data);
    }
    // Empty selections still clear existing owned layers/sources without adding any.
    if(!pinStops.length)for(const suffix of ['routes','cursor','stops']){const id=prefix+suffix;
      if(sources.has(id)&&map.getSource(id)===sources.get(id))sources.get(id).setData(collection([]));}
    notify();return true;
  }
  function styleReload() { if (!alive) return; cancelRetry();pause(); paint(); }
  function removed() { if (!alive) return; alive = false; playing = false; cancelRetry();cancel(); sources.clear(); layers.clear(); map.off('style.load', styleReload); notify(); }
  function destroy() {
    if (!alive) return; cancelRetry();pause();
    for (const [id, layer] of [...layers].reverse()) if (map.getLayer(id) === layer) map.removeLayer(id);
    for (const [id, source] of sources) if (map.getSource(id) === source) map.removeSource(id);
    sources.clear(); layers.clear(); alive = false;
    map.off('style.load', styleReload); map.off('remove', removed); notify();
  }
  map.on('style.load', styleReload); map.on('remove', removed);
  return Object.freeze({setPlan, clearPlan, play, pause, step, seekStop, destroy, snapshot: state});
}

/** Original fictional teaching networks; no railway geography, names or artwork. */
function trainLearningFixture(kind = 'local') {
  const names = kind === 'express' ? ['Harbour', 'Highland', 'Far Reach']
    : kind === 'branch' ? ['Junction', 'West Branch', 'Junction', 'East Branch']
    : ['Central', 'Interchange', 'Gardens', 'Terminus'];
  const spacing = kind === 'express' ? 2 : 0.04;
  return {schema: 'gridatlas.train.fixture.v1', synthetic: true,
    title: kind === 'express' ? 'Fictional express learning journey'
      : kind === 'branch' ? 'Fictional branch and junction journey' : 'Fictional local and interchange journey',
    stops: names.map((name, i) => ({stationId: 'synthetic-' + name.toLowerCase().replaceAll(' ', '-'),
      id: 'synthetic-' + name.toLowerCase().replaceAll(' ', '-'), stopId: 'visit-' + i, name, kv: 400,
      at: [kind === 'branch' && i === 2 ? -1 : -1 + i * spacing, 52 + (i % 2) * spacing / 2],
      source: 'SYNTHETIC_TEACHING_FIXTURE'})),
    note: 'Original invented example. Lines require the same explicit simulated-journey action; no real electrical or railway connection is asserted.'};
}

return {buildStationIndex,createScenarioStationStore,createItinerary,createPlaceBridge,normaliseJourneyLaw,buildRoutePlan,createTrainRide,trainLearningFixture};
})();
/** Shared native journey UI; all network evidence stays in the route planner. */
function createGreatGridJourney({map, registry, geodesy, parent, readFeatures,onProposedPick=()=>{},onMapView=()=>{},onRideState=()=>{},onStatus=()=>{}}) {
  let index = null, indexedFeatures = null, bridge = null, bridgeResolver = null, plan = null, searchEpoch = 0, destroyed = false;
  const D = document, cleanups = [], stationIndex={get:id=>index?.get(id)||null}, scenarioStore=TrainCore.createScenarioStationStore(), selected = TrainCore.createItinerary({mode:'journey',stationIndex,scenarioStore});
  let demo=null;
  let proposedPicking=false,proposedSource=null,mapRemoved=false,drawnEpoch=null,visible=true,overlayArmed=false,inventoryWaiting=false;
  const proposedLayers=new Map(),proposedSourceId='gridatlas-train-proposed-stations';
  const proposedMarkers=new Map();
  const chosenVoltage = new Map();
  const el = (tag,text,host,attrs={}) => {const e=D.createElement(tag);if(text!=null)e.textContent=text;for(const[k,v]of Object.entries(attrs))e.setAttribute(k,v);host?.appendChild(e);return e;};
  const on = (node,type,fn) => {node.addEventListener(type,fn);if(!node.closest('.train-search-results,.train-stops'))cleanups.push(()=>node.removeEventListener(type,fn));};
  const box=el('fieldset',null,parent,{class:'train-panel'});el('legend','Great Grid Journeys',box);
  el('p','Choose real stations, set your journey law, then draw or play. A travelling light is a learning cursor; it never represents electrical current.',box);
  el('p','Documented routing is unavailable in this build: stations have not been joined to reviewed circuit routes. Existing map lines are context, not routing proof. Explicit SIMULATED drawing is available.',box,{class:'train-routing-status'});
  const modeGroup=el('div',null,box,{class:'vic-actions','aria-label':'Journey mode'});
  const journeyMode=el('button','Journey · 10 stops',modeGroup,{type:'button','aria-pressed':'true'}), vicinityMode=el('button','Vicinity · 90 stops',modeGroup,{type:'button','aria-pressed':'false'});
  const inventory=el('p','Station inventory loading.',box,{class:'train-inventory'});
  const searchForm=el('form',null,box,{class:'train-search'});
  el('label','Station name, source ID, place or postcode',searchForm,{for:'gridatlas-train-query'});
  const query=el('input',null,searchForm,{id:'gridatlas-train-query',type:'search',autocomplete:'off',maxlength:'200',placeholder:'For example: North Hyde or a postcode'});
  const searchActions=el('div',null,searchForm,{class:'vic-actions'});
  const stationSearch=el('button','Find stations',searchActions,{type:'submit'}), placeSearch=el('button','Find place / postcode',searchActions,{type:'button'});
  const role=el('select',null,searchForm,{'aria-label':'Use search choice as'});
  for(const[value,label]of [['start','START'],['waypoint','WAYPOINT'],['finish','FINISH']])el('option',label,role,{value});
  const feedback=el('p','Search the full station inventory, independently of the nearby display limit.',box,{role:'status','aria-live':'polite',class:'train-status'});
  const searchResults=el('ol',null,box,{class:'train-search-results'});
  const ordered=el('ol',null,box,{class:'train-stops','aria-label':'Ordered selected stops'});
  const selectedStatus=el('p','0 / 10 selected stops, including START and FINISH.',box);
  const reset=el('button','Clear selected stops',box,{type:'button'});
  const proposedBox=el('details',null,box,{class:'train-proposed'});el('summary','Proposed customer substation · screening',proposedBox);
  el('p','Session-only FEED concept, not an official station, approved connection, transformer or land right. Golden customer-substation symbol plus Proposed label distinguishes the scenario.',proposedBox);
  const proposedName=el('input',null,proposedBox,{type:'text',value:'Proposed customer substation',maxlength:'80','aria-label':'Proposed customer substation label'});
  const proposedVoltage=el('select',null,proposedBox,{'aria-label':'Proposed customer substation voltage'});el('option','11 kV',proposedVoltage,{value:'11'});el('option','33 kV',proposedVoltage,{value:'33'});
  const propose=el('button','Pin proposed FEED concept',proposedBox,{type:'button','aria-pressed':'false'});
  const proposedList=el('ol',null,proposedBox,{'aria-label':'Session proposed substations'});
  const lawBox=el('details',null,box,{class:'train-law'});lawBox.open=true;el('summary','Journey law',lawBox);
  el('p','The ordered selected stops are required visits. Voltage and evidence rules apply to every traversed edge, not just the endpoints.',lawBox);
  const lawBands=el('div',null,lawBox,{class:'vic-bands'}), voltageInputs=[];
  for(const band of ['11','33','66','132','220','275','400','other','unknown']){const label=el('label',null,lawBands),input=el('input',null,label,{type:'checkbox',value:band});input.checked=true;el('span',band==='other'||band==='unknown'?band:band+' kV',label);voltageInputs.push(input);on(input,'change',applyLawChange);}
  const fallbackLabel=el('label',null,lawBox,{class:'train-check'}),fallback=el('input',null,fallbackLabel,{type:'checkbox'});el('span','Allow my SIMULATED straight-line legs where a reviewed route is missing',fallbackLabel);
  const transformerLabel=el('label',null,lawBox,{class:'train-check'}),transformers=el('input',null,transformerLabel,{type:'checkbox'});el('span','Allow documented, reviewed transformers between allowed voltage levels',transformerLabel);
  const controls=el('div',null,box,{class:'vic-actions train-controls'});
  const draw=el('button','Draw itinerary',controls,{type:'button'}),play=el('button','Play',controls,{type:'button'}),pause=el('button','Pause',controls,{type:'button'}),previous=el('button','Previous stop',controls,{type:'button'}),step=el('button','Step / next stop',controls,{type:'button'});
  const fitJourney=el('button','Fit itinerary on map',controls,{type:'button'});
  el('p','Solid: reviewed GIS route. Long dash: documented topology, schematic. Dotted: SIMULATED user leg. The cursor is a learning heading; electrical flow is unknown.',box,{class:'train-route-legend'});
  const cameraLabel=el('label',null,box,{class:'train-check'}),camera=el('input',null,cameraLabel,{type:'checkbox'});el('span','Follow the learning cursor with the camera',cameraLabel);
  const speedLabel=el('label','Seconds per leg',box),speed=el('input',null,speedLabel,{type:'range',min:'1',max:'20',step:'1',value:'4','aria-label':'Seconds per leg'});
  const progress=el('p','No itinerary drawn.',box,{class:'train-progress',role:'status'}),legs=el('ol',null,box,{class:'train-legs'});
  const demos=el('details',null,box);el('summary','Fictional topology demonstrations',demos);
  el('p','Original interchange, long-leg and branch patterns. Fictional grid-learning diagrams, with no railway dataset, map or logo. Load a pattern, edit its law, and explicitly allow simulation to draw it.',demos);
  for(const[kind,label]of [['interchange','Load interchange demo'],['express','Load express / long-leg demo'],['branch','Load branch demo']]){const b=el('button',label,demos,{type:'button'});on(b,'click',()=>loadDemo(kind));}
  const reduced=globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches===true;
  const ride=TrainCore.createTrainRide({map,geodesy,palette:{SUBSTATION_COLOUR:'#5fbdc2'},reducedMotion:reduced,readPlanEpoch:()=>selected.snapshot().planEpoch,onState:s=>{
    if(destroyed)return;onRideState(s);const caption=s.unavailable||`${s.playing?'Playing':reduced?'Static reduced-motion view':'Paused'} · stop ${Math.min(s.stops,s.stopIndex+1)} / ${s.stops} · ${s.evidence||'no route'} · electrical flow unknown`;
    if(progress.textContent!==caption)progress.textContent=caption;
    pause.disabled=!s.playing;play.setAttribute('aria-pressed',String(s.playing));
  }});
  function say(message){if(feedback.textContent!==message)feedback.textContent=message;onStatus(message);}
  function fullIndex(){const features=readFeatures();if(!Array.isArray(features)||!features.length){const hadIndex=!!index;index=null;indexedFeatures=null;if(hadIndex)invalidate();bridge?.invalidate();bridge=null;inventoryWaiting=true;say('Full substation inventory is not loaded. Use Show physical grid, then search again.');return null;}if(features!==indexedFeatures){const changed=!!indexedFeature  … [line shortened here: 1,143 characters; full line on GitHub]
  function invalidate(){const state=selected.snapshot();ride.clearPlan({stops:visible&&overlayArmed?state.stops.filter(stop=>!stop.invalid):[]});drawnEpoch=null;plan=null;legs.replaceChildren();progress.textContent='Selections or law changed. Draw again to apply them.';}
  function setMode(mode){try{selected.setMode(mode);journeyMode.setAttribute('aria-pressed',String(mode==='journey'));vicinityMode.setAttribute('aria-pressed',String(mode==='vicinity'));invalidate();renderStops();return true;}catch(e){say(e.message+' Your selected stops were kept.');return false;}}
  function add(row){try{const choice=role.value;if(choice==='start')selected.setStart(row);else if(choice==='finish')selected.setFinish(row);else{const count=selected.snapshot().selectedCount;selected.add(row,{index:count>1?count-1:count});}demo=null;overlayArmed=true;role.value=selected.snapshot().selectedCount===1?'finish':'waypoint';invalidate();renderStops();say('Station bound explicitly. The   … [line shortened here: 486 characters; full line on GitHub]
  function renderStops(){const state=selected.snapshot();selectedStatus.textContent=`${state.selectedCount} / ${state.limit} selected stops, including START and FINISH. Intermediate network traversal is not limited by this stop count.`;ordered.replaceChildren();for(const[rowIndex,row]of state.stops.entries()){
    const li=el('li',null,ordered,{'data-train-stop-id':row.stopId});el('strong',`${row.proposed?'Proposed - FEED concept - ':''}${row.invalid?'INVALID VISIT - ':''}${rowIndex===0?'START':rowIndex===state.stops.length-1?'FINISH':'WAYPOINT '+rowIndex} · ${row.name}`,li);el('span',`ID ${row.stationId} · ${row.kv.length?row.kv.join(' / ')+' kV':'voltage unknown'}`,li,{class:'vic-row-meta'});
    if(row.place)el('p',`${row.place.label} → ${row.name} · ${row.place.distanceKm.toFixed(2)} km from resolved ${row.place.provider} point (${row.place.precision||'precision unknown'}). Place coordinate ${row.place.at.join(', ')}; station coordinate ${row.at.join(', ')}.`,li,{class:'train-place-binding'});
    if(!row.kv.includes(chosenVoltage.get(row.stopId)))chosenVoltage.delete(row.stopId);
    const selector=el('select',null,li,{'aria-label':'Journey voltage at '+row.name});el('option','Choose journey voltage',selector,{value:''});for(const kv of row.kv)el('option',kv+' kV',selector,{value:String(kv)});selector.value=String(chosenVoltage.get(row.stopId)??(row.kv.length===1?row.kv[0]:''));on(selector,'change',()=>{selector.value?chosenVoltage.set(row.stopId,Number(selector.value)):ch  … [line shortened here: 447 characters; full line on GitHub]
    const buttons=el('div',null,li,{class:'vic-actions'});for(const[label,action,disabled]of [['Move up',()=>selected.move(rowIndex,rowIndex-1),rowIndex===0],['Move down',()=>selected.move(rowIndex,rowIndex+1),rowIndex===state.stops.length-1],['Remove',()=>selected.remove(rowIndex),false]]){const b=el('button',label,buttons,{type:'button','aria-label':label+' '+row.name});b.disabled=disabled;on(b,  … [line shortened here: 453 characters; full line on GitHub]
  }}
  function showChoices(result,binding){searchResults.replaceChildren();say(`${result.matched} matching stations${result.truncated?'; showing the first 30 — refine your search':''}. ${result.ambiguous?'Choose the intended source ID explicitly.':''}`);for(const row of result.rows){const li=el('li',`${row.name} · ID ${row.stationId} · ${row.kv.join(' / ')||'unknown'} kV${row.distanceKm!=null?' · '+ro  … [line shortened here: 589 characters; full line on GitHub]
  function searchStations(){searchEpoch++;bridge?.invalidate();const idx=fullIndex();if(idx)showChoices(idx.search(query.value,{limit:30}));}
  async function searchPlaces(){const idx=fullIndex();if(!idx)return;const resolve=globalThis.__GRIDATLAS_PLACE_SEARCH__?.resolveLocations;if(typeof resolve!=='function'){say('The existing place resolver is not ready. Station-name and source-ID search remain available.');return;}if(!bridge||bridgeResolver!==resolve){bridge=TrainCore.createPlaceBridge({resolve:label=>resolve(label),index:idx,geodes  … [line shortened here: 1,295 characters; full line on GitHub]
  function law(){return TrainCore.normaliseJourneyLaw({mustVisitStationIds:(demo?.stops||selected.snapshot().stops).map(s=>s.stationId||s.id),allowedVoltageBands:voltageInputs.every(e=>e.checked)?null:voltageInputs.filter(e=>e.checked).map(e=>e.value),fallback:fallback.checked?'user-opted-hypothetical':'documented-only',allowTransformers:transformers.checked});}
  function applyLawChange(){invalidate();try{selected.setLaw(law());invalidate();}catch(e){fallback.checked=selected.snapshot().law.fallback==='user-opted-hypothetical';say(e.message);}}
  function cancelProposedPick(){proposedPicking=false;propose.setAttribute('aria-pressed','false');}
  function paintProposed(){
    if(mapRemoved||destroyed||!visible||!overlayArmed||!map.getStyle?.())return;
    const rows=scenarioStore.snapshot().stations,pointLayer='gridatlas-train-proposed-point';
    const current=map.getSource(proposedSourceId),existing=map.getLayer(pointLayer);
    if(current&&current!==proposedSource||existing&&existing!==proposedLayers.get(pointLayer)){say('A scenario overlay ID is already in use. Existing map objects were preserved.');return;}
    if(!current){map.addSource(proposedSourceId,{type:'geojson',data:{type:'FeatureCollection',features:[]}});proposedSource=map.getSource(proposedSourceId);}
    if(!existing){map.addLayer({id:pointLayer,type:'circle',source:proposedSourceId,paint:{'circle-radius':5,'circle-color':'#e0b050','circle-stroke-color':'#000c10','circle-stroke-width':1.5}});proposedLayers.set(pointLayer,map.getLayer(pointLayer));}
    proposedSource.setData({type:'FeatureCollection',features:rows.map(row=>({type:'Feature',properties:{role:'customer_substation',evidence:'SESSION_ONLY_USER_PROPOSED',label:'Proposed · FEED concept',name:row.name,kv:row.kv[0]},geometry:{type:'Point',coordinates:row.at}}))});
    const keep=new Set(rows.map(row=>row.id));for(const[id,marker]of proposedMarkers)if(!keep.has(id)){marker.remove();proposedMarkers.delete(id);}
    for(const row of rows){let marker=proposedMarkers.get(row.id);if(!marker&&globalThis.maplibregl?.Marker){const label=D.createElement('span');label.className='train-proposed-map-label';label.textContent='Proposed · FEED concept';label.style.cssText='color:#e0b050;background:#020809;padding:2px 4px;border:1px dashed #e0b050;font:11px monospace;pointer-events:none';marker=new globalThis.maplibreg  … [line shortened here: 545 characters; full line on GitHub]
  }
  function clearProposedOverlay(){for(const marker of proposedMarkers.values())marker.remove();proposedMarkers.clear();if(!mapRemoved&&map.getStyle?.()){for(const[id,layer]of proposedLayers)if(map.getLayer(id)===layer)map.removeLayer(id);if(map.getSource(proposedSourceId)===proposedSource&&!(map.getStyle().layers||[]).some(layer=>layer.source===proposedSourceId))map.removeSource(proposedSourceId);  … [line shortened here: 445 characters; full line on GitHub]
  function renderProposed(){proposedList.replaceChildren();for(const row of scenarioStore.snapshot().stations){const li=el('li',null,proposedList);el('strong','Proposed · FEED concept',li);el('p',row.id+' · '+row.at.join(', ')+' · session-only; connection and rights unknown',li);const name=el('input',null,li,{type:'text',value:row.name,maxlength:'80','aria-label':'Edit proposed label '+row.name}),  … [line shortened here: 1,128 characters; full line on GitHub]
  function proposedClick(event){if(!proposedPicking||!event.lngLat)return;cancelProposedPick();try{if(!fallback.checked)throw Error('Explicit SIMULATED fallback is required for a proposed station.');selected.setLaw(law());const count=selected.snapshot();if(role.value==='waypoint'&&count.selectedCount>=count.limit)throw Error('Remove a selected visit before adding another proposed stop.');const row  … [line shortened here: 623 characters; full line on GitHub]
  const proposedRemoved=()=>{mapRemoved=true;cancelProposedPick();};
  map.on('click',proposedClick);map.on('remove',proposedRemoved);map.on('style.load',paintProposed);
  on(propose,'click',()=>{if(!fallback.checked){say('Enable SIMULATED fallback in the journey law before pinning a proposed FEED concept.');return;}proposedPicking=!proposedPicking;propose.setAttribute('aria-pressed',String(proposedPicking));if(proposedPicking){onProposedPick();onMapView();say('Tap one point on the map for your proposed customer substation. It remains a session-only screening conc  … [line shortened here: 411 characters; full line on GitHub]
  function drawPlan(){overlayArmed=true;paintProposed();ride.clearPlan({stops:selected.snapshot().stops.filter(stop=>!stop.invalid)});drawnEpoch=null;plan=null;try{if(!fullIndex()&&!demo)throw Error('The current full station inventory is unavailable.');const currentLaw=law();if(!demo)selected.setLaw(currentLaw);const state=selected.snapshot();if(!demo&&!state.valid)throw Error('A selected proposed  … [line shortened here: 1,464 characters; full line on GitHub]
  function planIsCurrent(){const state=selected.snapshot();if(!demo&&(!state.valid||state.planEpoch!==drawnEpoch)){invalidate();say('The station scenario or law changed. Draw a new valid itinerary before moving the cursor.');return false;}return !!plan;}
  function loadDemo(kind){demo=TrainCore.trainLearningFixture(kind==='interchange'?'local':kind);invalidate();legs.replaceChildren();for(const stop of demo.stops)el('li',stop.name,legs);say(demo.title+'. Fictional demonstration loaded separately; your real selected stops are preserved. Explicitly allow SIMULATED fallback, then draw. No physical route is asserted.');}
  on(searchForm,'submit',e=>{e.preventDefault();searchStations();});on(placeSearch,'click',searchPlaces);on(query,'input',()=>{searchEpoch++;bridge?.invalidate();});on(journeyMode,'click',()=>setMode('journey'));on(vicinityMode,'click',()=>setMode('vicinity'));on(reset,'click',()=>{selected.clear();demo=null;chosenVoltage.clear();invalidate();renderStops();});on(fallback,'change',applyLawChange);o  … [line shortened here: 1,198 characters; full line on GitHub]
  on(fitJourney,'click',()=>{const stops=demo?.stops||selected.snapshot().stops.filter(stop=>!stop.invalid);if(!stops.length){say('Choose located stops first.');return;}const xs=stops.map(stop=>stop.at[0]),ys=stops.map(stop=>stop.at[1]);onMapView();map.fitBounds([[Math.min(...xs),Math.min(...ys)],[Math.max(...xs),Math.max(...ys)]],{padding:{top:140,bottom:120,left:30,right:30},duration:0,maxZoom:1  … [line shortened here: 407 characters; full line on GitHub]
  selected.setLaw(law());fullIndex();renderStops();
  return Object.freeze({element:box,open(){visible=true;},close(){visible=false;overlayArmed=false;cancelProposedPick();ride.clearPlan({stops:[]});plan=null;drawnEpoch=null;clearProposedOverlay();legs.replaceChildren();progress.textContent='Closed. Selected stops are kept; draw again to show them.';},setMode,nextStop:()=>step.click(),previousStop:()=>previous.click(),refreshInventory:fullIndex,pau  … [line shortened here: 1,827 characters; full line on GitHub]
}

const W = window, D = document, NS = W.__GRIDATLAS_MODULES__ = W.__GRIDATLAS_MODULES__ || {};
if (!NS.gridVicinity) {
  let controller = null, timer = null, stopped = false, pendingIntent = null, intentError = null;
  try { pendingIntent = parseVicinityIntent(W.location.search); } catch (error) { intentError = error.message; }
  function createController(map) {
    const geodesy = NS.geodesy;
    if (!geodesy?.distanceKm || !geodesy?.voltagesKv || !geodesy?.representativePoint) throw new Error('Canonical Atlas geodesy is not ready.');
    const host = map.getContainer(), prior = D.getElementById('gridatlas-vicinity');
    if (prior) throw new Error('Vicinity UI already mounted.');
    let alive = true, opened = false, origin = null, radius = 10, picking = false, result = null, records = [], contextSource = 'No loaded substation data', error = null, phase = 'CHOOSE_ORIGIN';
    let source = null, sourceUnavailable = false, selectionEpoch = 0, refreshTimer = null, returning = null, newsBase = null, newsTopic = null, assetContext = null, documentContext = null, assetSignature = null, stationSignature = null, documentSignature = null;
    const categoryElements = new Map();
    const bands = new Set(VOLTAGE_BANDS.map(b => b[0])), listeners = [], groups = [], controls = [], ownedLayers = new Map();
    const SOURCE = 'gridatlas-vicinity-context', LAYERS = ['gridatlas-vicinity-radius', 'gridatlas-vicinity-points', 'gridatlas-vicinity-model'];
    const root = D.createElement('div'); root.id = 'gridatlas-vicinity'; host.appendChild(root);
    const style = D.createElement('style'); style.textContent = VICINITY_CSS; root.appendChild(style);
    function el(tag, text, parent, attrs = {}) { const e = D.createElement(tag); if (text != null) e.textContent = text; for (const [k,v] of Object.entries(attrs)) e.setAttribute(k, v); parent?.appendChild(e); return e; }
    function listen(target, type, fn) { target.addEventListener(type, fn); listeners.push(() => target.removeEventListener(type, fn)); }
    const launch = el('button', 'Great Grid Journeys', root, {type: 'button', class: 'vic-launch', 'aria-expanded': 'false', 'aria-controls': 'gridatlas-vicinity-panel'});
    const panel = el('section', null, root, {id: 'gridatlas-vicinity-panel', class: 'vic-panel', 'aria-label': 'Vicinity familiarisation'}); panel.hidden = true;
    const heading = el('div', null, panel, {class: 'vic-head'}); el('h2', 'Explore the nearby grid', heading);
    const close = el('button', 'Close', heading, {type: 'button', 'aria-label': 'Close vicinity explorer'});
    const compact=el('section',null,root,{class:'vic-train-compact','aria-label':'Journey map controls'});compact.hidden=true;
    const compactActions=el('div',null,compact,{class:'vic-actions'});
    const compactPause=el('button','Pause',compactActions,{type:'button','aria-label':'Pause journey'}),compactPrevious=el('button','Previous',compactActions,{type:'button','aria-label':'Previous journey stop'}),compactNext=el('button','Next',compactActions,{type:'button','aria-label':'Next journey stop'}),compactEdit=el('button','Edit',compactActions,{type:'button','aria-label':'Edit journey'});
    const compactStatus=el('p','Learning cursor; electrical flow unknown.',compact,{role:'status'});
    const mapLegend=el('p','Solid — reviewed GIS. Long dash — topology (schematic). Dotted — SIMULATED. Proposed pin — FEED concept. Electrical flow and rights unknown.',root,{class:'vic-train-map-legend'});mapLegend.hidden=true;
    const originLabel = el('p', '', panel, {class: 'vic-origin'});
    const originPrecision = el('p', 'Source-provided location; coordinate precision not supplied.', panel, {class: 'vic-origin-precision'});
    el('p', 'Spatial vicinity, connectivity unknown. Mapped points and voltage tags are context, not capacity or an electrical path.', panel, {class: 'vic-caption'});
    const actions = el('div', null, panel, {class: 'vic-actions'});
    const centre = el('button', 'Use map centre', actions, {type: 'button'});
    const pick = el('button', 'Pick origin on map', actions, {type: 'button', 'aria-pressed': 'false'});
    const fit = el('button', 'Fit radius', actions, {type: 'button'});
    const physical = el('button', 'Show physical grid', actions, {type: 'button'});
    const news = el('a', 'News context', actions, {target: '_blank', rel: 'noopener noreferrer', 'aria-label': 'Open news topic context in the supplied dated edition'}); news.hidden = true;
    news.style.cssText = 'display:inline-flex;align-items:center;min-height:44px;padding:7px 10px;color:#0ff;background:#061216;border:1px solid #367078';
    const newsCaption = el('p', 'Topic context only; a headline is not an association with this asset.', panel, {class: 'vic-news-caption'}); newsCaption.hidden = true;
    const radial = el('fieldset', null, panel); el('legend', 'Radius in whole kilometres', radial);
    const rangeLabel = el('label', '', radial, {for: 'gridatlas-vicinity-radius-input'});
    const slider = el('input', null, radial, {id: 'gridatlas-vicinity-radius-input', type: 'range', min: '1', max: '50', step: '1', value: '10', 'aria-label': 'Vicinity radius in kilometres'});
    const voltage = el('fieldset', null, panel); el('legend', 'Source voltage tags', voltage);
    const bandBox = el('div', null, voltage, {class: 'vic-bands'});
    for (const [key, name, colour] of VOLTAGE_BANDS) {
      const label = el('label', null, bandBox), input = el('input', null, label, {type: 'checkbox', value: key, 'aria-label': name}); input.checked = true;
      const text = el('span', name, label); text.style.color = colour;
      listen(input, 'change', () => { input.checked ? bands.add(key) : bands.delete(key); refresh(); });
    }
    const status = el('p', '', panel, {class: 'vic-status', role: 'status', 'aria-live': 'polite'});
    const failure = el('p', '', panel, {class: 'vic-error', role: 'alert'}); failure.hidden = true;
    el('p', 'Nearby mapped substations · straight-line distance', panel);
    const list = el('ol', null, panel, {class: 'vic-results'});
    el('p', 'Existing Atlas substation layer; source tags and coverage may be incomplete. Reuses the map’s existing data loader.', panel, {class: 'vic-source'});
    const energy = el('fieldset', null, panel, {class: 'vic-energy-context'}); el('legend', 'Nearby generation and demand context', energy);
    el('p', 'Counts describe loaded source records. Nameplates, IT load, grid requests and actual electricity demand are different quantities.', energy);
    const loadAssets = el('button', 'Load existing asset layers', energy, {type: 'button'});
    const energyRows = el('div', null, energy, {class: 'vic-energy-categories'});
    const documents = el('details', null, panel, {class: 'vic-document-context'}); el('summary', 'Documented works and official notices', documents);
    const documentRows = el('div', null, documents);
    panel.insertBefore(energy, list); panel.insertBefore(documents, list);
    const train = createGreatGridJourney({map,registry:NS,geodesy,parent:panel,onMapView:()=>{panel.hidden=true;compact.hidden=false;const target=train.snapshot().proposedPicking?map.getCanvas():compactEdit;target.focus({preventScroll:true});},onStatus:message=>{if(!compact.hidden&&compactStatus.textContent!==message)compactStatus.textContent=message;},onRideState:state=>{const message=`${state.pl  … [line shortened here: 727 characters; full line on GitHub]
      if(!map.getStyle?.())return null;
      const data=map.getSource('src-subs')?.serialize?.().data;
      return data&&typeof data==='object'&&Array.isArray(data.features)?data.features:null;
    }});
    panel.insertBefore(train.element,originLabel);
    listen(compactPause,'click',()=>train.pause());listen(compactPrevious,'click',()=>train.previousStop());listen(compactNext,'click',()=>train.nextStop());listen(compactEdit,'click',()=>{train.pause();compact.hidden=true;panel.hidden=false;close.focus();});
    for(const type of ['click','dblclick','pointerdown','touchstart'])listen(compact,type,event=>event.stopPropagation());
    listen(compact,'keydown',event=>{if(event.key==='Escape'){event.preventDefault();shut();}});
    // Keep the fixed Close row outside the scrolling content so native scroll-to-focus cannot hide a control behind it.
    const scroller=el('div',null,null,{class:'vic-panel-body'});
    for(const child of [...panel.children])if(child!==heading)scroller.appendChild(child);
    panel.appendChild(scroller);

    function sourceAnchor(parent, title, href) {
      try { const url = new URL(href); if (url.protocol !== 'https:' || url.username || url.password) return; el('a', title, parent, {href: url.href, target: '_blank', rel: 'noopener noreferrer'}); } catch (_) {}
    }
    function rowOrigin(row) {
      return {at: row.at, name: row.name, id: row.originId || row.id, type: row.kind === 'datacentre' ? 'datacentre' : ['generation','storage'].includes(row.kind) ? 'repd' : 'context-asset'};
    }
    function text(node, value) { if (node.textContent !== value) node.textContent = value; }
    function renderAssetContext() {
      assetContext = collectAssetContext({map, registry: NS, origin, radiusKm: radius, geodesy, limit: 40});
      const originRow = assetContext.categories.flatMap(category => category.rows).find(row => (row.originId || row.id) === origin.id && row.at.every((v,i) => v === origin.at[i]));
      text(originPrecision, ['map-centre','map-point'].includes(origin.type) ? 'User-chosen map point; no facility identity was inferred.'
        : originRow?.approximateLocation ? 'Source-provided location is approximate' + (originRow.precision ? ': ' + originRow.precision.replace(/_/g,' ').toLowerCase() : '') + '.'
        : originRow?.precision ? 'Source location tag: ' + originRow.precision.replace(/_/g,' ').toLowerCase() + '. Facility position has not been independently verified.'
        : 'Source-provided location; coordinate precision not supplied. A stable ID and coordinates alone do not verify a facility location.');
      const signature = JSON.stringify(assetContext);
      if (signature === assetSignature) return;
      assetSignature = signature;
      const scroll = scroller.scrollTop;
      for (const category of assetContext.categories) {
        let view = categoryElements.get(category.id);
        if (!view) {
          const section = el('details', null, energyRows, {'data-vicinity-category': category.id});
          view = {section, heading: el('summary','',section), source: el('p','',section), hint: el('p','',section), rows: el('ol',null,section), records: new Map()};
          categoryElements.set(category.id, view);
        }
        text(view.heading, category.availability === 'LOADED' ? `${category.label}: ${category.count} within ${radius} km · ${category.loadedRecords} loaded records` : `${category.label}: not loaded; nearby count unknown`);
        text(view.source, `${category.source || 'Existing Atlas layer'}${category.truncated ? ' · showing nearest 40; narrow the radius for more detail.' : ''}`);
        text(view.hint, 'Use Load existing asset layers to request the map’s existing data.'); view.hint.hidden = category.availability === 'LOADED';
        const retained = new Set();
        for (const [index,row] of category.rows.entries()) {
          // A source-row index is a DOM cache key only; it never becomes an asset identity.
          const key = row.source + '|' + (row.originId || row.id || 'missing-source-id:' + row.sourceRow);
          retained.add(key);
          let entry = view.records.get(key);
          if (!entry) {
            const item = el('li',null,null,{'data-vicinity-asset-id':row.originId || row.id || ''});
            entry = {item, title: el('span','',item), meta: el('span','',item,{class:'vic-row-meta'}), row};
            const buttons = el('div',null,item,{class:'vic-actions'});
            entry.recenter = el('button','Use as origin',buttons,{type:'button'}); entry.add = el('button','Find stations nearby',buttons,{type:'button'});
            entry.recenter.addEventListener('click',()=>setOrigin(rowOrigin(entry.row))); entry.add.addEventListener('click',()=>train.nearContext(entry.row));
            view.records.set(key,entry);
          }
          entry.row = row; text(entry.title,row.name);
          entry.recenter.setAttribute('aria-label','Use '+row.name+' as origin'); entry.add.setAttribute('aria-label','Find stations near '+row.name);
          const facts = [`${row.km.toFixed(2)} km straight-line`, row.status, row.technology].filter(Boolean);
          const basis = row.capacityBasis === 'REGISTER_STATED_POWER_BASIS_NOT_DECLARED' ? 'register power; basis not supplied' : row.capacityBasis === 'SOURCE_STATED_POWER_NOT_CURRENT_OUTPUT' ? 'source-stated power, not current output' : row.capacityBasis || 'source-stated basis not supplied';
          if (row.capacityMw != null) facts.push(`${row.capacityMw} MW (${basis})`);
          if (row.metrics?.itLoadMw != null) facts.push(`${row.metrics.itLoadMw} MW IT load`);
          if (row.metrics?.gridConnectionMw != null) facts.push(`${row.metrics.gridConnectionMw} MW grid-connection statement`);
          if (row.metrics?.unclassifiedMw != null) facts.push(`${row.metrics.unclassifiedMw} MW (basis unclassified)`);
          if (row.kind === 'datacentre' || row.kind === 'demand-context') facts.push('Actual electricity demand unknown');
          if (row.kind === 'storage') facts.push('Storage energy (MWh) unknown');
          if (row.approximateLocation) facts.push('Approximate source location' + (row.precision ? ': ' + row.precision.replace(/_/g,' ').toLowerCase() : ''));
          else facts.push(row.precision ? 'Source location tag: ' + row.precision.replace(/_/g,' ').toLowerCase() : 'Coordinate precision not supplied');
          text(entry.meta,facts.join(' · '));
          if (view.rows.children[index] !== entry.item) view.rows.insertBefore(entry.item,view.rows.children[index] || null);
        }
        for (const [key,entry] of view.records) if (!retained.has(key)) { entry.item.remove(); view.records.delete(key); }
      }
      scroller.scrollTop = scroll;
    }
    function renderDocumentContext() {
      documentContext = documentContextFor(origin, {declaredConnections: NS.declaredConnections});
      const signature = JSON.stringify(documentContext); if (signature === documentSignature) return; documentSignature = signature;
      documentRows.replaceChildren();
      el('p', documentContext.matchedRecords?.length ? 'Existing published works context; source citations have not been revalidated in this release.' : 'No exact documentary works context is available for this asset.', documentRows);
      for (const row of (documentContext.matchedRecords || []).slice(0,10)) {
        const box = el('div', null, documentRows); el('strong', row.title || 'Existing source declaration', box);
        el('p', row.statement || '', box); el('p', 'Existing published declaration; not independently revalidated.', box); sourceAnchor(box, 'Source record', row.sourceUrl);
      }
      for (const row of (documentContext.unassociatedNotices || []).slice(0,5)) {
        const box = el('div', null, documentRows); el('strong', row.title || 'Unassociated official notice', box);
        el('p', row.statement || 'No verified association to the selected asset.', box); sourceAnchor(box, 'Official notice context', row.sourceUrl);
      }
      for (const text of documentContext.limitations || []) el('p', String(text), documentRows);
    }

    function readRecords() {
      let features = [];
      try {
        const data = map.getSource('src-subs')?.serialize?.().data;
        if (data?.type === 'FeatureCollection' && Array.isArray(data.features) && data.features.length) {
          contextSource = 'Existing loaded Atlas substation GeoJSON'; return stationRecords(data.features, geodesy);
        }
      } catch (_) {}
      try { if (map.getSource('src-subs')) features = map.querySourceFeatures('src-subs') || []; } catch (_) {}
      if (features.length) { contextSource = 'Loaded viewport subset of Atlas substations; use Fit radius to load this view'; return stationRecords(features, geodesy); }
      const loaded = W.__GRIDATLAS_NEON_LINKS__?.substations || W.__GRIDATLAS_SUBSTATIONS__ || [];
      if (loaded.length) {
        contextSource = 'Loaded Atlas ≥33 kV screening subset; lower voltages are not included';
        return stationRecords(loaded.map(row => ({type: 'Feature', id: row.id ?? undefined, geometry: {type: 'Point', coordinates: row.at},
          properties: {name: row.name, operator: row.operator, kv: (row.kv || []).join(';'), source: row.source || 'Existing Atlas screening subset'}})), geodesy);
      }
      contextSource = 'Substation layer is not loaded yet'; return [];
    }
    function draw() {
      if (!opened || !result || !alive) return;
      try {
        let current = map.getSource(SOURCE);
        if (current && current !== source) { sourceUnavailable = true; return; }
        for (const id of LAYERS) {
          const existing = map.getLayer(id);
          if (existing && existing !== ownedLayers.get(id)) { sourceUnavailable = true; showError('A map layer ID is already in use. Results remain available; existing layers were preserved.'); return; }
        }
        if (!current) { map.addSource(SOURCE, {type: 'geojson', data: {type: 'FeatureCollection', features: []}}); source = map.getSource(SOURCE); }
        sourceUnavailable = false;
        const specs = [
          {id: LAYERS[0], type: 'line', source: SOURCE, filter: ['==', ['get', 'kind'], 'radius'], paint: {'line-color': '#0ff', 'line-width': 1.5, 'line-dasharray': [3,3], 'line-opacity': 0.8}},
          {id: LAYERS[1], type: 'circle', source: SOURCE, filter: ['in', ['get', 'kind'], ['literal', ['origin','substation']]], paint: {'circle-color': ['case', ['==', ['get', 'kind'], 'origin'], '#ff4fd8', ['get', 'colour']], 'circle-radius': ['case', ['==', ['get', 'kind'], 'origin'], 8, 5], 'circle-stroke-color': '#020809', 'circle-stroke-width': 1.5}},
          {id: LAYERS[2], type: 'line', source: SOURCE, filter: ['==', ['get', 'kind'], 'user-model'], paint: {'line-color': '#ff4fd8', 'line-width': 3, 'line-dasharray': [2,3]}}
        ];
        for (const spec of specs) if (!map.getLayer(spec.id)) { map.addLayer(spec); ownedLayers.set(spec.id, map.getLayer(spec.id)); }
        const data = vicinityGeoJSON(result, geodesy);
        source.setData(data);
      } catch (e) { sourceUnavailable = true; failure.textContent = 'Map overlay not ready. Results remain available below.'; failure.hidden = false; }
    }
    function removeMap(mapRemoved = false) {
      if (!source || mapRemoved) { source = null; ownedLayers.clear(); return; }
      try {
        if (map.getSource(SOURCE) === source) {
          for (const id of [...LAYERS].reverse()) if (map.getLayer(id) && map.getLayer(id) === ownedLayers.get(id)) map.removeLayer(id);
          const foreignDependency = (map.getStyle()?.layers || []).some(layer => layer.source === SOURCE);
          if (!foreignDependency && map.getSource(SOURCE) === source) map.removeSource(SOURCE);
        }
      } catch (_) {}
      source = null; ownedLayers.clear();
    }
    function showError(message) { error = message; failure.textContent = message; failure.hidden = !message; }
    function clearNews() { newsBase = null; newsTopic = null; news.removeAttribute('href'); news.hidden = newsCaption.hidden = true; }
    function clearSelectedContext() { origin = null; result = null; assetContext = null; documentContext = null; assetSignature = stationSignature = documentSignature = null; categoryElements.clear(); list.replaceChildren(); energyRows.replaceChildren(); documentRows.replaceChildren(); news.hidden = newsCaption.hidden = true; removeMap(); }
    function addStation(row) { train.addSourceStation(row); }
    function refresh() {
      if (!alive || !opened) return;
      if (!origin) { rangeLabel.textContent = `${radius} km radius`; slider.value = String(radius); train.refreshInventory(); return; }
      try {
        records = readRecords(); result = exploreVicinity({origin, radius, records, bands, geodesy});
        originLabel.textContent = `Origin: ${origin.name}${origin.id ? ' · source ID ' + origin.id : ''}`;
        if (newsBase) { news.href = newsContextHref(newsBase, origin, newsTopic); news.hidden = newsCaption.hidden = false; }
        rangeLabel.textContent = `${radius} km radius`; slider.value = String(radius);
        status.textContent = `${result.matching} matching mapped stations within ${radius} km · ${result.loadedRecords} loaded records. ${result.truncated ? 'Showing nearest 200. ' : ''}${contextSource}.`;
        const nextStationSignature = JSON.stringify(result);
        if (nextStationSignature !== stationSignature) {
          stationSignature = nextStationSignature; list.replaceChildren();
          for (const row of result.shown) {
          const item = el('li', row.name, list); el('span', `${row.km.toFixed(2)} km · ${row.kv.length ? row.kv.join(' / ') + ' kV' : 'Voltage not stated'}${row.operator ? ' · ' + row.operator : ''}`, item, {class: 'vic-row-meta'});
          const buttons = el('div', null, item, {class: 'vic-actions'});
          const recenter = el('button', 'Use as origin', buttons, {type: 'button', 'aria-label': 'Use ' + row.name + ' as origin'});
          const add = el('button', 'Add to my model', buttons, {type: 'button', 'aria-label': 'Add ' + row.name + ' to my model'});
          recenter.addEventListener('click', () => setOrigin({at: row.at, name: row.name, id: row.id, type: 'substation'}));
          add.addEventListener('click', () => addStation(row));
          }
        }
        renderAssetContext(); renderDocumentContext(); draw(); train.refreshInventory();
      } catch (e) { showError(e.message); }
    }
    function setOrigin(next) {
      train.cancelProposedPick();
      try { const validated = normaliseOrigin(next); origin = validated; phase = 'READY'; selectionEpoch++; picking = false; pick.setAttribute('aria-pressed', 'false'); pick.textContent = 'Pick origin on map'; showError(null); refresh(); return true; }
      catch (e) { clearSelectedContext(); phase = 'REFUSED'; originLabel.textContent = 'Origin was not applied.'; showError(e.message); return false; }
    }
    function mapCentre() { const c = map.getCenter(); return {at: [c.lng, c.lat], type: 'map-centre', id: null, name: 'Chosen map centre'}; }
    function fitRadius() {
      if (!result) return;
      const points = vicinityGeoJSON(result, geodesy).features[0].geometry.coordinates;
      const lngs = points.map(p => p[0]), lats = points.map(p => p[1]);
      map.fitBounds([[Math.min(...lngs), Math.min(...lats)], [Math.max(...lngs), Math.max(...lats)]], {padding: 32, duration: 0});
    }
    function installControls() {
      for (const host of [D.getElementById('scada-ui-container'), D.getElementById('fs-curtain-keys'), D.querySelector('#gridatlas-menu-bar-panel-4 .gm-panel-body')]) {
        if (!host || groups.some(g => g.parentNode === host)) continue;
        if (host.id === 'scada-ui-container' && !host.querySelector('input[data-layer-id]')) continue;
        if (host.id === 'fs-curtain-keys' && !host.querySelector('input[data-layer-id]')) continue;
        if (host.closest?.('#gridatlas-menu-bar-panel-4') && !NS.menuBar?.installed) continue;
        const group = el('div', null, host, {class: 'key-group', 'data-vicinity-group': 'true'}); group.style.gridColumn = '1/-1'; el('div', 'Vicinity familiarisation', group, {class: 'key-title'});
        const button = el('button', 'Explore nearby grid · 1–50 km', group, {type: 'button', class: 'map-ctrl-btn', 'aria-expanded': String(opened), 'aria-controls': panel.id});
        button.style.minHeight = '44px'; listen(button, 'click', event => { event.stopPropagation(); NS.menuBar?.closeAll?.(); open({mode:'vicinity'}, button); });
        const journeyButton=el('button','Great Grid Journeys',group,{type:'button',class:'map-ctrl-btn','aria-controls':panel.id});journeyButton.style.minHeight='44px';listen(journeyButton,'click',event=>{event.stopPropagation();NS.menuBar?.closeAll?.();open({mode:'journey'},journeyButton);});
        groups.push(group); controls.push(button);
      }
    }
    function open(options = {}, invoker = null) {
      if (!alive) return false;
      returning = invoker || (D.activeElement && D.activeElement !== D.body && D.activeElement !== D.documentElement ? D.activeElement : launch); opened = true; panel.hidden = false; compact.hidden=true; launch.setAttribute('aria-expanded', 'true'); for (const b of controls) b.setAttribute('aria-expanded', 'true');
      try {
        train.open();if(!train.setMode(options.mode||'vicinity')) {showError('Selected stops exceed the requested mode. Remove stops explicitly before changing mode.');close.focus();return false;}
        if (options.error) { clearSelectedContext(); phase = 'REFUSED'; originLabel.textContent = 'Journey link was not applied. Choose an origin to explore.'; status.textContent = ''; showError(options.error); close.focus(); return false; }
        let newsError = options.newsContextError || null;
        if (newsError) clearNews();
        else if (options.newsContextUrl !== undefined) {
          try { const base = validateNewsContextBase(options.newsContextUrl), topic = normaliseNewsTopic(options.newsTopic, options.origin); newsBase = base; newsTopic = topic; }
          catch (e) { clearNews(); newsError = 'News context link was not applied: ' + e.message; }
        }
        radius = radiusKm(options.radiusKm ?? radius);
        if (options.manual || !options.origin && !origin) {
          clearSelectedContext(); phase = 'CHOOSE_ORIGIN'; picking = false; pick.setAttribute('aria-pressed','false'); pick.textContent = 'Pick origin on map';
          originLabel.textContent = 'Choose an origin to begin.'; originPrecision.textContent = 'Use map centre or pick a point; no location is chosen automatically.';
          status.textContent = 'Choose a location, then explore the grid within your selected radius.'; refresh(); showError(newsError ? newsError + ' Choose a location to continue grid exploration.' : null); close.focus(); return true;
        }
        if (!setOrigin(options.origin || origin)) return false;
        try { W.__GRIDATLAS_NEON_LINKS__?.enableSubstationLayer?.(); } catch (_) {}
        refresh(); if (newsError) showError(newsError + ' Grid exploration continues.'); close.focus(); return true;
      } catch (e) { clearSelectedContext(); phase = 'REFUSED'; originLabel.textContent = 'Journey request was not applied. Choose a valid origin and radius.'; showError(e.message); close.focus(); return false; }
    }
    function shut() {
      if (!alive) return;
      opened = false; picking = false; panel.hidden = true; compact.hidden=true;mapLegend.hidden=true; launch.setAttribute('aria-expanded', 'false'); for (const b of controls) b.setAttribute('aria-expanded', 'false');
      train.close(); removeMap(); const candidate = returning?.isConnected && returning.getClientRects().length ? returning : D.getElementById('gridatlas-menu-bar-title-4') || launch; candidate.focus();
    }
    listen(launch, 'click', () => { opened ? shut() : open({mode:'journey'}, launch); }); listen(close, 'click', shut);
    listen(centre, 'click', () => setOrigin(mapCentre())); listen(fit, 'click', fitRadius);
    listen(loadAssets, 'click', event => {
      event.stopPropagation();
      const 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 boxes = ids.map(id => D.querySelector(`#scada-ui-container input[data-layer-id="${id}"]`)).filter(Boolean);
      for (const box of boxes) if (!box.checked) box.click();
      NS.ukOfftakers?.setOn?.(true); refresh();
    });
    listen(physical, 'click', event => {
      event.stopPropagation();
      const boxes = ['400','275','220','132','66','subs'].map(id => D.querySelector(`#scada-ui-container input[data-layer-id="${id}"]`)).filter(Boolean);
      if (!boxes.length) { showError('Physical grid controls are loading. Try again when the map controls appear.'); return; }
      for (const box of boxes) if (!box.checked) box.click();
      showError(null); status.textContent = 'Existing physical grid layers switched on. Source-mapped corridors are context; crossings and proximity do not establish a connection.';
      fitRadius();
    });
    listen(pick, 'click', () => { train.cancelProposedPick(); picking = !picking; pick.setAttribute('aria-pressed', String(picking)); pick.textContent = picking ? 'Tap a point on the map' : 'Pick origin on map'; });
    listen(slider, 'input', () => { try { radius = radiusKm(slider.value); showError(null); refresh(); } catch (e) { showError(e.message); } });
    listen(panel, 'keydown', event => { if (event.key === 'Escape') { event.preventDefault(); shut(); } });
    for (const type of ['click','dblclick','pointerdown','touchstart']) listen(panel, type, event => event.stopPropagation());
    const clicked = event => { if (opened && picking && event.lngLat) setOrigin({at: [event.lngLat.lng,event.lngLat.lat], name: 'Chosen map point', type: 'map-point', id: null}); };
    const sourced = event => { if (opened && (!event || ['src-subs','src-repd','gridatlas-offtakers'].includes(event.sourceId))) { clearTimeout(refreshTimer); refreshTimer = setTimeout(refresh, 100); } };
    const styled = () => { if (!map.getSource(SOURCE)) source = null; if (opened) refresh(); };
    const removed = () => destroy(true);
    map.on('click', clicked); map.on('sourcedata', sourced); map.on('style.load', styled); map.on('remove', removed);
    const onIntent = event => open(event.detail || {}); listen(W, 'gridatlas:vicinity-open', onIntent);
    const onCard = event => { if (event.detail?.origin && opened && !train.snapshot().proposedPicking) setOrigin(event.detail.origin); }; listen(W, 'gridatlas:card-open', onCard);
    const observer = new MutationObserver(installControls); observer.observe(D.documentElement, {childList: true, subtree: true}); installControls();
    function destroy(mapRemoved = false) {
      if (!alive) return; alive = false; clearTimeout(refreshTimer); observer.disconnect(); listeners.forEach(off => off());