import { useRef, useState } from 'react' import { Link } from 'react-router-dom' import { CENSUS_REGION_LABEL, type CensusRegionId } from '../../utils/censusRegions' import { rowDelayMs } from '../../utils/folioMotion' import { scatterStory } from '../../utils/matrixStory' import { niceScale, olsFit } from '../../utils/matrixMapMath' import { useElementWidth, useFitHeight, useSeries } from './hooks' import LegendChips from './LegendChips' import { Empty } from './parts' import SectionShell from './SectionShell' import { Tooltip, useTooltip } from './Tooltip' import { delayVar, type MatrixCtx } from './types' const REGIONS = Object.keys(CENSUS_REGION_LABEL) as CensusRegionId[] /** Two metrics across states, coloured by Census region, with a live OLS line, slope and r². Legend chips toggle regions. */ export default function ScatterSection({ ctx }: { ctx: MatrixCtx }) { const xSlug = ctx.metricSlug const ySlug = ctx.sp.get('y') && ctx.metrics.some((m) => m.slug === ctx.sp.get('y')) ? ctx.sp.get('y')! : ctx.metrics.find((m) => m.slug !== xSlug)?.slug ?? '' const sv = useSeries(ctx, 'scatter', REGIONS) const [trend, setTrend] = useState(true) const host = useRef(null) const w = useElementWidth(host) const tt = useTooltip() const pts = ctx.rows .map((r) => ({ r, x: r.vals[xSlug] ?? null, y: r.vals[ySlug] ?? null })) .filter((p): p is { r: MatrixCtx['rows'][number]; x: number; y: number } => p.x != null && p.y != null) const vis = pts.filter((p) => sv.on(p.r.region ?? '')) const fit = olsFit(vis) const xl = ctx.labelOf(xSlug) const yl = ctx.labelOf(ySlug) const usable = !!ySlug && pts.length >= 3 const story = scatterStory({ xLabel: xl, yLabel: yl, n: fit?.n ?? vis.length, total: ctx.rows.length, fit: fit ? { slope: fit.slope, r2: fit.r2 } : null }) const H = useFitHeight(360, 505) const pad = { l: 64, r: 14, t: 12, b: 46 } const hot = sv.hot const xs = pts.map((p) => p.x) const ys = pts.map((p) => p.y) const sx = usable ? niceScale(Math.min(...xs), Math.max(...xs), 4) : null const sy = usable ? niceScale(Math.min(...ys), Math.max(...ys), 4) : null const X = (v: number) => pad.l + ((v - sx!.min) / (sx!.max - sx!.min || 1)) * (w - pad.l - pad.r) const Y = (v: number) => H - pad.b - ((v - sy!.min) / (sy!.max - sy!.min || 1)) * (H - pad.t - pad.b) const order = new Map(pts.map((p, i) => [p.r.fips, i])) return (

Each dot is one geography, placed by {xl.toLowerCase()} (across) and {yl.toLowerCase()} (up) and coloured by Census region. The dashed line is a least-squares fit through the dots shown; it updates as you hide regions with the legend chips.

{fit && (

Slope {fit.slope.toPrecision(3)}, r² {fit.r2.toFixed(2)}, n={fit.n}. A relationship in these data is not evidence that one metric causes the other.

)} } controls={ } caption={ <> {yl} against {xl}, one point per geography, coloured by Census region; {vis.length} points shown, {ctx.vintage} ACS 5-year. Source: ACS 5-year, {ctx.vintage}. } table={() => usable ? { columns: [{ label: 'Geography' }, { label: 'Region' }, { label: xl, numeric: true }, { label: yl, numeric: true }], rows: vis.map((p) => [p.r.name, p.r.region ? CENSUS_REGION_LABEL[p.r.region] : '—', ctx.fmt(xSlug, p.x), ctx.fmt(ySlug, p.y)]), } : null } > {!usable ? ( No data available — need at least 3 geographies with both metrics. ) : (
({ key: id, label: CENSUS_REGION_LABEL[id], color: ctx.theme.series[i]! }))} off={sv.off} onToggle={sv.toggle} onHot={sv.setHot} /> {sy!.ticks.map((t) => ( {ctx.fmt(ySlug, t)} ))} {sx!.ticks.map((t) => ( {ctx.fmt(xSlug, t)} ))} {xl} {yl} {fit && ( p.x)))} x2={X(Math.max(...vis.map((p) => p.x)))} y1={Y(fit.slope * Math.min(...vis.map((p) => p.x)) + fit.intercept)} y2={Y(fit.slope * Math.max(...vis.map((p) => p.x)) + fit.intercept)} stroke="var(--ink)" strokeWidth={1.5} strokeDasharray="5 4" style={{ opacity: trend ? 1 : 0, transition: 'opacity 180ms var(--ease-std)', pointerEvents: 'none' }} /> )} {pts.map((p) => { const ri = REGIONS.indexOf((p.r.region ?? '') as CensusRegionId) const on = sv.on(p.r.region ?? '') const info = { cat: p.r.name, val: `${ctx.fmt(xSlug, p.x)} / ${ctx.fmt(ySlug, p.y)}`, sub: `${xl} / ${yl}${p.r.region ? ` · ${CENSUS_REGION_LABEL[p.r.region]}` : ''}` } return ( = 0 ? ctx.theme.series[ri] : 'var(--ink-3)'} stroke="var(--ink)" strokeWidth={0.75} style={{ ...delayVar(rowDelayMs(order.get(p.r.fips) ?? 0, pts.length, 12, 500)), opacity: on ? (hot && hot !== p.r.region ? 0.2 : 0.9) : 0, transition: 'opacity var(--d-3) var(--ease-std)', }} {...tt.bind(info)} /> ) })}
)}
) }