GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / testcode/202609060349/pipeline/assets

Testcode — Pipeline (part 2)

A JavaScript module in the assets folder of GlobalGrid2050 covering pipeline filtered and engine graph, using EPSG:27700 and SHA-256, and uses data from the ventus-grid-engine repository.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Electricity markets and data pipelines. Section 912 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. Testcode — Pipeline energy-data · globalgrid2050 / testcode/202609060349/pipeline/assets/202608291447-app.mjs lines 701–1400

Testcode — Pipeline

A JavaScript module in the assets folder of GlobalGrid2050 covering pipeline filtered and engine graph, using EPSG:27700 and SHA-256, and uses data from the ventus-grid-engine repository.

Set aside from the main view: 92% of its lines are the same as releases/202611132345-pipelinenews/assets/202608291447-app.mjs (pipelinenews), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with Releases — PipelineNews; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9244 to pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/202611132345-pipelinenews/assets/202608291447-app.mjs:1-2082 c117027cd73a354235c49f217b1cbe780becca50
  • sha256 5471b7d72f9c025853484c5581de282674d975e5b35f3245856a1db92ce68aa9
  • target sha256 18a65716f320460c65da7326ae8348be1647cc20b9fbacffa056dcc298a1a00b
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

energy-dataglobalgrid2050 / testcode/202609060349/pipeline/assets/202608291447-app.mjs · lines 701–1400 of 2097 · version 2026-08-29 14:47 (continued from section 911) · Entry point · pattern bindProvisionalProjects (shared by 2 files)

What it does
It draws pipeline filtered, engine graph, the REPD register and postcodes. Defines 95 functions or classes, including localityFor, gridFor, substationFor, updateMetricCoverage, describe. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register, postcodes, 33kV, 11kV.
Inputs & outputs
In: data source: ventus-grid-engine data; JSON file 202608291447-registry.json; JSON file engine-graph.json. Out: GeoJSON file pipeline-202609060334-filtered.geojson; downloaded file pipeline-202609060334-filtered.geojson. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 33kV, 11kV.
Downstream impact
Used directly by 1 file: Testcode — Pipeline Page (globalgrid2050, https://globalgrid2050.com/testcode/202609060345/pipeline/). Reached from 20 other entry points, including Homepage V073 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v073.html); Homepage V074 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v074.html); Homepage V075 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v075.html).
What it achieves
It updates metric coverage (`updateMetricCoverage`), compares text (`compareText`) and fetches queue (`FetchQueue`). Its `downloadCsv` function gives CSV download or refusal from active table owner, filtered register rows and official detail partitions (VEDIC: export filtered projects). Its code works with 33 kV, 1 MW and 11 kV. It responds to click, change and input events.
Why it matters
Loaded by the page of the same name at https://globalgrid2050.com/testcode/202609060345/pipeline/.
Application
globalgrid2050 · testcode/202609060349/pipeline/assets · JavaScript module
VEDIC
EXPORT FILTERED PROJECTS (GG2050-VEDIC-000060): Pipeline News · Renewable project register. active_table_owner, filtered_register_rows, official_detail_partitions → csv_download_or_refusal
Uses
Geometry Filter (import), Metric Coverage (import), Project GeoJSON (import), Wider Metrics (import), Metric Details (import), Atlas Pointer Deep Link (import)
Used by
loaded by Testcode — Pipeline Page (script src)
Produces
localityFor, gridFor, substationFor, updateMetricCoverage, describe, metricChip, gridActionHtml, substationActionHtml, compareText, FetchQueue, escapeHtml, normalise
Defines here
onSpineRepaint, syncFilterUrl, sizeFilterActive, nearestStopIndex, clampSize, formatMw, renderCapacityRange, apply, populateCounties, populateStatuses, setButtonState, hydrateFiltersFromUrl, ensureSearchSupplement, loadDetailPartition, detailFor, hydrateDetail, copyProjectId, csvCell, downloadProjectGeoJSON, downloadCsv, used, releaseWiderStatus, clearFilters, bindProjectControls, onRange, onBox, newsTechnology, newsMatches, newsHtml
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060349/pipeline/assets/202608291447-app.mjs:701-1400 · blob db47fc5cb6331117b9f1202d46a3299a627c57a0 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
  const shaped = {
    count: summary.count,
    total: typeof summary.total === "number" ? summary.total : rows.length,
    capacity: summary.capacity,
    largest: summary.largest,
  };
  updateSummary(shaped);
  updateGauges(shaped);
  presentedExport = typeof summary.exportProvider === "function"
    ? summary.exportProvider
    : null;
}

