Olivia Jackson Lambert
Olivia Jackson Lambert
Work About Contact
Election 2026 A Forecast of Every Senate, House & Governor Race See the Forecast
Work About Contact

2026 Midterms Forecast

A forecast of every 2026 Senate, House and governor race, published in October and now scored against the results.

Forecast v1 · 22 October 2026 · 20,000 simulations Forecast Published 22 October 2026 How the model works → How it scored →

Code
Plot = import("https://cdn.jsdelivr.net/npm/@observablehq/plot@0.6.16/+esm")
topojson = import("https://cdn.jsdelivr.net/npm/topojson-client@3.1.0/+esm")
us = d3.json("https://cdn.jsdelivr.net/npm/us-atlas@3.0.1/counties-10m.json")
states = topojson.feature(us, us.objects.states).features
counties = topojson.feature(us, us.objects.counties).features
stateMesh = topojson.mesh(us, us.objects.states, (a, b) => a !== b)

isTrue = v => String(v).toLowerCase() === "true"
races = (await FileAttachment("data/races.csv").csv({typed: true})).map(r => ({...r, special: isTrue(r.special), open_seat: isTrue(r.open_seat)}))
isSpecial = r => r.special === true
national = (await FileAttachment("data/national.csv").csv({typed: true}))[0]
senateSeats = normalise(await FileAttachment("data/senate_seats.csv").csv({typed: true}))
governorSeats = normalise(await FileAttachment("data/governor_seats.csv").csv({typed: true}))
houseSeats = normalise(await FileAttachment("data/house_seats.csv").csv({typed: true}))
districts = FileAttachment("data/house_districts.csv").csv({typed: true})
turnout = FileAttachment("data/turnout_counties.csv").csv({typed: true})
turnoutStates = FileAttachment("data/turnout_states.csv").csv({typed: true})
credits = FileAttachment("img/credits.json").json()
photoFor = new Map(credits.map(c => [`${c.race_id}-${c.side}`, c]))

DEM = "#4d6a8f"
REP = "#c9503f"
IND = "#5f6368"
GREEN = "#4e7d5b"
PURPLE = "#8c6d8f"
NO_RACE = "#9aa0a8"
TURNOUT_2022 = 0.465
probColour = d3.piecewise(d3.interpolateRgb, [REP, "#e0a59c", "#d6d7d9", "#9fb1c8", DEM])
changeColour = d3.interpolateRgbBasis(["#4f3a5c", PURPLE, "#eeeff0", GREEN, "#2e5539"])
// party colours as text: a CSS variable per mode, so small labels stay legible in dark mode
textColour = c => ({[DEM]: "var(--fc-dem-text)", [REP]: "var(--fc-rep-text)", [GREEN]: "var(--fc-green-text)"})[c] ?? c

FIPS = ({"01":"AL","02":"AK","04":"AZ","05":"AR","06":"CA","08":"CO","09":"CT","10":"DE","11":"DC","12":"FL",
  "13":"GA","15":"HI","16":"ID","17":"IL","18":"IN","19":"IA","20":"KS","21":"KY","22":"LA","23":"ME","24":"MD",
  "25":"MA","26":"MI","27":"MN","28":"MS","29":"MO","30":"MT","31":"NE","32":"NV","33":"NH","34":"NJ","35":"NM",
  "36":"NY","37":"NC","38":"ND","39":"OH","40":"OK","41":"OR","42":"PA","44":"RI","45":"SC","46":"SD","47":"TN",
  "48":"TX","49":"UT","50":"VT","51":"VA","53":"WA","54":"WV","55":"WI","56":"WY"})
NAME = ({AL:"Alabama",AK:"Alaska",AZ:"Arizona",AR:"Arkansas",CA:"California",CO:"Colorado",CT:"Connecticut",
  DE:"Delaware",DC:"District of Columbia",FL:"Florida",GA:"Georgia",HI:"Hawaii",ID:"Idaho",IL:"Illinois",IN:"Indiana",
  IA:"Iowa",KS:"Kansas",KY:"Kentucky",LA:"Louisiana",ME:"Maine",MD:"Maryland",MA:"Massachusetts",MI:"Michigan",
  MN:"Minnesota",MS:"Mississippi",MO:"Missouri",MT:"Montana",NE:"Nebraska",NV:"Nevada",NH:"New Hampshire",
  NJ:"New Jersey",NM:"New Mexico",NY:"New York",NC:"North Carolina",ND:"North Dakota",OH:"Ohio",OK:"Oklahoma",
  OR:"Oregon",PA:"Pennsylvania",RI:"Rhode Island",SC:"South Carolina",SD:"South Dakota",TN:"Tennessee",TX:"Texas",
  UT:"Utah",VT:"Vermont",VA:"Virginia",WA:"Washington",WV:"West Virginia",WI:"Wisconsin",WY:"Wyoming"})

// v1's seat files were rounded to four decimals, which loses up to 0.3% of the total; rescale to 1.
normalise = (rows) => { const t = d3.sum(rows, d => d.probability); return rows.map(d => ({...d, probability: d.probability / t})) }
pct = (p) => p >= 0.995 ? ">99%" : p <= 0.005 ? "<1%" : `${Math.round(p * 100)}%`
share = (x) => `${(x * 100).toFixed(1)}%`
pts = (x) => `${x > 0 ? "+" : x < 0 ? "−" : ""}${Math.abs(x * 100).toFixed(1)}`
esc = (s) => String(s ?? "").replace(/[&<>"']/g, c => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]))
isInd = (r) => r.d_side !== "democrat"
favourite = (r) => r.p_dem_win >= 0.5
  ? {side: isInd(r) ? "Independent" : "Democrat", name: r.dem_candidate, p: r.p_dem_win, colour: isInd(r) ? IND : DEM}
  : {side: "Republican", name: r.rep_candidate, p: 1 - r.p_dem_win, colour: REP}
rating = (p) => { const q = Math.max(p, 1 - p); return q < 0.6 ? "Toss-Up" : q < 0.8 ? "Lean" : q < 0.95 ? "Likely" : "Solid" }
ratingLabel = (r) => { const f = favourite(r), k = rating(f.p); return k === "Toss-Up" ? k : `${k} ${f.side.slice(0, 3)}` }
distribution = (rows, key) => d3.rollups(rows, v => d3.sum(v, d => d.probability), d => d[key])
  .map(([seats, p]) => ({seats, p})).sort((a, b) => a.seats - b.seats)
median = (dist) => quantile(dist, 0.5)
quantile = (dist, q) => { let c = 0; for (const d of dist) { c += d.p; if (c >= q) return d.seats } }

// Candidates: party, display name, photo (if a free one exists) and the initials used when there is none.
PARTY = ({D: {short: "Dem", long: "Democrat", colour: DEM}, R: {short: "Rep", long: "Republican", colour: REP}, I: {short: "Ind", long: "Independent", colour: IND}})
sideParty = (r, side) => side === "rep" ? "R" : isInd(r) ? "I" : "D"
candName = (r, side) => side === "rep"
  ? (r.rep_candidate.startsWith("Several Republicans") ? "Republican Field (Top Four)" : r.rep_candidate)
  : r.dem_candidate
initials = (name) => {
  if (name.startsWith("Republican Field")) return "R"
  const w = name.split(/\s+/).filter(x => x && !/^(Jr\.?|Sr\.?|II|III|IV)$/i.test(x) && !/^[A-Z]\.$/.test(x))
  return w.length ? (w[0][0] + (w.length > 1 ? w[w.length - 1][0] : "")).toUpperCase() : "?"
}
raceTitle = (r) => `${NAME[r.state]} ${r.office === "senate" ? "Senate" : "Governor"}${isSpecial(r) ? " (Special)" : ""}`
avatar = (name, party, photo) => html`<span class="fc-av" style="--av:${PARTY[party].colour}" aria-hidden="true">${initials(name)}${photo
  ? `<img src="img/${esc(photo.image)}" alt="" loading="lazy" decoding="async" onerror="this.remove()">` : ""}</span>`
candLine = (party, name, p, photo) => html`<span class="${p >= 0.5 ? "fc-cand is-fav" : "fc-cand"}">
    ${avatar(name, party, photo)}
    <span class="fc-cand-name"><span>${name}</span><span class="fc-cand-party">${PARTY[party].long}</span></span>
    <span class="fc-cand-p" style="color:${textColour(PARTY[party].colour)}">${pct(p)}</span>
  </span>`
candRow = (r, side) => candLine(sideParty(r, side), candName(r, side), side === "rep" ? 1 - r.p_dem_win : r.p_dem_win, photoFor.get(`${r.race_id}-${side}`))
segBar = (segs) => html`<span class="fc-pbar" aria-hidden="true">${segs.filter(s => s.p > 0).map(s => `<span style="width:${s.p * 100}%;background:${s.colour}"></span>`).join("")}<i></i></span>`
probBar = (r) => segBar([{p: r.p_dem_win, colour: PARTY[sideParty(r, "dem")].colour}, {p: 1 - r.p_dem_win, colour: REP}])
describe = (r) => `${raceTitle(r)}: ${candName(r, "dem")} (${PARTY[sideParty(r, "dem")].short}) ${pct(r.p_dem_win)}, ${candName(r, "rep")} (Rep) ${pct(1 - r.p_dem_win)}. ${ratingLabel(r)}.`
textOn = (fill) => d3.lab(fill).l > 62 ? "#1d1f23" : "#ffffff"
chip = (party, text) => `<span class="fc-chip" style="--chip:${PARTY[party].colour}">${text}</span>`
reveal = (sel) => setTimeout(() => document.querySelector(sel)?.scrollIntoView({block: "nearest", behavior: "smooth"}), 80)

// Cards for the closest races: clicking one selects it. `mark` highlights the selected card without redrawing.
cardGrid = (items, onPick) => {
  const el = html`<div class="fc-races">${items.map(it => html`<button type="button" class="fc-race" data-id="${it.id}" aria-pressed="false">
      <span class="fc-race-head"><span class="fc-race-title">${it.title}</span><span class="fc-rating">${it.rating}</span></span>
      ${it.lines}${it.bar}<span class="fc-race-foot">${it.foot}</span></button>`)}</div>`
  for (const b of el.querySelectorAll("button")) b.addEventListener("click", () => onPick(b.dataset.id))
  el.mark = id => { for (const b of el.querySelectorAll("button")) b.setAttribute("aria-pressed", b.dataset.id === id) }
  return el
}

// A light sortable, searchable table. Each column: {key, label, value(row) for sorting, render(row) as HTML, cls}.
// Optional `filters` ([{key, label, test(row)}]) add a row of toggle buttons; `filter` is the one shown first.
dataTable = ({items, columns, sortKey, sortDir = 1, searchText, placeholder, noun, caption, onPick, filters, filter}) => {
  const el = html`<div class="fc-tbl">
    <div class="fc-tbl-bar">
      <label class="fc-tbl-search"><span class="visually-hidden">Search ${noun[1]}</span>
        <input type="search" placeholder="${placeholder}" autocomplete="off"></label>
      ${filters ? `<div class="fc-segb fc-tbl-filter" role="group" aria-label="Which ${noun[1]} to show">${filters.map(f =>
        `<button type="button" data-f="${f.key}" aria-pressed="${f.key === filter}">${f.label}</button>`).join("")}</div>` : ""}
      <span class="fc-tbl-count" aria-live="polite"></span>
    </div>
    <div class="fc-tbl-scroll"><table><caption class="visually-hidden">${caption}</caption>
      <thead><tr>${columns.map(c => `<th scope="col" class="${c.cls ?? ""}" data-key="${c.key}" aria-sort="none"><button type="button">${c.label}<span class="fc-sort" aria-hidden="true"></span></button></th>`).join("")}</tr></thead>
      <tbody></tbody></table></div></div>`
  const input = el.querySelector("input"), tbody = el.querySelector("tbody"), count = el.querySelector(".fc-tbl-count")
  const index = items.map(it => ({it, text: searchText(it).toLowerCase()}))
  const draw = () => {
    const words = input.value.toLowerCase().split(/\s+/).filter(Boolean)
    const col = columns.find(c => c.key === sortKey)
    const cmp = col.compare ?? ((a, b) => d3.ascending(col.value(a), col.value(b)))
    const test = filters?.find(f => f.key === filter)?.test ?? (() => true)
    const rows = index.filter(x => test(x.it) && words.every(w => x.text.includes(w))).map(x => x.it).sort((a, b) => sortDir * cmp(a, b))
    count.textContent = rows.length === items.length ? `${items.length} ${noun[1]}` : `${rows.length} of ${items.length} ${noun[1]}`
    for (const th of el.querySelectorAll("th")) th.setAttribute("aria-sort", th.dataset.key === sortKey ? (sortDir > 0 ? "ascending" : "descending") : "none")
    if (!rows.length) {
      const tr = document.createElement("tr"), td = document.createElement("td"), btn = document.createElement("button")
      tr.className = "fc-tbl-empty"; td.colSpan = columns.length
      if (!words.length) { td.append(`No ${noun[1]} in this group yet.`); tr.append(td); tbody.replaceChildren(tr); return }
      td.append(`No ${noun[1]} match “${input.value.trim()}”. `)
      btn.type = "button"; btn.textContent = "Clear the Search"; btn.onclick = () => { input.value = ""; draw(); input.focus() }
      td.append(btn); tr.append(td); tbody.replaceChildren(tr); return
    }
    tbody.innerHTML = rows.map(r => `<tr data-id="${r.id}">${columns.map(c => `<td class="${c.cls ?? ""}">${c.render(r)}</td>`).join("")}</tr>`).join("")
  }
  input.addEventListener("input", draw)
  for (const b of el.querySelectorAll(".fc-tbl-filter button")) b.addEventListener("click", () => {
    filter = b.dataset.f
    for (const x of el.querySelectorAll(".fc-tbl-filter button")) x.setAttribute("aria-pressed", x === b)
    draw()
  })
  for (const th of el.querySelectorAll("th")) th.querySelector("button").addEventListener("click", () => {
    sortDir = th.dataset.key === sortKey ? -sortDir : 1; sortKey = th.dataset.key; draw()
  })
  if (onPick) tbody.addEventListener("click", e => {
    const tr = e.target.closest("tr[data-id]")
    if (tr && (e.target.closest(".fc-row-link") || !e.target.closest("a, button"))) onPick(tr.dataset.id)
  })
  draw()
  return el
}
Code
senateDist = distribution(senateSeats, "dem_seats")
pSenateD = d3.sum(senateSeats.filter(d => d.dem_seats >= 51), d => d.probability) / d3.sum(senateSeats, d => d.probability)
pSenateR = d3.sum(senateSeats.filter(d => 100 - d.dem_seats - d.independent_seats >= 50), d => d.probability) / d3.sum(senateSeats, d => d.probability)
govDist = distribution(governorSeats, "dem_seats")
pGovD = d3.sum(governorSeats.filter(d => d.dem_seats >= 26), d => d.probability) / d3.sum(governorSeats, d => d.probability)
pGovR = d3.sum(governorSeats.filter(d => d.dem_seats + d.independent_seats <= 24), d => d.probability) / d3.sum(governorSeats, d => d.probability)
houseDist = distribution(houseSeats, "dem_seats")
// v1's four-decimal seat files sum to just under 1, so each chance is divided by its file's total
pHouseD = d3.sum(houseSeats.filter(d => d.dem_seats >= 218), d => d.probability) / d3.sum(houseSeats, d => d.probability)
pHouseR = d3.sum(houseSeats.filter(d => d.rep_seats >= 218), d => d.probability) / d3.sum(houseSeats, d => d.probability)
Code
// Forecast | Results. The forecast is the default; the reader's choice is remembered, and #results opens the results.
viewof view = {
  const KEY = "fc-view", forecastTabs = ["senate", "house", "governors", "turnout"]
  const fromHash = () => { const h = location.hash.slice(1).toLowerCase(); return h.startsWith("results") ? "results" : forecastTabs.includes(h) ? "forecast" : null }
  let stored = null
  try { stored = localStorage.getItem(KEY) } catch (e) {}
  const el = html`<div class="fc-viewbar"><div class="fc-segb" role="group" aria-label="Show the forecast or the results">
    <button type="button" data-v="forecast">Forecast</button><button type="button" data-v="results">Results</button></div></div>`
  const buttons = [...el.querySelectorAll("button")]
  const apply = (v, {remember = false, hash = false, notify = true} = {}) => {
    if (v !== "results") v = "forecast"
    const changed = v !== el.value
    el.value = v
    for (const b of buttons) b.setAttribute("aria-pressed", b.dataset.v === v)
    document.documentElement.classList.toggle("fc-results", v === "results")
    if (remember) { try { localStorage.setItem(KEY, v) } catch (e) {} }
    if (hash) {
      const h = location.hash.slice(1).toLowerCase()
      if (v === "results" && !h.startsWith("results")) history.replaceState(null, "", "#results")
      if (v === "forecast" && h.startsWith("results")) history.replaceState(null, "", location.pathname + location.search)
    }
    // the forecast's sticky bar measured itself while hidden; let it measure again
    if (v === "forecast") setTimeout(() => dispatchEvent(new Event("resize")), 0)
    if (changed && notify) el.dispatchEvent(new Event("input", {bubbles: true}))
  }
  el.addEventListener("click", e => { const b = e.target.closest("button[data-v]"); if (b) apply(b.dataset.v, {remember: true, hash: true}) })
  const onHash = () => { const v = fromHash(); if (v) apply(v) }
  addEventListener("hashchange", onHash)
  invalidation.then(() => removeEventListener("hashchange", onHash))
  apply(fromHash() ?? stored ?? "forecast", {notify: false})
  // the switch sits at the right of the line under the title, out of the way of the page itself
  const lede = document.querySelector(".fc-lede")
  const line = lede?.querySelector("p") ?? lede
  if (line) { line.classList.add("has-switch"); line.append(el) }
  return el
}
Code
// The one control for the page: four headline numbers that are also the tabs. Once the reader scrolls
// into the tab content it sticks under the site header as a slim row of labels and numbers.
viewof tab = {
  const tabs = ["senate", "house", "governors", "turnout"]
  const panel = k => k === "house" ? "fc-panel-house" : k === "turnout" ? "fc-panel-turnout" : "fc-panel-races"
  const fromHash = () => { const h = location.hash.slice(1).toLowerCase(); return tabs.includes(h) ? h : null }
  const bar = (pD, pR) => `<span class="fc-card-bar" aria-hidden="true"><span class="fc-bar"><span style="width:${pD * 100}%;background:${DEM}"></span><span style="flex:1;background:var(--fc-tie)"></span><span style="width:${pR * 100}%;background:${REP}"></span></span></span>`
  const card = (key, label, big, colour, text, extra) => `<button type="button" role="tab" class="fc-card" id="fc-tab-${key}" data-tab="${key}" aria-controls="${panel(key)}">
      <span class="fc-card-label">${label}</span>
      <span class="fc-card-big" style="color:${textColour(colour)}">${big}</span>
      <span class="fc-card-text">${text}</span>
      ${extra}</button>`
  const race = (key, label, prize, pD, pR) => {
    const [lead, other] = pD >= pR ? [["Democrats", pD, DEM], ["Republicans", pR]] : [["Republicans", pR, REP], ["Democrats", pD]]
    return card(key, label, pct(lead[1]), lead[2], `Chance ${lead[0]} win ${prize}. ${other[0]}: ${pct(other[1])}.`, bar(pD, pR))
  }
  const lo = national.turnout_2026_lo80, hi = national.turnout_2026_hi80, scale = x => (x - 0.3) / 0.35 * 100
  const el = html`<div class="fc-switch">
    <div class="fc-cards" role="tablist" aria-label="Forecast sections">
      ${race("senate", "Senate", "the Senate", pSenateD, pSenateR)}
      ${race("house", "House", "the House", pHouseD, pHouseR)}
      ${race("governors", "Governors", "a majority of governorships", pGovD, pGovR)}
      ${card("turnout", "Turnout", `${(national.turnout_2026_median * 100).toFixed(1)}%`, GREEN,
        `Expected share of adult citizens voting. In 2022: ${(TURNOUT_2022 * 100).toFixed(1)}%.`,
        `<span class="fc-card-bar" aria-hidden="true"><span class="fc-range"><span style="left:${scale(lo)}%;width:${scale(hi) - scale(lo)}%;background:${GREEN}"></span><i style="left:${scale(TURNOUT_2022)}%"></i></span></span>`)}
    </div>
    <div class="fc-jump"></div>
  </div>`
  const buttons = [...el.querySelectorAll("[role=tab]")]
  const paint = () => buttons.forEach(b => { const on = b.dataset.tab === el.value; b.setAttribute("aria-selected", on); b.tabIndex = on ? 0 : -1 })
  const head = () => { const h = document.querySelector(".sitehead")?.offsetHeight ?? 64; document.body.style.setProperty("--fc-head", `${h}px`); return h }
  // Compact once the tab content has scrolled under the full bar by the height the bar is about to give up.
  // That height goes into --fc-shrink, a top margin above the stuck bar, so at the switch the bar stays stuck,
  // the content beneath it is already continuous with its new bottom edge, and nothing moves or opens a gap.
  let compactH = 0, fullH = 0
  el.barH = () => compactH || 49
  const measure = (cell) => {
    fullH = cell.offsetHeight
    el.classList.add("is-compact"); compactH = cell.offsetHeight; el.classList.remove("is-compact")
    document.body.style.setProperty("--fc-bar", `${compactH}px`)
  }
  const fit = (force) => {
    const cell = el.closest(".fc-tabbar"), wrap = el.closest(".fc-tabwrap")
    if (!cell || !wrap) return
    if (force || !compactH) { el.classList.remove("is-compact"); cell.style.setProperty("--fc-shrink", "0px"); measure(cell) }
    const want = wrap.getBoundingClientRect().top < head() - (fullH - compactH) - 1
    if (!want && el.classList.contains("is-compact")) { el.classList.remove("is-compact"); cell.style.setProperty("--fc-shrink", "0px") }
    if (want && !el.classList.contains("is-compact")) {
      el.classList.add("is-compact")
      cell.style.setProperty("--fc-shrink", `${fullH - compactH}px`)
    }
  }
  el.jump = el.querySelector(".fc-jump")
  el.setTab = (k, focus) => {
    if (!tabs.includes(k)) return
    if (location.hash.slice(1) !== k) history.replaceState(null, "", `#${k}`)
    if (k !== el.value) {
      el.value = k; paint(); el.dispatchEvent(new Event("input", {bubbles: true}))
      // If the reader has scrolled into a tab, start the new one from its top, just under the slim bar.
      // (every panel starts at the same point, so the one still showing gives the position)
      const p = document.querySelector(".fc-panel.is-active")
      if (p && el.classList.contains("is-compact")) {
        const y = Math.max(0, p.getBoundingClientRect().top + window.scrollY - head() - el.barH() - 16)
        setTimeout(() => window.scrollTo({top: y, behavior: "instant"}), 0)
      }
    }
    const b = buttons.find(b => b.dataset.tab === k)
    if (focus) b.focus()
  }
  el.addEventListener("click", e => { const b = e.target.closest("[role=tab]"); if (b) el.setTab(b.dataset.tab) })
  el.addEventListener("keydown", e => {
    const i = buttons.indexOf(document.activeElement)
    if (i < 0) return
    const j = {ArrowRight: i + 1, ArrowLeft: i - 1, ArrowDown: i + 1, ArrowUp: i - 1, Home: 0, End: buttons.length - 1}[e.key]
    if (j === undefined) return
    e.preventDefault()
    el.setTab(buttons[(j + buttons.length) % buttons.length].dataset.tab, true)
  })
  addEventListener("hashchange", () => { const h = fromHash(); if (h) el.setTab(h) })
  el.value = fromHash() ?? "senate"
  paint()
  head()
  let raf = 0
  const onScroll = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(() => fit()) }
  const onResize = () => { head(); compactH = 0; fit(true) }
  addEventListener("scroll", onScroll, {passive: true})
  addEventListener("resize", onResize)
  invalidation.then(() => { removeEventListener("scroll", onScroll); removeEventListener("resize", onResize) })
  // the site header can change height (fonts loading, narrow screens), so keep the sticky offset in step with it
  const sh = document.querySelector(".sitehead")
  if (sh) new ResizeObserver(head).observe(sh)
  setTimeout(() => fit(), 0)
  return el
}
Code
{
  const which = tab === "house" ? "house" : tab === "turnout" ? "turnout" : "races"
  for (const k of ["races", "house", "turnout"]) {
    const p = document.getElementById(`fc-panel-${k}`)
    if (!p) continue
    p.classList.toggle("is-active", k === which)
    p.setAttribute("role", "tabpanel")
    p.setAttribute("aria-labelledby", `fc-tab-${k === "races" ? (tab === "governors" ? "governors" : "senate") : k}`)
  }
}
Code
// The width the tab panels actually have (narrower than the page when the contents rail is showing).
pw = Generators.observe(notify => {
  const el = document.querySelector(".fc-tabbar")
  let last = 0
  const measure = () => { const w = Math.floor(el?.getBoundingClientRect().width || width); if (Math.abs(w - last) > 4) { last = w; notify(Math.max(280, w)) } }
  measure()
  const ro = new ResizeObserver(measure)
  if (el) ro.observe(el)
  return () => ro.disconnect()
})
Code
// Contents for the current tab: a sticky rail on wide screens, a compact jump menu in the tab bar on narrow ones.
{
  const panel = document.getElementById(tab === "house" ? "fc-panel-house" : tab === "turnout" ? "fc-panel-turnout" : "fc-panel-races")
  // Quarto puts each heading's id on its <section>; the rail scrolls to the section.
  const heads = panel ? [...panel.querySelectorAll("section.level2")] : []
  const label = {senate: "Senate", house: "House", governors: "Governors", turnout: "Turnout"}[tab]
  const items = heads.map(h => ({id: h.id, text: h.querySelector("h2")?.textContent.trim() ?? ""}))
  const nav = html`<nav class="fc-rail" aria-label="Sections in the ${label} tab"><div class="fc-rail-title">${label}</div>
    <ol>${items.map(i => `<li><a href="#${i.id}" data-id="${i.id}">${esc(i.text)}</a></li>`).join("")}</ol></nav>`
  const jump = html`<label class="fc-jumpsel"><span class="visually-hidden">Jump to a section</span><select>
    <option value="">Jump To</option>${items.map(i => `<option value="${i.id}">${esc(i.text)}</option>`).join("")}</select></label>`
  const sel = jump.querySelector("select")
  viewof tab.jump.replaceChildren(jump)
  const offset = () => (document.querySelector(".sitehead")?.offsetHeight ?? 64) + viewof tab.barH() + 16
  const go = (id) => {
    const h = document.getElementById(id)
    if (!h) return
    // window.scrollY, not scrollY: OJS reads a bare global once, when the cell first runs
    window.scrollTo({top: h.getBoundingClientRect().top + window.scrollY - offset() + 4, behavior: "smooth"})
    h.setAttribute("tabindex", "-1"); h.focus({preventScroll: true})
  }
  nav.addEventListener("click", e => { const a = e.target.closest("a[data-id]"); if (a) { e.preventDefault(); go(a.dataset.id) } })
  sel.addEventListener("change", () => { if (sel.value) go(sel.value); sel.value = "" })
  const links = [...nav.querySelectorAll("a")]
  const spy = () => {
    if (!panel?.classList.contains("is-active")) return
    let cur = heads[0]
    for (const h of heads) if (h.getBoundingClientRect().top - offset() <= 8) cur = h
    for (const a of links) { const on = a.dataset.id === cur?.id; a.classList.toggle("is-current", on); on ? a.setAttribute("aria-current", "true") : a.removeAttribute("aria-current") }
  }
  let raf = 0
  const onScroll = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(spy) }
  addEventListener("scroll", onScroll, {passive: true})
  invalidation.then(() => removeEventListener("scroll", onScroll))
  spy(); setTimeout(spy, 300); setTimeout(spy, 1500)
  return nav
}
Code
office = tab === "governors" ? "governor" : "senate"
officeRaces = races.filter(r => r.office === office)
closeness = (a, b) => Math.abs(a.p_dem_win - 0.5) - Math.abs(b.p_dem_win - 0.5)
keyRaces = officeRaces.filter(r => favourite(r).p < 0.8).sort(closeness)
closestRaces = [...officeRaces].sort(closeness).slice(0, 6)
officeWord = office === "senate" ? "Senate" : "governor"
mutable pickId = null
current = officeRaces.find(r => r.race_id === pickId) ?? closestRaces[0]
raceByState = new Map(officeRaces.map(r => [r.state, r]))
mapData = states.map(f => ({...f, state: FIPS[f.id], race: raceByState.get(FIPS[f.id])}))
pickRace = (id) => { mutable pickId = id; reveal(".fc-detail") }

