{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pull-to-refresh",
  "type": "registry:ui",
  "title": "Pull To Refresh",
  "description": "Pull a list down from its top to load what is new, the gesture a phone reader already knows. The pull is one finger and one path, so it always has a twin: a Refresh button that is visible wherever the pointer is a mouse, and reachable by keyboard and…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "feedback",
    "pattern"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/spinner.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/pull-to-refresh.tsx",
      "target": "components/ui/patterns/pull-to-refresh.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/pull-to-refresh v1.1.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/pull-to-refresh\n// What changed since: https://ds.interlace.tools/c/pull-to-refresh#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — PullToRefresh\n *\n * Pull a list down from its top to load what is new, the gesture a phone\n * reader already knows. The pull is one finger and one path, so it always\n * has a twin: a Refresh button that is visible wherever the pointer is a\n * mouse, and reachable by keyboard and screen reader everywhere else\n * (WCAG 2.5.1). What happens is said in words in a live region.\n *\n * ## Anatomy\n *\n *   <div data-slot=\"pull-to-refresh\" data-state=\"idle|pulling|armed|refreshing|settling\">\n *     <button data-slot=\"pull-to-refresh-button\">Refresh</button>\n *     <div data-slot=\"pull-to-refresh-indicator\" aria-hidden>{arrow | spinner}</div>\n *     <div data-slot=\"pull-to-refresh-content\">{children}</div>\n *     <span role=\"status\">{Refreshing… | Updated}</span>\n *   </div>\n *\n * ## The gesture\n *\n * It starts only when the page (and this region, if it scrolls) is at its\n * top, the finger moves down more than across, and past a few pixels of\n * slack. The distance is damped, so it feels like pulling against a spring,\n * and stops growing past `threshold`. Releasing past `threshold` refreshes;\n * releasing before it springs back. While pulling, the browser's own\n * pull-to-refresh and bounce are held back, so only one thing happens.\n *\n * ## Motion\n *\n * The content and the indicator follow the finger (a transform, set on a\n * CSS variable, no re-render per move); the arrow turns as the pull nears\n * the threshold and flips when releasing will refresh. On release they\n * settle back with `--ease-move` (250ms). Under reduced motion nothing\n * moves: the indicator fades in place and the content stays still.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                 | Where in this file                                 |\n * | ---- | ----------------------- | -------------------------------------------------- |\n * | R4   | Extends native el       | `React.ComponentProps<'div'>`                      |\n * | R6   | data-slot per part      | pull-to-refresh, -button, -indicator, -content     |\n * | R7   | className merged + rest | `cn(BASE, className)` + `{...props}`               |\n * | R14  | Declares min viewport   | `data-min-viewport` + exported const               |\n * | R25  | Client component        | touch listeners, the refresh promise               |\n * | R26  | A11y                    | a real button twin, a live region, reduced motion  |\n */\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { Spinner } from '@/components/ui/spinner';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nexport type PullToRefreshState = 'idle' | 'pulling' | 'armed' | 'refreshing' | 'settling';\n\nexport interface PullToRefreshLabels {\n  /** The button twin of the gesture. @default 'Refresh' */\n  button: string;\n  /** Said while refreshing. @default 'Refreshing' */\n  refreshing: string;\n  /** Said when the refresh has finished. @default 'Updated' */\n  done: string;\n  /** Said when the refresh failed. @default 'Could not refresh' */\n  failed: string;\n}\n\nconst LABELS: PullToRefreshLabels = {\n  button: 'Refresh',\n  refreshing: 'Refreshing',\n  done: 'Updated',\n  failed: 'Could not refresh',\n};\n\nexport interface PullToRefreshProps extends React.ComponentProps<'div'> {\n  /** Load what is new. The indicator spins until the promise settles. */\n  onRefresh: () => Promise<unknown> | void;\n  /** Pull distance, in CSS pixels after damping, that arms the refresh. @default 64 */\n  threshold?: number;\n  /** Turn the gesture and the button off, e.g. while offline. @default false */\n  disabled?: boolean;\n  /**\n   * The Refresh button: `auto` shows it wherever the pointer is fine (a mouse) and\n   * keeps it for keyboard and screen readers elsewhere, visible on focus; `hidden`\n   * when the page already has a refresh control of its own. @default 'auto'\n   */\n  button?: 'auto' | 'hidden';\n  /** Words, in the page's language. */\n  labels?: Partial<PullToRefreshLabels>;\n}\n\n/** Slack before a touch counts as a pull. */\nconst SLOP = 6;\n/** How long the spring back takes: --duration-medium. */\nconst SETTLE_MS = 250;\n\n/** The finger's travel, damped: half speed up to the threshold, a fifth past it. */\nexport function dampPull(distance: number, threshold: number): number {\n  if (distance <= 0) return 0;\n  const half = distance / 2;\n  if (half <= threshold) return half;\n  return Math.min(threshold * 1.5, threshold + (half - threshold) / 5);\n}\n\nfunction scrolledToTop(el: HTMLElement): boolean {\n  return window.scrollY <= 0 && el.scrollTop <= 0;\n}\n\nfunction PullToRefresh({\n  onRefresh,\n  threshold = 64,\n  disabled = false,\n  button = 'auto',\n  labels: labelsProp,\n  className,\n  children,\n  ...props\n}: PullToRefreshProps) {\n  const labels = { ...LABELS, ...labelsProp };\n  const reduced = useReducedMotion();\n  const ref = React.useRef<HTMLDivElement>(null);\n  const [state, setState] = React.useState<PullToRefreshState>('idle');\n  const [message, setMessage] = React.useState('');\n  const stateRef = React.useRef(state);\n  stateRef.current = state;\n  const refreshRef = React.useRef(onRefresh);\n  refreshRef.current = onRefresh;\n  const mounted = React.useRef(true);\n  React.useEffect(\n    () => () => {\n      mounted.current = false;\n    },\n    [],\n  );\n\n  const setPull = React.useCallback((px: number) => {\n    const el = ref.current;\n    /* c8 ignore next */\n    if (!el) return;\n    el.style.setProperty('--pull', `${px}px`);\n  }, []);\n\n  /** Spring back, then drop the transform so fixed children are not held by it. */\n  const settleTimer = React.useRef<ReturnType<typeof setTimeout>>(undefined);\n  const settle = React.useCallback(() => {\n    stateRef.current = 'settling';\n    setState('settling');\n    setPull(0);\n    clearTimeout(settleTimer.current);\n    settleTimer.current = setTimeout(() => {\n      if (stateRef.current !== 'settling') return;\n      stateRef.current = 'idle';\n      setState('idle');\n    }, SETTLE_MS);\n  }, [setPull]);\n  React.useEffect(() => () => clearTimeout(settleTimer.current), []);\n\n  // Never re-entered: the button is disabled and a pull cannot start while refreshing.\n  const refresh = React.useCallback(async () => {\n    stateRef.current = 'refreshing';\n    setState('refreshing');\n    setMessage(labels.refreshing);\n    setPull(threshold);\n    let ok = true;\n    try {\n      await refreshRef.current();\n    } catch {\n      ok = false;\n    }\n    if (!mounted.current) return;\n    setMessage(ok ? labels.done : labels.failed);\n    settle();\n  }, [labels.refreshing, labels.done, labels.failed, setPull, settle, threshold]);\n\n  React.useEffect(() => {\n    const el = ref.current;\n    /* c8 ignore next */\n    if (!el || disabled) return;\n    let start: { x: number; y: number } | null = null;\n    let pulling = false;\n    let pull = 0;\n\n    const onStart = (event: TouchEvent) => {\n      if (event.touches.length !== 1 || stateRef.current === 'refreshing' || !scrolledToTop(el)) {\n        start = null;\n        return;\n      }\n      const touch = event.touches[0]!;\n      start = { x: touch.clientX, y: touch.clientY };\n      pulling = false;\n      pull = 0;\n    };\n    const onMove = (event: TouchEvent) => {\n      if (!start) return;\n      const touch = event.touches[0]!;\n      const dy = touch.clientY - start.y;\n      const dx = touch.clientX - start.x;\n      if (!pulling) {\n        if (Math.abs(dy) < SLOP && Math.abs(dx) < SLOP) return;\n        // Across or up: a scroll or a swipe, not a pull.\n        if (dy <= 0 || Math.abs(dx) > Math.abs(dy)) {\n          start = null;\n          return;\n        }\n        pulling = true;\n      }\n      if (event.cancelable) event.preventDefault();\n      pull = dampPull(dy - SLOP, threshold);\n      setPull(pull);\n      const next = pull >= threshold ? 'armed' : 'pulling';\n      if (stateRef.current !== next) {\n        stateRef.current = next;\n        setState(next);\n      }\n    };\n    const onEnd = () => {\n      if (!start || !pulling) {\n        start = null;\n        return;\n      }\n      start = null;\n      pulling = false;\n      if (pull >= threshold) {\n        void refresh();\n      } else {\n        settle();\n      }\n    };\n\n    // A cancel is the system cutting the gesture short (a call, a fourth finger): never refresh.\n    const onCancel = () => {\n      const wasPulling = start !== null && pulling;\n      start = null;\n      pulling = false;\n      if (wasPulling) settle();\n    };\n\n    el.addEventListener('touchstart', onStart, { passive: true });\n    el.addEventListener('touchmove', onMove, { passive: false });\n    el.addEventListener('touchend', onEnd);\n    el.addEventListener('touchcancel', onCancel);\n    return () => {\n      el.removeEventListener('touchstart', onStart);\n      el.removeEventListener('touchmove', onMove);\n      el.removeEventListener('touchend', onEnd);\n      el.removeEventListener('touchcancel', onCancel);\n    };\n  }, [disabled, refresh, setPull, settle, threshold]);\n\n  const moving = state === 'pulling' || state === 'armed';\n  return (\n    <div\n      ref={ref}\n      data-slot=\"pull-to-refresh\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      data-state={state}\n      aria-busy={state === 'refreshing' || undefined}\n      className={cn('relative [--pull:0px]', moving && 'overscroll-y-contain', className)}\n      {...props}\n    >\n      {button === 'hidden' ? null : (\n        <div className=\"pointer-fine:flex pointer-fine:justify-end\">\n          <button\n            type=\"button\"\n            data-slot=\"pull-to-refresh-button\"\n            disabled={disabled || state === 'refreshing'}\n            onClick={() => void refresh()}\n            className={cn(\n              'sr-only focus-visible:not-sr-only pointer-fine:not-sr-only',\n              'text-muted-foreground hover:text-foreground hover:bg-muted inline-flex min-h-9 items-center gap-2 rounded-md px-3 text-sm font-medium',\n              'focus-visible:ring-ring focus-visible:ring-offset-background focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden',\n              'disabled:pointer-events-none disabled:opacity-60',\n            )}\n          >\n            <svg\n              aria-hidden\n              focusable=\"false\"\n              viewBox=\"0 0 24 24\"\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth={2}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              className=\"size-4\"\n            >\n              <path d=\"M21 12a9 9 0 1 1-3-6.7L21 8\" />\n              <path d=\"M21 3v5h-5\" />\n            </svg>\n            {labels.button}\n          </button>\n        </div>\n      )}\n      <div\n        aria-hidden\n        data-slot=\"pull-to-refresh-indicator\"\n        className={cn(\n          'pointer-events-none absolute inset-x-0 top-0 z-raised flex justify-center',\n          reduced ? 'translate-y-2' : 'translate-y-[calc(var(--pull)-2.75rem)]',\n          state === 'idle' || state === 'settling' ? 'opacity-0' : 'opacity-100',\n          !moving && 'motion-safe:transition-[translate,opacity] motion-safe:duration-(--duration-medium) motion-safe:ease-move',\n        )}\n      >\n        <span className=\"bg-background border-border text-foreground flex size-9 items-center justify-center rounded-full border shadow-sm\">\n          {state === 'refreshing' ? (\n            <Spinner decorative size=\"sm\" />\n          ) : (\n            <svg\n              viewBox=\"0 0 24 24\"\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth={2}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              className={cn(\n                'size-4',\n                state === 'armed' && 'rotate-180',\n                'motion-safe:transition-transform motion-safe:duration-(--duration-base) motion-safe:ease-move',\n              )}\n            >\n              <path d=\"M12 5v14\" />\n              <path d=\"m19 12-7 7-7-7\" />\n            </svg>\n          )}\n        </span>\n      </div>\n      <div\n        data-slot=\"pull-to-refresh-content\"\n        className={cn(\n          !reduced && state !== 'idle' && 'translate-y-(--pull)',\n          !moving && 'motion-safe:transition-[translate] motion-safe:duration-(--duration-medium) motion-safe:ease-move',\n        )}\n      >\n        {children}\n      </div>\n      <span role=\"status\" className=\"sr-only\">\n        {message}\n      </span>\n    </div>\n  );\n}\nPullToRefresh.displayName = 'PullToRefresh';\n\nexport { PullToRefresh };\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/pull-to-refresh\n\nInstalled to `components/ui/patterns/pull-to-refresh.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/pull-to-refresh';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/pull-to-refresh\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