/* ── THE RELEASE SEAM ─────────────────────────────────

   The other half of the summary seam. presentSummary() lets a cut that is not
   the spine's own SAY what it is showing. This lets it be TOLD that the spine
   has taken the table back.

   Measured on 202609040144, live, with WIDER FLEET set to Landfill Gas
   (275 rows, 787.87 MW):

     control used            what the table then held        the control still said
     SORT county A–Z         24 solar, 45 battery, 31 wind   LANDFILL GAS
     COUNTY select           24 solar, 43 battery, 31 wind   LANDFILL GAS
     STATUS Operational       3 solar,  1 battery,  2 wind   LANDFILL GAS
     COUNTY column header     3 solar,  1 battery,  2 wind   LANDFILL GAS
     CLEAR FILTERS            9 solar, 36 battery, 55 wind   LANDFILL GAS

   Zero landfill gas rows in all five, and the wider-fleet note above the table
   went on describing a cut that was no longer on it. The cartridge let go on a
   click of one of the spine's five tabs and on nothing else, so every other
   control that repaints repainted underneath it.

   The fix is not a longer list of control ids. A hand-kept list of controls is
   the same mistake as a hand-kept list of technologies, one layer up, and the
   next control added to this product would not be on it. apply() is the single
   place the spine repaints from its own data — every one of the fourteen
   handlers ends there — so apply() is where the announcement belongs. A cut
   that is not the spine's own registers here and lets go when it fires. */

let spineRepaintListener = null;

function onSpineRepaint(listener) {
  spineRepaintListener = typeof listener === "function" ? listener : null;
}

function syncFilterUrl() {
  const url = new URL(location.href);
  for (const parameter of ["technology", "status", "county", "q", "sort", "repd_ref",
    "mw_min", "mw_max", "geometry"]) url.searchParams.delete(parameter);
  if (technology !== "all") url.searchParams.set("technology", technology);
  if (status !== "All") url.searchParams.set("status", status);
  if (county !== "All") url.searchParams.set("county", county);
  if (requestedRepdRef) url.searchParams.set("repd_ref", requestedRepdRef);
  else if (query) url.searchParams.set("q", query);
  if (sortMode !== "capacity_desc") url.searchParams.set("sort", sortMode);
  if (geometryMode !== "all") url.searchParams.set("geometry",geometryMode);
  if (capacityMin > SIZE_FLOOR) url.searchParams.set("mw_min", String(capacityMin));
  if (capacityMax < SIZE_CEILING) url.searchParams.set("mw_max", String(capacityMax));
  history.replaceState(null, "", url);
}

// PROJECT SIZE range.
//
// The ladder is not linear, and the reason is in the data rather than in
// taste. The register's median project is 12.3 MW and 98% of it sits under
// 500 MW, so a linear 1-5000 track would compress the band almost every user
// cares about into the first two pixels. These stops thicken where the
// projects are and still reach 5000.
const SIZE_STOPS = Object.freeze([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100, 125, 150, 175, 200, 250, 300, 350, 400, 450, 500, 600, 700, 800, 900, 1000, 1250, 1500, 1750, 2000, 2500, 3000, 3500, 4000, 4500, 5000]);
const SIZE_FLOOR = SIZE_STOPS[0];
const SIZE_CEILING = SIZE_STOPS[SIZE_STOPS.length - 1];

let capacityMin = SIZE_FLOOR;
let capacityMax = SIZE_CEILING;

// The full range is "no filter", so it never reaches the URL and never claims
// to have excluded anything.
function sizeFilterActive() {
  return capacityMin > SIZE_FLOOR || capacityMax < SIZE_CEILING;
}

function nearestStopIndex(value) {
  let best = 0;
  for (let i = 1; i < SIZE_STOPS.length; i += 1) {
    if (Math.abs(SIZE_STOPS[i] - value) < Math.abs(SIZE_STOPS[best] - value)) best = i;
  }
  return best;
}

// A typed value is honoured exactly; only the slider snaps. Reversed bounds are
// swapped rather than rejected, because a user who types 40 then 30 means the
// band between them.
//
// The absent cases are tested BEFORE Number(), not after. Number(null) is 0 and
// Number("") is 0 -- both finite -- so a missing mw_max would otherwise clamp to
// the floor and pin the whole register to 1 MW. An emptied box does the same.
// This is the fallback path, so it has to survive the values that mean "nothing
// was given" rather than only the ones that mean "not a number".
function clampSize(value, fallback) {
  if (value === null || value === undefined || value === "") return fallback;
  const number = Number(value);
  if (!Number.isFinite(number)) return fallback;
  return Math.min(SIZE_CEILING, Math.max(SIZE_FLOOR, number));
}

function formatMw(value) {
  return value.toLocaleString("en-GB", { maximumFractionDigits: 2 });
}

