import { useMemo, useState } from 'react' import { createPortal } from 'react-dom' import { HOUSE_STYLE } from '../../utils/houseTheme' import { allocateWaffleCells, type WaffleCategory } from '../../utils/waffleGrid' import { Tooltip, useTooltip } from '../matrix/Tooltip' import ChartFrame from '../chart/ChartFrame' import { useChartReveal } from './useChartReveal' import './storyCharts.css' interface Props { categories: WaffleCategory[] title: string unitLabel?: string /** Optional key that replays the sequential box wave when scope changes. */ replayKey?: string } const fmt = (n: number) => n.toLocaleString('en-US') /** * 10x10 proportion waffle chart (#1400, ported from vizjb12 ยง4.8A): 100 rounded boxes filled from bottom-left, * with sequential entrance wave, interactive category spotlighting (dims others to `--neutral-data`), a bold headline * percentage stat readout, and `[data-box]` marks so its 100 boxes participate in cross-screen particle flights. */ export default function BoxWaffleChart({ categories, title, unitLabel = 'records', replayKey }: Props) { const { cells, shares, total } = useMemo(() => allocateWaffleCells(categories, 10), [categories]) const { ref: revealRef, revealed, reduced } = useChartReveal(replayKey ?? `${title}|${total}`) const { bind, tip, hide } = useTooltip() const [hovered, setHovered] = useState(null) const [pinned, setPinned] = useState(null) if (total <= 0 || cells.length === 0) return null const activeKey = hovered ?? pinned const topShare = shares.reduce((best, s) => (s.count > best.count ? s : best), shares[0]!) const lead = (activeKey ? shares.find((s) => s.key === activeKey) : null) ?? topShare const leadPct = Math.round(lead.pct) const cellSize = 18 const gap = 3.5 const step = cellSize + gap const gridPx = 10 * step - gap const cellsByKey = new Map(shares.map((s) => [s.key, s.cells])) const legend = (
{shares.map((s) => { const on = pinned === s.key const active = activeKey === s.key return ( ) })}
) const topPct = Math.round(topShare.pct) const frameTitle = `${title}: ${topShare.label} is the largest share, ${topPct}% of ${fmt(total)} ${unitLabel}` return (
{leadPct}% {lead.label} {fmt(lead.count)} of {fmt(total)} {unitLabel}
{ setHovered(null) hide() }} > {cells.map((c) => { const dimmed = activeKey != null && activeKey !== c.categoryKey const delay = reduced ? 0 : c.index * 5 const b = bind({ cat: c.label, val: `${Math.round(c.sharePct)}% (${cellsByKey.get(c.categoryKey) ?? 0} of 100 boxes)`, sub: `${fmt(c.count)} of ${fmt(total)} ${unitLabel}`, }) return ( { setHovered(c.categoryKey) b.onPointerEnter(e) }} onPointerMove={b.onPointerMove} onPointerLeave={b.onPointerLeave} onClick={() => setPinned((p) => (p === c.categoryKey ? null : c.categoryKey))} /> ) })}
{typeof document !== 'undefined' && createPortal(
, document.body)}
) }