{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sparkline-draw",
  "title": "Sparkline draw",
  "description": "Smooth monotone sparkline that draws itself in, fades in a gradient area, shows point values on hover or arrow keys, and redraws when the data changes.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/numbers/sparkline-draw.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { motion, useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { useGooduiLocale, useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, spring, ease as easing } from \"@/lib/goodui-motion\"\n\nconst CSS = `\n@keyframes pc-sparkline-draw-ping { 0% { transform: scale(1); opacity: .5 } 80%, 100% { transform: scale(2.6); opacity: 0 } }\n.pc-sparkline-draw-ping { transform-box: fill-box; transform-origin: center; animation: pc-sparkline-draw-ping 2s var(--pc-ease-out) infinite; }\n@media (prefers-reduced-motion: reduce) { .pc-sparkline-draw-ping { animation: none; opacity: 0 } }\n`\n\ntype Point = [number, number]\n\n/** Monotone cubic interpolation (Fritsch–Carlson): smooth, but never overshoots above a peak or below a dip. */\nfunction smoothPath(p: Point[]) {\n  const n = p.length\n  if (n === 0) return \"\"\n  if (n < 3) return p.map(([x, y], i) => `${i ? \"L\" : \"M\"}${x},${y}`).join(\"\")\n  // Every index below stays within 0..n-1 (n >= 3), so the non-null assertions are safe.\n  const m: number[] = []\n  for (let i = 0; i < n - 1; i++) {\n    const [x0, y0] = p[i]!\n    const [x1, y1] = p[i + 1]!\n    m.push((y1 - y0) / (x1 - x0 || 1))\n  }\n  const t: number[] = [m[0]!]\n  for (let i = 1; i < n - 1; i++) {\n    const m0 = m[i - 1]!\n    const m1 = m[i]!\n    t.push(m0 * m1 <= 0 ? 0 : (m0 + m1) / 2)\n  }\n  t.push(m[n - 2]!)\n  for (let i = 0; i < n - 1; i++) {\n    const mi = m[i]!\n    if (mi === 0) {\n      t[i] = 0\n      t[i + 1] = 0\n      continue\n    }\n    const a = t[i]! / mi\n    const b = t[i + 1]! / mi\n    const s = a * a + b * b\n    if (s > 9) {\n      const k = 3 / Math.sqrt(s)\n      t[i] = k * a * mi\n      t[i + 1] = k * b * mi\n    }\n  }\n  const [sx, sy] = p[0]!\n  let d = `M${sx},${sy}`\n  for (let i = 0; i < n - 1; i++) {\n    const [x0, y0] = p[i]!\n    const [x1, y1] = p[i + 1]!\n    const dx = (x1 - x0) / 3\n    d += `C${x0 + dx},${y0 + t[i]! * dx},${x1 - dx},${y1 - t[i + 1]! * dx},${x1},${y1}`\n  }\n  return d\n}\n\n\nexport type SparklineDrawLabels = {\n  point: (n: number) => string\n  summary: (first: string, last: string, low: string, high: string) => string\n  noData: string\n}\nconst DEFAULT_LABELS: SparklineDrawLabels = {\n  point: (n) => `Point ${n}`,\n  summary: (first, last, low, high) => `Trend from ${first} to ${last}, low ${low}, high ${high}`,\n  noData: \"No data\",\n}\n\nexport type SparklineDrawProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n  /** Values in order, oldest first. The line scales between their min and max; changed values redraw the line. */\n  data: number[]\n  /** One label per point, shown in the tooltip (e.g. dates). */\n  pointLabels?: string[]\n  /** Height in px. The width follows the container. */\n  height?: number\n  /** Line thickness in px; the end dot and padding grow with it. */\n  strokeWidth?: number\n  /** Any CSS color. Defaults to the theme's first chart color. */\n  color?: string\n  /** Gradient fill under the line. */\n  area?: boolean\n  /** smooth: monotone curve that never overshoots the data. linear: straight segments. */\n  curve?: \"smooth\" | \"linear\"\n  /** Show the hovered point's value. Arrow keys move it when focused. */\n  tooltip?: boolean\n  /** Pulsing dot on the latest point. */\n  endDot?: boolean\n  /** Seconds the line takes to draw. */\n  duration?: number\n  /** Formats values for the tooltip and screen readers. index is -1 for the low and high in the summary. */\n  formatValue?: (value: number, index: number) => string\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<SparklineDrawLabels>\n}\n\n/** Sparkline that draws itself in, fades in a gradient area and shows point values on hover. Redraws when data changes. */\nexport function SparklineDraw({\n  data,\n  pointLabels,\n  labels,\n  height = 48,\n  strokeWidth = 2,\n  color = \"var(--chart-1)\",\n  area = true,\n  curve = \"smooth\",\n  tooltip = true,\n  endDot = true,\n  duration = 0.9,\n  formatValue: formatValueProp,\n  className,\n  style,\n  \"aria-label\": ariaLabel,\n  ...props\n}: SparklineDrawProps) {\n  const l = useLabels(\"sparkline-draw\", DEFAULT_LABELS, labels)\n  const { lang } = useGooduiLocale()\n  const formatValue = React.useMemo<(value: number, index: number) => string>(() => {\n    if (formatValueProp) return formatValueProp\n    const nf = new Intl.NumberFormat(lang, { maximumFractionDigits: 2 })\n    return (v: number) => nf.format(v)\n  }, [formatValueProp, lang])\n  const reduce = useReducedMotion() ?? false\n  const ref = React.useRef<HTMLDivElement>(null)\n  const [width, setWidth] = React.useState(240)\n  const [active, setActive] = React.useState<number | null>(null)\n  const gradientId = `pc-spark-${React.useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`\n\n  React.useEffect(() => {\n    const el = ref.current\n    if (!el) return\n    const ro = new ResizeObserver(([entry]) => {\n      if (entry) setWidth(Math.max(40, Math.round(entry.contentRect.width)))\n    })\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [])\n\n  const padX = endDot || tooltip ? strokeWidth + 4 : strokeWidth\n  const padY = strokeWidth + 4\n  const min = data.length ? Math.min(...data) : 0\n  const max = data.length ? Math.max(...data) : 0\n  const range = max - min || 1\n  const step = data.length > 1 ? (width - padX * 2) / (data.length - 1) : 0\n  const points: Point[] = data.map((v, i) => [\n    padX + i * step,\n    max === min ? height / 2 : padY + (1 - (v - min) / range) * (height - padY * 2),\n  ])\n  const line = curve === \"smooth\" ? smoothPath(points) : points.map(([x, y], i) => `${i ? \"L\" : \"M\"}${x},${y}`).join(\"\")\n  const fill = points.length > 1 ? `${line}L${points[points.length - 1]![0]},${height}L${points[0]![0]},${height}Z` : \"\"\n  // A new data set remounts the paths so they draw in again; a resize only reshapes them.\n  const signature = data.join(\",\")\n  const last = points[points.length - 1]\n  const activePoint = active !== null ? points[active] : undefined\n  const summary =\n    ariaLabel ??\n    (data.length ? l.summary(formatValue(data[0]!, 0), formatValue(data[data.length - 1]!, data.length - 1), formatValue(min, -1), formatValue(max, -1)) : l.noData)\n\n  const indexAt = (clientX: number) => {\n    const rect = ref.current?.getBoundingClientRect()\n    if (!rect || data.length === 0) return null\n    if (data.length === 1) return 0\n    return Math.min(data.length - 1, Math.max(0, Math.round((clientX - rect.left - padX) / step)))\n  }\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (!tooltip || data.length === 0) return\n    if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {\n      e.preventDefault()\n      setActive((i) => {\n        const cur = i ?? data.length - 1\n        return Math.min(data.length - 1, Math.max(0, cur + (e.key === \"ArrowLeft\" ? -1 : 1)))\n      })\n    } else if (e.key === \"Home\" || e.key === \"End\") {\n      e.preventDefault()\n      setActive(e.key === \"Home\" ? 0 : data.length - 1)\n    } else if (e.key === \"Escape\") setActive(null)\n  }\n\n  const snap = reduce ? { duration: 0 } : spring.snap\n  const tipAlign = activePoint ? (activePoint[0] < 48 ? \"0%\" : activePoint[0] > width - 48 ? \"-100%\" : \"-50%\") : \"-50%\"\n\n  return (\n    <div\n      ref={ref}\n      role=\"group\"\n      aria-roledescription=\"sparkline\"\n      aria-label={summary}\n      tabIndex={tooltip ? 0 : undefined}\n      onPointerMove={tooltip ? (e) => setActive(indexAt(e.clientX)) : undefined}\n      onPointerLeave={tooltip ? () => setActive(null) : undefined}\n      onFocus={tooltip ? () => setActive((i) => i ?? data.length - 1) : undefined}\n      onBlur={tooltip ? () => setActive(null) : undefined}\n      onKeyDown={onKeyDown}\n      className={cn(\"relative w-full touch-pan-y rounded-md outline-none focus-visible:ring-3 focus-visible:ring-ring/50\", className)}\n      style={{ height, ...style }}\n      {...props}\n    >\n      <GooduiTokens />\n      <style href=\"pc-sparkline-draw\" precedence=\"default\">\n        {CSS}\n      </style>\n      <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} className=\"absolute inset-0 overflow-visible\" aria-hidden=\"true\">\n        <defs>\n          <linearGradient id={gradientId} x1=\"0\" x2=\"0\" y1=\"0\" y2=\"1\">\n            <stop offset=\"0%\" style={{ stopColor: color, stopOpacity: 0.28 }} />\n            <stop offset=\"100%\" style={{ stopColor: color, stopOpacity: 0 }} />\n          </linearGradient>\n        </defs>\n        {area && fill && (\n          <motion.path\n            key={`a${signature}`}\n            d={fill}\n            fill={`url(#${gradientId})`}\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 1 }}\n            transition={reduce ? { duration: 0 } : { duration: 0.6, delay: duration * 0.45, ease: \"easeOut\" }}\n          />\n        )}\n        {line && (\n          <motion.path\n            key={`l${signature}`}\n            d={line}\n            fill=\"none\"\n            style={{ stroke: color }}\n            strokeWidth={strokeWidth}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            initial={{ pathLength: reduce ? 1 : 0 }}\n            animate={{ pathLength: 1 }}\n            transition={reduce ? { duration: 0 } : { duration, ease: easing.inOut }}\n          />\n        )}\n        {endDot && last && (\n          <motion.g\n            key={`d${signature}`}\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 1 }}\n            transition={reduce ? { duration: 0 } : { duration: 0.2, delay: duration * 0.9 }}\n          >\n            <circle className=\"pc-sparkline-draw-ping\" cx={last[0]} cy={last[1]} r={strokeWidth + 1.5} style={{ fill: color }} />\n            <circle cx={last[0]} cy={last[1]} r={strokeWidth + 1.5} style={{ fill: color }} className=\"stroke-background\" strokeWidth={2} />\n          </motion.g>\n        )}\n        {activePoint && (\n          <g>\n            <motion.line\n              x1={0}\n              x2={0}\n              y1={0}\n              y2={height}\n              className=\"stroke-border\"\n              strokeDasharray=\"3 3\"\n              initial={false}\n              animate={{ x: activePoint[0] }}\n              transition={snap}\n            />\n            <motion.circle\n              r={strokeWidth + 2}\n              style={{ fill: color }}\n              className=\"stroke-background\"\n              strokeWidth={2}\n              initial={false}\n              animate={{ cx: activePoint[0], cy: activePoint[1] }}\n              transition={snap}\n            />\n          </g>\n        )}\n      </svg>\n      {tooltip && activePoint && active !== null && (\n        <div\n          className=\"pointer-events-none absolute z-10 rounded-md border bg-popover px-2 py-1 text-xs whitespace-nowrap text-popover-foreground shadow-[var(--pc-e2)]\"\n          style={{ left: activePoint[0], top: Math.min(activePoint[1], height) - 10, transform: `translate(${tipAlign}, -100%)` }}\n        >\n          {pointLabels?.[active] && <span className=\"me-1.5 text-muted-foreground\">{pointLabels[active]}</span>}\n          <span className=\"font-medium tabular-nums\">{formatValue(data[active]!, active)}</span>\n        </div>\n      )}\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {active !== null && data[active] !== undefined ? `${pointLabels?.[active] ?? l.point(active + 1)}: ${formatValue(data[active], active)}` : \"\"}\n      </span>\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/sparkline-draw.tsx"
    }
  ],
  "categories": [
    "components",
    "numbers"
  ],
  "type": "registry:component"
}