{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"before-after-slider","type":"registry:component","title":"Before After Slider","description":"Compare two images with a draggable divider. Drag or click anywhere on the frame, use the arrow keys, and keep vertical page scroll on touch.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","lucide-react","motion","tailwind-merge"],"registryDependencies":[],"files":[{"path":"components/motion/before-after-slider.tsx","type":"registry:component","target":"@components/motion/before-after-slider.tsx","content":"\"use client\";\n// beui.dev/components/motion/before-after-slider\n\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport {\n  type AnimationPlaybackControls,\n  animate,\n  motion,\n  useInView,\n  useMotionValue,\n  useReducedMotion,\n  useSpring,\n  useTransform,\n  useVelocity,\n} from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  type PointerEvent,\n  type ReactNode,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_IN_OUT, SPRING_GLIDE, SPRING_MOUSE, SPRING_PRESS } from \"@/lib/ease\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { capturePointer, releasePointer, TOUCH_GESTURE_CLASS } from \"@/lib/touch\";\nimport { cn } from \"@/lib/utils\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const beforeAfterSliderMessages = {\n  label: \"Before and after comparison\",\n  before: \"Before\",\n  after: \"After\",\n  valueText: \"{value}% before\",\n};\n\nexport type BeforeAfterSliderMessages = typeof beforeAfterSliderMessages;\n\nexport interface BeforeAfterSliderProps {\n  /** Shown on the left of the divider, usually an image. */\n  before: ReactNode;\n  /** Shown on the right of the divider, usually an image of the same size. */\n  after: ReactNode;\n  /** Divider position as a percent of the width, 0 to 100 (controlled). */\n  value?: number;\n  /** Starting position when uncontrolled. */\n  defaultValue?: number;\n  onValueChange?: (value: number) => void;\n  /** Show the Before and After labels in the top corners. */\n  showLabels?: boolean;\n  /** Sweep the divider once when the slider first scrolls into view, to show it moves. */\n  hint?: boolean;\n  disabled?: boolean;\n  labels?: Partial<BeforeAfterSliderMessages>;\n  /** Size the frame here; it defaults to a 3:2 box at full width. */\n  className?: string;\n}\n\nconst clamp = (value: number) => Math.min(100, Math.max(0, value));\n// Two decimals keep a drag smooth on wide images without a noisy value.\nconst round = (value: number) => Math.round(value * 100) / 100;\n// Movement before a touch counts as a horizontal drag rather than a scroll.\nconst TOUCH_SLOP = 6;\n// Half the handle, so grabbing it keeps the grab point instead of jumping.\nconst HANDLE_RADIUS = 20;\n// How far, in percent, the first-view hint sweeps each way, and how long.\nconst HINT_REACH = 10;\nconst HINT_DURATION = 1.6;\n// Divider speed (percent of the width per second) that reaches the full bend.\nconst BEND_SPEED = 250;\n// How far the line's ends trail its middle at full bend, as a share of the height.\nconst BEND_MAX = 0.12;\n// How far each chevron moves out from the center, in pixels.\nconst CHEVRON_SPLIT = { rest: 0, hover: 1.5, drag: 3 };\n\ntype Gesture = {\n  id: number;\n  left: number;\n  width: number;\n  startX: number;\n  startY: number;\n  /** Pointer distance from the divider when the handle was grabbed. */\n  offset: number;\n  /** False while a touch has not yet proved to be a horizontal drag. */\n  active: boolean;\n};\n\n/**\n * Compare two images (or any two layers) with a draggable divider. Drag the\n * handle or anywhere on the frame, click to glide the divider there, or use\n * the arrow keys. On touch, a vertical swipe still scrolls the page.\n */\nexport function BeforeAfterSlider({\n  before,\n  after,\n  value,\n  defaultValue = 50,\n  onValueChange,\n  showLabels = true,\n  hint = true,\n  disabled = false,\n  labels,\n  className,\n}: BeforeAfterSliderProps) {\n  const t = useMessages(\"beforeAfterSlider\", beforeAfterSliderMessages, labels);\n  const reduce = useReducedMotion();\n  const [internal, setInternal] = useState(() => clamp(defaultValue));\n  const controlled = value !== undefined;\n  const current = clamp(controlled ? value : internal);\n  const [dragging, setDragging] = useState(false);\n  const [hovered, setHovered] = useState(false);\n  const hoverCapable = useHoverCapable();\n  const gesture = useRef<Gesture | null>(null);\n  const frameRef = useRef<HTMLDivElement>(null);\n  const handleRef = useRef<HTMLDivElement>(null);\n  const inView = useInView(frameRef, { once: true, amount: 0.6 });\n  // The hint plays once per mount and never after the user has touched it.\n  const hintState = useRef<\"pending\" | \"done\">(hint ? \"pending\" : \"done\");\n  const hintRun = useRef<AnimationPlaybackControls | null>(null);\n  // The next position change glides (a click or a key) instead of following\n  // the pointer exactly.\n  const glide = useRef(false);\n\n  const position = useMotionValue(current);\n  const width = useMotionValue(0);\n  const height = useMotionValue(0);\n  // The line bends like a rope held at the handle: its middle follows the\n  // divider and its ends trail behind, more the faster it moves, then it\n  // wobbles straight when it stops. Velocity covers drags, glides and the hint.\n  const velocity = useVelocity(position);\n  const pull = useTransform(velocity, [-BEND_SPEED, 0, BEND_SPEED], [-1, 0, 1]);\n  const bend = useSpring(useTransform(pull, (amount) => (reduce ? 0 : amount)), SPRING_MOUSE);\n  // clip-path, not a resize: the before layer keeps its full size, so the\n  // two layers stay aligned pixel for pixel at every position. The cut follows\n  // the line's curve. Until the frame is measured it is a plain straight cut.\n  const clipPath = useTransform([position, bend, width, height], ([p, amount, w, h]: number[]) => {\n    if (!w || !h) return `inset(0 ${100 - p}% 0 0)`;\n    const middle = (p / 100) * w;\n    const trail = amount * BEND_MAX * h;\n    // The control point sits past the middle by as much as the ends trail,\n    // so the curve passes exactly through the divider at half height.\n    return `path(\"M0 0 L${middle - trail} 0 Q${middle + trail} ${h / 2} ${middle - trail} ${h} L0 ${h} Z\")`;\n  });\n  // The same curve for the drawn line, in a 100 by 100 box stretched over the\n  // frame, so it needs no measuring for its straight resting shape.\n  const lineD = useTransform([position, bend, width, height], ([p, amount, w, h]: number[]) => {\n    const trail = w ? ((amount * BEND_MAX * h) / w) * 100 : 0;\n    return `M${p - trail} 0 Q${p + trail} 50 ${p - trail} 100`;\n  });\n  const dividerX = useTransform(position, (p) => `${p}%`);\n  // Each label fades as the divider comes close, so neither is cut in half.\n  const beforeOpacity = useTransform(position, [8, 22], [0, 1]);\n  const afterOpacity = useTransform(position, [78, 92], [1, 0]);\n\n  useLayoutEffect(() => {\n    if (reduce || !glide.current) {\n      position.stop();\n      // set, not jump: jump zeroes the velocity the drag bend is read from.\n      if (reduce) position.jump(current);\n      else position.set(current);\n      return;\n    }\n    glide.current = false;\n    animate(position, current, { type: \"spring\", ...SPRING_GLIDE });\n  }, [current, position, reduce]);\n  useEffect(() => () => position.stop(), [position]);\n\n  // The curved cut is drawn in pixels, so it needs the frame's size.\n  useLayoutEffect(() => {\n    const frame = frameRef.current;\n    if (!frame) return;\n    const measure = () => {\n      const rect = frame.getBoundingClientRect();\n      width.set(rect.width);\n      height.set(rect.height);\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(frame);\n    return () => observer.disconnect();\n  }, [width, height]);\n\n  // The hint moves only the picture, never the value, so assistive tech hears\n  // nothing and a controlled parent sees no change.\n  useEffect(() => {\n    if (!inView || reduce || disabled || hintState.current !== \"pending\") return;\n    const from = position.get();\n    const right = Math.min(100, from + HINT_REACH);\n    const left = Math.max(0, from - HINT_REACH);\n    const run = animate(position, [from, right, left, from], {\n      duration: HINT_DURATION,\n      ease: EASE_IN_OUT,\n      times: [0, 0.3, 0.7, 1],\n      delay: 0.25,\n    });\n    hintRun.current = run;\n    // Done only once it finishes or the user cuts in (stopHint), so a cleanup\n    // that stopped it early lets the next run play it from the start.\n    run.then(() => {\n      if (hintRun.current !== run) return;\n      hintRun.current = null;\n      hintState.current = \"done\";\n    });\n    return () => {\n      if (hintRun.current !== run) return;\n      run.stop();\n      hintRun.current = null;\n      position.jump(from);\n    };\n  }, [inView, reduce, disabled, position]);\n\n  // Any input ends the hint where the value says the divider is.\n  const stopHint = () => {\n    hintState.current = \"done\";\n    if (!hintRun.current) return;\n    hintRun.current.stop();\n    hintRun.current = null;\n    position.jump(current);\n  };\n\n  const commit = (next: number, smooth: boolean) => {\n    const clean = round(clamp(next));\n    if (clean === current) return;\n    glide.current = smooth;\n    if (!controlled) setInternal(clean);\n    onValueChange?.(clean);\n  };\n\n  const fromPointer = (active: Gesture, clientX: number) =>\n    ((clientX - active.left - active.offset) / active.width) * 100;\n\n  const start = (event: PointerEvent<HTMLDivElement>, active: Gesture) => {\n    active.active = true;\n    setDragging(true);\n    capturePointer(event.currentTarget, event.pointerId);\n    handleRef.current?.focus({ preventScroll: true });\n  };\n\n  const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {\n    if (disabled || event.button !== 0 || gesture.current) return;\n    stopHint();\n    const rect = event.currentTarget.getBoundingClientRect();\n    if (!rect.width) return;\n    const dividerPx = (position.get() / 100) * rect.width;\n    const pointerPx = event.clientX - rect.left;\n    const onHandle = Math.abs(pointerPx - dividerPx) <= HANDLE_RADIUS;\n    const active: Gesture = {\n      id: event.pointerId,\n      left: rect.left,\n      width: rect.width,\n      startX: event.clientX,\n      startY: event.clientY,\n      offset: onHandle ? pointerPx - dividerPx : 0,\n      active: false,\n    };\n    gesture.current = active;\n    // A touch waits to see which way it moves; a mouse or pen drags at once.\n    if (event.pointerType === \"touch\") return;\n    event.preventDefault();\n    start(event, active);\n    if (!onHandle) commit(fromPointer(active, event.clientX), true);\n  };\n\n  const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {\n    const active = gesture.current;\n    if (!active || active.id !== event.pointerId || disabled) return;\n    if (!active.active) {\n      const dx = Math.abs(event.clientX - active.startX);\n      const dy = Math.abs(event.clientY - active.startY);\n      if (dx < TOUCH_SLOP && dy < TOUCH_SLOP) return;\n      // A mostly vertical swipe belongs to the page.\n      if (dy >= dx) {\n        gesture.current = null;\n        return;\n      }\n      start(event, active);\n    }\n    commit(fromPointer(active, event.clientX), false);\n  };\n\n  const end = (event: PointerEvent<HTMLDivElement>) => {\n    const active = gesture.current;\n    if (!active || active.id !== event.pointerId) return;\n    // Clear first: releasing capture fires lostpointercapture, which lands here again.\n    gesture.current = null;\n    // A tap that never became a drag glides the divider to the tap.\n    if (!active.active && event.type === \"pointerup\" && !disabled) {\n      commit(fromPointer(active, event.clientX), true);\n    }\n    setDragging(false);\n    releasePointer(event.currentTarget, event.pointerId);\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    if (disabled) return;\n    const step = event.shiftKey ? 10 : 1;\n    const next = {\n      ArrowRight: current + step,\n      ArrowUp: current + step,\n      ArrowLeft: current - step,\n      ArrowDown: current - step,\n      PageUp: current + 10,\n      PageDown: current - 10,\n      Home: 0,\n      End: 100,\n    }[event.key];\n    if (next === undefined) return;\n    event.preventDefault();\n    stopHint();\n    commit(next, true);\n  };\n\n  const chip =\n    \"pointer-events-none absolute top-3 rounded-full bg-black/45 px-2.5 py-1 text-xs font-medium text-white backdrop-blur-sm\";\n\n  return (\n    // biome-ignore lint/a11y/noStaticElementInteractions: a pointer surface for the slider below, which owns focus, keys and the accessible value.\n    <div\n      ref={frameRef}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={end}\n      onPointerCancel={end}\n      onLostPointerCapture={(event) => {\n        // A touch is implicitly captured by the child it landed on; taking\n        // capture for the frame makes that child lose it, and the event\n        // bubbles here. Only the frame's own capture ends the drag.\n        if (event.target === event.currentTarget) end(event);\n      }}\n      // Images inside are the consumer's; stop the browser dragging them out.\n      onDragStart={(event) => event.preventDefault()}\n      className={cn(\n        \"relative isolate aspect-[3/2] w-full touch-pan-y overflow-hidden rounded-2xl bg-muted\",\n        TOUCH_GESTURE_CLASS,\n        disabled ? \"opacity-60\" : dragging ? \"cursor-grabbing\" : \"cursor-ew-resize\",\n        className,\n      )}\n    >\n      <div className=\"absolute inset-0\">{after}</div>\n      <motion.div className=\"absolute inset-0\" style={{ clipPath }}>\n        {before}\n      </motion.div>\n\n      {showLabels ? (\n        <div aria-hidden=\"true\">\n          <motion.span className={cn(chip, \"left-3\")} style={{ opacity: beforeOpacity }}>\n            {t(\"before\")}\n          </motion.span>\n          <motion.span className={cn(chip, \"right-3\")} style={{ opacity: afterOpacity }}>\n            {t(\"after\")}\n          </motion.span>\n        </div>\n      ) : null}\n\n      {/* The stroke stays its pixel width however the box is stretched. */}\n      <svg\n        aria-hidden=\"true\"\n        viewBox=\"0 0 100 100\"\n        preserveAspectRatio=\"none\"\n        className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\"\n      >\n        <motion.path\n          d={lineD}\n          fill=\"none\"\n          stroke=\"rgb(0 0 0 / 0.14)\"\n          strokeLinecap=\"square\"\n          vectorEffect=\"non-scaling-stroke\"\n          initial={false}\n          animate={{ strokeWidth: dragging && !reduce ? 5.5 : 4 }}\n          transition={SPRING_PRESS}\n        />\n        <motion.path\n          d={lineD}\n          fill=\"none\"\n          stroke=\"white\"\n          strokeLinecap=\"square\"\n          vectorEffect=\"non-scaling-stroke\"\n          initial={false}\n          animate={{ strokeWidth: dragging && !reduce ? 3.5 : 2 }}\n          transition={SPRING_PRESS}\n        />\n      </svg>\n\n      {/* Full width so a percent translate moves the handle by a percent of the frame. */}\n      <motion.div className=\"pointer-events-none absolute inset-0\" style={{ x: dividerX }}>\n        <div className=\"absolute top-1/2 left-0 -translate-x-1/2 -translate-y-1/2\">\n          <motion.div\n            ref={handleRef}\n            role=\"slider\"\n            tabIndex={disabled ? -1 : 0}\n            aria-label={t(\"label\")}\n            aria-valuemin={0}\n            aria-valuemax={100}\n            aria-valuenow={Math.round(current)}\n            aria-valuetext={t(\"valueText\", { value: Math.round(current) })}\n            aria-orientation=\"horizontal\"\n            aria-disabled={disabled || undefined}\n            onKeyDown={onKeyDown}\n            onPointerEnter={(event) => {\n              if (hoverCapable && event.pointerType !== \"touch\") setHovered(true);\n            }}\n            onPointerLeave={() => setHovered(false)}\n            animate={{ scale: reduce ? 1 : dragging ? 1.08 : hovered ? 1.04 : 1 }}\n            transition={SPRING_PRESS}\n            className=\"pointer-events-auto flex size-10 items-center justify-center rounded-full bg-white text-neutral-900 shadow-[0_0_0_1px_rgb(0_0_0/0.12)] outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-black/20\"\n          >\n            {/* The chevrons part as the handle is hovered and grabbed. */}\n            {([ChevronLeft, ChevronRight] as const).map((Icon, index) => {\n              const split = reduce\n                ? 0\n                : CHEVRON_SPLIT[dragging ? \"drag\" : hovered ? \"hover\" : \"rest\"];\n              return (\n                <motion.span\n                  key={index === 0 ? \"left\" : \"right\"}\n                  aria-hidden=\"true\"\n                  animate={{ x: index === 0 ? -split : split }}\n                  transition={SPRING_PRESS}\n                  className={cn(\"flex\", index === 0 ? \"-mr-1\" : \"-ml-1\")}\n                >\n                  <Icon className=\"size-3.5\" strokeWidth={2.5} />\n                </motion.span>\n              );\n            })}\n          </motion.div>\n        </div>\n      </motion.div>\n    </div>\n  );\n}\n"},{"path":"lib/ease.ts","type":"registry:lib","target":"@lib/ease.ts","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps — label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances — modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides — pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) — critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n"},{"path":"lib/hooks/use-hover-capable.ts","type":"registry:hook","target":"@lib/hooks/use-hover-capable.ts","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true only on devices that have a true hover (mouse / trackpad).\n * Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere\n * — gate hover-only effects (scale lifts, magnetic pulls) behind this.\n */\nexport function useHoverCapable() {\n  const [canHover, setCanHover] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\" || !window.matchMedia) return;\n    const mq = window.matchMedia(\"(hover: hover) and (pointer: fine)\");\n    const update = () => setCanHover(mq.matches);\n    update();\n    mq.addEventListener?.(\"change\", update);\n    return () => mq.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canHover;\n}\n"},{"path":"lib/i18n.tsx","type":"registry:lib","target":"@lib/i18n.tsx","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/touch.ts","type":"registry:lib","target":"@lib/touch.ts","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page — the long-press selection callout and the selection it drags in with\n// it — and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant — which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing — the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis — leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures — a coarse\n * pointer — so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction — the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal — a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs — routine on iOS, where the\n * system can claim the touch first — and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active — implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer — a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger — so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it — `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"}]}