{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"pagination","type":"registry:component","title":"Pagination","description":"Numbers roll in place like an odometer; the one you click never moves.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/pagination.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n\ntype Slot = number | \"start-gap\" | \"end-gap\";\n\n// Always seven slots once there are more than seven pages, so the control\n// keeps one width and the arrows never move while you page through.\nfunction slots(page: number, total: number): Slot[] {\n  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);\n  if (page <= 4) return [1, 2, 3, 4, 5, \"end-gap\", total];\n  if (page >= total - 3)\n    return [\n      1,\n      \"start-gap\",\n      ...Array.from({ length: 5 }, (_, i) => total - 4 + i),\n    ];\n  return [1, \"start-gap\", page - 1, page, page + 1, \"end-gap\", total];\n}\n\n// A gap counts as the middle of the pages it hides, so every slot has a\n// number to compare and knows which way to roll.\nfunction valueAt(layout: Slot[], i: number): number {\n  const slot = layout[i];\n  if (typeof slot === \"number\") return slot;\n  return ((layout[i - 1] as number) + (layout[i + 1] as number)) / 2;\n}\n\nconst sameLayout = (a: Slot[], b: Slot[]) =>\n  a.length === b.length && a.every((slot, i) => slot === b[i]);\n\n// Slots are fixed places; only their labels change, rolling like an\n// odometer wheel. Critically damped, so a label never overshoots its slot.\nconst ROLL = { type: \"spring\", duration: 0.35, bounce: 0 } as const;\nconst GLIDE = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n// How far a label travels as it rolls: past the 20px line box, so the\n// incoming and outgoing numbers never sit on top of each other.\nconst ROLL_DISTANCE = 14;\n// A finger has already lifted, so there is nothing under it to protect;\n// this only lets the tap's own feedback land before the numbers roll.\nconst TOUCH_SETTLE_MS = 450;\n\nconst slotBox = \"relative flex size-9 items-center justify-center sm:size-10\";\n\nconst control =\n  \"relative flex size-9 touch-manipulation items-center justify-center rounded-full text-sm font-medium tabular-nums outline-hidden transition-[scale,color,background-color] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground sm:size-10 motion-reduce:transition-[color,background-color]\";\n\nexport function Pagination({\n  page,\n  total,\n  onPageChange,\n  label = \"Pagination\",\n  className,\n}: {\n  page: number;\n  total: number;\n  onPageChange: (page: number) => void;\n  label?: string;\n  className?: string;\n}) {\n  const id = useId();\n  const listRef = useRef<HTMLUListElement>(null);\n  const settle = useRef<ReturnType<typeof setTimeout>>(undefined);\n  // Set by arrow keys, so focus follows the page only when the keyboard moved it.\n  const focusCurrent = useRef(false);\n  // The row as it stood when a number was clicked. It holds while the\n  // pointer is still over the control, so the number you just clicked stays\n  // under it (and the one beside it stays where you were aiming). Leaving\n  // the control recentres the window, the way a browser's tab strip waits\n  // for the mouse to leave before it closes up the gaps.\n  const [frozen, setFrozen] = useState<Slot[] | null>(null);\n  const standard = slots(page, total);\n  const visible = frozen && frozen.includes(page) ? frozen : standard;\n\n  // Each slot rolls up when its number grows and down when it shrinks.\n  // Worked out while rendering, from the layout that was on screen before.\n  const [shown, setShown] = useState<{ layout: Slot[]; dirs: number[] }>({\n    layout: visible,\n    dirs: [],\n  });\n  if (!sameLayout(shown.layout, visible)) {\n    setShown({\n      layout: visible,\n      dirs: visible.map((_, i) =>\n        i < shown.layout.length\n          ? Math.sign(valueAt(visible, i) - valueAt(shown.layout, i))\n          : 0,\n      ),\n    });\n  }\n\n  useEffect(() => () => clearTimeout(settle.current), []);\n\n  const go = (next: number) => {\n    const clamped = Math.min(Math.max(next, 1), total);\n    if (clamped !== page) onPageChange(clamped);\n  };\n\n  const recenter = () => {\n    clearTimeout(settle.current);\n    setFrozen(null);\n  };\n\n  useEffect(() => {\n    if (!focusCurrent.current) return;\n    focusCurrent.current = false;\n    listRef.current\n      ?.querySelector<HTMLElement>('[aria-current=\"page\"]')\n      ?.focus();\n  }, [page]);\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const target = {\n      ArrowLeft: page - 1,\n      ArrowRight: page + 1,\n      Home: 1,\n      End: total,\n    }[e.key];\n    if (target === undefined) return;\n    e.preventDefault();\n    focusCurrent.current = true;\n    recenter();\n    go(target);\n  };\n\n  const atStart = page <= 1;\n  const atEnd = page >= total;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <nav\n        aria-label={label}\n        className={cn(\"flex justify-center\", className)}\n        onPointerLeave={(e) => {\n          if (e.pointerType !== \"touch\") recenter();\n        }}\n        onBlur={(e) => {\n          if (!e.currentTarget.contains(e.relatedTarget as Node | null))\n            recenter();\n        }}\n      >\n        <ul\n          ref={listRef}\n          onKeyDown={onKeyDown}\n          className=\"relative flex items-center gap-0.5 sm:gap-1\"\n        >\n          <li>\n            {/* aria-disabled rather than disabled, so a focused arrow keeps\n                focus when it reaches the end instead of dropping it to the page. */}\n            <button\n              type=\"button\"\n              aria-label=\"Previous page\"\n              aria-disabled={atStart}\n              onClick={() => {\n                recenter();\n                go(page - 1);\n              }}\n              className={cn(\n                control,\n                atStart\n                  ? \"cursor-not-allowed text-muted-foreground opacity-40\"\n                  : \"text-foreground hover:bg-muted active:scale-[0.96]\",\n              )}\n            >\n              <Chevron direction=\"left\" />\n            </button>\n          </li>\n\n          {/* Keyed by position, not page: the seven places never move or\n              remount, only the numbers printed on them change. */}\n          {visible.map((slot, index) => {\n            const current = slot === page;\n            const dir = shown.dirs[index] ?? 0;\n            return (\n              <li key={index} className={slotBox}>\n                {typeof slot === \"number\" ? (\n                  <button\n                    type=\"button\"\n                    aria-label={`Page ${slot}`}\n                    aria-current={current ? \"page\" : undefined}\n                    onClick={(e) => {\n                      setFrozen(visible);\n                      go(slot);\n                      // Touch has no hover to wait out, so it recentres\n                      // on its own once the tap has registered.\n                      if (\n                        e.nativeEvent instanceof PointerEvent &&\n                        e.nativeEvent.pointerType === \"touch\"\n                      ) {\n                        clearTimeout(settle.current);\n                        settle.current = setTimeout(\n                          () => setFrozen(null),\n                          TOUCH_SETTLE_MS,\n                        );\n                      }\n                    }}\n                    className={cn(\n                      control,\n                      \"peer absolute inset-0\",\n                      !current &&\n                        \"hover:bg-muted active:scale-[0.96] motion-reduce:active:scale-100\",\n                    )}\n                  />\n                ) : null}\n                {current && (\n                  <motion.span\n                    layoutId={`${id}-pill`}\n                    transition={GLIDE}\n                    aria-hidden\n                    className=\"pointer-events-none absolute inset-0 rounded-full bg-foreground\"\n                  />\n                )}\n                <Wheel\n                  value={slot}\n                  dir={dir}\n                  className={cn(\n                    \"transition-[color,scale] duration-150 ease-out peer-active:scale-[0.96]\",\n                    current\n                      ? \"text-background\"\n                      : typeof slot === \"number\"\n                        ? \"text-muted-foreground peer-hover:text-foreground\"\n                        : \"text-muted-foreground\",\n                  )}\n                />\n              </li>\n            );\n          })}\n\n          <li>\n            <button\n              type=\"button\"\n              aria-label=\"Next page\"\n              aria-disabled={atEnd}\n              onClick={() => {\n                recenter();\n                go(page + 1);\n              }}\n              className={cn(\n                control,\n                atEnd\n                  ? \"cursor-not-allowed text-muted-foreground opacity-40\"\n                  : \"text-foreground hover:bg-muted active:scale-[0.96]\",\n              )}\n            >\n              <Chevron direction=\"right\" />\n            </button>\n          </li>\n        </ul>\n      </nav>\n    </MotionConfig>\n  );\n}\n\n// One place on the odometer. The old label rolls out one way while the new\n// one rolls in from the other, blurred at the edges of travel so the two\n// read as one wheel turning rather than two numbers swapping.\nfunction Wheel({\n  value,\n  dir,\n  className,\n}: {\n  value: Slot;\n  dir: number;\n  className?: string;\n}) {\n  const label = typeof value === \"number\" ? String(value) : \"…\";\n  return (\n    <span\n      aria-hidden\n      className={cn(\n        \"pointer-events-none relative grid h-5 place-items-center text-sm font-medium tabular-nums select-none\",\n        className,\n      )}\n    >\n      <AnimatePresence initial={false} custom={dir}>\n        <motion.span\n          key={label}\n          custom={dir}\n          variants={{\n            in: (d: number) => ({\n              opacity: 0,\n              y: d * ROLL_DISTANCE,\n              filter: \"blur(3px)\",\n            }),\n            rest: { opacity: 1, y: 0, filter: \"blur(0px)\", transition: ROLL },\n            // Leaves quicker than the new label arrives, so the eye lands on\n            // the incoming number.\n            out: (d: number) => ({\n              opacity: 0,\n              y: -d * ROLL_DISTANCE,\n              filter: \"blur(3px)\",\n              transition: { duration: 0.2, ease: EASE_OUT },\n            }),\n          }}\n          initial=\"in\"\n          animate=\"rest\"\n          exit=\"out\"\n          className=\"col-start-1 row-start-1\"\n        >\n          {label}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction Chevron({ direction }: { direction: \"left\" | \"right\" }) {\n  return (\n    <svg\n      viewBox=\"0 0 16 16\"\n      className=\"size-4\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      // 1.5 matches the medium-weight numbers beside it.\n      strokeWidth={1.5}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      aria-hidden\n    >\n      <path\n        d={\n          direction === \"left\"\n            ? \"M10 3.5 5.5 8l4.5 4.5\"\n            : \"m6 3.5 4.5 4.5L6 12.5\"\n        }\n      />\n    </svg>\n  );\n}\n\nconst PER_PAGE = 5;\nconst TOTAL_ITEMS = 100;\nconst CUSTOMERS = [\n  \"Acme Studio\",\n  \"Birchwood Labs\",\n  \"Cobalt & Co\",\n  \"Driftline\",\n  \"Evergreen Health\",\n  \"Fieldnote\",\n  \"Granite Works\",\n  \"Harbor Supply\",\n  \"Ironbark\",\n  \"Juniper Books\",\n  \"Kestrel Air\",\n];\n\nfunction invoice(n: number) {\n  // Deterministic pseudo-random amounts, so the server and client agree.\n  const cents = ((n * 7919) % 90000) + 4000;\n  return {\n    id: `INV-${1000 + n}`,\n    customer: CUSTOMERS[(n * 7) % CUSTOMERS.length],\n    amount: `$${(cents / 100).toLocaleString(\"en-US\", {\n      minimumFractionDigits: 2,\n    })}`,\n  };\n}\n\nexport default function PaginationDemo() {\n  const reduceMotion = useReducedMotion();\n  const pages = TOTAL_ITEMS / PER_PAGE;\n  const [page, setPage] = useState(1);\n  const [direction, setDirection] = useState(1);\n\n  const first = (page - 1) * PER_PAGE + 1;\n  const last = Math.min(page * PER_PAGE, TOTAL_ITEMS);\n  // Pages slide a hair in the direction of travel; reduced motion keeps\n  // only the fade.\n  const shift = reduceMotion ? 0 : 8;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div className=\"w-[min(480px,100%)]\">\n        <div className=\"rounded-2xl bg-background p-2 shadow-raised\">\n          <p\n            aria-live=\"polite\"\n            className=\"px-3 pt-1.5 pb-2 text-sm text-muted-foreground tabular-nums\"\n          >\n            Showing {first}-{last} of {TOTAL_ITEMS}\n          </p>\n          {/* Every page stacks in one grid cell, so the outgoing rows fade\n              out in place while the new ones fade in over them. */}\n          <div className=\"grid\">\n            <AnimatePresence initial={false} custom={direction}>\n              <motion.ul\n                key={page}\n                custom={direction}\n                variants={{\n                  enter: (d: number) => ({\n                    opacity: 0,\n                    x: d * shift,\n                    filter: reduceMotion ? \"blur(0px)\" : \"blur(4px)\",\n                  }),\n                  center: {\n                    opacity: 1,\n                    x: 0,\n                    filter: \"blur(0px)\",\n                    transition: { duration: 0.2, ease: EASE_OUT },\n                  },\n                  // Half the travel and quicker, so the old page gets out of\n                  // the way rather than competing with the new one.\n                  exit: (d: number) => ({\n                    opacity: 0,\n                    x: (-d * shift) / 2,\n                    transition: { duration: 0.12, ease: EASE_OUT },\n                  }),\n                }}\n                initial=\"enter\"\n                animate=\"center\"\n                exit=\"exit\"\n                className=\"col-start-1 row-start-1\"\n              >\n                {Array.from({ length: last - first + 1 }, (_, i) => {\n                  const item = invoice(first + i);\n                  return (\n                    <li\n                      key={item.id}\n                      className=\"flex h-12 items-center gap-3 rounded-xl px-3\"\n                    >\n                      <span className=\"min-w-0 flex-1 truncate text-[15px] text-foreground\">\n                        {item.customer}\n                      </span>\n                      <span className=\"font-mono text-xs text-muted-foreground\">\n                        {item.id}\n                      </span>\n                      <span className=\"w-20 text-right text-[15px] text-foreground tabular-nums\">\n                        {item.amount}\n                      </span>\n                    </li>\n                  );\n                })}\n              </motion.ul>\n            </AnimatePresence>\n          </div>\n        </div>\n\n        <Pagination\n          page={page}\n          total={pages}\n          onPageChange={(next) => {\n            setDirection(next > page ? 1 : -1);\n            setPage(next);\n          }}\n          label=\"Invoices pages\"\n          className=\"mt-4\"\n        />\n      </div>\n    </MotionConfig>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["navigation"],"docs":"From ui lab: https://lab.xevrion.dev/lab/pagination"}