In this section
- Projects V9 8 energy-data · globalgrid2050 / uk_renewables_pipeline/202611280048/scripts/plugins/projects-v9-8.js lines 1–589
Projects V9 8
A JavaScript module in the plugins folder of GlobalGrid2050 that compares register columns, parses MW, syncs MW controls and reads inputs for min MW, max MW and county.
energy-dataglobalgrid2050 / uk_renewables_pipeline/202611280048/scripts/plugins/projects-v9-8.js · lines 1–589 of 589 · version 2026-11-28 00:48 · Entry point · pattern interconnectorRowHtml (shared by 2 files)
- What it does
- It draws the REPD register, interconnectors, solar and battery storage (BESS). Defines 46 functions or classes, including compareRegisterColumns, universeFor, parseMW, capacityWithinMW, syncMWControls. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'renewables'): 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, interconnectors, solar, battery storage (BESS).
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 6 files: App V9 8 (globalgrid2050); Renewable Energy Planning Database (REPD) Liquid (globalgrid2050); Renewable Energy Planning Database (REPD) Expanded (globalgrid2050); Renewable Energy Planning Database (REPD) Reports (globalgrid2050); and 2 more. Reached from 7 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 Pn V973 Capacity Reports Workflow (globalgrid2050).
- What it achieves
- It compares register columns (`compareRegisterColumns`), parses MW (`parseMW`) and syncs MW controls (`syncMWControls`). 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 and change events.
- Why it matters
- Imported by 4 files, including App V9 8, Renewable Energy Planning Database (REPD) Liquid and Renewable Energy Planning Database (REPD) Expanded. Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Native V975 Workflow and GlobalGrid2050 V923 Six Hour Python Repair Workflow.
- Application
- globalgrid2050 · uk_renewables_pipeline/202611280048/scripts/plugins · 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
- Link (import), Testcode — Pipeline (import), Atlas Receiver V9 7 (import), State (import), Operator Aliases (import), Project Filter V9 2 (import), Canonical Projects V9 5 1 (import), Gauges V9 2 (import), and 3 more
- Used by
- imported by App V9 8 (import), imported by Renewable Energy Planning Database (REPD) Liquid (import), imported by Renewable Energy Planning Database (REPD) Expanded (import), imported by Renewable Energy Planning Database (REPD) Reports (import), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Native V975 Workflow (workflow run), run by GlobalGrid2050 V923 Six Hour Python Repair Workflow (workflow run)
- Produces
- compareRegisterColumns, parseMW, capacityWithinMW, atlasUrlV9_5_1, compareProjectUpdatesV9_5_1, compareProjectSubmissionsV934, compareProjectOperationalV935, shortProjectName, loadProjectsV9_8, refreshProjectsV9_8, bindProjectControlsV9_8, setExpandedPageRows
- Defines here
- compareRegisterColumns, universeFor, parseMW, capacityWithinMW, syncMWControls, atlasUrlV9_5_1, displayDate, repdUpdatedTimestamp, compareProjectUpdatesV9_5_1, compareProjectSubmissionsV934, compareProjectOperationalV935, updateSortHeader, populateDateYears, syncYearControls, matchesYear, relationshipSummary, mapActionHtmlV9_5_1, schedule, interconnectorRowHtml, shortProjectName, compactSummary, projectRowHtml, pageCount, pagerElement, renderPager, renderTable, updateResultSummary, syncFilterUrl, apply, populateNativeFilters
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202611280048/scripts/plugins/projects-v9-8.js:1-589 · blob 9cde9d80db82663f7054f3bdd0ee3dc4e395058d · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import { legalEvidenceAction } from "../../../../automation/pipeline_legal_evidence/link.mjs";
import { escapeHtml } from "../core/utils.js";
import {
atlasCentresOnRepdPointV9_7,
atlasReceiverV9_7,
atlasUnavailableReasonV9_7,
buildAtlasDeepLinkV9_7,
verifyAtlasReceiverV9_7,
} from "../core/atlas-receiver-v9-7.js";
import { state } from "../core/state.js";
import { canonicalOperator } from "../../../../automation/repd_reporting/v3/operator-aliases.mjs";
import {
buildProjectSearchTextV9_2,
projectMatchesV9_2,
summariseProjectsV9_2,
tokeniseSearchV9_2,
} from "../core/project-filter-v9-2.js";
import { loadCanonicalProjectsV9_5_1 } from "../data/canonical-projects-v9-5-1.js";
import {
formatCapacityV9_2,
formatLargestV9_2,
setGaugeUniverseV9_2,
updateGaugesV9_2,
} from "./gauges-v9-2.js";
import { signalForProjectV9_5_1 } from "./newspaper-v9-5-1.js";
import { loadInterconnectorsV9_8 } from "../data/interconnectors-v9-8.js";
import {
buildAtlasInterconnectorLinkV9_8,
interconnectorMapNoteV9_8,
interconnectorMapUnavailableReasonV9_8,
} from "../core/atlas-interconnector-link-v9-8.js";
const LABELS = Object.freeze({
solar: "Solar",
bess: "Battery Storage",
wind_onshore: "Onshore Wind",
wind_offshore: "Offshore Wind",
interconnector: "Interconnector",
});
const COLOURS = Object.freeze({ solar: "#ffff00", bess: "#ffae00", wind_onshore: "#00ffff", wind_offshore: "#0066ff", interconnector: "#0066ff" });
const UNITS = Object.freeze({ solar: "MWp", bess: "MW", wind_onshore: "MW", wind_offshore: "MW", interconnector: "MW" });
const ALLOWED_TECHNOLOGIES = new Set(["all", "solar", "bess", "wind_onshore", "wind_offshore", "interconnector"]);
const ALLOWED_STATUSES = new Set(["All", "Operational", "Under Construction", "Awaiting Construction", "Application Submitted"]);
const ALLOWED_SORTS = new Set(["capacity_desc", "updated_desc", "updated_asc", "submitted_desc", "submitted_asc", "operational_desc", "operational_asc"]);
const COLUMN_FIELDS=Object.freeze({name:"name",county:"county",operator:"operator",technology:"technology",status:"status",capacity:"capacity_mw",repd:"repd_ref",globalgrid:"gg_project_id"});
for(const key of Object.keys(COLUMN_FIELDS))for(const dir of ["asc","desc"])ALLOWED_SORTS.add(key+"_"+dir);
const collator=new Intl.Collator("en-GB",{numeric:true,sensitivity:"base"});
export function compareRegisterColumns(a,b,key,direction){
const field=COLUMN_FIELDS[key];if(!field)return 0;
const x=a[field],y=b[field],missing=v=>v===null||v===undefined||v==="";
if(missing(x))return missing(y)?0:1;if(missing(y))return -1;
const result=key==="capacity"?Number(x)-Number(y):collator.compare(String(x),String(y));
return direction==="desc"?-result:result;
}
let all = [];
let interconnectors = [];
let interconnectorFailure = "";
function universeFor() {
return technology === "interconnector" ? interconnectors : all;
}
let filtered = [];
let page = 0;
let metadata = null;
let release = null;
let searchIndex = new Map();
let technology = "all";
let status = "All";
let county = "All";
let operatorFilter = "All", regionFilter = "All";
let query = "";
let sortMode = "capacity_desc";
let controlsBound = false;
let submittedYear = "All", updatedYear = "All", operationalYear = "All";
let minMW = null, maxMW = null;
export function parseMW(value) {
if(value===null||value===undefined||String(value).trim()==="")return null;
const n=Number(value);
return Number.isFinite(n)&&n>=0?n:null;
}
export function capacityWithinMW(value,min,max){
return Number.isFinite(value)&&(min===null||value>=min)&&(max===null||value<=max);
}
function syncMWControls(){
document.getElementById("minMW").value=minMW??"";
document.getElementById("maxMW").value=maxMW??"";
}
export function atlasUrlV9_5_1(project) {
return buildAtlasDeepLinkV9_7(project);
}
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 repdUpdatedTimestamp(project) {
if (!project.repd_record_updated) return null;
const value = Date.parse(`${project.repd_record_updated}T00:00:00Z`);
return Number.isFinite(value) ? value : null;
}
export function compareProjectUpdatesV9_5_1(left, right, direction = "desc") {
const leftTime = repdUpdatedTimestamp(left);
const rightTime = repdUpdatedTimestamp(right);
if (leftTime === null && rightTime === null) return 0;
if (leftTime === null) return 1;
if (rightTime === null) return -1;
return direction === "asc" ? leftTime - rightTime : rightTime - leftTime;
}
export function compareProjectSubmissionsV934(left, right, direction="desc") {
const a=left.planning_application_submitted, b=right.planning_application_submitted;
if(!a)return b?1:0;if(!b)return -1;
return direction==="asc"?a.localeCompare(b):b.localeCompare(a);
}
export function compareProjectOperationalV935(left,right,direction="desc") {
const a=left.operational,b=right.operational;
if(!a)return b?1:0;if(!b)return -1;
return direction==="asc"?a.localeCompare(b):b.localeCompare(a);
}
function updateSortHeader() {
for(const button of document.querySelectorAll("[data-column-sort]")){const key=button.dataset.columnSort,direction=sortMode===key+"_asc"?"ascending":sortMode===key+"_desc"?"descending":"none";button.querySelector("span").textContent=direction==="ascending"?"▲":direction==="descending"?"▼":"↕";button.setAttribute("aria-pressed",String(direction!=="none"));const th=button.closest("th");if(th?.datase … [line shortened here: 462 characters; full line on GitHub]
for(const [prefix,id,label] of [["updated","repdUpdatedHeader","REPD updated"],["submitted","planningSubmittedHeader","Planning application submitted"],["operational","operationalHeader","Operational date"]]) {
const header=document.getElementById(id), button=document.getElementById(prefix==="updated"?"sortUpdated":prefix==="submitted"?"sortSubmitted":"sortOperational");
const direction=sortMode===prefix+"_asc"?"ascending":sortMode===prefix+"_desc"?"descending":"none";
header.setAttribute("aria-sort",direction);button.setAttribute("aria-label",label+", "+direction+"; click to toggle date order");
document.getElementById(prefix+"SortIndicator").textContent=direction==="ascending"?"\u25b2":direction==="descending"?"\u25bc":"\u2195";
}
}
function populateDateYears() {
for(const [field,id] of [["planning_application_submitted","submittedYear"],["repd_record_updated","updatedYear"],["operational","operationalYear"]]) {
const years=[...new Set(all.map(p=>p[field]?.slice(0,4)).filter(Boolean))].sort().reverse();
for(const select of document.querySelectorAll('[data-year-filter="'+id+'"]')) {
select.replaceChildren(new Option("All years","All"),new Option("Not supplied","missing"));
for(const year of years)select.add(new Option(year,year));
}
}
}
function syncYearControls() {
for(const [id,value] of [["submittedYear",submittedYear],["updatedYear",updatedYear],["operationalYear",operationalYear]])for(const select of document.querySelectorAll('[data-year-filter="'+id+'"]'))select.value=value;
}
function matchesYear(value,year){return year==="All"||(year==="missing"?!value:value?.startsWith(year+"-"));}
function relationshipSummary(project) {
const development = Array.isArray(project.development_repd_refs) ? project.development_repd_refs.length : 0;
const direct = Array.isArray(project.direct_related_repd_refs) ? project.direct_related_repd_refs.length : 0;
const siblings = Array.isArray(project.planning_sibling_repd_refs) ? project.planning_sibling_repd_refs.length : 0;
return `${development} development · ${direct} direct · ${siblings} planning sibling record(s)`;
}
function mapActionHtmlV9_5_1(project) {
const href = atlasUrlV9_5_1(project);
if (!href) {
return `<span class="action-disabled">NO MAP</span>`
+ `<div class="map-note">${escapeHtml(atlasUnavailableReasonV9_7(project))}</div>`;
}
const link = `<a class="action-link atlaslink" target="_blank" rel="noopener" href="${escapeHtml(href)}">MAP ↗</a>`;
if (atlasCentresOnRepdPointV9_7(project)) return link;
return `${link}<div class="map-note">REPD published no coordinate for this record. `
+ `The Atlas resolves it from REPD ${escapeHtml(project.repd_ref)} and centres on its own geometry.</div>`;
}
const FIRST_PAINT_ROWS = 100;
const CHUNK_ROWS = 300;
let renderToken = 0;
function schedule(step) {
if (document.visibilityState === "visible" && typeof requestAnimationFrame === "function") {
requestAnimationFrame(step);
} else {
setTimeout(step, 0);
}
}
function interconnectorRowHtml(record) {
const label = LABELS[record.technology];
const unit = UNITS[record.technology];
const location = [record.county, record.region].filter(Boolean).join(" · ");
const news = new URL("https://www.google.com/search");
news.searchParams.set("q", `${record.name} interconnector`);
news.searchParams.set("tbm", "nws");
const href = buildAtlasInterconnectorLinkV9_8(record);
const mapAction = href
? `<a class="action-link atlaslink" target="_blank" rel="noopener" href="${escapeHtml(href)}">MAP ↗</a><div class="map-note">${escapeHtml(interconnectorMapNoteV9_8(record))}</div>`
: `<span class="action-disabled">NO MAP</span><div class="map-note">${escapeHtml(interconnectorMapUnavailableReasonV9_8(record))}</div>`;
const identity = record.bmrs_code ? `BMRS ${record.bmrs_code}` : "NO BMRS CODE YET";
const geometry = record.geometry_status === "valid"
? `straight line converter to converter, ${record.span.straight_line_km} km; the midpoint is a label anchor, not a location`
: record.geometry_status === "gb_end_only"
? `GB converter ${record.gb_end.name}; the far converter is not held yet`
: "no converter coordinates held";
const gbEnd = record.gb_end && record.gb_end.name ? record.gb_end.name : "GB end not held";
const farEnd = record.far_end && record.far_end.name ? record.far_end.name : `${record.country} end not held`;
const flow = record.flow
? `${record.flow.net_direction}; ${Math.round(record.flow.net_mwh).toLocaleString("en-GB")} MWh net over ${record.flow.years}`
: "flow data not wired for this link";
const lifecycle = record.lifecycle + (record.target_operational ? ` · target ${record.target_operational}` : "");
return `<tr id="repd-${escapeHtml(record.repd_ref)}" data-repd-updated="" data-technology="interconnector"><td class="site"><span class="compact-project-name">${escapeHtml(record.name)}</span><div class="project-meta">${escapeHtml(identity)} · ${escapeHtml(record.gg_project_id)} · NOT A REPD RECORD</div><div class="mobile-extra">${escapeHtml(location)}</div><details class="project-record">${compac … [line shortened here: 2,655 characters; full line on GitHub]
}
// Compact labels are presentation only: the full REPD name is kept unchanged.
export function shortProjectName(name) {
const full=String(name??"").trim();
const comma=full.indexOf(",");
return comma>0&&full.slice(0,comma).trim().length>=3?full.slice(0,comma).trim():full;
}
function compactSummary(project,unit) {
return '<summary><span class="desktop-details-label">Details</span><span class="phone-project-label" title="'+escapeHtml(project.name)+'">'+escapeHtml(shortProjectName(project.name))+'</span><span class="phone-project-status">'+escapeHtml(project.status||"Status not supplied")+'</span></summary>';
}
function projectRowHtml(project) {
if (project.technology === "interconnector") return interconnectorRowHtml(project);
const label = LABELS[project.technology];
const unit = UNITS[project.technology];
const location = [project.county, project.region].filter(Boolean).join(" · ");
const signal = signalForProjectV9_5_1(project);
const news = new URL("https://www.google.com/search");
news.searchParams.set("q", `${project.name} ${label} UK`);
news.searchParams.set("tbm", "nws");
const mapAction = mapActionHtmlV9_5_1(project);
const planning = project.planning_application_reference || "not supplied by REPD";
const authority = project.planning_authority || "not supplied by REPD";
const developmentId = project.gg_development_id || "not assigned";
const updated = displayDate(project.repd_record_updated);
const submitted = displayDate(project.planning_application_submitted);
const operational = displayDate(project.operational);
return `<tr id="repd-${escapeHtml(project.repd_ref)}" data-repd-updated="${escapeHtml(project.repd_record_updated || "")}" data-planning-application-submitted="${escapeHtml(project.planning_application_submitted || "")}" data-operational="${escapeHtml(project.operational || "")}"><td class="site"><span class="compact-project-name">${escapeHtml(project.name)}</span><div class="project-meta">REPD ${ … [line shortened here: 4,598 characters; full line on GitHub]
}
let PAGE_ROWS = 50;
function pageCount() {
return Math.max(1, Math.ceil(filtered.length / PAGE_ROWS));
}
function pagerElement() {
let el = document.getElementById("projectPager");
if (!el) {
el = document.createElement("nav");
el.id = "projectPager";
el.className = "pager";
el.setAttribute("aria-label", "Project pages");
const table = document.getElementById("tbody");
const anchor = table ? table.closest("table") : null;
if (anchor && anchor.parentNode) anchor.parentNode.insertBefore(el, anchor.nextSibling);
else if (table) table.parentNode.appendChild(el);
}
return el;
}
function renderPager() {
const el = pagerElement();
const pages = pageCount();
const total = filtered.length;
if (!total) {
el.innerHTML = '<span class="pager-meta">no records match the current filters</span>';
return;
}
const from = page * PAGE_ROWS + 1;
const to = Math.min(total, (page + 1) * PAGE_ROWS);
el.innerHTML =
'<button type="button" class="pager-btn" data-page-step="-1"' + (page === 0 ? ' disabled' : '') + '>← PREV</button>' +
'<span class="pager-meta">' + from.toLocaleString("en-GB") + '–' + to.toLocaleString("en-GB") +
' of ' + total.toLocaleString("en-GB") + ' · page ' + (page + 1) + ' of ' + pages + '</span>' +
'<button type="button" class="pager-btn" data-page-step="1"' + (page + 1 >= pages ? ' disabled' : '') + '>NEXT →</button>';
el.dataset.page = String(page + 1);
el.dataset.pages = String(pages);
el.dataset.from = String(from);
el.dataset.to = String(to);
}
function renderTable() {
const body = document.getElementById("tbody");
const total = filtered.length;
const pages = pageCount();
if (page > pages - 1) page = pages - 1;
if (page < 0) page = 0;
const from = page * PAGE_ROWS;
const slice = filtered.slice(from, from + PAGE_ROWS);
body.innerHTML = slice.map(projectRowHtml).join("");
window.dispatchEvent(new Event("pipeline-projects-rendered"));
body.dataset.rendered = String(slice.length);
body.dataset.total = String(total);
body.dataset.page = String(page + 1);
body.dataset.pages = String(pages);
body.dataset.complete = "true";
renderPager();
}
function updateResultSummary() {
const summary = summariseProjectsV9_2(filtered);
const element = document.getElementById("resultsMeta");
const universe = universeFor();
element.textContent = `${summary.count.toLocaleString("en-GB")} of ${universe.length.toLocaleString("en-GB")} ${technology === "interconnector" ? "interconnector records (outside the REPD spine)" : "records"} · ${formatCapacityV9_2(summary.capacity_mw)} MW · largest ${formatLargestV9_2(summary.largest_mw)} MW`;
element.classList.toggle("is-filtered", summary.count !== universe.length);
element.dataset.filteredCount = String(summary.count);
element.dataset.totalCount = String(universe.length);
}
function syncFilterUrl() {
const url = new URL(window.location.href);
for (const parameter of ["technology", "status", "county", "operator", "region", "q", "sort", "submitted_year", "updated_year", "operational_year", "min_mw", "max_mw"]) url.searchParams.delete(parameter);
if (technology !== "all" || submittedYear !== "All" || updatedYear !== "All" || operationalYear !== "All" || sortMode !== "capacity_desc") url.searchParams.set("technology", technology);
if (status !== "All") url.searchParams.set("status", status);
if (county !== "All") url.searchParams.set("county", county);
if (operatorFilter !== "All") url.searchParams.set("operator", operatorFilter);
if (regionFilter !== "All") url.searchParams.set("region", regionFilter);
if (query) url.searchParams.set("q", query);
if (sortMode !== "capacity_desc") url.searchParams.set("sort", sortMode);
if(submittedYear!=="All")url.searchParams.set("submitted_year",submittedYear);
if(updatedYear!=="All")url.searchParams.set("updated_year",updatedYear);
if(operationalYear!=="All")url.searchParams.set("operational_year",operationalYear);
if(minMW!==null)url.searchParams.set("min_mw",String(minMW));
if(maxMW!==null)url.searchParams.set("max_mw",String(maxMW));
history.replaceState(history.state, "", url);
}
function apply({ syncUrl = true } = {}) {
const tokens = tokeniseSearchV9_2(query);
filtered = universeFor().filter((project) => projectMatchesV9_2(project, {
technology,
status: "All",
county,
tokens,
}, searchIndex.get(project.repd_ref)) && (status === "All" || (String(project.status || "").trim() || "Not reported") === status) && (operatorFilter === "All" || canonicalOperator(project.operator) === operatorFilter) && (regionFilter === "All" || (String(project.region || "").trim() || "Not reported") === regionFilter) && matchesYear(project.planning_application_submitted,submittedYear) && matche … [line shortened here: 553 characters; full line on GitHub]
const [column,direction]=sortMode.split("_");
if(Object.hasOwn(COLUMN_FIELDS,column))filtered.sort((a,b)=>compareRegisterColumns(a,b,column,direction));
if (sortMode === "updated_desc") filtered.sort((left, right) => compareProjectUpdatesV9_5_1(left, right, "desc"));
if (sortMode === "updated_asc") filtered.sort((left, right) => compareProjectUpdatesV9_5_1(left, right, "asc"));
if(sortMode.startsWith("submitted_"))filtered.sort((a,b)=>compareProjectSubmissionsV934(a,b,sortMode.endsWith("_asc")?"asc":"desc"));
if(sortMode.startsWith("operational_"))filtered.sort((a,b)=>compareProjectOperationalV935(a,b,sortMode.endsWith("_asc")?"asc":"desc"));
state.filtered = filtered;
page = 0;
updateGaugesV9_2(filtered);
renderTable();
updateResultSummary();
updateSortHeader();
if (syncUrl) syncFilterUrl();
}
function populateNativeFilters() {
const inventory = [...all, ...interconnectors];
const labels = key => [...new Set(inventory.map(row=>String(row[key]||"").trim()||"Not reported"))]
.sort((a,b)=>a.localeCompare(b,"en-GB"));
const statuses=labels("status");
for(const value of statuses) ALLOWED_STATUSES.add(value);
for(const [id, values, title] of [
["repdNativeStatus", statuses, "ALL OFFICIAL STATUSES"],
["repdNativeOperator", [...new Set(inventory.map(row=>canonicalOperator(row.operator)))].sort((a,b)=>a.localeCompare(b,"en-GB")), "ALL OPERATORS"],
["repdNativeRegion", labels("region"), "ALL REGIONS"]
]) {
const select=document.getElementById(id);
select.replaceChildren(new Option(title,"All"),...values.filter(v=>v!=="All").map(v=>new Option(v,v)));
}
const scan=document.getElementById("pnScanStatus");
if(scan) for(const value of statuses) {
if(![...scan.options].some(o=>o.value===value)) scan.add(new Option(value,value));
}
}
function syncNativeFilters() {
for(const [id,value] of [["repdNativeStatus",status],["repdNativeOperator",operatorFilter],["repdNativeRegion",regionFilter],["pnScanStatus",status]]) {
const select=document.getElementById(id);
if(select && [...select.options].some(o=>o.value===value)) select.value=value;
}
}
function populateCounties() {
const select = document.getElementById("county");
select.replaceChildren(new Option("🌍 ALL COUNTIES", "All"));
[...new Set(all.map((project) => project.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(window.location.search);
minMW=parseMW(parameters.get("min_mw"));maxMW=parseMW(parameters.get("max_mw"));
if(minMW!==null&&maxMW!==null&&minMW>maxMW){minMW=null;maxMW=null;}syncMWControls();
const requestedTechnology = parameters.get("technology") || "all";
const requestedStatus = parameters.get("status") || "All";
const requestedCounty = parameters.get("county") || "All";
const requestedOperator = parameters.get("operator") || "All";
const requestedRegion = parameters.get("region") || "All";
const requestedSort = parameters.get("sort") || "capacity_desc";
technology = ALLOWED_TECHNOLOGIES.has(requestedTechnology) ? requestedTechnology : "all";
status = ALLOWED_STATUSES.has(requestedStatus) ? requestedStatus : "All";
county = [...document.getElementById("county").options].some((option) => option.value === requestedCounty)
? requestedCounty
: "All";
operatorFilter = [...document.getElementById("repdNativeOperator").options].some(o=>o.value===requestedOperator) ? requestedOperator : "All";
regionFilter = [...document.getElementById("repdNativeRegion").options].some(o=>o.value===requestedRegion) ? requestedRegion : "All";
query = parameters.get("q") || "";
sortMode = ALLOWED_SORTS.has(requestedSort) ? requestedSort : "capacity_desc";
for(const [param,id] of [["submitted_year","submittedYear"],["updated_year","updatedYear"],["operational_year","operationalYear"]]){const v=parameters.get(param)||"All";const valid=[...document.querySelector('[data-year-filter="'+id+'"]').options].some(o=>o.value===v);if(id==="submittedYear")submittedYear=valid?v:"All";else if(id==="updatedYear")updatedYear=valid?v:"All";else operationalYear=valid … [line shortened here: 410 characters; full line on GitHub]
syncYearControls();
setButtonState("#tech", "technology", technology);
setButtonState("#status", "officialStatus", status);
syncNativeFilters();
document.getElementById("county").value = county;
document.getElementById("search").value = query;
document.getElementById("sortProjects").value = sortMode;
}
function csvCell(value) {
let text = value === null || value === undefined ? "" : String(value);
if (/^(?:[=+\-@]|\s+[=+\-@]|\t|\r|\n)/u.test(text)) text = `'${text}`;
return `"${text.replaceAll('"', '""')}"`;
}
function reconciliationNote() {
const count = Number(metadata && metadata.source_record_count);
if (!Number.isInteger(count) || count <= 0) return "source record count not stated by the build manifest";
return `${count}/${count} canonical REPD Ref IDs`;
}
function downloadCsv(event) {
event.preventDefault();
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 Updated … [line shortened here: 1,128 characters; full line on GitHub]
const rows = filtered.map((project) => {
const signal = signalForProjectV9_5_1(project);
return [project.name, project.repd_ref, project.gg_project_id, project.gg_development_id, project.identity_status, project.identity_confidence, LABELS[project.technology], project.repd_technology, project.capacity_mw, UNITS[project.technology], project.status, project.lifecycle, project.operator, project.county, project.region, project.country, project.planning_authority, project.planning_applicat … [line shortened here: 1,372 characters; full line on GitHub]
});
const content = `\ufeff${[headers, ...rows].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_v9_8_${new Date().toISOString().slice(0, 10)}.csv`;
anchor.click();
URL.revokeObjectURL(url);
document.getElementById("exportMeta").textContent = `${filtered.length.toLocaleString("en-GB")} filtered records exported`;
}
function clearFilters(event) {
event.preventDefault();
technology = "all";
status = "All";
county = "All";
operatorFilter = "All"; regionFilter = "All";
submittedYear = updatedYear = operationalYear = "All";syncYearControls();
minMW=maxMW=null;syncMWControls();document.getElementById("mwRangeError").textContent="";
query = "";
sortMode = "capacity_desc";
setButtonState("#tech", "technology", technology);
setButtonState("#status", "officialStatus", status);
syncNativeFilters();
document.getElementById("county").value = county;
document.getElementById("search").value = "";
document.getElementById("sortProjects").value = sortMode;
apply();
}
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.setAttribute("readonly", "");
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";
button.classList.add("copied");
setTimeout(() => {
button.textContent = original;
button.classList.remove("copied");
}, 1200);
}
export async function loadProjectsV9_8() {
try {
const verifying = verifyAtlasReceiverV9_7();
const model = await loadCanonicalProjectsV9_5_1();
all = [...model.projects];
try {
const interconnectorModel = await loadInterconnectorsV9_8();
interconnectors = [...interconnectorModel.records];
} catch (error) {
interconnectors = [];
interconnectorFailure = String((error && error.message) || error);
console.error(error);
const tab = document.querySelector('#tech [data-technology="interconnector"]');
if (tab) { tab.disabled = true; tab.title = interconnectorFailure; }
}
state.interconnectors = interconnectors;
filtered = all;
metadata = model.metadata;
// Label the loaded dataset, never the page build or news collection time.
const reportDate=document.getElementById("repdReportDate"),dataDate=document.getElementById("repdDataDate");
const sourceLabel=String(metadata.source_dataset||"");
const receipt=Object.freeze({workbook:"87811e249395a05b223db6855952334f425e66cc9a2106caea0e38fd9e5037ea",report:"OCTOBER 2026",recorded:"14 Nov 2026",commit:"0c78c8c136ddc356724f9a8b13f80e81fb1aa377"});
if(reportDate)reportDate.textContent=" · "+(metadata.source_workbook_sha256===receipt.workbook?receipt.report:sourceLabel.replace(/^DESNZ Renewable Energy Planning Database\s*/i,"")||"Report date unknown");
if(dataDate){dataDate.textContent=metadata.source_workbook_sha256===receipt.workbook?"Data recorded "+receipt.recorded:"Data import date not recorded";dataDate.title=metadata.source_workbook_sha256===receipt.workbook?"Source fixture first committed to Git on "+receipt.recorded+"; not the page publication date.":"";}
release = model.release;
searchIndex = new Map(all.map((project) => [project.repd_ref, buildProjectSearchTextV9_2(project)]));
for (const record of interconnectors) searchIndex.set(record.repd_ref, buildProjectSearchTextV9_2(record));
state.all = all;
state.filtered = filtered;
state.canonicalModel = model;
setGaugeUniverseV9_2(all);
populateCounties();
populateNativeFilters();
populateDateYears();
hydrateFiltersFromUrl();
apply({ syncUrl: false });
document.getElementById("releaseMeta").textContent = `V9.8 interface · V${release.data_parent.release} canonical data spine · ${interconnectors.length} interconnectors on their own tab · all ${all.length.toLocaleString("en-GB")} qualifying records loaded`;
verifying.then((result) => {
if (result.changed) refreshProjectsV9_8();
syncMapAtlasNavV9_7();
if (!result.verified) console.warn(`V9.5.1 MAP: ${result.reason}`);
});
} catch (error) {
console.error(error);
document.getElementById("tbody").innerHTML = '<tr><td colspan="13" style="text-align:center;color:#ff6666">Canonical Q2 REPD data unavailable. V9.5.1 has failed closed.</td></tr>';
document.getElementById("resultsMeta").textContent = "canonical data unavailable";
}
}
export function refreshProjectsV9_8() {
if (metadata) renderTable();
}
export function bindProjectControlsV9_8() {
if (controlsBound) return;
controlsBound = true;
for(const button of document.querySelectorAll("[data-column-sort]"))button.addEventListener("click",()=>{const k=button.dataset.columnSort;sortMode=sortMode===k+"_asc"?k+"_desc":sortMode===k+"_desc"?k+"_asc":k==="capacity"?k+"_desc":k+"_asc";document.getElementById("sortProjects").value=sortMode;apply();});
const applyMW=()=>{const lo=document.getElementById("minMW"),hi=document.getElementById("maxMW"),error=document.getElementById("mwRangeError");const a=parseMW(lo.value),b=parseMW(hi.value);if(!lo.validity.valid||!hi.validity.valid||(a!==null&&b!==null&&a>b)){error.textContent="Enter a valid MW range (minimum ≤ maximum).";return;}error.textContent="";minMW=a;maxMW=b;apply();};
for(const id of ["minMW","maxMW"])document.getElementById(id).addEventListener("change",applyMW);
document.getElementById("applyMW").addEventListener("click",applyMW);
document.querySelectorAll("#tech .btn").forEach((button) => {
button.onclick = () => {
technology = button.dataset.technology;
setButtonState("#tech", "technology", technology);
apply();
};
});
document.querySelectorAll("#status .btn").forEach((button) => {
button.onclick = () => {
status = button.dataset.officialStatus;
setButtonState("#status", "officialStatus", status);
syncNativeFilters();
apply();
};
});
document.getElementById("repdNativeStatus").onchange = event => { status=event.target.value;setButtonState("#status","officialStatus",status);syncNativeFilters();apply(); };
document.getElementById("repdNativeOperator").onchange = event => { operatorFilter=event.target.value;apply(); };
document.getElementById("repdNativeRegion").onchange = event => { regionFilter=event.target.value;apply(); };
document.getElementById("county").onchange = (event) => { county = event.target.value; apply(); };
document.getElementById("sortProjects").onchange = (event) => { sortMode = event.target.value; apply(); };
document.getElementById("sortUpdated").onclick = () => {
sortMode = sortMode === "updated_desc" ? "updated_asc" : "updated_desc";
document.getElementById("sortProjects").value = sortMode;
apply();
};
document.getElementById("sortSubmitted").onclick=()=>{sortMode=sortMode==="submitted_desc"?"submitted_asc":"submitted_desc";document.getElementById("sortProjects").value=sortMode;apply();};
document.getElementById("sortOperational").onclick=()=>{sortMode=sortMode==="operational_desc"?"operational_asc":"operational_desc";document.getElementById("sortProjects").value=sortMode;apply();};
for(const select of document.querySelectorAll('[data-year-filter]'))select.onchange=()=>{if(select.dataset.yearFilter==="submittedYear")submittedYear=select.value;else if(select.dataset.yearFilter==="updatedYear")updatedYear=select.value;else if(select.dataset.yearFilter==="operationalYear")operationalYear=select.value;syncYearControls();apply();};
for(const button of document.querySelectorAll('[data-date-sort]'))button.onclick=()=>{sortMode=button.dataset.dateSort;document.getElementById("sortProjects").value=sortMode;button.closest("details").open=false;apply();};
document.getElementById("search").oninput = (event) => { query = event.target.value.trim(); apply(); };
document.addEventListener("click", (event) => {
const button = event.target.closest ? event.target.closest("[data-page-step]") : null;
if (!button || !document.getElementById("projectPager")) return;
const step = Number(button.getAttribute("data-page-step"));
if (!Number.isFinite(step)) return;
const pages = pageCount();
const next = Math.min(pages - 1, Math.max(0, page + step));
if (next === page) return;
page = next;
renderTable();
const table = document.getElementById("tbody");
if (table && table.closest("table")) table.closest("table").scrollIntoView({ block: "start" });
});
document.getElementById("export").onclick = downloadCsv;
document.getElementById("exportInline").onclick = downloadCsv;
document.getElementById("clearFilters").onclick = clearFilters;
document.getElementById("tbody").addEventListener("click", (event) => {
const proxy=event.target.closest("[data-phone-map]");if(proxy){const row=proxy.closest("tr"),generated=row?.querySelector(".pn-journey-action"),link=generated?.matches("a[href]")?generated:!generated?row?.querySelector("a.atlaslink:not([hidden])"):null;if(link)link.click();else row.querySelector(".phone-map-status").textContent="No map available";return;}
const button = event.target.closest(".copy-id");
if (button) copyProjectId(button);
});
}
function syncMapAtlasNavV9_7() {
const nav = document.getElementById("mapAtlasNav");
if (!nav) return;
const route = atlasReceiverV9_7();
if (!route) {
nav.hidden = true;
return;
}
nav.hidden = false;
nav.href = route;
}
// V9.65: presentation-only page size. Original 50-row register is restored on exit.
export function setExpandedPageRows(enabled) {
const previousFirst = page * PAGE_ROWS;
const desired = enabled ? 100 : 50;
if (PAGE_ROWS === desired) return;
PAGE_ROWS = desired;
page = Math.floor(previousFirst / PAGE_ROWS);
if (metadata) renderTable();
}