In this section
- Pilot Grid render · cosmic / tools/explore/theme/pilot-grid.js lines 1–523
- Pilot Lightning render · cosmic / tools/explore/theme/pilot-lightning.css lines 1–37
Pilot Grid
A JavaScript file in the theme folder of Cosmic that maps grid 400kV, grid 275kV, grid 132kV and grid 66kV, and uses data from the GridAtlas repository.
rendercosmic / tools/explore/theme/pilot-grid.js · lines 1–523 of 523 · Entry point · pattern hudTick (shared by 2 files)
- What it does
- It maps grid 400kV, grid 275kV, grid 132kV and grid 66kV. Defines 44 functions or classes, including base, src, save, ckey, addCell. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: 400kV, 275kV, 132kV, 66kV, 33kV.
- Inputs & outputs
- In: data source: gridatlas data; browser storage (getItem); form fields (user input). Out: browser storage (setItem). Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV.
- Downstream impact
- Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
- What it achieves
- It adds cell (`addCell`), clamps box (`clampBox`) and renders toggles (`renderToggles`). Pilot module W05 "grid" (CONDUCTOR-466): 400, 275, 132 and 66kV lines and the 5,800 substations at 33kV and above, drawn as layers, tappable, with a find / jump list and a nearest list. Its code works with 33 kV, 66 kV and 132 kV. It responds to click, focus and input events.
- Why it matters
- Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
- Application
- cosmic · tools/explore/theme · script
- Uses
- GridAtlas — Index Page (estate URL)
- Used by
- loaded by Pilot (script src)
- Produces
- base, src, save, ckey, addCell, cellsOf, voltages, clsOf, kvText, approxM, packLines, packSubs
- Defines here
- base, src, save, ckey, addCell, cellsOf, voltages, clsOf, kvText, approxM, packLines, packSubs, load, lodKinds, subMinCls, clampBox, coarseOwner, hoverFor, flyBtn, srcLine, subCard, endSub, lineMid, lineCard, bearing, fmtD, fly, panelHtml, q, renderToggles
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-grid.js:1-523 · blob c2e26c831cf59afd6d0bb0cf3195530423fbf4cf · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: unknown · users: none · canonical: unknown
/* Pilot module W05 "grid" (CONDUCTOR-466): 400, 275, 132 and 66 kV lines and the 5,800 substations at 33 kV and
above, drawn as layers, tappable, with a find / jump list and a nearest list.
Data is real and streamed, never copied into cosmic (photon rule). Source: the GridAtlas atlas-v9 release,
OpenStreetMap (ODbL) as GridAtlas publishes it, under PILOT.data.GA + REL:
grid_400kv.geojson 4,106 lines grid_275kv.geojson 2,935 lines grid_132kv.geojson 6,227 lines
grid_66kv.geojson 1,171 lines grid_substations.geojson 5,800 points (name, operator, voltage)
Each file is fetched only when its layer is switched on, after the page has painted.
Lines are drawn on the ground along their mapped vertices; nothing here invents a location.
Built against /tmp/vk/pilot200/CONTRACT.md v1 (window.PILOT). No globals besides window.PILOT. */
(function () {
'use strict';
if (!window.PILOT) return;
var P = window.PILOT, D = document, W = window;
P.module('grid', { version: '1', owner: 'W05' });
var REL = 'atlas/releases/202608300453-atlas-v9/data/';
var CREDIT = 'Grid lines and substations: Data © OpenStreetMap contributors (ODbL), via GridAtlas atlas-v9';
var OSM_LINK = '<a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">OpenStreetMap contributors</a>';
// colours: 400/275/132 as pilot.js KV (from the owner's pylons-real.js); 66 kV and substations added here
var K = {
'400': { file: 'grid_400kv.geojson', col: '#4080ff', n: 4106, mb: 1.47, title: '400 kV lines', line: true },
'275': { file: 'grid_275kv.geojson', col: '#ff4d4d', n: 2935, mb: 1.02, title: '275 kV lines', line: true },
'132': { file: 'grid_132kv.geojson', col: '#33e666', n: 6227, mb: 2.84, title: '132 kV lines', line: true },
'66': { file: 'grid_66kv.geojson', col: '#ffab2e', n: 1171, mb: 0.60, title: '66 kV lines', line: true },
subs: { file: 'grid_substations.geojson', col: '#f2f2f2', n: 5800, mb: 1.19, title: 'Substations 33 kV+', line: false }
};
var ORDER = ['400', '275', '132', '66', 'subs'];
var CLS = [400, 275, 132, 66, 33];
var CLS_COL = { 400: '#4080ff', 275: '#ff4d4d', 132: '#33e666', 66: '#ffab2e', 33: '#d9d9d9' };
var CELL = 10; // index cells of 0.1 degree
var COARSE_M = 450; // vertex spacing kept at high LOD
var SEG_CAP = [14000, 10000, 7000, 5000]; // segments per frame by v.lod
var esc = P.esc || function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return '&#' + c.charCodeAt(0) + ';'; }); };
var rad = Math.PI / 180;
// ---- S02 sources: GridAtlas release, ?ga= override only for same origin or localhost (offline tests)
function base() {
var m = /[?&]ga=([^&#]+)/.exec(location.search);
if (m) {
try {
var u = new URL(decodeURIComponent(m[1]), location.href);
if (/^https?:$/.test(u.protocol) && (u.origin === location.origin || /^(localhost|127\.0\.0\.1)$/.test(u.hostname)))
return u.href.replace(/\/?$/, '/');
} catch (e) { /* ignore a bad override */ }
}
return ((P.data && P.data.GA) || 'https://ventusltd.github.io/gridatlas/') + REL;
}
function src(kind) { return K[kind] ? base() + K[kind].file : null; }
// ---- state
var st = {}; ORDER.forEach(function (k) { st[k] = { state: 'off', count: 0, p: null, err: '' }; });
var on = { '400': true, '275': true, '132': false, '66': false, subs: true };
try { var sv = JSON.parse(localStorage.getItem('p-grid-on') || 'null'); if (sv) ORDER.forEach(function (k) { if (k in sv) on[k] = !!sv[k]; }); } catch (e) { /* private mode */ }
function save() { try { localStorage.setItem('p-grid-on', JSON.stringify(on)); } catch (e) { /* ignore */ } }
// packed data
var LN = {}; // kind -> { lines: [{name, op, v, s, n}], ll: Float32Array [lat,lon,...], fine: index, coarse: {ll, seg, idx} }
var SB = null; // { n, lat, lon, cls, name, op, volt, named, idx }
function ckey(la, lo) { return Math.floor(la * CELL) * 100000 + Math.floor(lo * CELL) + 50000; }
function addCell(idx, key, i) { var a = idx.get(key); if (a) a.push(i); else idx.set(key, [i]); }
function cellsOf(b, fn) {
var s = Math.floor(b.s * CELL), n = Math.floor(b.n * CELL), w = Math.floor(b.w * CELL), e = Math.floor(b.e * CELL);
for (var a = s; a <= n; a++) for (var o = w; o <= e; o++) fn(a * 100000 + o + 50000);
}
function voltages(v) {
var out = [];
String(v == null ? '' : v).split(/[;,:]/).forEach(function (t) { var x = parseFloat(t); if (x > 0) out.push(x); });
return out;
}
function clsOf(mx) { return mx >= 350000 ? 400 : mx >= 200000 ? 275 : mx >= 100000 ? 132 : mx >= 50000 ? 66 : 33; }
function kvText(v) {
var vs = voltages(v).sort(function (a, b) { return b - a; }), seen = {};
var t = vs.map(function (x) { var k = x >= 1000 ? +(x / 1000).toFixed(1) : x / 1000; return k; })
.filter(function (k) { if (seen[k]) return false; seen[k] = 1; return true; });
return t.length ? t.join(' / ') + ' kV' : 'voltage not mapped';
}
function approxM(la1, lo1, la2, lo2) { var x = (lo2 - lo1) * Math.cos((la1 + la2) * 0.5 * rad) * 111320, y = (la2 - la1) * 111320; return Math.sqrt(x * x + y * y); }
// ---- S04 pack lines (fine index on every segment, coarse copy with ~450 m vertex spacing)
function packLines(kind, gj) {
var fs = (gj && gj.features) || [], lines = [], tot = 0;
fs.forEach(function (f) { var g = f.geometry; if (!g) return; if (g.type === 'LineString') tot += g.coordinates.length; else if (g.type === 'MultiLineString') g.coordinates.forEach(function (c) { tot += c.length; }); });
var ll = new Float32Array(tot * 2), at = 0;
var cll = [], cseg = [];
var fine = new Map(), coarse = new Map();
fs.forEach(function (f) {
var g = f.geometry, pr = f.properties || {}; if (!g) return;
var parts = g.type === 'LineString' ? [g.coordinates] : g.type === 'MultiLineString' ? g.coordinates : [];
parts.forEach(function (c) {
if (!c || c.length < 2) return;
var L = { name: pr.name || '', op: pr.operator || '', v: pr.voltage || '', kind: kind, s: at, n: c.length, cs: cll.length / 2, cn: 0 };
var li = lines.length; lines.push(L);
for (var i = 0; i < c.length; i++) {
ll[at * 2] = c[i][1]; ll[at * 2 + 1] = c[i][0];
if (i) { var a = at - 1, k1 = ckey(ll[a * 2], ll[a * 2 + 1]), k2 = ckey(ll[at * 2], ll[at * 2 + 1]); addCell(fine, k1, a); if (k2 !== k1) addCell(fine, k2, a); }
at++;
}
// coarse: first, every vertex >= COARSE_M from the last kept one, last
var lastLa = c[0][1], lastLo = c[0][0]; cll.push(lastLa, lastLo); L.cn = 1;
for (i = 1; i < c.length; i++) {
var la = c[i][1], lo = c[i][0];
if (i === c.length - 1 || approxM(lastLa, lastLo, la, lo) >= COARSE_M) {
var ci = cll.length / 2; cll.push(la, lo); L.cn++;
var k3 = ckey(lastLa, lastLo), k4 = ckey(la, lo); addCell(coarse, k3, ci - 1); if (k4 !== k3) addCell(coarse, k4, ci - 1);
cseg[ci - 1] = 1; lastLa = la; lastLo = lo;
}
}
cseg[cll.length / 2 - 1] = 0; // a line's last vertex does not start a segment
});
});
// segment start index -> is it a real segment (not the join between two lines)?
var segOK = new Uint8Array(at); lines.forEach(function (L) { for (var i = L.s; i < L.s + L.n - 1; i++) segOK[i] = 1; });
var cOK = new Uint8Array(cll.length / 2); cseg.forEach(function (x, i) { if (x) cOK[i] = 1; });
var owner = new Int32Array(at); lines.forEach(function (L, li) { for (var i = L.s; i < L.s + L.n; i++) owner[i] = li; });
LN[kind] = { lines: lines, ll: ll, ok: segOK, owner: owner, fine: fine,
cll: new Float32Array(cll), cok: cOK, coarse: coarse, stamp: new Uint32Array(at), cstamp: new Uint32Array(cll.length / 2) };
return lines.length;
}
// ---- S05 pack substations
function packSubs(gj) {
var fs = ((gj && gj.features) || []).filter(function (f) { return f.geometry && f.geometry.type === 'Point'; }), n = fs.length;
var S = { n: n, lat: new Float64Array(n), lon: new Float64Array(n), cls: new Uint16Array(n), name: [], op: [], volt: [], named: new Uint8Array(n), idx: new Map() };
fs.forEach(function (f, i) {
var c = f.geometry.coordinates, pr = f.properties || {}, vs = voltages(pr.voltage);
S.lat[i] = c[1]; S.lon[i] = c[0];
S.cls[i] = vs.length ? clsOf(Math.max.apply(null, vs)) : 33;
S.named[i] = pr.name ? 1 : 0;
S.name.push(pr.name || 'Substation (unnamed in OSM)'); S.op.push(pr.operator || ''); S.volt.push(pr.voltage || '');
addCell(S.idx, ckey(c[1], c[0]), i);
});
S.lname = S.name.map(function (s, i) { return S.named[i] ? s.toLowerCase() : ''; });
S.lop = S.op.map(function (s) { return s.toLowerCase(); });
SB = S; return n;
}
// ---- S03 lazy loader
function load(kind, retry) {
var s = st[kind];
if (s.p && !retry) return s.p;
if (P.offline) { s.state = 'offline'; renderToggles(); return Promise.reject(new Error('offline')); }
s.state = 'loading'; s.err = ''; renderToggles();
var url = src(kind) + (retry ? (src(kind).indexOf('?') < 0 ? '?' : '&') + 'r=' + Date.now() : '');
var t0 = performance.now();
s.p = P.data.fetchJSON(url, { cache: !retry, timeout: 30000 }).then(function (gj) {
s.count = kind === 'subs' ? packSubs(gj) : packLines(kind, gj);
s.state = 'ready'; s.ms = Math.round(performance.now() - t0);
renderToggles(); refreshFind(); P.emit('grid:ready', { kind: kind, count: s.count });
if (TEST) console.log('[grid] ' + kind + ' ' + s.count + ' features in ' + s.ms + ' ms');
return s.count;
}, function (e) {
s.state = 'failed'; s.err = (e && e.message) || 'failed'; s.p = null; renderToggles();
P.note('Could not load ' + K[kind].title + ' (offline?). Try again from the Grid panel.', 5000);
throw e;
});
return s.p;
}
var TEST = /[?&]gridtest=1/.test(location.search);
// ---- S06 / S08 line layer
var frame = 0;
function lodKinds(lod) { // which line voltages draw at each v.lod (0 near/low ... 3 high/fast)
return lod >= 3 ? ['400', '275'] : lod === 2 ? ['400', '275', '132'] : ['400', '275', '132', '66'];
}
function subMinCls(lod) { return lod >= 3 ? 275 : lod === 2 ? 132 : lod === 1 ? 66 : 33; }
function clampBox(v) {
var b = v.bbox, c = v.cam; if (!b || !c) return null;
var R = 0.9, dla = R, dlo = R / Math.max(0.2, Math.cos(c.lat * rad)); // never more than ~100 km round the camera
return { s: Math.max(b.s, c.lat - dla), n: Math.min(b.n, c.lat + dla), w: Math.max(b.w, c.lon - dlo), e: Math.min(b.e, c.lon + dlo) };
}
var lineLayer = {
id: 'grid', title: 'Grid lines 400/275/132/66 kV (OSM via GridAtlas)', order: 30, visible: true, credit: CREDIT,
src: src, _segs: new Float32Array(SEG_CAP[0] * 4), _segLine: [], _nseg: 0, _drawnSegs: 0,
draw: function (g, v) {
frame++; this._nseg = 0; this._segLine.length = 0; this._drawnSegs = 0;
var b = clampBox(v); if (!b) return;
var lod = v.lod || 0, cap = SEG_CAP[Math.min(3, lod)], useCoarse = lod >= 2, self = this, total = 0;
var kinds = lodKinds(lod).filter(function (k) { return on[k] && LN[k]; });
g.save(); g.lineCap = 'round'; g.lineJoin = 'round';
kinds.forEach(function (k) {
if (total >= cap) return;
var Lk = LN[k], idx = useCoarse ? Lk.coarse : Lk.fine, ll = useCoarse ? Lk.cll : Lk.ll, ok = useCoarse ? Lk.cok : Lk.ok, stp = useCoarse ? Lk.cstamp : Lk.stamp;
var segs = [];
cellsOf(b, function (key) { var a = idx.get(key); if (!a) return; for (var i = 0; i < a.length; i++) { var s = a[i]; if (stp[s] !== frame && ok[s]) { stp[s] = frame; segs.push(s); } } });
if (total + segs.length > cap) segs.length = Math.max(0, cap - total);
total += segs.length;
// dark casing for contrast on imagery, then the voltage colour
var pts = [];
g.beginPath();
for (var i = 0; i < segs.length; i++) {
var s = segs[i], a = v.project(ll[s * 2], ll[s * 2 + 1], null), c = v.project(ll[s * 2 + 2], ll[s * 2 + 3], null);
if (a && c) {
if ((a.x < -50 && c.x < -50) || (a.y < -50 && c.y < -50) || (a.x > v.w + 50 && c.x > v.w + 50) || (a.y > v.h + 50 && c.y > v.h + 50)) continue;
g.moveTo(a.x, a.y); g.lineTo(c.x, c.y); pts.push(a.x, a.y, c.x, c.y, s);
} else if (v.line) v.line([ll[s * 2], ll[s * 2 + 1], null], [ll[s * 2 + 2], ll[s * 2 + 3], null]);
}
var wd = k === '400' ? 2.6 : k === '275' ? 2.3 : k === '132' ? 1.8 : 1.5;
g.strokeStyle = 'rgba(0,0,0,0.55)'; g.lineWidth = wd + 2.2; g.stroke();
g.strokeStyle = K[k].col; g.lineWidth = wd; g.stroke();
self._drawnSegs += pts.length / 5;
for (var j = 0; j < pts.length; j += 5) {
if (self._nseg >= self._segs.length / 4) break;
var n = self._nseg++; self._segs[n * 4] = pts[j]; self._segs[n * 4 + 1] = pts[j + 1]; self._segs[n * 4 + 2] = pts[j + 2]; self._segs[n * 4 + 3] = pts[j + 3];
self._segLine[n] = useCoarse ? coarseOwner(k, pts[j + 4]) : Lk.owner[pts[j + 4]];
self._segKind = self._segKind || []; self._segKind[n] = k;
}
});
g.restore();
},
pick: function (sx, sy) {
var best = -1, bd = 22 * 22;
for (var n = 0; n < this._nseg; n++) {
var x1 = this._segs[n * 4], y1 = this._segs[n * 4 + 1], x2 = this._segs[n * 4 + 2], y2 = this._segs[n * 4 + 3];
var dx = x2 - x1, dy = y2 - y1, l2 = dx * dx + dy * dy, t = l2 ? Math.max(0, Math.min(1, ((sx - x1) * dx + (sy - y1) * dy) / l2)) : 0;
var ex = x1 + t * dx - sx, ey = y1 + t * dy - sy, d = ex * ex + ey * ey;
if (d < bd) { bd = d; best = n; }
}
if (best < 0) return null;
return lineCard(this._segKind[best], this._segLine[best]);
}
};
function coarseOwner(k, ci) { // coarse vertex -> line index (lines keep cs/cn ranges in order)
var L = LN[k].lines, lo = 0, hi = L.length - 1;
while (lo < hi) { var m = (lo + hi + 1) >> 1; if (L[m].cs <= ci) lo = m; else hi = m - 1; }
return lo;
}
// ---- S07 substation layer
var subLayer = {
id: 'grid-subs', title: 'Substations 33 kV and above (OSM via GridAtlas)', order: 50, visible: true, credit: CREDIT,
_drawn: [],
draw: function (g, v) {
this._drawn = [];
if (!on.subs || !SB) return;
var b = clampBox(v); if (!b) return;
var lod = v.lod || 0, minC = subMinCls(lod), dr = this._drawn, S = SB, occ = [];
g.save();
cellsOf(b, function (key) {
var a = S.idx.get(key); if (!a) return;
for (var i = 0; i < a.length; i++) {
var s = a[i]; if (S.cls[s] < minC) continue;
var p = v.project(S.lat[s], S.lon[s], null); if (!p || p.x < -20 || p.y < -20 || p.x > v.w + 20 || p.y > v.h + 20) continue;
dr.push({ i: s, x: p.x, y: p.y, d: p.d });
}
});
if (dr.length > 3000) { dr.sort(function (a, c) { return S.cls[c.i] - S.cls[a.i] || a.d - c.d; }); dr.length = 3000; }
dr.forEach(function (o) {
var c = S.cls[o.i], r = c >= 400 ? 6 : c >= 275 ? 5.5 : c >= 132 ? 4.5 : c >= 66 ? 3.8 : 3;
if (o.d > 20000) r *= 0.7;
g.beginPath(); g.rect(o.x - r, o.y - r, r * 2, r * 2);
g.fillStyle = CLS_COL[c]; g.fill(); g.lineWidth = 1.5; g.strokeStyle = 'rgba(0,0,0,0.8)'; g.stroke();
});
// labels: named, near, no overlap (nearest first)
var near = dr.filter(function (o) { return S.named[o.i] && o.d < (S.cls[o.i] >= 275 ? 6000 : 3000); }).sort(function (a, c) { return a.d - c.d; });
g.font = '600 12px system-ui, sans-serif'; g.textBaseline = 'middle';
var labelled = 0;
for (var j = 0; j < near.length && labelled < 24; j++) {
var o = near[j], t = S.name[o.i], w = g.measureText(t).width + 8, x = o.x + 9, y = o.y - 8, hit = false;
for (var q = 0; q < occ.length; q++) { var R = occ[q]; if (x < R[2] && x + w > R[0] && y - 9 < R[3] && y + 9 > R[1]) { hit = true; break; } }
if (hit) continue;
occ.push([x, y - 9, x + w, y + 9]); o.label = t; labelled++;
g.fillStyle = 'rgba(0,0,0,0.62)'; g.fillRect(x, y - 9, w, 18);
g.fillStyle = '#fff'; g.fillText(t, x + 4, y);
}
g.restore();
},
pick: function (sx, sy) {
var best = null, bd = 22 * 22;
this._drawn.forEach(function (o) { var dx = o.x - sx, dy = o.y - sy, d = dx * dx + dy * dy; if (d < bd) { bd = d; best = o; } });
return best ? subCard(best.i) : null;
}
};
// ---- S10 / S11 / S16 cards and fly-to
function hoverFor(c) { return c >= 275 ? { alt: 320, dist: 900 } : c >= 132 ? { alt: 240, dist: 700 } : { alt: 160, dist: 450 }; }
function flyBtn(lat, lon, label, c, extra) {
return '<button type="button" class="p-grid-btn" data-p-grid-fly="' + lat.toFixed(6) + ',' + lon.toFixed(6) + ',' + c + (extra || '') + '" data-p-grid-label="' + esc(label) + '">' + 'Fly here' + '</button>';
}
function srcLine(kind) { return '<p class="p-grid-src">Source: GridAtlas atlas-v9 ' + esc(K[kind].file) + ' · Data © ' + OSM_LINK + ' (ODbL)</p>'; }
function subCard(i) {
var S = SB, c = S.cls[i];
P.emit('grid:select', { name: S.name[i], kv: c, lat: S.lat[i], lon: S.lon[i] });
return {
title: S.name[i], lat: S.lat[i], lon: S.lon[i], id: 'grid-sub-' + i, cap: 'SUBSTATION ' + c + ' kV CLASS',
html: '<div class="p-grid-card"><p><b>' + esc(kvText(S.volt[i])) + '</b>' + (S.op[i] ? ' · ' + esc(S.op[i]) : ' · operator not mapped') + '</p>' +
'<p class="p-grid-dim">' + S.lat[i].toFixed(5) + ', ' + S.lon[i].toFixed(5) + '</p>' +
flyBtn(S.lat[i], S.lon[i], S.name[i], c) + srcLine('subs') + '</div>'
};
}
function endSub(la, lo) {
if (!SB) return null; var best = -1, bd = 1000;
for (var a = -1; a <= 1; a++) for (var o = -1; o <= 1; o++) {
var ar = SB.idx.get(ckey(la + a / CELL, lo + o / CELL)); if (!ar) continue;
ar.forEach(function (s) { var d = P.dist(la, lo, SB.lat[s], SB.lon[s]); if (d < bd) { bd = d; best = s; } });
}
return best < 0 ? null : { i: best, d: bd };
}
function lineMid(L, ll) { var m = L.s + (L.n >> 1), m2 = Math.min(L.s + L.n - 1, m + 1), m1 = m2 === m ? m - 1 : m; return { lat: ll[m * 2], lon: ll[m * 2 + 1], a: m1, b: m2 }; }
function lineCard(kind, li) {
var Lk = LN[kind]; if (!Lk) return null; var L = Lk.lines[li], ll = Lk.ll, kvc = +kind;
var mid = lineMid(L, ll), hdg = bearing(ll[mid.a * 2], ll[mid.a * 2 + 1], ll[mid.b * 2], ll[mid.b * 2 + 1]);
var ends = [[ll[L.s * 2], ll[L.s * 2 + 1]], [ll[(L.s + L.n - 1) * 2], ll[(L.s + L.n - 1) * 2 + 1]]];
var endsHtml = ends.map(function (e, k) {
var r = endSub(e[0], e[1]), tag = k ? 'End B' : 'End A';
if (!r) return '<li>' + tag + ': no mapped substation within 1 km of this end' + (SB ? '' : ' (substations layer not loaded)') + '</li>';
return '<li>' + tag + ': ' + esc(SB.name[r.i]) + ' (' + fmtD(r.d) + ') ' + flyBtn(SB.lat[r.i], SB.lon[r.i], SB.name[r.i], SB.cls[r.i]) + '</li>';
}).join('');
var len = 0; for (var i = L.s; i < L.s + L.n - 1; i++) len += P.dist(ll[i * 2], ll[i * 2 + 1], ll[i * 2 + 2], ll[i * 2 + 3]);
P.emit('grid:select', { name: L.name, kv: kvc, lat: mid.lat, lon: mid.lon });
return {
title: L.name || (kind + ' kV line (unnamed in OSM)'), lat: mid.lat, lon: mid.lon, id: 'grid-' + kind + '-' + li, cap: kind + ' kV LINE',
html: '<div class="p-grid-card"><p><b>' + esc(kvText(L.v)) + '</b>' + (L.op ? ' · ' + esc(L.op) : ' · operator not mapped') + '</p>' +
'<p class="p-grid-dim">This mapped section: ' + fmtD(len) + ', ' + L.n + ' vertices</p>' +
flyBtn(mid.lat, mid.lon, L.name || kind + ' kV line', kvc, ',' + Math.round(hdg)) +
'<ul class="p-grid-ends">' + endsHtml + '</ul>' + srcLine(kind) + '</div>'
};
}
function bearing(la1, lo1, la2, lo2) {
if (P.bearing) return P.bearing(la1, lo1, la2, lo2);
var y = Math.sin((lo2 - lo1) * rad) * Math.cos(la2 * rad), x = Math.cos(la1 * rad) * Math.sin(la2 * rad) - Math.sin(la1 * rad) * Math.cos(la2 * rad) * Math.cos((lo2 - lo1) * rad);
return (Math.atan2(y, x) / rad + 360) % 360;
}
function fmtD(m) { return m < 1000 ? Math.round(m) + ' m' : (m / 1000).toFixed(m < 10000 ? 1 : 0) + ' km'; }
function fly(lat, lon, c, label, hdg) {
var h = hoverFor(c), o = { alt: h.alt, dist: h.dist, label: label, source: 'grid' };
if (hdg != null && !isNaN(hdg)) { o.hdg = hdg; o.dist = 600; }
var p = P.flyTo(lat, lon, o); if (p && p.catch) p.catch(function () { /* cancelled by the pilot */ });
return p;
}
D.addEventListener('click', function (e) {
var b = e.target && e.target.closest && e.target.closest('[data-p-grid-fly]'); if (!b) return;
var a = b.getAttribute('data-p-grid-fly').split(',').map(Number);
e.preventDefault(); fly(a[0], a[1], a[2], b.getAttribute('data-p-grid-label') || '', a.length > 3 ? a[3] : null);
});
// ---- S09 panel: layers / find / nearest
var body = null, tab = 'layers';
function panelHtml() {
return '<div class="p-grid">' +
'<div class="p-grid-tabs" role="tablist">' +
['layers:Layers', 'find:Find', 'near:Nearest'].map(function (t) { var p = t.split(':'); return '<button type="button" role="tab" class="p-grid-tab" data-p-grid-tab="' + p[0] + '" aria-selected="' + (p[0] === tab) + '">' + p[1] + '</button>'; }).join('') +
'</div>' +
'<div class="p-grid-pane" data-p-grid-pane="layers"><ul class="p-grid-tog"></ul>' +
'<p class="p-grid-src">Lines and substations: GridAtlas atlas-v9 release, Data © ' + OSM_LINK + ' (ODbL). Each layer loads only when switched on. Lines are drawn along mapped vertices; far away only the higher voltages draw.</p></div>' +
'<div class="p-grid-pane" data-p-grid-pane="find" hidden>' +
'<div class="p-grid-kind" role="radiogroup" aria-label="Find what"><button type="button" class="p-grid-chip" data-p-grid-what="subs" aria-pressed="true">Substations</button><button type="button" class="p-grid-chip" data-p-grid-what="lines" aria-pressed="false">Lines</button></div>' +
'<label class="p-grid-lbl" for="p-grid-q">Name or operator</label><input id="p-grid-q" class="p-grid-q" type="search" autocomplete="off" placeholder="e.g. Enderby, Drax, UK Power Networks">' +
'<div class="p-grid-chips" aria-label="Voltage class">' + CLS.map(function (c) { return '<button type="button" class="p-grid-chip" data-p-grid-cls="' + c + '" aria-pressed="false"><i style="background:' + CLS_COL[c] + '"></i>' + c + '</button>'; }).join('') + '</div>' +
'<p class="p-grid-dim p-grid-fstat" role="status"></p><ol class="p-grid-list p-grid-fres"></ol></div>' +
'<div class="p-grid-pane" data-p-grid-pane="near" hidden><p class="p-grid-dim p-grid-nstat" role="status"></p><ol class="p-grid-list p-grid-nres"></ol></div>' +
'</div>';
}
function q(sel) { return body ? body.querySelector(sel) : null; }
function renderToggles() {
var ul = q('.p-grid-tog'); if (!ul) return;
ul.innerHTML = ORDER.map(function (k) {
var s = st[k], m = K[k], txt = s.state === 'ready' ? s.count.toLocaleString() + (k === 'subs' ? ' sites' : ' sections') :
s.state === 'loading' ? 'loading ' + m.mb.toFixed(1) + ' MB…' : s.state === 'failed' ? 'could not load' : s.state === 'offline' ? 'offline: not loaded' :
m.n.toLocaleString() + ' · ' + m.mb.toFixed(1) + ' MB';
return '<li><button type="button" class="p-grid-row" role="switch" aria-checked="' + !!on[k] + '" data-p-grid-on="' + k + '">' +
'<i class="p-grid-sw' + (k === 'subs' ? ' p-grid-sq' : '') + '" style="background:' + m.col + '"></i><span>' + esc(m.title) + '</span><small>' + esc(txt) + '</small></button>' +
(s.state === 'failed' ? '<button type="button" class="p-grid-btn p-grid-retry" data-p-grid-retry="' + k + '">Retry</button>' : '') + '</li>';
}).join('');
}
function setOn(k, val) {
on[k] = val; save();
if (val) load(k).catch(function () { /* note shown */ });
var anyLine = ['400', '275', '132', '66'].some(function (x) { return on[x]; });
if (P.setLayerVisible) { P.setLayerVisible('grid', anyLine); P.setLayerVisible('grid-subs', !!on.subs); }
renderToggles(); legend();
}
var what = 'subs', clsOn = {};
function bindPanel() {
body.addEventListener('click', function (e) {
var t = e.target.closest ? e.target.closest('button') : null; if (!t) return;
if (t.hasAttribute('data-p-grid-tab')) {
tab = t.getAttribute('data-p-grid-tab');
Array.prototype.forEach.call(body.querySelectorAll('[data-p-grid-tab]'), function (b) { b.setAttribute('aria-selected', String(b === t)); });
Array.prototype.forEach.call(body.querySelectorAll('[data-p-grid-pane]'), function (p) { p.hidden = p.getAttribute('data-p-grid-pane') !== tab; });
if (tab !== 'layers') load('subs').catch(function () {});
if (tab === 'find') refreshFind(); if (tab === 'near') nearList(true);
} else if (t.hasAttribute('data-p-grid-on')) { var k = t.getAttribute('data-p-grid-on'); setOn(k, !on[k]); }
else if (t.hasAttribute('data-p-grid-retry')) { var r = t.getAttribute('data-p-grid-retry'); load(r, true).catch(function () {}); }
else if (t.hasAttribute('data-p-grid-cls')) { var c = t.getAttribute('data-p-grid-cls'); clsOn[c] = !clsOn[c]; t.setAttribute('aria-pressed', String(!!clsOn[c])); if (what === 'lines' && clsOn[c] && K[c]) load(c).catch(function () {}); refreshFind(); }
else if (t.hasAttribute('data-p-grid-what')) {
what = t.getAttribute('data-p-grid-what');
Array.prototype.forEach.call(body.querySelectorAll('[data-p-grid-what]'), function (b) { b.setAttribute('aria-pressed', String(b === t)); });
refreshFind();
} else if (t.hasAttribute('data-p-grid-jump')) {
var a = t.getAttribute('data-p-grid-jump').split(':');
if (a[0] === 's') { var i = +a[1]; fly(SB.lat[i], SB.lon[i], SB.cls[i], SB.name[i]); P.emit('grid:select', { name: SB.name[i], kv: SB.cls[i], lat: SB.lat[i], lon: SB.lon[i] }); }
else jumpLine(a[1], +a[2]);
}
});
var inp = q('#p-grid-q'), tm = 0;
inp.addEventListener('focus', function () { load('subs').catch(function () {}); });
inp.addEventListener('input', function () { clearTimeout(tm); tm = setTimeout(refreshFind, 120); });
}
// ---- S12 / S13 / S14 find
function rank(name, op, ql) {
if (!ql) return 5;
if (name.indexOf(ql) === 0) return 0;
var i = name.indexOf(ql); if (i > 0) return /[\s\-(/]/.test(name.charAt(i - 1)) ? 1 : 2;
return op.indexOf(ql) >= 0 ? 3 : -1;
}
function findSubs(ql, cls, max) {
if (!SB) return []; var out = [], S = SB, anyC = cls.length > 0;
for (var i = 0; i < S.n; i++) {
if (anyC && cls.indexOf(S.cls[i]) < 0) continue;
if (!S.named[i] && ql) continue;
var r = rank(S.lname[i], S.lop[i], ql); if (r < 0) continue;
out.push({ i: i, r: r });
}
out.sort(function (a, b) { return a.r - b.r || S.cls[b.i] - S.cls[a.i] || S.named[b.i] - S.named[a.i] || (S.name[a.i] < S.name[b.i] ? -1 : 1); });
return { total: out.length, rows: out.slice(0, max || 30) };
}
var circuits = {}; // kind -> [{name, lname, lop, li (longest section), n}]
function circuitsOf(k) {
if (circuits[k] || !LN[k]) return circuits[k] || [];
var m = {}, Lk = LN[k];
Lk.lines.forEach(function (L, li) {
if (!L.name) return; var key = L.name.toLowerCase();
var c = m[key]; if (!c) c = m[key] = { name: L.name, lname: key, lop: (L.op || '').toLowerCase(), li: li, n: 0, kind: k };
c.n++; if (L.n > Lk.lines[c.li].n) c.li = li;
});
return (circuits[k] = Object.keys(m).map(function (x) { return m[x]; }));
}
function findLines(ql, cls, max) {
var kinds = ['400', '275', '132', '66'].filter(function (k) { return !cls.length || cls.indexOf(+k) >= 0; }), out = [];
kinds.forEach(function (k) { circuitsOf(k).forEach(function (c) { var r = rank(c.lname, c.lop, ql); if (r >= 0) out.push({ c: c, r: r }); }); });
out.sort(function (a, b) { return a.r - b.r || +b.c.kind - +a.c.kind || (a.c.name < b.c.name ? -1 : 1); });
return { total: out.length, rows: out.slice(0, max || 30), kinds: kinds };
}
function jumpLine(k, li) {
var Lk = LN[k]; if (!Lk) return; var L = Lk.lines[li], ll = Lk.ll, mid = lineMid(L, ll);
var hdg = bearing(ll[mid.a * 2], ll[mid.a * 2 + 1], ll[mid.b * 2], ll[mid.b * 2 + 1]);
P.emit('grid:select', { name: L.name, kv: +k, lat: mid.lat, lon: mid.lon });
return fly(mid.lat, mid.lon, +k, L.name, hdg);
}
function refreshFind() {
var ol = q('.p-grid-fres'), stt = q('.p-grid-fstat'); if (!ol || tab !== 'find') return;
var ql = (q('#p-grid-q').value || '').trim().toLowerCase(), cls = CLS.filter(function (c) { return clsOn[c]; });
var html = '', msg = '';
if (what === 'subs') {
if (!SB) { msg = st.subs.state === 'failed' ? 'Substations could not load.' : P.offline ? 'Offline: substations not loaded.' : 'Loading 5,800 substations…'; }
else {
var r = findSubs(ql, cls, 30);
msg = r.total.toLocaleString() + ' match' + (r.total === 1 ? '' : 'es') + (r.total > 30 ? ', showing 30' : '');
html = r.rows.map(function (o) { var i = o.i; return '<li><button type="button" class="p-grid-jump" data-p-grid-jump="s:' + i + '"><i class="p-grid-sw p-grid-sq" style="background:' + CLS_COL[SB.cls[i]] + '"></i><span>' + esc(SB.name[i]) + '</span><small>' + esc(kvText(SB.volt[i])) + (SB.op[i] ? ' · ' + esc(SB.op[i]) : '') + '</small></button></li>'; }).join('');
}
} else {
var f = findLines(ql, cls, 30), missing = f.kinds.filter(function (k) { return !LN[k]; });
msg = f.total.toLocaleString() + ' named circuit' + (f.total === 1 ? '' : 's') + (f.total > 30 ? ', showing 30' : '') +
(missing.length ? '. Not loaded yet: ' + missing.map(function (k) { return k + ' kV'; }).join(', ') + ' (tap its chip or switch it on in Layers).' : '');
html = f.rows.map(function (o) { var c = o.c; return '<li><button type="button" class="p-grid-jump" data-p-grid-jump="l:' + c.kind + ':' + c.li + '"><i class="p-grid-sw" style="background:' + K[c.kind].col + '"></i><span>' + esc(c.name) + '</span><small>' + c.kind + ' kV · ' + c.n + ' mapped section' + (c.n === 1 ? '' : 's') + '</small></button></li>'; }).join('');
}
stt.textContent = msg; ol.innerHTML = html;
}
// ---- S15 nearest
function nearest(lat, lon, n, minKv) {
if (!SB) return []; var S = SB, cand = [], kx = Math.cos(lat * rad);
for (var i = 0; i < S.n; i++) { if (minKv && S.cls[i] < minKv) continue; var dx = (S.lon[i] - lon) * kx, dy = S.lat[i] - lat; cand.push([dx * dx + dy * dy, i]); }
cand.sort(function (a, b) { return a[0] - b[0]; });
return cand.slice(0, n || 10).map(function (c) {
var i = c[1], d = P.dist(lat, lon, S.lat[i], S.lon[i]);
return { i: i, name: S.name[i], operator: S.op[i], kv: S.cls[i], voltage: S.volt[i], lat: S.lat[i], lon: S.lon[i], d: d, brg: bearing(lat, lon, S.lat[i], S.lon[i]) };
}).sort(function (a, b) { return a.d - b.d; });
}
var lastNear = 0;
function nearList(force) {
var ol = q('.p-grid-nres'), stt = q('.p-grid-nstat'); if (!ol || tab !== 'near' || !P.camLL) return;
var now = performance.now(); if (!force && now - lastNear < 500) return; lastNear = now;
if (!SB) { stt.textContent = P.offline ? 'Offline: substations not loaded.' : 'Loading 5,800 substations…'; return; }
var c = P.camLL(), r = nearest(c.lat, c.lon, 10);
stt.textContent = 'Nearest 33 kV+ substations to you (' + c.lat.toFixed(4) + ', ' + c.lon.toFixed(4) + ')';
var dirs = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
ol.innerHTML = r.map(function (o) { return '<li><button type="button" class="p-grid-jump" data-p-grid-jump="s:' + o.i + '"><i class="p-grid-sw p-grid-sq" style="background:' + CLS_COL[o.kv] + '"></i><span>' + esc(o.name) + '</span><small>' + fmtD(o.d) + ' ' + dirs[Math.round(o.brg / 45) % 8] + ' · ' + esc(kvText(o.voltage)) + '</small></button></li>'; }).join('');
}
// ---- S17 HUD: nearest grid asset + legend
var lastHud = 0;
function legend() {
return ORDER.filter(function (k) { return on[k]; }).map(function (k) { return '<i class="p-grid-sw' + (k === 'subs' ? ' p-grid-sq' : '') + '" style="background:' + K[k].col + '" title="' + esc(K[k].title) + '"></i>' + (k === 'subs' ? 'sub' : k); }).join(' ');
}
function hudTick() {
var now = performance.now(); if (now - lastHud < 500 || !P.camLL) return; lastHud = now;
var lg = legend(), txt = '';
if (SB && on.subs) { var c = P.camLL(), r = nearest(c.lat, c.lon, 1)[0]; if (r) txt = esc(r.name) + ' · ' + r.kv + ' kV class · ' + fmtD(r.d); }
P.hud('status:grid', lg || txt ? '<span class="p-grid-hud">' + (lg ? '<span class="p-grid-leg">' + lg + '</span>' : '') + (txt ? ' <span>Grid: ' + txt + '</span>' : '') + '</span>' : '');
}
// ---- events for other modules (W07 vicinity, W09 nav): no extra globals
P.on('grid:query', function (d) {
if (!d || typeof d.reply !== 'function') return;
// query contract v2: optional radius in metres (d.radiusM / d.maxM); failures reply with meta.state 'error'
var n = d.n || 10, rM = +d.radiusM || +d.maxM || 0;
load('subs').then(function () {
var got = nearest(d.lat, d.lon, n, d.minKv || 0);
var list = got.filter(function (o) { return !rM || o.d <= rM; });
d.reply(list.map(function (o) { return { name: o.name, operator: o.operator, kv: o.kv, voltage: o.voltage, lat: o.lat, lon: o.lon, d: o.d }; }), { loaded: true, state: 'ok', capped: got.length >= n && list.length === got.length, radiusM: rM });
}, function (e) { d.reply([], { loaded: false, state: 'error', error: String(e && e.message || e) }); });
});
// ---- wire up
P.addLayer(lineLayer); P.addLayer(subLayer);
body = P.panel('grid', panelHtml(), { title: 'Grid', icon: 'kV' });
if (body) { bindPanel(); renderToggles(); }
P.onFrame(function () { hudTick(); nearList(false); });
function start() {
if (P.setLayerVisible) { P.setLayerVisible('grid', ['400', '275', '132', '66'].some(function (x) { return on[x]; })); P.setLayerVisible('grid-subs', !!on.subs); }
if (P.offline) { ORDER.forEach(function (k) { if (on[k]) st[k].state = 'offline'; }); renderToggles(); return; }
var go = function () { ORDER.forEach(function (k) { if (on[k]) load(k).catch(function () {}); }); };
if (W.requestIdleCallback) W.requestIdleCallback(go, { timeout: 2500 }); else setTimeout(go, 1200);
}
if (P.ready) P.ready(start); else start();
// test hooks (on the layer objects, not globals)
lineLayer._api = { src: src, load: load, nearest: nearest, findSubs: findSubs, findLines: findLines, jumpLine: jumpLine, setOn: setOn, state: st, on: on,
subs: function () { return SB; }, lines: function (k) { return LN[k]; }, endSub: endSub, lineCard: lineCard, subCard: subCard, kvText: kvText };
})();Pilot Lightning
A style sheet in the theme folder of Cosmic.
rendercosmic / tools/explore/theme/pilot-lightning.css · lines 1–37 of 37 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Downstream impact
- Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
- What it achieves
- W08 lightning panel (all classes prefixed p-lightning-).
- Why it matters
- Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
- Application
- cosmic · tools/explore/theme · style sheet
- Uses
- none found
- Used by
- loaded by Pilot (stylesheet)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-lightning.css:1-37 · blob d95eb4843483d9536f46bc63425cda940eff5b48 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* pilot-lightning.css - W08 lightning panel (all classes prefixed p-lightning-) */
.p-lightning-toggle,.p-lightning-btn,.p-lightning-chip,.p-lightning-row{min-height:44px;font:inherit;color:inherit;cursor:pointer;border-radius:8px;border:1px solid rgba(255,255,255,.22);background:rgba(255,255,255,.06);box-sizing:border-box;max-width:100%}
.p-lightning-toggle{display:block;width:100%;margin:0 0 8px;font-weight:700;text-align:left;padding:0 12px}
.p-lightning-toggle[aria-pressed="true"]{background:rgba(255,225,77,.18);border-color:#ffe14d}
.p-lightning-prox[aria-pressed="true"]{background:rgba(127,231,255,.16);border-color:#7fe7ff}
.p-lightning-btn{padding:0 12px;margin:4px 0;white-space:normal;text-align:left}
.p-lightning-chips{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0}
.p-lightning-chip{min-width:64px;padding:0 10px}
.p-lightning-chip[aria-pressed="true"]{background:rgba(255,225,77,.2);border-color:#ffe14d}
.p-lightning-list{list-style:none;margin:0 0 8px;padding:0}
.p-lightning-row{display:block;width:100%;margin:3px 0;padding:0 10px;text-align:left;white-space:normal;overflow-wrap:anywhere}
.p-lightning-h{font-size:14px;margin:12px 0 4px}
.p-lightning-dim,.p-lightning-src{opacity:.75;font-size:12px;margin:4px 0;overflow-wrap:anywhere}
.p-lightning-obs,.p-lightning-nofault{font-size:12px;margin:4px 0;color:#ffe9a0}
.p-lightning-near{margin:6px 0}
.p-lightning-fresh{font-size:12px;margin:4px 0}
.p-lightning-stale{color:#ffb38a;font-weight:700}
.p-lightning-archive{color:var(--dim,#a6adbb);font-style:italic}
.p-lightning-err{color:#ffb38a;font-size:13px}
.p-lightning-legend{height:10px;border-radius:5px;margin:4px 0 8px;background:linear-gradient(90deg,#5a5590,#6f68a8,#8d7fd0,#a066ff,#c23cff,#e01cff)}
.p-lightning-rules{font-size:12px;margin:10px 0}
.p-lightning-rules summary{min-height:44px;line-height:44px;cursor:pointer}
.p-lightning-rules ul{padding-left:18px;margin:4px 0}
.p-lightning-title{font-size:15px;margin:0 0 8px;line-height:1.3}
.p-lightning-link{display:inline-block;min-height:44px;line-height:44px;padding:0 6px;color:#83d9ff;text-decoration:underline}
.p-lightning-subs{padding-left:20px;margin:6px 0;overflow-wrap:anywhere}
.p-lightning-subs li{margin:4px 0}
.p-lightning-ga{font-family:ui-monospace,monospace;font-size:12px}
.p-lightning-brg{font-size:12px;opacity:.85}
.p-lightning-progress{font-size:12px;color:#ffe9a0}
.p-lightning-prov{font-size:12px;margin:8px 0}
.p-lightning-prov summary{min-height:44px;line-height:44px;cursor:pointer}
.p-lightning-prov a{color:#83d9ff}
.p-lightning-form{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin:8px 0}
.p-lightning-form label{flex:1 1 100%;font-size:12px}
.p-lightning-input{flex:1 1 180px;min-width:0;min-height:44px;font:inherit;color:inherit;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.22);border-radius:8px;padding:0 10px;box-sizing:border-box}
.p-lightning-chip[disabled]{opacity:.45;cursor:default}