import ChartFrame, { type LegendItem } from '../chart/ChartFrame' import { useEffect, useMemo, useState } from 'react' import { useQuery } from '@tanstack/react-query' import { geoPath } from 'd3-geo' import { feature } from 'topojson-client' import { fetchTopicLegislation, fetchTopicStateBills, type TopicLegislationResponse, type TopicStateBillsResponse } from '../../api/topicPolicy' import { STATES_ALBERS_TOPO, fetchTopo } from '../../lib/dotMatrix' import { STATE_FIPS_TO_CODE } from '../../utils/stateFips' import { STATE_CODE_TO_NAME } from '../../utils/stateMapping' import { NO_BILL_FILL, STATUS_FILL, STATUS_LABEL, STATUS_ORDER, countByCategory, countByStatus, shadeStates, yearSpan, type BillFilter, type StateShade, } from '../../utils/topicPolicy' import './storyCharts.css' interface Props { topic: string /** The page's active state scope (?state=), highlighted and opened by default. */ stateCode?: string scopeLabel: string subject: string } interface StateShape { code: string name: string d: string } // eslint-disable-next-line @typescript-eslint/no-explicit-any function toShapes(topo: any): StateShape[] { const fc = feature(topo, topo.objects.states) as unknown as { features: { id?: string | number; properties?: { name?: string } }[] } const path = geoPath() const out: StateShape[] = [] for (const f of fc.features) { const code = STATE_FIPS_TO_CODE[String(f.id ?? '').padStart(2, '0')] const d = path(f as never) if (code && d) out.push({ code, name: f.properties?.name ?? STATE_CODE_TO_NAME[code] ?? code, d }) } return out } const fmtDate = (iso: string | null) => iso ? new Date(`${iso}T00:00:00`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : null /** * State legislation map (#1274): each state coloured by the furthest any of its bills on the topic got (enacted, passed * one chamber, introduced and pending, or failed), from our OpenStates bills (public.topic_legislation_bill). A period * and a direction filter recolour the map; a state opens its bill list, each bill linked to its OpenStates page. Every * state with a bill is also in the list below the map, so nothing is reachable by colour or pointer alone. */ export default function LegislationMap({ topic, stateCode, scopeLabel, subject }: Props) { const q = useQuery({ queryKey: ['topic-legislation', topic], queryFn: () => fetchTopicLegislation(topic), staleTime: 10 * 60_000, retry: 1, }) const topo = useQuery({ queryKey: ['topo', STATES_ALBERS_TOPO], queryFn: () => fetchTopo(STATES_ALBERS_TOPO), staleTime: Infinity }) const shapes = useMemo(() => (topo.data ? toShapes(topo.data) : []), [topo.data]) const span = useMemo(() => (q.data ? yearSpan(q.data.summary) : null), [q.data]) const recentFrom = span ? Math.max(span[0], span[1] - 1) : null const [period, setPeriod] = useState<'recent' | 'all'>('recent') const [category, setCategory] = useState(null) const [picked, setPicked] = useState(null) const [hover, setHover] = useState(null) const filter: BillFilter = { sinceYear: period === 'recent' ? recentFrom : null, category } const shades = useMemo(() => (q.data ? shadeStates(q.data.summary, filter) : []), [q.data, filter.sinceYear, filter.category]) // eslint-disable-line react-hooks/exhaustive-deps const catCounts = useMemo(() => (q.data ? countByCategory(q.data.summary, filter.sinceYear) : new Map()), [q.data, filter.sinceYear]) const byCode = useMemo(() => new Map(shades.map((s) => [s.state_code, s])), [shades]) const counts = countByStatus(shades) const billCount = shades.reduce((n, s) => n + s.bills, 0) // The page's scoped state opens by default; 'none' means the reader closed it. A new scope resets the choice. useEffect(() => setPicked(null), [stateCode]) const open = picked === 'none' ? null : (picked ?? stateCode ?? null) const openShade = open ? byCode.get(open) : undefined const hoverShade = hover ? byCode.get(hover) : undefined const title =

State bills on {subject} · {scopeLabel === 'National' ? 'every state' : `${scopeLabel} highlighted`}