function renderCapacityRange() {
  const minRange = document.getElementById("sizeMinRange");
  const maxRange = document.getElementById("sizeMaxRange");
  const minBox = document.getElementById("sizeMinBox");
  const maxBox = document.getElementById("sizeMaxBox");
  const readout = document.getElementById("sizeReadout");
  const selected = document.getElementById("sizeSelected");
  if (!minRange || !maxRange) return;
  const last = SIZE_STOPS.length - 1;
  for (const input of [minRange, maxRange]) {
    input.min = "0";
    input.max = String(last);
    input.step = "1";
  }
  const lowIndex = nearestStopIndex(capacityMin);
  const highIndex = nearestStopIndex(capacityMax);
  minRange.value = String(lowIndex);
  maxRange.value = String(highIndex);
  if (minBox) minBox.value = String(capacityMin);
  if (maxBox) maxBox.value = String(capacityMax);
  if (readout) {
    readout.textContent = sizeFilterActive()
      ? `${formatMw(capacityMin)} – ${formatMw(capacityMax)} MW`
      : `1 – ${formatMw(SIZE_CEILING)} MW · all sizes`;
  }
  if (selected) {
    const left = (lowIndex / last) * 100;
    const right = (highIndex / last) * 100;
    selected.style.left = `${left}%`;
    selected.style.width = `${Math.max(right - left, 0)}%`;
  }
}

function apply({ syncUrl = true } = {}) {
  const tokens = normalise(query).split(" ").filter(Boolean);
  const next = [];
  let capacity = 0;
  let largest = 0;
  for (let index = 0; index < rows.length; index += 1) {
    const item = project(index);
    if (!matchesGeometry(item,geometryMode)) continue;
    if (technology !== "all" && item.technology !== technology) continue;
    // An official status is a value, not a phrase to search inside. Measured
    // across all 7,680 records of this cut, substring and equality agree
    // exactly on the four tab values -- 2,232 / 282 / 1,910 / 840, leak zero --
    // so this changes no answer today. It is tightened because the register has
    // fourteen statuses and the control below now reaches all of them, and
    // "Appeal Refused" inside "Application Refused" is the kind of pair a
    // substring test finds the day someone adds one.
    if (status !== "All" && item.status !== status) continue;
    if (county !== "All" && item.county !== county) continue;
    if (item.capacity_mw < capacityMin || item.capacity_mw > capacityMax) continue;
    if (requestedRepdRef && String(item.repd_ref) !== requestedRepdRef) continue;
    if (!requestedRepdRef && tokens.length) {
      const searchable = searchTextFor(index);
      if (!tokens.every((token) => searchable.includes(token))) continue;
    }
    next.push(index);
    capacity += item.capacity_mw;
    largest = Math.max(largest, item.capacity_mw);
  }
  if (sortMode === "capacity_asc") {
    // capacity_desc is the payload's own row order, so only ascending sorts.
    next.sort((left, right) => project(left).capacity_mw - project(right).capacity_mw || left - right);
  } else if (sortMode === "county_asc" || sortMode === "county_desc") {
    const direction = sortMode === "county_asc" ? 1 : -1;
    next.sort((left, right) =>
      compareText(project(left).county, project(right).county, direction) || left - right);
  } else if (sortMode === "town_asc" || sortMode === "town_desc") {
    const direction = sortMode === "town_asc" ? 1 : -1;
    next.sort((left, right) =>
      compareText(localityFor(project(left))?.town, localityFor(project(right))?.town, direction) || left - right);
  } else if (sortMode === "postcode_asc" || sortMode === "postcode_desc") {
    const direction = sortMode === "postcode_asc" ? 1 : -1;
    next.sort((left, right) =>
      compareText(localityFor(project(left))?.postcode, localityFor(project(right))?.postcode, direction) || left - right);
  } else if (["grid_asc","grid_desc","sub_asc","sub_desc"].includes(sortMode)) {
    // Blanks sort last in BOTH directions, exactly as postcode does. A project
    // with no mapped circuit has not got an infinite distance and has not got a
    // zero one; pushing it to the bottom either way keeps the measured rows
    // contiguous, which is the whole point of sorting by proximity.
    const direction = sortMode.endsWith("_asc") ? 1 : -1;
    const observationFor = sortMode.startsWith("sub_") ? substationFor : gridFor;
    next.sort((left, right) => {
      const a = observationFor(project(left))?.k;
      const b = observationFor(project(right))?.k;
      const aMissing = typeof a !== "number";
      const bMissing = typeof b !== "number";
      if (aMissing && bMissing) return left - right;
      if (aMissing) return 1;
      if (bMissing) return -1;
      return (a - b) * direction || left - right;
    });
  } else if (sortMode === "updated_desc" || sortMode === "updated_asc") {
    const direction = sortMode === "updated_asc" ? 1 : -1;
    next.sort((left, right) => {
      const leftTime = updatedTimestamp(left);
      const rightTime = updatedTimestamp(right);
      if (leftTime === null && rightTime === null) return left - right;
      if (leftTime === null) return 1;
      if (rightTime === null) return -1;
      return direction * (leftTime - rightTime) || left - right;
    });
  }
  filtered = next;
  windowStart = 0;
  const summary = { count: next.length, capacity: Math.round((capacity + Number.EPSILON) * 100) / 100, largest };
  renderTable();
  presentSummary(summary);
  // The spine has just repainted from its own payload. Anything that had the
  // table before this line no longer has it, and must stop saying it does.
  if (spineRepaintListener) spineRepaintListener();
  updateSortHeader();
  if (syncUrl) syncFilterUrl();
}

