GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / archive/202608261547-pipelinenews/newsv7/scripts/plugins

Projects News v7 and 2 more files

A JavaScript module in the plugins folder of PipelineNews that compares project updates v9, updates sort header, renders table and reads inputs for county and sort projects.

682 lines of JavaScript from pipelinenews, in 3 files. Topic: Electricity markets and data pipelines. Section 990 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. Newspaper News v7 Base render · pipelinenews / archive/202608261547-pipelinenews/newsv7/scripts/plugins/newspaper-newsv7-base.js lines 1–189
  2. Newspaper News v7 render · pipelinenews / archive/202608261547-pipelinenews/newsv7/scripts/plugins/newspaper-newsv7.js lines 1–101
  3. Projects News v7 energy-data · pipelinenews / archive/202608261547-pipelinenews/newsv7/scripts/plugins/projects-newsv7.js lines 1–392

Newspaper News v7 Base

A JavaScript module in the plugins folder of PipelineNews that draws major project news and the Renewable Energy Planning Database (REPD) register, and uses data from the GlobalGrid2050 repository.

renderpipelinenews / archive/202608261547-pipelinenews/newsv7/scripts/plugins/newspaper-newsv7-base.js · lines 1–189 of 189 · version 2026-08-26 15:47 · pattern signalForProjectNews (shared by 2 files)

