{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"radial-gauge","type":"registry:block","title":"Radial gauge","description":"A 240° radial gauge with a self-drawing arc, a sweeping needle whose tip is a lens glint dot, tick marks around the dial, a count-up score, and a label with a delta beneath.","dependencies":["motion","lucide-react"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/radial-gauge/radial-gauge.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n  MotionConfig,\n  animate,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport { ArrowDownRight, ArrowUpRight } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\n\n/* one shared clock so the arc, the needle, and the number land together */\nconst FILL_DURATION = 1.1;\nconst BASE_DELAY = 0.15;\n\n/* ------------------------------------------------------------------ */\n/* geometry — a 240° arc, gap at the bottom, kept fully inside the box */\n/* ------------------------------------------------------------------ */\n\nconst W = 240;\nconst H = 190;\nconst CX = 120;\nconst CY = 122;\nconst R = 76;\nconst STROKE = 11;\nconst START = 150; // degrees, bottom-left, measured clockwise (screen coords)\nconst SWEEP = 240; // 150° → 390° (30°), leaving a 120° gap at the bottom\n\nconst MINOR_STEP = 10;\nconst MAJOR_STEP = 60;\nconst TICK_IN = R + STROKE / 2 + 2;\nconst TICK_MINOR = TICK_IN + 5;\nconst TICK_MAJOR = TICK_IN + 9;\nconst LABEL_R = TICK_MAJOR + 13;\n\n/* ------------------------------------------------------------------ */\n/* types                                                               */\n/* ------------------------------------------------------------------ */\n\nexport type RadialGaugeProps = {\n  className?: string;\n  /** Score, clamped to [0, max]. */\n  value?: number;\n  /** Denominator of the score. Defaults to 100. */\n  max?: number;\n  /** Caption shown under the number, e.g. \"Health score\". */\n  label?: string;\n  /** Signed change, e.g. 4.2 for \"+4.2\". 0 renders a neutral badge. */\n  delta?: number;\n  /** Unit after the delta, e.g. \" pts\" or \"%\". Defaults to \" pts\". */\n  deltaSuffix?: string;\n  /** Decimals on the delta value. Defaults to 1. */\n  deltaDecimals?: number;\n  /** Context after the delta badge, e.g. \"vs last month\". */\n  deltaLabel?: string;\n  /** When true a negative delta is good (e.g. churn going down). */\n  goodWhenDown?: boolean;\n  /** Chart colour token 1–5. Defaults to 1. */\n  tone?: number;\n  formatValue?: (value: number) => string;\n  formatDelta?: (delta: number) => string;\n};\n\n/* ------------------------------------------------------------------ */\n/* deterministic demo data                                             */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_VALUE = 82;\nconst DEFAULT_MAX = 100;\nconst DEFAULT_LABEL = \"Health score\";\nconst DEFAULT_DELTA = 4.2;\nconst DEFAULT_DELTA_LABEL = \"vs last month\";\n\n/* ------------------------------------------------------------------ */\n/* helpers                                                             */\n/* ------------------------------------------------------------------ */\n\nfunction clamp(v: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, v));\n}\n\nfunction polar(cx: number, cy: number, r: number, deg: number) {\n  const a = (deg * Math.PI) / 180;\n  return { x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) };\n}\n\n/* Round geometry before it reaches the SVG: Math.cos/Math.sin can differ in\n   their last digits between the server and the browser, which React reports\n   as a hydration mismatch. Three decimals is well below a pixel. */\nfunction round(n: number) {\n  return Math.round(n * 1000) / 1000;\n}\n\nfunction arcPath(cx: number, cy: number, r: number, startDeg: number, endDeg: number) {\n  const s = polar(cx, cy, r, startDeg);\n  const e = polar(cx, cy, r, endDeg);\n  const large = endDeg - startDeg > 180 ? 1 : 0;\n  return `M ${s.x.toFixed(3)} ${s.y.toFixed(3)} A ${r} ${r} 0 ${large} 1 ${e.x.toFixed(3)} ${e.y.toFixed(3)}`;\n}\n\n/* ticks around the dial: a short tick every 10°, a long one every 60° */\nconst MINOR_TICKS = Array.from({ length: SWEEP / MINOR_STEP + 1 }, (_, i) => START + i * MINOR_STEP)\n  .filter((a) => (a - START) % MAJOR_STEP !== 0);\nconst MAJOR_TICKS = Array.from({ length: SWEEP / MAJOR_STEP + 1 }, (_, i) => START + i * MAJOR_STEP);\nconst LABELS = [\n  { text: \"0\", angle: START },\n  { text: \"50\", angle: START + SWEEP / 2 },\n  { text: \"100\", angle: START + SWEEP },\n];\n\n/* ------------------------------------------------------------------ */\n/* a single progress value (0 → fraction) driving needle + number      */\n/* ------------------------------------------------------------------ */\n\nfunction useProgress(\n  target: number,\n  opts: { start: boolean; reduce: boolean; delay: number }\n) {\n  const [value, setValue] = useState(target);\n  const started = useRef(false);\n\n  useEffect(() => {\n    if (!opts.start) return;\n    if (opts.reduce) {\n      setValue(target);\n      return;\n    }\n    if (started.current) return;\n    started.current = true;\n\n    const controls = animate(0, target, {\n      duration: FILL_DURATION,\n      ease: EASE,\n      delay: opts.delay,\n      onUpdate: (v) => setValue(v),\n      onComplete: () => setValue(target),\n    });\n\n    return () => controls.stop();\n  }, [opts.start, target, opts.reduce, opts.delay]);\n\n  return value;\n}\n\n/* ------------------------------------------------------------------ */\n/* block                                                               */\n/* ------------------------------------------------------------------ */\n\nexport function RadialGauge({\n  className,\n  value = DEFAULT_VALUE,\n  max = DEFAULT_MAX,\n  label = DEFAULT_LABEL,\n  delta = DEFAULT_DELTA,\n  deltaSuffix = \" pts\",\n  deltaDecimals = 1,\n  deltaLabel = DEFAULT_DELTA_LABEL,\n  goodWhenDown = false,\n  tone = 1,\n  formatValue,\n  formatDelta,\n}: RadialGaugeProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const inView = useInView(ref, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n  const show = inView;\n  const [hovered, setHovered] = useState(false);\n\n  const maxN = Math.max(1, max);\n  const raw = clamp(value, 0, maxN);\n  const fraction = raw / maxN;\n\n  const color = `var(--chart-${clamp(tone, 1, 5)})`;\n\n  const trackArc = useMemo(() => arcPath(CX, CY, R, START, START + SWEEP), []);\n  const valueArc = useMemo(\n    () => arcPath(CX, CY, R, START, START + fraction * SWEEP),\n    [fraction]\n  );\n\n  const progress = useProgress(fraction, { start: show, reduce, delay: BASE_DELAY });\n  const needleAngle = START + progress * SWEEP;\n  const tipPoint = polar(CX, CY, R, needleAngle);\n  const tip = { x: round(tipPoint.x), y: round(tipPoint.y) };\n\n  const format = formatValue ?? ((v: number) => Math.round(v).toLocaleString(\"en-US\"));\n  const formatDeltaValue =\n    formatDelta ??\n    ((d: number) => {\n      const sign = d > 0 ? \"+\" : d < 0 ? \"−\" : \"\";\n      return `${sign}${Math.abs(d).toFixed(deltaDecimals)}${deltaSuffix}`;\n    });\n\n  const positive = delta > 0;\n  const neutral = delta === 0;\n  const good = goodWhenDown ? delta < 0 : delta > 0;\n\n  const ariaLabel = `${label} gauge. ${format(raw)} out of ${maxN}. ${\n    neutral ? \"No change\" : `${formatDeltaValue(delta)}${deltaLabel ? ` ${deltaLabel}` : \"\"}`\n  }.`;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <motion.div\n        ref={ref}\n        initial={{ opacity: 0, y: 20 }}\n        animate={show ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}\n        transition={{ duration: 0.6, ease: EASE }}\n        onPointerEnter={() => setHovered(true)}\n        onPointerLeave={() => setHovered(false)}\n        className={cn(\n          \"rounded-xl border border-border bg-card text-card-foreground shadow-sm transition-colors hover:border-muted-foreground/30\",\n          className\n        )}\n      >\n        <div className=\"flex flex-col items-center px-6 py-7 sm:py-8\">\n          <div className=\"w-full max-w-[300px]\">\n            <svg\n              viewBox={`0 0 ${W} ${H}`}\n              role=\"img\"\n              aria-label={ariaLabel}\n              className=\"block h-auto w-full\"\n            >\n              {/* the quiet track behind the fill */}\n              <path\n                d={trackArc}\n                fill=\"none\"\n                stroke=\"var(--muted)\"\n                strokeWidth={STROKE}\n                strokeLinecap=\"round\"\n              />\n\n              {/* the value arc draws itself with a pathLength animation */}\n              {fraction > 0 ? (\n                <motion.path\n                  d={valueArc}\n                  fill=\"none\"\n                  stroke={color}\n                  strokeWidth={STROKE}\n                  strokeLinecap=\"round\"\n                  initial={{ pathLength: reduce ? 1 : 0 }}\n                  animate={{ pathLength: show ? 1 : 0 }}\n                  transition={\n                    reduce\n                      ? { duration: 0 }\n                      : { duration: FILL_DURATION, delay: BASE_DELAY, ease: EASE }\n                  }\n                />\n              ) : null}\n\n              {/* ticks fade in once the arc is under way */}\n              <motion.g\n                initial={{ opacity: reduce ? 1 : 0 }}\n                animate={{ opacity: show ? 1 : 0 }}\n                transition={\n                  reduce\n                    ? { duration: 0 }\n                    : { duration: 0.45, delay: BASE_DELAY + 0.15, ease: EASE }\n                }\n              >\n                {MINOR_TICKS.map((angle) => {\n                  const a = polar(CX, CY, TICK_IN, angle);\n                  const b = polar(CX, CY, TICK_MINOR, angle);\n                  return (\n                    <line\n                      key={`minor-${angle}`}\n                      x1={round(a.x)}\n                      y1={round(a.y)}\n                      x2={round(b.x)}\n                      y2={round(b.y)}\n                      stroke=\"var(--border)\"\n                      strokeWidth={1}\n                      strokeLinecap=\"round\"\n                    />\n                  );\n                })}\n                {MAJOR_TICKS.map((angle) => {\n                  const a = polar(CX, CY, TICK_IN, angle);\n                  const b = polar(CX, CY, TICK_MAJOR, angle);\n                  return (\n                    <line\n                      key={`major-${angle}`}\n                      x1={round(a.x)}\n                      y1={round(a.y)}\n                      x2={round(b.x)}\n                      y2={round(b.y)}\n                      stroke=\"var(--muted-foreground)\"\n                      strokeWidth={1.5}\n                      strokeLinecap=\"round\"\n                    />\n                  );\n                })}\n              </motion.g>\n\n              {/* numeric anchors at the ends and top */}\n              <motion.g\n                initial={{ opacity: reduce ? 1 : 0 }}\n                animate={{ opacity: show ? 1 : 0 }}\n                transition={\n                  reduce\n                    ? { duration: 0 }\n                    : { duration: 0.45, delay: BASE_DELAY + 0.3, ease: EASE }\n                }\n              >\n                {LABELS.map((l) => {\n                  const p = polar(CX, CY, LABEL_R, l.angle);\n                  return (\n                    <text\n                      key={l.text}\n                      x={round(p.x)}\n                      y={round(p.y)}\n                      textAnchor=\"middle\"\n                      dominantBaseline=\"central\"\n                      fill=\"var(--muted-foreground)\"\n                      style={{ fontSize: 11 }}\n                      className=\"select-none\"\n                    >\n                      {l.text}\n                    </text>\n                  );\n                })}\n              </motion.g>\n\n              {/* the lens glint dot on the arc at the value */}\n              <g>\n                {/* the lens at the tip: ring + core + a glint on its rim */}\n                <circle\n                  cx={tip.x}\n                  cy={tip.y}\n                  r={6.5}\n                  fill=\"var(--card)\"\n                  stroke={color}\n                  strokeWidth={1.5}\n                />\n                <circle cx={tip.x} cy={tip.y} r={2.75} fill={color} />\n                <motion.circle\n                  cx={tip.x - 2}\n                  cy={tip.y - 2}\n                  r={1.3}\n                  fill=\"var(--foreground)\"\n                  initial={false}\n                  animate={{ opacity: hovered ? 1 : 0.65 }}\n                  transition={{ duration: 0.2 }}\n                />\n              </g>\n\n              {/* the count-up score, centred in the dial */}\n              <text\n                x={CX}\n                y={CY}\n                textAnchor=\"middle\"\n                dominantBaseline=\"central\"\n                fill=\"currentColor\"\n                style={{\n                  fontSize: 44,\n                  fontWeight: 600,\n                  letterSpacing: \"-0.03em\",\n                  fontVariantNumeric: \"tabular-nums\",\n                }}\n                className=\"select-none\"\n              >\n                {format(progress * maxN)}\n              </text>\n              <text\n                x={CX}\n                y={CY + 32}\n                textAnchor=\"middle\"\n                dominantBaseline=\"central\"\n                fill=\"var(--muted-foreground)\"\n                style={{ fontSize: 13 }}\n                className=\"select-none\"\n              >\n                of {maxN}\n              </text>\n            </svg>\n          </div>\n\n          {/* label + delta under the number */}\n          <div className=\"mt-4 flex flex-col items-center gap-1.5 text-center\">\n            <span className=\"text-[14px] font-medium text-card-foreground\">\n              {label}\n            </span>\n            <div className=\"flex flex-wrap items-center justify-center gap-1.5\">\n              <span\n                className={cn(\n                  \"inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 text-[11px] font-medium tabular-nums\",\n                  neutral\n                    ? \"bg-muted text-muted-foreground\"\n                    : good\n                      ? \"bg-success/10 text-success\"\n                      : \"bg-destructive/10 text-destructive\"\n                )}\n              >\n                {neutral ? null : positive ? (\n                  <ArrowUpRight className=\"h-3 w-3\" />\n                ) : (\n                  <ArrowDownRight className=\"h-3 w-3\" />\n                )}\n                {formatDeltaValue(delta)}\n              </span>\n              {deltaLabel ? (\n                <span className=\"text-[12.5px] text-muted-foreground\">\n                  {deltaLabel}\n                </span>\n              ) : null}\n            </div>\n          </div>\n        </div>\n      </motion.div>\n    </MotionConfig>\n  );\n}\n\nexport default RadialGauge;\n"}]}