GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609271740-site-world/world

Search UI and 2 more files (part 2)

A JavaScript module in the world folder of GlobalGrid2050 that formats capacity and technology and converts to rows, covering postcodes, the Renewable Energy Planning Database (REPD) register, wind and solar.

518 lines of JavaScript from globalgrid2050, in 3 files. Topic: Solar and storage design. Section 167 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. Search UI interaction · globalgrid2050 / solar-design-studio/202609271740-site-world/world/search-ui.mjs lines 1–351
  2. Single-Line Diagram (SLD) Follow electrical · globalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-follow.mjs lines 1–139
  3. Single-Line Diagram (SLD) Hook electrical · globalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-hook.mjs lines 1–28

Search UI

A JavaScript module in the world folder of GlobalGrid2050 that formats capacity and technology and converts to rows, covering postcodes, the Renewable Energy Planning Database (REPD) register, wind and solar.

Set aside from the main view: 92% of its lines are the same as solar-design-studio/202609270220-site-world-v3/world/search-ui.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with Search UI; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9217 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270220-site-world-v3/world/search-ui.mjs:1-332 5be962c628d66b01f1d473f1c6c070d08ee74c9b
  • sha256 bf100c351ce559bedf4c407858ffd7e252a5ab466918a545e6a4ae0e450a9ba0
  • target sha256 fbaecee711f3ec4ec3ca3e364a6dc7b3fe0935879614d07a5b733b868198606e
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

interactionglobalgrid2050 / solar-design-studio/202609271740-site-world/world/search-ui.mjs · lines 1–351 of 351 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review) · pattern createSearchPanel (shared by 2 files)

