{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tone-area-chart",
  "title": "ToneAreaChart",
  "description": "Area chart with rotated SVG screentone halftone bands, speech-balloon peak callout, keyboard navigation, and accessible data table.",
  "registryDependencies": [
    "https://frame12.dev/r/frame12-styles.json",
    "https://frame12.dev/r/use-on-twos.json",
    "https://frame12.dev/r/use-tempo.json"
  ],
  "files": [
    {
      "path": "ui/tone-area-chart.tsx",
      "content": "'use client';\n\nimport * as React from 'react';\nimport { type MotionMode, useOnTwos, useSize } from '@/hooks/use-on-twos';\n\nexport interface ToneAreaDatum {\n  label: string;\n  longLabel?: string;\n  value: number;\n  compareValue?: number;\n}\n\nexport interface ToneAreaAnnotation {\n  index: number;\n  text: string;\n}\n\nexport interface ToneAreaChartProps {\n  data: ToneAreaDatum[];\n  seriesLabel?: string;\n  compareLabel?: string;\n  labelColumnHeader?: string;\n  formatValue?: (v: number) => string;\n  formatShort?: (v: number) => string;\n  annotation?: ToneAreaAnnotation | null;\n  motion?: MotionMode;\n  height?: number;\n  tableSummary?: string;\n  showTable?: boolean;\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function defaultFormatValue(v: number): string {\n  const safe = Number.isFinite(v) ? v : 0;\n  return Math.round(safe).toLocaleString('en-US');\n}\n\nexport function defaultFormatShort(v: number): string {\n  const safe = Number.isFinite(v) ? v : 0;\n  if (Math.abs(safe) >= 1000) {\n    const k = safe / 1000;\n    return (Number.isInteger(k) ? k.toFixed(0) : k.toFixed(1)) + 'k';\n  }\n  return String(Math.round(safe));\n}\n\nexport function fmtCurrency(v: number): string {\n  const safe = Number.isFinite(v) ? v : 0;\n  const sign = safe < 0 ? '-' : '';\n  return sign + '$' + Math.round(Math.abs(safe)).toLocaleString('en-US');\n}\n\nexport function fmtCurrencyShort(v: number): string {\n  const safe = Number.isFinite(v) ? v : 0;\n  const sign = safe < 0 ? '-' : '';\n  const abs = Math.abs(safe);\n  if (abs >= 1000) {\n    const k = abs / 1000;\n    return sign + '$' + (Number.isInteger(k) ? k.toFixed(0) : k.toFixed(1)) + 'k';\n  }\n  return sign + '$' + Math.round(abs);\n}\n\nfunction niceStep(span: number, count: number): number {\n  if (!Number.isFinite(span) || span <= 0) return 1;\n  const raw = span / count;\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)));\n  const n = raw / mag;\n  const step = n <= 1 ? 1 : n <= 2 ? 2 : n <= 2.5 ? 2.5 : n <= 5 ? 5 : 10;\n  return step * mag;\n}\n\nconst TONE_BAND_RADII = [1.25, 1.05, 0.85, 0.62] as const;\n\nconst useIsoLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n\nexport function ToneAreaChart({\n  data,\n  seriesLabel = 'Value',\n  compareLabel,\n  labelColumnHeader = 'Label',\n  formatValue = defaultFormatValue,\n  formatShort = defaultFormatShort,\n  annotation,\n  motion = 'stepped',\n  height = 260,\n  tableSummary = 'Show data table',\n  showTable = true,\n  ariaLabel,\n  className = '',\n}: ToneAreaChartProps) {\n  const wrap = React.useRef<HTMLDivElement | null>(null);\n  const { w } = useSize(wrap);\n  const rawId = React.useId();\n  const uid = React.useMemo(() => 'c-' + rawId.replace(/:/g, ''), [rawId]);\n\n  const safeData = React.useMemo<ToneAreaDatum[]>(\n    () =>\n      data.map((d) => ({\n        ...d,\n        value: Number.isFinite(d.value) ? d.value : 0,\n        compareValue:\n          d.compareValue != null && Number.isFinite(d.compareValue) ? d.compareValue : undefined,\n      })),\n    [data],\n  );\n\n  const n = safeData.length;\n  const hasCompare = Boolean(compareLabel) && safeData.some((d) => d.compareValue != null);\n  const tweenKey = `${n}|${safeData[0]?.label ?? ''}|${safeData[n - 1]?.value ?? ''}|${compareLabel ?? ''}`;\n  const p = useOnTwos(tweenKey, 750, motion);\n  const [hover, setHover] = React.useState<number | null>(null);\n  const balloon = React.useRef<HTMLDivElement | null>(null);\n  const [bw, setBw] = React.useState<number>(0);\n\n  const pad = { l: 46, r: 14, t: 46, b: 28 };\n  const isMeasured = w > 0;\n  const W = isMeasured ? w : 680;\n  const H = height;\n  const iw = Math.max(1, W - pad.l - pad.r);\n  const ih = Math.max(1, H - pad.t - pad.b);\n\n  const allValues: number[] = [];\n  for (const d of safeData) {\n    allValues.push(d.value);\n    if (hasCompare && d.compareValue != null) {\n      allValues.push(d.compareValue);\n    }\n  }\n  const rawMax = allValues.length > 0 ? Math.max(...allValues) : 0;\n  const rawMin = allValues.length > 0 ? Math.min(...allValues) : 0;\n  const domainMax = Math.max(0, rawMax);\n  const domainMin = Math.min(0, rawMin);\n  const span = Math.max(1, domainMax - domainMin);\n  const step = niceStep(span, 4);\n  const top = domainMax > 0 ? Math.ceil(domainMax / step) * step : domainMin === 0 ? step : 0;\n  const bottom = domainMin < 0 ? -Math.ceil(Math.abs(domainMin) / step) * step : 0;\n  const totalSpan = Math.max(step, top - bottom);\n\n  const x = (i: number) => pad.l + (n <= 1 ? iw / 2 : (i / (n - 1)) * iw);\n  const y = (v: number) => pad.t + ih - ((v - bottom) / totalSpan) * ih;\n  const zeroY = y(0);\n\n  const line = (get: (d: ToneAreaDatum) => number) =>\n    safeData.map((d, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)},${y(get(d)).toFixed(1)}`).join('');\n\n  const totalPath = n > 0 ? line((d) => d.value) : '';\n  const areaPath =\n    n > 0\n      ? `${totalPath}L${x(n - 1).toFixed(1)},${zeroY.toFixed(1)}L${x(0).toFixed(1)},${zeroY.toFixed(1)}Z`\n      : '';\n  const focusPath = hasCompare && n > 0 ? line((d) => d.compareValue ?? 0) : null;\n\n  const ticks: number[] = [];\n  for (let v = bottom; v <= top + 1e-6; v += step) {\n    ticks.push(Math.abs(v) < 1e-9 ? 0 : v);\n  }\n\n  const pxPerDay = n > 1 ? iw / (n - 1) : iw;\n  const baseEvery = n <= 7 ? 1 : n <= 30 ? 7 : 14;\n  const labelEvery = Math.max(baseEvery, Math.ceil(84 / pxPerDay / baseEvery) * baseEvery);\n  const xLabels: number[] = [];\n  for (let i = n - 1; i >= 0; i -= labelEvery) xLabels.push(i);\n\n  const resolvedAnnotation = React.useMemo<ToneAreaAnnotation | null>(() => {\n    if (annotation === null || n === 0) return null;\n    if (annotation !== undefined) {\n      const idx = Math.max(0, Math.min(n - 1, annotation.index));\n      return { index: idx, text: annotation.text };\n    }\n    let peakI = 0;\n    for (let i = 1; i < n; i++) {\n      if (safeData[i].value > safeData[peakI].value) peakI = i;\n    }\n    const pk = safeData[peakI];\n    return {\n      index: peakI,\n      text: `Peak ${pk.label} · ${formatValue(pk.value)}`,\n    };\n  }, [annotation, safeData, formatValue, n]);\n\n  const peakI = resolvedAnnotation ? resolvedAnnotation.index : 0;\n  const peakPoint = safeData[peakI];\n  const px = peakPoint ? x(peakI) : 0;\n  const py = peakPoint ? y(peakPoint.value) : 0;\n\n  useIsoLayoutEffect(() => {\n    if (balloon.current) setBw(balloon.current.offsetWidth);\n  });\n\n  const onMove = (e: React.PointerEvent<SVGSVGElement>) => {\n    if (!wrap.current || n === 0) return;\n    const r = wrap.current.getBoundingClientRect();\n    const mx = e.clientX - r.left;\n    const i = n <= 1 ? 0 : Math.round(((mx - pad.l) / iw) * (n - 1));\n    setHover(Math.max(0, Math.min(n - 1, i)));\n  };\n\n  const onKey = (e: React.KeyboardEvent<SVGSVGElement>) => {\n    if (n === 0) return;\n    if (e.key === 'ArrowRight') {\n      setHover((h) => Math.min(n - 1, h == null ? n - 1 : h + 1));\n      e.preventDefault();\n    } else if (e.key === 'ArrowLeft') {\n      setHover((h) => Math.max(0, h == null ? n - 1 : h - 1));\n      e.preventDefault();\n    } else if (e.key === 'Escape') {\n      setHover(null);\n    }\n  };\n\n  const clipW = pad.l + iw * p + 5;\n  const hd = hover != null && safeData[hover] ? safeData[hover] : null;\n  const bLeft = W ? Math.max(pad.l, Math.min(px - bw / 2, W - pad.r - bw)) : 0;\n  const tailX = Math.min(Math.max(px, bLeft + 14), Math.max(bLeft + 14, bLeft + bw - 14));\n  const bTop = 6;\n  const bH = 28;\n  const showPeak = p >= 0.999 && hover == null && resolvedAnnotation != null;\n\n  const computedAriaLabel =\n    ariaLabel ??\n    `${seriesLabel}, ${n} points.${\n      peakPoint\n        ? ` Peak ${peakPoint.longLabel ?? peakPoint.label}, ${formatValue(peakPoint.value)}.`\n        : ''\n    }`;\n\n  return (\n    <div className={`f12-tone-area-chart${className ? ` ${className}` : ''}`}>\n      <div className=\"f12-chart\" ref={wrap} style={{ height: H }}>\n        {n > 0 && (\n          <svg\n            width={isMeasured ? W : '100%'}\n            height={H}\n            viewBox={`0 0 ${W} ${H}`}\n            preserveAspectRatio={isMeasured ? undefined : 'none'}\n            className=\"f12-chart-svg\"\n            role=\"img\"\n            aria-label={computedAriaLabel}\n            tabIndex={0}\n            onPointerMove={onMove}\n            onPointerLeave={() => setHover(null)}\n            onKeyDown={onKey}\n            onBlur={() => setHover(null)}\n          >\n            <defs>\n              <clipPath id={`${uid}-clip`}>\n                <rect x=\"0\" y=\"0\" width={clipW} height={H} />\n              </clipPath>\n              {TONE_BAND_RADII.map((radius, b) => (\n                <React.Fragment key={b}>\n                  <pattern\n                    id={`${uid}-tone-${b}`}\n                    width=\"5\"\n                    height=\"5\"\n                    patternUnits=\"userSpaceOnUse\"\n                    patternTransform=\"rotate(45)\"\n                  >\n                    <circle cx=\"2.5\" cy=\"2.5\" r={radius} className=\"f12-tone-dot\" />\n                  </pattern>\n                  <clipPath id={`${uid}-band-${b}`}>\n                    <rect\n                      x=\"0\"\n                      y={pad.t + (ih * b) / TONE_BAND_RADII.length}\n                      width={W}\n                      height={ih / TONE_BAND_RADII.length + 0.5}\n                    />\n                  </clipPath>\n                </React.Fragment>\n              ))}\n            </defs>\n\n            {ticks.map((v) => (\n              <g key={v} className=\"f12-ytick\">\n                <line\n                  x1={pad.l}\n                  x2={W - pad.r}\n                  y1={y(v)}\n                  y2={y(v)}\n                  className={v === 0 ? 'f12-baseline' : 'f12-grid'}\n                />\n                <text x={pad.l - 8} y={y(v)} dy=\"0.35em\" textAnchor=\"end\">\n                  {formatShort(v)}\n                </text>\n              </g>\n            ))}\n\n            <g className=\"f12-sheet-ticks\" aria-hidden=\"true\">\n              {safeData.map(\n                (_, i) =>\n                  (n <= 30 || i % 3 === 0) && (\n                    <line\n                      key={i}\n                      x1={x(i)}\n                      x2={x(i)}\n                      y1={y(bottom)}\n                      y2={y(bottom) + (xLabels.includes(i) ? 7 : 3.5)}\n                    />\n                  ),\n              )}\n            </g>\n\n            {xLabels.map((i) => (\n              <text\n                key={i}\n                className=\"f12-xlab\"\n                x={x(i)}\n                y={H - 8}\n                textAnchor={i === n - 1 ? 'end' : i === 0 ? 'start' : 'middle'}\n              >\n                {safeData[i].label}\n              </text>\n            ))}\n\n            <g clipPath={`url(#${uid}-clip)`}>\n              {TONE_BAND_RADII.map((_, b) => (\n                <path\n                  key={b}\n                  d={areaPath}\n                  fill={`url(#${uid}-tone-${b})`}\n                  clipPath={`url(#${uid}-band-${b})`}\n                />\n              ))}\n              <path d={totalPath} className=\"f12-l-total\" fill=\"none\" />\n              {focusPath && (\n                <>\n                  <path d={focusPath} className=\"f12-l-focus\" fill=\"none\" />\n                  {xLabels.map((i) => {\n                    const cv = safeData[i]?.compareValue;\n                    if (cv == null) return null;\n                    const cx = x(i);\n                    const cy = y(cv);\n                    return (\n                      <polygon\n                        key={`cmp-pt-${i}`}\n                        className=\"f12-compare-pt\"\n                        points={`${cx.toFixed(1)},${(cy - 3.5).toFixed(1)} ${(cx + 3.5).toFixed(1)},${cy.toFixed(1)} ${cx.toFixed(1)},${(cy + 3.5).toFixed(1)} ${(cx - 3.5).toFixed(1)},${cy.toFixed(1)}`}\n                      />\n                    );\n                  })}\n                </>\n              )}\n            </g>\n\n            {showPeak && resolvedAnnotation && (\n              <>\n                {isMeasured && (\n                  <path\n                    className=\"f12-tail\"\n                    d={`M${tailX - 6},${bTop + bH - 1} L${px - (px - tailX) * 0.15},${py - 7} L${tailX + 6},${bTop + bH - 1}`}\n                  />\n                )}\n                <circle className=\"f12-peak-dot\" cx={px} cy={py} r=\"4\" />\n              </>\n            )}\n\n            {hd && hover != null && (\n              <g className=\"f12-cross\" aria-hidden=\"true\">\n                <line x1={x(hover)} x2={x(hover)} y1={pad.t - 4} y2={y(bottom)} />\n                <circle cx={x(hover)} cy={y(hd.value)} r=\"4.5\" className=\"f12-cross-dot\" />\n                {hasCompare && hd.compareValue != null && (\n                  <polygon\n                    className=\"f12-cross-dot2\"\n                    points={`${x(hover).toFixed(1)},${(y(hd.compareValue) - 4.5).toFixed(1)} ${(x(hover) + 4.5).toFixed(1)},${y(hd.compareValue).toFixed(1)} ${x(hover).toFixed(1)},${(y(hd.compareValue) + 4.5).toFixed(1)} ${(x(hover) - 4.5).toFixed(1)},${y(hd.compareValue).toFixed(1)}`}\n                  />\n                )}\n              </g>\n            )}\n          </svg>\n        )}\n\n        {showPeak && resolvedAnnotation && (\n          <div\n            ref={balloon}\n            className=\"f12-balloon\"\n            style={\n              isMeasured\n                ? { left: bLeft, top: bTop, minHeight: bH }\n                : {\n                    left: `${Math.max(10, Math.min(80, (px / W) * 100))}%`,\n                    transform: 'translateX(-50%)',\n                    top: bTop,\n                    minHeight: bH,\n                  }\n            }\n            aria-hidden=\"true\"\n          >\n            {isMeasured && <span className=\"f12-balloon-gap\" style={{ left: tailX - bLeft - 5 }} />}\n            {resolvedAnnotation.text}\n          </div>\n        )}\n\n        {hd && hover != null && (\n          <div\n            className=\"f12-tip\"\n            role=\"status\"\n            style={{ left: Math.min(Math.max(x(hover) - 80, 4), Math.max(4, W - 164)), top: 4 }}\n          >\n            <strong>{hd.longLabel ?? hd.label}</strong>\n            <span>\n              <i className=\"f12-sw f12-sw-total\" aria-hidden=\"true\" />\n              {seriesLabel} {formatValue(hd.value)}\n            </span>\n            {hasCompare && hd.compareValue != null && (\n              <span>\n                <i className=\"f12-sw f12-sw-focus\" aria-hidden=\"true\" />\n                {compareLabel} {formatValue(hd.compareValue)}\n              </span>\n            )}\n          </div>\n        )}\n      </div>\n\n      {showTable && (\n        <details className=\"f12-tbl\">\n          <summary>{tableSummary}</summary>\n          <div className=\"f12-tbl-scroll\">\n            <table>\n              <thead>\n                <tr>\n                  <th scope=\"col\">{labelColumnHeader}</th>\n                  <th scope=\"col\">{seriesLabel}</th>\n                  {hasCompare && <th scope=\"col\">{compareLabel}</th>}\n                </tr>\n              </thead>\n              <tbody>\n                {safeData\n                  .slice()\n                  .reverse()\n                  .map((d, idx) => (\n                    <tr key={`${d.label}-${idx}`}>\n                      <td>{d.longLabel ?? d.label}</td>\n                      <td>{formatValue(d.value)}</td>\n                      {hasCompare && <td>{formatValue(d.compareValue ?? 0)}</td>}\n                    </tr>\n                  ))}\n              </tbody>\n            </table>\n          </div>\n        </details>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/frame12/tone-area-chart.tsx"
    }
  ],
  "type": "registry:ui"
}