What it does
It draws major project news, the REPD register, battery storage (BESS) and solar. Defines 15 functions or classes, including refreshProjects, canonicalItem, indexNewsItems, signalLabel, signalForProjectNewsV7. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): 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, battery storage (BESS), solar.
Inputs & outputs
In: data source: globalgrid2050 data; JSON file major_project_news_v9_5_1.json.
Downstream impact
Used directly by 2 files: Newspaper News v7 (pipelinenews); Projects News v7 (pipelinenews). Reached from 3 other entry points, including PipelineNews — News v7 Page (pipelinenews, https://ventusltd.github.io/pipelinenews/archive/202608261547-pipelinenews/newsv7/); PipelineNews — PipelineNews Page (pipelinenews, https://ventusltd.github.io/pipelinenews/archive/202608261547-pipelinenews/202608251651-PipelineNews/); App News v7 (pipelinenews).
What it achieves
It refreshes projects (`refreshProjects`), indexes news (`indexNewsItems`) and draws news news v7 base (`drawNewsNewsV7Base`). Defines `refreshProjects`, `canonicalItem`, `indexNewsItems` and 12 more.
Why it matters
Imported by Newspaper News v7 and Projects News v7.
Application
pipelinenews · archive/202608261547-pipelinenews/newsv7/scripts/plugins · JavaScript module
Uses
State (import), Testcode — Pipeline (import), Intelligence News v7 (import)
Used by
imported by Newspaper News v7 (import), imported by Projects News v7 (import)
Produces
signalForProjectNewsV7, drawNewsNewsV7Base, loadNewsNewsV7Base, bindNewspaperNewsV7Base
Defines here
refreshProjects, canonicalItem, indexNewsItems, signalLabel, signalForProjectNewsV7, intelligenceMarkup, itemTechnology, newsMatches, drawNewsNewsV7Base, validPayload, fetchPayload, renderNews, loadNews, loadNewsNewsV7Base, bindNewspaperNewsV7Base
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/newsv7/scripts/plugins/newspaper-newsv7-base.js:1-189 · blob a7748aaecd0ed1bcf0163a01d5cff8b5aef5ec5c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
import { state } from "../core/state.js";
import { escapeHtml, isFinanceEvent, normaliseProject } from "../core/utils.js";
import { intelligenceForArticleNewsV7 } from "./intelligence-newsv7.js";

const NEWS_SOURCES = Object.freeze([
  ["PipelineNews release", "dist/major_project_news_v9_5_1.json"],
  ["Frozen GlobalGrid source", "https://raw.githubusercontent.com/Ventusltd/globalgrid2050/824a23cd0cf9f90a9df942f1b37a09c2dc6472b7/dist/major_project_news_v9_5_1.json"],
]);
const FETCH_TIMEOUT_MS = 15000;
let newsLoadPromise = null;

let refreshProjects = () => {};
let newsIndex = new Map();

function canonicalItem(item) {
  return item
    && item.role === "PRIMARY_MATCH"
    && item.eligible_for_news_signal === true
    && String(item.repd_ref || "")
    && item.gg_project_id === `GG2050-REPD-${item.repd_ref}`;
}

function indexNewsItems(items) {
  newsIndex = new Map();
  for (const item of items.filter(canonicalItem)) {
    const key = String(item.repd_ref);
    const previous = newsIndex.get(key);
    const candidateDate = Date.parse(String(item.published || "")) || 0;
    const previousDate = previous ? Date.parse(String(previous.published || "")) || 0 : 0;
    if (!previous || Number(item.confidence || 0) > Number(previous.confidence || 0)
      || (Number(item.confidence || 0) === Number(previous.confidence || 0) && candidateDate > previousDate)) {
      newsIndex.set(key, item);
    }
  }
}

function signalLabel(item) {
  const event = String(item.event || "PROJECT UPDATE").toUpperCase();
  if (event === "CONSENT") return { label: "APPROVED*", cls: "approved" };
  if (event === "OPERATIONAL") return { label: "OPERATIONAL*", cls: "operational" };
  if (event === "CONSTRUCTION") return { label: "CONSTRUCTION*", cls: "construction" };
  if (["FINANCIAL CLOSE", "ACQUISITION"].includes(event)) {
    return { label: event === "ACQUISITION" ? "M&A*" : "FINANCED*", cls: "finance" };
  }
  return { label: `${event}*`.slice(0, 22), cls: "" };
}

export function signalForProjectNewsV7(project) {
  const item = newsIndex.get(String(project.repd_ref));
  if (!item) return { label: "—", cls: "none", note: "no exact canonical PRIMARY_MATCH" };
  const intelligence = intelligenceForArticleNewsV7(item.article_id);
  return {
    ...signalLabel(item),
    note: intelligence
      ? `canonical PRIMARY_MATCH ${Number(item.confidence || 0)}% · event ${String(intelligence.event_type).toLowerCase()} remains headline-derived · roles abstained · research held`
      : `canonical PRIMARY_MATCH ${Number(item.confidence || 0)}% · unverified event · ${item.published || "date unavailable"}`,
  };
}

function intelligenceMarkup(item) {
  if (item.canonical_relevant !== true) return "";
  const intelligence = intelligenceForArticleNewsV7(item.article_id);
  if (!intelligence) return '<span class="story-intelligence"><span class="intelligence-badge">CUMULATIVE EVIDENCE LOADING</span></span>';
  const operators = intelligence.operator_labels.map((row) => row.source_label).join(" / ");
  return `<span class="story-intelligence"><span class="intelligence-badge">${escapeHtml(intelligence.event_type)} · UNVERIFIED</span><span class="intelligence-badge evidence">REPD OPERATOR: ${escapeHtml(operators)}</span><span class="intelligence-badge">ROLES ABSTAINED</span><span class="intelligence-badge">RESEARCH HELD</span></span>`;
}

function itemTechnology(item) {
  return String(item.canonical_technology || item.technology || "").toUpperCase();
}

function newsMatches(item) {
  const event = String(item.event || "").toUpperCase();
  const technology = itemTechnology(item);
  if (state.newsMode === "RELEVANT" && item.canonical_relevant !== true) return false;
  if (state.newsMode === "SOLAR" && technology !== "SOLAR") return false;
  if (state.newsMode === "BESS" && technology !== "BESS") return false;
  if (state.newsMode === "CONSENT" && event !== "CONSENT") return false;
  if (state.newsMode === "CONSTRUCTION" && event !== "CONSTRUCTION") return false;
  if (state.newsMode === "OPERATIONAL" && event !== "OPERATIONAL") return false;
  if (state.newsMode === "FINANCE" && !isFinanceEvent(event)) return false;
  if (state.newsQuery) {
    const haystack = normaliseProject([
      item.headline, item.canonical_project, item.project, item.operator, item.county,
      item.source, item.event, item.repd_ref, item.gg_project_id,
    ].join(" "));
    const tokens = normaliseProject(state.newsQuery).split(" ").filter(Boolean);
    if (!tokens.every((token) => haystack.includes(token))) return false;
  }
  return true;
}

export function drawNewsNewsV7Base() {
  const stories = document.getElementById("stories");
  const rows = state.newsItems.filter(newsMatches);
  if (!rows.length) {
    stories.innerHTML = '<div class="news-empty">No headlines match this newspaper filter.</div>';
    return;
  }
  stories.innerHTML = rows.map((item) => {
    const technology = itemTechnology(item);
    const articleClass = technology === "BESS" ? "bess" : "solar";
    const project = item.canonical_project || item.project || "";
    const capacity = Number(item.canonical_capacity_mw ?? item.capacity_mw ?? 0);
    const quality = item.canonical_relevant === true
      ? `<span class="news-quality relevant">RELEVANT ${Number(item.confidence || 0)}%</span> · PRIMARY_MATCH · REPD ${escapeHtml(item.repd_ref)}`
      : '<span class="news-quality unverified">DISCOVERY ONLY</span> · no project signal';
    return `<a class="story ${articleClass}" href="${escapeHtml(item.url)}" target="_blank" rel="noopener"><div class="kicker">${escapeHtml(technology)} · ${escapeHtml(item.event || "PROJECT UPDATE")} · ${escapeHtml(item.published || "")}</div><h3>${escapeHtml(item.headline || project)}</h3><p><span class="project">${escapeHtml(project)}${capacity ? ` · ${capacity.toLocaleString("en-GB")} MW` : ""  … [line shortened here: 663 characters; full line on GitHub]
  }).join("");
}

function validPayload(payload) {
  return payload
    && payload.schema === "globalgrid2050.major-project-news.v9.5.1"
    && payload.release === "9.5.1"
    && Array.isArray(payload.all_items)
    && Array.isArray(payload.canonical_items)
    && payload.all_headline_count === payload.all_items.length
    && payload.relevant_headline_count === payload.canonical_items.length
    && payload.v9_4_baseline_headline_count === 125
    && payload.all_items.every((item) => typeof item.canonical_relevant === "boolean")
    && payload.canonical_items.every(canonicalItem)
    && payload.beacon_fen_contract?.repd_ref === "13599"
    && payload.beacon_fen_contract?.official_capacity_mw === 400;
}

async function fetchPayload(label, url) {
  const target = new URL(url, window.location.href);
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
  try {
    const response = await fetch(target, { cache: "default", signal: controller.signal });
    if (!response.ok) throw new Error(`${label} ${response.status}`);
    const data = await response.json();
    if (!validPayload(data)) throw new Error(`${label} invalid V9.5.1 payload`);
    return { label, data };
  } finally {
    clearTimeout(timeout);
  }
}

function renderNews(payload, label) {
  state.newsItems = payload.all_items;
  indexNewsItems(payload.canonical_items);
  document.getElementById("newsMeta").textContent = `${payload.relevant_headline_count} relevant / ${payload.all_headline_count} headlines · ${payload.v9_4_baseline_headline_count} V9.4 baseline retained · ${String(payload.updated || "").slice(0, 10)} · ${label}`;
  drawNewsNewsV7Base();
  if (state.all.length) refreshProjects();
}

async function loadNews() {
  for (const [label, url] of NEWS_SOURCES) {
    try {
      const result = await fetchPayload(label, url);
      renderNews(result.data, result.label);
      return result.data;
    } catch (error) {
      console.error(`News V7 baseline source unavailable: ${label}`, error);
    }
  }
  document.getElementById("stories").innerHTML = '<div class="news-empty">News V7 newspaper unavailable. REPD analytics below remain live.</div>';
  document.getElementById("newsMeta").textContent = "newspaper unavailable";
  return null;
}

export function loadNewsNewsV7Base() {
  if (!newsLoadPromise) {
    newsLoadPromise = loadNews().catch((error) => {
      newsLoadPromise = null;
      throw error;
    });
  }
  return newsLoadPromise;
}

export function bindNewspaperNewsV7Base(onNewsLoaded) {
  refreshProjects = onNewsLoaded;
  document.querySelectorAll("#newsTools button").forEach((button) => {
    button.onclick = () => {
      document.querySelectorAll("#newsTools button").forEach((candidate) => candidate.classList.remove("active"));
      button.classList.add("active");
      state.newsMode = button.dataset.news;
      drawNewsNewsV7Base();
    };
  });
  document.getElementById("newsSearch").oninput = (event) => {
    state.newsQuery = event.target.value.trim();
    drawNewsNewsV7Base();
  };
}

Newspaper News v7

A JavaScript module in the plugins folder of PipelineNews that draws regional news, solar and battery storage (BESS).

renderpipelinenews / archive/202608261547-pipelinenews/newsv7/scripts/plugins/newspaper-newsv7.js · lines 1–101 of 101 · version 2026-08-26 15:47 · pattern bindNewspaperNews (shared by 2 files)

What it does
It draws regional news, solar and battery storage (BESS). Defines 7 functions or classes, including queryMatches, regionalRows, drawRegional, drawNewsNewsV7, fetchCommitted. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): 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: solar, battery storage (BESS).
Inputs & outputs
In: JSON file regional_news.json; JSON file regional_manifest.json.
Downstream impact
Used directly by 1 file: App News v7 (pipelinenews). Reached from 2 other entry points, including PipelineNews — News v7 Page (pipelinenews, https://ventusltd.github.io/pipelinenews/archive/202608261547-pipelinenews/newsv7/); PipelineNews — PipelineNews Page (pipelinenews, https://ventusltd.github.io/pipelinenews/archive/202608261547-pipelinenews/202608251651-PipelineNews/).
What it achieves
It queries matches (`queryMatches`), draws regional (`drawRegional`) and draws news news v7 (`drawNewsNewsV7`). Defines `queryMatches`, `regionalRows`, `drawRegional` and 4 more.
Why it matters
Imported by App News v7.
Application
pipelinenews · archive/202608261547-pipelinenews/newsv7/scripts/plugins · JavaScript module
Uses
State (import), Testcode — Pipeline (import), Newspaper News v7 Base (import)
Used by
imported by App News v7 (import)
Produces
drawNewsNewsV7, loadNewsNewsV7, bindNewspaperNewsV7
Defines here
queryMatches, regionalRows, drawRegional, drawNewsNewsV7, fetchCommitted, loadNewsNewsV7, bindNewspaperNewsV7
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/newsv7/scripts/plugins/newspaper-newsv7.js:1-101 · blob 90a36f9d6952770ed9c7b5c5908a9adc9bd3916d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
import { state } from "../core/state.js";
import { escapeHtml, normaliseProject } from "../core/utils.js";
import { bindNewspaperNewsV7Base, drawNewsNewsV7Base, loadNewsNewsV7Base } from "./newspaper-newsv7-base.js";

const REGIONAL_MODES = new Set(["INTERNATIONAL", "US", "EUROPE"]);
let regionalItems = [];
let regionalManifest = null;

function queryMatches(item) {
  if (!state.newsQuery) return true;
  const haystack = normaliseProject([
    item.headline, item.source, item.technology, item.country, item.region,
  ].join(" "));
  return normaliseProject(state.newsQuery).split(" ").filter(Boolean)
    .every((token) => haystack.includes(token));
}

function regionalRows() {
  return regionalItems.filter((item) => {
    if (!queryMatches(item)) return false;
    if (state.newsMode === "US") return item.region === "US";
    if (state.newsMode === "EUROPE") return item.region === "EUROPE";
    return true;
  });
}

function drawRegional() {
  const stories = document.getElementById("stories");
  const rows = regionalRows();
  if (!rows.length) {
    stories.innerHTML = '<div class="news-empty">No build-verified regional solar or battery headlines match this filter.</div>';
    return;
  }
  stories.innerHTML = rows.map((item) => {
    const articleClass = item.technology.includes("BESS") ? "bess" : "solar";
    const region = item.region === "INTERNATIONAL_OTHER" ? "INTERNATIONAL" : item.region;
    return `<a class="story ${articleClass}" href="${escapeHtml(item.url)}" target="_blank" rel="noopener"><div class="kicker">${escapeHtml(item.technology)} · REGIONAL DISCOVERY · ${escapeHtml(item.published)}</div><h3>${escapeHtml(item.headline)}</h3><p><span class="project">${escapeHtml(region)} · ${escapeHtml(item.country)}</span>${item.source ? ` · ${escapeHtml(item.source)}` : ""}</p><span c  … [line shortened here: 600 characters; full line on GitHub]
  }).join("");
}

export function drawNewsNewsV7() {
  if (REGIONAL_MODES.has(state.newsMode)) {
    drawRegional();
    return;
  }
  if (state.newsMode === "UK") {
    state.newsMode = "RELEVANT";
    drawNewsNewsV7Base();
    state.newsMode = "UK";
    return;
  }
  drawNewsNewsV7Base();
}

async function fetchCommitted(path) {
  const url = new URL(path, import.meta.url);
  const response = await fetch(url, { cache: "default" });
  if (!response.ok) throw new Error(`${path} ${response.status}`);
  return response.json();
}

export async function loadNewsNewsV7() {
  await loadNewsNewsV7Base();
  try {
    const [regional, manifest] = await Promise.all([
      fetchCommitted("../../data/v9.7/regional_news.json"),
      fetchCommitted("../../data/v9.7/regional_manifest.json"),
    ]);
    if (regional.schema !== "globalgrid2050.regional-news.v9.7"
      || regional.release !== "9.7" || !Array.isArray(regional.articles)
      || !regional.articles.every((item) => item.project_signal_eligible === false)) {
      throw new Error("invalid committed regional artifact");
    }
    regionalItems = regional.articles;
    regionalManifest = manifest;
    const counts = regionalManifest.telemetry.by_region;
    const uk = state.newsItems.filter((item) => item.canonical_relevant === true).length;
    document.getElementById("newsMeta").textContent = `${uk} UK · ${regionalItems.length} international (${counts.US} US · ${counts.EUROPE} Europe · ${counts.INTERNATIONAL_OTHER} other) · ${state.newsItems.length} headlines · audited snapshot`;
  } catch (error) {
    regionalItems = [];
    document.getElementById("newsMeta").textContent = `${state.newsItems.length} inherited headlines · regional ledger unavailable`;
    console.error("V9.7 regional artifact unavailable", error);
  }
  drawNewsNewsV7();
}

export function bindNewspaperNewsV7(onNewsLoaded) {
  bindNewspaperNewsV7Base(onNewsLoaded);
  document.querySelectorAll("#newsTools button").forEach((button) => {
    button.onclick = () => {
      document.querySelectorAll("#newsTools button").forEach((candidate) => candidate.classList.remove("active"));
      button.classList.add("active");
      state.newsMode = button.dataset.news;
      drawNewsNewsV7();
    };
  });
  document.getElementById("newsSearch").oninput = (event) => {
    state.newsQuery = event.target.value.trim();
    drawNewsNewsV7();
  };
}

Projects News v7

A JavaScript module in the plugins folder of PipelineNews that compares project updates v9, updates sort header, renders table and reads inputs for county and sort projects.

Set aside from the main view: 93% of its lines are the same as archive/202608261547-pipelinenews/newsv1/scripts/plugins/projects-newsv1.js (pipelinenews), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with Projects News v1; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9304 to pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/newsv1/scripts/plugins/projects-newsv1.js:1-392 1274a5ec007f6767fefc8646bb3f56ef1e07a888
  • sha256 fb501d835947e44be4e3f97a44b0f8212a40520f9d6cc9611c7c00c4363d0440
  • target sha256 604c17a8771687602ada2d068b0a177192558ef94a15a956473b27113a85b605
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

energy-datapipelinenews / archive/202608261547-pipelinenews/newsv7/scripts/plugins/projects-newsv7.js · lines 1–392 of 392 · version 2026-08-26 15:47 · pattern renderFirstPartitionPreview (shared by 2 files)

What it does
It draws the REPD register, solar, battery storage (BESS) and wind. Defines 23 functions or classes, including atlasUrlV9_5_1, displayDate, repdUpdatedTimestamp, compareProjectUpdatesV9_5_1, updateSortHeader. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): 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, solar, battery storage (BESS), wind.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: App News v7 (pipelinenews). Reached from 2 other entry points, including PipelineNews — News v7 Page (pipelinenews, https://ventusltd.github.io/pipelinenews/archive/202608261547-pipelinenews/newsv7/); PipelineNews — PipelineNews Page (pipelinenews, https://ventusltd.github.io/pipelinenews/archive/202608261547-pipelinenews/202608251651-PipelineNews/).
What it achieves
It compares project updates v9 (`compareProjectUpdatesV9_5_1`), updates sort header (`updateSortHeader`) and renders table (`renderTable`). 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 events.
Why it matters
Imported by App News v7.
Application
pipelinenews · archive/202608261547-pipelinenews/newsv7/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
Testcode — Pipeline (import), State (import), Project Filter V9 2 (import), Canonical Projects News v7 Release (import), Gauges V9 2 (import), Newspaper News v7 Base (import), GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
Used by
imported by App News v7 (import)
Produces
atlasUrlV9_5_1, compareProjectUpdatesV9_5_1, loadProjectsNewsV7, refreshProjectsNewsV7, bindProjectControlsNewsV7
Defines here
atlasUrlV9_5_1, displayDate, repdUpdatedTimestamp, compareProjectUpdatesV9_5_1, updateSortHeader, relationshipSummary, renderTable, renderPager, setProjectControlsReady, renderFirstPartitionPreview, updateResultSummary, syncFilterUrl, apply, populateCounties, setButtonState, hydrateFiltersFromUrl, csvCell, downloadCsv, clearFilters, copyProjectId, loadProjectsNewsV7, refreshProjectsNewsV7, bindProjectControlsNewsV7
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/newsv7/scripts/plugins/projects-newsv7.js:1-392 · blob ba755560d098f2a201be5743abc1a30aa6e5bb15 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: production_core
import { escapeHtml } from "../core/utils.js";
import { state } from "../core/state.js";
import {
  buildProjectSearchTextV9_2,
  projectMatchesV9_2,
  summariseProjectsV9_2,
  tokeniseSearchV9_2,
} from "../core/project-filter-v9-2.js";
import { loadCanonicalProjectsNewsV7Release } from "../data/canonical-projects-newsv7-release.js";
import {
  formatCapacityV9_2,
  formatLargestV9_2,
  setGaugeUniverseV9_2,
  updateGaugesV9_2,
} from "./gauges-v9-2.js";
import { signalForProjectNewsV7 } from "./newspaper-newsv7-base.js";

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 ALLOWED_TECHNOLOGIES = new Set(["all", "solar", "bess", "wind_onshore", "wind_offshore"]);
const ALLOWED_STATUSES = new Set(["All", "Operational", "Under Construction", "Awaiting Construction", "Application Submitted"]);
const ALLOWED_SORTS = new Set(["capacity_desc", "updated_desc", "updated_asc"]);
const ROWS_PER_PAGE = 100;
const SEARCH_DEBOUNCE_MS = 160;

let all = [];
let filtered = [];
let metadata = null;
let release = null;
let searchIndex = new Map();
let technology = "all";
let status = "All";
let county = "All";
let query = "";
let sortMode = "capacity_desc";
let controlsBound = false;
let pageIndex = 0;
let searchTimer = null;
let dataReady = false;

export function atlasUrlV9_5_1(project) {
  if (project.geometry_status !== "valid") return "";
  const url = new URL("https://globalgrid2050.com/repd_grid_atlasv8/");
  url.searchParams.set("repd_ref", project.repd_ref);
  url.searchParams.set("project", project.name);
  url.searchParams.set("technology", project.technology);
  url.searchParams.set("capacity_mw", project.capacity_mw);
  url.searchParams.set("latitude", project.latitude);
  url.searchParams.set("longitude", project.longitude);
  url.searchParams.set("zoom", "12");
  return url.href;
}

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;
}