What it does
It draws postcodes, the REPD register, wind and solar. Defines 30 functions or classes, including creditsFor, formatCapacity, trim, formatTechnology, gridRefQuery. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): 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, the REPD register, wind, solar.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Find Mount (globalgrid2050).
What it achieves
It formats capacity (`formatCapacity`), formats technology (`formatTechnology`) and merges rows (`mergeRows`). Search panel: "Find a place". A small box over the world that finds a town or village (OS Open Names through postcodes.io, see `places.mjs`), a REPD project, a UK postcode (postcodes.io, see `postcodes.mjs`) or a typed "lat, lon". Its code works with 1.2 GW, 49.9 MW and 650 kW. It responds to pointerdown, click and input events.
Why it matters
Imported by Find Mount.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Search (import), Postcodes (import), Places (import), Bng (import)
Used by
imported by Find Mount (import)
Produces
REPD_CREDIT, NO_TERRAIN, LIVE_TERRAIN, creditsFor, formatCapacity, formatTechnology, gridRefQuery, toRows, summaryText, moveSelection, rowForEnter, debounce
Defines here
creditsFor, formatCapacity, trim, formatTechnology, gridRefQuery, toRows, summaryText, moveSelection, rowForEnter, debounce, d, arrivalNote, mergeRows, statusLine, sourcesShown, runQuery, createSearchPanel, el, showCredits, ensureIndex, highlight, choose, render, paint, settle, ask, show, parseLike, openPanel, close
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/search-ui.mjs:1-351 · blob 9108580d5e8c58fbc97201a78f989041f8fdd3b0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Search panel: "Find a place". A small box over the world that finds a town or village (OS Open Names through
// postcodes.io, see places.mjs), a REPD project, a UK postcode (postcodes.io, see postcodes.mjs) or a typed "lat, lon",
// and hands the chosen point to the caller. The logic is pure functions at the top,
// tested without a DOM; createSearchPanel at the bottom only wires them to elements.
// The project index is large, so it is loaded the first time the panel is opened, never before.

import { search } from './search.mjs';
import { looksLikePostcode, createPostcodeLookup, POSTCODES_CREDIT } from './postcodes.mjs';
import { looksLikePlace, createPlaceLookup, PLACES_CREDIT } from './places.mjs';
import { parseGridRef, gridRef, bngToWgs84 } from './bng.mjs';

// The on-screen credit for the search layer, as worded in data/attribution.json (sources.repd.line).
// tests/search-ui.test.mjs checks this copy against the file, so the two cannot drift apart.
export const REPD_CREDIT = Object.freeze({
  id: 'repd',
  text: 'Contains public sector information licensed under the Open Government Licence v3.0. Source: DESNZ Renewable Energy Planning Database, via GridAtlas.',
  link: 'https://www.gov.uk/government/publications/renewable-energy-planning-database-monthly-extract'
});

// What the panel says after a jump, when the place has no staged ground.
export const NO_TERRAIN = 'No terrain tiles here yet. The ground is shown flat until terrain is fetched for this place.';
// What it says when the ground will come live from the Environment Agency service (wcs-terrain.mjs).
export const LIVE_TERRAIN = 'Fetching the ground live from the Environment Agency LiDAR service; it shows flat until it arrives.';

const TECH = {
  solar: 'Solar', wind: 'Wind', bess: 'Battery storage', battery: 'Battery storage', hydro: 'Hydro',
  biomass: 'Biomass', 'energy from waste': 'Energy from waste', efw: 'Energy from waste', 'anaerobic digestion': 'Anaerobic digestion',
  'offshore wind': 'Offshore wind', 'onshore wind': 'Onshore wind', tidal: 'Tidal', geothermal: 'Geothermal', 'landfill gas': 'Landfill gas'
};

// The credit lines for the given attribution.json object: every on-screen source under the "search" (REPD),
// "postcodes" and "names" (OS Open Names) layers, de-duplicated, {year} filled in as attribution.mjs does.
// Falls back to the built-in lines without the file.
export function creditsFor(attribution, layers = ['search', 'postcodes', 'names'], year = new Date().getUTCFullYear()) {
  const ids = [layers].flat().flatMap((l) => attribution?.layers?.[l] ?? []);
  if (!attribution?.layers) return [REPD_CREDIT, POSTCODES_CREDIT, PLACES_CREDIT];
  const out = [];
  for (const id of new Set(ids)) {
    const s = attribution.sources?.[id];
    if (s && s.on_screen !== false && s.line) out.push({ id, text: s.line.replaceAll('{year}', String(s.year ?? year)), link: s.link ?? null });
  }
  return out;
}

// "49.9 MW", "650 kW", "1.2 GW"; empty when the capacity is unknown.
export function formatCapacity(mw) {
  if (mw == null || mw === '' || !Number.isFinite(Number(mw))) return '';
  const v = Number(mw);
  if (v >= 1000) return `${trim(v / 1000)} GW`;
  if (v > 0 && v < 1) return `${trim(v * 1000)} kW`;
  return `${trim(v)} MW`;
}
const trim = (v) => String(Number(v.toFixed(v >= 100 ? 0 : v >= 10 ? 1 : 2)));

export function formatTechnology(t) {
  if (t == null || t === '') return '';
  const k = String(t).trim().toLowerCase();
  return TECH[k] ?? k.charAt(0).toUpperCase() + k.slice(1);
}

// "SP 01 09", "sp0109", "SP 012 098": an OS grid reference, two letters then 1 to 5 digits each way. Goes to the middle of
// the square it names (a 1 km square for four digits). lat, lon ride along for the "is ground staged here?" answer. Pure.
export function gridRefQuery(text) {
  const s = String(text ?? '').trim();
  if (!/^[A-Za-z]{2}\s*\d[\d\s]*$/.test(s) || looksLikePostcode(s)) return null; // "HR2 6" is the start of a postcode
  let p;
  try { p = parseGridRef(s); } catch { return null; }
  const digits = s.replace(/\D/g, '').length, size = 10 ** (5 - digits / 2), e = p.e + size / 2, n = p.n + size / 2;
  return { kind: 'gridref', e, n, size, label: gridRef(p.e, p.n, digits), ...bngToWgs84(e, n) };
}

// search() output to display rows. Each row: { key, title, detail, choice: { lat, lon, label } }.
// A coordinate query gives one row. Projects without a usable point are left out.
export function toRows(result) {
  if (!result) return [];
  if (result.kind === 'gridref') {
    const sq = result.size >= 1000 ? `${result.size / 1000} km` : `${result.size} m`;
    return [{ key: 'gridref', title: result.label, detail: `OS grid reference · the middle of its ${sq} square`,
      choice: { e: result.e, n: result.n, lat: result.lat, lon: result.lon, label: result.label } }];
  }
  if (result.kind === 'coords') {
    const label = `${result.lat.toFixed(5)}, ${result.lon.toFixed(5)}`;
    return [{ key: 'coords', title: label, detail: 'Latitude, longitude', choice: { lat: result.lat, lon: result.lon, label } }];
  }
  return (result.results ?? [])
    .filter((r) => r.lat != null && r.lon != null && r.lat !== '' && r.lon !== '' && Number.isFinite(Number(r.lat)) && Number.isFinite(Number(r.lon)))
    .map((r) => {
      const title = r.name ? String(r.name) : `REPD ${r.repd_ref}`;
      const detail = [`REPD ${r.repd_ref}`, formatCapacity(r.capacity_mw), formatTechnology(r.technology), r.county ?? ''].filter(Boolean).join(' · ');
      return { key: `repd-${r.repd_ref}`, source: 'repd', title, detail, rank: r.score, choice: { lat: Number(r.lat), lon: Number(r.lon), label: title, ref: r.repd_ref } };
    });
}

// "12 of 340 projects", "1 project", "No projects match", "" (no query).
export function summaryText(result, shown) {
  if (!result) return '';
  if (result.kind === 'coords') return 'Go to this point';
  if (result.kind === 'gridref') return 'Go to this grid square';
  if (!result.total) return 'No projects match';
  const noun = result.total === 1 ? 'project' : 'projects';
  return shown < result.total ? `${shown} of ${result.total} ${noun}` : `${result.total} ${noun}`;
}

// Arrow keys move the highlighted row, wrapping; Home and End jump. -1 means nothing highlighted.
// Returns the new index, or null when the key is not a selection key.
export function moveSelection(index, count, key) {
  if (count <= 0) return key === 'ArrowDown' || key === 'ArrowUp' || key === 'Home' || key === 'End' ? -1 : null;
  switch (key) {
    case 'ArrowDown': return index < 0 || index >= count - 1 ? 0 : index + 1;
    case 'ArrowUp': return index <= 0 ? count - 1 : index - 1;
    case 'Home': return 0;
    case 'End': return count - 1;
    default: return null;
  }
}

// Which row Enter chooses: the highlighted one, or the first when nothing is highlighted.
export function rowForEnter(rows, index) {
  if (!rows.length) return null;
  return rows[index >= 0 && index < rows.length ? index : 0];
}

// Trailing-edge debounce. Clock functions are injectable so tests need no real time.
export function debounce(fn, ms, clock = { set: (f, t) => setTimeout(f, t), clear: id => clearTimeout(id) }) { // bound: a bare setTimeout called as clock.set throws 'Illegal invocation' in browsers
  let id = null;
  const d = (...args) => {
    if (id !== null) clock.clear(id);
    id = clock.set(() => { id = null; fn(...args); }, ms);
  };
  d.cancel = () => { if (id !== null) clock.clear(id); id = null; };
  d.flush = (...args) => { d.cancel(); fn(...args); };
  return d;
}

// The note to show after choosing a place. hasTerrain(lat, lon) is the caller's answer to
// "is ground staged here?"; without it we cannot know, so we say so plainly. live: ground elsewhere
// is fetched from the EA service, so say that instead of "flat".
export function arrivalNote(choice, hasTerrain, live = false) {
  const known = typeof hasTerrain === 'function' ? Boolean(hasTerrain(choice.lat, choice.lon)) : false;
  return known ? '' : live ? LIVE_TERRAIN : NO_TERRAIN;
}

// Postcode rows first (an exact postcode is what was meant), then places and projects by their ranks
// (places.mjs PLACE_SCORE against search.mjs SCORE): an exact town name above every project, a town that starts
// with the text above projects that only start with it. Ties keep places first, and each list keeps its own order. Pure.
export function mergeRows(postcodeRows, projectRows, placeRows = []) {
  const rest = [...(placeRows || []).map((r) => ({ r, k: r.score ?? 0 })), ...(projectRows || []).map((r) => ({ r, k: r.rank ?? 0 }))];
  return [...(postcodeRows || []), ...rest.map((x, i) => ({ ...x, i })).sort((a, b) => b.k - a.k || a.i - b.i).map((x) => x.r)];
}

// The status line: what each source found, or that it is still looking. Counts of null mean "still waiting";
// projects is runQuery's summary, or null while the project list is not loaded. Pure.
export function statusLine({ postcodes = undefined, places = undefined, projects = null, projectRows = 0 } = {}) {
  const parts = [];
  if (postcodes === null) parts.push('Looking up postcode...');
  else if (postcodes !== undefined) parts.push(postcodes ? `${postcodes} ${postcodes === 1 ? 'postcode' : 'postcodes'}` : 'No postcode matches');
  if (places === null) parts.push('Looking up places...');
  else if (places) parts.push(`${places} ${places === 1 ? 'place' : 'places'}`);
  if (projects && (projectRows > 0 || !parts.length)) parts.push(projects);
  return parts.join(' · ');
}

// Which credits to show: those of the sources that have rows on screen.
export const sourcesShown = rows => new Set(rows.map(r => r.source).filter(Boolean));

// One lookup: query text in, everything the list needs out. Pure.
export function runQuery(index, text, limit = 12) {
  const q = String(text ?? '').trim();
  if (!q) return { rows: [], summary: '', credits: false };
  const result = gridRefQuery(q) || search(index, q, limit);
  const rows = toRows(result);
  return { rows, summary: summaryText(result, rows.length), credits: result.kind === 'projects' && rows.length > 0, result };
}

// ---- DOM wiring ----------------------------------------------------------------------------

// Uses world.html's colour tokens, with fallbacks. Rows are 44 px tall for touch.
const STYLE = `
.find-panel { position: fixed; top: 46px; right: 8px; width: min(360px, calc(100vw - 16px)); box-sizing: border-box;
  background: var(--panel, rgba(10,10,10,.9)); border: 1px solid var(--edge, #1c2c3a); border-radius: 6px; padding: 8px 10px; z-index: 5;
  display: flex; flex-direction: column; }
.find-panel > * { flex: none; }
.find-panel[hidden] { display: none; }
.find-panel label { display: block; color: var(--dim, #6f8ea6); margin-bottom: 4px; }
.find-panel input { width: 100%; box-sizing: border-box; height: 34px; padding: 0 8px; font: inherit; font-size: 16px;
  color: var(--text, #cfe9ff); background: #000; border: 1px solid var(--edge, #1c2c3a); border-radius: 4px; }
.find-panel input:focus { outline: none; border-color: var(--line, #9cdbff); }
.find-status { color: var(--dim, #6f8ea6); font-size: 11px; min-height: 16px; margin: 4px 0; }
.find-list { list-style: none; margin: 0; padding: 0; max-height: min(50vh, 400px); overflow-y: auto; }
.find-panel > .find-list { flex: 0 1 auto; min-height: 44px; } /* on a short panel the list scrolls; the credits stay in view */
.find-row { min-height: 44px; box-sizing: border-box; padding: 5px 6px; border-radius: 4px; cursor: pointer;
  display: flex; flex-direction: column; justify-content: center; }
.find-row[aria-selected="true"], .find-row:hover { background: rgba(156, 219, 255, 0.10); }
.find-name { color: var(--text, #cfe9ff); } .find-detail { color: var(--dim, #6f8ea6); font-size: 11px; }
.find-credit { margin: 6px 0 0; font-size: 10px; line-height: 1.3; } .find-credit[hidden] { display: none; }
.find-credit a { color: var(--dim, #6f8ea6); display: block; margin-top: 3px; } .find-credit a[hidden] { display: none; } /* one credit per line */
`;

// container: element the panel is built inside. loadIndex(): Promise of the projects.json object,
// called once, on first open. onChoose({ lat, lon, label }): the caller moves the world there.
// Options: attribution (the attribution.json object; defaults to the REPD and postcode lines), hasTerrain(lat, lon),
// liveTerrain (ground elsewhere comes from the EA service), postcodes (a lookup from createPostcodeLookup;
// false for none), places (a lookup from createPlaceLookup; false for none), limit (rows shown), delay (debounce ms). Returns { open, close, toggle, isOpen, element, destroy }.
let panelCount = 0;

export function createSearchPanel(container, { loadIndex, onChoose, attribution = null, hasTerrain = null, liveTerrain = false,
  postcodes = createPostcodeLookup(), places = createPlaceLookup(), limit = 12, delay = 120 } = {}) {
  if (typeof loadIndex !== 'function') throw Error('createSearchPanel needs loadIndex');
  if (typeof onChoose !== 'function') throw Error('createSearchPanel needs onChoose');
  const doc = container.ownerDocument;
  const el = (tag, props = {}, attrs = {}) => {
    const e = doc.createElement(tag);
    Object.assign(e, props);
    for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
    return e;
  };
  const uid = `find-${++panelCount}`; // a counter, not a random draw: ids stay the same on every run
  if (doc.head && !doc.getElementById?.('find-panel-style')) doc.head.appendChild(el('style', { id: 'find-panel-style', textContent: STYLE }));

  const root = el('section', { className: 'find-panel', hidden: true }, { 'aria-label': 'Find a place' });
  const label = el('label', { textContent: 'Find a place', htmlFor: `${uid}-q` });
  const input = el('input', { type: 'search', id: `${uid}-q`, autocomplete: 'off', spellcheck: false,
    placeholder: 'Town, postcode, project, grid ref or lat, lon' },
  { role: 'combobox', 'aria-autocomplete': 'list', 'aria-expanded': 'false', 'aria-controls': `${uid}-list`, enterkeyhint: 'go' });
  const status = el('div', { className: 'find-status' }, { role: 'status', 'aria-live': 'polite' });
  const list = el('ul', { id: `${uid}-list`, className: 'find-list' }, { role: 'listbox', 'aria-label': 'Places found' });
  const credit = el('p', { className: 'find-credit', hidden: true });
  for (const c of creditsFor(attribution)) {
    const a = el('a', { textContent: c.text, href: c.link ?? '#', target: '_blank', rel: 'noopener' }, { 'data-source': c.id ?? '' });
    credit.appendChild(a);
  }
  // Only the credits of sources with rows on screen are shown; the small print hides when there are none.
  const showCredits = (ids) => {
    for (const a of credit.childNodes) a.hidden = !ids.has(a.getAttribute('data-source'));
    credit.hidden = ids.size === 0;
  };
  root.append(label, input, status, list, credit);
  container.appendChild(root);

  let index = null, loading = null, rows = [], sel = -1, open = false, shown = null; // shown: the text the list was built for
  let pending = null, enterWhenReady = false; // pending: the text a postcode or place lookup is running for

  const ensureIndex = () => {
    if (index || loading) return loading;
    status.textContent = 'Loading project list...';
    loading = Promise.resolve().then(loadIndex).then((ix) => {
      index = ix; status.textContent = '';
      if (input.value.trim()) render(input.value);
    }, (e) => {
      loading = null; status.textContent = `Project list could not be loaded: ${e?.message ?? e}`;
    });
    return loading;
  };

  const highlight = (i) => {
    sel = i;
    list.childNodes.forEach((li, k) => li.setAttribute('aria-selected', String(k === sel)));
    if (sel >= 0) { input.setAttribute('aria-activedescendant', `${uid}-o${sel}`); list.childNodes[sel]?.scrollIntoView?.({ block: 'nearest' }); }
    else input.removeAttribute('aria-activedescendant');
  };

  const choose = (row) => {
    if (!row) return;
    status.textContent = arrivalNote(row.choice, hasTerrain, liveTerrain) || `Going to ${row.choice.label}`;
    list.replaceChildren(); rows = []; shown = null; pending = null; enterWhenReady = false;
    showCredits(new Set()); input.setAttribute('aria-expanded', 'false');
    onChoose({ ...row.choice });
  };

  function render(text) {
    const ref = Boolean(gridRefQuery(text)); // a grid reference is answered here: no postcode or place lookup
    const pc = !ref && Boolean(postcodes) && looksLikePostcode(text), pl = !ref && Boolean(places) && looksLikePlace(text);
    const point = parseLike(text);
    if (!index && !point) ensureIndex();
    if (!index && !point && !pc && !pl) return;
    const out = index || point ? runQuery(index, text, limit) : { rows: [], summary: '', result: null };
    const projects = out.result?.kind === 'projects' ? out.summary : null;
    shown = text;
    // Each answer: undefined when not asked, null while waiting, else the rows.
    const got = { postcodes: pc ? null : undefined, places: pl ? null : undefined };
    const paint = () => {
      show(mergeRows(got.postcodes, out.rows, got.places), point ? out.summary : statusLine({
        postcodes: got.postcodes === null ? null : got.postcodes?.length, places: got.places === null ? null : got.places?.length,
        projects, projectRows: out.rows.length }));
    };
    paint();
    pending = pc || pl ? text : null;
    const settle = () => {
      if (got.postcodes === null || got.places === null) return;
      pending = null;
      if (enterWhenReady) { enterWhenReady = false; choose(rowForEnter(rows, sel)); }
    };
    const ask = (key, lookup, noun) => lookup(text).then((found) => {
      if (found === null || shown !== text) return; // a newer query took over
      got[key] = found; paint(); settle();
    }, (e) => {
      if (shown !== text) return;
      got[key] = []; paint(); settle();
      status.textContent = [`${noun} lookup failed: ${e?.message ?? e}`, status.textContent].filter(Boolean).join(' · ');
    });
    if (pc) ask('postcodes', postcodes, 'Postcode');
    if (pl) ask('places', places, 'Place');
  }

  function show(next, summary) {
    rows = next;
    list.replaceChildren(...rows.map((r, i) => {
      const li = el('li', { id: `${uid}-o${i}`, className: 'find-row' }, { role: 'option', 'aria-selected': 'false' });
      li.append(el('span', { className: 'find-name', textContent: r.title }), el('span', { className: 'find-detail', textContent: r.detail }));
      li.addEventListener('pointerdown', (e) => e.preventDefault()); // keep focus in the box
      li.addEventListener('click', () => choose(r));
      return li;
    }));
    status.textContent = summary;
    showCredits(sourcesShown(rows));
    input.setAttribute('aria-expanded', String(rows.length > 0));
    highlight(-1);
  }
  const parseLike = (text) => runQuery(null, text).rows.length > 0; // a typed point needs no index

  const later = debounce(render, delay);
  input.addEventListener('input', () => later(input.value));
  input.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') { e.preventDefault(); close(); return; }
    if (e.key === 'Enter') {
      e.preventDefault();
      if (input.value !== shown) later.flush(input.value); else later.cancel();
      if (pending === input.value && sel < 0) { enterWhenReady = true; return; } // the postcode answer is on its way
      choose(rowForEnter(rows, sel)); return;
    }
    const next = moveSelection(sel, rows.length, e.key);
    if (next !== null) { e.preventDefault(); highlight(next); }
  });

  function openPanel() {
    if (open) return;
    open = true; root.hidden = false; ensureIndex(); input.focus?.(); input.select?.();
  }
  function close() { open = false; root.hidden = true; later.cancel(); }

  return {
    element: root,
    open: openPanel,
    close,
    toggle: () => (open ? close() : openPanel()),
    isOpen: () => open,
    destroy: () => { close(); root.remove(); }
  };
}

