{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "swipe-row",
  "title": "Swipe row",
  "description": "iOS trailing swipe actions for a list row on touch screens.",
  "registryDependencies": [
    "@khaeli/utils"
  ],
  "files": [
    {
      "path": "registry/khaeli/ui/swipe-row.tsx",
      "content": "\"use client\"\n\nimport {\n  useEffect,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type ReactNode,\n} from \"react\"\nimport { cn } from \"@/lib/utils\"\n\n// --- SwipeRow ---\n// iOS 26 trailing swipe actions (Messages): the row content slides left over\n// 48px circular action buttons, 8px apart, right-aligned 12px from the edge;\n// the content's corners round to 26px while it is displaced; a full swipe\n// (past 60% of the row) commits the trailing-most action. Active only under\n// `(pointer: coarse)` — mouse/desktop renders the children untouched. The\n// actions are real buttons in the tab order (focusing one reveals the tray),\n// so nothing is swipe-only for keyboards or screen readers. The sliding\n// content paints `bg-inherit`, so give the row its background via className.\n\ninterface SwipeAction {\n  label: string\n  icon: ReactNode\n  tone?: \"primary\" | \"destructive\" | \"neutral\"\n  onAction: () => void\n}\n\nconst BUTTON = 48\nconst GAP = 8\nconst EDGE = 12\n// Past the snap point the content follows the finger at a quarter speed\n// (UIScrollView rubber-band feel).\nconst RESIST = 0.25\n// Releases faster than this (px/ms ≈ 110 px/s) carry intent even when the\n// distance thresholds were not met (audit §4: velocity-based dismissal).\nconst FLICK = 0.11\n// Axis lock: the gesture owns the row only after 10px of mostly-horizontal\n// travel; vertical intent scrolls the page (touch-action: pan-y).\nconst LOCK = 10\n\nconst ACTION_TONES = {\n  primary: \"bg-primary text-primary-foreground\",\n  // --destructive pales in dark; the solid red is the token a white label is paired with (as FancyButton's).\n  destructive: \"bg-destructive-solid text-white\",\n  // Messages' non-tinted action is a solid gray with a contrasting glyph.\n  neutral: \"bg-muted-foreground text-background\",\n} as const\n\nconst COARSE = \"(pointer: coarse)\"\n\nfunction subscribeCoarse(onChange: () => void) {\n  const media = window.matchMedia(COARSE)\n  media.addEventListener(\"change\", onChange)\n  return () => media.removeEventListener(\"change\", onChange)\n}\n\n/** False on the server and on fine-pointer devices; gestures are JS-only, so desktop markup never changes. */\nfunction useCoarsePointer() {\n  return useSyncExternalStore(\n    subscribeCoarse,\n    () => window.matchMedia(COARSE).matches,\n    () => false\n  )\n}\n\nfunction SwipeRow({\n  actions,\n  children,\n  className,\n}: {\n  actions: SwipeAction[]\n  children: ReactNode\n  className?: string\n}) {\n  const coarse = useCoarsePointer()\n  if (!coarse || actions.length === 0) return <>{children}</>\n  return (\n    <SwipeRowTouch actions={actions} className={className}>\n      {children}\n    </SwipeRowTouch>\n  )\n}\n\nfunction SwipeRowTouch({\n  actions,\n  children,\n  className,\n}: {\n  actions: SwipeAction[]\n  children: ReactNode\n  className?: string\n}) {\n  const root = useRef<HTMLDivElement>(null)\n  const [offset, setOffset] = useState(0)\n  const [dragging, setDragging] = useState(false)\n  const content = useRef<HTMLDivElement>(null)\n  // True only for the full-swipe commit return, which earns a soft overshoot.\n  const [springy, setSpringy] = useState(false)\n  const drag = useRef<{\n    id: number\n    startX: number\n    startY: number\n    base: number\n    raw: number\n    locked: boolean\n    lastX: number\n    lastT: number\n    vx: number // px/ms, smoothed; negative = toward the tray (opening)\n  } | null>(null)\n  // Set when a horizontal drag just ended, so the click it produces on the\n  // row's own links/buttons is swallowed instead of navigating.\n  const suppressClick = useRef(false)\n\n  const openWidth = EDGE * 2 + actions.length * BUTTON + (actions.length - 1) * GAP\n  const open = offset !== 0\n\n  // A tap anywhere else or any scroll settles the tray closed (Messages).\n  useEffect(() => {\n    if (!open || dragging) return\n    const close = (event: Event) => {\n      if (event.target instanceof Node && root.current?.contains(event.target)) return\n      setOffset(0)\n    }\n    const closeOnScroll = () => setOffset(0)\n    document.addEventListener(\"pointerdown\", close, true)\n    document.addEventListener(\"scroll\", closeOnScroll, true)\n    return () => {\n      document.removeEventListener(\"pointerdown\", close, true)\n      document.removeEventListener(\"scroll\", closeOnScroll, true)\n    }\n  }, [open, dragging])\n\n  function rubber(raw: number) {\n    if (raw > 0) return raw * RESIST\n    if (raw < -openWidth) return -openWidth + (raw + openWidth) * RESIST\n    return raw\n  }\n\n  function settle(raw: number, vx: number) {\n    const width = root.current?.offsetWidth ?? 0\n    const flickOpen = vx < -FLICK\n    const flickClose = vx > FLICK\n    if (width > 0 && -raw > width * 0.6 && !flickClose) {\n      // Full swipe commits the trailing-most action with a light tick. The\n      // return trip keeps a soft overshoot; plain settles don't.\n      navigator.vibrate?.(10)\n      setSpringy(true)\n      setOffset(0)\n      actions[actions.length - 1]?.onAction()\n      return\n    }\n    setSpringy(false)\n    setOffset(\n      (flickOpen && raw < 0) || (!flickClose && raw < -openWidth / 2)\n        ? -openWidth\n        : 0\n    )\n  }\n\n  function onPointerDown(event: React.PointerEvent) {\n    // A new press starts a new gesture: any click from here on is its own.\n    // A touch swipe ends without a click, so the flag it set would otherwise\n    // wait for, and swallow, the next tap on an action.\n    suppressClick.current = false\n    if (event.pointerType === \"mouse\") return\n    // Grabbing mid-settle must start from where the row *looks*, not the\n    // offset it is animating toward — otherwise the first locked move snaps\n    // the content under the finger.\n    let base = offset\n    const node = content.current\n    if (node) {\n      const transform = getComputedStyle(node).transform\n      if (transform && transform !== \"none\") {\n        base = new DOMMatrixReadOnly(transform).m41\n      }\n    }\n    if (base !== offset) setOffset(base) // freeze the in-flight transition\n    drag.current = {\n      id: event.pointerId,\n      startX: event.clientX,\n      startY: event.clientY,\n      base,\n      raw: base,\n      locked: false,\n      lastX: event.clientX,\n      lastT: event.timeStamp,\n      vx: 0,\n    }\n  }\n\n  function onPointerMove(event: React.PointerEvent) {\n    const state = drag.current\n    if (!state || event.pointerId !== state.id) return\n    const dx = event.clientX - state.startX\n    const dy = event.clientY - state.startY\n    if (!state.locked) {\n      if (Math.abs(dy) > LOCK && Math.abs(dy) > Math.abs(dx)) {\n        // Vertical wins: hand the gesture back to the scroller.\n        drag.current = null\n        return\n      }\n      if (Math.abs(dx) <= LOCK) return\n      state.locked = true\n      root.current?.setPointerCapture(event.pointerId)\n      setDragging(true)\n    }\n    // Velocity sample (px/ms), exponentially smoothed: the newest event\n    // dominates, so a flick registers, but one noisy event cannot fake one.\n    const elapsed = event.timeStamp - state.lastT\n    if (elapsed > 0) {\n      const instant = (event.clientX - state.lastX) / elapsed\n      state.vx = state.vx * 0.2 + instant * 0.8\n      state.lastX = event.clientX\n      state.lastT = event.timeStamp\n    }\n    state.raw = state.base + dx\n    setOffset(rubber(state.raw))\n  }\n\n  function onPointerEnd(event: React.PointerEvent) {\n    const state = drag.current\n    if (!state || event.pointerId !== state.id) return\n    drag.current = null\n    if (!state.locked) return\n    suppressClick.current = true\n    setDragging(false)\n    if (event.type === \"pointercancel\") {\n      // No intent to read: snap to the nearest rest state, never commit.\n      // (state.base may be a frozen mid-settle offset — don't restore it.)\n      setOffset(state.raw < -openWidth / 2 ? -openWidth : 0)\n      return\n    }\n    // A pause before lifting voids the flick (velocity is now, not history).\n    const vx = event.timeStamp - state.lastT > 80 ? 0 : state.vx\n    settle(state.raw, vx)\n  }\n\n  function onClickCapture(event: React.MouseEvent) {\n    if (suppressClick.current) {\n      suppressClick.current = false\n      event.preventDefault()\n      event.stopPropagation()\n      return\n    }\n    // While the tray is out, a tap on the content closes it, nothing more.\n    const tray = root.current?.querySelector('[data-slot=\"swipe-row-actions\"]')\n    if (open && !(event.target instanceof Node && tray?.contains(event.target))) {\n      event.preventDefault()\n      event.stopPropagation()\n      setOffset(0)\n    }\n  }\n\n  return (\n    <div\n      ref={root}\n      data-slot=\"swipe-row\"\n      data-open={open || undefined}\n      className={cn(\"relative touch-pan-y overflow-hidden\", className)}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={onPointerEnd}\n      onPointerCancel={onPointerEnd}\n      onClickCapture={onClickCapture}\n    >\n      <div\n        data-slot=\"swipe-row-actions\"\n        className=\"absolute inset-y-0 right-0 flex items-center justify-end gap-2 pr-3\"\n        // Keyboard focus on a (visually covered) action slides the tray open,\n        // so the buttons are never interactable while invisible.\n        onFocus={() => setOffset(-openWidth)}\n        onBlur={(event) => {\n          if (!event.currentTarget.contains(event.relatedTarget)) setOffset(0)\n        }}\n      >\n        {actions.map((action) => (\n          <button\n            key={action.label}\n            type=\"button\"\n            aria-label={action.label}\n            onClick={() => {\n              setOffset(0)\n              action.onAction()\n            }}\n            className={cn(\n              \"flex size-12 shrink-0 items-center justify-center rounded-full [&_svg]:size-5\",\n              ACTION_TONES[action.tone ?? \"neutral\"]\n            )}\n          >\n            {action.icon}\n          </button>\n        ))}\n      </div>\n      <div\n        ref={content}\n        data-slot=\"swipe-row-content\"\n        className={cn(\n          \"relative bg-inherit\",\n          open && \"rounded-[26px]\",\n          !dragging && \"transition-transform duration-300 motion-reduce:transition-none\",\n          !dragging && (springy ? \"ease-spring-soft\" : \"ease-drawer\")\n        )}\n        style={{ transform: `translateX(${offset}px)` }}\n        onTransitionEnd={(event) => {\n          // The commit overshoot is one-shot; later closes (tap-away, scroll,\n          // blur) settle on the drawer curve.\n          if (event.target === event.currentTarget && event.propertyName === \"transform\")\n            setSpringy(false)\n        }}\n      >\n        {children}\n      </div>\n    </div>\n  )\n}\n\nexport { SwipeRow, type SwipeAction }\n",
      "type": "registry:ui"
    }
  ],
  "docs": "Install @khaeli/foundation first: this item's styling lives in its tokens and [data-slot] rules.",
  "type": "registry:ui"
}