import { useMemo, useRef, useState } from 'react' import { CENSUS_REGION_LABEL, type CensusRegionId } from '../../utils/censusRegions' import { niceScale } from '../../utils/matrixMapMath' import { columnsStory } from '../../utils/matrixStory' import { stackByRegion } from '../../utils/matrixTable' import { useElementWidth, useFitHeight, useSection, useSeries } from './hooks' import LegendChips from './LegendChips' import { Empty, Seg } from './parts' import SectionShell from './SectionShell' import { Tooltip, useTooltip } from './Tooltip' import type { MatrixCtx } from './types' const REGIONS = Object.keys(CENSUS_REGION_LABEL) as CensusRegionId[] type Mode = 'abs' | 'share' /** Stacked columns: one per vintage, stacked by Census region. Only for metrics that can be summed (counts). */ export default function ColumnsSection({ ctx }: { ctx: MatrixCtx }) { const { metricSlug: slug, metrics, vintages } = ctx const isCount = metrics.find((m) => m.slug === slug)?.format === 'count' const [mode, setMode] = useState('abs') const sv = useSeries(ctx, 'columns', REGIONS) const pending = vintages.some((v) => ctx.rowsByVintage[v] === undefined) const data = useMemo( () => stackByRegion( vintages.map((v) => ({ vintage: v, items: (ctx.rowsByVintage[v] ?? []).map((r) => ({ region: r.region, value: r.vals[slug] ?? null })), })), REGIONS, ), [vintages, ctx.rowsByVintage, slug], ) const have = new Set(vintages.filter((v) => ctx.rowsByVintage[v])) const shown = REGIONS.filter((id) => sv.on(id)) /** Per vintage: the value drawn for each shown region (a count, or its share of the shown regions' total). */ const cols = data.map((d) => { const sum = shown.reduce((a, id) => a + (d.byRegion[id] ?? 0), 0) const any = shown.some((id) => d.byRegion[id] != null) return { d, sum: any ? sum : null, draw: Object.fromEntries( shown.map((id) => { const v = d.byRegion[id] return [id, v == null ? null : mode === 'share' ? (sum > 0 ? (v / sum) * 100 : null) : v] }), ) as Record, } }) const fmtShare = (v: number | null) => (v == null ? '—' : `${v.toFixed(1)}%`) const firstCol = cols.find((c) => c.sum != null) const lastCol = [...cols].reverse().find((c) => c.sum != null) const story = pending ? { headline: `${ctx.metricLabel} by Census region.`, lead: null } : columnsStory({ metricLabel: ctx.metricLabel, isCount, vintage: lastCol?.d.vintage ?? null, regions: shown.map((id) => ({ label: CENSUS_REGION_LABEL[id], value: lastCol?.d.byRegion[id] ?? null })), }) let body: React.ReactNode if (!isCount) { const alt = ctx.countMetrics[0] body = (

This metric can't be stacked. {ctx.metricLabel} is a {metrics.find((m) => m.slug === slug)?.format ?? 'non-count'} measure, so adding it up across states would not mean anything. Columns are shown only for counts.

{alt && (

)}
) } else if (pending) body = Loading vintages… else if (!cols.some((c) => c.sum != null)) body = No data available for {ctx.metricLabel} in any vintage. else body = return (

One column per published vintage, stacked by Census region. Each segment is the sum of the states with a value; a region with no value in a vintage is left out of that column, never counted as zero. “Share of total” rescales every column to 100%.

{isCount && firstCol && lastCol && (

Total of the regions shown: {ctx.fmt(slug, firstCol.sum)} in {firstCol.d.vintage} {lastCol !== firstCol ? ` and ${ctx.fmt(slug, lastCol.sum)} in ${lastCol.d.vintage}` : ''}. The state count per region can differ between vintages; hover a column for it.

)} } controls={ isCount ? ( setMode(v as Mode)} options={[ { value: 'abs', label: 'Absolute' }, { value: 'share', label: 'Share of total' }, ]} /> ) : undefined } caption={ isCount ? ( <> {ctx.metricLabel} summed by Census region, one column per vintage; {shown.length} of {REGIONS.length} regions shown,{' '} {mode === 'abs' ? 'absolute' : 'share of the shown total'}. Source: ACS 5-year. ) : ( <>Nothing is drawn: {ctx.metricLabel} is not a count and cannot be summed across states. ) } table={() => isCount && !pending ? { columns: [{ label: 'Vintage' }, ...shown.map((id) => ({ label: CENSUS_REGION_LABEL[id], numeric: true })), { label: mode === 'abs' ? 'Total' : 'Total (share)', numeric: true }], rows: cols.map((c) => [ c.d.vintage, ...shown.map((id) => (mode === 'abs' ? ctx.fmt(slug, c.d.byRegion[id] ?? null) : fmtShare(c.draw[id] ?? null))), mode === 'abs' ? ctx.fmt(slug, c.sum) : c.sum == null ? '—' : '100.0%', ]), } : null } > {body}
) } function ColumnChart({ ctx, cols, shown, mode, sv, have, fmtShare, }: { ctx: MatrixCtx cols: Array<{ d: ReturnType[number]; sum: number | null; draw: Record }> shown: CensusRegionId[] mode: Mode sv: ReturnType have: Set fmtShare: (v: number | null) => string }) { const { seen } = useSection() const revealed = seen || ctx.reduced const host = useRef(null) const w = useElementWidth(host) const tt = useTooltip() const [cross, setCross] = useState(null) const refs = useRef>([]) const slug = ctx.metricSlug const padL = 56 const padR = 12 const padT = 34 const padB = 44 const h = useFitHeight(360, 400) const plotW = w - padL - padR const plotH = h - padT - padB const maxSum = Math.max(0, ...cols.map((c) => c.sum ?? 0)) const sc = mode === 'share' ? { min: 0, max: 100, ticks: [0, 25, 50, 75, 100] } : niceScale(0, maxSum, 4, true) const yOf = (v: number) => padT + plotH - ((v - sc.min) / (sc.max - sc.min || 1)) * plotH const slot = plotW / cols.length const barW = Math.max(18, Math.min(48, slot * 0.68)) const compact = slot < 36 const hot = sv.hot return (
({ key: id, label: CENSUS_REGION_LABEL[id], color: ctx.theme.series[i]! }))} off={sv.off} onToggle={sv.toggle} onHot={sv.setHot} />