export default createSearchPanel;

Single-Line Diagram (SLD) Follow

A JavaScript module in the world folder of GlobalGrid2050 that works with cables, transformers, solar and overhead lines (OHL). It parses panel (`parsePanel`) and picks panel (`pickPanel`).

electricalglobalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-follow.mjs · lines 1–139 of 139 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review) · pattern orient (shared by 5 files)

What it does
It calculates cables, transformers, solar and overhead lines (OHL). Defines 16 functions or classes, including len, panelId, parsePanel, pickPanel, followPath.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, transformers, solar, overhead lines (OHL).
Downstream impact
Used directly by 1 file: Single-Line Diagram (SLD) Mount (globalgrid2050).
What it achieves
Follow, from one solar module to the landing bay, as a list of stops along one continuous path.
Why it matters
Imported by Single-Line Diagram (SLD) Mount.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Single-Line Diagram (SLD) Calc (import), Single-Line Diagram (SLD) Rules (import), Measure Format (import)
Used by
imported by Single-Line Diagram (SLD) Mount (import)
Produces
panelId, parsePanel, pickPanel, followPath, dropSoFar
Defines here
len, panelId, parsePanel, pickPanel, followPath, move, local, gnd, stop, nodeAt, fault, isTx, cur, dropSoFar, orient, d
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/sld-follow.mjs:1-139 · blob 9d0dac153b5366daed1ef9ba35bf97c4860acc04 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// sld-follow.mjs: Follow, from one solar module to the landing bay, as a list of stops along one continuous path.
//
// module -> its string (the + and - conductors through the series loop) -> the two DC home cables along their trench ->
// the inverter on its pole -> the AC cable (3 x 400 mm2 Al, no local isolator) -> the station LV board -> the station
// transformer and its RMU -> each RMU along the feeder (the normally-open point noted) -> the MV board section -> the
// grid transformer and its HV bay -> the HV cable -> the gas-insulated bay at the substation (or the tower, tee option).
// The AC stops read the network readouts (sld-calc.mjs) so the cumulative drop is the sum of the element drops the
// GPU pair checks. The DC side is worked here: string current at the maximum-power point of a generic module class,
// copper home cables (EN 50618 class, size assumed). Every figure is illustrative, not a design for any site. Pure.