function updateSortHeader() {
  const header = document.getElementById("repdUpdatedHeader");
  const button = document.getElementById("sortUpdated");
  const indicator = document.getElementById("updatedSortIndicator");
  if (!header || !button || !indicator) return;
  if (sortMode === "updated_desc") {
    header.setAttribute("aria-sort", "descending");
    indicator.textContent = "▼";
    button.setAttribute("aria-label", "REPD updated date sorted newest first; click for oldest first");
    button.title = "Newest first — click for oldest first";
    return;
  }
  if (sortMode === "updated_asc") {
    header.setAttribute("aria-sort", "ascending");
    indicator.textContent = "▲";
    button.setAttribute("aria-label", "REPD updated date sorted oldest first; click for newest first");
    button.title = "Oldest first — click for newest first";
    return;
  }
  header.setAttribute("aria-sort", "none");
  indicator.textContent = "↕";
  button.setAttribute("aria-label", "Sort by REPD updated date, newest first");
  button.title = "Click for newest first";
}

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 renderTable() {
  const body = document.getElementById("tbody");
  const pageCount = Math.max(1, Math.ceil(filtered.length / ROWS_PER_PAGE));
  pageIndex = Math.min(pageIndex, pageCount - 1);
  const start = pageIndex * ROWS_PER_PAGE;
  const pageRows = filtered.slice(start, start + ROWS_PER_PAGE);
  body.innerHTML = pageRows.map((project) => {
    const label = LABELS[project.technology];
    const unit = UNITS[project.technology];
    const location = [project.county, project.region].filter(Boolean).join(" · ");
    const signal = signalForProjectNewsV7(project);
    const news = new URL("https://www.google.com/search");
    news.searchParams.set("q", `${project.name} ${label} UK`);
    news.searchParams.set("tbm", "nws");
    const atlas = atlasUrlV9_5_1(project);
    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>';
    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);
    return `<tr id="repd-${escapeHtml(project.repd_ref)}" data-repd-updated="${escapeHtml(project.repd_record_updated || "")}"><td class="site">${escapeHtml(project.name)}<div class="project-meta">REPD ${escapeHtml(project.repd_ref)} · ${escapeHtml(project.gg_project_id)} · UPDATED ${escapeHtml(updated)}</div><div class="mobile-extra">${escapeHtml([location, project.operator].filter(Boolean).join(  … [line shortened here: 2,120 characters; full line on GitHub]
  }).join("");
  renderPager();
}

function renderPager() {
  const previous = document.getElementById("projectPrev");
  const next = document.getElementById("projectNext");
  const statusElement = document.getElementById("projectPageStatus");
  if (!previous || !next || !statusElement) return;
  const pageCount = Math.max(1, Math.ceil(filtered.length / ROWS_PER_PAGE));
  const start = filtered.length ? pageIndex * ROWS_PER_PAGE + 1 : 0;
  const end = Math.min((pageIndex + 1) * ROWS_PER_PAGE, filtered.length);
  previous.disabled = pageIndex === 0;
  next.disabled = pageIndex >= pageCount - 1 || filtered.length === 0;
  statusElement.textContent = filtered.length
    ? `SHOWING ${start.toLocaleString("en-GB")}–${end.toLocaleString("en-GB")} OF ${filtered.length.toLocaleString("en-GB")} · PAGE ${(pageIndex + 1).toLocaleString("en-GB")} OF ${pageCount.toLocaleString("en-GB")}`
    : "NO PROJECTS MATCH THIS FILTER";
}

function setProjectControlsReady(ready) {
  dataReady = ready;
  document.querySelectorAll("#tech button, #status button, #county, #sortProjects, #search, #clearFilters, #exportInline, #sortUpdated")
    .forEach((control) => { control.disabled = !ready; });
  const exportLink = document.getElementById("export");
  exportLink.setAttribute("aria-disabled", String(!ready));
  document.querySelector(".tablewrap").setAttribute("aria-busy", String(!ready));
}

function renderFirstPartitionPreview({ projects, loaded_count: loadedCount, total_count: totalCount }) {
  if (dataReady) return;
  filtered = [...projects];
  state.filtered = filtered;
  pageIndex = 0;
  renderTable();
  const results = document.getElementById("resultsMeta");
  results.textContent = `${loadedCount.toLocaleString("en-GB")} verified records ready · loading full ${totalCount.toLocaleString("en-GB")} record index…`;
  results.dataset.hydration = "partial";
  document.getElementById("releaseMeta").textContent = "News V7 cumulative interface · first verified partition visible · completing canonical hydration";
}

function updateResultSummary() {
  const summary = summariseProjectsV9_2(filtered);
  const element = document.getElementById("resultsMeta");
  element.textContent = `${summary.count.toLocaleString("en-GB")} of ${all.length.toLocaleString("en-GB")} records · ${formatCapacityV9_2(summary.capacity_mw)} MW · largest ${formatLargestV9_2(summary.largest_mw)} MW`;
  element.classList.toggle("is-filtered", summary.count !== all.length);
  element.dataset.filteredCount = String(summary.count);
  element.dataset.totalCount = String(all.length);
}

function syncFilterUrl() {
  const url = new URL(window.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, resetPage = true } = {}) {
  const tokens = tokeniseSearchV9_2(query);
  filtered = all.filter((project) => projectMatchesV9_2(project, {
    technology,
    status,
    county,
    tokens,
  }, searchIndex.get(project.repd_ref)));
  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 (resetPage) pageIndex = 0;
  state.filtered = filtered;
  updateGaugesV9_2(filtered);
  renderTable();
  updateResultSummary();
  updateSortHeader();
  if (syncUrl) syncFilterUrl();
}

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);
  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 = 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";
  query = parameters.get("q") || "";
  sortMode = ALLOWED_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;
}

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 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 Updat  … [line shortened here: 1,130 characters; full line on GitHub]
  const rows = filtered.map((project) => {
    const signal = signalForProjectNewsV7(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_appl  … [line shortened here: 1,392 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 = `pipelinenews_uk_renewables_newsv7_${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";
  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();
}

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 loadProjectsNewsV7() {
  try {
    const model = await loadCanonicalProjectsNewsV7Release({ onFirstPartition: renderFirstPartitionPreview });
    all = [...model.projects];
    filtered = all;
    metadata = model.metadata;
    release = model.release;
    searchIndex = new Map(all.map((project) => [project.repd_ref, buildProjectSearchTextV9_2(project)]));
    state.all = all;
    state.filtered = filtered;
    state.canonicalModel = model;
    setGaugeUniverseV9_2(all);
    populateCounties();
    hydrateFiltersFromUrl();
    apply({ syncUrl: false });
    setProjectControlsReady(true);
    document.getElementById("resultsMeta").dataset.hydration = "complete";
    document.getElementById("releaseMeta").textContent = `News V7 cumulative interface · V${release.frozen_source.release} baseline · all ${all.length.toLocaleString("en-GB")} qualifying records loaded · 100-row pages`;
  } catch (error) {
    console.error(error);
    document.getElementById("tbody").innerHTML = '<tr><td colspan="11" style="text-align:center;color:#ff6666">Canonical Q2 REPD data unavailable. News V7 has failed closed.</td></tr>';
    document.getElementById("resultsMeta").textContent = "canonical data unavailable";
  }
}

export function refreshProjectsNewsV7() {
  if (metadata) renderTable();
}

export function bindProjectControlsNewsV7() {
  if (controlsBound) return;
  controlsBound = true;
  setProjectControlsReady(false);
  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);
      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("search").oninput = (event) => {
    clearTimeout(searchTimer);
    const value = event.target.value.trim();
    searchTimer = setTimeout(() => {
      query = value;
      apply();
    }, SEARCH_DEBOUNCE_MS);
  };
  document.getElementById("export").onclick = (event) => { if (dataReady) downloadCsv(event); else event.preventDefault(); };
  document.getElementById("exportInline").onclick = (event) => { if (dataReady) downloadCsv(event); };
  document.getElementById("clearFilters").onclick = clearFilters;
  document.getElementById("projectPrev").onclick = () => {
    if (pageIndex === 0) return;
    pageIndex -= 1;
    renderTable();
  };
  document.getElementById("projectNext").onclick = () => {
    if ((pageIndex + 1) * ROWS_PER_PAGE >= filtered.length) return;
    pageIndex += 1;
    renderTable();
  };
  document.getElementById("tbody").addEventListener("click", (event) => {
    const button = event.target.closest(".copy-id");
    if (button) copyProjectId(button);
  });
}