function populateCounties() {
  const select = document.getElementById("county");
  select.replaceChildren(new Option("🌍 ALL COUNTIES", "All"));
  dictionaries.county.filter(Boolean).sort((left, right) => left.localeCompare(right, "en-GB"))
    .forEach((value) => select.add(new Option(`📍 ${value}`, value)));
}

/* ── EVERY STATUS THE REGISTER HAS ────────────────────────────────────

   The product draws four official statuses as tabs. The register carries
   fourteen, and the other ten are 2,416 of this cut's 7,680 records -- just
   under a third:

     Application Refused 667 · Revised 531 · Application Withdrawn 420
     Appeal Refused 295 · Planning Permission Expired 227 · Abandoned 221
     Appeal Withdrawn 39 · Decommissioned 9 · Appeal Lodged 5
     No Application Required 2

   Every one of those rows is loaded, searchable, sortable and in the CSV. None
   of them could be SELECTED. ALL STATUS was the only view that contained them,
   and nothing on the surface said that the four tabs stop 2,416 records short
   of the register -- which is exactly what the product's own STATUS DISCIPLINE
   panel promises it will not do.

   One labelled select, in the status row, on the same pattern the technology
   row already settled on: the names and the counts are read from the payload
   at boot and are never listed in source, each option carries its own row
   count so a two-row status is visibly a two-row status, and the control costs
   the row one line at every width. It reuses the wider-fleet control's own
   classes, so it is the same object to look at and inherits the same 44px
   floor on a phone.

   It is NOT a separate cut. These are the spine's own rows in the spine's own
   payload, so this sets the spine's own `status` and calls the spine's own
   apply(). Nothing renders a second table. */

function populateStatuses() {
  const row = document.getElementById("status");
  if (!row || document.getElementById("widerStatus")) return;
  const counts = new Map();
  for (let index = 0; index < rows.length; index += 1) {
    const value = project(index).status;
    if (value) counts.set(value, (counts.get(value) || 0) + 1);
  }
  for (const name of counts.keys()) STATUSES.add(name);
  const rest = [...counts.keys()].filter((name) => !STATUS_TABS.includes(name))
    .sort((left, right) => counts.get(right) - counts.get(left));
  if (!rest.length) return;
  const covered = rest.reduce((total, name) => total + counts.get(name), 0);

  const group = document.createElement("div");
  group.className = "wider-fleet-control";
  const label = document.createElement("label");
  label.className = "wider-fleet-label";
  label.htmlFor = "widerStatus";
  label.textContent = "MORE STATUS";
  const select = document.createElement("select");
  select.id = "widerStatus";
  select.className = "wider-fleet-select";
  select.setAttribute("aria-label", `${rest.length} more official REPD statuses `
    + `outside this row's four, ${covered.toLocaleString("en-GB")} records`);
  const placeholder = document.createElement("option");
  placeholder.value = "";
  placeholder.textContent = `+ ${rest.length} MORE REPD STATUSES `
    + `(${covered.toLocaleString("en-GB")} RECORDS)`;
  select.appendChild(placeholder);
  for (const name of rest) {
    const option = document.createElement("option");
    option.value = name;
    option.textContent = `${name.toUpperCase()} · ${counts.get(name).toLocaleString("en-GB")}`;
    select.appendChild(option);
  }
  select.addEventListener("change", () => {
    // The empty entry is the way back to ALL STATUS, not an empty state.
    status = select.value || "All";
    select.classList.toggle("is-chosen", Boolean(select.value));
    setButtonState("#status", "officialStatus", status);
    apply();
  });
  group.append(label, select);
  row.appendChild(group);
}

function setButtonState(container, dataKey, selected) {
  document.querySelectorAll(`${container} .btn`).forEach((button) => {
    const active = button.dataset[dataKey] === selected;
    button.classList.toggle("active", active);
    button.setAttribute("aria-pressed", String(active));
  });
}