import { tracePath } from './sld-calc.mjs';
import { SLD_DEFAULTS, SLD_LABEL } from './sld-rules.mjs';
import { formatNumber, fmtQ, fmtPct, fmtLen, fmtVolt } from './measure-format.mjs';

const len = pts => pts.reduce((t, q, i) => (i ? t + Math.hypot(q[0] - pts[i - 1][0], q[1] - pts[i - 1][1], q[2] - pts[i - 1][2]) : 0), 0);
// Numbers by the one rule (measure-format.mjs): currents and fault levels 3 figures, drops 2 dp, whole metres.

/** Panel id 'S2:37:12' <-> { station: 'S2', string: 37, module: 12 }. */
export const panelId = p => `${p.station}:${p.string}:${p.module}`;
export function parsePanel(id) {
  const m = /^(S\d+):(\d+):(\d+)$/.exec(String(id || '').trim());
  return m ? { station: m[1], string: Number(m[2]), module: Number(m[3]) } : null;
}

/** The connected module nearest a ground point [e, n], or null when the point is off every station's tables. */
export function pickPanel(built, anchor, [e, n], reachM = 6) {
  const [E, N] = anchor, strings = built.station.strings.filter(s => s.connected);
  let best = null;
  for (const S of built.mv.stations) {
    const x = e - E - S.offset[0], y = n - N - S.offset[1];
    if (x < -20 || y < -20 || x > 200 || y > 360) continue;
    for (const s of strings) s.modules.forEach((m, k) => {
      const d = Math.hypot(m.terminal[0] - x, m.terminal[1] - y);
      if (d < reachM && (!best || d < best.d)) best = { d, station: S.id, string: s.index, module: k };
    });
  }
  return best && { station: best.station, string: best.string, module: best.module };
}

