GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/theme

Pilot Subfind and 1 more file

A JavaScript file in the theme folder of Cosmic that maps grid substations, postcodes, 33kV and A roads, and uses data from the GridAtlas repository.

515 lines of JavaScript and CSS from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1152 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Pilot Subfind render · cosmic / tools/explore/theme/pilot-subfind.js lines 1–463
  2. Pilot Ticker render · cosmic / tools/explore/theme/pilot-ticker.css lines 1–52

Pilot Subfind

A JavaScript file in the theme folder of Cosmic that maps grid substations, postcodes, 33kV and A roads, and uses data from the GridAtlas repository.

rendercosmic / tools/explore/theme/pilot-subfind.js · lines 1–463 of 463 · Entry point · pattern renderRecent (shared by 2 files)

What it does
It maps grid substations, postcodes, 33kV and A roads. Defines 50 functions or classes, including geo, distM, bearing, kvList, norm. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 33kV, 32.5kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: postcodes, 33kV, A roads, 32.5kV.
Inputs & outputs
In: data source: gridatlas data; browser storage (getItem); form fields (user input). Out: browser storage (setItem). Voltage levels named: 33kV, 32.5kV.
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
It marks ties (`markTies`), sets msg (`setMsg`) and loads grid (`loadGridFor`). Pilot module "subfind" (AZIMUTH-47, SUBFINDER): find substations by postcode, town, place or substation name. Its code works with 33 kV and 32.5 kV. It responds to submit, click and keydown 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 — Atlas Page (estate URL), GridAtlas — Index Page (estate URL)
Used by
loaded by Pilot (script src)
Produces
geo, distM, bearing, kvList, norm, caveat, level, topLevel, kvText, compass, fmtD, okLL
Defines here
geo, distM, bearing, kvList, norm, caveat, level, topLevel, kvText, compass, fmtD, okLL, byDist, atlasLink, hasModule, gaBase, sub, gridAll, ukpnNear, fin, recent, remember, measure, kvOn, compute, markTies, setMsg, loadGridFor, loadUkpnFor, setOrigin
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-subfind.js:1-463 · blob f7a780f36c35fce5bbdd3f992918e9fe535d992a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
/* Pilot module "subfind" (AZIMUTH-47, SUBFINDER): find substations by postcode, town, place or substation name.
   Licence: Apache-2.0 (Ventus Ltd). Built only against window.PILOT (/tmp/vk/pilot200/CONTRACT.md v1).

   Nothing here is a new engine. It joins what Pilot already has:
   - Place search: PILOT.goto.classify / PILOT.goto.search (pilot-goto.js: postcodes.io, then Nominatim / OpenStreetMap,
     typed lat/lon and OS grid references). Not duplicated here.
   - Substations 33 kV and above: GridAtlas atlas-v9 grid_substations.geojson (OpenStreetMap ODbL), the file pilot-grid.js
     loads, read through the same memoised PILOT.data.fetchJSON URL (no second download) in file order, so ties keep the
     engine's order. Nothing is bundled (photon rule).
   - UKPN secondary substations: the 'ukpn:query' event (pilot-ukpn.js). Routes: the 'nav:route' event (pilot-nav.js,
     straight air legs). Flight: PILOT.flyTo (core FAST arc for long hops; instant under reduced motion).
   - All maths from PILOT.estate (pilot-estate.js, vendored verbatim): geo.distM / geo.bearing (R_ATLAS 6378.137 km),
     voltagesKv (Ventus Grid Engine), nearest.normalise (the GridAtlas substation-name key), STRAIGHT_LINE_CAVEAT.
   - "Open in GridAtlas": the Pipeline News MAP link format, buildAtlasV9DeepLink
     (pipelinenews@ce0a1a16f0e1 .../202609040044-atlas-pointer-deep-link.mjs: receiver https://ventusltd.github.io/gridatlas/atlas/,
     parameter order repd_ref, project, technology, capacity_mw, latitude, longitude, zoom=12). A substation has no
     repd_ref, technology or capacity, so those are left out (never invented); GridAtlas measures a link with usable
     coordinates first (gridatlas atlas/modules/202611222130-sld-without-layout.js deepLinkPlan: MEASURE_LINK_FIRST).
   Unknown is shown as unknown, never as zero. Every result carries the straight-line screening caveat. */