function hydrateFiltersFromUrl() {
  const parameters = new URLSearchParams(location.search);
  const requestedTechnology = parameters.get("technology") || "all";
  const requestedStatus = parameters.get("status") || "All";
  const requestedCounty = parameters.get("county") || "All";
  const requestedSort = parameters.get("sort") || "capacity_desc";
  geometryMode=["all","located","missing"].includes(parameters.get("geometry"))?parameters.get("geometry"):"all";
  document.getElementById("geometryFilter").value=geometryMode;
  technology = TECHNOLOGIES.has(requestedTechnology) ? requestedTechnology : "all";
  status = STATUSES.has(requestedStatus) ? requestedStatus : "All";
  county = dictionaries.county.includes(requestedCounty) ? requestedCounty : "All";
  const repdRefParameter = parameters.get("repd_ref") || "";
  requestedRepdRef = /^\d+$/u.test(repdRefParameter) ? repdRefParameter : "";
  query = requestedRepdRef || (parameters.get("q") || "");
  sortMode = SORTS.has(requestedSort) ? requestedSort : "capacity_desc";
  setButtonState("#tech", "technology", technology);
  releaseWiderStatus(status);
  setButtonState("#status", "officialStatus", status);
  document.getElementById("county").value = county;
  document.getElementById("search").value = query;
  document.getElementById("sortProjects").value = sortMode;
  capacityMin = clampSize(parameters.get("mw_min"), SIZE_FLOOR);
  capacityMax = clampSize(parameters.get("mw_max"), SIZE_CEILING);
  if (capacityMin > capacityMax) [capacityMin, capacityMax] = [capacityMax, capacityMin];
  renderCapacityRange();
}

async function ensureSearchSupplement() {
  if (searchSupplement) return searchSupplement;
  runtimeEvidence.searchRequests += 1;
  const payload = await fetchImmutable(registry.assets.search.path);
  invariant(payload.schema === registry.assets.search.schema, "search schema mismatch");
  invariant(payload.generation === registry.assets.search.generation, "search generation mismatch");
  invariant(payload.cache_identity === registry.assets.search.cache_identity, "search cache identity mismatch");
  invariant(payload.row_alignment === registry.cache_contract.search_index.row_alignment, "search row alignment mismatch");
  invariant(Array.isArray(payload.rows) && payload.rows.length === rows.length, "search row count mismatch");
  searchSupplement = payload.rows;
  runtimeEvidence.searchReady = true;
  return searchSupplement;
}

async function loadDetailPartition(partitionIndex) {
  if (detailPromises.has(partitionIndex)) return detailPromises.get(partitionIndex);
  const entry = registry.detail_partitions[partitionIndex];
  invariant(entry, `detail partition ${partitionIndex} missing`);
  const promise = detailQueue.add(async () => {
    runtimeEvidence.detailRequests += 1;
    const payload = await fetchImmutable(entry.path);
    invariant(payload.schema === registry.detail_schema, `${entry.path} detail schema mismatch`);
    invariant(payload.record_count === entry.record_count && payload.projects.length === entry.record_count, `${entry.path} detail count mismatch`);
    for (const item of payload.projects) detailByRef.set(String(item.repd_ref), item);
    runtimeEvidence.maximumDetailConcurrency = detailQueue.maximumActive;
    return payload.projects;
  });
  detailPromises.set(partitionIndex, promise);
  promise.catch(() => detailPromises.delete(partitionIndex));
  return promise;
}

async function detailFor(index) {
  const ref = String(rows[index][FIELD.repdRef]);
  if (detailByRef.has(ref)) return detailByRef.get(ref);
  const partition = Math.floor(index / registry.detail_partition_size);
  await loadDetailPartition(partition);
  const item = detailByRef.get(ref);
  invariant(item, `REPD ${ref} missing from declared detail partition`);
  return item;
}

