{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "slider-tooltip",
  "title": "Slider with tooltip",
  "description": "Single or range slider built from scratch with pointer and keyboard control, step snapping, marks and a value bubble that scales in while dragging.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/inputs/slider-tooltip.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, animate, motion, useMotionValue, useReducedMotion, useTransform } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, spring } from \"@/lib/goodui-motion\"\n\nexport type SliderMark = { value: number; label?: React.ReactNode }\n\nexport type SliderTooltipLabels = {\n  /** Name of the first thumb in a range. */\n  minimum: string\n  /** Name of the second thumb in a range. */\n  maximum: string\n  /** Name of a single thumb when neither thumbLabels nor aria-label is passed. */\n  value: string\n}\nconst DEFAULT_LABELS: SliderTooltipLabels = { minimum: \"Minimum\", maximum: \"Maximum\", value: \"Value\" }\n\nexport type SliderTooltipProps = Omit<React.ComponentProps<\"div\">, \"defaultValue\" | \"onChange\"> & {\n  /** One value for a single thumb, two for a range. */\n  value?: number[]\n  /** Initial values when uncontrolled; defaults to [min]. */\n  defaultValue?: number[]\n  /** Called on every change while dragging or pressing keys, with all thumb values. */\n  onValueChange?: (value: number[]) => void\n  /** Fires when a drag ends or a key press changes the value (not when the value stays the same, e.g. at a bound). */\n  onValueCommit?: (value: number[]) => void\n  min?: number\n  max?: number\n  step?: number\n  /** Minimum gap between range thumbs, in steps. */\n  minStepsBetweenThumbs?: number\n  /** Labelled ticks under the track; a mark without a label shows formatValue(value). */\n  marks?: SliderMark[]\n  /** Draw a dot at every step (only when there are 40 steps or fewer). */\n  showSteps?: boolean\n  /** Formats the bubble, mark labels and aria-valuetext, e.g. (v) => `$${v}`. */\n  formatValue?: (value: number) => string\n  /** \"auto\" shows the bubble while dragging, hovering or keyboard-focused. */\n  tooltip?: \"auto\" | \"always\" | \"never\"\n  /** Accessible names per thumb, e.g. [\"Minimum price\", \"Maximum price\"]. */\n  thumbLabels?: string[]\n  disabled?: boolean\n  /** Form field name; one hidden input per thumb. */\n  name?: string\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<SliderTooltipLabels>\n}\n\nconst DIGITS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n/** Rolls each digit of an already formatted string, so any formatValue output works. Right-to-left text stays plain. */\nfunction RollingText({ text, reduce }: { text: string; reduce: boolean }) {\n  if (/[\\u0590-\\u08FF]/.test(text)) return <>{text}</>\n  const chars = Array.from(text)\n  return (\n    <span dir=\"ltr\" className=\"inline-flex whitespace-pre\">\n      {chars.map((c, i) => {\n        const key = chars.length - i\n        const d = c >= \"0\" && c <= \"9\" ? Number(c) : null\n        return d === null ? (\n          <span key={key}>{c}</span>\n        ) : (\n          <span key={key} className=\"relative inline-block h-[1.2em] w-[1ch] overflow-hidden leading-[1.2em]\">\n            <motion.span className=\"absolute inset-x-0 top-0 flex flex-col\" initial={false} animate={{ y: `${-d * 1.2}em` }} transition={reduce ? { duration: 0 } : spring.snap}>\n              {DIGITS.map((n) => (\n                <span key={n} className=\"h-[1.2em] text-center\">\n                  {n}\n                </span>\n              ))}\n            </motion.span>\n          </span>\n        )\n      })}\n    </span>\n  )\n}\n\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))\nconst decimals = (n: number) => (String(n).split(\".\")[1] ?? \"\").length\nconst isRtl = (el: Element | null) => !!el && getComputedStyle(el).direction === \"rtl\"\n\n/** Range slider built from scratch: one or two thumbs, pointer and keyboard, step snapping, marks and a value bubble. */\nexport function SliderTooltip({\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  onValueCommit,\n  min = 0,\n  max = 100,\n  step = 1,\n  minStepsBetweenThumbs = 0,\n  marks,\n  showSteps,\n  formatValue = (v) => String(v),\n  tooltip = \"auto\",\n  thumbLabels,\n  disabled,\n  name,\n  labels,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: SliderTooltipProps) {\n  const l = useLabels(\"slider-tooltip\", DEFAULT_LABELS, labels)\n  const prefersReduced = useReducedMotion()\n  const [mounted, setMounted] = React.useState(false)\n  React.useEffect(() => setMounted(true), [])\n  const reduce = mounted && !!prefersReduced\n  const [inner, setInner] = React.useState<number[]>(defaultValue ?? [min])\n  const values = valueProp ?? inner\n  const valuesRef = React.useRef(values)\n  React.useLayoutEffect(() => {\n    valuesRef.current = values\n  })\n  const trackRef = React.useRef<HTMLDivElement>(null)\n  const thumbRefs = React.useRef<(HTMLDivElement | null)[]>([])\n  const [active, setActive] = React.useState<number | null>(null)\n  const [hover, setHover] = React.useState<number | null>(null)\n  const [kbFocus, setKbFocus] = React.useState<number | null>(null)\n  const activeRef = React.useRef<number | null>(null)\n  const dragStart = React.useRef<number[] | null>(null)\n  const gap = minStepsBetweenThumbs * step\n  const pct = (v: number) => ((v - min) / (max - min)) * 100\n  // Elastic overdrag, in physical pixels: past an end the bar stretches after the finger and springs back on release.\n  const over = useMotionValue(0)\n  const trackWidth = React.useRef(1)\n  const barX = useTransform(over, (o) => 1 + Math.abs(o) / trackWidth.current)\n  const barY = useTransform(over, (o) => 1 - Math.min(0.3, Math.abs(o) / 60))\n  const barOrigin = useTransform(over, (o) => (o >= 0 ? 0 : 1))\n\n  const snap = (v: number) => {\n    const s = Math.round((v - min) / step) * step + min\n    return Number(clamp(s, min, max).toFixed(decimals(step)))\n  }\n  const bounds = (i: number, vals: number[]) => [i > 0 ? vals[i - 1]! + gap : min, i < vals.length - 1 ? vals[i + 1]! - gap : max] as const\n\n  const setAt = (i: number, raw: number) => {\n    const cur = valuesRef.current\n    const [lo, hi] = bounds(i, cur)\n    const v = clamp(snap(raw), lo, hi)\n    if (v === cur[i]) return cur\n    const next = cur.slice()\n    next[i] = v\n    valuesRef.current = next\n    if (valueProp === undefined) setInner(next)\n    onValueChange?.(next)\n    return next\n  }\n\n  const fromClientX = (x: number) => {\n    const r = trackRef.current!.getBoundingClientRect()\n    // Right-to-left tracks start at the right edge.\n    const t = isRtl(trackRef.current) ? (r.right - x) / r.width : (x - r.left) / r.width\n    return min + clamp(t, 0, 1) * (max - min)\n  }\n\n  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (disabled || e.button !== 0) return\n    e.preventDefault()\n    const raw = fromClientX(e.clientX)\n    const cur = valuesRef.current\n    // Pick the closest thumb; on a tie pick by direction so stacked thumbs can separate.\n    let idx = 0\n    let best = Infinity\n    cur.forEach((v, i) => {\n      const d = Math.abs(v - raw)\n      if (d < best || (d === best && raw > v)) {\n        best = d\n        idx = i\n      }\n    })\n    activeRef.current = idx\n    dragStart.current = cur\n    setActive(idx)\n    setKbFocus(null)\n    setAt(idx, raw)\n    e.currentTarget.setPointerCapture(e.pointerId)\n    thumbRefs.current[idx]?.focus({ preventScroll: true })\n  }\n\n  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    const i = activeRef.current\n    if (i === null) return\n    setAt(i, fromClientX(e.clientX))\n    if (reduce) return\n    const r = trackRef.current!.getBoundingClientRect()\n    trackWidth.current = r.width\n    const past = e.clientX < r.left ? e.clientX - r.left : e.clientX > r.right ? e.clientX - r.right : 0\n    // Only the thumb sitting on that end pulls the bar: a range's other thumb stays put.\n    const end = past < 0 !== isRtl(trackRef.current) ? min : max\n    over.set(past !== 0 && valuesRef.current[i] === end ? Math.sign(past) * 20 * (1 - Math.exp(-Math.abs(past) / 110)) : 0)\n  }\n\n  const end = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (activeRef.current === null) return\n    activeRef.current = null\n    setActive(null)\n    if (over.get() !== 0) animate(over, 0, spring.play)\n    if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)\n    const start = dragStart.current\n    dragStart.current = null\n    const cur = valuesRef.current\n    if (!start || start.length !== cur.length || start.some((v, k) => v !== cur[k])) onValueCommit?.(cur)\n  }\n\n  const onKeyDown = (i: number, e: React.KeyboardEvent<HTMLDivElement>) => {\n    if (disabled) return\n    const big = Math.max(step, (max - min) / 10)\n    const v = valuesRef.current[i]\n    if (v === undefined) return\n    const [lo, hi] = bounds(i, valuesRef.current)\n    // In right-to-left the track grows to the left, so Arrow Left increases.\n    const dir = isRtl(e.currentTarget) ? -1 : 1\n    const map: Record<string, number> = {\n      ArrowRight: v + step * dir,\n      ArrowUp: v + step,\n      ArrowLeft: v - step * dir,\n      ArrowDown: v - step,\n      PageUp: v + big,\n      PageDown: v - big,\n      Home: lo,\n      End: hi,\n    }\n    const next = map[e.key]\n    if (next === undefined) return\n    e.preventDefault()\n    setKbFocus(i)\n    const prev = valuesRef.current\n    const updated = setAt(i, next)\n    if (updated !== prev) onValueCommit?.(updated)\n  }\n\n  const visible = (i: number) => tooltip === \"always\" || (tooltip === \"auto\" && (active === i || hover === i || kbFocus === i))\n  const stepCount = (max - min) / step\n  const dots = showSteps && stepCount <= 40 ? Array.from({ length: stepCount + 1 }, (_, k) => min + k * step) : []\n  const [v0, v1] = values\n  const lo = values.length > 1 ? (v0 ?? min) : min\n  const hi = values[values.length - 1] ?? max\n  // With two always-on bubbles that collide, show one merged bubble instead.\n  const merged = tooltip === \"always\" && values.length === 2 && v0 !== undefined && v1 !== undefined && pct(v1) - pct(v0) < 16\n  const inRange = (v: number) => v >= lo && v <= hi\n\n  const bubble = (key: string, left: number, text: string, i?: number) => (\n    <motion.div\n      key={key}\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute bottom-full mb-2.5 -translate-x-1/2 rtl:translate-x-1/2\"\n      style={{ insetInlineStart: `${left}%`, x: i === active ? over : 0 }}\n      initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.95, y: 4 }}\n      animate={{ opacity: 1, scale: 1, y: 0 }}\n      exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.95, y: 2, transition: { duration: 0.1 } }}\n      transition={reduce ? { duration: 0.1 } : spring.ui}\n    >\n      <div className=\"rounded-lg bg-popover px-2 py-1 text-xs font-semibold whitespace-nowrap text-popover-foreground tabular-nums shadow-[var(--pc-e2)]\">\n        <RollingText text={text} reduce={reduce} />\n      </div>\n    </motion.div>\n  )\n\n  return (\n    <div className={cn(\"relative w-full select-none\", disabled && \"opacity-50\", className)} aria-label={ariaLabel} role=\"group\" {...props}>\n      <GooduiTokens />\n      <div\n        ref={trackRef}\n        className={cn(\"relative flex h-6 touch-none items-center\", disabled ? \"cursor-not-allowed\" : \"cursor-pointer\")}\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={end}\n        onPointerCancel={end}\n        onLostPointerCapture={end}\n      >\n        <motion.div className=\"relative h-2 w-full rounded-full bg-muted shadow-[var(--pc-well)]\" style={{ scaleX: barX, scaleY: barY, originX: barOrigin }}>\n          <div\n            className=\"absolute inset-y-0 rounded-full bg-primary bg-[image:var(--pc-sheen)] shadow-[inset_0_1px_var(--pc-edge-t)]\"\n            style={{ insetInlineStart: `${values.length > 1 ? pct(lo) : 0}%`, insetInlineEnd: `${100 - pct(hi)}%` }}\n          />\n          {dots.map((d) => (\n            <span\n              key={d}\n              aria-hidden=\"true\"\n              className={cn(\n                \"absolute top-1/2 size-1 -translate-x-1/2 -translate-y-1/2 rounded-full rtl:translate-x-1/2\",\n                inRange(d) && (values.length > 1 || d <= hi) ? \"bg-primary-foreground/70\" : \"bg-foreground/25\",\n              )}\n              style={{ insetInlineStart: `${pct(d)}%` }}\n            />\n          ))}\n        </motion.div>\n\n        {values.map((v, i) => (\n          <motion.div\n            key={i}\n            ref={(el) => {\n              thumbRefs.current[i] = el\n            }}\n            role=\"slider\"\n            tabIndex={disabled ? -1 : 0}\n            aria-label={thumbLabels?.[i] ?? (values.length > 1 ? (i === 0 ? l.minimum : l.maximum) : (ariaLabel ?? (props[\"aria-labelledby\"] ? undefined : l.value)))}\n            aria-labelledby={values.length === 1 && !thumbLabels?.[0] && !ariaLabel ? props[\"aria-labelledby\"] : undefined}\n            aria-valuemin={min}\n            aria-valuemax={max}\n            aria-valuenow={v}\n            aria-valuetext={formatValue(v)}\n            aria-orientation=\"horizontal\"\n            aria-disabled={disabled || undefined}\n            onKeyDown={(e) => onKeyDown(i, e)}\n            onFocus={(e) => {\n              if (e.currentTarget.matches(\":focus-visible\")) setKbFocus(i)\n            }}\n            onBlur={() => setKbFocus((k) => (k === i ? null : k))}\n            onPointerEnter={() => setHover(i)}\n            onPointerLeave={() => setHover((h) => (h === i ? null : h))}\n            className={cn(\n              \"absolute top-1/2 h-6 w-3 -translate-x-1/2 -translate-y-1/2 rounded-[6px] bg-white shadow-[0_0_0_.5px_rgb(0_0_0/.1),0_1px_2px_hsl(var(--pc-sh)/.22),0_4px_10px_-2px_hsl(var(--pc-sh)/.26)] outline-none rtl:translate-x-1/2 after:absolute after:-inset-x-2 after:-inset-y-1 focus-visible:ring-4 focus-visible:ring-ring/40\",\n              active === i ? \"z-20 cursor-grabbing\" : \"z-10 cursor-grab\",\n            )}\n            style={{ insetInlineStart: `${pct(v)}%`, x: active === i ? over : 0 }}\n            initial={false}\n            animate={{ scaleX: active === i && !reduce ? 1.2 : 1, scaleY: active === i && !reduce ? 0.92 : 1 }}\n            transition={reduce ? { duration: 0 } : spring.snap}\n          />\n        ))}\n\n        <AnimatePresence>\n          {merged\n            ? visible(0) && bubble(\"merged\", (pct(v0) + pct(v1)) / 2, `${formatValue(v0)} – ${formatValue(v1)}`)\n            : values.map((v, i) => visible(i) && bubble(`b${i}`, pct(v), formatValue(v), i))}\n        </AnimatePresence>\n      </div>\n\n      {marks && marks.length > 0 && (\n        <div className=\"relative mt-1 h-5\" aria-hidden=\"true\">\n          {marks.map((m) => {\n            const p = pct(m.value)\n            return (\n              <span\n                key={m.value}\n                className={cn(\n                  \"absolute top-0 flex flex-col text-xs whitespace-nowrap text-muted-foreground\",\n                  p <= 0 ? \"items-start\" : p >= 100 ? \"-translate-x-full items-end rtl:translate-x-full\" : \"-translate-x-1/2 items-center rtl:translate-x-1/2\",\n                  inRange(m.value) && (values.length > 1 || m.value <= hi) && \"text-foreground\",\n                )}\n                style={{ insetInlineStart: `${p}%` }}\n              >\n                <span className=\"mb-0.5 h-1.5 w-px bg-border\" />\n                {m.label ?? formatValue(m.value)}\n              </span>\n            )\n          })}\n        </div>\n      )}\n\n      {name && values.map((v, i) => <input key={i} type=\"hidden\" name={values.length > 1 ? `${name}[]` : name} value={v} />)}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/slider-tooltip.tsx"
    }
  ],
  "categories": [
    "components",
    "inputs"
  ],
  "type": "registry:component"
}