(function () {
  'use strict';
  if (typeof window === 'undefined' || !window.PILOT) return;
  var P = window.PILOT, D = document, W = window;
  P.module('subfind', { version: '1', owner: 'AZIMUTH-47' });
  var esc = P.esc || function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return '&#' + c.charCodeAt(0) + ';'; }); };

  var KV = [400, 275, 132, 66, 33];
  var KV_COL = { 400: '#4080ff', 275: '#ff4d4d', 132: '#33e666', 66: '#ffab2e', 33: '#d9d9d9', u: '#8a93a3', ukpn: '#35e6bb' };
  var RADII = [5, 10, 25];
  var LIMIT = 20, NAMED_MAX = 8, UKPN_N = 200, UKPN_DEFAULT_KM = 10, RKEY = 'p-subfind-recent';
  var RECEIVER = 'https://ventusltd.github.io/gridatlas/atlas/';
  var REL = 'atlas/releases/202608300453-atlas-v9/data/', SUBS_FILE = 'grid_substations.geojson';
  var SUBS_CREDIT = 'Substations: Data © OpenStreetMap contributors (ODbL), via GridAtlas atlas-v9';
  var LEAD = 'Screening only: straight-line distance, not a road or cable route, not a connection offer, not capacity.';

  // ---------------------------------------------------------------- maths (PILOT.estate; core fallbacks only if it is absent)
  function geo() { return P.estate && P.estate.geo; }
  function distM(a, b, c, d) { var g = geo(); return g ? g.distM(a, b, c, d) : P.dist(a, b, c, d); }
  function bearing(a, b, c, d) { var g = geo(); return g ? g.bearing(a, b, c, d) : P.bearing(a, b, c, d); }
  function kvList(raw) {
    if (P.estate && P.estate.voltagesKv) return P.estate.voltagesKv({ voltage: raw });
    return [];   // without the engine's parser the voltage is unknown, not guessed
  }
  function norm(s) {
    if (P.estate && P.estate.nearest) return P.estate.nearest.normalise(s);
    return String(s || '').toUpperCase().replace(/[^A-Z0-9 ]/g, ' ').split(/\s+/).filter(Boolean).join(' ');
  }
  function caveat() {
    var g = geo();
    return LEAD + ' ' + (g ? g.caveatText(['distance', 'substation', 'coverage']) + ' ' + (g.EARTH_NOTE || '') : 'Absence from a mapped layer is not absence on the ground.');
  }
  // voltage level a value belongs to, for the chips (the grid layer's own class breaks, applied to each voltage in kV)
  function level(kv) { return kv >= 350 ? 400 : kv >= 200 ? 275 : kv >= 100 ? 132 : kv >= 50 ? 66 : kv >= 20 ? 33 : 0; }
  function topLevel(kvs) { return kvs.length ? level(kvs[0]) || 'u' : 'u'; }
  function kvText(kvs) {
    if (!kvs || !kvs.length) return 'voltage unknown';
    return kvs.map(function (k) { return k >= 1 ? String(+k.toFixed(1)) : String(+k.toFixed(3)); }).join(' / ') + ' kV';
  }
  var PTS = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
  function compass(b) { return PTS[Math.round(((b % 360) + 360) % 360 / 22.5) % 16]; }
  function fmtD(m) { return m < 1000 ? Math.round(m) + ' m' : m < 10000 ? (m / 1000).toFixed(2) + ' km' : (m / 1000).toFixed(1) + ' km'; }
  function okLL(la, lo) { return isFinite(la) && isFinite(lo) && Math.abs(la) <= 90 && Math.abs(lo) <= 180 && !(Math.abs(la) < 1e-9 && Math.abs(lo) < 1e-9); }
  function byDist(a, b) { return a.m - b.m || a.ix - b.ix; }   // ties: engine order (file order), never by name

  // ---------------------------------------------------------------- GridAtlas link (Pipeline News MAP format, see header)
  function atlasLink(r) {
    if (!okLL(r.lat, r.lon)) return '';
    var u = new URL(RECEIVER);
    var name = String(r.name || '').replace(/\s+/g, ' ').trim();
    if (name && !/[\u0000-\u001f\u007f]/.test(name)) u.searchParams.set('project', name);
    u.searchParams.set('latitude', String(r.lat));
    u.searchParams.set('longitude', String(r.lon));
    u.searchParams.set('zoom', '12');
    return u.href;
  }

  // ---------------------------------------------------------------- data
  function hasModule(name) { try { return (P.modules() || []).some(function (m) { return m.name === name; }); } catch (e) { return false; } }
  function gaBase() {   // ?ga= override for local tests: same origin or localhost only (as pilot-grid.js)
    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) {} }
    return ((P.data && P.data.GA) || 'https://ventusltd.github.io/gridatlas/') + REL;
  }
  // Scope as the GridAtlas engine (and PILOTNAV M2 substation-finder.mjs MIN_KV): 33 kV and above. A site whose recorded
  // voltages are all below 32.5 kV is outside that scope and left out; a site with NO recorded voltage stays, as unknown.
  var MIN_KV = 33;
  function sub(name, operator, raw, lat, lon) {
    var all = kvList(raw), kvs = all.filter(function (v) { return v >= MIN_KV - 0.5; }), nm = String(name || '').trim();
    if (all.length && !kvs.length) return null;
    return { kind: 'grid', name: nm || 'Substation (unnamed in OpenStreetMap)', named: !!nm && !/unnamed/i.test(nm), key: norm(nm), operator: String(operator || '').trim(),
      raw: raw || '', kvs: kvs, lv: topLevel(kvs), lat: +lat, lon: +lon, id: 'osm-sub:' + (+lat).toFixed(5) + ',' + (+lon).toFixed(5) };
  }
  // Read the published file in FILE ORDER, so equal distances keep the order the GridAtlas engine gives them (its nearest
  // search scans the located list in file order and sorts stably by km; PILOTNAV M2 keeps that order too). The URL and
  // PILOT.data.fetchJSON memo are the ones pilot-grid.js uses, so with the grid layer loaded this is no second download.
  var gridP = null;
  function gridAll() {
    if (gridP) return gridP;
    if (P.offline) return Promise.reject(new Error('offline'));
    gridP = P.data.fetchJSON(gaBase() + SUBS_FILE, { cache: true, timeout: 30000 }).then(function (gj) {
      if (P.credit && !hasModule('grid')) P.credit('subfind', SUBS_CREDIT);   // the grid layer already credits this file
      var out = [];
      ((gj && gj.features) || []).forEach(function (f, i) {
        if (!f || !f.geometry || f.geometry.type !== 'Point') return;
        var pr = f.properties || {}, c = f.geometry.coordinates, s = sub(pr.name, pr.operator, pr.voltage, c[1], c[0]);
        if (s && okLL(s.lat, s.lon)) { s.ix = i; out.push(s); }
      });
      if (!out.length) throw new Error('no substations in the published file');
      return out;
    });
    gridP.catch(function () { gridP = null; });   // a failure can be retried
    return gridP;
  }
  function ukpnNear(lat, lon, rKm) {
    return new Promise(function (resolve) {
      if (!hasModule('ukpn')) return resolve({ state: 'missing', list: [] });
      var done = false, t = setTimeout(function () { fin({ state: 'error', list: [], error: 'no answer' }); }, 40000);
      function fin(v) { if (!done) { done = true; clearTimeout(t); resolve(v); } }
      try {
        P.emit('ukpn:query', { lat: lat, lon: lon, n: UKPN_N, radiusM: rKm * 1000, maxM: rKm * 1000, reply: function (list, meta) {
          if (!Array.isArray(list) || (meta && meta.state === 'error')) return fin({ state: 'error', list: [], error: (meta && meta.error) || 'failed' });
          fin({ state: 'ok', capped: !!(meta && meta.capped), list: list.filter(function (s) { return s && okLL(+s.lat, +s.lon); }).map(function (s, k) {
            var kv = s.voltage ? String(s.voltage) : '';
            return { kind: 'ukpn', name: 'UKPN secondary ' + s.id, named: true, operator: 'UK Power Networks' + (s.dno ? ' (' + s.dno + ')' : ''),
              raw: kv, kvs: [], kvLabel: kv || 'voltage unknown', lv: 'ukpn', lat: +s.lat, lon: +s.lon, id: 'ukpn:' + s.id, ix: 1e9 + k };
          }) });
        } });
      } catch (e) { fin({ state: 'error', list: [], error: String(e && e.message || e) }); }
    });
  }

  // ---------------------------------------------------------------- state
  var S = { q: '', serial: 0, busy: false, origin: null, alts: [], named: null, namedErr: '', grid: null, gridErr: '', ukpn: null,
            kv: {}, ukpnOn: false, rKm: 0, msg: '', msgKind: '', rows: [], hidden: 0 };
  function recent() { try { var a = JSON.parse(localStorage.getItem(RKEY) || '[]'); return Array.isArray(a) ? a.filter(function (r) { return r && typeof r.q === 'string'; }).slice(0, 8) : []; } catch (e) { return []; } }
  function remember(r) {
    try { var a = recent().filter(function (x) { return x.q.toLowerCase() !== r.q.toLowerCase(); }); a.unshift(r); localStorage.setItem(RKEY, JSON.stringify(a.slice(0, 8))); } catch (e) { /* private mode */ }
  }

  function measure(list, o) { return list.map(function (s) { var r = Object.assign({}, s); r.m = distM(o.lat, o.lon, s.lat, s.lon); r.brg = bearing(o.lat, o.lon, s.lat, s.lon); return r; }); }
  function kvOn() { return KV.filter(function (k) { return S.kv[k]; }); }
  // the ranked list shown for the current origin and filters
  function compute() {
    var rows = [], ks = kvOn(), rM = S.rKm * 1000, hidden = 0;
    var wantGrid = ks.length > 0 || !S.ukpnOn;   // UKPN chip alone = secondaries only; with kV chips = both
    if (S.grid && wantGrid) S.grid.forEach(function (r) {
      if (rM && r.m > rM) return;
      if (ks.length && !r.kvs.some(function (k) { return ks.indexOf(level(k)) >= 0; })) { if (!r.kvs.length) hidden++; return; }
      rows.push(r);
    });
    if (S.ukpnOn && S.ukpn && S.ukpn.state === 'ok') S.ukpn.list.forEach(function (r) { if (!rM || r.m <= rM) rows.push(r); });
    rows.sort(byDist);
    S.total = rows.length; S.hidden = hidden; S.rows = rows.slice(0, LIMIT);
    markTies(S.rows);
  }
  // equal straight-line distances are flagged, never hidden; order within a tie is the engine's (file order)
  function markTies(rows) { rows.forEach(function (r, i) { r.tie = (i > 0 && rows[i - 1].m === r.m) || (i + 1 < rows.length && rows[i + 1].m === r.m); }); return rows; }
  function setMsg(t, kind) { S.msg = t || ''; S.msgKind = kind || ''; }

  function loadGridFor(o, my) {
    return gridAll().then(function (list) { if (my !== S.serial) return; S.grid = measure(list, o).sort(byDist); S.gridErr = ''; },
      function (e) { if (my !== S.serial) return; S.grid = null; S.gridErr = String(e && e.message || e); });
  }
  function loadUkpnFor(o, my) {
    if (!S.ukpnOn) { S.ukpn = null; return Promise.resolve(); }
    return ukpnNear(o.lat, o.lon, S.rKm || UKPN_DEFAULT_KM).then(function (u) { if (my !== S.serial) return; u.list = measure(u.list, o); u.rKm = S.rKm || UKPN_DEFAULT_KM; S.ukpn = u; });
  }
  function setOrigin(o, opts) {
    var my = opts && opts.serial || ++S.serial;
    S.origin = { lat: +o.lat, lon: +o.lon, label: o.label || (o.lat.toFixed(5) + ', ' + o.lon.toFixed(5)), sub: o.sublabel || '', provider: o.provider || '' };
    S.busy = true; render();
    if (P.setLayerVisible) P.setLayerVisible('subfind', true);
    return Promise.all([loadGridFor(S.origin, my), loadUkpnFor(S.origin, my)]).then(function () {
      if (my !== S.serial) return;
      if (S.named) S.named = markTies(measure(S.named, S.origin).sort(function (a, b) { return a.rank - b.rank || byDist(a, b); }));
      S.busy = false; compute(); render(); publish();
    });
  }

  function matchNames(list, text) {
    var q = norm(text); if (!q) return [];
    var out = [];
    list.forEach(function (s) {
      if (!s.named || !s.key) return;
      var r = s.key === q ? 0 : s.key.indexOf(q + ' ') === 0 ? 1 : s.key.indexOf(q) === 0 ? 2 : (' ' + s.key + ' ').indexOf(' ' + q + ' ') >= 0 ? 3 : s.key.indexOf(q) >= 0 ? 4 : -1;
      if (r >= 0) { var c = Object.assign({}, s); c.rank = r; out.push(c); }
    });
    return out;
  }
  function failText(t) { return /could not be reached|unavailable|failed|timed? ?out|error|offline/i.test(t || ''); }

  function run(text) {
    text = String(text == null ? '' : text).trim().replace(/\s+/g, ' ');
    var my = ++S.serial;
    if (P.setLayerVisible) P.setLayerVisible('subfind', false);
    S.q = text; S.named = null; S.namedErr = ''; S.alts = []; S.origin = null; S.grid = null; S.gridErr = ''; S.ukpn = null; S.rows = []; S.total = 0;
    if (text.length < 2) { S.busy = false; setMsg('Type a postcode, town, place or substation name.', 'info'); render(); return Promise.resolve(); }
    S.busy = true; setMsg('Searching for “' + text + '”…', 'busy'); render();
    if (P.hash) try { P.hash('subfind', text); } catch (e) {}
    var k = P.goto && P.goto.classify ? P.goto.classify(text) : { kind: 'place', q: text };
    var namesP = k.kind === 'place' && norm(text)
      ? gridAll().then(function (list) { return { list: matchNames(list, text) }; }, function (e) { return { err: String(e && e.message || e) }; })
      : Promise.resolve(null);
    var placeP = P.goto && P.goto.search
      ? P.goto.search(text).then(function (o) { return o || { results: [] }; }, function (e) { return { results: [], msg: 'Place search failed (' + (e && e.message || e) + ').', failed: true }; })
      : Promise.resolve({ results: [], msg: 'Place search is not available here (the Go to module is not loaded); substation names still work.', failed: true });
    return Promise.all([namesP, placeP]).then(function (a) {
      if (my !== S.serial) return;
      var nm = a[0], pl = a[1] || { results: [] }, places = (pl.results || []).filter(function (r) { return r && okLL(+r.lat, +r.lon); });
      if (nm && nm.err) S.namedErr = nm.err;
      if (P.offline && !places.length) {
        S.busy = false;
        setMsg('Offline: place search (postcodes.io / OpenStreetMap) and substation data are not loaded here. Nearest substations: unknown, not zero.', 'error');
        render(); publish(); return;
      }
      var named = nm && nm.list ? nm.list : null;
      if (named) { var c = P.camLL ? P.camLL() : null; var ref = places[0] || c;
        S.named = ref ? measure(named, ref).sort(function (x, y) { return x.rank - y.rank || byDist(x, y); }) : named; }
      S.alts = places.slice(0, 5);
      var placeFail = pl.failed || (!places.length && failText(pl.msg));
      if (places.length) {
        setMsg(pl.msg && failText(pl.msg) ? pl.msg : '', pl.msg && failText(pl.msg) ? 'warn' : '');
        remember({ q: text, label: places[0].label, lat: +places[0].lat, lon: +places[0].lon, sub: places[0].sublabel || '' });
        return setOrigin(places[0], { serial: my });
      }
      S.busy = false;
      if (S.named && S.named.length) {
        setMsg(placeFail ? (pl.msg || 'Place search failed.') + ' Showing substation name matches only.' : '', placeFail ? 'warn' : '');
        remember({ q: text, label: text });
      } else if (placeFail || S.namedErr) {
        setMsg((placeFail ? (pl.msg || 'Place search failed.') : 'No place matched “' + text + '”.') +
          (S.namedErr ? ' Substation data could not load (' + S.namedErr + ').' : '') + ' Nearest substations: unknown, not zero.', 'error');
      } else {
        setMsg('No postcode, town, place or substation named “' + text + '” was found' + (pl.msg && !/^No /.test(pl.msg) ? ' (' + pl.msg + ')' : '') +
          '. Check the spelling, or try a postcode such as “SW1A 1AA”.', 'none');
      }
      render(); publish();
    });
  }
  function publish() {
    P.emit('subfind:results', { q: S.q, origin: S.origin, state: S.msgKind || (S.gridErr ? 'error' : 'ok'), total: S.total || 0,
      rows: S.rows.map(function (r) { return { kind: r.kind, name: r.name, kv: r.kvs, operator: r.operator, lat: r.lat, lon: r.lon, m: r.m, brg: r.brg, id: r.id }; }) });
  }

  // ---------------------------------------------------------------- actions
  function rowById(id) {
    var all = S.rows.concat(S.named || []);
    for (var i = 0; i < all.length; i++) if (all[i].id === id) return all[i];
    return null;
  }
  function phone() { return W.innerWidth < 900; }
  function fly(r) {
    if (phone() && P.closePanel) P.closePanel();
    P.card({ title: r.name, cap: r.kind === 'ukpn' ? 'UKPN SECONDARY SUBSTATION' : 'SUBSTATION (OSM VIA GRIDATLAS)', lat: r.lat, lon: r.lon, html: cardHtml(r) });
    return P.flyTo(r.lat, r.lon, { label: r.name, source: 'subfind', id: r.id, fast: 'auto', dist: 600, alt: 220 }).catch(function () {});
  }
  function route(r) {
    if (!hasModule('nav')) { P.note('Route there needs the SatNav module, which is not loaded here. Fly there still works.', 6000); return; }
    P.emit('nav:route', { lat: r.lat, lon: r.lon, name: r.name, source: 'subfind:' + r.kind, id: r.id });
    P.note('Route: straight air legs to ' + r.name + ' (not a road route; access unverified).', 6000);
    if (P.openPanel) P.openPanel('nav');
  }
  function flyOrigin() {
    var o = S.origin; if (!o) return;
    if (phone() && P.closePanel) P.closePanel();
    return P.flyTo(o.lat, o.lon, { label: o.label, source: 'subfind', fast: 'auto', dist: 1500, alt: 700 }).catch(function () {});
  }
  function cardHtml(r) {
    var o = S.origin, rel = o && r.m != null ? fmtD(r.m) + ' ' + compass(r.brg) + ' (' + Math.round(r.brg) + '°) from ' + esc(o.label) : '';
    var link = atlasLink(r);
    return '<p class="p-subfind-cmeta">' + esc(r.kind === 'ukpn' ? r.kvLabel : kvText(r.kvs)) + (r.operator ? ' · ' + esc(r.operator) : ' · operator not mapped') + '</p>' +
      (rel ? '<p class="p-subfind-cmeta">' + rel + ' (straight line)</p>' : '') +
      (link ? '<p><a class="p-subfind-link" href="' + esc(link) + '" target="_blank" rel="noopener">Open in GridAtlas</a></p>' : '') +
      '<p class="p-subfind-cav">' + esc(LEAD) + '</p>';
  }

  // ---------------------------------------------------------------- UI
  var body = null, ui = {};
  function panelHtml() {
    return '<form class="p-subfind-form" role="search" autocomplete="off">' +
      '<label class="p-subfind-sr" for="p-subfind-q">Find substations by postcode, town, place or substation name</label>' +
      '<div class="p-subfind-bar"><input id="p-subfind-q" class="p-subfind-q" type="search" enterkeyhint="search" spellcheck="false" autocapitalize="characters" ' +
      'placeholder="Postcode, town or substation" aria-describedby="p-subfind-hint">' +
      '<button type="submit" class="pbtn p-subfind-go">Find</button></div>' +
      '<p id="p-subfind-hint" class="p-subfind-dim">e.g. SW1A 1AA · Peterborough · Walpole · TL 2 9</p></form>' +
      '<div class="p-subfind-chips" role="group" aria-label="Filter by voltage or network">' +
      KV.map(function (k, i) { return '<button type="button" class="p-subfind-chip" data-p-subfind-kv="' + k + '" aria-pressed="false" aria-label="' + k + ' kV"><i style="background:' + KV_COL[k] + '"></i>' + k + (i === KV.length - 1 ? ' kV' : '') + '</button>'; }).join('') +
      '<button type="button" class="p-subfind-chip" data-p-subfind-ukpn aria-pressed="false" aria-label="UKPN secondary substations"><i style="background:' + KV_COL.ukpn + '"></i>UKPN<span class="p-subfind-wide"> secondaries</span></button></div>' +
      '<div class="p-subfind-chips" role="group" aria-label="Filter by straight-line distance">' +
      RADII.map(function (r) { return '<button type="button" class="p-subfind-chip" data-p-subfind-r="' + r + '" aria-pressed="false" aria-label="within ' + r + ' km"><span class="p-subfind-wide">within </span>' + r + ' km</button>'; }).join('') + '</div>' +
      '<p class="p-subfind-status" role="status" aria-live="polite"></p>' +
      '<div class="p-subfind-out"></div>' +
      '<div class="p-subfind-recent"></div>' +
      '<p class="p-subfind-cav p-subfind-foot"></p>';
  }
  function rowHtml(r, i) {
    var col = KV_COL[r.lv] || KV_COL.u, link = atlasLink(r);
    var kv = r.kind === 'ukpn' ? r.kvLabel : kvText(r.kvs);
    var where = r.m != null ? (r.tie ? '<span class="p-subfind-tie" title="Same straight-line distance as the next or previous row">tie</span> ' : '') + '<b class="p-subfind-d">' + fmtD(r.m) + '</b> <span class="p-subfind-brg" title="Compass bearing from the search point">' + compass(r.brg) + ' ' + Math.round(r.brg) + '°</span>' : '';
    return '<li class="p-subfind-row" data-p-subfind-id="' + esc(r.id) + '">' +
      '<div class="p-subfind-head"><span class="p-subfind-rank" style="border-color:' + col + '">' + (i + 1) + '</span><span class="p-subfind-name">' + esc(r.name) + '</span>' + where + '</div>' +
      '<div class="p-subfind-meta"><span class="p-subfind-kv' + (r.kvs.length || r.kind === 'ukpn' && r.raw ? '' : ' p-subfind-unk') + '">' + esc(kv) + '</span>' +
      (r.operator ? ' · <span class="p-subfind-op">' + esc(r.operator) + '</span>' : '') + '</div>' +
      '<div class="p-subfind-acts"><button type="button" class="pbtn p-subfind-fly" data-p-subfind-act="fly" aria-label="Fly there: ' + esc(r.name) + '">Fly there</button>' +
      '<button type="button" class="pbtn" data-p-subfind-act="route" aria-label="Route there by straight air legs: ' + esc(r.name) + '">Route there</button>' +
      (link ? '<a class="pbtn p-subfind-ga" href="' + esc(link) + '" target="_blank" rel="noopener" aria-label="Open ' + esc(r.name) + ' in GridAtlas (new tab)">Open in GridAtlas</a>' : '') +
      '</div></li>';
  }
  function render() {
    if (!body) return;
    var st = ui.st, out = ui.out;
    st.textContent = S.msg; st.className = 'p-subfind-status' + (S.msgKind ? ' p-subfind-' + S.msgKind : '');
    var h = '';
    if (S.named && S.named.length) {
      h += '<h3 class="p-subfind-h">Substations named “' + esc(S.q) + '” <small>' + S.named.length + (S.named.length > NAMED_MAX ? ', showing ' + NAMED_MAX : '') + '</small></h3>' +
        '<ol class="p-subfind-list p-subfind-named">' + S.named.slice(0, NAMED_MAX).map(rowHtml).join('') + '</ol>';
    }
    if (S.origin) {
      var o = S.origin;
      h += '<div class="p-subfind-origin"><div><span class="p-subfind-pin" aria-hidden="true"></span><b>' + esc(o.label) + '</b>' +
        (o.sub ? '<small> · ' + esc(o.sub) + '</small>' : '') + '<br><small class="p-subfind-dim">' + o.lat.toFixed(5) + ', ' + o.lon.toFixed(5) +
        (o.provider ? ' · ' + esc(o.provider) + ' (location only)' : '') + '</small></div>' +
        '<button type="button" class="pbtn" data-p-subfind-act="origin">Fly to place</button></div>';
      if (S.alts.length > 1) h += '<div class="p-subfind-alts" role="group" aria-label="Other places that match"><small class="p-subfind-dim">Not this place?</small>' +
        S.alts.slice(1).map(function (a, i) { return '<button type="button" class="p-subfind-chip" data-p-subfind-alt="' + (i + 1) + '">' + esc(a.label) + (a.sublabel ? ' <small>' + esc(String(a.sublabel).split(/[,·]/)[0]) + '</small>' : '') + '</button>'; }).join('') + '</div>';
      h += '<h3 class="p-subfind-h">Nearest substations ' + summary() + '</h3>';
      if (S.busy) h += '<p class="p-subfind-dim">Measuring straight-line distances…</p>';
      else {
        var notes = [];
        var wantGrid = kvOn().length > 0 || !S.ukpnOn;
        if (wantGrid && S.gridErr) notes.push('<p class="p-subfind-error">Substations 33 kV+ could not load (' + esc(S.gridErr) + '): nearest substations unknown, not zero. <button type="button" class="pbtn" data-p-subfind-act="retry">Retry</button></p>');
        if (S.ukpnOn && S.ukpn) {
          if (S.ukpn.state === 'missing') notes.push('<p class="p-subfind-warn">UKPN secondaries are not available here (module not loaded): unknown, not zero.</p>');
          else if (S.ukpn.state === 'error') notes.push('<p class="p-subfind-error">UKPN secondaries could not load (' + esc(S.ukpn.error || 'failed') + '): unknown, not zero. <button type="button" class="pbtn" data-p-subfind-act="retry">Retry</button></p>');
          else if (!S.ukpn.list.length) notes.push('<p class="p-subfind-dim">No UKPN secondary with a published point within ' + S.ukpn.rKm + ' km. UKPN publishes only its own area (London, East and South East England).</p>');
          else if (!S.rKm) notes.push('<p class="p-subfind-dim">UKPN secondaries searched within ' + S.ukpn.rKm + ' km' + (S.ukpn.capped ? ' (nearest ' + UKPN_N + ')' : '') + '.</p>');
        }
        if (S.hidden) notes.push('<p class="p-subfind-dim">' + S.hidden + ' substation' + (S.hidden === 1 ? '' : 's') + ' with unknown voltage hidden by the kV filter.</p>');
        h += notes.join('');
        if (S.rows.length) h += '<ol class="p-subfind-list p-subfind-near">' + S.rows.map(rowHtml).join('') + '</ol>';
        else if (!S.gridErr || !wantGrid) {
          var anyData = (wantGrid && S.grid) || (S.ukpnOn && S.ukpn && S.ukpn.state === 'ok');
          if (anyData) h += '<p class="p-subfind-none">No mapped substation matches these filters' + (S.rKm ? ' within ' + S.rKm + ' km' : '') + '. Absence from a mapped layer is not absence on the ground.</p>';
        }
      }
    }
    out.innerHTML = h;
    renderChips(); renderRecent();
    ui.foot.textContent = caveat();
    P.hud('status:subfind', S.origin && S.rows.length && !S.busy ? 'Nearest to ' + esc(S.origin.label) + ': <b>' + esc(S.rows[0].name) + '</b> ' + fmtD(S.rows[0].m) + ' ' + compass(S.rows[0].brg) + ' (straight line)' : '');
  }
  function summary() {
    var parts = [], ks = kvOn();
    if (ks.length) parts.push(ks.join('/') + ' kV');
    if (S.ukpnOn) parts.push('UKPN');
    if (S.rKm) parts.push('≤ ' + S.rKm + ' km');
    var n = S.busy ? '' : (S.total > S.rows.length ? S.rows.length + ' of ' + S.total : String(S.rows.length));
    return '<small>' + esc([n].concat(parts).filter(Boolean).join(' · ')) + '</small>';
  }
  function renderChips() {
    body.querySelectorAll('[data-p-subfind-kv]').forEach(function (b) { b.setAttribute('aria-pressed', S.kv[b.getAttribute('data-p-subfind-kv')] ? 'true' : 'false'); });
    body.querySelectorAll('[data-p-subfind-r]').forEach(function (b) { b.setAttribute('aria-pressed', String(+b.getAttribute('data-p-subfind-r') === S.rKm)); });
    var u = body.querySelector('[data-p-subfind-ukpn]'); if (u) u.setAttribute('aria-pressed', String(S.ukpnOn));
  }
  function renderRecent() {
    var a = recent();
    ui.recent.innerHTML = a.length ? '<div class="p-subfind-rhead"><span class="p-subfind-lab">RECENT</span><button type="button" class="pbtn" data-p-subfind-act="clear">Clear</button></div>' +
      '<div class="p-subfind-chips">' + a.map(function (r, i) { return '<button type="button" class="p-subfind-chip" data-p-subfind-recent="' + i + '">' + esc(r.q) + '</button>'; }).join('') + '</div>' : '';
  }
  function refilter(requery) {
    if (!S.origin) { renderChips(); return; }
    if (requery && S.ukpnOn) { var my = ++S.serial; S.busy = true; render(); return loadUkpnFor(S.origin, my).then(function () { if (my !== S.serial) return; S.busy = false; compute(); render(); publish(); }); }
    compute(); render(); publish();
  }
  function bind() {
    ui.form = body.querySelector('form'); ui.q = body.querySelector('#p-subfind-q'); ui.st = body.querySelector('.p-subfind-status');
    ui.out = body.querySelector('.p-subfind-out'); ui.recent = body.querySelector('.p-subfind-recent'); ui.foot = body.querySelector('.p-subfind-foot');
    ui.form.addEventListener('submit', function (e) { e.preventDefault(); if (ui.q.blur && phone()) ui.q.blur(); run(ui.q.value); });
    body.addEventListener('click', function (e) {
      var b = e.target.closest && e.target.closest('button'); if (!b || !body.contains(b)) return;
      var v;
      if ((v = b.getAttribute('data-p-subfind-kv'))) { S.kv[v] = !S.kv[v]; refilter(false); return; }
      if (b.hasAttribute('data-p-subfind-ukpn')) { S.ukpnOn = !S.ukpnOn; refilter(true); return; }
      if ((v = b.getAttribute('data-p-subfind-r'))) { S.rKm = S.rKm === +v ? 0 : +v; refilter(true); return; }
      if ((v = b.getAttribute('data-p-subfind-recent')) != null) {
        var r = recent()[+v]; if (!r) return; ui.q.value = r.q;
        if (okLL(+r.lat, +r.lon)) { S.q = r.q; S.named = null; S.alts = []; setMsg('', ''); if (P.hash) try { P.hash('subfind', r.q); } catch (x) {} setOrigin({ lat: +r.lat, lon: +r.lon, label: r.label, sublabel: r.sub, provider: 'recent search' }); }
        else run(r.q);
        return;
      }
      if ((v = b.getAttribute('data-p-subfind-alt'))) { var a = S.alts[+v]; if (a) { S.alts = [a].concat(S.alts.filter(function (x) { return x !== a; })); setOrigin(a); } return; }
      var act = b.getAttribute('data-p-subfind-act');
      if (act === 'clear') { try { localStorage.removeItem(RKEY); } catch (x) {} renderRecent(); return; }
      if (act === 'retry') { if (S.origin) setOrigin(S.origin); else run(S.q); return; }
      if (act === 'origin') { flyOrigin(); return; }
      var li = b.closest('.p-subfind-row'), row = li && rowById(li.getAttribute('data-p-subfind-id'));
      if (!row) return;
      if (act === 'fly') fly(row); else if (act === 'route') route(row);
    });
  }
  function openFind() {
    P.openPanel('subfind');
    setTimeout(function () { if (ui.q) { ui.q.focus(); if (ui.q.select) ui.q.select(); } }, 40);
  }

  // ---------------------------------------------------------------- map layer: search point, ranked markers, straight-line spokes
  var marks = [];
  // visible only while a search result is on the map, so its credit line shows only then
  var layer = { id: 'subfind', title: 'Find substations (search point and nearest results)', order: 85, visible: false, credit: SUBS_CREDIT,
    draw: function (g, v) {
      marks = [];
      var o = S.origin; if (!o) return;
      var po = v.project(o.lat, o.lon, null), rows = S.rows.slice(0, 10);
      g.save();
      g.lineWidth = 1.5; g.setLineDash([6, 5]); g.strokeStyle = 'rgba(0,255,255,.55)';
      g.beginPath();
      rows.slice(0, 5).forEach(function (r) { v.line([o.lat, o.lon, null], [r.lat, r.lon, null]); });
      g.stroke(); g.setLineDash([]);
      g.font = '600 11px ui-monospace, Menlo, monospace'; g.textAlign = 'center'; g.textBaseline = 'middle';
      rows.forEach(function (r, i) {
        var p = v.project(r.lat, r.lon, null); if (!p || p.x < -20 || p.y < -20 || p.x > v.w + 20 || p.y > v.h + 20) return;
        g.fillStyle = 'rgba(0,0,0,.75)'; g.strokeStyle = KV_COL[r.lv] || KV_COL.u; g.lineWidth = 2;
        g.beginPath(); g.arc(p.x, p.y, 10, 0, 6.2832); g.fill(); g.stroke();
        g.fillStyle = '#fff'; g.fillText(String(i + 1), p.x, p.y + 0.5);
        marks.push({ x: p.x, y: p.y, r: r });
      });
      if (po) {
        g.fillStyle = '#00ffff'; g.strokeStyle = '#000'; g.lineWidth = 2;
        g.beginPath(); g.moveTo(po.x, po.y); g.lineTo(po.x - 7, po.y - 14); g.lineTo(po.x + 7, po.y - 14); g.closePath(); g.fill(); g.stroke();
        g.textAlign = 'left'; g.fillStyle = '#fff'; g.strokeStyle = 'rgba(0,0,0,.8)'; g.lineWidth = 3;
        var t = String(o.label).slice(0, 28); g.strokeText(t, po.x + 10, po.y - 10); g.fillText(t, po.x + 10, po.y - 10);
      }
      g.restore();
    },
    pick: function (sx, sy) {
      for (var i = 0; i < marks.length; i++) { var m = marks[i]; if (Math.hypot(sx - m.x, sy - m.y) <= 22) return { title: m.r.name, html: cardHtml(m.r), lat: m.r.lat, lon: m.r.lon, id: m.r.id }; }
      return null;
    } };

  // ---------------------------------------------------------------- wire up
  function start() {
    body = P.panel('subfind', panelHtml(), { title: 'Find substations', icon: 'SUB' });
    if (body) { bind(); render(); }
    var hb = P.hud('top:subfind', '<button type="button" class="pbtn p-subfind-hudbtn" aria-label="Find substations by postcode, town or name"><span aria-hidden="true">⌖</span> Find substations</button>');
    var btn = hb && hb.querySelector && hb.querySelector('button');
    if (btn) btn.addEventListener('click', openFind);
    if (P.addLayer) P.addLayer(layer);
    var want = P.hash ? P.hash('subfind') : null;
    if (want && ui.q) { ui.q.value = want; run(want); }
  }
  P.on('subfind:search', function (d) { if (d && d.q) { if (ui.q) ui.q.value = d.q; openFind(); run(d.q); } });
  P.on('subfind:open', openFind);
  if (D && D.addEventListener) D.addEventListener('keydown', function (e) {
    var t = e.target, tag = t && t.tagName;
    if (e.ctrlKey || e.metaKey || e.altKey || tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (t && t.isContentEditable)) return;
    if ((e.key || '').toLowerCase() === 'b') { openFind(); e.preventDefault(); }
  });
  if (P.ready) P.ready(start); else start();

  // test hooks and a small API (through PILOT only)
  P.subfind = { version: '1', run: run, open: openFind, state: function () { return S; }, atlasLink: atlasLink, compass: compass, level: level, layer: layer };
})();