Closest Races

Code
{
  return html`<p class="fc-takeaway fc-lead">In ${keyRaces.length} of the ${officeRaces.length} ${officeWord} races this year the favourite has less than an 80% chance. The closest is ${raceTitle(closestRaces[0])}.</p>`
}
Code
keyCards = cardGrid(closestRaces.map(r => ({
  id: r.race_id, title: raceTitle(r), rating: ratingLabel(r),
  lines: [candRow(r, "dem"), candRow(r, "rep")], bar: probBar(r),
  foot: r.n_polls > 0 ? `Poll Average: ${PARTY[sideParty(r, "dem")].short} ${share(r.poll_avg)} (${r.n_polls} Poll${r.n_polls === 1 ? "" : "s"})` : "No Polls Yet"
})), pickRace)

Every Race

Select a state, or pick a race from the list, to see its candidates and the numbers behind the chance. The small north-eastern states are labelled to the right of the map.

Code
raceMap = {
  const narrow = pw < 860
  const w = Math.round(narrow ? pw : pw - 356), gutter = narrow ? 46 : 58, h = Math.round((w - gutter) * 0.62)
  const projection = d3.geoAlbersUsa().fitExtent([[4, 4], [w - gutter, h - 4]], {type: "FeatureCollection", features: states})
  const path = d3.geoPath(projection)
  const select = (id) => { mutable pickId = id }

  const picker = html`<label class="fc-pick"><span>Race</span><select>${[...officeRaces].sort((a, b) => d3.ascending(NAME[a.state], NAME[b.state]))
    .map(r => `<option value="${r.race_id}">${NAME[r.state]}${isSpecial(r) ? " (Special)" : ""}: ${ratingLabel(r)}</option>`).join("")}</select></label>`
  const sel = picker.querySelector("select")
  sel.addEventListener("change", () => select(sel.value))

  const svg = d3.create("svg").attr("class", "fc-map").attr("viewBox", [0, 0, w, h]).attr("width", w).attr("height", h)
    .attr("role", "group").attr("aria-label", `Map of the ${officeRaces.length} ${officeWord} races, coloured by the chance each side wins`)
  svg.append("g").selectAll("path").data(mapData.filter(d => !d.race)).join("path").attr("class", "fc-st-none").attr("d", path)
  const raced = mapData.filter(d => d.race)
  const race = svg.append("g").selectAll("path").data(raced).join("path")
    .attr("class", "fc-st").attr("d", path).attr("fill", d => probColour(d.race.p_dem_win))
    .attr("tabindex", 0).attr("role", "button").attr("aria-label", d => describe(d.race))
    .on("click", (e, d) => select(d.race.race_id))
    .on("keydown", (e, d) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); select(d.race.race_id) } })
  race.append("title").text(d => describe(d.race))
  const outline = svg.append("path").attr("class", "fc-st-sel")

  // Labels: inside the state where it fits, otherwise a callout in a column to the right with a leader line.
  const SMALL = new Set(["VT", "NH", "MA", "RI", "CT", "NJ", "DE", "MD", "DC"])
  const inside = raced.filter(d => !SMALL.has(d.state))
  const out = raced.filter(d => SMALL.has(d.state)).map(d => ({d, c: path.centroid(d)})).sort((a, b) => a.c[1] - b.c[1])
  let y = -Infinity
  for (const o of out) { o.y = Math.max(o.c[1], y + 17); y = o.y }
  const over = (out.at(-1)?.y ?? 0) - (h - 10)
  if (over > 0) out.forEach(o => o.y -= over)
  const lx = w - gutter / 2 + 2
  svg.append("g").attr("class", "fc-st-labels").attr("aria-hidden", "true").selectAll("text").data(inside).join("text")
    .attr("transform", d => { const [x, yy] = path.centroid(d); return `translate(${x + (d.state === "FL" ? 6 : d.state === "MI" ? 4 : 0)},${yy + (d.state === "MI" ? 8 : 0)})` })
    .attr("dy", "0.35em").attr("fill", d => textOn(probColour(d.race.p_dem_win))).text(d => d.state)
  const call = svg.append("g").attr("class", "fc-st-callouts").attr("aria-hidden", "true").selectAll("g").data(out).join("g")
    .on("click", (e, o) => select(o.d.race.race_id))
  call.append("path").attr("class", "fc-leader").attr("d", o => `M${o.c[0]},${o.c[1]}L${lx - 20},${o.y}`)
  call.append("circle").attr("class", "fc-leader-dot").attr("cx", o => o.c[0]).attr("cy", o => o.c[1]).attr("r", 2)
  call.append("rect").attr("x", lx - 17).attr("y", o => o.y - 8).attr("width", 34).attr("height", 16).attr("rx", 8)
    .attr("fill", o => probColour(o.d.race.p_dem_win))
  call.append("text").attr("x", lx).attr("y", o => o.y).attr("dy", "0.35em").attr("fill", o => textOn(probColour(o.d.race.p_dem_win))).text(o => o.d.state)

  const legend = Plot.legend({color: {type: "linear", domain: [0, 1], interpolate: probColour,
    tickFormat: d => d === 0 ? "Rep" : d === 1 ? "Dem" : d === 0.5 ? "Even" : "", ticks: [0, 0.5, 1]},
    width: 210, marginLeft: 10, marginRight: 10, label: "Chance Democrats Win", className: "fc-plot"})
  const el = html`<div class="fc-map-wrap"><div class="fc-map-top">${picker}<div class="fc-legend fc-map-legend">${legend}<span class="fc-key"><span class="fc-key-none"></span>No Race</span></div></div>${svg.node()}</div>`
  el.mark = id => {
    const d = mapData.find(m => m.race?.race_id === id)
    outline.attr("d", d ? path(d) : null)
    race.attr("aria-pressed", m => m.race.race_id === id)
    call.classed("is-selected", o => o.d.race.race_id === id)
    sel.value = id
  }
  return el
}
Code
detailPanel = {
  const el = html`<aside class="fc-detail" aria-live="polite" aria-label="Selected race"></aside>`
  el.render = (r) => {
    const dp = PARTY[sideParty(r, "dem")], inc = PARTY[r.incumbent_party]?.short ?? r.incumbent_party
    const seat = r.open_seat ? `Open seat. ${r.incumbent} (${inc}) is not on the ballot.` : `${r.incumbent} (${inc}) is running again.`
    el.replaceChildren(html`<div class="fc-detail-body"><div class="fc-detail-kicker">${r === closestRaces[0] ? "Closest Race" : "Selected Race"}</div>
      <h3 class="fc-detail-title">${raceTitle(r)}</h3>
      <span class="fc-rating">${ratingLabel(r)}</span>
      <div class="fc-detail-cands">${candRow(r, "dem")}${candRow(r, "rep")}</div>
      ${probBar(r)}
      <dl class="fc-facts">
        <dt>Seat</dt><dd>${seat}</dd>
        <dt>Expected Vote</dt><dd>${dp.short} ${share(r.dem_share_median)}, Rep ${share(1 - r.dem_share_median)} of the two-party vote</dd>
        <dt>Likely Range</dt><dd>${dp.short} between ${share(r.dem_share_lo80)} and ${share(r.dem_share_hi80)} in 80% of simulations</dd>
        <dt>Polls</dt><dd>${r.n_polls > 0 ? `${dp.short} ${share(r.poll_avg)} on average, from ${r.n_polls} poll${r.n_polls === 1 ? "" : "s"}` : "No polls yet, so this race rests on the fundamentals alone"}</dd>
        ${r.n_polls > 0 ? `<dt>Without Polls</dt><dd>${candName(r, "dem")} would have a ${pct(r.fundamentals_p_dem_win)} chance</dd>` : ""}
      </dl></div>`)
  }
  return el
}
Code
{
  raceMap.mark(current.race_id)
  keyCards.mark(current.race_id)
  detailPanel.render(current)
}

Balance of Power

Code
{
  const up = [...officeRaces].sort((a, b) => b.p_dem_win - a.p_dem_win)
  const total = office === "senate" ? 100 : 50
  const notUpD = office === "senate" ? 47 - up.filter(r => ["D", "I"].includes(r.incumbent_party)).length : 6
  const notUpR = total - notUpD - up.length
  const cells = [
    ...d3.range(notUpD).map(() => ({p: 1, label: "Democratic, not up this year"})),
    ...up.map(r => ({p: r.p_dem_win, race: r, label: describe(r)})),
    ...d3.range(notUpR).map(() => ({p: 0, label: "Republican, not up this year"}))
  ]
  const favD = notUpD + up.filter(r => r.p_dem_win >= 0.5).length
  const el = html`<div class="fc-strip-wrap">
    <p class="fc-takeaway">Every ${office === "senate" ? "Senate seat" : "governorship"}, safest Democratic on the left to safest Republican on the right; the solid ends are not up this year. If every race went to its favourite, Democrats would hold ${favD} and Republicans ${total - favD}.</p>
    <div class="fc-strip-labels"><span style="color:${textColour(DEM)}">Democratic</span><strong>${office === "senate" ? "51 for Control" : "26 for a Majority"}</strong><span style="color:${textColour(REP)}">Republican</span></div>
    <div class="fc-strip">${cells.map(d => `<span class="${d.race ? "is-race" : ""}" data-id="${d.race?.race_id ?? ""}" style="background:${probColour(d.p)}" title="${esc(d.label)}"></span>`).join("")}<i></i></div>
    <div class="fc-strip-labels fc-strip-foot"><span>${notUpD} Not Up</span><span>${up.length} on the Ballot</span><span>${notUpR} Not Up</span></div>
  </div>`
  for (const s of el.querySelectorAll(".is-race")) s.addEventListener("click", () => pickRace(s.dataset.id))
  return el
}

Range of Outcomes

