Initial commit

This commit is contained in:
ebagot committed 2026-11-13 17:35:10 +01:00
commit a206bfb5db
21 files changed
+16747

No files matched your search

+534
View File
@@ -0,0 +1,534 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>US Officeholders 2027</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<style>
/* Layout: civic reference sheet. Header + mode switch, then map (left) beside a sticky detail panel (right); stacks on phones. */
:root {
--bg: #f6f7f9;
--surface: #ffffff;
--fg: #1b1f27;
--muted: #5d6573;
--line: #dde1e8;
--map-empty: #e4e7ec;
--map-stroke: #ffffff;
--rep: #c8253b;
--dem: #2457b8;
--ind: #7a46b0;
--unk: #9aa1ad;
--focus: #e0a100;
--font: "Public Sans", "Segoe UI", system-ui, -apple-system, sans-serif;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #12151b; --surface: #1a1e26; --fg: #e9ecf1; --muted: #9ba3b1; --line: #2c323d;
--map-empty: #2a303b; --map-stroke: #12151b;
--rep: #e2475b; --dem: #4f80e0; --ind: #a174d6; --unk: #6c7482; --focus: #f2bf3a;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #12151b; --surface: #1a1e26; --fg: #e9ecf1; --muted: #9ba3b1; --line: #2c323d;
--map-empty: #2a303b; --map-stroke: #12151b;
--rep: #e2475b; --dem: #4f80e0; --ind: #a174d6; --unk: #6c7482; --focus: #f2bf3a;
color-scheme: dark;
}
* { box-sizing: border-box; }
body {
background: var(--bg); color: var(--fg); font-family: var(--font); font-size: 15px; line-height: 1.5;
padding-left: max(16px, env(safe-area-inset-left, 0px));
padding-right: max(16px, env(safe-area-inset-right, 0px));
padding-block: 20px 40px;
}
.wrap { max-width: 1320px; margin: 0 auto; display: grid; gap: 18px; }
header { display: grid; gap: 6px; }
h1 { margin: 0; font-size: clamp(1.6rem, 3.2vw, 2.3rem); font-weight: 800; letter-spacing: -0.02em; text-wrap: balance; }
.lede { margin: 0; color: var(--muted); max-width: 72ch; }
.lede a { color: inherit; }
.modes { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.modes .label { font-size: 0.75rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); margin-right: 4px; }
.modes button {
font: inherit; font-size: 0.9rem; font-weight: 600; padding: 7px 14px; border-radius: 999px;
border: 1px solid var(--line); background: var(--surface); color: var(--fg); cursor: pointer;
}
.modes button[aria-pressed="true"] { background: var(--fg); color: var(--bg); border-color: var(--fg); }
.modes button:focus-visible, .state:focus-visible, .chip:focus-visible, select:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
.main { display: grid; grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); gap: 20px; align-items: start; }
@media (max-width: 900px) { .main { grid-template-columns: minmax(0, 1fr); } }
.mapcard { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 14px; display: grid; gap: 12px; min-width: 0; }
.totals { display: flex; flex-wrap: wrap; gap: 6px 18px; align-items: baseline; }
.totals .t-title { font-weight: 700; }
.totals .t-sub { color: var(--muted); font-size: 0.85rem; }
svg.map { width: 100%; height: auto; display: block; }
.state { stroke: var(--map-stroke); stroke-width: 1; cursor: pointer; transition: filter 0.12s; }
.state:hover { filter: brightness(1.08) saturate(1.1); }
.state.sel { stroke: var(--fg); stroke-width: 2.4; }
.lbl { font: 700 11px var(--font); fill: #fff; pointer-events: none; text-anchor: middle; dominant-baseline: central; paint-order: stroke; stroke: rgba(0,0,0,0.28); stroke-width: 2px; }
.lbl.dark { fill: var(--fg); stroke: none; }
.chip rect { stroke: var(--map-stroke); stroke-width: 1; }
.chip { cursor: pointer; }
.chip.sel rect { stroke: var(--fg); stroke-width: 2.2; }
.legend { display: flex; flex-wrap: wrap; gap: 6px 16px; font-size: 0.85rem; color: var(--muted); align-items: center; }
.legend .sw { display: inline-block; width: 14px; height: 14px; border-radius: 3px; vertical-align: -2px; margin-right: 6px; }
.picker { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: 0.9rem; color: var(--muted); }
select { font: inherit; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface); color: var(--fg); }
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 18px; min-width: 0; }
@media (min-width: 901px) { .panel { position: sticky; top: calc(env(safe-area-inset-top, 0px) + 12px); max-height: calc(100vh - 24px); overflow-y: auto; } }
.panel h2 { margin: 0 0 2px; font-size: 1.5rem; font-weight: 800; letter-spacing: -0.01em; }
.panel .sub { color: var(--muted); margin: 0 0 12px; font-size: 0.88rem; }
.cat { border-top: 1px solid var(--line); padding-block: 12px; display: grid; gap: 6px; }
.cat h3 { margin: 0; font-size: 0.75rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); }
.cat .chamber { font-size: 0.85rem; color: var(--muted); }
ul.people { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; }
ul.people li { display: grid; grid-template-columns: 14px minmax(0, 1fr) auto; gap: 8px; align-items: baseline; }
ul.people .who { min-width: 0; }
ul.people .dist { color: var(--muted); font-size: 0.82rem; font-variant-numeric: tabular-nums; margin-right: 4px; }
ul.people .end { color: var(--muted); font-size: 0.82rem; font-variant-numeric: tabular-nums; white-space: nowrap; }
ul.people .role { display: block; color: var(--muted); font-size: 0.8rem; }
.note { display: block; color: var(--muted); font-size: 0.78rem; font-style: italic; }
.tag { display: inline-block; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; padding: 1px 6px; border-radius: 4px; border: 1px solid var(--line); color: var(--muted); margin-left: 4px; vertical-align: 1px; }
.sq { display: inline-block; width: 12px; height: 12px; border-radius: 2px; background: var(--unk); vertical-align: -1px; flex: none; }
.sq.D { background: var(--dem); } .sq.R { background: var(--rep); } .sq.I { background: var(--ind); }
.sq.U { background: repeating-linear-gradient(45deg, var(--unk) 0 2px, transparent 2px 4px); border: 1px solid var(--unk); }
.sum { font-weight: 700; font-variant-numeric: tabular-nums; display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: center; padding-top: 2px; }
.sum span.item { display: inline-flex; gap: 6px; align-items: center; }
.sum .extra { font-weight: 400; color: var(--muted); font-size: 0.82rem; }
ul.powers { margin: 4px 0 0; padding-left: 18px; display: grid; gap: 3px; font-size: 0.9rem; }
.overview .row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: center; padding-block: 8px; border-top: 1px solid var(--line); }
.overview .row:first-of-type { border-top: 0; }
.hint { color: var(--muted); font-size: 0.88rem; margin: 12px 0 0; }
.tip { position: fixed; pointer-events: none; background: var(--fg); color: var(--bg); font-size: 0.82rem; padding: 6px 9px; border-radius: 6px; max-width: 260px; z-index: 5; }
footer { color: var(--muted); font-size: 0.8rem; max-width: 90ch; }
@media (prefers-reduced-motion: reduce) { .state { transition: none; } }
/* update from Wikipedia */
.updatebar { display: flex; flex-wrap: wrap; gap: 8px 14px; align-items: center; margin-top: 4px; }
.updatebar button {
font: inherit; font-size: 0.9rem; font-weight: 700; padding: 7px 14px; border-radius: 8px;
border: 1px solid var(--fg); background: var(--fg); color: var(--bg); cursor: pointer;
}
.updatebar button:disabled { opacity: 0.6; cursor: progress; }
.updatebar button:focus-visible, details.warn summary:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
.datainfo { color: var(--muted); font-size: 0.88rem; }
.upstatus { font-size: 0.88rem; padding: 8px 12px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface); max-width: 90ch; }
.upstatus.error { border-color: var(--rep); }
.upstatus.ok { border-color: var(--dem); }
.upstatus .spin { display: inline-block; width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--muted); border-top-color: transparent; margin-right: 8px; animation: spin 0.9s linear infinite; vertical-align: -1px; }
@keyframes spin { to { transform: rotate(360deg); } }
details.warn { font-size: 0.86rem; color: var(--muted); max-width: 90ch; }
details.warn summary { cursor: pointer; font-weight: 600; color: var(--fg); }
details.warn ul { margin: 6px 0 0; padding-left: 18px; display: grid; gap: 4px; }
@media (prefers-reduced-motion: reduce) { .upstatus .spin { animation: none; } }
</style>
<div class="wrap">
<header>
<h1 id="title">US Officeholders</h1>
<p class="lede" id="lede">Loading the data…</p>
<div class="updatebar">
<button type="button" id="updateBtn">Update from Wikipedia</button>
<span class="datainfo" id="dataInfo"></span>
</div>
<div class="upstatus" id="upStatus" role="status" aria-live="polite" hidden></div>
<details class="warn" id="warnBox" hidden><summary id="warnSummary"></summary><ul id="warnList"></ul></details>
</header>
<div class="modes" role="group" aria-label="Color the map by">
<span class="label">Color map by</span>
<button type="button" data-mode="gov" aria-pressed="true">Governor</button>
<button type="button" data-mode="sen">U.S. Senate</button>
<button type="button" data-mode="house">U.S. House</button>
<button type="button" data-mode="upper">State Senate</button>
<button type="button" data-mode="lower">State House</button>
</div>
<div class="main">
<section class="mapcard" aria-label="Map">
<div class="totals" id="totals"></div>
<svg class="map" id="map" viewBox="-10 0 1060 615" role="group" aria-label="Map of US states">
<defs>
<pattern id="p-split" patternUnits="userSpaceOnUse" width="8" height="8" patternTransform="rotate(45)">
<rect width="4" height="8" fill="var(--dem)"></rect><rect x="4" width="4" height="8" fill="var(--rep)"></rect>
</pattern>
<pattern id="p-unk" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(45)">
<rect width="6" height="6" fill="var(--map-empty)"></rect><rect width="2" height="6" fill="var(--unk)"></rect>
</pattern>
</defs>
<g id="states"></g>
<g id="labels"></g>
<g id="chips"></g>
</svg>
<div class="legend" id="legend"></div>
<div class="picker">
<label for="statePick">Or pick a state</label>
<select id="statePick"><option value="">United States (overview)</option></select>
</div>
</section>
<aside class="panel" id="panel" aria-live="polite"></aside>
</div>
<footer id="foot"></footer>
</div>
<div class="tip" id="tip" hidden></div>
<script src="/static/vendor/d3.min.js"></script>
<script src="/static/vendor/topojson.min.js"></script>
<script>
let GEO = null, DATA = {}, META = {};
let app = null;
/* ---------- texts that depend on the data mode ---------- */
const LONG_MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
function longDate(iso) { const m = String(iso || "").match(/^(\d{4})-(\d{2})-(\d{2})/); return m ? `${LONG_MONTHS[+m[2] - 1]} ${+m[3]}, ${m[1]}` : ""; }
function isElection() { return META.mode === "election" && META.electionYear; }
function fromWhen() { return isElection() ? `from January ${META.electionYear + 1}` : "today"; }
function periodText() { return isElection() ? `Officeholders from January ${META.electionYear + 1}` : "Current officeholders"; }
function applyMeta() {
const title = isElection() ? `US Officeholders ${META.electionYear + 1}` : "US Officeholders";
document.title = title;
document.getElementById("title").textContent = title;
const after = isElection() ? `, after the ${longDate(META.electionDay)} elections` : "";
document.getElementById("lede").textContent = `Who represents each state ${fromWhen()}${after}: U.S. senators, U.S. representatives, state senators, state representatives and the governor. Click a state to see names and term ends. Source: English Wikipedia, read on ${longDate(META.asOf) || "an unknown date"}.`;
document.getElementById("dataInfo").textContent = `Data as of ${fmtDate(META.asOf)} · source: ${META.modeLabel || "unknown"}`;
document.getElementById("foot").textContent = META.footer || "";
showWarnings(META.warnings || [], "from the last update");
}
const CODES = {"Alabama":"AL","Alaska":"AK","Arizona":"AZ","Arkansas":"AR","California":"CA","Colorado":"CO","Connecticut":"CT","Delaware":"DE","Florida":"FL","Georgia":"GA","Hawaii":"HI","Idaho":"ID","Illinois":"IL","Indiana":"IN","Iowa":"IA","Kansas":"KS","Kentucky":"KY","Louisiana":"LA","Maine":"ME","Maryland":"MD","Massachusetts":"MA","Michigan":"MI","Minnesota":"MN","Mississippi":"MS","Missouri":"MO","Montana":"MT","Nebraska":"NE","Nevada":"NV","New Hampshire":"NH","New Jersey":"NJ","New Mexico":"NM","New York":"NY","North Carolina":"NC","North Dakota":"ND","Ohio":"OH","Oklahoma":"OK","Oregon":"OR","Pennsylvania":"PA","Rhode Island":"RI","South Carolina":"SC","South Dakota":"SD","Tennessee":"TN","Texas":"TX","Utah":"UT","Vermont":"VT","Virginia":"VA","Washington":"WA","West Virginia":"WV","Wisconsin":"WI","Wyoming":"WY"};
const NAMES = Object.fromEntries(Object.entries(CODES).map(([n, c]) => [c, n]));
const SMALL = ["VT","NH","MA","RI","CT","NJ","DE","MD"];
const LABEL_SHIFT = { LA: [-10, 0], FL: [14, 6], MI: [12, 22], KY: [4, 2], WV: [-2, 4], ID: [0, 14], HI: [10, 8], AK: [0, 0], NY: [6, 0], CA: [-8, 0], ME: [2, -4], OK: [10, 0], VA: [8, 2], NC: [6, 0] };
const PARTY_NAME = { D: "Democrat", R: "Republican", I: "Independent / other", U: "Not yet known" };
const MODES = {
gov: { title: "Governors" },
sen: { title: "U.S. Senate" },
house: { title: "U.S. House" },
upper: { title: "State Senates" },
lower: { title: "State Houses" }
};
let mode = "gov";
let selected = null;
/* ---------- formatting ---------- */
const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
function fmtDate(raw) {
if (!raw) return "—";
const s = String(raw);
let m = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (m) return `${MONTHS[+m[2] - 1]} ${+m[3]}, ${m[1]}`;
m = s.match(/^(\d{4})-(\d{2})$/);
if (m) return `${MONTHS[+m[2] - 1]} ${m[1]}`;
return s;
}
function esc(s) { return String(s ?? "").replace(/[&<>"]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }
function partyKey(p) { return p === "D" || p === "R" || p === "I" ? p : "U"; }
function sq(p) { const k = partyKey(p); return `<span class="sq ${k}" role="img" aria-label="${PARTY_NAME[k]}" title="${PARTY_NAME[k]}"></span>`; }
const STATUS_TAG = { uncalled: "Not yet called", runoff: "Runoff", vacant: "Vacant", appointed: "Appointed", current: "Current leader" };
function tag(status) { return STATUS_TAG[status] ? `<span class="tag">${STATUS_TAG[status]}</span>` : ""; }
/* "■ 3D ■ 2R ■ 1I", zero counts left out */
function summary(counts, extra) {
const parts = [];
for (const k of ["D", "R", "I"]) if (counts[k] > 0) parts.push(`<span class="item">${sq(k)}${counts[k]}${k}</span>`);
if (counts.U > 0) parts.push(`<span class="item">${sq("U")}${counts.U} ${isElection() ? "not yet called" : "vacant or unknown"}</span>`);
if (extra) parts.push(`<span class="extra">${extra}</span>`);
return `<div class="sum">${parts.join("") || '<span class="extra">No data</span>'}</div>`;
}
function countParties(list) {
const c = { D: 0, R: 0, I: 0, U: 0 };
for (const p of list) c[partyKey(p)]++;
return c;
}
/* a race not yet called counts as unknown, whoever leads */
function eff(p) { return p && (p.status === "uncalled" || p.status === "runoff") ? null : p && p.party; }
/* ---------- per-state values for map coloring ---------- */
function chamber(code, which) { const l = DATA[code] && DATA[code].leg; return l ? l[which] : null; }
function chamberCounts(ch) { return { D: ch.D || 0, R: ch.R || 0, I: ch.I || 0, U: ch.uncalled || 0 }; }
function majority(c) {
const seats = c.D + c.R + c.I + c.U;
const top = ["D", "R", "I"].sort((a, b) => c[b] - c[a]);
if (!seats || c[top[0]] === c[top[1]]) return { party: null, share: 0 };
return { party: top[0], share: c[top[0]] / seats };
}
function tint(p, share) {
// share 0.5 → light tint, 1.0 → full color
const pct = Math.round(40 + Math.min(1, Math.max(0, (share - 0.5) / 0.4)) * 60);
const v = p === "D" ? "--dem" : p === "R" ? "--rep" : "--ind";
return `color-mix(in srgb, var(${v}) ${pct}%, var(--map-empty))`;
}
function fillFor(code) {
const d = DATA[code];
if (!d) return "url(#p-unk)";
if (mode === "gov") {
const k = partyKey(eff(d.gov));
return k === "U" ? "url(#p-unk)" : `var(${k === "D" ? "--dem" : k === "R" ? "--rep" : "--ind"})`;
}
if (mode === "sen") {
const ps = (d.senators || []).map(s => partyKey(eff(s)));
if (ps.includes("U")) return "url(#p-unk)";
if (ps[0] === ps[1]) return `var(${ps[0] === "D" ? "--dem" : ps[0] === "R" ? "--rep" : "--ind"})`;
if (ps.includes("I") ) return `color-mix(in srgb, var(--ind) 65%, var(${ps.includes("D") ? "--dem" : "--rep"}))`;
return "url(#p-split)";
}
let c;
if (mode === "house") c = countParties((d.house || []).map(eff));
else { const ch = chamber(code, mode); if (!ch) return "url(#p-unk)"; c = chamberCounts(ch); }
const m = majority(c);
return m.party ? tint(m.party, m.share) : "url(#p-unk)";
}
function lightLabel(code) {
// labels are white on strong fills, dark on pale tints / patterns
const f = fillFor(code);
if (f.startsWith("url")) return false;
const m = f.match(/ (\d+)%/);
return !m || +m[1] >= 70;
}
/* ---------- map (built once the shapes are loaded) ---------- */
function startMap() {
const svg = d3.select("#map");
const gStates = d3.select("#states"), gLabels = d3.select("#labels"), gChips = d3.select("#chips");
const path = d3.geoPath();
const features = topojson.feature(GEO, GEO.objects.states).features.filter(f => CODES[f.properties.name]);
features.forEach(f => { f.code = CODES[f.properties.name]; });
const tip = document.getElementById("tip");
function tipText(code) {
const d = DATA[code]; if (!d) return NAMES[code];
const g = d.gov ? `Gov. ${d.gov.name || "?"} (${partyKey(d.gov.party)})` : "";
const s = countParties((d.senators || []).map(eff));
const h = countParties((d.house || []).map(eff));
const fmt = c => ["D","R","I"].filter(k => c[k]).map(k => c[k] + k).concat(c.U ? [c.U + "?"] : []).join(" ");
return `<strong>${NAMES[code]}</strong><br>${esc(g)}<br>Senate ${fmt(s)} · House ${fmt(h)}`;
}
function showTip(ev, code) { tip.innerHTML = tipText(code); tip.hidden = false; moveTip(ev); }
function moveTip(ev) { tip.style.left = Math.min(window.innerWidth - 270, ev.clientX + 14) + "px"; tip.style.top = (ev.clientY + 14) + "px"; }
function hideTip() { tip.hidden = true; }
gStates.selectAll("path").data(features).join("path")
.attr("class", "state").attr("d", path)
.attr("tabindex", 0).attr("role", "button")
.attr("aria-label", f => NAMES[f.code])
.on("click", (ev, f) => select(f.code))
.on("keydown", (ev, f) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); select(f.code); } })
.on("mouseenter", (ev, f) => showTip(ev, f.code))
.on("mousemove", moveTip)
.on("mouseleave", hideTip);
gLabels.selectAll("text").data(features.filter(f => !SMALL.includes(f.code))).join("text")
.attr("class", "lbl")
.attr("x", f => path.centroid(f)[0] + (LABEL_SHIFT[f.code] || [0, 0])[0])
.attr("y", f => path.centroid(f)[1] + (LABEL_SHIFT[f.code] || [0, 0])[1])
.text(f => f.code);
const chip = gChips.selectAll("g").data(SMALL).join("g")
.attr("class", "chip").attr("tabindex", 0).attr("role", "button").attr("aria-label", c => NAMES[c])
.attr("transform", (c, i) => `translate(985, ${250 + i * 30})`)
.on("click", (ev, c) => select(c))
.on("keydown", (ev, c) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); select(c); } })
.on("mouseenter", (ev, c) => showTip(ev, c)).on("mousemove", moveTip).on("mouseleave", hideTip);
chip.append("rect").attr("width", 40).attr("height", 22).attr("rx", 4);
chip.append("text").attr("class", "lbl").attr("x", 20).attr("y", 11).text(c => c);
/* ---------- national totals per mode ---------- */
function nationalTotals() {
const codes = Object.keys(NAMES);
if (mode === "gov") return { title: "Governors", c: countParties(codes.map(c => eff(DATA[c]?.gov))) };
if (mode === "sen") return { title: "U.S. senators", c: countParties(codes.flatMap(c => (DATA[c]?.senators || []).map(eff))) };
if (mode === "house") return { title: "U.S. representatives", c: countParties(codes.flatMap(c => (DATA[c]?.house || []).map(eff))) };
const ctrl = { D: 0, R: 0, I: 0, U: 0 }, seats = { D: 0, R: 0, I: 0, U: 0 };
for (const c of codes) {
const ch = chamber(c, mode); if (!ch) continue;
const cc = chamberCounts(ch); for (const k in seats) seats[k] += cc[k];
const m = majority(cc); ctrl[m.party || "U"]++;
}
return { title: mode === "upper" ? "State senate chambers controlled" : "State house chambers controlled", c: ctrl, seats };
}
function renderTotals() {
const t = nationalTotals();
let html = `<span class="t-title">${t.title}</span>${summary(t.c)}`;
if (t.seats) {
const s = t.seats;
html += `<span class="t-sub">Seats: ${["D","R","I"].filter(k => s[k]).map(k => s[k].toLocaleString("en-US") + k).join(" · ")}${s.U ? " · " + s.U + " not yet called" : ""}${mode === "upper" ? " (Nebraska's unicameral legislature counted here)" : " (Nebraska has no lower house)"}</span>`;
}
document.getElementById("totals").innerHTML = html;
}
function renderLegend() {
const sw = (bg) => `<span class="sw" style="background:${bg}"></span>`;
const items = [];
if (mode === "gov" || mode === "sen") {
items.push(sw("var(--dem)") + "Democrat", sw("var(--rep)") + "Republican", sw("var(--ind)") + "Independent / other");
if (mode === "sen") items.push(sw("repeating-linear-gradient(45deg,var(--dem) 0 4px,var(--rep) 4px 8px)") + "Split delegation");
} else {
items.push(sw(tint("D", 0.95)) + "Strong D majority", sw(tint("D", 0.55)) + "Narrow D", sw(tint("R", 0.55)) + "Narrow R", sw(tint("R", 0.95)) + "Strong R majority");
}
items.push(sw("repeating-linear-gradient(45deg,var(--unk) 0 2px,var(--map-empty) 2px 6px)") + (isElection() ? (mode === "lower" ? "Tied, not yet called, or no chamber" : "Tied or not yet called") : (mode === "lower" ? "Tied, vacant, or no chamber" : "Tied or vacant")));
document.getElementById("legend").innerHTML = items.map(i => `<span>${i}</span>`).join("");
}
function paint() {
gStates.selectAll("path").style("fill", f => fillFor(f.code)).classed("sel", f => f.code === selected);
gLabels.selectAll("text").classed("dark", f => !lightLabel(f.code));
chip.select("rect").style("fill", c => fillFor(c));
chip.select("text").classed("dark", c => !lightLabel(c));
chip.classed("sel", c => c === selected);
renderTotals(); renderLegend();
}
/* ---------- detail panel ---------- */
function personRow(p, extra) {
const note = p.note ? `<span class="note">${esc(p.note)}</span>` : "";
const open = eff(p) == null;
const who = p.name ? esc(p.name) + (open && p.party ? ` (${p.party})` : "") : "Not yet known";
return `<li>${sq(eff(p))}<span class="who">${extra || ""}${who}${tag(p.status)}${note}</span><span class="end">${fmtDate(p.termEnd)}</span></li>`;
}
function chamberBlock(title, ch, code) {
if (!ch) return `<div class="cat"><h3>${title}</h3><p class="chamber">${code === "NE" ? "Nebraska has a single-chamber legislature, shown under State senators." : "No data."}</p></div>`;
const L = ch.leader;
const leader = L ? `<ul class="people">${personRow(L, `<span class="role">${esc(L.title || "Leader")}</span>`)}</ul>` : "";
const extras = [];
if (ch.vacant) extras.push(`${ch.vacant} vacant`);
if (ch.seats) extras.push(`${ch.seats} seats`);
const cnote = ch.compositionNote ? `<span class="note">${esc(ch.compositionNote)}</span>` : "";
return `<div class="cat"><h3>${title}</h3><span class="chamber">${esc(ch.name || "")}</span>${leader}${summary(chamberCounts(ch), extras.join(" · "))}${cnote}</div>`;
}
function renderState(code) {
const d = DATA[code] || {};
const sen = d.senators || [], house = (d.house || []).slice().sort((a, b) => a.district - b.district), g = d.gov;
const senHtml = `<div class="cat"><h3>U.S. senators</h3><ul class="people">${sen.map(s => personRow(s)).join("")}</ul>${summary(countParties(sen.map(eff)))}</div>`;
const houseHtml = `<div class="cat"><h3>U.S. representatives</h3><ul class="people">${house.map(r => personRow(r, `<span class="dist">${r.district === 0 ? "At-large" : "District " + r.district}</span>`)).join("")}</ul>${summary(countParties(house.map(eff)))}</div>`;
const upper = chamberBlock(code === "NE" ? "State senators (unicameral)" : "State senators", chamber(code, "upper"), code);
const lower = chamberBlock("State representatives", chamber(code, "lower"), code);
let govHtml = "";
if (g) {
const powers = (g.powers || []).length ? `<div class="chamber">Main powers</div><ul class="powers">${g.powers.map(p => `<li>${esc(p)}</li>`).join("")}</ul>` : "";
govHtml = `<div class="cat"><h3>Governor</h3><ul class="people">${personRow(g)}</ul>${summary(countParties([eff(g)]))}${powers}</div>`;
}
document.getElementById("panel").innerHTML =
`<h2>${NAMES[code]}</h2><p class="sub">${periodText()} · right-hand column = end of term</p>${senHtml}${houseHtml}${upper}${lower}${govHtml}`;
}
function renderOverview() {
const codes = Object.keys(NAMES);
const row = (label, c, extra) => `<div class="row"><span>${label}${extra ? `<span class="note">${extra}</span>` : ""}</span>${summary(c)}</div>`;
const ctrl = (which) => { const c = { D: 0, R: 0, I: 0, U: 0 }; for (const k of codes) { const ch = chamber(k, which); if (ch) c[majority(chamberCounts(ch)).party || "U"]++; } return c; };
document.getElementById("panel").innerHTML = `<h2>United States</h2><p class="sub">National totals ${fromWhen()}. Pick a state on the map for names and term ends.</p>
<div class="overview">
${row("U.S. senators", countParties(codes.flatMap(c => (DATA[c]?.senators || []).map(eff))))}
${row("U.S. representatives", countParties(codes.flatMap(c => (DATA[c]?.house || []).map(eff))))}
${row("State senates", ctrl("upper"), "Chambers by majority party, Nebraska included")}
${row("State houses", ctrl("lower"), "Chambers by majority party; 49 states")}
${row("Governors", countParties(codes.map(c => eff(DATA[c]?.gov))))}
</div>
<p class="hint">"Not yet called" counts races Wikipedia had not settled when the data was read; ties count there too for chambers.</p>`;
}
function select(code) {
selected = code && NAMES[code] ? code : null;
document.getElementById("statePick").value = selected || "";
if (selected) renderState(selected); else renderOverview();
paint();
try { history.replaceState(null, "", selected ? "#" + selected : location.pathname + location.search); } catch (e) {}
}
/* ---------- wiring ---------- */
const pick = document.getElementById("statePick");
Object.keys(NAMES).sort((a, b) => NAMES[a].localeCompare(NAMES[b])).forEach(c => pick.add(new Option(NAMES[c], c)));
pick.addEventListener("change", () => select(pick.value));
document.querySelectorAll(".modes button").forEach(b => b.addEventListener("click", () => {
mode = b.dataset.mode;
document.querySelectorAll(".modes button").forEach(x => x.setAttribute("aria-pressed", String(x === b)));
paint();
}));
window.addEventListener("hashchange", () => select(location.hash.slice(1)));
select(location.hash.slice(1));
return { rerender: () => select(selected) };
}
/* ---------- loading and updating ---------- */
async function getJSON(url, opts) {
const r = await fetch(url, Object.assign({ cache: "no-store" }, opts || {}));
let body = null;
try { body = await r.json(); } catch (e) { /* not JSON */ }
if (!r.ok && r.status !== 409) throw new Error((body && body.error) || `the server answered ${r.status}`);
return { status: r.status, body };
}
async function loadData() {
const { body } = await getJSON("/api/data");
DATA = body.data; META = body.meta;
applyMeta();
}
function setStatus(kind, html) {
const el = document.getElementById("upStatus");
el.className = "upstatus" + (kind ? " " + kind : "");
el.innerHTML = html;
el.hidden = !html;
}
function showWarnings(list, when) {
const box = document.getElementById("warnBox");
box.hidden = !list.length;
document.getElementById("warnSummary").textContent = `${list.length} warning${list.length === 1 ? "" : "s"} ${when}`;
document.getElementById("warnList").innerHTML = list.map(w => `<li>${esc(w)}</li>`).join("");
}
const btn = document.getElementById("updateBtn");
let polling = null;
function busy(on) { btn.disabled = on; btn.textContent = on ? "Updating…" : "Update from Wikipedia"; }
async function poll() {
let st;
try { st = (await getJSON("/api/update/status")).body; }
catch (e) { setStatus("error", `Could not reach the server to follow the update (${esc(e.message)}). Reload the page to try again.`); stopPolling(); return; }
if (st.state === "running") {
const last = st.messages && st.messages.length ? st.messages[st.messages.length - 1] : (st.runningElsewhere ? "An update started from the command line is running." : "Starting…");
setStatus("", `<span class="spin" aria-hidden="true"></span>${esc(last)}`);
return;
}
stopPolling();
if (st.state === "failed") {
setStatus("error", `The update did not finish: ${esc(st.error || "unknown error")}`);
return;
}
try {
await loadData();
if (app) app.rerender();
const n = (st.warnings || []).length;
setStatus("ok", n ? `Updated. Some data could not be refreshed and was kept as before (${n} warning${n === 1 ? "" : "s"} below).` : "Updated from Wikipedia. Everything was refreshed.");
} catch (e) {
setStatus("error", `The update finished, but the new data could not be loaded (${esc(e.message)}).`);
}
}
function startPolling() { busy(true); if (!polling) { polling = setInterval(poll, 1500); poll(); } }
function stopPolling() { clearInterval(polling); polling = null; busy(false); }
btn.addEventListener("click", async () => {
busy(true);
setStatus("", `<span class="spin" aria-hidden="true"></span>Starting the update…`);
try {
const { status } = await getJSON("/api/update", { method: "POST", headers: { "X-Requested-With": "us-officeholders-map" } });
if (status === 409) setStatus("", `<span class="spin" aria-hidden="true"></span>An update is already running; following it.`);
startPolling();
} catch (e) {
busy(false);
setStatus("error", `Could not start the update: ${esc(e.message)}.`);
}
});
(async function boot() {
try {
const shapes = fetch("/static/states-albers-10m.json").then(r => { if (!r.ok) throw new Error("the map shapes are missing"); return r.json(); });
const [geo] = await Promise.all([shapes, loadData()]);
GEO = geo;
app = startMap();
} catch (e) {
document.getElementById("lede").textContent = "";
document.getElementById("panel").innerHTML = `<p>The map could not be loaded: ${esc(e.message)}. Check that the server is running, then reload the page.</p>`;
return;
}
try { const st = (await getJSON("/api/update/status")).body; if (st.state === "running") startPolling(); } catch (e) { /* the map still works */ }
})();
</script>
+1
View File
@@ -0,0 +1 @@
{"type":"Topology","bbox":[-57.66491068874468,12.97635452036684,957.5235629133763,606.5694262668667],"transform":{"scale":[0.010151986255883769,0.005935990077365771],"translate":[-57.66491068874468,12.97635452036684]},"objects":{"states":{"type":"GeometryCollection","geometries":[{"type":"MultiPolygon","arcs":[[[0]],[[1,2,3,4,5]]],"id":"01","properties":{"name":"Alabama"}},{"type":"MultiPolygon","arcs":[[[6]],[[7]],[[8]],[[9]],[[10]],[[11]],[[12]],[[13]],[[14]],[[15]],[[16]],[[17]],[[18]],[[19]],[[20]],[[21]],[[22]],[[23]],[[24]],[[25]],[[26]],[[27]],[[28]],[[29]],[[30]],[[31]],[[32]],[[33]],[[34]],[[35]],[[36]],[[37]],[[38]],[[39]],[[40]],[[41]],[[42]],[[43]],[[44]],[[45]],[[46]],[[47]],[[48]],[[49]],[[50]],[[51]],[[52]],[[53]],[[54]],[[55]],[[56]],[[57]],[[58]],[[59]],[[60]],[[61]]],"id":"02","properties":{"name":"Alaska"}},{"type":"Polygon","arcs":[[62,63,64,65,66]],"id":"04","properties":{"name":"Arizona"}},{"type":"Polygon","arcs":[[67,68,69,70,71,72]],"id":"08","properties":{"name":"Colorado"}},{"type":"MultiPolygon","arcs":[[[73]],[[74]],[[75]],[[76]],[[77]],[[78]],[[79]],[[80]],[[81]],[[82,83,-4]]],"id":"12","properties":{"name":"Florida"}},{"type":"Polygon","arcs":[[84,85,86,87,-83,-3]],"id":"13","properties":{"name":"Georgia"}},{"type":"Polygon","arcs":[[88,89,90,91,92]],"id":"18","properties":{"name":"Indiana"}},{"type":"Polygon","arcs":[[93,94,95,-70]],"id":"20","properties":{"name":"Kansas"}},{"type":"MultiPolygon","arcs":[[[96]],[[97]],[[98]],[[99]],[[100]],[[101]],[[102]],[[103,104]]],"id":"23","properties":{"name":"Maine"}},{"type":"MultiPolygon","arcs":[[[105]],[[106]],[[107,108,109,110,111,112,113,114]]],"id":"25","properties":{"name":"Massachusetts"}},{"type":"Polygon","arcs":[[115,116,117,118,119]],"id":"27","properties":{"name":"Minnesota"}},{"type":"Polygon","arcs":[[120,121,122,123,124,125,126,127]],"id":"34","properties":{"name":"New Jersey"}},{"type":"MultiPolygon","arcs":[[[128]],[[129]],[[130,131,132,-86,133]]],"id":"37","properties":{"name":"North Carolina"}},{"type":"Polygon","arcs":[[134,-120,135,136]],"id":"38","properties":{"name":"North Dakota"}},{"type":"Polygon","arcs":[[-71,-96,137,138,139,140]],"id":"40","properties":{"name":"Oklahoma"}},{"type":"Polygon","arcs":[[141,142,-123,143,144,145,146]],"id":"42","properties":{"name":"Pennsylvania"}},{"type":"Polygon","arcs":[[147,-136,-119,148,149,150]],"id":"46","properties":{"name":"South Dakota"}},{"type":"Polygon","arcs":[[-140,151,152,153,154]],"id":"48","properties":{"name":"Texas"}},{"type":"Polygon","arcs":[[-151,155,-68,156,157,158]],"id":"56","properties":{"name":"Wyoming"}},{"type":"Polygon","arcs":[[-114,159,160,161]],"id":"09","properties":{"name":"Connecticut"}},{"type":"Polygon","arcs":[[162,163,164,165,166,167,168,-138,-95,169]],"id":"29","properties":{"name":"Missouri"}},{"type":"Polygon","arcs":[[170,-146,171,172,173]],"id":"54","properties":{"name":"West Virginia"}},{"type":"Polygon","arcs":[[174,175,176,-93,177,-164]],"id":"17","properties":{"name":"Illinois"}},{"type":"Polygon","arcs":[[-72,-141,-155,178,-66]],"id":"35","properties":{"name":"New Mexico"}},{"type":"Polygon","arcs":[[-169,179,180,181,-152,-139]],"id":"05","properties":{"name":"Arkansas"}},{"type":"MultiPolygon","arcs":[[[182]],[[183]],[[184]],[[185]],[[186]],[[187]],[[188]],[[189,190,-63,191]]],"id":"06","properties":{"name":"California"}},{"type":"MultiPolygon","arcs":[[[-128,192]],[[-144,-122,193,194]]],"id":"10","properties":{"name":"Delaware"}},{"type":"Polygon","arcs":[[195,196]],"id":"11","properties":{"name":"District of Columbia"}},{"type":"MultiPolygon","arcs":[[[197]],[[198]],[[199]],[[200]],[[201]],[[202]],[[203]],[[204]]],"id":"15","properties":{"name":"Hawaii"}},{"type":"Polygon","arcs":[[-118,205,-175,-163,206,-149]],"id":"19","properties":{"name":"Iowa"}},{"type":"MultiPolygon","arcs":[[[-178,-92,207,-174,208,209,-165]],[[210,-167]]],"id":"21","properties":{"name":"Kentucky"}},{"type":"MultiPolygon","arcs":[[[211,212]],[[213]],[[-145,-195,214,215,216,217,-196,218,-172]]],"id":"24","properties":{"name":"Maryland"}},{"type":"MultiPolygon","arcs":[[[219]],[[220]],[[221]],[[222]],[[223]],[[224]],[[225]],[[226]],[[227,228,-90]],[[229]],[[230,231]]],"id":"26","properties":{"name":"Michigan"}},{"type":"MultiPolygon","arcs":[[[232]],[[233]],[[234]],[[235]],[[-181,236,-6,237,238]]],"id":"28","properties":{"name":"Mississippi"}},{"type":"Polygon","arcs":[[239,-137,-148,-159,240]],"id":"30","properties":{"name":"Montana"}},{"type":"Polygon","arcs":[[241,-104,242,-109,243]],"id":"33","properties":{"name":"New Hampshire"}},{"type":"MultiPolygon","arcs":[[[244]],[[245]],[[246,-126]],[[247]],[[248]],[[249,250,-115,-162,251,-124,-143]]],"id":"36","properties":{"name":"New York"}},{"type":"MultiPolygon","arcs":[[[252]],[[253]],[[-229,254,-147,-171,-208,-91]]],"id":"39","properties":{"name":"Ohio"}},{"type":"Polygon","arcs":[[255,256,257,-190,258]],"id":"41","properties":{"name":"Oregon"}},{"type":"Polygon","arcs":[[-168,-211,-166,-210,259,-134,Line truncated