In this section
- Route Plan render · gridatlas / tools/train/src/route-plan.mjs lines 1–165
- Scenario Stations transform · gridatlas / tools/train/src/scenario-stations.mjs lines 1–9
- Station Index transform · gridatlas / tools/train/src/station-index.mjs lines 1–57
- Train Motion render · gridatlas / tools/train/src/train-motion.mjs lines 1–181
- Train Motion Test test · gridatlas / tools/train/train-motion.test.mjs lines 1–122
- UI render · gridatlas / tools/train/ui.js lines 1–100
Route Plan
A JavaScript module in the train folder of GridAtlas that creates eligible train index (`createEligibleTrainIndex`) (units: kV), covering cables.
rendergridatlas / tools/train/src/route-plan.mjs · lines 1–165 of 165 · pattern createEligibleTrainIndex (shared by 2 files)
- What it does
- It lists and searches cables. Defines 12 functions or classes, including buildRoutePlan, trainVoltageAllowed, planTrainBuses, binding, voltages.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: cables.
- Downstream impact
- Used directly by 2 files: Route Plan Test (gridatlas); Train Motion Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It creates eligible train index (`createEligibleTrainIndex`) and is built from the train voltage allowed helper (`trainVoltageAllowed`) and the plan train buses helper (`planTrainBuses`). Ordered user itinerary; proximity never establishes electrical connectivity.
- Why it matters
- Checked by 2 tests, including Route Plan Test.
- Application
- gridatlas · tools/train/src · JavaScript module
- Uses
- none found
- Used by
- imported by Route Plan Test (import), imported by Train Motion Test (import)
- Produces
- buildRoutePlan, createEligibleTrainIndex
- Defines here
- buildRoutePlan, trainVoltageAllowed, planTrainBuses, binding, voltages, statesAt, order, trainExactBusPath, createEligibleTrainIndex, permitted, same, validLine
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/train/src/route-plan.mjs:1-165 · blob 29870a71af8d6cb7132ce3cacf1aae5edd3e72ef · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
/** Ordered user itinerary; proximity never establishes electrical connectivity. */
export function buildRoutePlan({stops, stationIndex = null, scenarioStore = null, planEpoch = null, synthetic = false, geodesy, allowSimulated = false, network = null, rules = {}, law = null} = {}) {
if (!Array.isArray(stops) || stops.length < 2 || stops.length > 90) throw Error('Choose 2–90 station stops.');
if (typeof geodesy?.distanceKm !== 'function') throw Error('Canonical geodesy is required.');
const ids = new Set();
const selected = stops.map(stop => {
const id = stop.stationId || stop.id;
if (typeof id !== 'string' || !id) throw Error('Each stop needs a stable station identity.');
if (stop.id != null && stop.id !== id) throw Error('Conflicting station identity.');
const canonical = stationIndex?.get(id);
const proposed = !canonical && law?.fallback === 'user-opted-hypothetical' ? scenarioStore?.get(id) : null;
if (proposed && (proposed.proposed !== true || proposed.source !== 'SESSION_ONLY_USER_PROPOSED'
|| !id.startsWith('scenario:') || proposed.kv.length !== 1 || ![11,33].includes(proposed.kv[0]))) throw Error('Invalid session-owned proposal.');
const owned = canonical || proposed;
if (stop.invalid || !synthetic && (!owned || !same(owned.at, stop.at))) throw Error('Choose an existing canonical station from the station index or an opted-in current session proposal.');
if (synthetic && !String(stop.source).startsWith('SYNTHETIC')) throw Error('Fictional stops need an explicit synthetic source.');
const stopId = stop.stopId || 'visit-' + ids.size;
if (ids.has(stopId)) throw Error('Each visit needs a distinct stop identity.');
ids.add(stopId);
if (!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('A station stop is unlocated.');
const trusted = owned || stop;
const kv = (Array.isArray(trusted.kv) ? trusted.kv : [trusted.kv]).filter(kv => Number.isFinite(kv) && kv > 0);
if (stop.selectedVoltageKv != null && !kv.includes(stop.selectedVoltageKv)) throw Error('Selected journey voltage must belong to the canonical station.');
return {...trusted, ...(stop.place ? {place: stop.place} : {}), id, stationId: id, stopId, at: [...trusted.at],
kv, ...(stop.selectedVoltageKv != null ? {selectedVoltageKv: stop.selectedVoltageKv} : {})};
});
if (law) {
rules = {...rules, allowedVoltages: law.allowedVoltageBands == null ? null : law.allowedVoltageBands.filter(v => /^\d+$/.test(String(v))).map(Number),
allowOtherVoltage: law.allowedVoltageBands?.includes('other') === true, allowTransformers: law.allowTransformers !== false};
allowSimulated = law.fallback === 'user-opted-hypothetical';
let at = 0;
for (const id of law.mustVisitStationIds || []) {
while (at < selected.length && selected[at].id !== id) at++;
if (at === selected.length) throw Error('Required stations must appear in their declared order.');
at++;
}
}
const allowedVoltages = rules.allowedVoltages === undefined ? null : rules.allowedVoltages;
if (allowedVoltages !== null && (!Array.isArray(allowedVoltages) || allowedVoltages.some(kv => !Number.isFinite(kv) || kv <= 0))) throw Error('Choose valid voltage levels.');
const eligible = network?.index && createEligibleTrainIndex(network.index,
{allowedVoltages, allowOtherVoltage:rules.allowOtherVoltage===true, allowTransformers: rules.allowTransformers === true}, network.isReviewedEdge);
const sequence = planTrainBuses(selected, eligible, network, allowedVoltages, allowSimulated,rules.allowOtherVoltage===true);
const legs = selected.slice(1).map((to, i) => {
const from = selected[i];
const choice = sequence[i];
let evidence = choice?.topology ? 'TOPOLOGY_ONLY' : choice?.simulated ? 'SIMULATED' : 'MISSING';
let coordinates = choice ? [[...from.at], [...to.at]] : null;
const topology = choice?.topology || null, source = choice?.source || null;
if (topology) {
const joined = topology.path.map(hop => {
const id = hop.circuit_id, join = id && network.geometryByCircuit?.[id];
return join?.reviewed === true && join.source && join.circuitId === id
&& join.fromNode === hop.from_node && join.toNode === hop.to_node
&& join.geometry?.type === 'LineString' && validLine(join.geometry.coordinates)
? join.geometry.coordinates.map(at => [...at]) : null;
});
if (joined.length && joined.every(Boolean) && joined.every((line, n) => !n || same(line[0], joined[n - 1].at(-1)))) {
evidence = 'GIS_REVIEWED'; coordinates = joined.flatMap((line, n) => n ? line.slice(1) : line);
}
}
const km = coordinates ? coordinates.slice(1).reduce((sum, at, n) => sum
+ geodesy.distanceKm(...coordinates[n], ...at), 0) : null;
if (km !== null && (!Number.isFinite(km) || km < 0)) throw Error('Invalid route distance.');
return {id: 'leg-' + i, index: i, fromId: from.id, toId: to.id, evidence, coordinates, km,
topology, source, simulationVoltageKv: choice?.simulated ? choice.kv : null, fromBus: choice?.fromBus || null, toBus: choice?.toBus || null,
electricalTopology: topology ? 'PUBLISHED_REVIEWED_PATH' : 'UNKNOWN',
geometry: evidence === 'GIS_REVIEWED' ? 'REVIEWED_SOURCE_GIS' : coordinates ? 'SCHEMATIC' : 'UNKNOWN',
surveyConstructability: 'UNKNOWN', accessStatus: 'UNKNOWN', direction: 'USER_JOURNEY_HEADING_ONLY', electricalFlow: 'UNKNOWN',
label: evidence === 'SIMULATED' ? 'User-assumed simulated leg; not a cable route'
: evidence === 'TOPOLOGY_ONLY' ? 'Published topology; schematic line, not a cable route'
: evidence === 'GIS_REVIEWED' ? 'Reviewed circuit identity and source GIS geometry'
: 'No reviewed route for this leg'};
});
return {schema: 'gridatlas.train.route-plan.v1', planEpoch, rules: {allowedVoltages: allowedVoltages === null ? null : [...allowedVoltages], allowOtherVoltage:rules.allowOtherVoltage===true, allowTransformers: rules.allowTransformers === true}, stops: selected, legs,
totalKm: legs.every(leg => leg.km !== null) ? legs.reduce((sum, leg) => sum + leg.km, 0) : null,
synthetic: !!synthetic, playable: legs.every(leg => leg.coordinates !== null), simulated: legs.some(leg => leg.evidence === 'SIMULATED')};
}
function trainVoltageAllowed(kv, allowed,other=false) { return Number.isFinite(kv) && kv > 0 && (allowed === null || allowed.includes(kv)
||other&&![400,275,220,132,66,33,11].includes(kv)); }
/** 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. */
export 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);
}Scenario Stations
A JavaScript module in the train folder of GridAtlas that creates scenario station store (`createScenarioStationStore`) (units: kV).
transformgridatlas / tools/train/src/scenario-stations.mjs · lines 1–9 of 9 · pattern createScenarioStationStore (shared by 2 files)
- What it does
- It calculates its inputs. Defines createScenarioStationStore, clone.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
- Downstream impact
- Used directly by 1 file: Route Plan Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It creates scenario station store (`createScenarioStationStore`) and is built from the clone step (`clone`). Session-owned drawing input. Never an official station, inventory or connection.
- Why it matters
- Checked by Route Plan Test.
- Application
- gridatlas · tools/train/src · JavaScript module
- Uses
- Station Index (import)
- Used by
- imported by Route Plan Test (import)
- Produces
- createScenarioStationStore
- Defines here
- createScenarioStationStore, clone
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/train/src/scenario-stations.mjs:1-9 · blob ee40d1df93fd321b9b8666cda03b4f76669a6468 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import {normaliseTrainStop,trainCoordinate} from './station-index.mjs';
/** Session-owned drawing input. Never an official station, inventory or connection. */
export function createScenarioStationStore({sessionId=globalThis.crypto?.randomUUID?.()}={}) {
if(typeof sessionId!=='string'||!/^[A-Za-z0-9_-]{1,80}$/.test(sessionId))throw new Error('A valid unique session ID is required.');
let revision=0,serial=0;const rows=new Map(),prefix='scenario:'+sessionId+':';
const clone=row=>({...normaliseTrainStop(row),proposed:true,sessionId,scenarioRevision:row.scenarioRevision,evidence:'SESSION_ONLY_USER_PROPOSED_NOT_OFFICIAL'});
function record(id,value){if(typeof value.name!=='string'||!value.name.trim()||!trainCoordinate(value.at)||!Array.isArray(value.kv)||value.kv.length!==1||![11,33].includes(value.kv[0]))throw new Error('Name, pin point and explicit11 or33kV choice are required.');return{stationId:id,id,name:value.name.trim(),at:value.at.slice(),kv:value.kv.slice(),operator:'',source:'SESSION_ONLY_USER_PROPOSED',pr … [line shortened here: 452 characters; full line on GitHub]
return Object.freeze({create(value){if(value?.stationId!=null||value?.id!=null)throw new Error('Proposed IDs are assigned by the current session.');const id=prefix+(serial+1),row=record(id,value);serial++;revision++;rows.set(id,row);return clone(row);},edit(id,patch){const old=rows.get(id);if(!old)throw new Error('No proposed station owned by this session.');if(patch?.id!=null||patch?.stationId!= … [line shortened here: 933 characters; full line on GitHub]
}Station Index
A JavaScript module in the train folder of GridAtlas that works with substations.
transformgridatlas / tools/train/src/station-index.mjs · lines 1–57 of 57 · pattern normaliseTrainStop (shared by 2 files)
- What it does
- It calculates substations. Defines 6 functions or classes, including trainCoordinate, normaliseTrainStop, buildStationIndex, copy, limitValue.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): 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: substations. README: "`station-index.mjs` reads the original loaded `src-subs` FeatureCollection."
- Downstream impact
- Used directly by 3 files: Itinerary (gridatlas); Place Bridge (gridatlas); Scenario Stations (gridatlas). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Route Plan Test (gridatlas).
- What it achieves
- It normalises train stop (`normaliseTrainStop`) and is built from the train coordinate helper (`trainCoordinate`) and the copy step (`copy`). Full source inventory. Display limits never change inventory or itinerary limits.
- Why it matters
- Imported by Itinerary, Place Bridge and Scenario Stations.
- Application
- gridatlas · tools/train/src · JavaScript module
- Uses
- none found
- Used by
- imported by Itinerary (import), imported by Place Bridge (import), imported by Scenario Stations (import)
- Produces
- trainCoordinate, normaliseTrainStop, buildStationIndex
- Defines here
- trainCoordinate, normaliseTrainStop, buildStationIndex, copy, limitValue, result
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/train/src/station-index.mjs:1-57 · blob 8b0356eef605aff46042a28a524754c5475339f6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Full source inventory. Display limits never change inventory or itinerary limits. */
export function trainCoordinate(at) {
return Array.isArray(at) && at.length === 2 && at.every(v => typeof v === 'number' && Number.isFinite(v)) && Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90 && !(at[0] === 0 && at[1] === 0);
}
export function normaliseTrainStop(stop) {
const stationId = stop?.stationId ?? stop?.id;
if (typeof stationId !== 'string' || !stationId.trim() || /[\u0000-\u001f\u007f]/.test(stationId) || (stop.id != null && stop.id !== stationId) || !trainCoordinate(stop.at)) throw new Error('A stable source station ID and valid source point are required.');
const row = {stationId, id: stationId, name: String(stop.name || 'Unnamed mapped substation'), at: stop.at.slice(), kv: [...new Set((stop.kv || []).filter(v => typeof v === 'number' && Number.isFinite(v) && v > 0))], operator: String(stop.operator || ''), source: String(stop.source || 'Existing Atlas substation layer')};
if (stop.place) {
const p = stop.place;
if (typeof p.label !== 'string' || !p.label.trim() || !trainCoordinate(p.at) || typeof p.provider !== 'string' || !p.provider || typeof p.distanceKm !== 'number' || !Number.isFinite(p.distanceKm) || p.distanceKm < 0) throw new Error('Place binding requires label, resolved point, provider and measured distance.');
row.place = {label: p.label, at: p.at.slice(), provider: p.provider, precision: p.precision == null ? null : String(p.precision), distanceKm: p.distanceKm, ...(p.resolvedLabel ? {resolvedLabel: String(p.resolvedLabel)} : {})};
}
return row;
}
export function buildStationIndex(features, {geodesy, datasetPin = null} = {}) {
if (!Array.isArray(features) || typeof geodesy?.representativePoint !== 'function' || typeof geodesy?.voltagesKv !== 'function' || typeof geodesy?.distanceKm !== 'function') throw new Error('Full source features and canonical geodesy are required.');
const sourceRecords = features.length, rows = [], ids = new Map(), conflictingIds = new Set();
let invalidRecords = 0, duplicateRecords = 0;
for (const feature of features) {
const p = feature?.properties || {}, stationId = feature?.id ?? p.id, at = geodesy.representativePoint(feature?.geometry);
if (stationId == null) { invalidRecords++; continue; }
let row;
try { row = normaliseTrainStop({stationId: String(stationId), at, name: p.name, kv: Array.from(geodesy.voltagesKv(p)), operator: p.operator, source: p.source}); } catch { invalidRecords++; continue; }
if (ids.has(row.stationId)) {
duplicateRecords++;
if (JSON.stringify(ids.get(row.stationId)) !== JSON.stringify(row)) conflictingIds.add(row.stationId);
continue;
}
ids.set(row.stationId, row); rows.push(row);
}
// Conflicting identities are visible as a coverage gap, never silently selectable.
const inventory = rows.filter(row => !conflictingIds.has(row.stationId));
const pin = datasetPin == null ? null : JSON.parse(JSON.stringify(datasetPin));
const copy = row => normaliseTrainStop(row), folded = s => String(s).normalize('NFKC').toLocaleLowerCase('en').trim();
const limitValue = limit => { if (limit == null) return Infinity; if (!Number.isInteger(limit) || limit < 1) throw new Error('Result limit must be a positive integer.'); return limit; };
function result(matches, limit, query = null) {
const n = limitValue(limit);
return {schema: 'gridatlas.station-search.v1', query, sourceRecords, indexedRecords: inventory.length, matched: matches.length, truncated: matches.length > n, ambiguous: matches.length > 1, rows: matches.slice(0,n).map(row => ({...copy(row), ...(row.distanceKm == null ? {} : {distanceKm: row.distanceKm})}))};
}
return Object.freeze({
search(query, {limit} = {}) {
const q = folded(query ?? '');
const matches = q ? inventory.filter(row => folded(row.stationId).includes(q) || folded(row.name).includes(q)) : [];
matches.sort((a,b) => Number(folded(b.stationId) === q) - Number(folded(a.stationId) === q) || Number(folded(b.name) === q) - Number(folded(a.name) === q) || a.name.localeCompare(b.name,'en') || a.stationId.localeCompare(b.stationId,'en'));
return result(matches, limit, String(query ?? ''));
},
near(at, {radiusKm, limit} = {}) {
if (!trainCoordinate(at) || !Number.isInteger(radiusKm) || radiusKm < 1 || radiusKm > 50) throw new Error('Choose a valid place point and whole radius from 1 to 50 km.');
const matches = inventory.map(row => ({...row, distanceKm: geodesy.distanceKm(at[0],at[1],row.at[0],row.at[1])})).filter(row => Number.isFinite(row.distanceKm) && row.distanceKm >= 0 && row.distanceKm <= radiusKm).sort((a,b) => a.distanceKm-b.distanceKm || a.stationId.localeCompare(b.stationId,'en'));
return result(matches, limit);
},
get(stationId) { const row = ids.get(stationId); return row && !conflictingIds.has(stationId) ? copy(row) : null; },
snapshot() { return {schema:'gridatlas.station-index.v1', sourceRecords, indexedRecords:inventory.length, invalidRecords, duplicateRecords, conflictingIds:[...conflictingIds], datasetPin: pin == null ? null : JSON.parse(JSON.stringify(pin)), datasetPinStatus:pin == null ? 'NOT_SUPPLIED' : 'CALLER_SUPPLIED_NOT_REVALIDATED', coordinatePrecision:'SOURCE_PROVIDED_NOT_INDEPENDENTLY_VERIFIED', conne … [line shortened here: 420 characters; full line on GitHub]
});
}
Train Motion
A JavaScript module in the tools folder of GridAtlas that maps substations. It creates train ride (`createTrainRide`), paints cursor (`paintCursor`) and sets plan (`setPlan`).
rendergridatlas / tools/train/src/train-motion.mjs · lines 1–181 of 181 · pattern createTrainRide (shared by 2 files)
- What it does
- It maps substations. Defines 25 functions or classes, including createTrainRide, state, notify, collection, point.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): 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: substations.
- Downstream impact
- Used directly by 1 file: Train Motion Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Native MapLibre learning cursor. Travel direction is never electrical flow.
- Why it matters
- Checked by Train Motion Test.
- Application
- gridatlas · tools/train/src · JavaScript module
- Uses
- none found
- Used by
- imported by Train Motion Test (import)
- Produces
- createTrainRide
- Defines here
- createTrainRide, state, notify, collection, point, cancel, schedule, pause, cancelRetry, waitForStyle, ensure, add, position, paint, paintCursor, tick, setPlan, play, seekStop, step, stopData, clearPlan, styleReload, removed, destroy
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/train/src/train-motion.mjs:1-181 · blob 4a8f0d803d20e9dff2c6d258048cbb6e823e0422 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Native MapLibre learning cursor. Travel direction is never electrical flow. */
export 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});
}Train Motion Test
A test in the tools folder of GridAtlas that checks Route Plan and Train Motion. It makes plan (`makePlan`) and is built from the run step (`run`).
testgridatlas / tools/train/train-motion.test.mjs · lines 1–122 of 122 · Entry point · pattern access (shared by 2 files)
- What it does
- It tests its inputs. Defines makePlan, fixture, access, run. Uses libraries node:test, node:assert/strict.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Defines `makePlan`, `fixture`, `access` and 1 more.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/train · test
- Uses
- Route Plan (import), Train Motion (import), node:test, node:assert/strict
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- makePlan, fixture, access, run
- Defines here
- makePlan, fixture, access, run
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/train/train-motion.test.mjs:1-122 · blob 91309e1ca406aaa428df3715d954c99b6e7d5911 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import {buildRoutePlan} from './src/route-plan.mjs';
import {createTrainRide} from './src/train-motion.mjs';
const geodesy={distanceKm:(a,b,c,d)=>Math.hypot(c-a,d-b)*100};
const makePlan=()=>buildRoutePlan({synthetic:true,stops:[{source:'SYNTHETIC_TEST',id:'a',at:[0,51],kv:400},{source:'SYNTHETIC_TEST',id:'b',at:[1,51],kv:400},{source:'SYNTHETIC_TEST',id:'c',at:[2,51],kv:400}],geodesy,allowSimulated:true});
function fixture(reducedMotion=false,extras={},busyAfterSetData=false){
const sources=new Map(),layers=new Map(),listeners=new Map(),frames=new Map(),history=[],cameras=[];let serial=0,removed=false,styleReady=true;
const access=()=>{if(removed)throw Error('destroyed style');};
const map={isStyleLoaded:()=>styleReady,on(n,fn){listeners.set(n,fn);},off(n,fn){if(listeners.get(n)===fn)listeners.delete(n);},
getSource(id){access();return sources.get(id);},getLayer(id){access();return layers.get(id);},
addSource(id,s){access();sources.set(id,{...s,setData(data){access();this.data=data;history.push(id);if(busyAfterSetData)styleReady=false;}});},addLayer(layer){access();layers.set(layer.id,layer);},
removeSource(id){access();sources.delete(id);},removeLayer(id){access();layers.delete(id);},
setPaintProperty(id,k,v){access();layers.get(id).paint[k]=v;},easeTo(o){cameras.push(o);}};
const ride=createTrainRide({map,geodesy,reducedMotion,requestFrame:fn=>{frames.set(++serial,fn);return serial;},cancelFrame:id=>frames.delete(id),...extras});
const run=time=>{const [id,fn]=frames.entries().next().value;frames.delete(id);fn(time);};
return{ride,map,sources,layers,frames,history,cameras,run,listeners,setStyleReady(value){styleReady=value;},
remove(){removed=true;listeners.get('remove')();},styleReload(){sources.clear();layers.clear();listeners.get('style.load')();}};
}
test('explicit play owns one cursor/one bounded loop and leaves native layers intact',()=>{
const f=fixture();f.layers.set('native400',{id:'native400'});f.ride.setPlan(makePlan());assert.equal(f.frames.size,0);
assert.equal(f.ride.play(),true);assert.equal(f.ride.play(),true);assert.equal(f.frames.size,1);
f.run(0);f.run(200);assert.ok(f.ride.snapshot().fraction>0);assert.equal(f.frames.size,1);
assert.equal(f.sources.get('gridatlas-train-cursor').data.features.length,1);assert.equal(f.cameras.length,0);
f.ride.pause();assert.equal(f.frames.size,0);f.ride.destroy();assert.deepEqual([...f.layers.keys()],['native400']);
});
test('plan edit midplay invalidates queued old epoch and never moves replacement cursor',()=>{
const f=fixture();f.ride.setPlan(makePlan());f.ride.play();const stale=[...f.frames.values()][0];
f.ride.setPlan(makePlan());f.ride.play();stale(100000);assert.equal(f.ride.snapshot().fraction,0);assert.equal(f.frames.size,1);
});
test('reduced motion has static manual step/seek and no animation loop',()=>{
const f=fixture(true);f.ride.setPlan(makePlan());assert.equal(f.ride.play(),false);assert.equal(f.frames.size,0);
assert.equal(f.ride.snapshot().stopIndex,1);assert.equal(f.ride.seekStop(2),true);assert.equal(f.ride.snapshot().stopIndex,2);
assert.equal(f.ride.seekStop(-1),false);assert.equal(f.layers.get('gridatlas-train-flow').paint['line-opacity'],0);
});
test('style reload restores own overlay paused; map removal cancels and queued callbacks do not access style',()=>{
const f=fixture();f.ride.setPlan(makePlan());f.ride.play();f.styleReload();assert.equal(f.ride.snapshot().playing,false);
assert.equal(f.layers.size,7);f.ride.play();const stale=[...f.frames.values()][0];f.remove();assert.equal(f.frames.size,0);
assert.doesNotThrow(()=>stale(9000));assert.doesNotThrow(()=>f.ride.destroy());assert.equal(f.ride.snapshot().alive,false);
});
test('foreign source/layer identities are preserved and block playback',()=>{
const f=fixture(),foreign={data:'foreign'};f.sources.set('gridatlas-train-routes',foreign);f.ride.setPlan(makePlan());
assert.equal(f.ride.play(),false);f.ride.destroy();assert.equal(f.sources.get('gridatlas-train-routes'),foreign);
});
test('missing documented route cannot start motion; setting a plan snapshots later UI mutation',()=>{
const f=fixture(),p=makePlan();f.ride.setPlan(p);p.stops[0].at[0]=99;
assert.equal(f.sources.get('gridatlas-train-stops').data.features[0].geometry.coordinates[0],0);
p.playable=false;f.ride.setPlan(p);assert.equal(f.ride.play(),false);assert.equal(f.frames.size,0);
});
test('step and seek cannot cross a missing leg; later stop pins remain and cursor stays on approved prefix',()=>{
const f=fixture(),p=makePlan();p.legs[1]={...p.legs[1],evidence:'MISSING',coordinates:null,km:null};p.playable=false;
f.ride.setPlan(p);assert.equal(f.ride.snapshot().approvedThroughStop,1);assert.equal(f.sources.get('gridatlas-train-stops').data.features.length,3);
assert.equal(f.sources.get('gridatlas-train-routes').data.features.length,1);assert.equal(f.ride.step(),true);
const at=f.sources.get('gridatlas-train-cursor').data.features[0].geometry.coordinates;
assert.equal(f.ride.step(),false);assert.equal(f.ride.seekStop(2),false);assert.equal(f.ride.play(),false);
assert.deepEqual(f.sources.get('gridatlas-train-cursor').data.features[0].geometry.coordinates,at);
const gapFirst=makePlan();gapFirst.legs[0]={...gapFirst.legs[0],evidence:'MISSING',coordinates:null};gapFirst.playable=false;
f.ride.setPlan(gapFirst);assert.equal(f.ride.step(),false);assert.equal(f.ride.seekStop(1),false);assert.equal(f.sources.get('gridatlas-train-routes').data.features.length,0);
});
test('clearPlan atomically removes stale route/cursor, retains current valid pins, and refuses old navigation',()=>{
const f=fixture();f.ride.setPlan(makePlan());f.ride.play();const stale=[...f.frames.values()][0];
const current=[{id:'new',at:[3,51],kv:[33],proposed:true},{id:'deleted',at:[4,51],invalid:true}];
assert.equal(f.ride.clearPlan({stops:current}),true);stale(9999);
assert.equal(f.sources.get('gridatlas-train-routes').data.features.length,0);assert.equal(f.sources.get('gridatlas-train-cursor').data.features.length,0);
const pins=f.sources.get('gridatlas-train-stops').data.features;assert.equal(pins.length,1);assert.equal(pins[0].properties.kind,'customer_substation');
assert.equal(f.layers.get('gridatlas-train-proposals').paint['circle-radius'],5);assert.equal(f.layers.get('gridatlas-train-proposals').paint['circle-stroke-width'],1.5);
assert.equal(f.layers.get('gridatlas-train-proposals').paint['circle-color'],'#e0b050');assert.equal(f.layers.get('gridatlas-train-proposals').paint['circle-stroke-color'],'#000c10');
assert.equal(f.ride.play(),false);assert.equal(f.ride.seekStop(1),false);assert.equal(f.ride.step(),false);assert.equal(f.frames.size,0);
f.styleReload();assert.equal(f.sources.get('gridatlas-train-cursor').data.features.length,0);assert.equal(f.sources.get('gridatlas-train-stops').data.features.length,1);
});
test('changed external plan epoch clears the active cursor before a stale frame or seek can run',()=>{
let epoch=1;const f=fixture(false,{readPlanEpoch:()=>epoch}),p=makePlan();p.planEpoch=1;f.ride.setPlan(p);f.ride.play();
epoch=2;f.run(100);assert.equal(f.ride.snapshot().playing,false);assert.equal(f.frames.size,0);assert.equal(f.sources.get('gridatlas-train-cursor').data.features.length,0);assert.equal(f.ride.seekStop(1),false);
});
test('GIS solid, topology long-dash and simulated dots are distinct without relying on colour',()=>{
const f=fixture();f.ride.setPlan(makePlan());
assert.equal(f.layers.get('gridatlas-train-route-gis').paint['line-dasharray'],undefined);
assert.deepEqual(f.layers.get('gridatlas-train-route-topology').paint['line-dasharray'],[5,2]);
assert.deepEqual(f.layers.get('gridatlas-train-route-simulated').paint['line-dasharray'],[1,3]);
assert.deepEqual(f.layers.get('gridatlas-train-flow').filter,['==',['get','evidence'],'GIS_REVIEWED']);
});
test('rejected replacement clears old route, cursor and queued animation before reporting failure',()=>{
const f=fixture();f.ride.setPlan(makePlan());f.ride.play();const stale=[...f.frames.values()][0];
assert.throws(()=>f.ride.setPlan({schema:'invalid'}),/Invalid/);stale(10000);
assert.equal(f.frames.size,0);assert.equal(f.ride.play(),false);assert.equal(f.ride.seekStop(1),false);
assert.equal(f.sources.get('gridatlas-train-routes').data.features.length,0);assert.equal(f.sources.get('gridatlas-train-cursor').data.features.length,0);
});
test('stale epoch is rejected before first paint or any mutation of a current valid ride',()=>{
const f=fixture(false,{readPlanEpoch:()=>2}),stale=makePlan();stale.planEpoch=1;
assert.throws(()=>f.ride.setPlan(stale),/Stale/);assert.equal(f.sources.size,0);assert.equal(f.layers.size,0);assert.equal(f.history.length,0);
const current=makePlan();current.planEpoch=2;f.ride.setPlan(current);f.ride.play();const writes=f.history.length;
const cursor=structuredClone(f.sources.get('gridatlas-train-cursor').data);
assert.throws(()=>f.ride.setPlan(stale),/Stale/);assert.equal(f.history.length,writes);assert.equal(f.frames.size,1);assert.equal(f.ride.snapshot().playing,true);
assert.deepEqual(f.sources.get('gridatlas-train-cursor').data,cursor);
});
test('owned pending GeoJSON work cannot blank a second Draw or pause its own animation',()=>{
const f=fixture(false,{},true);f.ride.setPlan(makePlan());assert.equal(f.map.isStyleLoaded(),false);
assert.equal(f.sources.get('gridatlas-train-routes').data.features.length,2);assert.equal(f.sources.get('gridatlas-train-cursor').data.features.length,1);
f.ride.clearPlan({stops:makePlan().stops});f.ride.setPlan(makePlan());
assert.equal(f.sources.get('gridatlas-train-routes').data.features.length,2);assert.equal(f.sources.get('gridatlas-train-cursor').data.features.length,1);
assert.equal(f.ride.play(),true);f.run(0);f.run(200);assert.equal(f.map.isStyleLoaded(),false);
assert.equal(f.ride.snapshot().playing,true);assert.ok(f.ride.snapshot().fraction>0);assert.equal(f.frames.size,1);f.ride.destroy();
});
test('only absent sources wait on public readiness; retry is bounded and style-load/destroy clean it up',()=>{
const timers=new Map();let serial=0;const f=fixture(false,{setTimer:fn=>{timers.set(++serial,fn);return serial;},clearTimer:id=>timers.delete(id)});
f.setStyleReady(false);f.ride.setPlan(makePlan());assert.equal(f.sources.size,0);assert.equal(timers.size,1);
for(let i=0;i<12;i++){const next=timers.entries().next().value;if(!next)break;timers.delete(next[0]);next[1]();}
assert.equal(timers.size,0);assert.equal(f.sources.size,0);assert.match(f.ride.snapshot().unavailable,/Retry Draw/);
f.setStyleReady(true);f.listeners.get('style.load')();assert.equal(f.sources.size,3);assert.equal(timers.size,0);assert.equal(f.ride.snapshot().unavailable,null);
f.sources.clear();f.layers.clear();f.setStyleReady(false);f.ride.setPlan(makePlan());assert.equal(timers.size,1);
f.ride.destroy();assert.equal(timers.size,0);
});
test('camera follows only active opted-in Play; Pause, invalidation, OFF Draw and Step never move it',()=>{
const f=fixture();f.ride.setPlan(makePlan());f.ride.play({cameraFollow:true});f.run(0);f.run(200);
assert.ok(f.cameras.length>0);f.ride.pause();const before=f.cameras.length;
f.ride.step();assert.equal(f.cameras.length,before,'manual step never inherits last Play follow');
f.ride.clearPlan({stops:makePlan().stops});assert.equal(f.ride.snapshot().cameraFollow,false);
f.ride.setPlan(makePlan());f.ride.step();assert.equal(f.cameras.length,before,'redraw/step after invalidation do not follow');
f.ride.play({cameraFollow:false});f.run(300);f.run(500);assert.equal(f.cameras.length,before);
f.ride.pause();f.ride.play({cameraFollow:true});f.run(600);f.run(800);assert.ok(f.cameras.length>before,'next explicit opted-in Play can follow again');
f.ride.destroy();
});UI
A JavaScript file in the train folder of GridAtlas that maps substations, transformers and postcodes. It creates great grid journey (`createGreatGridJourney`), sets mode (`setMode`) and renders stops (`renderStops`).
rendergridatlas / tools/train/ui.js · lines 1–100 of 100 · Not reached from any entry point (candidate for review) · pattern createGreatGridJourney (shared by 2 files)
- What it does
- It maps substations, transformers and postcodes. Defines 15 functions or classes, including createGreatGridJourney, el, on, say, invalidate. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): 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: substations, transformers, postcodes, 33kV, 11kV.
- Inputs & outputs
- Out: interactive map. Voltage levels named: 33kV, 11kV.
- What it achieves
- Shared native journey UI; all network evidence stays in the route planner. Its code works with 11 kV and 33 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/train · script
- Uses
- none found
- Used by
- none found
- Produces
- createGreatGridJourney, el, on, say, invalidate, setMode, renderStops, searchStations, law, applyLawChange, cancelProposedPick, paintProposed
- Defines here
- createGreatGridJourney, el, on, say, invalidate, setMode, renderStops, searchStations, law, applyLawChange, cancelProposedPick, paintProposed, proposedRemoved, planIsCurrent, loadDemo
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/train/ui.js:1-100 · blob b31986df3d106c2a1944cafe01960f7812240622 · 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
/** 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&¤t!==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]
}