Code
function seatChart({dist, lo, hi, majority, majorityLabel, step, xLabel, colourOf, unit}) {
  const rows = dist.filter(d => d.seats >= lo && d.seats <= hi)
  const med = rows.filter(d => d.seats === median(dist))
  const top = d3.max(rows, d => d.p) * 1.3
  return Plot.plot({
    width: pw, height: 250, marginLeft: 44, marginTop: 26, className: "fc-plot",
    x: {label: xLabel, domain: [lo - 0.5, hi + 0.5], ticks: d3.range(Math.ceil(lo / step) * step, hi + 1, step), tickFormat: "d"},
    y: {label: "Chance (%)", grid: true, percent: true, domain: [0, top * 100]},
    marks: [
      Plot.rectY(rows, {x1: d => d.seats - 0.5, x2: d => d.seats + 0.5, y: "p", fill: colourOf, inset: rows.length > 40 ? 0.3 : 1,
        tip: true, title: d => `${d.seats} ${unit}: ${(d.p * 100).toFixed(1)}%`}),
      Plot.ruleX([majority], {y1: 0, y2: top, stroke: "currentColor", strokeWidth: 1.2, strokeDasharray: "4,3"}),
      Plot.text([majorityLabel], {x: majority, frameAnchor: "top", dy: -14, dx: 5, textAnchor: "start", fontSize: 11.5, fontWeight: 600, className: "fc-halo"}),
      Plot.text(med, {x: "seats", y: "p", text: d => `Median ${d.seats}`, dy: -9, fontSize: 11.5, className: "fc-halo"}),
      Plot.ruleY([0])
    ]
  })
}
seatKey = (items) => html`<div class="fc-legend fc-seat-key">${items.map(([c, t]) => `<span class="fc-key"><span style="background:${c}"></span>${t}</span>`).join("")}</div>`
Code
{
  const dist = office === "senate" ? senateDist : govDist
  const unit = office === "senate" ? "Democratic-caucus Senate seats" : "Democratic governors"
  const takeaway = html`<p class="fc-takeaway">The median simulation gives ${median(dist)} ${unit}. In 80% of simulations the number lands between ${quantile(dist, 0.1)} and ${quantile(dist, 0.9)}.</p>`
  const chart = office === "senate"
    ? seatChart({dist, lo: 42, hi: 58, majority: 50.5, majorityLabel: "51 for Control", step: 2, xLabel: "Democratic-Caucus Senate Seats", unit: "seats",
        colourOf: d => d.seats >= 51 ? DEM : REP})
    : seatChart({dist, lo: 16, hi: 36, majority: 25.5, majorityLabel: "26 for a Majority", step: 2, xLabel: "Democratic Governors", unit: "Democratic governors",
        colourOf: d => d.seats >= 26 ? DEM : d.seats === 25 ? NO_RACE : REP})
  const key = office === "senate"
    ? seatKey([[DEM, "Democratic Control"], [REP, "Republican Control (50 With the VP)"]])
    : seatKey([[DEM, "Democratic Majority"], [NO_RACE, "25–25 Split"], [REP, "Republican Majority"]])
  return html`<div>${takeaway}<div class="fc-chartbox">${chart}${key}</div></div>`
}

All Races

Code
dataTable({
  items: officeRaces.map(r => ({...r, id: r.race_id})),
  caption: `All ${officeRaces.length} ${officeWord} races`,
  noun: ["race", "races"], placeholder: "Search a state or candidate",
  searchText: r => `${NAME[r.state]} ${r.state} ${r.dem_candidate} ${r.rep_candidate} ${ratingLabel(r)}`,
  sortKey: "race", onPick: pickRace,
  columns: [
    {key: "race", label: "Race", value: r => NAME[r.state] + (isSpecial(r) ? " 2" : " 1"),
      render: r => `<button type="button" class="fc-row-link">${NAME[r.state]}${isSpecial(r) ? " (Special)" : ""}</button><span class="fc-sub fc-narrow">${candName(r, "dem")} v ${candName(r, "rep")}</span>`},
    {key: "dem", label: "Democrat", cls: "fc-wide", value: r => r.dem_candidate,
      render: r => `${r.dem_candidate}${isInd(r) ? ` <span class="fc-dim">(Ind)</span>` : ""}`},
    {key: "rep", label: "Republican", cls: "fc-wide", value: r => r.rep_candidate, render: r => candName(r, "rep")},
    {key: "fav", label: "Favourite", value: r => favourite(r).p,
      render: r => { const f = favourite(r), party = r.p_dem_win >= 0.5 ? sideParty(r, "dem") : "R"
        return `${chip(party, `${PARTY[party].short} ${pct(f.p)}`)}<span class="fc-sub fc-narrow">${ratingLabel(r)}</span>` }},
    {key: "rating", label: "Rating", cls: "fc-wide fc-nowrap", value: r => favourite(r).p, render: r => ratingLabel(r)},
    {key: "polls", label: "Poll Average", cls: "fc-wide fc-num", value: r => r.n_polls > 0 ? r.poll_avg : -1,
      render: r => r.n_polls > 0 ? `${share(r.poll_avg)} <span class="fc-dim">${PARTY[sideParty(r, "dem")].short}</span>` : `<span class="fc-dim">No Polls</span>`}
  ]
})
Code
houseRows = [...districts].map(r => {
  const names = (s) => (s ?? "").split(";").map(x => x.trim()).filter(Boolean).join(", ")
  const cands = []
  if (r.dem_candidates) cands.push({party: "D", name: names(r.dem_candidates), p: r.p_dem_win})
  if (r.rep_candidates) cands.push({party: "R", name: names(r.rep_candidates), p: r.p_rep_win})
  if (!r.certain_hold_party && (r.stand_in || r.p_ind_win > 0.005)) cands.push({party: "I", name: r.stand_in || "Other Candidate", p: r.p_ind_win})
  const fav = r.certain_hold_party ? {party: r.certain_hold_party, p: 1} : d3.greatest(cands, c => c.p) ?? {party: "R", p: r.p_rep_win}
  const k = rating(fav.p)
  return {...r, id: r.cd, cands, fav,
    rating: r.certain_hold_party ? `Certain ${PARTY[fav.party].short}` : k === "Toss-Up" ? k : `${k} ${PARTY[fav.party].short}`,
    p: r.certain_hold_party === "D" ? 1 : r.certain_hold_party === "R" ? 0 : r.p_dem_win}
}).sort((a, b) => b.p - a.p).map((r, i) => ({...r, i}))
mutable districtPick = null
currentDistrict = houseRows.find(r => r.cd === districtPick) ?? null
closeDistricts = houseRows.filter(r => !r.certain_hold_party).sort((a, b) => a.fav.p - b.fav.p).slice(0, 9)
pickDistrict = (cd) => { mutable districtPick = cd; reveal(".fc-hemi") }
districtBar = (r) => segBar(["D", "I", "R"].map(party => ({p: r.cands.find(c => c.party === party)?.p ?? (r.certain_hold_party === party ? 1 : 0), colour: PARTY[party].colour})))
cdOrder = (cd) => { const [s, n] = cd.split("-"); return `${s}-${n === "AL" ? "00" : n.padStart(2, "0")}` }

Closest Districts

Code
{
  const favD = houseRows.filter(r => r.fav.party === "D").length, favR = houseRows.filter(r => r.fav.party === "R").length
  return html`<p class="fc-takeaway fc-lead">Democrats are favoured in ${favD} of the 435 districts and Republicans in ${favR}. The median simulation gives Democrats ${median(houseDist)} seats.</p>`
}
Code
houseCards = cardGrid(closeDistricts.map(r => ({
  id: r.cd, title: r.cd, rating: r.rating,
  lines: r.cands.map(c => candLine(c.party, c.name, c.p)), bar: districtBar(r),
  foot: r.incumbents_running ? `Incumbent Running: ${r.incumbents_running.replaceAll(";", ",")}` : "No Incumbent Running"
})), pickDistrict)

Every District

Code
hemicycle = {
  const d = houseRows, n = d.length
  const W = Math.min(pw, 720), R = W / 2 - 8, rows = 12, r0 = 0.36, top = 30
  const radii = d3.range(rows).map(i => R * (r0 + (1 - r0) * i / (rows - 1)))
  const counts = radii.map(r => Math.floor(n * r / d3.sum(radii)))
  for (let i = rows - 1, left = n - d3.sum(counts); left > 0; i = (i - 1 + rows) % rows, left--) counts[i]++
  const cx = W / 2, cy = top + R, dot = (R * (1 - r0) / (rows - 1)) * 0.42
  const seats = radii.flatMap((r, i) => d3.range(counts[i]).map(j => {
    const a = Math.PI * (1 - (counts[i] === 1 ? 0.5 : j / (counts[i] - 1)))
    return {a, r, x: cx + r * Math.cos(a), y: cy - r * Math.sin(a)}
  })).sort((p, q) => d3.descending(p.a, q.a) || d3.ascending(p.r, q.r))
  d.forEach((r, i) => Object.assign(r, {x: seats[i].x, y: seats[i].y}))
  const H = cy + 22

  const svg = d3.create("svg").attr("class", "fc-hemi-svg").attr("viewBox", [0, 0, W, H]).attr("width", W).attr("height", H)
    .attr("tabindex", 0).attr("role", "group")
    .attr("aria-label", "All 435 House districts in a half circle, from the safest Democratic seat on the left to the safest Republican seat on the right. Use the arrow keys to move between districts and Escape to close the details.")
  svg.append("line").attr("class", "fc-hemi-mid").attr("x1", cx).attr("x2", cx).attr("y1", 14).attr("y2", cy - R * r0 + 6)
  svg.append("text").attr("class", "fc-hemi-label").attr("x", cx).attr("y", 10).text("218 for a Majority")
  svg.append("g").selectAll("circle").data(d).join("circle")
    .attr("cx", r => r.x).attr("cy", r => r.y).attr("r", dot).attr("fill", r => probColour(r.p))
  svg.append("circle").attr("class", "fc-hemi-218").attr("cx", d[217].x).attr("cy", d[217].y).attr("r", dot + 2.2)
  const ring = svg.append("circle").attr("class", "fc-hemi-sel").attr("r", dot + 2.6).attr("opacity", 0)
  svg.append("text").attr("class", "fc-hemi-end").attr("x", cx - R).attr("y", cy + 18).attr("text-anchor", "start").style("fill", textColour(DEM)).text("Safest Dem")
  svg.append("text").attr("class", "fc-hemi-end").attr("x", cx + R).attr("y", cy + 18).attr("text-anchor", "end").style("fill", textColour(REP)).text("Safest Rep")

  const pop = html`<div class="fc-pop" hidden></div>`
  const live = html`<div class="visually-hidden" aria-live="polite"></div>`
  const wrap = html`<div class="fc-hemi">${svg.node()}${pop}${live}</div>`
  let at = 217, pinned = false
  const place = (r) => {
    const box = svg.node().getBoundingClientRect(), k = box.width / W
    const x = r.x * k, y = r.y * k, pwid = pop.offsetWidth, ph = pop.offsetHeight, ww = wrap.clientWidth
    const left = Math.max(0, Math.min(ww - pwid, x - pwid / 2))
    const above = y - ph - dot * k - 10
    pop.style.left = `${left}px`
    pop.style.top = `${above >= 0 ? above : y + dot * k + 10}px`
  }
  const show = (i, pin) => {
    at = Math.max(0, Math.min(n - 1, i)); const r = d[at]
    pinned = pin ?? pinned
    ring.attr("cx", r.x).attr("cy", r.y).attr("opacity", 1)
    pop.replaceChildren(html`<div class="fc-pop-head"><strong>${r.cd}</strong><span class="fc-rating">${r.rating}</span>
        <button type="button" class="fc-pop-close" aria-label="Close">×</button></div>
      <div class="fc-pop-kicker">${at === 217 ? "The 218th Seat" : `Seat ${at + 1} of 435`}</div>
      ${r.certain_hold_party
        ? `<p class="fc-dim">Only ${r.certain_hold_party === "D" ? "Democrats" : "Republicans"} are on the ballot (${r.cands.map(c => c.name).join(", ")}), so this is a certain hold.</p>`
        : html`<div class="fc-pop-cands">${r.cands.map(c => candLine(c.party, c.name, c.p))}</div>`}
      ${r.certain_hold_party ? "" : districtBar(r)}
      ${r.incumbents_running ? `<p class="fc-dim">Incumbent running: ${r.incumbents_running.replaceAll(";", ",")}</p>` : ""}`)
    pop.querySelector(".fc-pop-close").addEventListener("click", () => { hide(true); svg.node().focus() })
    pop.hidden = false
    place(r)
    live.textContent = `${r.cd}, ${r.rating}. ${r.cands.map(c => `${c.name} ${pct(c.p)}`).join(", ")}`
  }
  const hide = (force) => { if (pinned && !force) return; pinned = false; pop.hidden = true; ring.attr("opacity", 0) }
  const nearest = (e) => {
    const [px, py] = d3.pointer(e, svg.node())
    const best = d3.least(d, r => (r.x - px) ** 2 + (r.y - py) ** 2)
    return (best.x - px) ** 2 + (best.y - py) ** 2 < (dot * 3) ** 2 ? best : null
  }
  svg.on("pointermove", e => { if (pinned || e.pointerType === "touch") return; const r = nearest(e); r ? show(r.i, false) : hide() })
  svg.on("pointerleave", () => hide())
  svg.on("click", e => { const r = nearest(e); if (r) { mutable districtPick = r.cd; show(r.i, true) } else hide(true) })
  svg.on("keydown", e => {
    const step = {ArrowRight: 1, ArrowLeft: -1, ArrowUp: 12, ArrowDown: -12, Home: -n, End: n}[e.key]
    if (step) { e.preventDefault(); show(at + step, true) }
    else if (e.key === "Escape") hide(true)
    else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); show(at, true) }
  })
  svg.on("focus", () => { if (pop.hidden) show(at, true) })
  const onKey = e => { if (e.key === "Escape" && !pop.hidden) hide(true) }
  addEventListener("keydown", onKey)
  invalidation.then(() => removeEventListener("keydown", onKey))
  const out = html`<div>
    <p class="fc-takeaway">Each dot is one district, ordered from the safest Democratic seat on the left to the safest Republican seat on the right. ${d.filter(r => !r.certain_hold_party && r.fav.p < 0.6).length} are closer than 60–40. The ringed dot at the top is the 218th seat, ${d[217].cd}, where the majority is decided. Hover over, tap or select a dot for its candidates.</p>
    ${wrap}</div>`
  out.show = (cd) => { const r = d.find(x => x.cd === cd); if (r) show(r.i, true) }
  return out
}
Code
{
  houseCards.mark(currentDistrict?.cd)
  if (currentDistrict) hemicycle.show(currentDistrict.cd)
}

Range of Outcomes

Code
{
  const takeaway = html`<p class="fc-takeaway">Democrats win ${median(houseDist)} seats in the median simulation, and between ${quantile(houseDist, 0.1)} and ${quantile(houseDist, 0.9)} in 80% of simulations. A majority is 218.</p>`
  const chart = seatChart({dist: houseDist, lo: 200, hi: 270, majority: 217.5, majorityLabel: "218 for a Majority", step: 10,
    xLabel: "Democratic House Seats", unit: "Democratic seats", colourOf: d => d.seats >= 218 ? DEM : REP})
  return html`<div>${takeaway}<div class="fc-chartbox">${chart}${seatKey([[DEM, "Democratic Majority"], [REP, "Republican Majority"]])}</div></div>`
}

All Districts

Code
dataTable({
  items: houseRows,
  caption: "All 435 House districts",
  noun: ["district", "districts"], placeholder: "Search a district, state or candidate",
  searchText: r => `${r.cd} ${NAME[r.state] ?? ""} ${r.cands.map(c => c.name).join(" ")} ${r.rating}`,
  sortKey: "cd", onPick: pickDistrict,
  columns: [
    {key: "cd", label: "District", value: r => cdOrder(r.cd),
      render: r => `<button type="button" class="fc-row-link">${r.cd}</button><span class="fc-sub fc-narrow">${r.cands.map(c => c.name).join(" v ")}</span>`},
    {key: "dem", label: "Democrat", cls: "fc-wide", value: r => r.dem_candidates ?? "", render: r => r.cands.find(c => c.party === "D")?.name ?? `<span class="fc-dim">None</span>`},
    {key: "rep", label: "Republican or Other", cls: "fc-wide", value: r => r.rep_candidates ?? r.stand_in ?? "",
      render: r => r.cands.filter(c => c.party !== "D").map(c => c.party === "I" ? `${c.name} <span class="fc-dim">(Other)</span>` : c.name).join(", ") || `<span class="fc-dim">None</span>`},
    {key: "fav", label: "Favourite", value: r => r.fav.p,
      render: r => `${chip(r.fav.party, r.certain_hold_party ? `${PARTY[r.fav.party].short}, Certain` : `${PARTY[r.fav.party].short} ${pct(r.fav.p)}`)}<span class="fc-sub fc-narrow">${r.rating}</span>`},
    {key: "rating", label: "Rating", cls: "fc-wide fc-nowrap", value: r => r.fav.p, render: r => r.rating},
    {key: "share", label: "Dem Share", cls: "fc-wide fc-num", value: r => r.dem_share_median ?? -1,
      render: r => r.dem_share_median != null ? share(r.dem_share_median) : `<span class="fc-dim">n/a</span>`}
  ]
})
Code
stateTurnout = turnoutStates.map(s => ({...s, id: s.state, change: s.turnout_2026_median - s.turnout_2022})).sort((a, b) => b.change - a.change)

Turnout by County

Code
{
  return html`<p class="fc-takeaway fc-lead">The likely national range is ${(national.turnout_2026_lo80 * 100).toFixed(0)} to ${(national.turnout_2026_hi80 * 100).toFixed(0)}% of adult citizens.</p>`
}
Code
{
  const unit = id => id.startsWith("02") ? "02000" : id.startsWith("09") ? "09000" : ["29047", "29165"].includes(id) ? "29095" : id
  const byUnit = new Map(turnout.map(t => [String(t.unit_fips).padStart(5, "0"), t]))
  const data = counties.map(f => ({...f, t: byUnit.get(unit(f.id))}))
  const up = turnout.filter(t => t.turnout_2026_median > t.turnout_2022).length
  const top3 = stateTurnout.slice(0, 3).map(s => `${NAME[s.state]} (${pts(s.change)})`)
  return html`<div><p class="fc-takeaway">Green means turnout is expected to rise from 2022 and purple means it is expected to fall. It rises in ${up.toLocaleString("en-GB")} of ${turnout.length.toLocaleString("en-GB")} counties. By state, the biggest rises, in points, are ${top3.slice(0, 2).join(", ")} and ${top3[2]}. Hover over or tap a county for its numbers.</p>
  ${Plot.plot({
    // Map and legend fit in about 80% of the window height, so the whole map is visible while scrolling.
    projection: "albers-usa", width: Math.round(Math.min(pw, (innerHeight * 0.8 - 64) / 0.6)), height: Math.round(Math.min(pw, (innerHeight * 0.8 - 64) / 0.6) * 0.6), className: "fc-plot",
    color: {type: "linear", domain: [-10, 10], clamp: true, interpolate: changeColour, legend: true,
      label: "Change in Turnout From 2022 (Points)", tickFormat: d => d > 0 ? `+${d}` : d},
    marks: [
      Plot.geo(data, {fill: d => d.t ? (d.t.turnout_2026_median - d.t.turnout_2022) * 100 : null, stroke: null}),
      Plot.geo(stateMesh, {stroke: "white", strokeWidth: 0.7}),
      Plot.tip(data.filter(d => d.t), Plot.pointer(Plot.geoCentroid({title: d =>
        `${d.t.county}, ${d.t.state}\n2022: ${(d.t.turnout_2022 * 100).toFixed(1)}%\n2026 forecast: ${(d.t.turnout_2026_median * 100).toFixed(1)}% (likely ${(d.t.turnout_2026_lo80_county * 100).toFixed(0)} to ${(d.t.turnout_2026_hi80_county * 100).toFixed(0)}%)`})))
    ]
  })}</div>`
}

Turnout by State