/**
 * followPath({ built, anchor, graph, sol, ro, panel, groundAt }) -> { stops, points, nodes, branches, panel, label }
 * stops: [{ key, title, at: [e, n, z], view: 'walk' | 'drone' | 'high', leg: [[e, n, z]...] (from the previous stop),
 *           rows: [[label, value]...], dropPct, cumDropPct }]; points: the whole path as one polyline.
 */
export function followPath({ built, anchor, graph, sol, ro, panel, groundAt = () => 0 }) {
  const P = typeof panel === 'string' ? parsePanel(panel) : panel;
  const S = P && built.mv.stations.find(s => s.id === P.station);
  const str = S && built.station.strings[P.string];
  if (!S || !str || !str.connected || !str.modules[P.module]) throw Error('follow: no connected module ' + (typeof panel === 'string' ? panel : panelId(P || {})));
  const [E, N] = anchor, [ox, oy] = S.offset, d = SLD_DEFAULTS, M = d.module;
  // Station 1 is drawn in full; the others are the same block moved, so their points ride their own ground.
  const move = q => { if (!ox && !oy) return q; const e = q[0] + ox, n = q[1] + oy; return [e, n, q[2] - groundAt(q[0], q[1]) + groundAt(e, n)]; };
  const local = q => move([E + q[0], N + q[1], groundAt(E + q[0], N + q[1]) + (q[2] ?? 0)]);
  const gnd = (q, h = 0.5) => [q[0], q[1], groundAt(q[0], q[1]) + h];
  const stops = [];
  // cum: the cables' voltage drop only; a transformer's voltage change (txPct) is said on its own, never added to it
  // (user test H6).
  let cum = 0, tx = 0, run = 0, prev = null;
  const stop = (key, title, at, view, leg, rows, dropPct = 0, lengthM = 0, txPct = 0) => {
    cum += dropPct; tx += txPct; run += lengthM;
    const path = [...(prev ? [prev] : []), ...leg, at];
    stops.push({ key, title, at, view, leg: path, dropPct, cumDropPct: cum, txPct, lengthM: run,
      rows: [...rows, ['Length so far', `${fmtLen(run)}`], ['Cable voltage drop here', `${fmtPct(dropPct)}`],
        ...(txPct ? [['Transformer voltage change', `${fmtPct(txPct)} (not a cable drop)`]] : []), ['Cable drop so far', `${fmtPct(cum)}`]] });
    prev = at;
  };

  // ---- DC: module, string loop, home cables ----
  const mods = str.modules.map(m => local(m.terminal)), mod = mods[P.module], vStr = M.vmp * str.modules.length;
  stop('module', `Module ${P.module + 1} of string ${P.string + 1}, station ${S.id.slice(1)}`, mod, 'walk', [],
    [['What', `Solar module, ${M.w} W class (generic)`], ['Voltage', `${fmtQ(M.vmp, 'V')} DC at maximum power`], ['Current', `${fmtQ(M.imp, 'A')}`]]);
  const dc = built.cables.dc, neg = dc[2 * P.string], pos = dc[2 * P.string + 1];
  const seriesM = len(mods), R = d.dcOhmKm20 / 1000 * (1 + 0.00393 * (d.dcTempC - 20));
  const dropSeries = M.imp * R * seriesM / vStr * 100;
  stop('string', `String ${P.string + 1}: ${str.modules.length} modules in series`, mods.at(-1), 'walk', mods.slice(P.module),
    [['What', 'String loop, + and − conductors through every module'], ['Voltage', `${fmtVolt(vStr)} DC`], ['Current', `${fmtQ(M.imp, 'A')}`],
      ['Cable', `module leads, ${d.dcAreaMm2} mm² Cu (assumed)`]], dropSeries, seriesM);
  const pp = pos.points.map(move), np = neg.points.map(move), homeM = len(pp) + len(np);
  stop('dc', 'DC home cables, + and −, in the DC trench', pp.at(-1), 'walk', pp,
    [['What', `Two home cables (+ ${fmtLen(len(pp))}, − ${fmtLen(len(np))}), duct ${neg.id.split('-')[0]}`], ['Voltage', `${fmtVolt(vStr)} DC`],
      ['Current', `${fmtQ(M.imp, 'A')}`], ['Cable', `${d.dcAreaMm2} mm² Cu, EN 50618 class (assumed size)`]], M.imp * R * homeM / vStr * 100, homeM);

  // ---- AC: up the network tree from the inverter ----
  const invNode = `${S.id}.I${pos.inverter + 1}`, trail = tracePath(graph, sol, invNode), node = new Map(graph.nodes.map(x => [x.id, x]));
  const br = new Map(graph.branches.map(x => [x.id, x])), acPts = built.cables.ac[3 * pos.inverter].points.map(move);
  const fe = graph.branches.find(b => b.kind === 'feeder-cable' && trail.some(t => t.branch === b.id))?.feeder;
  const feeder = fe && graph.branches.filter(b => b.feeder === fe), open = feeder?.find(b => b.open);
  const nodeAt = id => { const a = node.get(id)?.at; return a ? gnd(a, 1.5) : prev; };
  const fault = id => `${fmtQ(ro.nodes.get(id).faultKA, 'kA')} (${fmtQ(ro.nodes.get(id).faultMVA, 'MVA')})`, carry = { drop: 0, tx: 0, len: 0 };
  const isTx = b => /^(st-tx|gt)$/.test(b?.kind || '');
  for (let i = 0; i < trail.length; i++) {
    const { node: id } = trail[i], n = node.get(id), into = i ? ro.branches.get(trail[i - 1].branch) : null, b = i ? br.get(trail[i - 1].branch) : null;
    const k = n.kind, at = id === invNode ? acPts[0] : nodeAt(id), kv = n.kv < 1 ? `${formatNumber(n.kv * 1000, 0)} V AC` : `${n.kv} kV AC`;
    const cur = x => (x ? fmtQ(x.currentA, 'A') : '—'), base = [['Voltage level', kv], ['Fault level', fault(id)]];
    // The grid transformer's LV terminals and the plant-end busbar are passed through, not stopped at: their drop and
    // length are carried into the next stop (the transformer with its HV bay, then the HV cable to the landing).
    if (k === 'gt-lv' || k === 'hv-bus') { carry[isTx(b) ? 'tx' : 'drop'] += into ? into.dropPct : 0; carry.len += b?.lengthM || 0; continue; }
    if (k === 'inverter') { stop('inverter', `Inverter ${pos.inverter + 1} on its pole`, at, 'walk', [], [['What', n.label], ...base,
      ['Current', cur(ro.branches.get(trail[0].branch))]]); continue; }
    const cable = b?.areaMm2 ? `${b.areaMm2} mm² Al, ${fmtLen(b.lengthM)}` : b?.lengthM ? `${fmtLen(b.lengthM)}` : '—';
    const leg = b?.path ? orient(b.path.map(q => (q.length > 2 ? q : gnd(q, 0))), prev) : [];
    const view = (b?.lengthM || 0) > 500 ? 'high' : k === 'lv-board' ? 'walk' : 'drone';
    const title = k === 'lv-board' ? `Station ${S.id.slice(1)} LV board ${id.split('.').at(-1)}` : k === 'st-hv' ? n.label.split(':')[0]
      : k === 'rmu' ? `${n.label}${id === `${S.id}.R` ? ' (this station)' : ''}` : k === 'mv-board' ? n.label : k === 'gt-lv' ? `Grid transformer ${id.split('.')[0]}`
      : k === 'hv-bay' ? `Grid transformer ${id.split('.')[0]} and its HV bay: disconnector, earth switch, surge arresters`
      : n.label;
    // The leg into this stop by what it is: an overhead line is never called a cable; a transformer or bay has no leg row.
    const legName = b?.kind === 'ohl-tee' ? 'Overhead line' : /^(st-tx|gt|hv-bay|source)$/.test(b?.kind || '') ? null : 'Cable';
    const rows = [['What', b?.label || n.label], ...base, ['Current', cur(into)], ...(legName ? [[legName, cable]] : [])];
    if (b?.kind === 'st-tx' || b?.kind === 'gt') {                 // a transformer: its current on the lower-voltage side too
      const lv = node.get(trail[i - 1].node).kv;
      rows.splice(3, 1, ['Current', `${fmtQ(into.currentA, 'A')} at ${b.kv} kV · ${fmtQ(into.currentA * b.kv / lv / 1000, 'kA')} at ${lv < 1 ? formatNumber(lv * 1000, 0) + ' V' : lv + ' kV'}`]);
    }
    if (k === 'rmu' && feeder) rows.push(['Feeder', open ? `${fe} ring: normally-open point at ${open.id}` : `${fe} radial chain: no normally-open point`]);
    if (k === 'mv-board') rows.push(['Board', `earthing transformer + NER on this section; ${graph.branches.some(x => x.kind === 'bus-tie') ? 'bus tie normally open' : 'one section'}`]);
    if (id === 'LAND') rows.push(['Connection', n.meta?.ruleText || 'assumed']);
    if (k === 'lv-board') { stop('ac', `AC cable, 3 × 400 mm² Al, no local isolator, to ${title}`, acPts.at(-1), 'walk', acPts.slice(1), rows, into.dropPct, b.lengthM || 0); continue; }
    const here = into ? into.dropPct : 0;
    stop(k, title, at, view, leg, rows, (isTx(b) ? 0 : here) + carry.drop, (b?.lengthM || 0) + carry.len, (isTx(b) ? here : 0) + carry.tx);
    carry.drop = 0; carry.tx = 0; carry.len = 0;
  }
  const points = stops.flatMap((s, i) => (i ? s.leg.slice(1) : s.leg));
  return { stops, points, panel: panelId(P), nodes: trail.map(t => t.node), branches: trail.map(t => t.branch).filter(Boolean),
    dcDropPct: stops[2].cumDropPct, acDropPct: cum - stops[2].cumDropPct, transformerPct: tx, label: SLD_LABEL };
}

