{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"gauge","type":"registry:component","title":"Gauge","description":"Ticks light up as the value sweeps in, and a peak marker holds where it was before falling.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/gauge.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  animate,\n  motion,\n  useInView,\n  useMotionValue,\n  useMotionValueEvent,\n  useSpring,\n  useTransform,\n  type AnimationPlaybackControls,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// No bounce: an arc that overshoots would briefly show a value that isn't\n// true. Longer than a UI transition because the eye has to follow a change\n// in magnitude, not just notice one.\nconst FILL = { visualDuration: 0.6, bounce: 0 };\n\n// Instrument geometry in viewBox units: a half circle of ticks centred on\n// (CX, CY), read left to right as 0 to 100.\nconst CX = 100;\nconst CY = 100;\nconst R = 84;\n// 41 ticks is one every 2.5%, about 6.6 units apart on the arc: dense\n// enough to read as a sweep, sparse enough that each tick is its own mark.\nconst TICKS = 41;\nconst TICK_IN = R - 8;\nconst TICK_OUT = R + 8;\n// The peak marker reaches past the ticks on both sides so it stays legible\n// on top of a lit run.\nconst PEAK_IN = R - 13;\nconst PEAK_OUT = R + 13;\n// Peak hold, as on an audio meter: after a drop the marker waits where the\n// value was, long enough to be seen (the fill settles in ~600ms), then falls.\nconst PEAK_HOLD = 900;\n// An ease-in on purpose: the marker is let go and drops under its own\n// weight, so it starts slow and lands fast.\nconst PEAK_FALL = { duration: 0.45, ease: [0.55, 0, 1, 0.45] } as const;\n\nfunction pointAt(percent: number, radius: number) {\n  const angle = Math.PI * (1 - percent / 100);\n  // Rounded because the server's and the browser's trig can differ in the\n  // last float digits, which would fail hydration on every tick.\n  const round = (n: number) => Math.round(n * 1000) / 1000;\n  return [round(CX + radius * Math.cos(angle)), round(CY - radius * Math.sin(angle))];\n}\n\nconst TICK_PERCENTS = Array.from({ length: TICKS }, (_, i) => (i / (TICKS - 1)) * 100);\n\nexport function Gauge({\n  value,\n  label,\n  threshold = 85,\n  className,\n}: {\n  value: number;\n  label: string;\n  threshold?: number;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const tickRefs = useRef<(SVGLineElement | null)[]>([]);\n  const lit = useRef(0);\n  // Fills in when first seen, so a gauge below the fold still gets its\n  // entrance instead of finishing offscreen.\n  const inView = useInView(rootRef, { once: true });\n  const clamped = Math.round(Math.min(Math.max(value, 0), 100));\n  const high = clamped > threshold;\n\n  // One spring drives the ticks, the number and the peak so they never\n  // drift apart.\n  const progress = useSpring(0, FILL);\n  const shown = useTransform(progress, (v) => Math.round(v));\n  const peak = useMotionValue(0);\n  const fall = useRef<AnimationPlaybackControls>(undefined);\n\n  useEffect(() => {\n    if (!inView) return;\n    if (reduceMotion) progress.jump(clamped);\n    else progress.set(clamped);\n    if (clamped >= peak.get()) return;\n    const timer = setTimeout(() => {\n      fall.current?.stop();\n      if (reduceMotion) peak.jump(clamped);\n      else fall.current = animate(peak, clamped, PEAK_FALL);\n    }, PEAK_HOLD);\n    return () => clearTimeout(timer);\n  }, [clamped, inView, reduceMotion, progress, peak]);\n\n  useEffect(() => () => fall.current?.stop(), []);\n\n  // Lights ticks as the fill passes them, writing only the ticks that\n  // changed straight to the DOM, so a frame costs a handful of attribute\n  // writes and never a React render. The peak rides the fill upward.\n  useMotionValueEvent(progress, \"change\", (v) => {\n    if (v > peak.get()) {\n      fall.current?.stop();\n      peak.set(v);\n    }\n    // Half a percent of slack so a spring settling at 50 still lights 50.\n    const count = v < 0.5 ? 0 : TICK_PERCENTS.filter((p) => p <= v + 0.5).length;\n    const before = lit.current;\n    if (count === before) return;\n    for (let i = Math.min(count, before); i < Math.max(count, before); i++) {\n      const tick = tickRefs.current[i];\n      if (tick) tick.dataset.lit = String(i < count);\n    }\n    lit.current = count;\n  });\n\n  // The marker only shows once it has come apart from the fill, fading in\n  // over the first few percent of separation instead of popping.\n  const peakOpacity = useTransform([peak, progress], ([p, v]: number[]) =>\n    Math.min(Math.max((p - v - 1) / 3, 0), 1),\n  );\n  const px1 = useTransform(peak, (p) => pointAt(p, PEAK_IN)[0]);\n  const py1 = useTransform(peak, (p) => pointAt(p, PEAK_IN)[1]);\n  const px2 = useTransform(peak, (p) => pointAt(p, PEAK_OUT)[0]);\n  const py2 = useTransform(peak, (p) => pointAt(p, PEAK_OUT)[1]);\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"meter\"\n      aria-label={label}\n      aria-valuemin={0}\n      aria-valuemax={100}\n      aria-valuenow={clamped}\n      aria-valuetext={`${clamped}%${high ? \", high\" : \"\"}`}\n      className={cn(\"flex w-[320px] max-w-full flex-col items-center\", className)}\n    >\n      <div className=\"relative w-full\">\n        <svg\n          viewBox=\"0 0 200 110\"\n          className=\"block w-full overflow-visible\"\n          fill=\"none\"\n          aria-hidden\n        >\n          {TICK_PERCENTS.map((p, i) => {\n            const [x1, y1] = pointAt(p, TICK_IN);\n            const [x2, y2] = pointAt(p, TICK_OUT);\n            const danger = p > threshold;\n            return (\n              <line\n                key={i}\n                ref={(el) => {\n                  tickRefs.current[i] = el;\n                }}\n                x1={x1}\n                y1={y1}\n                x2={x2}\n                y2={y2}\n                data-lit=\"false\"\n                strokeWidth={2.5}\n                strokeLinecap=\"round\"\n                // A short fade per tick turns the spring's sweep into a\n                // smooth wave instead of ticks snapping on one by one. The\n                // danger zone is faintly tinted even when unlit, so the\n                // limit is visible before the value gets there.\n                className={cn(\n                  \"transition-[stroke] duration-150 ease-out motion-reduce:transition-none\",\n                  danger\n                    ? \"stroke-destructive/25 data-[lit=true]:stroke-destructive\"\n                    : \"stroke-border data-[lit=true]:stroke-foreground\",\n                )}\n              />\n            );\n          })}\n          <motion.line\n            x1={px1}\n            y1={py1}\n            x2={px2}\n            y2={py2}\n            style={{ opacity: peakOpacity }}\n            strokeWidth={2}\n            strokeLinecap=\"round\"\n            className=\"stroke-foreground\"\n          />\n        </svg>\n\n        {/* Tabular so the width holds steady while the number counts. */}\n        <span\n          aria-hidden\n          className=\"absolute inset-x-0 bottom-0 flex items-baseline justify-center text-6xl leading-none font-semibold tracking-tight text-foreground tabular-nums\"\n        >\n          <motion.span>{shown}</motion.span>\n          <span className=\"ml-1 text-2xl font-medium text-muted-foreground\">%</span>\n        </span>\n      </div>\n\n      <div aria-hidden className=\"relative mt-3 flex h-6 items-center text-[15px]\">\n        <span className=\"text-muted-foreground\">{label}</span>\n        {/* Status never rides on colour alone, so high usage also gets a word.\n            Out of flow so the label stays centred whether or not it shows. */}\n        <span\n          className={cn(\n            \"absolute left-full ml-2 flex items-center whitespace-nowrap gap-1.5 font-medium text-foreground transition-[opacity,filter,translate] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity]\",\n            high\n              ? \"translate-y-0 opacity-100 blur-[0px] duration-200\"\n              : \"translate-y-0.5 opacity-0 blur-[4px] duration-150 motion-reduce:translate-y-0\",\n          )}\n        >\n          <span className=\"size-2 rounded-full bg-destructive\" />\n          High\n        </span>\n      </div>\n    </div>\n  );\n}\n\nconst PRESETS = [\n  { label: \"CPU\", value: 34 },\n  { label: \"Memory\", value: 72 },\n  { label: \"Disk\", value: 91 },\n];\n\nexport default function GaugeDemo() {\n  const [active, setActive] = useState(0);\n  const preset = PRESETS[active];\n\n  return (\n    <div className=\"flex max-w-full flex-col items-center gap-6\">\n      <Gauge value={preset.value} label={preset.label} />\n      <div className=\"flex gap-1 rounded-full bg-muted p-1\">\n        {PRESETS.map((p, i) => (\n          <button\n            key={p.label}\n            type=\"button\"\n            aria-pressed={i === active}\n            onClick={() => setActive(i)}\n            className={cn(\n              \"h-10 touch-manipulation rounded-full px-4 text-sm font-medium outline-hidden transition-[scale,color,background-color,box-shadow] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color,box-shadow]\",\n              i === active\n                ? \"bg-background text-foreground shadow-raised\"\n                : \"text-muted-foreground hover:text-foreground\",\n            )}\n          >\n            {p.label} <span className=\"tabular-nums\">{p.value}%</span>\n          </button>\n        ))}\n      </div>\n    </div>\n  );\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"}],"cssVars":{"light":{"marker":"#d93d31","shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"marker":"#ff6b5f","shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"color-marker":"var(--marker)","shadow-raised":"var(--shadow-raised)"}},"categories":["data"],"docs":"From ui lab: https://lab.xevrion.dev/lab/gauge"}