async function hydrateDetail(details) {
  if (details.dataset.loaded === "true" || details.dataset.loading === "true") return;
  details.dataset.loading = "true";
  const container = details.querySelector(".record-grid");
  try {
    const item = await detailFor(Number(details.dataset.detailIndex));
    container.innerHTML = `<div><b>PLANNING AUTHORITY</b><span>${escapeHtml(item.planning_authority || "not supplied by REPD")}</span></div><div><b>PLANNING REF</b><span>${escapeHtml(item.planning_application_reference || "not supplied by REPD")}</span></div><div><b>DEVELOPMENT ID</b><span>${escapeHtml(item.gg_development_id || "not assigned")}</span></div><div><b>LIFECYCLE</b><span>${escapeHtml(i  … [line shortened here: 682 characters; full line on GitHub]
    details.dataset.loaded = "true";
  } catch (error) {
    console.error(error);
    container.innerHTML = '<div class="detail-error">Official project details unavailable; the canonical row remains live.</div>';
  } finally {
    delete details.dataset.loading;
  }
}

async function copyProjectId(button) {
  const value = button.dataset.copyId;
  try {
    await navigator.clipboard.writeText(value);
  } catch {
    const field = document.createElement("textarea");
    field.value = value;
    field.style.position = "fixed";
    field.style.opacity = "0";
    document.body.appendChild(field);
    field.select();
    document.execCommand("copy");
    field.remove();
  }
  const original = button.textContent;
  button.textContent = "COPIED";
  setTimeout(() => { button.textContent = original; }, 1200);
}

function csvCell(value) {
  let text = value === null || value === undefined ? "" : String(value);
  if (/^(?:[=+\-@]|\s+[=+\-@]|\t|\r|\n)/u.test(text)) text = `'${text}`;
  return `"${text.replaceAll('"', '""')}"`;
}

/* The product's CSV contract, named once. It is the export's header row, and
   it is also the question an export provider is asked: a cut that is not the
   spine's own is handed these column names and answers with the ones it can
   honestly fill, so the refusal below counts real columns rather than a
   number somebody typed. Add a column here and the refusal re-counts itself.
*/
const CSV_COLUMNS = Object.freeze(["Site Name", "REPD Ref", "GlobalGrid Project ID", "GlobalGrid Development ID", "Identity Status", "Identity Confidence", "Technology", "Official REPD Technology", "Official REPD Capacity", "Capacity Unit", "Official REPD Status", "Derived Lifecycle", "Operator or Applicant", "County", "Region", "Country", "Planning Authority", "Planning Application Reference", "R  … [line shortened here: 1,147 characters; full line on GitHub]

function downloadProjectGeoJSON() {
  const meta=document.getElementById('exportMeta');
  if(presentedExport){meta.textContent='GeoJSON export declined: the wider-fleet view owns this table. Select a main pipeline technology first.';return;}
  try {
    const data=projectGeoJSON(filtered.map(index=>({...project(index),capacity_unit:UNITS[project(index).technology]})),{release:'202609060334',source:registry.source,filters:Object.fromEntries(new URL(location.href).searchParams)});
    const url=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)+'\n'],{type:'application/geo+json'}));
    const anchor=document.createElement('a');anchor.href=url;anchor.download='pipeline-202609060334-filtered.geojson';document.body.append(anchor);anchor.click();anchor.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);
    meta.textContent=data.metadata.records.toLocaleString('en-GB')+' filtered records exported as GeoJSON; '+data.metadata.null_geometry+' retain null geometry.';
  } catch(error){meta.textContent='GeoJSON export failed: '+error.message;}
}

