{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"sparkline","type":"registry:component","title":"Sparkline","description":"Draws itself in, then scrubs to the nearest point under your cursor.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/sparkline.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useRef, useState } from \"react\";\nimport { motion, useInView } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\ntype Point = { label: string; value: number };\n\n// The plot's size at full width. On a narrower screen the whole chart\n// scales down with its width, so the overlay is positioned in percentages.\nconst W = 520;\nconst H = 160;\n// Room for the 12px scrub dot and its 2px ring at the extremes.\nconst PAD_X = 8;\nconst PAD_Y = 10;\n// Long for a UI animation on purpose: the draw is the chart introducing its\n// shape once, and a line that races in under 300ms reads as a flicker.\nconst DRAW = { duration: 0.7, ease: [0.23, 1, 0.32, 1] } as const;\n\nexport function Sparkline({\n  data,\n  title,\n  format = (v) => String(v),\n  className,\n}: {\n  data: Point[];\n  title: string;\n  format?: (value: number) => string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const plotRef = useRef<HTMLDivElement>(null);\n  const inView = useInView(plotRef, { once: true });\n  const [index, setIndex] = useState(data.length - 1);\n  const [active, setActive] = useState(false);\n  const [announcement, setAnnouncement] = useState(\"\");\n\n  const values = data.map((d) => d.value);\n  const min = Math.min(...values);\n  const max = Math.max(...values);\n  const span = max - min || 1;\n  const step = (W - PAD_X * 2) / Math.max(data.length - 1, 1);\n  const xAt = (i: number) => PAD_X + i * step;\n  const yAt = (v: number) => PAD_Y + (1 - (v - min) / span) * (H - PAD_Y * 2);\n\n  const line = data\n    .map((d, i) => `${i ? \"L\" : \"M\"}${xAt(i).toFixed(1)} ${yAt(d.value).toFixed(1)}`)\n    .join(\" \");\n  const area = `${line} L${xAt(data.length - 1)} ${H} L${xAt(0)} ${H} Z`;\n\n  const last = data[data.length - 1];\n  const delta = last.value - data[0].value;\n\n  const nearest = (clientX: number) => {\n    const box = plotRef.current?.getBoundingClientRect();\n    if (!box) return index;\n    const x = ((clientX - box.left) / box.width) * W;\n    return Math.min(Math.max(Math.round((x - PAD_X) / step), 0), data.length - 1);\n  };\n\n  const describe = (i: number) => `${data[i].label}: ${format(data[i].value)}`;\n\n  const point = data[index];\n  const x = xAt(index);\n  const y = yAt(point.value);\n  // Keeps the ~130px tooltip inside the chart near either edge.\n  const tipX = Math.min(Math.max(x, 72), W - 72);\n  const pct = (v: number, of: number) => `${(v / of) * 100}%`;\n\n  return (\n    <div className={cn(\"w-[520px] max-w-full\", className)}>\n      <div className=\"flex items-baseline justify-between\">\n        <div>\n          <p className=\"text-[15px] text-muted-foreground\">{title}</p>\n          <p className=\"text-3xl font-semibold tracking-tight text-foreground tabular-nums\">\n            {format(last.value)}\n          </p>\n        </div>\n        <p className=\"text-[15px] text-muted-foreground\">\n          <span className=\"font-medium text-foreground tabular-nums\">\n            {delta > 0 ? \"+\" : delta < 0 ? \"-\" : \"\"}\n            {format(Math.abs(delta))}\n          </span>{\" \"}\n          vs {data[0].label}\n        </p>\n      </div>\n\n      <div\n        ref={plotRef}\n        role=\"group\"\n        tabIndex={0}\n        aria-roledescription=\"line chart\"\n        aria-label={`${title}, ${data.length} points. Use arrow keys to read values.`}\n        // pan-y leaves vertical scrolling to the page and hands sideways\n        // drags to the scrubber.\n        className=\"relative mt-12 aspect-[520/160] w-full touch-pan-y rounded-sm outline-hidden select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-foreground\"\n        onPointerDown={(e) => {\n          if (e.pointerType !== \"touch\") return;\n          setIndex(nearest(e.clientX));\n          setActive(true);\n        }}\n        onPointerMove={(e) => {\n          if (e.pointerType === \"touch\" && !active) return;\n          setIndex(nearest(e.clientX));\n          setActive(true);\n        }}\n        onPointerLeave={(e) => {\n          if (e.pointerType !== \"touch\") setActive(false);\n        }}\n        onPointerUp={(e) => {\n          if (e.pointerType === \"touch\") setActive(false);\n        }}\n        onPointerCancel={() => setActive(false)}\n        onFocus={() => {\n          setActive(true);\n          setAnnouncement(describe(index));\n        }}\n        onBlur={() => setActive(false)}\n        onKeyDown={(e) => {\n          const next = {\n            ArrowLeft: index - 1,\n            ArrowRight: index + 1,\n            Home: 0,\n            End: data.length - 1,\n          }[e.key];\n          if (next === undefined) return;\n          e.preventDefault();\n          const clamped = Math.min(Math.max(next, 0), data.length - 1);\n          setIndex(clamped);\n          setActive(true);\n          setAnnouncement(describe(clamped));\n        }}\n      >\n        <svg\n          viewBox={`0 0 ${W} ${H}`}\n          className=\"block h-auto w-full overflow-visible\"\n          aria-hidden\n        >\n          <motion.path\n            d={area}\n            className=\"fill-foreground/[0.08]\"\n            initial={{ opacity: 0 }}\n            animate={inView ? { opacity: 1 } : undefined}\n            transition={DRAW}\n          />\n          <motion.path\n            d={line}\n            fill=\"none\"\n            className=\"stroke-foreground\"\n            strokeWidth={2.5}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            // Opacity hides the round cap's dot before the draw starts.\n            initial={{ pathLength: 0, opacity: 0 }}\n            animate={inView ? { pathLength: 1, opacity: 1 } : undefined}\n            // Reduced motion skips the draw and keeps only a fade.\n            transition={\n              reduceMotion\n                ? { pathLength: { duration: 0 }, opacity: DRAW }\n                : { pathLength: DRAW, opacity: { duration: 0.05 } }\n            }\n          />\n        </svg>\n\n        {/* Everything below moves instantly: scrubbing is constant, and any\n            easing would make the readout trail the pointer. Only the\n            appearance fades. */}\n        <div\n          aria-hidden\n          className={cn(\n            \"pointer-events-none absolute inset-0 transition-opacity ease-out\",\n            active ? \"opacity-100 duration-100\" : \"opacity-0 duration-150\",\n          )}\n        >\n          <div\n            className=\"absolute top-0 h-full w-px -translate-x-1/2 bg-muted-foreground/40\"\n            style={{ left: pct(x, W) }}\n          />\n          <div\n            className=\"absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground ring-2 ring-background\"\n            style={{ left: pct(x, W), top: pct(y, H) }}\n          />\n          <div\n            className=\"absolute bottom-full mb-2.5 flex -translate-x-1/2 items-baseline gap-2 rounded-full bg-foreground px-3 py-1.5 text-sm whitespace-nowrap text-background\"\n            style={{ left: pct(tipX, W) }}\n          >\n            <span className=\"font-semibold tabular-nums\">{format(point.value)}</span>\n            <span className=\"opacity-70\">{point.label}</span>\n          </div>\n        </div>\n      </div>\n\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </span>\n      {/* sr-only on a wrapper: a table ignores the 1px height it sets and\n          stays full height, stretching the page below it. */}\n      <div className=\"sr-only\">\n      <table>\n        <caption>{title}</caption>\n        <thead>\n          <tr>\n            <th scope=\"col\">Day</th>\n            <th scope=\"col\">Value</th>\n          </tr>\n        </thead>\n        <tbody>\n          {data.map((d) => (\n            <tr key={d.label}>\n              <th scope=\"row\">{d.label}</th>\n              <td>{format(d.value)}</td>\n            </tr>\n          ))}\n        </tbody>\n      </table>\n      </div>\n    </div>\n  );\n}\n\n// Seeded so the server and client render the same walk.\nfunction mulberry32(seed: number) {\n  return () => {\n    seed = (seed + 0x6d2b79f5) | 0;\n    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\nconst DEMO: Point[] = (() => {\n  const random = mulberry32(7);\n  const points: Point[] = [];\n  let value = 128;\n  for (let i = 0; i < 30; i++) {\n    // Days 25 to 31 of August, then September.\n    const day = 25 + i;\n    const label = day <= 31 ? `Aug ${day}` : `Sep ${day - 31}`;\n    value = Math.max(80, value + (random() - 0.48) * 18);\n    points.push({ label, value: Math.round(value) });\n  }\n  return points;\n})();\n\nexport default function SparklineDemo() {\n  return <Sparkline data={DEMO} title=\"Response time\" format={(v) => `${v} ms`} />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"categories":["data"],"docs":"From ui lab: https://lab.xevrion.dev/lab/sparkline"}