Code
{
  const rows = stateTurnout
  const up = rows.filter(r => r.change > 0).length, bottom = rows.at(-1)
  const changeChip = (x) => `<span class="fc-chip fc-chip-soft" style="--chip:${x >= 0 ? GREEN : PURPLE}">${pts(x)} Pts</span>`
  return html`<div><p class="fc-takeaway">Turnout rises in ${up} of ${rows.length} states (counting DC) and falls in ${rows.length - up}. The biggest fall is in ${NAME[bottom.state]} (${pts(bottom.change)} points).</p>
  ${dataTable({
    items: rows, caption: "Turnout by state, 2022 and 2026 forecast", noun: ["state", "states"], placeholder: "Search a state",
    searchText: r => `${NAME[r.state]} ${r.state}`, sortKey: "change", sortDir: -1,
    columns: [
      {key: "state", label: "State", value: r => NAME[r.state], render: r => NAME[r.state]},
      {key: "t22", label: "2022", cls: "fc-num fc-wide", value: r => r.turnout_2022, render: r => share(r.turnout_2022)},
      {key: "t26", label: "2026 Forecast", cls: "fc-num", value: r => r.turnout_2026_median, render: r => share(r.turnout_2026_median)},
      {key: "change", label: "Change", cls: "fc-num", value: r => r.change, render: r => changeChip(r.change)},
      {key: "range", label: "Likely Range", cls: "fc-num fc-wide", value: r => r.turnout_2026_lo80_state,
        render: r => `${(r.turnout_2026_lo80_state * 100).toFixed(0)} to ${(r.turnout_2026_hi80_state * 100).toFixed(0)}%`}
    ]
  })}</div>`
}
Code
results = FileAttachment("data/results.json").json()
isSample = results.sample === true || /\bsample\b/i.test(results.note ?? "")
resById = new Map((results.races ?? []).map(r => [r.id, r]))
WIN = ({D: "Democrat", R: "Republican", I: "Independent"})
WINS = ({D: "Democrats", R: "Republicans", I: "Independents"})
OFFICE = ({senate: "Senate", house: "House", governor: "Governors"})
INK = "var(--ds-ink)"
ord = (n) => { const s = ["th", "st", "nd", "rd"], v = n % 100; return n + (s[(v - 20) % 10] || s[v] || s[0]) }
num = (x, d = 3) => x == null || !isFinite(x) ? "—" : x.toFixed(d)
// one row per race in the forecast, with its result
resRaces = [
  ...races.map(r => ({id: r.race_id, office: r.office, state: r.state, title: raceTitle(r),
    short: `${r.state} ${r.office === "senate" ? "Sen" : "Gov"}${isSpecial(r) ? " Sp." : ""}`,
    pD: r.p_dem_win, demParty: sideParty(r, "dem"), favParty: r.p_dem_win >= 0.5 ? sideParty(r, "dem") : "R", favP: Math.max(r.p_dem_win, 1 - r.p_dem_win),
    median: r.dem_share_median, lo: r.dem_share_lo80, hi: r.dem_share_hi80, race: r})),
  ...houseRows.map(h => ({id: h.cd, office: "house", state: h.state, title: h.cd, short: h.cd,
    pD: h.p, demParty: "D", favParty: h.fav.party, favP: h.fav.p, median: h.dem_share_median, lo: h.dem_share_lo80, hi: h.dem_share_hi80, district: h}))
].map(x => {
  const res = resById.get(x.id) ?? null
  const called = !!(res?.called && res.winner_party)
  const winner = called ? res.winner_party : null
  const pOf = (party) => x.district
    ? (x.district.cands.find(c => c.party === party)?.p ?? (x.district.certain_hold_party === party ? 1 : 0))
    : party === "R" ? 1 - x.pD : party === x.demParty ? x.pD : 0
  return {...x, res, called, winner, status: !called ? "count" : winner === x.favParty ? "won" : "upset",
    pWinner: called ? pOf(winner) : null, yD: called ? +(winner === x.demParty) : null,
    actual: res?.dem_share_2p ?? null, counted: res?.pct_counted ?? null,
    // vote figures use a called race's share once most of it is in (85% counted, or called when the count share is unknown)
    voteReady: called && res?.dem_share_2p != null && (res.pct_counted == null || res.pct_counted >= 0.85)
      && (!x.district || !!(x.district.dem_candidates && x.district.rep_candidates))}  // Democrat against Republican only
})
resOf = (office) => resRaces.filter(r => r.office === office)
// Races where the main challenger was an independent (Nebraska, Idaho, South Dakota) are scored on their own,
// as the scoring script does; the headline numbers, squares and accuracy figures leave them out.
isIndRace = (r) => r.office !== "house" && r.demParty === "I"
scored = resRaces.filter(r => !isIndRace(r))
indRaces = resRaces.filter(isIndRace)
// the scoring script's fuller measures, when filed alongside (null otherwise)
scoreExtra = FileAttachment("data/score_provisional.json").json().catch(() => null)
brierOf = (rows) => { const c = rows.filter(r => r.called); return c.length ? d3.mean(c, r => (r.pD - r.yD) ** 2) : null }
// the scoring script's numbers where it has filed them; otherwise the same quantities from the race rows
scoreFor = (k) => {
  const s = results.score?.[k]
  if (s && s.called != null) return s
  const rows = (k === "all" ? scored : resOf(k).filter(r => !isIndRace(r))).filter(r => r.called)
  return {called: rows.length, favourites_won: rows.filter(r => r.status === "won").length, upsets: rows.filter(r => r.status === "upset").length,
    expected_upsets: d3.sum(rows, r => 1 - r.favP), brier: brierOf(rows), log_loss: null}
}
asOf = results.as_of ? new Date(results.as_of) : null
asOfText = asOf ? `${new Intl.DateTimeFormat("en-US", {timeZone: "America/New_York", hour: "numeric", minute: "2-digit"}).format(asOf)} ET on ${new Intl.DateTimeFormat("en-GB", {timeZone: "America/New_York", day: "numeric", month: "long", year: "numeric"}).format(asOf)}` : "a time not yet recorded"
asOfShort = asOf ? `${new Intl.DateTimeFormat("en-GB", {timeZone: "America/New_York", day: "numeric", month: "short"}).format(asOf)}, ${new Intl.DateTimeFormat("en-US", {timeZone: "America/New_York", hour: "numeric", minute: "2-digit"}).format(asOf)} ET` : "time not recorded"
// percentile of a result within a seat distribution, counting half of the result's own bar
seatPct = (dist, x) => d3.sum(dist.filter(d => d.seats < x), d => d.p) + 0.5 * d3.sum(dist.filter(d => d.seats === x), d => d.p)
chamberDist = ({senate: senateDist, house: houseDist, governor: govDist})
chamberP = ({senate: pSenateD, house: pHouseD, governor: pGovD})
chamberRes = (k) => results.chambers?.[k] ?? {}
// the scoring script's percentile when it has filed one; otherwise computed, but only once the chamber is complete,
// since a partial count is not a result
resultPct = (k) => { const c = chamberRes(k), x = c.dem_seats; if (x == null) return null
  const filed = results.score?.seat_percentiles?.[k]; return filed != null ? filed : c.complete ? seatPct(chamberDist[k], x) : null }
// result stamp used on cards, the table and the race panel
stampFor = (x) => x.status === "count" ? `<span class="fc-stampr is-count">Still Counting</span>`
  : `<span class="fc-stampr${x.status === "upset" ? " is-upset" : ""}">${WIN[x.winner]} Won · ${x.status === "upset" ? "Upset" : "Favourite Won"}</span>`
// a segmented switch of real buttons (aria-pressed); returns an element with .value, like an Observable input
segButtons = (opts, value, label) => {
  const el = html`<div class="fc-segb" role="group" aria-label="${label}">${opts.map(([k, t]) => `<button type="button" data-k="${k}" aria-pressed="${k === value}">${t}</button>`).join("")}</div>`
  el.value = value
  el.addEventListener("click", e => {
    const b = e.target.closest("button[data-k]")
    if (!b || b.dataset.k === el.value) return
    el.value = b.dataset.k
    for (const x of el.querySelectorAll("button")) x.setAttribute("aria-pressed", x === b)
    el.dispatchEvent(new Event("input", {bubbles: true}))
  })
  return el
}
placeholder = (title, text) => `<div class="fc-ph"><strong>${title}</strong><span>${text}</span></div>`
// the tile map's grid: column and row for each state
GRID = ({AK: [0, 0], ME: [11, 0], WI: [6, 1], VT: [10, 1], NH: [11, 1], WA: [1, 2], ID: [2, 2], MT: [3, 2], ND: [4, 2], MN: [5, 2], IL: [6, 2], MI: [7, 2], NY: [9, 2], MA: [10, 2],
  OR: [1, 3], NV: [2, 3], WY: [3, 3], SD: [4, 3], IA: [5, 3], IN: [6, 3], OH: [7, 3], PA: [8, 3], NJ: [9, 3], CT: [10, 3], RI: [11, 3],
  CA: [1, 4], UT: [2, 4], CO: [3, 4], NE: [4, 4], MO: [5, 4], KY: [6, 4], WV: [7, 4], VA: [8, 4], MD: [9, 4], DE: [10, 4],
  AZ: [2, 5], NM: [3, 5], KS: [4, 5], AR: [5, 5], TN: [6, 5], NC: [7, 5], SC: [8, 5], DC: [9, 5], OK: [4, 6], LA: [5, 6], MS: [6, 6], AL: [7, 6], GA: [8, 6],
  HI: [0, 7], TX: [4, 7], FL: [9, 7]})
// cells: Map state -> {fill, status ("upset" | "count" | ""), big, small, label, id}; states without a cell are drawn empty
tileMap = ({cells, label, onPick}) => {
  const el = html`<div class="fc-tiles" role="group" aria-label="${label}">${Object.entries(GRID).map(([s, [x, y]]) => {
    const c = cells.get(s), pos = `grid-column:${x + 1};grid-row:${y + 1}`
    if (!c) return `<span class="fc-tile is-none" style="${pos}" aria-hidden="true"><b>${s}</b></span>`
    const tag = onPick ? "button" : "span"
    const style = `${pos};${c.status === "count" ? "" : `background:${c.fill};color:${textOn(c.fill)}`}`
    return `<${tag} ${onPick ? `type="button" data-id="${c.id}" aria-pressed="false"` : `role="img"`} class="fc-tile${c.status ? ` is-${c.status}` : ""}" style="${style}" aria-label="${esc(c.label)}" title="${esc(c.label)}"><b>${s}</b><small>${c.small}</small></${tag}>`
  }).join("")}</div>`
  if (onPick) el.addEventListener("click", e => { const b = e.target.closest("button[data-id]"); if (b) onPick(b.dataset.id) })
  el.mark = (id) => { for (const b of el.querySelectorAll("button[data-id]")) b.setAttribute("aria-pressed", b.dataset.id === id) }
  return el
}
// width the results view actually has
rw = Generators.observe(notify => {
  const el = document.getElementById("fc-view-results")
  let last = 0
  const measure = () => { const w = Math.floor(el?.getBoundingClientRect().width || 0) || width; if (Math.abs(w - last) > 4) { last = w; notify(Math.max(280, w)) } }
  measure()
  const ro = new ResizeObserver(measure)
  if (el) ro.observe(el)
  return () => ro.disconnect()
})
Code
// The provisional note, four numbers and every race as a small square.
{
  const all = scoreFor("all"), total = scored.length
  const byOffice = ["senate", "governor", "house"].map(k => [k, resOf(k).filter(r => !r.called && !isIndRace(r)).length])
  const counting = d3.sum(byOffice, d => d[1])
  const nums = [
    ["Favourites That Won", all.called ? `${all.favourites_won} of ${all.called}` : "—", all.called ? `${(all.favourites_won / all.called * 100).toFixed(1)}% of races called` : "No races called yet"],
    ["Upsets", all.called ? `${all.upsets}` : "—", all.expected_upsets != null && all.called ? `About ${Math.round(all.expected_upsets)} expected` : "The favourite lost"],
    ["Accuracy Score", num(all.brier), "0 is perfect, 0.25 a coin toss"],
    ["Still Counting", `${counting}`, byOffice.map(([k, n]) => `${n} ${k === "senate" ? "Senate" : k === "governor" ? "Governor" : "House"}`).join(" · ")]
  ]
  const order = ["senate", "governor", "house"]
  const cells = [...scored].sort((a, b) => d3.ascending(order.indexOf(a.office), order.indexOf(b.office)) || d3.descending(a.favP, b.favP))
  const nUp = cells.filter(r => r.status === "upset").length, nWon = cells.filter(r => r.status === "won").length
  const status = results.status === "certified" ? "Certified" : "Provisional"
  // the status sits on the same line as the Forecast and Results switch, small and to the right
  const bar = document.querySelector(".fc-lede .fc-stamp.fc-res")
  if (bar) {
    bar.parentNode.querySelector(".fc-vstat")?.remove()
    const note = status === "Provisional" ? "Election-night calls and counts; certified results will replace them as states certify." : "Certified results."
    bar.insertAdjacentHTML("afterend", `<span class="fc-vstat" title="${esc(note)}"><i aria-hidden="true"></i>${status}: ${all.called} of ${total} called, ${esc(asOfShort)}</span>`)
  }
  const sec = html`<section class="fc-rsum" aria-labelledby="fc-rsum-h">
    ${isSample ? `<p class="fc-prov fc-prov-sample"><span class="fc-prov-tag is-sample">Sample Data</span><span>This page is reading a sample results file built from the election-night notes. Only the ${nUp + nWon} races those notes name carry a result in the squares below; the four numbers come from the same snapshot.</span></p>` : ""}
    <h2 id="fc-rsum-h" class="fc-rh">The Results So Far</h2>
    <div class="fc-rnums">${nums.map(([a, b, c]) => `<div><span class="fc-card-label">${a}</span><span class="fc-rnum">${b}</span><span class="fc-rnum-sub">${c}</span></div>`).join("")}</div>
    <div class="fc-sq" role="img" aria-label="Every race as a square: ${nWon} called for the favourite, ${nUp} upsets and ${total - nWon - nUp} still counting in the results file.">${cells.map(r =>
      `<span class="is-${r.status}" title="${esc(`${r.title}: ${r.status === "count" ? "still counting" : `${WIN[r.winner]} won${r.status === "upset" ? ", an upset" : ""}`}`)}"></span>`).join("")}</div>
    <div class="fc-sq-key"><span class="fc-k"><span class="is-won"></span>Favourite Won</span><span class="fc-k"><span class="is-upset"></span>Upset</span><span class="fc-k"><span class="is-count"></span>Still Counting</span>
      <span class="fc-sq-right"><span class="fc-dim">${total} races: Senate, Governors, then House, most certain first</span>${indRaces.length ? `<details class="fc-info"><summary aria-label="About the races with an independent challenger"><span aria-hidden="true">i</span></summary><p>${indRaces.length === 1 ? "One Senate race" : `${["", "One", "Two", "Three", "Four", "Five"][indRaces.length] ?? indRaces.length} Senate races`} with an independent as the main challenger (${indRaces.map(r => NAME[r.state]).join(", ").replace(/, ([^,]*)$/, " and $1")}) ${indRaces.length === 1 ? "is" : "are"} counted separately, as in the scoring: ${(() => { const c = indRaces.filter(r => r.called); return c.length ? `the favourite won ${c.filter(r => r.status === "won").length} of ${c.length} called` : "none called yet" })()}.</p></details>` : ""}</span></div>
  </section>`
  const info = sec.querySelector(".fc-info")
  if (info) info.addEventListener("mouseleave", () => info.removeAttribute("open"))
  return sec
}
Code
// Five tabs in the Results view. #results opens the overview; #results-races and so on open a tab directly.
viewof rtab = {
  const tabs = [["overview", "Overview"], ["races", "Race Breakdown"], ["accuracy", "Accuracy"], ["whatif", "What Would Have Helped"], ["compare", "Against Other Forecasts"], ["turnout", "Turnout"]]
  const keys = tabs.map(t => t[0])
  const fromHash = () => { const h = location.hash.slice(1).toLowerCase(); if (!h.startsWith("results")) return null; const k = h.slice(8); return keys.includes(k) ? k : "overview" }
  const el = html`<div class="fc-rtabs" role="tablist" aria-label="Results sections">${tabs.map(([k, t]) =>
    `<button type="button" role="tab" id="fc-rtab-${k}" data-tab="${k}" aria-controls="fc-r-${k}">${t}</button>`).join("")}</div>`
  const buttons = [...el.querySelectorAll("[role=tab]")]
  const paint = () => buttons.forEach(b => { const on = b.dataset.tab === el.value; b.setAttribute("aria-selected", on); b.tabIndex = on ? 0 : -1 })
  el.setTab = (k, {focus = false, scroll = true} = {}) => {
    if (!keys.includes(k)) return
    const want = k === "overview" ? "#results" : `#results-${k}`
    if (location.hash !== want) history.replaceState(null, "", want)
    if (k !== el.value) {
      el.value = k; paint(); el.dispatchEvent(new Event("input", {bubbles: true}))
      // start the new tab from its top if the reader had scrolled past the tab bar
      const cell = el.closest(".fc-rtabcell"), head = document.querySelector(".sitehead")?.offsetHeight ?? 64
      if (scroll && cell) {
        const y = cell.getBoundingClientRect().top + window.scrollY - head
        if (window.scrollY > y + 1) setTimeout(() => window.scrollTo({top: y, behavior: "instant"}), 0)
      }
    }
    if (focus) buttons.find(b => b.dataset.tab === k)?.focus()
  }
  el.addEventListener("click", e => { const b = e.target.closest("[role=tab]"); if (b) el.setTab(b.dataset.tab) })
  el.addEventListener("keydown", e => {
    const i = buttons.indexOf(document.activeElement)
    if (i < 0) return
    const j = {ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: buttons.length - 1}[e.key]
    if (j === undefined) return
    e.preventDefault()
    el.setTab(buttons[(j + buttons.length) % buttons.length].dataset.tab, {focus: true})
  })
  const onHash = () => { const k = fromHash(); if (k) el.setTab(k, {scroll: false}) }
  addEventListener("hashchange", onHash)
  invalidation.then(() => removeEventListener("hashchange", onHash))
  el.value = fromHash() ?? "overview"
  paint()
  return el
}
Code
{
  for (const p of document.querySelectorAll(".fc-rpanel")) {
    const k = p.id.replace("fc-r-", "")
    p.classList.toggle("is-active", k === rtab)
    p.setAttribute("role", "tabpanel")
    p.setAttribute("aria-labelledby", `fc-rtab-${k}`)
  }
}

Who Controls What

