{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "slider",
  "title": "Slider",
  "description": "A slider with one thumb or a range of two. The thumb glides to where you press, and its number rises above it while you hover, drag or use the arrow keys.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core",
    "class-variance-authority"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/tooltip.json",
    "https://kinoui.com/r/track.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/slider.tsx",
      "content": "'use client'\n\nimport { Tooltip } from '@/registry/components/kino/tooltip'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport { markResizing } from '@/registry/lib/resize'\nimport {\n  thumbDotClassName,\n  trackClassName,\n  trackDirClassName,\n  trackFillClassName,\n  trackHeaderClassName,\n  trackLabelClassName,\n  trackRootClassName,\n  valuePercent,\n} from '@/registry/lib/track'\nimport { type PartProps, renderElement } from '@ui-sdk/react/primitive'\nimport {\n  SliderControl as SliderControlPrimitive,\n  SliderIndicator as SliderIndicatorPrimitive,\n  Slider as SliderPrimitive,\n  SliderThumb as SliderThumbPrimitive,\n  SliderTrack as SliderTrackPrimitive,\n  SliderValue as SliderValuePrimitive,\n  type SliderValueChangeReason,\n} from '@ui-sdk/react/slider'\nimport { TooltipContent as TooltipContentPrimitive } from '@ui-sdk/react/tooltip'\nimport {\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  Fragment,\n  type ReactNode,\n  use,\n  useCallback,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useReducer,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/** How many thumbs a value draws: one for a number, one per entry for an array. */\nfunction thumbCount(value: number | readonly number[] | undefined) {\n  return Array.isArray(value) ? value.length : 1\n}\n\n/**\n * Why each thumb shows its number, by index, -1 for none: the pointer is over\n * it, it is dragged, or the keys moved it last. More than one can be true, on\n * different thumbs.\n */\ninterface ThumbReveal {\n  hovered: number\n  dragged: number\n  keyed: number\n}\n\ntype ThumbEvent =\n  | { type: 'enter'; thumb: number }\n  | { type: 'leave'; thumb: number }\n  | { type: 'change'; reason: SliderValueChangeReason; thumb: number }\n  | { type: 'commit' }\n  | { type: 'press' }\n  | { type: 'focus' }\n  | { type: 'blur' }\n\nconst HIDDEN: ThumbReveal = { hovered: -1, dragged: -1, keyed: -1 }\n\n/**\n * A drag shows the thumb it moves until it is let go, and the keys show the\n * thumb they moved until the pointer presses the track or focus moves.\n */\nfunction revealStep(state: ThumbReveal, event: ThumbEvent): ThumbReveal {\n  switch (event.type) {\n    case 'enter':\n      return { ...state, hovered: event.thumb }\n    case 'leave':\n      return state.hovered === event.thumb ? { ...state, hovered: -1 } : state\n    case 'change':\n      return {\n        ...state,\n        dragged: event.reason === 'drag' ? event.thumb : -1,\n        keyed: event.reason === 'step-key' ? event.thumb : -1,\n      }\n    case 'commit':\n      return { ...state, dragged: -1 }\n    case 'press':\n    case 'focus':\n    case 'blur':\n      return { ...state, keyed: -1 }\n  }\n}\n\n/** Whether the thumb at `index` shows its number. */\nfunction thumbShowsValue(state: ThumbReveal, index: number) {\n  return state.hovered === index || state.dragged === index || state.keyed === index\n}\n\n// In forced colours the fill turns to the system highlight, so a dashed track keeps the invalid state.\nconst sliderTrackClassName = cn(\n  trackClassName,\n  'forced-colors:group-has-aria-invalid/slider:outline-2 forced-colors:group-has-aria-invalid/slider:outline-dashed forced-colors:group-aria-invalid/slider:outline-2 forced-colors:group-aria-invalid/slider:outline-dashed',\n)\n\n// ui-sdk's Field marks a single thumb's input invalid, and a range's group.\nconst sliderThumbClassName = cn(\n  thumbDotClassName,\n  'bg-background border-primary size-4 shadow-sm forced-colors:border-[CanvasText]',\n  'group-has-aria-invalid/slider:border-destructive group-has-aria-invalid/slider:ring-destructive/20 dark:group-has-aria-invalid/slider:ring-destructive/40',\n  'group-aria-invalid/slider:border-destructive group-aria-invalid/slider:ring-destructive/20 dark:group-aria-invalid/slider:ring-destructive/40',\n  'group-data-disabled/slider:ring-0',\n)\n\n/** The slider's label's id, for its thumbs or its group, and the text the visible value shows. */\nconst SliderContext = createContext<{\n  labelId: string\n  labelled: (on: boolean) => void\n  display: (value: number) => string\n} | null>(null)\n\n// ui-sdk places a thumb with `inset-inline` and the fill with `width`, which\n// motion.md won't let us animate. The thumb is pinned to the start and moved\n// with `translate`, against the control's width (`cqw`: the control is a size\n// container), and the fill is clipped, so both glide on the compositor.\n\ntype SliderProps<Value extends number | number[]> = Omit<\n  ComponentProps<typeof SliderPrimitive<Value>>,\n  'orientation' | 'format' | 'className' | 'children'\n> & {\n  className?: string\n  /**\n   * How the value is written, in its thumb's number and in `SliderValue`:\n   * number format options, or a function of the value, such as a stop's\n   * label on a scale that isn't even (`100+`).\n   */\n  format?: Intl.NumberFormatOptions | ((value: number) => string)\n  /** What a screen reader hears for a value, from its written form; the written form by default. */\n  getAriaValueText?: (formatted: string, value: number) => string\n  /** Names the thumb at `index` of a range, such as \"Lowest price\". */\n  getAriaLabel?: (index: number) => string\n  /** Names a slider that has no `SliderLabel` or Field. */\n  'aria-label'?: string\n  /** The label and value, in a row above the track. */\n  children?: ReactNode\n}\n\nfunction Slider<Value extends number | number[]>({\n  className,\n  children,\n  value,\n  defaultValue,\n  min = 0,\n  max = 100,\n  format,\n  locale,\n  disabled,\n  onValueChange,\n  onValueCommit,\n  onFocus,\n  onBlur,\n  getAriaLabel,\n  getAriaValueText,\n  'aria-label': ariaLabel,\n  'aria-describedby': ariaDescribedBy,\n  style,\n  ...props\n}: SliderProps<Value>) {\n  const count = thumbCount(value ?? defaultValue)\n  const labelId = useId()\n  const [hasLabel, setHasLabel] = useState(false)\n  const [reveal, send] = useReducer(revealStep, HIDDEN)\n  const formatter = numberFormatter(locale, typeof format === 'function' ? {} : format)\n  const display = useCallback(\n    (next: number) =>\n      typeof format === 'function' ? format(next) : formatter.format(next),\n    [format, formatter],\n  )\n  const context = useMemo(\n    () => ({ labelId, labelled: setHasLabel, display }),\n    [labelId, display],\n  )\n  const [control, setControl] = useState<HTMLDivElement | null>(null)\n  const controlRef = useCallback((element: HTMLDivElement | null) => {\n    setControl(element)\n    // Thumbs sit in `cqw`, so while the slider resizes they move at once.\n    return markResizing(element)\n  }, [])\n  const range = count > 1\n\n  return (\n    <SliderContext value={context}>\n      <SliderPrimitive<Value>\n        value={value}\n        defaultValue={defaultValue}\n        min={min}\n        max={max}\n        locale={locale}\n        disabled={disabled}\n        format={(next) => {\n          if (next === null) return ''\n          return getAriaValueText ? getAriaValueText(display(next), next) : display(next)\n        }}\n        onValueChange={(next, details) => {\n          send({ type: 'change', reason: details.reason, thumb: details.thumb ?? -1 })\n          onValueChange?.(next, details)\n        }}\n        onValueCommit={(next, details) => {\n          send({ type: 'commit' })\n          onValueCommit?.(next, details)\n        }}\n        onFocus={(event) => {\n          send({ type: 'focus' })\n          onFocus?.(event)\n        }}\n        onBlur={(event) => {\n          send({ type: 'blur' })\n          onBlur?.(event)\n        }}\n        aria-label={range ? ariaLabel : undefined}\n        aria-labelledby={range && hasLabel && !ariaLabel ? labelId : undefined}\n        style={(state) =>\n          ({\n            ...(typeof style === 'function' ? style(state) : style),\n            '--slider-start': range\n              ? valuePercent([state.value].flat()[0] ?? min, min, max)\n              : 0,\n            '--slider-end': valuePercent([state.value].flat().at(-1) ?? min, min, max),\n          }) as CSSProperties\n        }\n        // ui-sdk marks a press on the track as dragging too, which still glides; only a drag follows at once.\n        data-following={reveal.dragged >= 0 || undefined}\n        className={cn(trackRootClassName, 'group/slider', className)}\n        {...props}\n      >\n        {(state) => {\n          const values = [state.value].flat()\n          return (\n            <>\n              {children ? (\n                <div data-slider-header='' className={trackHeaderClassName}>\n                  {children}\n                </div>\n              ) : null}\n              <SliderControlPrimitive\n                ref={controlRef}\n                onPointerDown={() => send({ type: 'press' })}\n                className='group/control @container relative flex h-(--control-height-xs) w-full touch-none items-center select-none data-disabled:pointer-events-none data-disabled:opacity-50'\n              >\n                <SliderTrackPrimitive className={sliderTrackClassName}>\n                  <SliderIndicatorPrimitive\n                    // ui-sdk sizes the fill with `width`, which moves on the main thread: it stays the track's width and is clipped instead.\n                    render={(fill) => <span {...fill} style={undefined} />}\n                    className={cn(\n                      trackFillClassName,\n                      'pointer-events-none inset-x-0',\n                      'transition-[clip-path] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-following/slider:duration-0 motion-reduce:transition-none',\n                      '[clip-path:inset(0_calc(100%-var(--slider-end)*1%)_0_calc(var(--slider-start)*1%)_round_9999px)]',\n                      'rtl:[clip-path:inset(0_calc(var(--slider-start)*1%)_0_calc(100%-var(--slider-end)*1%)_round_9999px)]',\n                      'group-has-aria-invalid/slider:bg-destructive group-aria-invalid/slider:bg-destructive',\n                    )}\n                  />\n                  {Array.from({ length: count }, (_, index) => (\n                    // oxlint-disable-next-line react/no-array-index-key -- a thumb is its index in the value\n                    <Fragment key={index}>\n                      <SliderThumbPrimitive\n                        index={index}\n                        // A range's thumbs take the slider's name too, unless `getAriaLabel` names each.\n                        aria-label={getAriaLabel?.(index) ?? ariaLabel}\n                        aria-labelledby={\n                          getAriaLabel || ariaLabel || !hasLabel ? undefined : labelId\n                        }\n                        aria-describedby={ariaDescribedBy}\n                        // ui-sdk places a thumb with `inset-inline`, which moves on the main thread, so the thumb takes our place instead.\n                        render={(thumb, { percent }) => (\n                          <div\n                            {...thumb}\n                            style={{ '--slider-value': percent } as CSSProperties}\n                          />\n                        )}\n                        onPointerEnter={() => send({ type: 'enter', thumb: index })}\n                        onPointerLeave={() => send({ type: 'leave', thumb: index })}\n                        className={cn(\n                          'group/thumb absolute start-0 top-1/2 flex size-6 [translate:calc(var(--track-dir)*(var(--slider-value)*1cqw-50%))_-50%] items-center justify-center rounded-full data-dragging:z-2 has-focus-visible:z-1',\n                          // After a press on the track or a key, it glides on `layout`; while dragged, it follows the pointer at once.\n                          'transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-following/slider:duration-0 group-data-resizing/control:transition-none motion-reduce:transition-none',\n                        )}\n                      >\n                        <span aria-hidden className={sliderThumbClassName} />\n                      </SliderThumbPrimitive>\n                      <SliderThumbValue\n                        control={control}\n                        open={!state.disabled && thumbShowsValue(reveal, index)}\n                        following={reveal.dragged >= 0}\n                        percent={valuePercent(values[index] ?? min, min, max)}\n                      >\n                        {display(values[index] ?? min)}\n                      </SliderThumbValue>\n                    </Fragment>\n                  ))}\n                </SliderTrackPrimitive>\n              </SliderControlPrimitive>\n            </>\n          )\n        }}\n      </SliderPrimitive>\n    </SliderContext>\n  )\n}\n\n/** A thumb's place and whether its number shows, with where the thumb was the render before. */\ninterface ValueTrail {\n  percent: number\n  open: boolean\n  from: number\n}\n\n/**\n * Where a thumb's number appears: where the thumb was the render before, so\n * it glides with a thumb that the same change moves, such as a key that both\n * moves it and shows its number. Unchanged, it returns the same trail.\n */\nfunction trailStep(trail: ValueTrail, percent: number, open: boolean): ValueTrail {\n  if (trail.percent === percent && trail.open === open) return trail\n  return { percent, open, from: trail.percent }\n}\n\n/**\n * The line through the middle of the control, as wide as it, that a thumb's\n * number is placed above: the number then slides along it in CSS, in step\n * with the thumb, rather than being placed again on every frame.\n */\nfunction midline(control: HTMLElement) {\n  return {\n    getBoundingClientRect() {\n      const box = control.getBoundingClientRect()\n      return new DOMRect(box.left, box.top + box.height / 2, box.width, 0)\n    },\n  }\n}\n\n/**\n * A thumb's number, above it, in Kino's Tooltip: in the top layer, so no box\n * that clips, such as a Card, cuts it off. The tooltip is as wide as the\n * control, and the number slides along it.\n */\nfunction SliderThumbValue({\n  control,\n  open,\n  following,\n  percent,\n  children,\n}: {\n  control: HTMLElement | null\n  open: boolean\n  /** A thumb is dragged, so the number trails it a little. */\n  following: boolean\n  /** Where the thumb is along the track, from 0 to 100. */\n  percent: number\n  children: ReactNode\n}) {\n  const [trail, setTrail] = useState<ValueTrail>({ percent, open, from: percent })\n  const next = trailStep(trail, percent, open)\n  if (next !== trail) setTrail(next)\n  const anchor = useMemo(() => (control ? midline(control) : null), [control])\n  return (\n    <Tooltip open={open && anchor !== null}>\n      <TooltipContentPrimitive\n        anchor={anchor}\n        side='top'\n        align='start'\n        // The thumb's 8px radius and a 6px gap above the track's middle.\n        sideOffset={14}\n        aria-hidden\n        // The number repeats the thumb's value, which the thumb says itself.\n        data-agent-hidden\n        className={cn(\n          trackDirClassName,\n          'group/value pointer-events-none isolate h-0 w-(--anchor-width) overflow-visible',\n        )}\n      >\n        <div\n          data-following={following || undefined}\n          style={\n            { '--slider-value': percent, '--slider-from': next.from } as CSSProperties\n          }\n          className={cn(\n            // A percentage of its own width, the track's, so a resize moves it at once rather than gliding.\n            'absolute start-0 bottom-0 w-full [translate:calc(var(--track-dir)*var(--slider-value)*1%)_0]',\n            // It appears where the thumb was, so it glides beside a thumb that the keys moved.\n            'starting:[translate:calc(var(--track-dir)*var(--slider-from)*1%)_0]',\n            // Glides with the thumb after a press or a key, and trails it a little while dragged.\n            'transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) data-following:duration-(--motion-press-duration) data-following:ease-(--motion-press-easing) motion-reduce:transition-none',\n          )}\n        >\n          <span\n            data-slider-thumb-value=''\n            className={cn(\n              'bg-primary text-primary-foreground absolute start-0 bottom-0 flex h-6 -translate-x-1/2 items-center rounded-full px-2 text-xs font-medium whitespace-nowrap tabular-nums shadow-md rtl:translate-x-1/2 forced-colors:border',\n              // Rises out of the thumb, from a little below and smaller, and sinks back into it.\n              'origin-bottom group-data-ending-style/value:[transform:translateY(var(--slider-value-rise,6px))_scale(0.6)] group-data-ending-style/value:opacity-0 group-data-starting-style/value:[transform:translateY(var(--slider-value-rise,6px))_scale(0.6)] group-data-starting-style/value:opacity-0',\n              '[transition:transform_var(--motion-enter-duration)_var(--motion-enter-easing),opacity_var(--motion-enter-duration)_var(--motion-enter-easing)] group-data-ending-style/value:[transition:transform_var(--motion-exit-duration)_var(--motion-exit-easing),opacity_var(--motion-exit-duration)_var(--motion-exit-easing)] motion-reduce:[transition-property:opacity] motion-reduce:group-data-ending-style/value:[transform:none] motion-reduce:group-data-starting-style/value:[transform:none]',\n            )}\n          >\n            {children}\n          </span>\n        </div>\n      </TooltipContentPrimitive>\n    </Tooltip>\n  )\n}\n\n/** The slider's name, in the row above the track: it names its thumb, or a range's group. */\nfunction SliderLabel({\n  className,\n  render,\n  ...props\n}: Omit<PartProps<'div'>, 'className'> & { className?: string }) {\n  const slider = use(SliderContext)\n  const labelled = slider?.labelled\n  useLayoutEffect(() => {\n    labelled?.(true)\n    return () => labelled?.(false)\n  }, [labelled])\n  return renderElement(\n    'div',\n    {\n      id: slider?.labelId,\n      'data-slider-label': '',\n      className: cn(\n        trackLabelClassName,\n        'group-data-disabled/slider:text-muted-foreground',\n        className,\n      ),\n      ...props,\n    },\n    render,\n  )\n}\n\n/** The value, written as the slider's `format` says, a range's two joined with an en dash. Children replace it. */\nfunction SliderValue({\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof SliderValuePrimitive>, 'className'> & {\n  className?: string\n}) {\n  const display = use(SliderContext)?.display\n  return (\n    <SliderValuePrimitive\n      className={cn('text-muted-foreground ms-auto shrink-0 tabular-nums', className)}\n      {...props}\n    >\n      {children ??\n        (({ value, text }) => (display ? [value].flat().map(display).join(' – ') : text))}\n    </SliderValuePrimitive>\n  )\n}\n\nexport {\n  revealStep,\n  Slider,\n  SliderLabel,\n  SliderValue,\n  sliderThumbClassName,\n  sliderTrackClassName,\n  thumbCount,\n  thumbShowsValue,\n  trailStep,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/slider.tsx"
    }
  ],
  "type": "registry:component"
}