async function downloadCsv(event) {
  event.preventDefault();
  const meta = document.getElementById("exportMeta");
  /* ASKED BEFORE ANYTHING IS BUILT, AND FAILING CLOSED.

     `filtered` holds indices into the spine's OWN payload. A wider-fleet row
     is not in that index space at all, so with one flywheel on screen this
     function used to map the spine's 3,563 solar indices, write them to disk
     under a flywheel heading, and report "3,563 filtered records exported".
     That file leaves the platform and cannot be recalled.

     So: if any cut other than the spine's own owns the table, the spine does
     not write the file. The cut answers, in words, what it can and cannot
     fill. A provider that answers nothing useful is refused too -- the
     default here is no CSV, never the spine's rows, because the failure being
     fixed is precisely a plausible file full of the wrong rows. */
  if (presentedExport) {
    const answer = presentedExport({ columns: CSV_COLUMNS }) || {};
    meta.textContent = typeof answer.declined === "string" && answer.declined
      ? answer.declined
      : "EXPORT DECLINED \u00b7 the view on screen is not this product's own cut "
        + "and did not state what it can export. No CSV was written.";
    meta.classList.add("is-declined");
    if (Array.isArray(answer.missing) && answer.missing.length) {
      meta.dataset.exportDeclinedColumns = answer.missing.join(" | ");
    }
    return;
  }
  meta.textContent = "Loading full official fields for filtered export…";
  try {
    await Promise.all(registry.detail_partitions.map((_, index) => loadDetailPartition(index)));
    const headers = CSV_COLUMNS;
    const outputRows = filtered.map((index) => {
      const compact = project(index);
      const item = detailByRef.get(String(compact.repd_ref));
      invariant(item, `REPD ${compact.repd_ref} unavailable for export`);
      const signal = signalFor(compact);
      return [item.name, item.repd_ref, item.gg_project_id, item.gg_development_id, item.identity_status, item.identity_confidence, LABELS[item.technology], item.repd_technology, item.capacity_mw, UNITS[item.technology], item.status, item.lifecycle, item.operator, item.county, item.region, item.country, item.planning_authority, item.planning_application_reference, item.repd_record_updated, item.pl  … [line shortened here: 1,281 characters; full line on GitHub]
    });
    const content = `\ufeff${[headers, ...outputRows].map((row) => row.map(csvCell).join(",")).join("\r\n")}`;
    const url = URL.createObjectURL(new Blob([content], { type: "text/csv;charset=utf-8" }));
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = `globalgrid2050_uk_renewables_pipeline_v8_fast_${new Date().toISOString().slice(0, 10)}.csv`;
    anchor.click();
    URL.revokeObjectURL(url);
    meta.textContent = `${filtered.length.toLocaleString("en-GB")} filtered records exported`;
  } catch (error) {
    console.error(error);
    meta.textContent = "export unavailable; no partial CSV was produced";
  }
}

/* The select and the four tabs are one control between them. Whoever sets the
   status last says so here, so the two can never name different things -- the
   defect this release already fixed once, one row up, for technology. */
function releaseWiderStatus(current) {
  const select = document.getElementById("widerStatus");
  if (!select) return;
  const value = STATUS_TABS.includes(current) ? "" : current;
  select.value = value;
  select.classList.toggle("is-chosen", Boolean(value));
}

function clearFilters(event) {
  geometryMode="all";document.getElementById("geometryFilter").value="all";
  event.preventDefault();
  technology = "all";
  status = "All";
  county = "All";
  query = "";
  requestedRepdRef = "";
  sortMode = "capacity_desc";
  setButtonState("#tech", "technology", technology);
  releaseWiderStatus(status);
  setButtonState("#status", "officialStatus", status);
  document.getElementById("county").value = county;
  document.getElementById("search").value = "";
  document.getElementById("sortProjects").value = sortMode;
  capacityMin = SIZE_FLOOR;
  capacityMax = SIZE_CEILING;
  renderCapacityRange();
  apply();
}

function bindProjectControls() {
  if (controlsBound) return;
  controlsBound = true;
  document.querySelectorAll("#tech .btn").forEach((button) => {
    button.addEventListener("click", () => {
      technology = button.dataset.technology;
      setButtonState("#tech", "technology", technology);
      apply();
    });
  });
  document.querySelectorAll("#status .btn").forEach((button) => {
    button.addEventListener("click", () => {
      status = button.dataset.officialStatus;
      // The tabs and the select are one choice, so choosing a tab lets the
      // select go rather than leaving it naming a status the table has left.
      releaseWiderStatus(status);
      setButtonState("#status", "officialStatus", status);
      apply();
    });
  });
  document.getElementById("county").addEventListener("change", (event) => { county = event.target.value; apply(); });
  const sizeMinRange = document.getElementById("sizeMinRange");
  const sizeMaxRange = document.getElementById("sizeMaxRange");
  const sizeMinBox = document.getElementById("sizeMinBox");
  const sizeMaxBox = document.getElementById("sizeMaxBox");
  if (sizeMinRange && sizeMaxRange) {
    // Dragging one handle past the other pushes rather than crosses, so the
    // band can be collapsed to a single stop but never inverted.
    const onRange = () => {
      let low = Number(sizeMinRange.value);
      let high = Number(sizeMaxRange.value);
      if (low > high) { const swap = low; low = high; high = swap; }
      capacityMin = SIZE_STOPS[low];
      capacityMax = SIZE_STOPS[high];
      renderCapacityRange();
      apply();
    };
    sizeMinRange.addEventListener("input", onRange);
    sizeMaxRange.addEventListener("input", onRange);
  }
  // The boxes take an exact value, so a band the ladder does not carry -- 33 to
  // 37 -- is still reachable. Committed on change, not on every keystroke.
  const onBox = () => {
    capacityMin = clampSize(sizeMinBox?.value, SIZE_FLOOR);
    capacityMax = clampSize(sizeMaxBox?.value, SIZE_CEILING);
    if (capacityMin > capacityMax) {
      const swap = capacityMin; capacityMin = capacityMax; capacityMax = swap;
    }
    renderCapacityRange();
    apply();
  };
  if (sizeMinBox) sizeMinBox.addEventListener("change", onBox);
  if (sizeMaxBox) sizeMaxBox.addEventListener("change", onBox);
  const sizeReset = document.getElementById("sizeReset");
  if (sizeReset) {
    sizeReset.addEventListener("click", () => {
      capacityMin = SIZE_FLOOR;
      capacityMax = SIZE_CEILING;
      renderCapacityRange();
      apply();
    });
  }
  document.getElementById("sortProjects").addEventListener("change", (event) => { sortMode = event.target.value; apply(); });
  for (const [column, spec] of Object.entries(SORT_HEADINGS)) {
    const heading = document.getElementById("sort" + column.charAt(0).toUpperCase() + column.slice(1));
    if (!heading) continue;
    heading.addEventListener("click", () => {
      // First click takes the column's natural direction; clicking the column
      // you are already on flips it.
      sortMode = sortMode === spec.first
        ? (spec.first === spec.desc ? spec.asc : spec.desc)
        : spec.first;
      document.getElementById("sortProjects").value = sortMode;
      apply();
    });
  }
  document.getElementById("search").addEventListener("input", (event) => {
    requestedRepdRef = "";
    query = event.target.value.trim();
    clearTimeout(searchTimer);
    if (!query) {
      apply();
      return;
    }
    document.getElementById("resultsMeta").textContent = "loading complete planning/reference search index…";
    searchTimer = setTimeout(async () => {
      try {
        await ensureSearchSupplement();
        apply();
      } catch (error) {
        console.error(error);
        apply();
      }
    }, 120);
  });
  document.getElementById("export").addEventListener("click", downloadCsv);
  document.getElementById("exportInline").addEventListener("click", downloadCsv);
  document.getElementById("exportGeoJSON").addEventListener("click", downloadProjectGeoJSON);
  document.getElementById("clearFilters").addEventListener("click", clearFilters);
  document.getElementById("geometryFilter").addEventListener("change",event=>{geometryMode=event.target.value;apply();});
  document.getElementById("tbody").addEventListener("click", (event) => {
    const copy = event.target.closest(".copy-id");
    if (copy) copyProjectId(copy);
    const summary = event.target.closest("summary");
    const details = summary?.closest("details[data-detail-index]");
    if (details) hydrateDetail(details);
  });
}

function newsTechnology(row) {
  return String(row[NEWS_FIELD.technology] || row[NEWS_FIELD.regionalTechnology] || "").toUpperCase();
}

function newsMatches(row) {
  const event = String(row[NEWS_FIELD.event] || "").toUpperCase();
  const newsTechnologyValue = newsTechnology(row);
  const regional = row[NEWS_FIELD.region];
  if (newsMode === "UK" && row[NEWS_FIELD.canonical] !== true) return false;
  if (newsMode === "INTERNATIONAL" && !regional) return false;
  if (newsMode === "US" && regional !== "US") return false;
  if (newsMode === "EUROPE" && regional !== "EUROPE") return false;
  if (newsMode === "SOLAR" && !newsTechnologyValue.includes("SOLAR")) return false;
  if (newsMode === "BESS" && !newsTechnologyValue.includes("BESS")) return false;
  if (newsMode === "CONSENT" && event !== "CONSENT") return false;
  if (newsMode === "CONSTRUCTION" && event !== "CONSTRUCTION") return false;
  if (newsMode === "OPERATIONAL" && event !== "OPERATIONAL") return false;
  if (newsMode === "FINANCE" && !FINANCE_EVENTS.has(event)) return false;
  if (newsQuery) {
    const haystack = normalise([
      row[NEWS_FIELD.headline],
      row[NEWS_FIELD.project],
      row[NEWS_FIELD.operator],
      row[NEWS_FIELD.county],
      row[NEWS_FIELD.source],
      row[NEWS_FIELD.event],
      row[NEWS_FIELD.eventDetail],
      row[NEWS_FIELD.repdRef],
      row[NEWS_FIELD.projectId],
      row[NEWS_FIELD.relatedContextRepdRef],
      row[NEWS_FIELD.relatedContextProject],
      row[NEWS_FIELD.bindingLabel],
      JSON.stringify(row[NEWS_FIELD.relatedComponents] || []),
    ].join(" "));
    const tokens = normalise(newsQuery).split(" ").filter(Boolean);
    if (!tokens.every((token) => haystack.includes(token))) return false;
  }
  return true;
}

function newsHtml(row) {
  const regional = row[NEWS_FIELD.region];
  const technologyValue = newsTechnology(row);
  const articleClass = technologyValue.includes("BESS") ? "bess" : "solar";
  // With no repd_ref there is no project this story is about, so it must not
  // carry one. This is what captioned a New Jersey storage story "Wilton
  // International, Greystones Road".
  const projectName = String(row[NEWS_FIELD.repdRef] || "").trim()
    ? (row[NEWS_FIELD.project] || "")
    : "";
  const capacity = Number(row[NEWS_FIELD.capacity] || 0);
  const role = String(row[NEWS_FIELD.role] || "");
  const relatedContextProject = String(row[NEWS_FIELD.relatedContextProject] || "");
  const relatedContextRef = String(row[NEWS_FIELD.relatedContextRepdRef] || "");
  const relatedComponents = Array.isArray(row[NEWS_FIELD.relatedComponents]) ? row[NEWS_FIELD.relatedComponents] : [];
  const eventDetail = String(row[NEWS_FIELD.eventDetail] || "").replaceAll("_", " ");
  const quality = role === "RELATED_MENTION"
    ? `<span class="news-quality unverified">${escapeHtml(row[NEWS_FIELD.bindingLabel] || "RELATED CONTEXT ONLY — NOT A PROJECT BINDING")}</span>${relatedContextProject ? ` · context: ${escapeHtml(relatedContextProject)}` : ""}${relatedContextRef ? ` · related REPD ${escapeHtml(relatedContextRef)}` : ""} · no project signal`
    : row[NEWS_FIELD.canonical] === true