/** The cable drop so far at stop i, split into its DC and AC parts: dc + ac === cum at every stop (the DC part ends at the
 * DC home cables, stop 2). The whole path's totals are f.dcDropPct and f.acDropPct. */
export function dropSoFar(f, i) {
  const s = f.stops[Math.max(0, Math.min(i, f.stops.length - 1))], dc = f.stops[Math.min(Math.max(0, i), 2)].cumDropPct;
  return { cum: s.cumDropPct, dc, ac: s.cumDropPct - dc };
}

// A cable path runs whichever way it was drawn: start it at the end nearer where Follow is now.
function orient(pts, from) {
  if (!from || pts.length < 2) return pts;
  const d = q => Math.hypot(q[0] - from[0], q[1] - from[1]);
  return d(pts[0]) <= d(pts.at(-1)) ? pts : [...pts].reverse();
}

Single-Line Diagram (SLD) Hook

A JavaScript module in the world folder of GlobalGrid2050 that works with solar.

electricalglobalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-hook.mjs · lines 1–28 of 28 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review)

What it does
It calculates solar. Defines sldHook, load, call.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
What it achieves
It is built from the SLD hook helper (`sldHook`), the load step (`load`) and the call step (`call`). The thin, typed hook for the single-line diagram: world.sld.show, world.sld.station(id), Nothing heavy loads until the first call, the first press of Single-line diagram or Follow (Design > Plant). It responds to click, pointerdown and pointerup events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Single-Line Diagram (SLD) Mount (dynamic import)
Used by
none found
Produces
sldHook
Defines here
sldHook, load, call
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/sld-hook.mjs:1-28 · blob 87344fee7694163e33756f2755ad45eb567da9da · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// sld-hook.mjs: the thin, typed hook for the single-line diagram: world.sld.show(), world.sld.station(id),
// world.sld.follow(panelId), next(), back(), play(), pause(), close(), state(), readout(nodeId), source(kA), rules({ cableM, ... }),
// network().
// Nothing heavy loads until the first call, the first press of Single-line diagram or Follow (Design > Plant), or the
// first tap on a module of a placed solar block; then sld-mount.mjs is imported once.