Code
{
  const sen = chamberRes("senate"), house = chamberRes("house"), gov = chamberRes("governor")
  // one headline and two short sentences per chamber, built the same way so the three columns read alike
  const ctlLine = (c, noun) => c.control == null
    ? (c.dem_seats != null ? `Still counting: ${c.dem_seats} Democratic ${noun}` : "Still counting")
    : `Democrats: ${c.dem_seats} ${noun}${c.complete ? "" : " so far"}`
  const detail = (k, what, noun) => {
    const dist = chamberDist[k], p = resultPct(k), rg = scoreExtra?.seat_percentiles?.[k]?.percentile_range
    const first = `Forecast: a ${pct(chamberP[k])} chance of ${what}, with a median of ${median(dist)} ${noun}.`
    if (p != null) return `${first} The result is at its ${ord(Math.round(p * 100))} percentile.`
    if (rg && rg[1] - rg[0] < 0.5) return `${first} The result will land at its ${ord(Math.round(rg[0] * 100))} to ${ord(Math.round(rg[1] * 100))} percentile.`
    return `${first} Its 80% range was ${quantile(dist, 0.1)} to ${quantile(dist, 0.9)}.`
  }
  // Senate: 100 seats as dots
  const nD = sen.dem_seats ?? 0, nI = sen.ind_seats ?? 0, nR = sen.rep_seats ?? 0
  const sd = d3.range(100).map(i => i < nD ? "d" : i < nD + nI ? "i" : i >= 100 - nR ? "r" : "c")
  const senDots = `<div class="fc-dots100" role="img" aria-label="The Senate's 100 seats: ${nD} Democratic, ${nI ? `${nI} independent, ` : ""}${nR ? `${nR} Republican, ` : ""}${100 - nD - nI - nR} not yet assigned in the results file.">${sd.map(c => `<span class="is-${c}"></span>`).join("")}</div>`
  // House: one bar of 435 seats, Democrats from the left, Republicans from the right, 218 marked
  const hD = house.dem_seats ?? 0, hR = house.rep_seats ?? 0
  const houseBar = `<div class="fc-hbar" role="img" aria-label="House seats: ${house.dem_seats == null ? "still counting" : `${hD} Democratic, ${hR} Republican`}. 218 are needed for control."><span style="width:${hD / 435 * 100}%;background:${DEM}"></span><span class="is-c"></span><span style="width:${hR / 435 * 100}%;background:${REP}"></span><i style="left:${218 / 435 * 100}%"></i></div><span class="fc-dim fc-small">218 for control</span>`
  // Governors: the 36 races, by the forecast's order, coloured by the winner
  const g = [...resOf("governor")].sort((a, b) => b.pD - a.pD)
  const govSq = `<div class="fc-gsq" role="img" aria-label="The 36 governor races: ${g.filter(r => r.winner === "D").length} won by Democrats, ${g.filter(r => r.winner === "R").length} by Republicans, ${g.filter(r => !r.called).length} still counting.">${g.map(r =>
    `<span class="${r.called ? "" : "is-c"}" style="${r.called ? `background:${PARTY[r.winner].colour}` : ""}" title="${esc(`${r.title}: ${r.called ? `${WIN[r.winner]} won` : "still counting"}`)}"></span>`).join("")}</div>`
  const gCalled = g.filter(r => r.called).length
  const col = (label, pic, l1, l2) => `<div class="fc-ctl"><span class="fc-card-label fc-ink">${label}</span><div class="fc-ctl-pic">${pic}</div><span class="fc-ctl-1">${l1}</span><span class="fc-ctl-2">${l2}</span></div>`
  return html`<div>
    <p class="fc-takeaway fc-lead">The chance this forecast gave each outcome on 22 October, and what happened. Outlined shapes are still counting.</p>
    <div class="fc-ctl3">
      ${col("Senate", senDots, ctlLine(sen, "seats"), detail("senate", "control", "seats"))}
      ${col("House", houseBar, ctlLine(house, "seats"), detail("house", "control", "seats"))}
      ${col("Governors", govSq, gov.dem_seats != null ? ctlLine(gov, "governorships") : `Still counting: ${gCalled} of 36 called`, detail("governor", "a majority", "governors"))}
    </div></div>`
}

What the Results Show