{ctx.metricLabel} by Census region, {mode === 'abs' ? 'absolute' : 'share of total'}

{ tt.hide(); setCross(null) }}> {sc.ticks.map((t) => ( {mode === 'share' ? `${t}%` : ctx.fmt(slug, t)} ))} {cols.map((c, idx) => { const cx = padL + slot * idx + slot / 2 const x0 = cx - barW / 2 let acc = 0 const delay = ctx.reduced ? 0 : idx * 45 const total = c.sum return ( {REGIONS.map((id, ri) => { const on = shown.includes(id) const val = on ? c.draw[id] ?? null : null const y1 = yOf(acc + (val ?? 0)) const y0 = yOf(acc) if (val != null) acc += val const hh = val != null ? Math.max(0, y0 - y1) : 0 return ( ) })} {total == null ? '—' : mode === 'share' ? '100%' : ctx.fmt(slug, total)} {compact ? `’${c.d.vintage.slice(2)}` : c.d.vintage} {!have.has(c.d.vintage) && ( no file )} ) })} {cross != null && } {cols.map((c, idx) => { const cx = padL + slot * idx + slot / 2 const lines = shown.map((id) => `${CENSUS_REGION_LABEL[id]}: ${mode === 'abs' ? ctx.fmt(slug, c.d.byRegion[id] ?? null) : fmtShare(c.draw[id] ?? null)}${c.d.byRegion[id] != null ? ` (${c.d.counts[id]} states)` : ''}`) const info = { cat: `${ctx.metricLabel} · ${c.d.vintage}`, val: c.sum == null ? '—' : ctx.fmt(slug, c.sum), sub: lines.join(' | ') } return ( { refs.current[idx] = n }} x={padL + slot * idx} y={padT} width={slot} height={plotH} fill="transparent" tabIndex={0} role="img" aria-label={`${c.d.vintage}: total ${c.sum == null ? 'no data' : ctx.fmt(slug, c.sum)}. ${lines.join('; ')}`} onPointerEnter={(e) => { setCross(cx); tt.show(info, e) }} onPointerMove={(e) => tt.show(info, e)} onPointerLeave={() => { setCross(null); tt.hide() }} onFocus={(e) => { setCross(cx); tt.show(info, e.currentTarget) }} onBlur={() => { setCross(null); tt.hide() }} onKeyDown={(e) => { const n = refs.current.length if (e.key === 'ArrowRight') { e.preventDefault(); refs.current[(idx + 1) % n]?.focus() } else if (e.key === 'ArrowLeft') { e.preventDefault(); refs.current[(idx - 1 + n) % n]?.focus() } }} /> ) })}
) }