// deps: { api (substrate), design (its blockApi and plantApi), doc }
export function sldHook({ api, design, doc = document }) {
  let mounted = null;
  const load = () => (mounted ||= import('./sld-mount.mjs').then(m => m.mountSld({ api, block: design.blockApi, plant: design.plantApi, doc })));
  const call = name => async (...a) => (await load())[name](...a);
  // Buttons in the Design panel (design-sections.mjs puts them in): Single-line diagram and Follow a module.
  doc.addEventListener('click', e => {
    const id = e.target?.closest?.('#block-sld, #plant-sld, #block-follow')?.id;
    if (!id) return;
    (id === 'block-follow' ? call('follow')() : call('show')()).catch(err => console.warn('single-line diagram: ' + err.message));
  });
  // A tap (not a drag) on the ground: when the solar block is placed and no design tool is in hand, a module starts Follow.
  let down = null;
  api.canvas.addEventListener('pointerdown', e => { down = [e.clientX, e.clientY]; });
  api.canvas.addEventListener('pointerup', e => {
    if (!down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 6) return;
    if (!design.blockApi?.state?.()?.placed || api.design().tool) return;
    load().then(m => m.tap(e.clientX, e.clientY)).catch(() => {});
  });
  return Object.freeze(Object.fromEntries(['show', 'hide', 'station', 'follow', 'next', 'back', 'play', 'pause', 'close', 'state', 'readout', 'source', 'rules',
    'network', 'summary', 'graph', 'refresh'].map(k => [k, call(k)])));
}