import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react' import { createPortal } from 'react-dom' import { useQuery } from '@tanstack/react-query' import { fetchTopicTimeline, type TimelineMilestone, type TopicTimelineResponse } from '../../api/topicTimeline' import { buildSeries, dateToYearPos, defaultMarker, defaultSeriesMode, gapYears, isHollow, milestoneLanes, MILESTONE_LABELS, niceMax, splitRun, stepMarker, thinNote, thinYears, timelinePads, MIN_RECORDED_FOR_ZERO, type SeriesMode, } from '../../utils/storyTimeline' import { HOUSE_STYLE } from '../../utils/houseTheme' import { DataTable } from '../matrix/SectionShell' import { Tooltip, useTooltip } from '../matrix/Tooltip' import { useChartReveal } from './useChartReveal' import { useChartWidth } from './useChartWidth' import { pickYearTicks } from '../../utils/axisTicks' import './storyCharts.css' const fmt = (n: number) => n.toLocaleString('en-US') const COVERAGE_NOTE = 'Meetings in our record by year; recording coverage grew sharply in 2025–26, so the rise partly reflects coverage.' /** Below this width the milestone track becomes a tap list (the reference's compact breakpoint). */ const COMPACT_W = 560 const TAP_LIST_FIRST = 12 /** The line's draw-in, matching `--d-4` in storyCharts.css: points and milestones are timed against it. */ const DRAW_MS = 900 /** Delays for `.sc-pt` / `.sc-ms-pop` (opacity, transform, fill): the entrance waits, a selection's colour change never does. */ const popDelay = (ms: number) => `${ms}ms, ${ms}ms, 0ms` interface Props { topic: string stateCode?: string city?: string | null scopeLabel: string /** Lower-case subject for sentences ("data centers"). */ subject: string idBase: string } export function useTopicTimeline(topic: string, stateCode?: string, city?: string | null, enabled = true) { const c = stateCode && city ? city : '' return useQuery({ queryKey: ['topic-timeline', topic, stateCode ?? 'national', c], queryFn: () => fetchTopicTimeline(topic, stateCode, c || undefined), enabled, staleTime: 5 * 60_000, retry: 1, }) } function prettyDate(iso: string): string { const d = new Date(`${iso.slice(0, 10)}T12:00:00Z`) return Number.isNaN(d.getTime()) ? iso : d.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' }) } function MilestoneCard({ m }: { m: TimelineMilestone }) { const what = MILESTONE_LABELS[m.kind] const place = [m.place, m.state_code && m.place !== m.state_code ? m.state_code : null].filter(Boolean).join(', ') return (
{prettyDate(m.date)}

{what} {place ? ` · ${place}` : ''} {m.source === 'ai_reading' ? 'AI reading' : 'Official record'}

{m.title &&

{m.title}

}

{m.source === 'ai_reading' ? `What officials did with the item, as an AI (Jev) read the meeting transcript; not an official record.` : 'The bill as recorded by the state legislature (Open States).'}{' '} {m.url && ( {m.kind === 'bill_enacted' ? 'Open the bill' : 'Watch the meeting'} ↗ )}

) } /** * The Meetings screen's trend line (#1140, the reference's §4.5): meetings per year for the topic and scope, or the * topic's share of all recorded meetings, with an aligned milestone track underneath. A click or the arrow keys pick a * marker and the card below shows it; under 560px the markers become a tap list. A year with no data is a gap. */ export default function TimelineChart({ topic, stateCode, city, scopeLabel, subject, idBase }: Props) { const q = useTopicTimeline(topic, stateCode, city) const { ref, width } = useChartWidth() const { bind, tip } = useTooltip() // null until the reader picks: the chart opens on the share when a year's count isn't comparable (#1207). const [mode, setMode] = useState(null) const [sel, setSel] = useState(-1) const [tableOpen, setTableOpen] = useState(false) const [showAll, setShowAll] = useState(false) const trackRef = useRef(null) const listRef = useRef(null) const data = q.data const years = useMemo(() => data?.years ?? [], [data]) const ms = useMemo(() => data?.milestones ?? [], [data]) const shareOk = Boolean(data?.coverage_available) && years.some((y) => y.share != null) const thin = useMemo(() => thinYears(years), [years]) const openOn = useMemo(() => defaultSeriesMode(years, Boolean(data?.coverage_available)), [years, data]) const activeMode: SeriesMode = (mode ?? openOn) === 'share' && shareOk ? 'share' : 'meetings' const runs = useMemo(() => buildSeries(years, activeMode), [years, activeMode]) // Dashed pieces only on the count line: the share stays comparable in a thin year. const pieces = useMemo(() => runs.map((run) => splitRun(run, activeMode === 'meetings' ? thin : new Set())), [runs, activeMode, thin]) const gaps = useMemo(() => gapYears(years, activeMode), [years, activeMode]) const lanes = useMemo(() => milestoneLanes(ms), [ms]) useEffect(() => setSel(defaultMarker(ms)), [ms]) // The reference's §4.5 entrance (#1228): when the chart scrolls into view the line draws left to right, the year points // pop in as it passes them and the milestone squares follow along the track. A new series (scope or mode) replays it. const { ref: revealRef, revealed, reduced } = useChartReveal(runs) if (q.isLoading) return

Loading the timeline…

if (q.isError) return

The timeline could not be loaded right now.

const pts = runs.flat() if (!data || pts.length === 0) return null const w = Math.max(280, width) const h = 240 const { padL, padR } = timelinePads(w, ms.length > 0) const padT = 20 const padB = 28 const allYears = pts.map((p) => p.year) const msPos = ms.map((m) => dateToYearPos(m.date)).filter((v): v is number => v != null) const x0 = Math.min(...allYears, ...msPos.map(Math.floor)) const x1 = Math.max(...allYears, ...msPos.map(Math.floor)) const span = Math.max(1, x1 - x0 + 1) // A year's point sits at the middle of its year, so a milestone dated in that year lands under or near it. const xs = (pos: number) => padL + ((pos - x0) / span) * (w - padL - padR) const xYear = (y: number) => xs(y + 0.5) // How far along the plot an x is (0 at the left edge, 1 at the right), and when the drawing line reaches it. const alongFrac = (x: number) => Math.min(1, Math.max(0, (x - padL) / Math.max(1, w - padL - padR))) const alongMs = (x: number) => Math.round(alongFrac(x) * (DRAW_MS - 150)) const vmax = niceMax(Math.max(...pts.map((p) => p.value))) const ys = (v: number) => h - padB - (v / vmax) * (h - padT - padB) const ticks = [0, vmax / 2, vmax] // Year labels chosen by the room they have, so they never run together on a phone. const yearTicks = pickYearTicks(Array.from({ length: span }, (_, i) => x0 + i), w - padL - padR) const valueText = (v: number) => (activeMode === 'share' ? `${v < 10 ? v.toFixed(1) : Math.round(v)}%` : fmt(v)) const last = pts[pts.length - 1]! const compact = w < COMPACT_W const drawnYears = new Set(allYears) const thinDrawn = new Set([...thin].filter((y) => drawnYears.has(y))) const thinText = thinNote(years, thinDrawn) const hollowShare = activeMode === 'share' && pts.some((p) => isHollow(p, 'share', thin)) const pick = (i: number, focus = false) => { setSel(i) if (focus) { const host = compact ? listRef.current : trackRef.current requestAnimationFrame(() => host?.querySelector(`[data-ms="${i}"]`)?.focus()) } } const onMsKey = (e: KeyboardEvent) => { const to = stepMarker(sel, e.key, ms.length) if (to == null) return e.preventDefault() e.stopPropagation() if (compact && !showAll && to >= TAP_LIST_FIRST) setShowAll(true) pick(to, true) } const laneH = 26 const trackH = 16 + lanes.length * laneH // Newest first in the tap list. const tapOrder = ms.map((_, i) => i).reverse() const tapShown = showAll ? tapOrder : tapOrder.slice(0, TAP_LIST_FIRST) return (

{activeMode === 'share' ? `Share of recorded meetings that discussed ${subject}, by year` : `Meetings that discussed ${subject}, by year`} · {scopeLabel}

{shareOk && (
)}
{ticks.map((t) => ( {valueText(t)} ))} {yearTicks.map((y) => ( {y} ))} {pieces.flat().map((piece) => { const d = piece.points.map((p, i) => `${i ? 'L' : 'M'} ${xYear(p.year).toFixed(1)} ${ys(p.value).toFixed(1)}`).join(' ') return piece.dashed ? ( ) : ( ) })} {pts.map((p) => { const y = p.src const sub = [ y.passages != null ? `${fmt(y.passages)} passages` : null, y.all_recorded_meetings != null ? `of ${fmt(y.all_recorded_meetings)} recorded meetings` : null, y.share != null ? `${(y.share * 100).toFixed(1)}%` : null, ] .filter(Boolean) .join(' · ') const hollow = isHollow(p, activeMode, thin) const caveat = hollow ? activeMode === 'meetings' ? ' (few meetings were recorded that year: the count is not comparable)' : ` (fewer than ${MIN_RECORDED_FOR_ZERO} meetings recorded)` : '' const label = `${y.year}: ${fmt(y.meetings)} meetings${sub ? `, ${sub}` : ''}${caveat}` return ( ) })} {valueText(last.value)} {ms.length > 0 && !compact && ( {lanes.map((k, li) => { const y = 10 + li * laneH + laneH / 2 const n = ms.filter((m) => m.kind === k).length return ( {k === 'bill_enacted' ? 'Bills' : MILESTONE_LABELS[k].split(' ')[0]} · {n} ) })} {ms.map((m, i) => { const pos = dateToYearPos(m.date) if (pos == null) return null const li = lanes.indexOf(m.kind) const cx = xs(pos) const cy = 10 + li * laneH + laneH / 2 const on = i === sel const size = on ? 12 : 8 return ( pick(i)} onFocus={() => setSel(i)} > ) })} )} {ms.length > 0 && compact && (
{tapShown.map((i) => { const m = ms[i]! return ( ) })} {!showAll && tapOrder.length > TAP_LIST_FIRST && ( )}
)} {sel >= 0 && ms[sel] && }

