In this section
- JavaScript App V9 6 2 other · pipelinenews / ui/javascript/202608261806-app-v9-6-2.js lines 1–28
- JavaScript V8 Fast Runtime energy-data · pipelinenews / ui/javascript/202608270055-v8-fast-runtime.js lines 1–672
JavaScript App V9 6 2
A JavaScript module in PipelineNews.
otherpipelinenews / ui/javascript/202608261806-app-v9-6-2.js · lines 1–28 of 28 · version 2026-08-26 18:06 · Not reached from any entry point (candidate for review)
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Downstream impact
- Used directly by 1 file: Compare V9 6 2 to Compiled (pipelinenews).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
- Why it matters
- Run by Compare V9 6 2 to Compiled.
- Application
- pipelinenews · ui/javascript · JavaScript module
- Uses
- Gauges V9 2 (import), JavaScript Newspaper V9 6 2 (import), JavaScript Projects V9 5 1 (import), Plugin Host (import)
- Used by
- run by Compare V9 6 2 to Compiled (script call)
- 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
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 ui/javascript/202608261806-app-v9-6-2.js:1-28 · blob f386fa4aab77defd75c7d9ca0bebf66239dad0c7 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import { initialiseGaugesV9_2 } from "./202608261725-gauges.js";
import { bindNewspaperV9_6_2, loadNewsV9_6_2 } from "./202608261802-newspaper-v9-6-2.js";
import {
bindProjectControlsV9_5_1,
loadProjectsV9_5_1,
refreshProjectsV9_5_1,
} from "./202608261804-projects-v9-5-1.js";
import { startPlugins } from "./202608261557-startplugins.js";
startPlugins([
{ id: "gauges", start: initialiseGaugesV9_2 },
{
id: "newspaper",
dependsOn: ["gauges"],
start() {
bindNewspaperV9_6_2(refreshProjectsV9_5_1);
loadNewsV9_6_2();
},
},
{
id: "projects",
dependsOn: ["gauges", "newspaper"],
start() {
bindProjectControlsV9_5_1();
loadProjectsV9_5_1();
},
},
]);JavaScript V8 Fast Runtime
A JavaScript file in PipelineNews covering the Renewable Energy Planning Database (REPD) register, battery storage (BESS), solar and wind, using EPSG:27700 and SHA-256, and uses data from the GridAtlas repository.
energy-datapipelinenews / ui/javascript/202608270055-v8-fast-runtime.js · lines 1–672 of 862 · version 2026-08-27 00:55 · Not reached from any entry point (candidate for review) · pattern ensureSearchSupplement (shared by 6 files)
- What it does
- It draws the REPD register, battery storage (BESS), solar and wind. Defines 48 functions or classes, including FetchQueue, escapeHtml, normalise, invariant, arraysEqual. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, battery storage (BESS), solar, wind.
- Inputs & outputs
- In: data source: gridatlas data. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- What it achieves
- It fetches queue (`FetchQueue`), hashes JSON (`hashJson`) and fetches immutable (`fetchImmutable`). Its `downloadCsv` function gives CSV download or refusal from active table owner, filtered register rows and official detail partitions (VEDIC: export filtered projects). It responds to click, change and input events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- pipelinenews · ui/javascript · script
- 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
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- FetchQueue, escapeHtml, normalise, invariant, arraysEqual, hashJson, fetchImmutable, promise, dictionary, project, compactSearchText, formatNumber
- Defines here
- FetchQueue, escapeHtml, normalise, invariant, arraysEqual, hashJson, fetchImmutable, promise, dictionary, project, compactSearchText, formatNumber, displayDate, updatedTimestamp, atlasUrl, signalFor, relationshipSummary, rowHtml, ensureWindowControls, renderTable, updateSortHeader, updateChart, updateGauges, updateSummary, syncFilterUrl, apply, populateCounties, setButtonState, hydrateFiltersFromUrl, ensureSearchSupplement
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 ui/javascript/202608270055-v8-fast-runtime.js:1-672 · blob f5ac4eb56e96b8036c47f08c874f94a8d1970121 · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
const GENERATION = "__FAST_GENERATION__";
const EXPECTED_COMPILER_METHOD = "__FAST_COMPILER_METHOD__";
const EXPECTED_CACHE_IDENTITY = "__FAST_CACHE_IDENTITY__";
const REGISTRY_URL = `data/${GENERATION}-v8-fast-registry.json`;
const WINDOW_SIZE = 50;
const NEWS_WINDOW_SIZE = 30;
const DETAIL_CONCURRENCY = 4;
const PROJECT_FIELDS = Object.freeze([
"repd_ref",
"gg_project_id",
"name",
"technology",
"status",
"capacity_mw",
"county",
"region",
"operator",
"repd_record_updated",
"geometry_status",
"latitude",
"longitude",
]);
const NEWS_FIELDS = Object.freeze([
"gg_article_id",
"repd_ref",
"gg_project_id",
"project",
"technology",
"capacity_mw",
"operator",
"county",
"country",
"event",
"headline",
"published",
"source",
"url",
"confidence",
"canonical_relevant",
"role",
"eligible_for_news_signal",
"regional_classification",
"regional_technology",
"regional_evidence",
]);
const FIELD = Object.freeze({
repdRef: 0,
projectId: 1,
name: 2,
technology: 3,
status: 4,
capacity: 5,
county: 6,
region: 7,
operator: 8,
updated: 9,
geometry: 10,
latitude: 11,
longitude: 12,
});
const NEWS_FIELD = Object.freeze({
articleId: 0,
repdRef: 1,
projectId: 2,
project: 3,
technology: 4,
capacity: 5,
operator: 6,
county: 7,
country: 8,
event: 9,
headline: 10,
published: 11,
source: 12,
url: 13,
confidence: 14,
canonical: 15,
role: 16,
eligible: 17,
region: 18,
regionalTechnology: 19,
regionalEvidence: 20,
});
const LABELS = Object.freeze({
solar: "Solar",
bess: "Battery Storage",
wind_onshore: "Onshore Wind",
wind_offshore: "Offshore Wind",
});
const COLOURS = Object.freeze({
solar: "#ffff00",
bess: "#ffae00",
wind_onshore: "#00ffff",
wind_offshore: "#0066ff",
});
const UNITS = Object.freeze({ solar: "MWp", bess: "MW", wind_onshore: "MW", wind_offshore: "MW" });
const TECHNOLOGIES = new Set(["all", "solar", "bess", "wind_onshore", "wind_offshore"]);
const STATUSES = new Set(["All", "Operational", "Under Construction", "Awaiting Construction", "Application Submitted"]);
const SORTS = new Set(["capacity_desc", "updated_desc", "updated_asc"]);
const FINANCE_EVENTS = new Set(["FINANCIAL CLOSE", "ACQUISITION"]);
const immutablePromises = new Map();
class FetchQueue {
constructor(limit) {
this.limit = limit;
this.active = 0;
this.maximumActive = 0;
this.pending = [];
}
add(task) {
return new Promise((resolve, reject) => {
this.pending.push({ task, resolve, reject });
this.drain();
});
}
drain() {
while (this.active < this.limit && this.pending.length) {
const entry = this.pending.shift();
this.active += 1;
this.maximumActive = Math.max(this.maximumActive, this.active);
Promise.resolve()
.then(entry.task)
.then(entry.resolve, entry.reject)
.finally(() => {
this.active -= 1;
this.drain();
});
}
}
}
const detailQueue = new FetchQueue(DETAIL_CONCURRENCY);
const detailPromises = new Map();
const detailByRef = new Map();
const charts = { capacity: null, projects: null, largest: null };
let registry = null;
let projectPayload = null;
let rows = [];
let dictionaries = null;
let searchSupplement = null;
let newsRows = [];
let filtered = [];
let updatedTimes = [];
let windowStart = 0;
let newsStart = 0;
let technology = "all";
let status = "All";
let county = "All";
let query = "";
let sortMode = "capacity_desc";
let newsMode = "ALL";
let newsQuery = "";
let searchTimer = null;
let controlsBound = false;
const runtimeEvidence = {
generation: GENERATION,
detailConcurrency: DETAIL_CONCURRENCY,
maximumDetailConcurrency: 0,
detailRequests: 0,
newsRequests: 0,
searchRequests: 0,
chartsReady: false,
newsReady: false,
searchReady: false,
};
globalThis.__PIPELINENEWS_FAST__ = runtimeEvidence;
function escapeHtml(value) {
return String(value ?? "").replace(/[&<>"']/g, (character) => ({
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
})[character]);
}
function normalise(value) {
return String(value ?? "")
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.toLocaleLowerCase("en-GB")
.replace(/&/g, " and ")
.replace(/[^a-z0-9.-]+/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function invariant(condition, message) {
if (!condition) throw new Error(`PipelineNews V8 fast runtime: ${message}`);
}
function arraysEqual(left, right) {
return Array.isArray(left) && Array.isArray(right)
&& left.length === right.length
&& left.every((value, index) => value === right[index]);
}
async function hashJson(value) {
invariant(globalThis.crypto?.subtle, "Web Crypto unavailable for cache-contract verification");
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(value)));
return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");
}
async function fetchImmutable(url, { timeoutMs = 15000 } = {}) {
const target = new URL(url, document.baseURI);
invariant(target.origin === location.origin, `cross-origin cartridge rejected: ${target.href}`);
const key = target.href;
if (immutablePromises.has(key)) return immutablePromises.get(key);
const promise = (async () => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(target, { cache: "force-cache", signal: controller.signal });
invariant(response.ok, `${target.pathname} returned HTTP ${response.status}`);
return response.json();
} finally {
clearTimeout(timeout);
}
})();
immutablePromises.set(key, promise);
promise.catch(() => immutablePromises.delete(key));
return promise;
}
function dictionary(name, index) {
return dictionaries[name][index] ?? "";
}
function project(index) {
const row = rows[index];
return {
index,
row,
repd_ref: row[FIELD.repdRef],
gg_project_id: row[FIELD.projectId],
name: row[FIELD.name],
technology: dictionary("technology", row[FIELD.technology]),
status: dictionary("status", row[FIELD.status]),
capacity_mw: Number(row[FIELD.capacity]),
county: dictionary("county", row[FIELD.county]),
region: dictionary("region", row[FIELD.region]),
operator: dictionary("operator", row[FIELD.operator]),
repd_record_updated: row[FIELD.updated],
geometry_status: dictionary("geometry_status", row[FIELD.geometry]),
latitude: row[FIELD.latitude],
longitude: row[FIELD.longitude],
};
}
function compactSearchText(index) {
const item = project(index);
return normalise([
item.name,
item.operator,
item.repd_ref,
item.gg_project_id,
item.technology,
item.status,
item.capacity_mw,
item.county,
item.region,
item.repd_record_updated,
item.geometry_status,
].join(" "));
}
function formatNumber(value) {
return (Number(value) || 0).toLocaleString("en-GB", { maximumFractionDigits: 2 });
}
function displayDate(value) {
if (!value) return "not supplied by REPD";
const [year, month, day] = String(value).split("-");
return year && month && day ? `${day}/${month}/${year}` : String(value);
}
function updatedTimestamp(index) {
return updatedTimes[index] ?? null;
}
function atlasUrl(item) {
if (item.geometry_status !== "valid") return "";
const url = new URL("https://ventusltd.github.io/gridatlas/202608300453-atlas-v9/");
url.searchParams.set("repd_ref", item.repd_ref);
url.searchParams.set("technology", item.technology);
url.searchParams.set("longitude", item.longitude);
url.searchParams.set("latitude", item.latitude);
return url.href;
}
function signalFor(item) {
const signal = registry.signals[item.repd_ref];
if (!signal) return { label: "—", cls: "none", note: "no exact canonical PRIMARY_MATCH" };
const [eventValue, confidence, published] = signal;
const event = String(eventValue || "PROJECT UPDATE").toUpperCase();
if (event === "CONSENT") return { label: "APPROVED*", cls: "approved", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
if (event === "OPERATIONAL") return { label: "OPERATIONAL*", cls: "operational", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
if (event === "CONSTRUCTION") return { label: "CONSTRUCTION*", cls: "construction", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
if (FINANCE_EVENTS.has(event)) return { label: event === "ACQUISITION" ? "M&A*" : "FINANCED*", cls: "finance", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
return { label: `${event}*`.slice(0, 22), cls: "", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
}
function relationshipSummary(item) {
const development = Array.isArray(item.development_repd_refs) ? item.development_repd_refs.length : 0;
const direct = Array.isArray(item.direct_related_repd_refs) ? item.direct_related_repd_refs.length : 0;
const siblings = Array.isArray(item.planning_sibling_repd_refs) ? item.planning_sibling_repd_refs.length : 0;
return `${development} development · ${direct} direct · ${siblings} planning sibling record(s)`;
}
function rowHtml(index) {
const item = project(index);
const label = LABELS[item.technology];
const signal = signalFor(item);
const locationText = [item.county, item.region].filter(Boolean).join(" · ");
const news = new URL("https://www.google.com/search");
news.searchParams.set("q", `${item.name} ${label} UK`);
news.searchParams.set("tbm", "nws");
const atlas = atlasUrl(item);
const mapAction = atlas
? `<a class="action-link atlaslink" target="_blank" rel="noopener" href="${escapeHtml(atlas)}">MAP ↗</a>`
: '<span class="action-disabled" title="REPD geometry is unavailable; the record remains searchable and exportable">NO MAP</span>';
return `<tr id="repd-${escapeHtml(item.repd_ref)}" data-project-index="${index}"><td class="site">${escapeHtml(item.name)}<div class="project-meta">REPD ${escapeHtml(item.repd_ref)} · ${escapeHtml(item.gg_project_id)} · UPDATED ${escapeHtml(displayDate(item.repd_record_updated))}</div><div class="mobile-extra">${escapeHtml([locationText, item.operator].filter(Boolean).join(" | "))}</div><details … [line shortened here: 1,648 characters; full line on GitHub]
}
function ensureWindowControls() {
let panel = document.getElementById("projectWindowControls");
if (panel) return panel;
panel = document.createElement("div");
panel.id = "projectWindowControls";
panel.className = "project-window-controls";
panel.innerHTML = '<button type="button" data-window="previous">PREVIOUS 50</button><span data-window-range></span><button type="button" data-window="next">NEXT 50</button>';
document.querySelector(".tablewrap").after(panel);
panel.addEventListener("click", (event) => {
const action = event.target.closest("[data-window]")?.dataset.window;
if (!action) return;
if (action === "previous") windowStart = Math.max(0, windowStart - WINDOW_SIZE);
if (action === "next") windowStart = Math.min(Math.floor(Math.max(0, filtered.length - 1) / WINDOW_SIZE) * WINDOW_SIZE, windowStart + WINDOW_SIZE);
renderTable();
});
return panel;
}
function renderTable() {
const body = document.getElementById("tbody");
const page = filtered.slice(windowStart, windowStart + WINDOW_SIZE);
body.innerHTML = page.map(rowHtml).join("");
const panel = ensureWindowControls();
const end = Math.min(filtered.length, windowStart + WINDOW_SIZE);
panel.querySelector("[data-window-range]").textContent = filtered.length
? `${windowStart + 1}–${end} of ${filtered.length.toLocaleString("en-GB")}`
: "0 records";
panel.querySelector('[data-window="previous"]').disabled = windowStart === 0;
panel.querySelector('[data-window="next"]').disabled = end >= filtered.length;
}
function updateSortHeader() {
const header = document.getElementById("repdUpdatedHeader");
const indicator = document.getElementById("updatedSortIndicator");
const button = document.getElementById("sortUpdated");
if (sortMode === "updated_desc") {
header.setAttribute("aria-sort", "descending");
indicator.textContent = "▼";
button.title = "Newest first — click for oldest first";
} else if (sortMode === "updated_asc") {
header.setAttribute("aria-sort", "ascending");
indicator.textContent = "▲";
button.title = "Oldest first — click for newest first";
} else {
header.setAttribute("aria-sort", "none");
indicator.textContent = "↕";
button.title = "Click for newest first";
}
}
function updateChart(chart, value, maximum) {
if (!chart) return;
chart.data.datasets[0].data = [value, Math.max(maximum - value, 0)];
chart.update("none");
}
function updateGauges(summary) {
document.getElementById("v1").textContent = formatNumber(summary.capacity);
document.getElementById("v2").textContent = summary.count.toLocaleString("en-GB");
document.getElementById("v3").textContent = formatNumber(summary.largest);
updateChart(charts.capacity, summary.capacity, registry.totals.capacity_mw || 1);
updateChart(charts.projects, summary.count, registry.totals.project_count || 1);
updateChart(charts.largest, summary.largest, registry.totals.largest_mw || 1);
}
function updateSummary(summary) {
const element = document.getElementById("resultsMeta");
element.textContent = `${summary.count.toLocaleString("en-GB")} of ${rows.length.toLocaleString("en-GB")} records · ${formatNumber(summary.capacity)} MW · largest ${formatNumber(summary.largest)} MW`;
element.classList.toggle("is-filtered", summary.count !== rows.length);
element.dataset.filteredCount = String(summary.count);
element.dataset.totalCount = String(rows.length);
}
function syncFilterUrl() {
const url = new URL(location.href);
for (const parameter of ["technology", "status", "county", "q", "sort"]) 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 (query) url.searchParams.set("q", query);
if (sortMode !== "capacity_desc") url.searchParams.set("sort", sortMode);
history.replaceState(null, "", url);
}
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 (technology !== "all" && item.technology !== technology) continue;
if (status !== "All" && !item.status.includes(status)) continue;
if (county !== "All" && item.county !== county) continue;
if (tokens.length) {
const searchable = searchSupplement?.[index] || compactSearchText(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 === "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();
updateSummary(summary);
updateGauges(summary);
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)));
}
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";
technology = TECHNOLOGIES.has(requestedTechnology) ? requestedTechnology : "all";
status = STATUSES.has(requestedStatus) ? requestedStatus : "All";
county = dictionaries.county.includes(requestedCounty) ? requestedCounty : "All";
query = parameters.get("q") || "";
sortMode = SORTS.has(requestedSort) ? requestedSort : "capacity_desc";
setButtonState("#tech", "technology", technology);
setButtonState("#status", "officialStatus", status);
document.getElementById("county").value = county;
document.getElementById("search").value = query;
document.getElementById("sortProjects").value = sortMode;
}
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 === GENERATION, "search generation mismatch");
invariant(payload.cache_identity === EXPECTED_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('"', '""')}"`;
}
async function downloadCsv(event) {
event.preventDefault();
const meta = document.getElementById("exportMeta");
meta.textContent = "Loading full official fields for filtered export…";
try {
await Promise.all(registry.detail_partitions.map((_, index) => loadDetailPartition(index)));
const headers = ["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", "REPD Record Upd … [line shortened here: 1,132 characters; full line on GitHub]
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";
}
}
function clearFilters(event) {
event.preventDefault();
technology = "all";
status = "All";
county = "All";
query = "";
sortMode = "capacity_desc";
setButtonState("#tech", "technology", technology);
setButtonState("#status", "officialStatus", status);
document.getElementById("county").value = county;
document.getElementById("search").value = "";
document.getElementById("sortProjects").value = sortMode;
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;
setButtonState("#status", "officialStatus", status);
apply();
});
});
document.getElementById("county").addEventListener("change", (event) => { county = event.target.value; apply(); });
document.getElementById("sortProjects").addEventListener("change", (event) => { sortMode = event.target.value; apply(); });
document.getElementById("sortUpdated").addEventListener("click", () => {
sortMode = sortMode === "updated_desc" ? "updated_asc" : "updated_desc";
document.getElementById("sortProjects").value = sortMode;
apply();
});
document.getElementById("search").addEventListener("input", (event) => {
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("clearFilters").addEventListener("click", clearFilters);
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) {