Pilot Ticker

A style sheet in the theme folder of Cosmic.

rendercosmic / tools/explore/theme/pilot-ticker.css · lines 1–52 of 52 · 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
Pilot module: Pipeline News ticker (MARQUEE-53).
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-ticker.css:1-52 · blob 1c3c3d0edb9d18b74e1cee7152a0f905213b4955 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* Pilot module: Pipeline News ticker (MARQUEE-53). Palette from Pipeline News V9.40/V9.41: crisp red #f33 on solid black,
   border #333, muted #aeb2b8 (automation/ticker_neon_ui/20261117-v940 + ticker_crisp_ui/20261117-v941). */
.p-hud-sub.p-ticker-host { background: none; border: 0; padding: 0; width: 100%; max-width: 760px; }
/* wide screens: the core top slot starts at 380px but the code card's border box ends at 396px, so step clear of it */
@media (min-width: 900px) { .p-hud-sub.p-ticker-host { align-self: flex-end; width: calc(100% - 20px); } }
.p-ticker { --p-ticker-red: #f33; display: flex; align-items: stretch; width: 100%; min-height: 44px; box-sizing: border-box; background: #000; color: var(--p-ticker-red);
  border: 1px solid #333; border-radius: 4px; overflow: hidden; font: 12px ui-monospace, Menlo, Consolas, monospace; }
.p-ticker-chip, .p-ticker-btn { flex: 0 0 auto; min-height: 44px; min-width: 44px; padding: 0 6px; background: #000; color: #aeb2b8; border: 0; border-right: 1px solid #333;
  font: 11px ui-monospace, Menlo, monospace; letter-spacing: .04em; cursor: pointer; white-space: nowrap; }
.p-ticker-btn { border-right: 0; border-left: 1px solid #333; color: var(--p-ticker-red); font-size: 12px; }
.p-ticker-btn[hidden] { display: none; }
.p-ticker[data-state="live"] .p-ticker-chip { color: #fff; }
.p-ticker[data-state="snapshot"] .p-ticker-chip, .p-ticker[data-state="overdue"] .p-ticker-chip, .p-ticker[data-state="overdue-partial"] .p-ticker-chip,
.p-ticker[data-state="partial"] .p-ticker-chip, .p-ticker[data-state="unknown"] .p-ticker-chip, .p-ticker[data-state="future"] .p-ticker-chip { color: #ffae00; }
.p-ticker[data-state="unavailable"] .p-ticker-chip, .p-ticker[data-state="failed"] .p-ticker-chip, .p-ticker[data-state="offline"] .p-ticker-chip { color: #000; background: var(--p-ticker-red); }
.p-ticker-vp { flex: 1 1 auto; min-width: 0; overflow: hidden; position: relative; touch-action: pan-x pan-y; scrollbar-width: thin; scrollbar-color: #70313b #000; }
.p-ticker-track { display: flex; width: max-content; will-change: transform; animation: p-ticker-flow var(--p-ticker-dur, 120s) linear infinite; }
.p-ticker-list { display: flex; flex: none; gap: 28px; list-style: none; margin: 0; padding: 0 28px 0 10px; }
.p-ticker-list > li { display: flex; margin: 0; }
.p-ticker-item { display: inline-flex; align-items: center; gap: 6px; min-height: 44px; padding: 0 2px; white-space: nowrap; background: #000; color: var(--p-ticker-red);
  border: 0; font: inherit; cursor: pointer; text-align: left; }
.p-ticker-item:hover .p-ticker-t { text-decoration: underline; }
.p-ticker-t { font-weight: 700; }
.p-ticker-d { font-size: 10px; color: #c7868e; }
.p-ticker-unk { color: #ffae00; }
.p-ticker-tag { font-size: 9px; letter-spacing: .06em; border: 1px solid #61232c; border-radius: 2px; padding: 0 3px; color: #aeb2b8; }
.p-ticker-near { color: #000; background: var(--p-ticker-red); border-color: var(--p-ticker-red); }
.p-ticker-msg { display: flex; align-items: center; min-height: 44px; white-space: nowrap; color: #aeb2b8; }
.p-ticker-copy { pointer-events: none; user-select: none; -webkit-user-select: none; }
.p-ticker[data-motion="static"] .p-ticker-track { animation: none; transform: none; will-change: auto; }
.p-ticker[data-motion="static"] .p-ticker-copy { display: none; }
.p-ticker[data-motion="static"] .p-ticker-vp { overflow-x: auto; }
.p-ticker :focus-visible { outline: 2px solid #fff; outline-offset: -2px; }
@keyframes p-ticker-flow { to { transform: translateX(calc(-1 * var(--p-ticker-w, 50%))); } }
@media (hover: hover) { .p-ticker:hover .p-ticker-track { animation-play-state: paused; } }
@media (prefers-reduced-motion: reduce) {
  .p-ticker .p-ticker-track { animation: none !important; transform: none !important; }
  .p-ticker .p-ticker-copy { display: none; }
  .p-ticker .p-ticker-vp { overflow-x: auto; }
}
/* card + panel */
.p-ticker-cmeta { color: #aeb2b8; font-size: 11px; }
.p-ticker-cnote { color: #aeb2b8; font-size: 11px; }
.p-ticker-cnear { color: #f33; }
.p-ticker-acts { display: flex; flex-wrap: wrap; gap: 6px; }
.p-ticker-link { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.p-ticker-panel .p-ticker-pstat { color: #fff; }
.p-ticker-panel .p-ticker-pstat:not([data-state="live"]) { color: #ffae00; }
.p-ticker-plist { margin: 6px 0; padding-left: 22px; }
.p-ticker-plist li { margin: 0 0 8px; overflow-wrap: anywhere; }
.p-ticker-plist a { color: #f33; display: inline-flex; align-items: center; min-height: 44px; }
.p-ticker-panel b.p-ticker-near { font-size: 9px; padding: 0 3px; border-radius: 2px; }