{COVERAGE_NOTE} {activeMode === 'share' && ' The share divides by every recorded meeting in the same place and year.'} {thinText && (activeMode === 'meetings' ? ` ${thinText} ${thinDrawn.size === 1 ? 'It is drawn as a hollow point' : 'They are drawn as hollow points'} on a dashed line.` : ` ${thinText} The share of recorded meetings still compares, so the chart opens on it; Meetings shows the counts.`)} {hollowShare && ` A hollow point is a share of fewer than ${MIN_RECORDED_FOR_ZERO} recorded meetings.`} {gaps.length > 0 && ` No line is drawn for ${gaps.join(', ')}: too few recorded meetings to say.`} {data.undated_meetings > 0 && ` ${fmt(data.undated_meetings)} ${data.undated_meetings === 1 ? 'meeting has' : 'meetings have'} no date and ${data.undated_meetings === 1 ? 'is' : 'are'} not on the line.`} {ms.length > 0 && ' Milestones are meetings where officials approved, denied, tabled or paused the item, as an AI read the transcript'} {ms.length > 0 && (data.bills_available ? ', and state bills enacted.' : '.')}

{ms.length > 0 && !compact &&

Select a square on the track, then use the arrow keys to move between milestones.

} {tableOpen && ( [ y.year, fmt(y.meetings), y.passages != null ? fmt(y.passages) : '—', y.all_recorded_meetings != null ? fmt(y.all_recorded_meetings) : '—', y.share != null ? `${(y.share * 100).toFixed(1)}%` : '—', ]), }} /> )} {typeof document !== 'undefined' && createPortal(
, document.body)}
) }