if (q.isLoading) { return (
{title}

Loading state bills…

) } if (q.isError || !q.data) { return (
{title}

State bills could not be loaded right now.

) } if (!q.data.available || q.data.total_bills === 0) { return (
{title}

No state bills on {subject} in our OpenStates data yet.

) } const periodLabel = period === 'recent' && recentFrom && span ? `${recentFrom}–${span[1]}` : span ? `${span[0]}–${span[1]}` : 'all years' const cats = q.data.categories.filter((c) => c.bills > 0) const toggle = (code: string) => setPicked(open === code ? 'none' : code) const describe = (s: StateShade | undefined, code: string) => s ? `${s.state ?? STATE_CODE_TO_NAME[code] ?? code}: ${STATUS_LABEL[s.status].toLowerCase()} (${s.bills.toLocaleString('en-US')} bill${s.bills === 1 ? '' : 's'})` : `${STATE_CODE_TO_NAME[code] ?? code}: no bill in this view` // Title and key (#1409): the takeaway from the real bill counts; the key uses the same fills the states are drawn with. const furthest = STATUS_ORDER.find((st) => counts[st] > 0) const frameTitle = `${billCount.toLocaleString('en-US')} state bill${billCount === 1 ? '' : 's'} on ${subject} in ${shades.length} state${shades.length === 1 ? '' : 's'}${ furthest && counts[furthest] > 0 ? `; ${counts[furthest]} ${counts[furthest] === 1 ? 'state' : 'states'} ${STATUS_LABEL[furthest].toLowerCase()}` : '' } · ${periodLabel}` const legend: LegendItem[] = [ ...STATUS_ORDER.map((st) => ({ key: st, label: `${STATUS_LABEL[st]} (${counts[st]})`, color: STATUS_FILL[st] })), { key: 'none', label: 'No bill in this view', color: NO_BILL_FILL }, ] return (
{(['recent', 'all'] as const).map((p) => ( ))}

{billCount.toLocaleString('en-US')} bill{billCount === 1 ? '' : 's'} in {shades.length} state {shades.length === 1 ? '' : 's'}, {periodLabel} {category ? `, ${(cats.find((c) => c.category === category)?.label ?? category).toLowerCase()}` : ''}.

{topo.isError ? (

The map shapes could not be loaded; the state list below has every bill.

) : ( {shapes.map((s) => { const shade = byCode.get(s.code) const isOpen = open === s.code return ( setHover(s.code)} onMouseLeave={() => setHover((h) => (h === s.code ? null : h))} onFocus={() => setHover(s.code)} onBlur={() => setHover((h) => (h === s.code ? null : h))} onClick={() => shade && toggle(s.code)} onKeyDown={(e) => { if (shade && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault() toggle(s.code) } }} > {describe(shade, s.code)} ) })} )}
{openShade && ( setPicked('none')} /> )} {open && !openShade && (

{STATE_CODE_TO_NAME[open] ?? open} has no bill on {subject} in this view.

)}
Every state with a bill ({shades.length})
    {[...shades] .sort((a, b) => STATUS_ORDER.indexOf(a.status) - STATUS_ORDER.indexOf(b.status) || a.state_code.localeCompare(b.state_code)) .map((s) => (
  • ))}

From our copy of OpenStates: state bills whose subject tags, title or abstract name {subject}. Colour is the furthest any bill got, from its own recorded actions. Direction comes from keyword rules on the title and abstract; a bill whose text doesn't say which way is counted as “direction not stated” and shown by status only. Omnibus bills that never name the topic in their title or abstract are missed.

) } function StateBills({ topic, shade, filter, cats, onClose, }: { topic: string shade: StateShade filter: BillFilter cats: TopicLegislationResponse['categories'] onClose: () => void }) { const q = useQuery({ queryKey: ['topic-state-bills', topic, shade.state_code, filter.sinceYear, filter.category], queryFn: () => fetchTopicStateBills(topic, shade.state_code, filter), staleTime: 10 * 60_000, retry: 1, }) const catLabel = new Map(cats.map((c) => [c.category, c.label ?? c.category])) const name = shade.state ?? STATE_CODE_TO_NAME[shade.state_code] ?? shade.state_code const bills = q.data?.bills ?? [] return (

{name}: {shade.bills.toLocaleString('en-US')} bill{shade.bills === 1 ? '' : 's'}

{q.isLoading &&

Loading {name}'s bills…

} {q.isError &&

{name}'s bills could not be loaded right now.

} {q.data && q.data.matching > bills.length && (

Showing the first {bills.length.toLocaleString('en-US')} of {q.data.matching.toLocaleString('en-US')}: furthest along first, then newest.

)}
    {bills.map((b) => (
  • {STATUS_LABEL[b.status]} {' '} {catLabel.get(b.category) ?? b.category}
    {b.url ? ( {b.identifier} ) : ( b.identifier )} {b.session ? · {b.session} session : null} — {b.title}
    {b.last_action && (
    Last action{b.last_action_date ? ` ${fmtDate(b.last_action_date)}` : ''}: {b.last_action} {b.status === 'failed' && b.passed_a_chamber ? ' (it had passed one chamber)' : ''}
    )}
  • ))}
) }