Code
{
  const ups = scored.filter(r => r.status === "upset").sort((a, b) => a.pWinner - b.pWinner)
  const parties = [...new Set(ups.map(r => r.winner))]
  const mini = (t, body, cap) => `<div class="fc-find"><span class="fc-find-t">${t}</span><div class="fc-find-pic">${body}</div><span class="fc-find-c">${cap}</span></div>`
  const odds = n => n >= 1e6 ? `${Math.round(n / 1e6)} million` : n.toLocaleString("en-GB")
  // 1. direction of the upsets
  const one = ups.length
    ? `<div class="fc-updots" role="img" aria-label="The ${ups.length} upsets: ${ups.map(r => `${r.title}, won by the ${WIN[r.winner]}`).join("; ")}.">${ups.slice(0, 27).map(r =>
        `<span><i style="background:${PARTY[r.winner].colour}"></i><b>${r.short}</b></span>`).join("")}${ups.length > 27 ? `<span><i class="fc-more">+${ups.length - 27}</i><b>More</b></span>` : ""}</div>`
    : placeholder("No Upsets Yet", "No called race has gone against the forecast's favourite.")
  const oneCap = !ups.length ? "" : parties.length === 1
    ? `All ${ups.length} went to ${WINS[parties[0]]}. If each were equally likely to go either way, that would happen about 1 time in ${odds(2 ** ups.length)}.`
    : `${parties.map(p => `${ups.filter(r => r.winner === p).length} went to ${WINS[p]}`).join(" and ")}.`
  const oneT = parties.length === 1 && ups.length > 1 ? "Every Upset Went the Same Way" : "Which Way the Upsets Went"
  // 2. the shift in the vote, from race rows when filed, otherwise the scoring script's summary
  const withVote = scored.filter(r => r.voteReady && r.median != null)
  const vs = results.score?.vote_share ?? {}
  let two, twoCap
  if (withVote.length >= 10) {
    const err = withVote.map(r => (r.actual - r.median) * 100), m = d3.mean(err), sd = d3.deviation(err) ?? 0
    const bins = d3.bin().domain([-10, 10]).thresholds(d3.range(-10, 10.01, 1))(err.map(e => Math.max(-9.99, Math.min(9.99, e))))
    const top = d3.max(bins, b => b.length) || 1, X = v => (v + 10) / 20 * 100
    two = `<div class="fc-hist" role="img" aria-label="Histogram of the gap between result and forecast in ${withVote.length} races; mean ${pts(m / 100)} points.">${bins.map(b =>
      `<span style="height:${b.length / top * 100}%;background:${b.x0 >= 0 ? "#9fb1c8" : "#e0a59c"}"></span>`).join("")}<i class="is-zero" style="left:${X(0)}%"></i><i style="left:${X(m)}%"></i></div>
      <span class="fc-axis"><span>10 pts more Rep</span><span>0</span><span>10 pts more Dem</span></span>`
    const mm = vs.mean_error_toward_dem ?? m, nn = vs.n ?? withVote.length
    twoCap = `Across ${nn} races with most of the vote counted, results ran a mean ${Math.abs(mm).toFixed(1)} points more ${mm >= 0 ? "Democratic" : "Republican"} than forecast, give or take ${sd.toFixed(1)}.`
  } else if (vs.mean_error_toward_dem != null) {
    const m = vs.mean_error_toward_dem, X = v => (v + 6) / 12 * 100
    two = `<div class="fc-shift" role="img" aria-label="Mean shift of ${m} points toward Democrats"><span class="fc-shift-axis"></span><i class="is-zero" style="left:50%"></i><span class="fc-shift-arrow" style="left:${Math.min(50, X(m))}%;width:${Math.abs(X(m) - 50)}%"></span><b style="left:${X(m)}%">${pts(m / 100)}</b></div>
      <span class="fc-axis"><span>6 pts more Rep</span><span>Forecast</span><span>6 pts more Dem</span></span>`
    twoCap = `Across ${vs.n} races with most of the vote counted, results landed a mean ${Math.abs(m).toFixed(1)} points more ${m >= 0 ? "Democratic" : "Republican"} than the forecast expected. The race-by-race spread appears once vote shares are filed.`
  } else {
    two = placeholder("Waiting for Vote Shares", "This figure fills in once most of the vote is counted.")
    twoCap = ""
  }
  // 3. coverage of the 80% ranges
  // the scoring script's counts when filed (it works from unrounded ranges, so results exactly on an edge are placed
  // correctly); otherwise counted here from the race rows
  let cov = null
  if (vs.above_80 != null) cov = {n: vs.n ?? (vs.above_80 + vs.inside_80 + vs.below_80), above: vs.above_80, below: vs.below_80}
  else if (withVote.length >= 10) cov = {n: withVote.length, above: withVote.filter(r => r.actual > r.hi).length, below: withVote.filter(r => r.actual < r.lo).length}
  let three = placeholder("Waiting for Vote Shares", "This figure fills in once most of the vote is counted."), threeCap = "", threeT = "How Often Results Fell Outside the Ranges"
  if (cov) {
    const inside = cov.n - cov.above - cov.below, w = v => (v / cov.n * 100).toFixed(1)
    three = `<div class="fc-cov" role="img" aria-label="Of ${cov.n} results, ${cov.below} fell below the forecast's 80% range, ${inside} inside and ${cov.above} above. The target is about 10% each side.">
      <span>Target</span><span class="fc-cov-bar"><span style="width:10%;background:#e0a59c"></span><span style="width:80%;background:var(--fc-tie)"></span><span style="width:10%;background:#9fb1c8"></span></span>
      <span><b>Result</b></span><span class="fc-cov-bar is-real"><span style="width:${w(cov.below)}%;background:${REP}"></span><span style="width:${w(inside)}%;background:#8b8f95">${inside / cov.n > 0.25 ? `${inside} inside` : ""}</span><span style="width:${w(cov.above)}%;background:${DEM}">${cov.above / cov.n > 0.15 ? `${cov.above} above` : ""}</span></span></div>`
    const ratio = (k) => k ? `about 1 in ${Math.max(1, Math.round(cov.n / k))}` : "none"
    threeCap = `About 1 result in 10 should land above the 80% range and 1 in 10 below. Of ${cov.n}, ${cov.above} landed above (${ratio(cov.above)}) and ${cov.below} below.`
    if (cov.above / cov.n > 0.2 || cov.below / cov.n > 0.2) threeT = "The Ranges Were Too Narrow"
  }
  return html`<div><div class="fc-find3">${mini(oneT, one, oneCap)}${mini(withVote.length >= 10 || vs.mean_error_toward_dem != null ? "One Shift, Nearly Everywhere" : "How Far Off Was the Vote?", two, twoCap)}${mini(threeT, three, threeCap)}</div>
    <div class="fc-btnrow"><a class="op-btn op-btn-solid fc-btn" href="/work/scorecard-2026/">Read Why in the Write-Up <span aria-hidden="true">→</span></a></div></div>`
}
Code
{
  const c = cmpBlock("senate", "oct")
  const others = c.control.filter(r => r.name !== "v1")
  const lines = []
  if (others.length) {
    const fmt = r => `${r.name} ${r.news_report ? "about " : ""}${pct(r.p_dem)}`
    const below = others.filter(r => r.p_dem < pSenateD).sort((a, b) => a.p_dem - b.p_dem), above = others.filter(r => r.p_dem >= pSenateD).sort((a, b) => a.p_dem - b.p_dem)
    const list = (xs) => xs.map(fmt).join(", ").replace(/, ([^,]*)$/, " and $1")
    lines.push(`On 22 October this forecast gave Democrats a ${pct(pSenateD)} chance of winning the Senate${below.length && above.length ? `, above ${list(below)}, and below ${list(above)}` : below.length ? `, above ${list(below)}` : `, below ${list(above)}`}.`)
    const allWrong = cmpGrid("senate", "oct").rows.filter(r => r.x.called && r.cells.some(c => c && c.fav) && r.cells.every(c => !c || !c.fav || c.fav !== r.x.winner))
    if (allWrong.length) lines.push(`In ${allWrong.map(r => NAME[r.x.state]).join(", ").replace(/, ([^,]*)$/, " and $1")}, every forecast that named a favourite named the side that lost.`)
  } else lines.push("Other forecasts for 22 October have not been collected yet.")
  const el = html`<div class="fc-teaser"><span class="fc-teaser-t">Against Other Forecasts on 22 October</span><span class="fc-teaser-b">${lines.join(" ")} <button type="button" class="fc-textlink fc-teaser-go">See the comparison →</button></span></div>`
  el.querySelector("button").addEventListener("click", () => viewof rtab.setTab("compare"))
  return el
}
Code
viewof rchamber = segButtons([["senate", "Senate"], ["house", "House"], ["governor", "Governors"]], "senate", "Chamber")
Code
rRows = resOf(rchamber)
mutable rPick = null
rCurrent = rRows.find(r => r.id === rPick) ?? null
rClosest = [...rRows].filter(r => !r.district?.certain_hold_party).sort((a, b) => Math.abs(a.pD - 0.5) - Math.abs(b.pD - 0.5)).slice(0, rchamber === "house" ? 9 : 6)
rNoun = ({senate: "Senate race", house: "district", governor: "governor race"})[rchamber]
pickResult = (id) => { mutable rPick = id; reveal(".fc-rdetail") }

Every Race

Code
{
  const n = rRows.length, up = rRows.filter(r => r.status === "upset"), cnt = rRows.filter(r => r.status === "count").length
  const lean = up.length && up.every(r => r.favParty === up[0].favParty) ? ` all in ${rchamber === "house" ? "districts" : "states"} the forecast leaned ${WINS[up[0].favParty].replace(/s$/, "")}` : ""
  const tileNote = rchamber === "house" ? "Each dot is a district, shaded by the forecast's chance." : "The number in each tile is the forecast's chance for its favourite."
  return html`<p class="fc-takeaway fc-lead fc-every">${n} ${rNoun}s. ${tileNote} ${up.length ? `A black frame marks the ${up.length} where the forecast's favourite lost,${lean}.` : "No upsets among the races called so far."} ${cnt ? `${cnt} ${cnt === 1 ? "is" : "are"} still counting${isSample ? " in the sample file" : ""}.` : ""}</p>`
}
Code
rMap = {
  if (rchamber === "house") {
    // 435 districts in the forecast's order, safest Democratic first
    const d = [...rRows].sort((a, b) => b.pD - a.pD)
    const el = html`<div class="fc-hdots-wrap">
      <div class="fc-hdots" role="img" aria-label="All 435 House districts, from the safest Democratic seat to the safest Republican seat. ${d.filter(r => r.status === "upset").length} upsets are ringed in black; ${d.filter(r => r.status === "count").length} are still counting.">${d.map((r, i) =>
        `<span class="is-${r.status}${i === 217 ? " is-218" : ""}" data-id="${r.id}" style="${r.status === "count" ? "" : `background:${probColour(r.pD)}`}" title="${esc(`${r.title}: ${r.status === "count" ? "still counting" : `${WIN[r.winner]} won${r.status === "upset" ? " (upset)" : ""}`}`)}"></span>`).join("")}</div>
      <div class="fc-legend fc-tiles-key"><span class="fc-k"><span class="is-upset fc-k-round"></span>Upset</span><span class="fc-k"><span class="is-count fc-k-round"></span>Still Counting</span><span class="fc-dim">The dashed ring is the 218th seat.</span></div></div>`
    // the dots are for pointing; the table below is the keyboard route to every district
    el.addEventListener("click", e => { const b = e.target.closest("[data-id]"); if (b) pickResult(b.dataset.id) })
    el.mark = (id) => { for (const b of el.querySelectorAll("[data-id]")) b.classList.toggle("is-sel", b.dataset.id === id) }
    return el
  }
  const by = new Map()
  for (const r of rRows) if (!by.has(r.state) || !isSpecial(r.race)) by.set(r.state, r)
  const cells = new Map([...by].map(([s, r]) => [s, {id: r.id, fill: probColour(r.pD), status: r.status === "won" ? "" : r.status, small: pct(r.favP).replace("%", ""),
    label: `${r.title}: forecast ${PARTY[r.favParty].short} ${pct(r.favP)}; ${r.status === "count" ? "still counting" : `${WIN[r.winner]} won${r.status === "upset" ? ", an upset" : ""}`}`}]))
  const map = tileMap({cells, label: `Tile map of the ${rRows.length} ${rNoun}s, shaded by the forecast's chance, upsets framed in black`, onPick: pickResult})
  const legend = Plot.legend({color: {type: "linear", domain: [0, 1], interpolate: probColour, tickFormat: d => d === 0 ? "Rep" : d === 1 ? "Dem" : d === 0.5 ? "Even" : "", ticks: [0, 0.5, 1]},
    width: 210, marginLeft: 10, marginRight: 10, label: "Forecast Chance Democrats Win", className: "fc-plot"})
  const twos = [...new Set(rRows.filter(r => isSpecial(r.race)).map(r => NAME[r.state]))]
  const el = html`<div class="fc-tiles-wrap">${map}
    <div class="fc-legend fc-tiles-key">${legend}<span class="fc-k"><span class="is-upset"></span>Upset: the Favourite Lost</span><span class="fc-k"><span class="is-count"></span>Still Counting</span></div>
    ${twos.length ? `<p class="fc-note">${twos.join(" and ")} also ${twos.length > 1 ? "hold" : "holds"} a special election; the map shows the regular race, and the table lists both.</p>` : ""}</div>`
  el.mark = map.mark
  return el
}
Code
// the race panel beside the map: forecast and result side by side
rDetail = {
  const el = html`<aside class="fc-detail fc-rdetail" aria-live="polite" aria-label="Selected race"></aside>`
  el.render = (x) => {
    if (!x) { el.replaceChildren(html`<div class="fc-detail-body"><div class="fc-detail-kicker">Select a Race</div><p class="fc-dim">Select a state on the map, a card or a row in the table to see the forecast next to the result.</p></div>`); return }
    const r = x.race, h = x.district
    const lines = r ? [candRow(r, "dem"), candRow(r, "rep")] : h.cands.map(c => candLine(c.party, c.name, c.p))
    const bar = r ? probBar(r) : districtBar(h)
    const inRange = x.actual == null ? null : x.actual < x.lo ? "Below its 80% range" : x.actual > x.hi ? "Above its 80% range" : "Inside its 80% range"
    el.replaceChildren(html`<div class="fc-detail-body"><div class="fc-detail-kicker">${x.status === "upset" ? "Upset" : "Selected Race"}</div>
      <h3 class="fc-detail-title">${x.title}</h3>
      ${stampFor(x)}
      <div class="fc-detail-cands">${lines}</div>${bar}
      <dl class="fc-facts">
        <dt>Result</dt><dd>${x.called ? `${esc(x.res.winner_name ?? WIN[x.winner])} (${PARTY[x.winner].short}) won` : "Still counting"}</dd>
        <dt>Forecast Vote</dt><dd>${x.median != null ? `Dem ${share(x.median)} of the two-party vote (80% range ${share(x.lo)} to ${share(x.hi)})` : "Not modelled (only one party on the ballot)"}</dd>
        <dt>Actual Vote</dt><dd>${x.actual != null ? `Dem ${share(x.actual)}${inRange ? `, ${inRange.toLowerCase()}` : ""}${x.counted != null ? ` with ${Math.round(x.counted * 100)}% counted` : ""}` : "Still counting"}</dd>
        ${x.res?.source ? `<dt>Source</dt><dd><a href="${esc(x.res.source)}">${x.res.source.includes("github.com") ? "Election-night notes" : x.res.source.includes("apelections") ? "AP results feed" : "Source"}</a>${x.res.pulled_at ? `, pulled ${esc(x.res.pulled_at.slice(0, 16).replace("T", " "))} UTC` : ""}</dd>` : ""}
      </dl></div>`)
  }
  return el
}
Code
{
  rMap.mark(rCurrent?.id)
  rCards.mark(rCurrent?.id)
  rDetail.render(rCurrent ?? (rchamber === "house" ? null : rClosest[0]))
}

The Closest Races

Code
rCards = cardGrid(rClosest.map(x => ({
  id: x.id, title: x.title, rating: x.race ? ratingLabel(x.race) : x.district.rating,
  lines: x.race ? [candRow(x.race, "dem"), candRow(x.race, "rep")] : x.district.cands.map(c => candLine(c.party, c.name, c.p)),
  bar: x.race ? probBar(x.race) : districtBar(x.district),
  foot: stampFor(x)
})), pickResult)

Every Race in a Table

Code
{
  const items = rRows.map(x => ({...x, id: x.id}))
  const nUp = items.filter(r => r.status === "upset").length, nCount = items.filter(r => r.status === "count").length
  return dataTable({
    items, caption: `All ${items.length} ${rNoun}s with the forecast and the result`,
    noun: [rNoun, `${rNoun}s`], placeholder: "Search a state or candidate",
    searchText: r => `${r.title} ${NAME[r.state] ?? ""} ${r.state} ${r.race ? `${r.race.dem_candidate} ${r.race.rep_candidate}` : r.district.cands.map(c => c.name).join(" ")} ${r.res?.winner_name ?? ""}`,
    sortKey: "race", onPick: pickResult,
    filters: [{key: "all", label: `All ${items.length}`, test: () => true}, {key: "upsets", label: `Upsets ${nUp}`, test: r => r.status === "upset"}, {key: "count", label: `Counting ${nCount}`, test: r => r.status === "count"}],
    filter: "all",
    columns: [
      {key: "race", label: "Race", value: r => r.race ? NAME[r.state] + (isSpecial(r.race) ? " 2" : " 1") : cdOrder(r.id),
        render: r => `<button type="button" class="fc-row-link">${r.race ? `${NAME[r.state]}${isSpecial(r.race) ? " (Special)" : ""}` : r.id}</button><span class="fc-sub fc-narrow">${stampFor(r)}</span>`},
      {key: "fav", label: "Forecast Favourite", value: r => r.favP,
        render: r => chip(r.favParty, r.district?.certain_hold_party ? `${PARTY[r.favParty].short}, Certain` : `${PARTY[r.favParty].short} ${pct(r.favP)}`)},
      {key: "fshare", label: "Forecast Dem Share", cls: "fc-wide fc-num", value: r => r.median ?? -1, render: r => r.median != null ? share(r.median) : `<span class="fc-dim">n/a</span>`},
      {key: "ashare", label: "Actual Dem Share", cls: "fc-num", value: r => r.voteReady ? r.actual : -1,
        render: r => r.voteReady ? share(r.actual) : `<span class="fc-dim">${r.called && r.actual != null && r.district && !(r.district.dem_candidates && r.district.rep_candidates) ? "n/a" : "Counting"}</span>`},
      {key: "result", label: "Result", cls: "fc-wide", value: r => ({upset: 0, won: 1, count: 2})[r.status], render: r => stampFor(r)}
    ]
  })
}

When the Forecast Was Sure, Was It Right?

Code
{
  const called = scored.filter(r => r.called), all = scoreFor("all")
  // A file that lists only some of the called races (the sample lists the upsets) would make these rows misleading.
  if (results.score?.all?.called != null && called.length < results.score.all.called) {
    const per = ["senate", "house", "governor"].map(k => { const s = scoreFor(k); return `${s.favourites_won} of ${s.called} ${k === "governor" ? "governor" : OFFICE[k]} favourites won (about ${Math.round(s.expected_upsets)} upsets expected, ${s.upsets} seen)` })
    return html`<div><p class="fc-takeaway fc-lead">Each dot will be a called race, grouped by how confident the forecast was in its favourite, with upsets as open circles. A well-judged forecast should be wrong now and then in the closer groups, and almost never in the near-certain ones.</p>
      ${placeholder("Waiting for the Race-by-Race Calls", `The results file lists ${called.length} of the ${all.called} called races, so grouping them here would give a false picture. The totals so far: ${per.join("; ")}.`)}</div>`
  }
  const bands = [[0.5, 0.6, "Toss-Up", "50 to 60%"], [0.6, 0.75, "Lean", "60 to 75%"], [0.75, 0.9, "Likely", "75 to 90%"], [0.9, 0.99, "Very Likely", "90 to 99%"], [0.99, 1.01, "Near Certain", "99% and up"]]
  const rows = bands.map(([lo, hi, lab, rng]) => {
    const xs = called.filter(r => r.favP >= lo && r.favP < hi), k = xs.filter(r => r.status === "upset").length, exp = d3.sum(xs, r => 1 - r.favP)
    return {lab, rng, n: xs.length, k, exp, xs: [...xs].sort((a, b) => d3.descending(a.status === "upset", b.status === "upset"))}
  })
  return html`<div>
    <p class="fc-takeaway fc-lead">Each dot is a called race, grouped by how confident the forecast was in its favourite. Open circles are upsets. A well-judged forecast should be wrong now and then in the closer groups, and almost never in the near-certain ones.${isSample ? " In the sample file only a handful of races are called, so most rows are thin." : ""}</p>
    <div class="fc-bands" role="list">${rows.map(b => `<div class="fc-band" role="listitem">
      <span class="fc-band-l"><b>${b.lab}</b><span>${b.rng}</span></span>
      <span class="fc-band-dots" role="img" aria-label="${b.n} called races, ${b.k} upsets">${b.xs.map(r => `<span class="${r.status === "upset" ? "is-upset" : ""}" title="${esc(`${r.title}: ${WIN[r.winner]} won${r.status === "upset" ? ", an upset" : ""}`)}"></span>`).join("") || `<span class="fc-dim fc-small fc-band-none">None called yet</span>`}</span>
      <span class="fc-band-r">${b.n ? `<b>${b.n - b.k}<small>/${b.n}</small></b><span>won · ${b.k} upset${b.k === 1 ? "" : "s"}, about ${b.exp < 1 && b.exp > 0 ? b.exp.toFixed(1) : Math.round(b.exp)} expected</span>` : "—"}</span></div>`).join("")}</div></div>`
}

How Far Off Was the Vote?

Code
{
  const rows = scored.filter(r => r.office !== "house" && r.voteReady && r.median != null)
  const vs = results.score?.vote_share ?? {}
  const summary = vs.mean_error_toward_dem != null ? ` Across all ${vs.n} races with most of the vote counted, House included, results averaged ${Math.abs(vs.mean_error_toward_dem).toFixed(1)} points more ${vs.mean_error_toward_dem >= 0 ? "Democratic" : "Republican"} than forecast.` : ""
  const intro = `Each dot is a Senate or governor race: the forecast's Democratic share of the two-party vote, across, against the result, up. Above the dashed diagonal, the Democrat did better than forecast; the grey bar is the forecast's 80% range.`
  if (!rows.length) return html`<div><p class="fc-takeaway fc-lead">${intro}</p>${placeholder("Waiting for Vote Shares", `No Senate or governor race has a filed vote share yet, so no dots are drawn.${summary}`)}</div>`
  const lo = Math.floor(Math.min(0.3, d3.min(rows, r => Math.min(r.lo, r.actual))) * 20) / 20, hi = Math.ceil(Math.max(0.7, d3.max(rows, r => Math.max(r.hi, r.actual))) * 20) / 20
  const above = rows.filter(r => r.actual > r.hi).length, below = rows.filter(r => r.actual < r.lo).length
  const side = rw > 860 ? Math.min(420, Math.round(rw * 0.45)) : Math.min(rw, 420)
  const chart = Plot.plot({width: side, height: side, marginLeft: 48, marginBottom: 40, className: "fc-plot",
    ariaLabel: `Forecast against result for ${rows.length} Senate and governor races; ${above} above the forecast's 80% range and ${below} below.`,
    x: {label: "Forecast Democratic share (%)", domain: [lo * 100, hi * 100], ticks: 5},
    y: {label: "Result (%)", domain: [lo * 100, hi * 100], ticks: 5, grid: true},
    marks: [
      Plot.line([[lo * 100, lo * 100], [hi * 100, hi * 100]], {stroke: "currentColor", strokeDasharray: "4,3", strokeWidth: 1}),
      Plot.ruleX([50], {stroke: "currentColor", strokeOpacity: 0.2}), Plot.ruleY([50], {stroke: "currentColor", strokeOpacity: 0.2}),
      Plot.ruleX(rows, {x: r => r.median * 100, y1: r => r.lo * 100, y2: r => r.hi * 100, stroke: "#8b8f95", strokeOpacity: 0.45, strokeWidth: 3}),
      Plot.dot(rows, {x: r => r.median * 100, y: r => r.actual * 100, r: 4.5, fill: r => r.office === "senate" ? "currentColor" : "var(--bs-body-bg)", stroke: "currentColor", strokeWidth: 1.4,
        tip: true, title: r => `${r.title}\nForecast: ${share(r.median)} Dem (${share(r.lo)} to ${share(r.hi)})\nResult: ${share(r.actual)} Dem`})
    ]})
  // beside the square chart, the three numbers it shows, so the text column runs the chart's height
  const exp = Math.round(rows.length / 10), mErr = vs.mean_error_toward_dem
  const stats = [
    [`${above}<small> of ${rows.length}</small>`, `Above the 80% range`, `About ${exp} expected`],
    [`${below}<small> of ${rows.length}</small>`, `Below the 80% range`, `About ${exp} expected`],
    ...(mErr != null ? [[`${Math.abs(mErr).toFixed(1)}<small> pts</small>`, `Mean miss toward ${mErr >= 0 ? "Democrats" : "Republicans"}`, `All ${vs.n} counted races, House included`]] : [])
  ]
  const el = html`<div class="fc-side fc-side-stats"><div class="fc-side-l"><p class="fc-takeaway fc-lead">${intro}</p>
    <div class="fc-vnums">${stats.map(([n, a, b]) => `<div><span class="fc-rnum">${n}</span><span><b>${a}</b><span>${b}</span></span></div>`).join("")}</div></div>
    <div class="fc-scatter"><div class="fc-chartbox"></div><div class="fc-sq-key"><span class="fc-k"><span class="fc-kdot"></span>Senate</span><span class="fc-k"><span class="fc-kdot is-open"></span>Governor</span><span class="fc-k"><span class="fc-kbar"></span>Forecast's 80% range</span></div></div></div>`
  el.querySelector(".fc-chartbox").append(chart)
  return el
}

The Seats Against Their Range

Code
{
  // the three seat distributions side by side, each with the result marked and one short caption
  const spec = [["senate", "Senate", 44, 60, 51, "51 for control", 2, "Democratic-caucus seats"], ["house", "House", 200, 270, 218, "218", 10, "Democratic seats"], ["governor", "Governors", 18, 34, 26, "26 for a majority", 2, "Democratic governors"]]
  const w = rw > 860 ? Math.floor((rw - 64) / 3) : Math.min(rw, 520)
  const el = html`<div><p class="fc-takeaway">The forecast's chance of each seat total, with the result so far as a black line. A result near the edge of a range is a sign the range was too narrow.</p><div class="fc-seat3">${spec.map(([k, label]) => `<div class="fc-ctl"><span class="fc-card-label fc-ink">${label}</span><div class="fc-chartbox"></div><span class="fc-ctl-2"></span></div>`).join("")}</div></div>`
  el.querySelectorAll(".fc-seat3 > div").forEach((col, i) => {
    const [k, label, lo, hi, maj, majLabel, step, unit] = spec[i]
    const dist = chamberDist[k], x = chamberRes(k).dem_seats, done = chamberRes(k).complete, p = resultPct(k)
    const rg0 = scoreExtra?.seat_percentiles?.[k]?.percentile_range, rg = rg0 && rg0[1] - rg0[0] < 0.5 ? rg0 : null
    const rows = dist.filter(d => d.seats >= lo && d.seats <= hi), top = d3.max(rows, d => d.p) * 1.3
    col.querySelector(".fc-chartbox").append(Plot.plot({width: w, height: 170, marginLeft: 30, marginRight: 8, marginTop: 24, className: "fc-plot",
      ariaLabel: `${label}: the forecast's distribution of ${unit}${x == null ? "" : `, with the result of ${x} marked`}`,
      x: {label: null, domain: [lo - 0.5, hi + 0.5], ticks: d3.range(Math.ceil(lo / (step * 2)) * step * 2, hi + 1, step * 2), tickFormat: "d"},
      y: {label: null, grid: true, percent: true, domain: [0, top * 100], ticks: 3},
      marks: [
        Plot.rectY(rows, {x1: d => d.seats - 0.5, x2: d => d.seats + 0.5, y: "p", fill: d => d.seats >= maj ? DEM : REP, fillOpacity: x == null ? 1 : 0.55, inset: rows.length > 40 ? 0.2 : 0.8,
          tip: true, title: d => `${d.seats} ${unit}: ${(d.p * 100).toFixed(1)}%`}),
        Plot.ruleX([maj - 0.5], {y1: 0, y2: top, stroke: "currentColor", strokeWidth: 1, strokeDasharray: "4,3"}),
        ...(x == null ? [] : [Plot.ruleX([x], {y1: 0, y2: top, stroke: "currentColor", strokeWidth: 3}),
          Plot.text([`${x}${done ? "" : " so far"}`], {x, frameAnchor: "top", dy: -14, dx: 5, textAnchor: "start", fontSize: 11.5, fontWeight: 700, className: "fc-halo"})]),
        Plot.ruleY([0])
      ]}))
    col.querySelector(".fc-ctl-2").textContent = x == null ? `Still counting. The forecast's median was ${median(dist)}, with ${quantile(dist, 0.1)} to ${quantile(dist, 0.9)} in 80% of simulations.`
      : `Median ${median(dist)}, 80% range ${quantile(dist, 0.1)} to ${quantile(dist, 0.9)}. ${p != null ? `The result is at its ${ord(Math.round(p * 100))} percentile.` : rg ? `The result will land at its ${ord(Math.round(rg[0] * 100))} to ${ord(Math.round(rg[1] * 100))} percentile.` : "Its percentile follows once the count is complete."}`
  })
  return el
}

What Would Have Helped

Code
diag = FileAttachment("data/diagnostics.json").json().catch(() => null)
throughTime = FileAttachment("data/through_time.json").json().catch(() => null)
Code
{
  if (!diag) return html`${placeholder("Not Yet Run", "The diagnostic reruns have not been filed yet.")}`
  const V = diag.variants, when = fmtWhen(diag.pulled_at)
  const rows = [
    ["v1", "The forecast as published", "Fixed on 22 October"],
    ["h6_late_polls", "Polls up to election eve", "Race polls as of 3 November"],
    ["h1a_bias_0", "No generic-ballot correction", "The −1.75-point adjustment removed"],
    ["h1a_and_h6", "Both changes together", "No correction; 3 November polls"],
    ["h7_house_effects", "Pollster leans removed", "Each pollster's usual lean taken out"],
    ["h8_no_partisan", "Partisan polls left out", "Only polls without a party sponsor"]
  ].filter(([k]) => V[k])
  const m = (k) => V[k].metrics.all, base = m("v1")
  // three measures, each on its own small scale, the published value marked on every row
  const cols = [
    {key: "mean_error", label: "Lean Toward Republicans", sub: "Mean error, points; 0 is unbiased", lo: 0, hi: 4, fmt: v => `${v.toFixed(1)} pts`},
    {key: "coverage_80", label: "Results Inside the 80% Range", sub: "Target 80%", lo: 0.5, hi: 1, fmt: v => `${Math.round(v * 100)}%`, target: 0.8},
    {key: "brier", label: "Accuracy (Brier)", sub: "Lower is better", lo: 0, hi: 0.04, fmt: v => v.toFixed(3)}
  ]
  const X = (c, v) => (Math.max(0, Math.min(1, (v - c.lo) / (c.hi - c.lo))) * 100).toFixed(1)
  const cell = (c, k) => { const v = m(k)[c.key], b = base[c.key]
    return `<span class="fc-cm-cell"><span class="fc-cm-line"><span class="fc-wi-track"></span>${c.target != null ? `<i class="fc-wi-target" style="left:${X(c, c.target)}%"></i>` : ""}<i style="left:${X(c, b)}%"></i>${k === "v1" ? "" : `<span class="fc-wi-move" style="left:${Math.min(X(c, v), X(c, b))}%;width:${Math.abs(X(c, v) - X(c, b))}%"></span>`}<span class="fc-cmp-dot" style="left:${X(c, v)}%"></span></span><span class="fc-cm-num"><b>${c.fmt(v)}</b></span></span>` }
  const nCalled = base.called
  return html`<div>
    <p class="fc-takeaway fc-lead">${V.h1a_bias_0 ? `The forecast leaned ${base.mean_error.toFixed(1)} points toward Republicans, for two reasons. The polls understated Democrats, and almost all of them in the same direction, so later polls, adjusting for each pollster's lean and leaving out partisan polls all barely moved it. A 1.75-point correction to the generic ballot then added to the polls' error: without it, the lean falls to ${m("h1a_bias_0").mean_error.toFixed(1)} points and ${Math.round(m("h1a_bias_0").coverage_80 * 100)}% of results land inside their 80% ranges, close to the target.` : "Each row reruns the forecast's own code with one change, scored against the same results."}</p>
    <div class="fc-cm fc-wi" role="table" aria-label="Diagnostic reruns of the forecast, scored">
      <div class="fc-cm-row fc-cm-head" role="row"><span role="columnheader" class="fc-card-label">Rerun</span>${cols.map(c => `<span role="columnheader" class="fc-cm-h"><b>${c.label}</b><span>${c.sub}</span></span>`).join("")}</div>
      ${rows.map(([k, name, sub]) => `<div class="fc-cm-row${k === "v1" ? " is-me" : ""}" role="row"><span role="rowheader" class="fc-cmp-name"><b>${name}</b><span>${sub}</span></span>${cols.map(c => cell(c, k)).join("")}</div>`).join("")}
    </div>
    <p class="fc-note">Each row reruns the forecast's code with one change; the published forecast is unchanged. Scored on the ${nCalled} races called and the ${base.vote_n} with most of the vote counted at ${when}. Thin tick: as published; dashed tick: the 80% target.</p></div>`
}
Code
{
  if (!diag) return html``
  const h2 = diag.h2, h4 = diag.h4, h6 = diag.h6
  const lab = h2.polls.by_label, age = h2.polls.by_age_days
  const bars = (items) => { const top = d3.max(items, d => d[1]) || 1
    return `<div class="fc-wi-bars"><span class="fc-wi-bh">Mean miss by poll sponsor, points</span>${items.map(([t, v, n]) => `<span class="fc-wi-bl">${t}</span><span class="fc-wi-bt"><span style="width:${(v / top * 100).toFixed(1)}%"></span></span><span class="fc-wi-bv">+${v.toFixed(1)}<small> · ${n}</small></span>`).join("")}</div>` }
  const pollBars = bars([["Republican-sponsored", lab["Republican-labelled"].mean, lab["Republican-labelled"].n], ["Unaffiliated", lab.unlabelled.mean, lab.unlabelled.n], ["Democratic-sponsored", lab["Democratic-labelled"].mean, lab["Democratic-labelled"].n]])
  // the realised House shift against the forecast's spread for it, drawn on a normal curve
  const sd = h4.house.sd_simulated, x = h4.house.realised_mean_shift_points, lo = -5, hi = 5
  const pts2 = d3.range(lo, hi + 0.01, 0.1).map(v => [v, Math.exp(-0.5 * (v / sd) ** 2)])
  const W = 300, H = 92, sx = v => (v - lo) / (hi - lo) * W, sy = y => H - 8 - y * (H - 18)
  const q = 1.2816 * sd
  const curve = `<svg class="fc-wi-curve" viewBox="0 0 ${W} ${H + 18}" role="img" aria-label="The forecast's spread for the national House shift, with the realised shift of ${x.toFixed(1)} points at its ${Math.round(h4.house.percentile_realised * 1000) / 10}th percentile">
    <path d="M${sx(-q)},${sy(0)} ${pts2.filter(p => p[0] >= -q && p[0] <= q).map(p => `L${sx(p[0]).toFixed(1)},${sy(p[1]).toFixed(1)}`).join(" ")} L${sx(q)},${sy(0)} Z" fill="color-mix(in srgb, var(--bs-body-color) 10%, transparent)"/>
    <path d="${pts2.map((p, i) => `${i ? "L" : "M"}${sx(p[0]).toFixed(1)},${sy(p[1]).toFixed(1)}`).join(" ")}" fill="none" stroke="currentColor" stroke-width="1.2"/>
    <line x1="${sx(0)}" x2="${sx(0)}" y1="${sy(0)}" y2="${sy(1) - 4}" stroke="currentColor" stroke-dasharray="3,3" stroke-width="1"/>
    <line x1="${sx(x)}" x2="${sx(x)}" y1="${sy(0)}" y2="6" stroke="currentColor" stroke-width="2.5"/>
    <text x="${sx(x) - 6}" y="14" font-size="11" font-weight="600" text-anchor="end" fill="currentColor">Result: +${x.toFixed(1)}</text>
    <line x1="0" x2="${W}" y1="${sy(0)}" y2="${sy(0)}" stroke="currentColor" stroke-width="1"/>
    ${[-4, -2, 0, 2, 4].map(v => `<text x="${sx(v)}" y="${H + 12}" font-size="10" text-anchor="middle" fill="currentColor" opacity=".7">${v > 0 ? "+" : ""}${v}</text>`).join("")}</svg>`
  const mini = (t, body, cap) => `<div class="fc-find"><span class="fc-find-t">${t}</span><div class="fc-find-pic">${body}</div><span class="fc-find-c">${cap}</span></div>`
  return html`<div><h2 class="fc-rh2">Why It Missed</h2><div class="fc-find3">
    ${mini("The Polls Missed Together", pollBars, `Polls understated Democrats by ${h2.races.mean.toFixed(1)} points on average, about ${h2.model.mean_error_in_s_nat.toFixed(1)} times the shared error the forecast allowed.`)}
    ${mini("The Range Was Too Narrow", curve, `The House shift sat at the ${ord(Math.round(h4.house.percentile_realised * 100))} percentile; covering it needed a range ${h4.house.scale_needed.toFixed(1)} times as wide.`)}
    ${mini("Late Polls Helped a Little", `<div class="fc-wi-big"><b>${Math.round(h6.scored.share_of_error_closed * 100)}%</b><span>of the polling miss closed by later polls</span></div>`, `Polls moved ${h6.movement_toward_dem.mean.toFixed(1)} points toward Democrats after 22 October; most of the miss remained.`)}
  </div></div>`
}

The Forecast Through Time

Code
{
  const t = throughTime
  if (!t?.rows?.length) return html`<div><p class="fc-takeaway">The same forecast rerun as it would have stood on dates from 1 September to 2 November, each with only the polls public on that day.</p>${placeholder("Being Rerun", "These reruns are in progress; the chart fills in when they are filed.")}</div>`
  const vars = [...new Set(t.rows.map(r => r.variant))], built = vars.find(v => /built/.test(v)) ?? vars[0], alt = vars.find(v => v !== built)
  const rows = t.rows.map(r => ({...r, d: new Date(r.date + "T12:00:00Z"), v: r.variant === built ? "As built" : "No correction"}))
  const lock = new Date("2026-10-22T12:00:00Z")
  const w = rw > 860 ? Math.floor((rw - 3 * 28) / 4) : Math.min(rw, 420)
  const panel = (title, y, fmt, domain, extra = []) => {
    const box = html`<div class="fc-ctl"><span class="fc-card-label fc-ink">${title}</span></div>`
    box.append(Plot.plot({width: w, height: 170, marginLeft: 42, marginRight: 10, marginTop: 14, className: "fc-plot",
      x: {type: "utc", label: null, ticks: [new Date("2026-09-01"), new Date("2026-10-01"), new Date("2026-11-01")], tickFormat: d3.utcFormat("%-d %b")},
      y: {label: null, domain, grid: true, ticks: 4, tickFormat: fmt},
      marks: [
        Plot.ruleX([lock], {stroke: "currentColor", strokeOpacity: 0.35, strokeDasharray: "2,3"}),
        ...extra,
        Plot.line(rows.filter(d => d.v !== "As built"), {x: "d", y, stroke: "currentColor", strokeWidth: 1.6, strokeDasharray: "5,3", strokeOpacity: 0.55}),
        Plot.line(rows.filter(d => d.v === "As built"), {x: "d", y, stroke: "currentColor", strokeWidth: 2}),
        Plot.dot(rows, {x: "d", y, fill: d => d.v === "As built" ? "currentColor" : "var(--bs-body-bg)", stroke: "currentColor", r: 3, strokeOpacity: d => d.v === "As built" ? 1 : 0.6,
          tip: true, title: d => `${d.v}, ${d3.utcFormat("%-d %B")(d.d)}: ${fmt(y(d))}`})
      ]}))
    return box
  }
  const pc = v => `${Math.round(v * 100)}%`
  const half = [Plot.ruleY([0.5], {stroke: "currentColor", strokeOpacity: 0.25})]
  const grid = html`<div class="fc-tt4"></div>`
  grid.append(panel("Senate", r => r.chances.senate.dem_control, pc, [0, 1], half),
    panel("House", r => r.chances.house.dem_control, pc, [0, 1], half),
    panel("Governors", r => r.chances.governor.dem_control, pc, [0, 1], half),
    panel("Lean Toward Republicans, Points", r => r.scores.all.mean_error, v => v.toFixed(1), [0, 5], [Plot.ruleY([0], {stroke: "currentColor"})]))
  const at = (date, v) => rows.find(r => r.date === date && r.variant === v)
  const first = at(rows[0].date, built), last = at(rows[rows.length - 1].date, built), oct = rows.find(r => r.variant === built && r.date === "2026-10-22")
  return html`<div>
    <p class="fc-takeaway">The forecast rerun on seven dates from 1 September to 2 November, each with only the data public that day: the chance Democrats win each chamber, and how far it leaned toward Republicans. Solid lines as built; dashed, without the generic-ballot correction; dotted, 22 October.</p>
    ${grid}
    <p class="fc-note">The lean fell from ${first.scores.all.mean_error.toFixed(1)} to ${last.scores.all.mean_error.toFixed(1)} points as more races were polled, but no date removed it; dropping the correction did more. Every date uses the eventual nominees, a small look-ahead before some primaries.</p></div>`
}
Code
comparisonFile = FileAttachment("data/comparison.json").json().catch(() => null)
cmpSrc = comparisonFile ?? results.comparison ?? {}
cmpBlock = (ch, when) => {
  const c = cmpSrc
  const src = when === "final" ? (c.final ?? {}) : c
  const officeOf = (id) => /-SENS?$/.test(id) ? "senate" : /-GOV$/.test(id) ? "governor" : "house"
  const b = src[ch] ?? {
    control: ch === "senate" ? (src.senate_control ?? []) : [], seats: [],
    races: (src.races ?? []).filter(r => officeOf(r.id) === ch)
  }
  return {control: b.control ?? [], seats: b.seats ?? [], races: (b.races ?? []).filter(r => r.forecaster !== "v1"), score: b.score ?? null}
}
V1 = "This Forecast"
nameOf = (n) => n === "v1" ? V1 : n
RATING_P = cmpSrc.conventions?.rating_mapping ?? ({"Toss Up": 0.5, "Lean D": 0.65, "Likely D": 0.85, "Solid D": 0.97, "Lean R": 0.35, "Likely R": 0.15, "Solid R": 0.03})
// what kind of forecast a forecaster publishes, from its rows (a rating, a market price or a model probability)
kindOf = (name, b) => {
  const c = b.control.find(r => r.name === name), h = b.score?.head_to_head?.find(r => r.forecaster === name)
  if (h?.kind) return h.kind
  if (c?.kind) return c.kind
  const r = b.races.find(r => r.forecaster === name)
  return r?.rating ? "rating" : r?.margin_dem != null ? "margin" : "model"
}
KIND = ({model: "Model", market: "Market Price", rating: "Rating", margin: "Projected Margin"})
// a forecaster's call on one race, whatever form it took: a probability, a rating or a margin
callOf = (row, x) => {
  if (!row) return null
  const dem = x.demParty
  if (row.p_dem != null) return {kind: "p", pD: row.p_dem, fav: row.p_dem > 0.5 ? dem : row.p_dem < 0.5 ? "R" : null, favP: Math.max(row.p_dem, 1 - row.p_dem),
    text: row.p_dem === 0.5 ? "Even" : `${PARTY[row.p_dem > 0.5 ? dem : "R"].short} ${pct(Math.max(row.p_dem, 1 - row.p_dem))}`, row}
  if (row.rating) {
    const key = Object.keys(RATING_P).find(k => k.toLowerCase().replace(/[^a-z]/g, "") === String(row.rating).toLowerCase().replace(/[^a-z]/g, ""))
    const pD = key != null ? RATING_P[key] : 0.5
    return {kind: "rating", pD, fav: pD > 0.5 ? dem : pD < 0.5 ? "R" : null, favP: Math.max(pD, 1 - pD), text: row.rating, row}
  }
  if (row.margin_dem != null) return {kind: "margin", pD: null, fav: row.margin_dem > 0 ? dem : row.margin_dem < 0 ? "R" : null, favP: null,
    text: `${row.margin_dem > 0 ? PARTY[dem].short : "Rep"} +${Math.abs(row.margin_dem).toFixed(1)}`, row}
  return null
}
v1Call = (x) => ({kind: "p", pD: x.pD, fav: x.favParty, favP: x.favP, text: `${PARTY[x.favParty].short} ${pct(x.favP)}`, row: null})
KIND_ORDER = ({model: 0, market: 1, margin: 2, rating: 3})
// forecasters with no public race-by-race numbers get an empty column marked "Not public"
notPublic = (name) => (cmpSrc.missing ?? []).some(m => m.forecaster === name && /race-by-race/i.test(m.what ?? ""))
// the race-by-race grid: competitive races (favourite under 85% in any forecast), one column per forecaster
cmpGrid = (ch, when) => {
  const b = cmpBlock(ch, when)
  const withRaces = [...new Set(b.races.map(r => r.forecaster))]
  const hidden = b.control.map(r => r.name).filter(n => n !== "v1" && !withRaces.includes(n) && notPublic(n))
  const names = [...withRaces, ...hidden].sort((a, c) => d3.ascending(KIND_ORDER[kindOf(a, b)] ?? 9, KIND_ORDER[kindOf(c, b)] ?? 9))
  const byId = new Map(resOf(ch).map(x => [x.id, x]))
  const rowsBy = d3.group(b.races, r => r.id)
  const ids = [...rowsBy.keys()].filter(id => byId.has(id))
  const rows = ids.map(id => { const x = byId.get(id), rs = rowsBy.get(id); return {x, cells: names.map(n => hidden.includes(n) ? {kind: "hidden"} : callOf(rs.find(r => r.forecaster === n), x))} })
    .filter(r => r.x.favP < 0.85 || r.cells.some(c => c && c.favP != null && c.favP < 0.85))
    .sort((a, c) => Math.abs(a.x.pD - 0.5) - Math.abs(c.x.pD - 0.5))
  return {names, hidden, rows: rows.map(r => ({...r, v1: v1Call(r.x)})), block: b, byId}
}
logLoss = (p, y) => { const q = Math.min(0.999, Math.max(0.001, p)); return -(y * Math.log(q) + (1 - y) * Math.log(1 - q)) }
// scores: the comparison file's head-to-head table when filed (each forecaster against this forecast on the races both
// covered); otherwise computed here the same way from the race rows
cmpScores = (ch, when) => {
  const g = cmpGrid(ch, when), b = g.block
  if (b.score?.head_to_head?.length) return b.score.head_to_head.map(h => ({...h, name: h.forecaster, filed: true}))
  return g.names.filter(n => !g.hidden.includes(n)).map(n => {
    const mine = b.races.filter(r => r.forecaster === n).map(r => ({x: g.byId.get(r.id), r})).filter(o => o.x).map(o => ({...o, c: callOf(o.r, o.x)})).filter(o => o.c && o.c.pD != null)
    const sc = mine.filter(o => o.x.called), comp = sc.filter(o => o.x.favP < 0.85 || o.c.favP < 0.85)
    const br = (os, f) => os.length ? d3.mean(os, o => (f(o) - o.x.yD) ** 2) : null
    const ll = (os, f) => os.length ? d3.mean(os, o => logLoss(f(o), o.x.yD)) : null
    const miss = (os, f) => d3.sum(os, o => { const p = f(o); return p === 0.5 ? 0.5 : (p > 0.5) !== (o.x.yD === 1) ? 1 : 0 })
    return {name: n, kind: kindOf(n, b), n: sc.length, brier: br(sc, o => o.c.pD), v1_brier: br(sc, o => o.x.pD), log_loss: ll(sc, o => o.c.pD), v1_log_loss: ll(sc, o => o.x.pD),
      upsets_missed: miss(sc, o => o.c.pD), v1_upsets_missed: miss(sc, o => o.x.pD), n_competitive: comp.length, brier_competitive: br(comp, o => o.c.pD), v1_brier_competitive: br(comp, o => o.x.pD)}
  })
}
cmpOutcome = (ch) => cmpSrc[ch]?.control_outcome?.control ?? chamberRes(ch).control ?? null
cmpControl = (ch, when) => {
  const b = cmpBlock(ch, when), out = cmpOutcome(ch)
  const y = out == null ? null : +(out === "D")
  const me = {name: V1, p_dem: chamberP[ch], kind: "model", source: "forecasts/v1", captured: "2026-10-22", news_report: false, me: true}
  return [me, ...b.control.filter(r => r.name !== "v1" && r.p_dem != null).map(r => ({...r, name: nameOf(r.name)}))]
    .sort((a, c) => c.p_dem - a.p_dem)
    .map(r => ({...r, brier: y == null ? null : r.brier ?? (r.p_dem - y) ** 2}))
}
cmpSeats = (ch, when) => {
  const b = cmpBlock(ch, when), dist = chamberDist[ch]
  const norm = (r) => ({...r, name: nameOf(r.name), median: r.median ?? r.dem_median ?? r.dem_projection ?? null, lo80: r.lo80 ?? r.dem_lo80 ?? null, hi80: r.hi80 ?? r.dem_hi80 ?? null,
    projectionOnly: (r.median ?? r.dem_median) == null && r.dem_projection != null})
  return [{name: V1, median: median(dist), lo80: quantile(dist, 0.1), hi80: quantile(dist, 0.9), me: true},
    ...b.seats.filter(r => r.name !== "v1").map(norm)]
}
fmtWhen = (s) => { if (!s) return ""; const d = new Date(s); return isNaN(d) || !/^\d{4}-\d{2}-\d{2}/.test(s) ? String(s) : d.toLocaleDateString("en-GB", {day: "numeric", month: "short", timeZone: "UTC"}) }
srcLine = (r) => r.me ? "Published 22 Oct; fixed"
  : [r.kind === "market" ? "Market price" : null, r.news_report ? "From news reports †" : null, r.captured ? fmtWhen(r.captured) : null].filter(Boolean).join(" · ")
cWord = ({senate: "the Senate", house: "the House", governor: "a majority of governorships"})
srcLink = (s) => /^https?:/.test(s ?? "") ? `<a href="${esc(s)}">${esc(new URL(s).hostname.replace(/^www\./, ""))}</a>` : esc(s ?? "")

Chance of Winning

Code
{
  // every chamber in one table; in each cell an open dot for 22 October and a filled dot for the forecaster's final number
  const chs = [["senate", "Senate", "control"], ["house", "House", "control"], ["governor", "Governors", "a majority"]]
  const per = Object.fromEntries(chs.map(([k]) => [k, {oct: cmpControl(k, "oct"), fin: cmpControl(k, "final")}]))
  const names = [...new Set(chs.flatMap(([k]) => [...per[k].oct, ...per[k].fin].map(r => r.name)))]
    .sort((a, b) => (b === V1) - (a === V1) || d3.descending(per.senate.oct.find(r => r.name === a)?.p_dem ?? per.senate.fin.find(r => r.name === a)?.p_dem ?? -1, per.senate.oct.find(r => r.name === b)?.p_dem ?? per.senate.fin.find(r => r.name === b)?.p_dem ?? -1))
  const meta = (n) => chs.flatMap(([k]) => [per[k].oct.find(r => r.name === n), per[k].fin.find(r => r.name === n)]).find(Boolean)
  const p = (r) => `${r.news_report ? "~" : ""}${pct(r.p_dem)}`
  const cell = (k, n) => {
    const o = per[k].oct.find(r => r.name === n), f = n === V1 ? null : per[k].fin.find(r => r.name === n)
    if (!o && !f) return `<span class="fc-cm-cell is-none"><span class="fc-dim fc-small">Not published</span></span>`
    const a = o ?? f, z = f ?? o, lo = Math.min(a.p_dem, z.p_dem) * 100, hi = Math.max(a.p_dem, z.p_dem) * 100
    const txt = o && f && Math.round(o.p_dem * 100) !== Math.round(f.p_dem * 100) ? `${p(o)} → ${p(f)}` : p(z)
    const br = z.brier != null ? `Brier ${num(z.brier, 2)}` : ""
    return `<span class="fc-cm-cell" title="${esc(`${n}, ${OFFICE[k]}: ${o ? `22 October ${p(o)}` : ""}${o && f ? "; " : ""}${f ? `final ${p(f)}` : ""}`)}">
      <span class="fc-cm-line"><span class="fc-cmp-track"></span><i style="left:50%"></i>${o && f ? `<span class="fc-cm-join" style="left:${lo}%;width:${hi - lo}%"></span>` : ""}${o ? `<span class="fc-cmp-dot is-oct" style="left:${o.p_dem * 100}%"></span>` : ""}${f ? `<span class="fc-cmp-dot is-fin" style="left:${f.p_dem * 100}%"></span>` : ""}</span>
      <span class="fc-cm-num"><b>${txt}</b>${br ? `<span>${br}</span>` : ""}</span></span>`
  }
  const outs = chs.map(([k]) => { const o = cmpOutcome(k); return o == null ? "still counting" : `${WINS[o]} won` })
  return html`<div>
    <p class="fc-takeaway fc-lead">Each forecaster's chance that Democrats would win each chamber: the open dot on 22 October, when this forecast was fixed, and the filled dot its final number before the election. The Brier score is for the final number: 0 is perfect and 0.25 is what a 50–50 guess would get.</p>
    <div class="fc-cm" role="table" aria-label="Chance Democrats win each chamber, by forecaster, on 22 October and at the end">
      <div class="fc-cm-row fc-cm-head" role="row"><span role="columnheader" class="fc-card-label">Forecaster</span>${chs.map(([k, l, what], i) => `<span role="columnheader" class="fc-cm-h"><b>${l}</b><span>Result: ${outs[i]}</span></span>`).join("")}</div>
      ${names.map(n => { const m = meta(n); return `<div class="fc-cm-row${n === V1 ? " is-me" : ""}" role="row"><span role="rowheader" class="fc-cmp-name"><b>${esc(n)}${m?.news_report ? " †" : ""}</b><span>${esc(n === V1 ? "Published 22 Oct; fixed" : m?.kind === "market" ? "Market price" : m?.kind === "rating" ? "Rating" : "Model")}</span></span>${chs.map(([k]) => cell(k, n)).join("")}</div>` }).join("")}
    </div>
    <div class="fc-legend fc-cm-key"><span class="fc-k"><span class="fc-kdot is-open"></span>22 October</span><span class="fc-k"><span class="fc-kdot"></span>Final, before the election</span><span class="fc-dim">Market prices are converted to chances; they are prices, not models. † From news reports; ~ an approximate figure.</span></div>
    ${(() => { const notes = chs.flatMap(([k]) => ["oct", "final"].flatMap(w => cmpBlock(k, w).control.filter(r => r.name !== "v1").map(r => ({...r, ch: OFFICE[k], w}))))
      return notes.length ? `<details class="fc-disclose fc-srcs"><summary>Sources for These Chances</summary><ul>${notes.map(r =>
        `<li><strong>${esc(nameOf(r.name))}</strong>, ${esc(r.ch)}, ${r.w === "oct" ? "22 October" : "final"}${r.kind === "market" ? " (market price)" : ""}: ${srcLink(r.source)}${r.captured ? `, ${esc(fmtWhen(r.captured))}` : ""}${r.news_report ? ", from news reports" : ""}.</li>`).join("")}</ul></details>` : "" })()}</div>`
}

Seat Totals

Code
{
  // one row per forecaster, one column per chamber: each cell a seat range, 22 October above and final below
  const chs = [["senate", "Senate", [45, 58, 51]], ["house", "House", [205, 280, 218]], ["governor", "Governors", [20, 32, 26]]]
  const per = Object.fromEntries(chs.map(([k]) => [k, {oct: cmpSeats(k, "oct"), fin: cmpSeats(k, "final")}]))
  const names = [...new Set(chs.flatMap(([k]) => [...per[k].oct, ...per[k].fin].map(r => r.name)))].sort((a, b) => (b === V1) - (a === V1))
  const desc = (r) => r.lo80 != null ? `${r.median} (${r.lo80}–${r.hi80})` : r.median != null ? `${r.median}` : "—"
  const bar = (r, X, cls) => r ? `<span class="fc-sm-bar ${cls}">${r.lo80 != null ? `<span class="fc-sb-band" style="left:${X(r.lo80)}%;width:${X(r.hi80) - X(r.lo80)}%"></span>` : ""}${r.median != null ? `<span class="fc-sb-med" style="left:${X(r.median)}%"></span>` : ""}</span>` : `<span class="fc-sm-bar ${cls}"></span>`
  const cell = (k, [lo, hi, maj], n) => {
    const X = v => ((Math.max(lo, Math.min(hi, v)) - lo) / (hi - lo) * 100).toFixed(2), x = chamberRes(k).dem_seats
    const o = per[k].oct.find(r => r.name === n), f = n === V1 ? null : per[k].fin.find(r => r.name === n)
    if (!o && !f) return `<span class="fc-cm-cell is-none"><span class="fc-dim fc-small">Not published</span></span>`
    return `<span class="fc-cm-cell"><span class="fc-sm" style="--maj:${X(maj - 0.5)}%;${x == null ? "" : `--res:${X(x)}%`}"><i class="fc-sb-maj"></i>${x == null ? "" : `<i class="fc-sb-res"></i>`}${bar(o, X, "is-oct")}${n === V1 ? "" : bar(f, X, "is-fin")}</span>
      <span class="fc-cm-num"><b>${desc(f ?? o)}</b>${o && f && desc(o) !== desc(f) ? `<span>22 Oct: ${desc(o)}</span>` : ""}</span></span>`
  }
  const res = chs.map(([k, l, [lo, hi, maj]]) => { const r = chamberRes(k); return `${r.dem_seats == null ? "Still counting" : `Result: ${r.dem_seats}${r.complete ? "" : " so far"}`} · ${maj} for ${k === "governor" ? "a majority" : "control"}` })
  return html`<div>
    <p class="fc-takeaway">Each forecaster's median or projected number of Democratic seats (governors for the governors' races), with its 80% range where one was published. The black line is the result so far; the dashed line, the number needed.</p>
    <div class="fc-cm fc-cm-seats" role="table" aria-label="Seat forecasts by forecaster and chamber">
      <div class="fc-cm-row fc-cm-head" role="row"><span role="columnheader" class="fc-card-label">Forecaster</span>${chs.map(([k, l], i) => `<span role="columnheader" class="fc-cm-h"><b>${l}</b><span>${res[i]}</span></span>`).join("")}</div>
      ${names.map(n => `<div class="fc-cm-row${n === V1 ? " is-me" : ""}" role="row"><span role="rowheader" class="fc-cmp-name"><b>${esc(n)}</b></span>${chs.map(([k, , sc]) => cell(k, sc, n)).join("")}</div>`).join("")}
    </div>
    <div class="fc-legend fc-cm-key"><span class="fc-k"><span class="fc-kbar is-oct"></span>22 October</span><span class="fc-k"><span class="fc-kbar is-fin"></span>Final</span><span class="fc-dim">Numbers shown are the final ones, with 22 October beneath where it differed.</span></div></div>`
}

Race by Race

Code
{
  // the competitive races in all three chambers in one table, grouped by chamber; each cell the 22 October call, with the final call beneath where it changed
  const chs = [["senate", "Senate"], ["governor", "Governors"], ["house", "House"]]
  const grids = chs.map(([k, l]) => ({k, l, oct: cmpGrid(k, "oct"), fin: cmpGrid(k, "final")}))
  const names = [...new Set(grids.flatMap(g => g.oct.names))]
  const hidden = [...new Set(grids.flatMap(g => g.oct.hidden))]
  const kinds = new Map(names.map(n => [n, (grids.map(g => kindOf(n, g.oct.block)).find(Boolean))]))
  names.sort((a, b) => d3.ascending(KIND_ORDER[kinds.get(a)] ?? 9, KIND_ORDER[kinds.get(b)] ?? 9))
  const chart = new Set(grids.flatMap(g => g.oct.block.races.filter(r => r.read_from_chart).map(r => r.forecaster)))
  const one = (c, x) => {
    const lost = x.called && c.fav && c.fav !== x.winner
    return `<span class="fc-cg${c.fav ? "" : " is-even"}${lost ? " is-lost" : ""}" style="${c.fav ? `background:${c.fav === "R" ? "#e0a59c" : "#9fb1c8"}` : ""}" title="${esc(`${c.text}${lost ? ": this forecaster's favourite lost" : ""}`)}">${esc(c.text)}${lost ? `<span class="visually-hidden"> (favourite lost)</span>` : ""}</span>`
  }
  const cell = (c, cf, x, isHidden) => {
    if (isHidden) return `<td class="fc-cg-none"><span class="fc-dim fc-small">Not public</span></td>`
    if (!c && !cf) return `<td class="fc-cg-none"><span class="fc-dim">—</span></td>`
    const changed = cf && c && cf.text !== c.text
    return `<td>${one(c ?? cf, x)}${changed ? `<span class="fc-cg-fin">Final ${esc(cf.text)}</span>` : ""}</td>`
  }
  const winner = (x) => x.called ? `<span class="fc-chip" style="--chip:${PARTY[x.winner].colour}">${WIN[x.winner]}</span>` : `<span class="fc-stampr is-count">Counting</span>`
  const label = (x) => x.race ? `${NAME[x.state]}${isSpecial(x.race) ? " (Special)" : ""}` : x.id
  const body = grids.map(g => {
    const finBy = new Map(g.fin.rows.map(r => [r.x.id, r]))
    const rows = g.oct.rows
    if (!rows.length) return ""
    return `<tr class="fc-cg-group"><th scope="rowgroup" colspan="${names.length + 3}">${g.l} <span>${rows.length} competitive</span></th></tr>` + rows.map(r => {
      const fr = finBy.get(r.x.id)
      return `<tr><th scope="row">${label(r.x)}</th><td>${winner(r.x)}</td><td>${one(r.v1, r.x)}</td>${names.map(n => {
        const i = g.oct.names.indexOf(n), j = fr ? g.fin.names.indexOf(n) : -1
        const c = i >= 0 ? r.cells[i] : null, cf = j >= 0 ? fr.cells[j] : null
        return cell(c?.kind === "hidden" ? null : c, cf?.kind === "hidden" ? null : cf, r.x, hidden.includes(n) && !(c && c.kind !== "hidden"))
      }).join("")}</tr>` }).join("")
  }).join("")
  const head = (n) => `<th scope="col"><span class="fc-th">${esc(nameOf(n))}${chart.has(n) ? " §" : ""}${hidden.includes(n) ? " †" : ""}</span><span class="fc-th-kind">${KIND[kinds.get(n)] ?? ""}</span></th>`
  return html`<div>
    <p class="fc-takeaway">The competitive races, where at least one forecast gave the favourite under 85%, closest first within each chamber. Each cell is the forecaster's call on 22 October, with its final call beneath where it changed; a black outline marks a favourite who lost.</p>
    <div class="fc-tbl"><div class="fc-tbl-scroll fc-cg-scroll is-tall"><table class="fc-cgrid"><caption class="visually-hidden">Race-by-race calls by forecaster</caption>
      <thead><tr><th scope="col"><span class="fc-th">Race</span></th><th scope="col"><span class="fc-th">Winner</span></th><th scope="col"><span class="fc-th fc-ink">${V1}</span><span class="fc-th-kind">Model</span></th>${names.map(head).join("")}</tr></thead>
      <tbody>${body}</tbody></table></div></div>
    <p class="fc-note">Probabilities and prices as chances for the favourite; ratings as published.${chart.size ? ` § ${[...chart].join(", ")}: read from chart images on archived pages.` : ""}${hidden.length ? ` † ${hidden.join(", ")}: race-by-race numbers are not public (paywalled).` : ""}</p></div>`
}

How Each Forecaster Scored

Code
{
  // Brier by chamber for each forecaster, on the called races it shared with this forecast; 22 October and final as two lines
  const chs = [["senate", "Senate"], ["house", "House"], ["governor", "Governors"]]
  const sc = Object.fromEntries(chs.map(([k]) => [k, {oct: cmpScores(k, "oct"), fin: cmpScores(k, "final")}]))
  const names = [...new Set(chs.flatMap(([k]) => [...sc[k].oct, ...sc[k].fin].filter(r => r.n > 0).map(r => r.name)))]
  if (!names.length) return html`${placeholder("Not Yet Scored", "No called race is covered by another forecaster yet.")}`
  const kindOfName = (n) => chs.map(([k]) => [...sc[k].oct, ...sc[k].fin].find(r => r.name === n)?.kind).find(Boolean)
  const val = (k, w, n) => { const r = sc[k][w].find(r => r.name === n && r.n > 0); return r ? r : null }
  const line = (r) => r ? `${num(r.brier, 3)}<span class="fc-sub">This forecast ${num(r.v1_brier, 3)} · ${r.n} races</span>` : `<span class="fc-dim">—</span>`
  const better = (r) => r && r.brier != null && r.v1_brier != null ? (r.brier < r.v1_brier ? " is-better" : r.brier > r.v1_brier ? " is-worse" : "") : ""
  const table = (list, title) => `<h3 class="fc-sch">${title}</h3>
    <div class="fc-tbl"><div class="fc-tbl-scroll fc-cg-scroll"><table class="fc-sctbl"><caption class="visually-hidden">${title}</caption>
      <thead><tr><th scope="col"><span class="fc-th">Forecaster</span></th><th scope="col"><span class="fc-th">When</span></th>${chs.map(([, l]) => `<th scope="col" class="fc-num"><span class="fc-th">${l} Brier</span></th>`).join("")}</tr></thead>
      <tbody>${list.map(n => ["oct", "fin"].map((w, i) => { const any = chs.some(([k]) => val(k, w, n)); if (!any) return ""
        return `<tr${i ? ' class="fc-sc-fin"' : ""}>${i === 0 || !chs.some(([k]) => val(k, "oct", n)) ? `<th scope="row" rowspan="${chs.some(([k]) => val(k, "oct", n)) && chs.some(([k]) => val(k, "fin", n)) ? 2 : 1}">${esc(nameOf(n))}<span class="fc-sub">${KIND[kindOfName(n)] ?? ""}</span></th>` : ""}<td class="fc-dim fc-small">${w === "oct" ? "22 Oct" : "Final"}</td>${chs.map(([k]) => { const r = val(k, w, n); return `<td class="fc-num${better(r)}">${line(r)}</td>` }).join("")}</tr>` }).join("")).join("")}</tbody></table></div></div>`
  const probs = names.filter(n => !["rating", "margin"].includes(kindOfName(n))), rats = names.filter(n => kindOfName(n) === "rating")
  return html`<div>
    <p class="fc-takeaway">Each forecaster is scored only on the called races it covered, with this forecast's score on the same races beneath, so each pair is like for like. Lower is better; a score in bold beat this forecast on those races.</p>
    ${probs.length ? table(probs, "Models and Markets") : ""}${rats.length ? table(rats, "Ratings, Converted to Chances ‡") : ""}
    <p class="fc-note">Brier score: the mean squared gap between each chance and the result. ‡ Ratings converted with a stated mapping: ${Object.entries(RATING_P).map(([k, v]) => `${k} ${Math.round(v * 100)}%`).join(", ")}.</p>
    ${(cmpSrc.missing ?? []).length ? `<details class="fc-disclose fc-srcs"><summary>Forecasts Not Included</summary><ul>${cmpSrc.missing.map(x => `<li><strong>${esc(x.forecaster)}</strong>, ${esc(x.what)}: ${esc(x.why)}.</li>`).join("")}</ul></details>` : ""}</div>`
}

National Turnout

Code
{
  const actual = results.turnout?.national ?? null
  const lo = national.turnout_2026_lo80, hi = national.turnout_2026_hi80, med = national.turnout_2026_median
  const X = v => ((v - 0.40) / 0.16 * 100).toFixed(2)
  return html`<div>
    <p class="fc-takeaway fc-lead">The forecast expected ${share(med)} of adult citizens to vote, against ${share(TURNOUT_2022)} in 2022, and between ${(lo * 100).toFixed(0)} and ${(hi * 100).toFixed(0)}% in 80% of simulations. ${actual == null ? "The national figure is still being counted." : `The result was ${share(actual)}, ${actual < lo || actual > hi ? "outside" : "inside"} that range.`}</p>
    <div class="fc-nat" role="img" aria-label="National turnout: forecast ${share(med)} with an 80% range of ${share(lo)} to ${share(hi)}; 2022 was ${share(TURNOUT_2022)}; result ${actual == null ? "still counting" : share(actual)}.">
      <span class="fc-nat-t"><span class="fc-nat-axis"></span><span class="fc-nat-band" style="left:${X(lo)}%;width:${X(hi) - X(lo)}%"></span>
        <span class="fc-nat-22" style="left:${X(TURNOUT_2022)}%"></span><span class="fc-nat-f" style="left:${X(med)}%"></span>${actual == null ? "" : `<span class="fc-nat-a" style="left:${X(actual)}%"></span>`}</span>
      <span class="fc-axis"><span>40%</span><span>48%</span><span>56%</span></span>
      <span class="fc-legend"><span class="fc-k"><span class="fc-k-f"></span>Forecast ${share(med)} (${(lo * 100).toFixed(0)} to ${(hi * 100).toFixed(0)})</span><span class="fc-k"><span class="fc-k-22"></span>2022: ${share(TURNOUT_2022)}</span><span class="fc-k"><span class="fc-k-a"></span>Result: ${actual == null ? "still counting" : share(actual)}</span></span>
    </div></div>`
}

Turnout Change by State

Code
{
  // the forecast change and the actual change side by side, one map each, on one colour scale
  const st = results.turnout?.states ?? {}
  const rows = turnoutStates.map(s => ({s: s.state, t22: s.turnout_2022, f: s.turnout_2026_median, a: st[s.state] ?? null}))
  const tcol = (d) => changeColour(Math.max(0, Math.min(1, (d * 100 + 6) / 12)))
  const sgn = (k) => k === 0 ? "0" : `${k > 0 ? "+" : "−"}${Math.abs(k)}`
  const cellsFor = (mode) => new Map(rows.map(r => {
    const d = mode === "actual" ? (r.a == null ? null : r.a - r.t22) : r.f - r.t22
    return [r.s, {id: r.s, fill: d == null ? null : tcol(d), status: d == null ? "count" : "", small: d == null ? "…" : sgn(Math.round(d * 100)),
      label: `${NAME[r.s]}: ${d == null ? "actual turnout still counting" : `${mode} change ${pts(d)} points from 2022`}`}]
  }))
  const have = rows.filter(r => r.a != null), up = rows.filter(r => r.f > r.t22).length
  const text = `Change in turnout from 2022 by state, in points: forecast on the left, actual on the right. The forecast expected a rise in ${up} of ${rows.length} states (counting DC)${have.length ? `; of the ${have.length} with near-final counts, turnout rose in ${have.filter(r => r.a > r.t22).length}.` : `; the right-hand map fills in as counts near final.`}`
  const map = (mode) => tileMap({cells: cellsFor(mode), label: `Tile map of turnout change from 2022 by state, ${mode}`})
  return html`<div><p class="fc-takeaway">${text}</p>
    <div class="fc-turn2"><div><span class="fc-card-label fc-ink">Forecast Change</span>${map("forecast")}</div><div><span class="fc-card-label fc-ink">Actual Change</span>${map("actual")}</div></div>
    <div class="fc-legend fc-tiles-key"><span class="fc-grad"><span class="fc-card-label">Change in Points, 2022 to 2026</span><span class="fc-grad-bar" style="background:linear-gradient(90deg,${[0, 0.25, 0.5, 0.75, 1].map(t => changeColour(t)).join(",")})"></span><span class="fc-axis"><span>−6, Lower</span><span>+6, Higher</span></span></span>
      <span class="fc-k"><span class="is-count"></span>Still Counting</span></div></div>`
}
Code
html`<details class="fc-disclose fc-srcnote"><summary>About These Results</summary><div class="fc-src3">
  <div><b>The Forecast.</b> Published and fixed on 22 October 2026 (release v1). Nothing in this view changes it; the results are shown against it.</div>
  <div><b>The Results.</b> ${esc(results.note ?? "Sources are listed with each race.")} Pulled at ${asOfText}.</div>
  <div><b>The Scoring.</b> Set out before the election: Brier score, calibration, interval coverage and seat percentiles, misses included. The full account is in <a href="/work/scorecard-2026/">the provisional scorecard</a>.</div>
</div></details>`
How to Read These Numbers

A 70% chance is not a prediction that something will happen. It means that in about seven of every ten simulated elections it did, and in three it did not. In the bars, the grey gap between the parties is the share of outcomes where neither wins outright, such as a 25–25 split of governorships or independents holding the balance in the Senate.

Using This Forecast

For Everyone

  • It is a forecast, not a prediction of a single outcome. Each number is the share of 20,000 simulated elections in which that outcome happened.
  • Polls are included and weighted by how accurate they were in past cycles. Even so, the model’s ranges were a little too narrow in its 2018 and 2022 tests, so the most confident calls are probably overconfident.
  • It is published in advance and will be scored. This version is fixed in a dated, tagged release, and every forecast will be compared with the certified results after the election.

For Forecasters

The full tables are free to use as a baseline, with a manifest giving the input dates and file hashes.

  • Races: vote share, 80% interval and win chance, with and without polls
  • House districts and House seats
  • Senate seats and governor seats
  • County turnout and state turnout
  • Backtests and the manifest

The method, backtests and limits are set out in the full write-up.

Code
html`<details class="fc-disclose fc-credits"><summary>Photo Credits</summary>
  <p>Candidate photos come from Wikimedia Commons and are used under the licences below. Candidates without a freely licensed photo are shown by their initials.</p>
  <ul>${[...credits].sort((a, b) => d3.ascending(a.candidate, b.candidate)).map(c => `<li><strong>${esc(c.candidate)}</strong>:
    <a href="${esc(c.source_url)}">${esc(c.commons_file.replace(/^File:/, ""))}</a>, ${esc(c.author || "author not stated")},
    ${c.licence_url ? `<a href="${esc(c.licence_url)}">${esc(c.licence)}</a>` : esc(c.licence)}</li>`).join("")}</ul>
</details>`