{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pagination",
  "title": "Pagination",
  "description": "ui-sdk’s Pagination: Previous, Next and the pages between them, as buttons or links, in a nav, with First and Last, the range a page shows, a page-size Select and a field to type a page in. Drawn as the Tabs are: the pill slides to the current page, a backdrop follows the pointer, and the numbers roll as the range moves. The row keeps its width on every page and shows fewer pages when it is narrow.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/theme.json",
    "https://kinoui.com/r/highlight.json",
    "https://kinoui.com/r/number-input.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/pages.json",
    "https://kinoui.com/r/pill.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/roll.json",
    "https://kinoui.com/r/select.json",
    "https://kinoui.com/r/swap.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/pagination.tsx",
      "content": "'use client'\n\nimport {\n  isStep,\n  NumberInput,\n  NumberInputGroup,\n  NumberInputControl,\n} from '@/registry/components/kino/number-input'\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/registry/components/kino/select'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { useControllable } from '@/registry/lib/controllable'\nimport {\n  followPick,\n  followPointer,\n  highlightClassName,\n  itemMatching,\n  pickClassName,\n} from '@/registry/lib/highlight'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport { clampPage, pageCountOf, pageForSize, pageRange } from '@/registry/lib/pages'\nimport {\n  pillBackdropClassName,\n  pillClassName,\n  pillItemClassName,\n} from '@/registry/lib/pill'\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport { Roll } from '@/registry/lib/roll'\nimport { Swap, useSwapLeaving } from '@/registry/lib/swap'\nimport {\n  createPaginationController,\n  Pagination as PaginationPrimitive,\n  PaginationEllipsis as PaginationEllipsisPrimitive,\n  PaginationFirst as PaginationFirstPrimitive,\n  PaginationItem as PaginationItemPrimitive,\n  PaginationLast as PaginationLastPrimitive,\n  PaginationLink as PaginationLinkPrimitive,\n  PaginationList as PaginationListPrimitive,\n  PaginationNext as PaginationNextPrimitive,\n  PaginationPrevious as PaginationPreviousPrimitive,\n  paginationRange,\n} from '@ui-sdk/react/pagination'\nimport type { RenderProp } from '@ui-sdk/react/primitive'\nimport {\n  cloneElement,\n  type ComponentProps,\n  type CSSProperties,\n  createContext,\n  type HTMLAttributes,\n  type ReactElement,\n  type ReactNode,\n  type RefObject,\n  use,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\nimport { flushSync } from 'react-dom'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * A pager on ui-sdk's Pagination: the row of pages with Previous and Next,\n * and beside it what a table's footer needs, where the page sits in the\n * whole (\"21–40 of 4,800\"), how many rows a page holds, and a field to type\n * a page in. The row looks and moves like the Tabs: labels that darken on\n * hover, a backdrop that glides under the pointer, and a pill in the primary\n * colour that slides to the current page, with a copy of the row inside it\n * so each number changes colour exactly at its edge. The row keeps the same\n * number of places on every page, so nothing beside it moves: in the middle\n * of a long range the pill stays put and the numbers roll past it. A row too\n * wide for its room first drops the words beside Previous and Next, then\n * shows fewer pages.\n */\n\n// The current page in the row, not its copy in the pill, which has no slots.\nconst CURRENT = '[data-slot=pagination-link][aria-current=page]'\n\nconst ITEM =\n  '[data-slot=pagination-link], [data-slot=pagination-first], [data-slot=pagination-previous], [data-slot=pagination-next], [data-slot=pagination-last]'\n\nconst LAYERS = '[data-slot=pagination-backdrop], [data-slot=pagination-pill]'\n\n// The row and the pill's copy of it share this, so every number sits exactly on its twin.\nconst paginationRow = 'flex items-center gap-1'\n\n// A page is a square of the control's height, wider only when the last page's\n// number needs it, so every place is as wide as the widest and the row keeps\n// its width as the numbers change. `1ch` is a digit's width in tabular figures.\nconst itemLayout =\n  \"inline-flex h-(--control-height) min-w-[max(var(--control-height),calc(var(--pagination-digits,1)*1ch+0.75rem))] shrink-0 items-center justify-center gap-1.5 rounded-(--control-radius) px-1.5 text-sm font-medium whitespace-nowrap tabular-nums select-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\"\n\n// Previous and Next are a page's square around their arrow, and their word\n// beside it when there is room. The word's outer side matches the room the\n// square leaves beside the arrow, and it sits a quarter rem into the square,\n// so the gap to the arrow follows the density.\nconst stepLayout = 'min-w-(--control-height) px-0'\nconst stepArrow = 'flex size-(--control-height) shrink-0 items-center justify-center'\n// Until the row is measured, a narrow one leaves the words out already. Beside\n// the page field they always go: \"Previous Page 4\" would read as one phrase.\nconst stepWord =\n  '[[data-slot=pagination-list]:not([data-words])_&]:sr-only [[data-slot=pagination-list]:has([data-slot=pagination-page-field])_&]:sr-only @max-lg/pagination:[[data-slot=pagination]:not([data-mounted])_&]:sr-only'\n// Before the row is measured (as the page loads, before its script runs), a\n// narrow row shows only the current page, so nothing is cut at its edges.\nconst beforeFit =\n  '@max-md/pagination:[[data-slot=pagination]:not([data-mounted])_&]:hidden'\n\n// First and Last, when the row has no room for them.\nconst edgeHidden = '[[data-slot=pagination-list]:not([data-edges])_&]:hidden'\nconst previousWord = cn(stepWord, '-ms-1 pe-[calc((var(--control-height)-1rem)/2)]')\nconst nextWord = cn(stepWord, '-me-1 ps-[calc((var(--control-height)-1rem)/2)]')\n\ntype PaginationController = ReturnType<typeof createPaginationController>\n\n/** How many pages the row has room for, and whether its words and First and Last fit. */\ninterface Fit {\n  words: boolean\n  siblings: number\n  boundaries: number\n  edges: boolean\n}\n\ninterface PaginationContextValue {\n  page: number\n  /** The pages there are, or while the count is unknown, the pages known so far. */\n  pageCount: number\n  /** Whether the count of pages is known. */\n  known: boolean\n  /** How many items there are, when that is known. */\n  total: number | null\n  pageSize: number\n  controller: PaginationController\n  setPageSize: (pageSize: number) => void\n  /** The page a pressed page went to, so the row moves focus to it once it has rolled. */\n  refocusRef: RefObject<number | null>\n  /** The siblings and boundaries asked for. */\n  siblings: number\n  boundaries: number\n  fit: Fit\n  setFit: (fit: Fit) => void\n  linked: boolean\n  renderLink?: RenderProp\n  disabled: boolean\n  locale: Intl.LocalesArgument\n}\n\nconst PaginationContext = createContext<PaginationContextValue | null>(null)\n\nfunction usePagination() {\n  const context = use(PaginationContext)\n  if (!context) throw new Error('Pagination parts must be inside <Pagination>.')\n  return context\n}\n\n/** True inside the pill's copy of the row, where a part is only its label. */\nconst PaginationCopyContext = createContext(false)\n\n/** True inside the row, where a part is one of its places. */\nconst RowContext = createContext(false)\n\nfunction Pagination({\n  ref,\n  className,\n  page: pageProp,\n  defaultPage = 1,\n  onPageChange,\n  pageCount,\n  total,\n  pageSize: pageSizeProp,\n  defaultPageSize = 10,\n  onPageSizeChange,\n  hasNextPage = false,\n  siblings = 1,\n  boundaries = 1,\n  getHref,\n  renderLink,\n  controller: controllerProp,\n  disabled = false,\n  locale = 'en-US',\n  style,\n  'aria-label': ariaLabel = 'Pagination',\n  ...props\n}: Omit<\n  ComponentProps<typeof PaginationPrimitive>,\n  'className' | 'style' | 'children' | 'controller'\n> & {\n  className?: string\n  style?: CSSProperties\n  children?: ReactNode\n  /** How many items a page holds, when it holds its own state. */\n  defaultPageSize?: number\n  /** Called with the new size. The page moves, through `onPageChange`, to the one that keeps the first item it showed. */\n  onPageSizeChange?: (pageSize: number) => void\n  /** Whether there is a page after this one, while the count is unknown, as with a cursor. */\n  hasNextPage?: boolean\n  /** Renders every page and step, such as your router's `<Link />`, with `getHref`. */\n  renderLink?: RenderProp\n  /** Pages it from anywhere. Create one with `createPaginationController()`. */\n  controller?: PaginationController\n  /** The locale numbers are written in. */\n  locale?: Intl.LocalesArgument\n}) {\n  const [chosenSize, setPageSize] = useControllable(\n    pageSizeProp,\n    defaultPageSize,\n    onPageSizeChange,\n  )\n  const pageSize = Math.max(1, Math.floor(chosenSize) || 1)\n  const [own, setOwn] = useState(defaultPage)\n  const known = countOf({ pageCount, total, pageSize })\n  const page = clampPage(pageProp ?? own, known ?? Number.POSITIVE_INFINITY)\n  // While the count is unknown, the pages known so far: up to this one, and the next when there is one.\n  const count = known ?? page + (hasNextPage ? 1 : 0)\n  const [fit, setFit] = useState<Fit>({ words: true, siblings, boundaries, edges: true })\n  const [ownController] = useState(createPaginationController)\n  const controller = controllerProp ?? ownController\n\n  const refocusRef = useRef<number | null>(null)\n  const navRef = useMemo(() => mergeRefs(markMounted, ref), [ref])\n\n  return (\n    <PaginationContext\n      value={{\n        page,\n        pageCount: count,\n        known: known !== null,\n        total: total === undefined ? null : Math.max(0, Math.floor(total)),\n        pageSize,\n        controller,\n        setPageSize: (size) => {\n          const next = Math.max(1, Math.floor(size))\n          if (next === pageSize) return\n          // The new size first, so the page it moves to is counted in it.\n          flushSync(() => setPageSize(next))\n          controller.setPage(pageForSize(page, pageSize, next))\n        },\n        refocusRef,\n        siblings,\n        boundaries,\n        fit,\n        setFit,\n        linked: getHref !== undefined,\n        renderLink,\n        disabled,\n        locale,\n      }}\n    >\n      <PaginationPrimitive\n        ref={navRef}\n        aria-label={ariaLabel}\n        page={page}\n        pageCount={count}\n        siblings={fit.siblings}\n        boundaries={fit.boundaries}\n        getHref={getHref}\n        controller={controller}\n        disabled={disabled}\n        onPageChange={(next, details) => {\n          // While the count is unknown, Last has nowhere to go.\n          if (details.reason === 'last-press' && known === null) {\n            details.cancel()\n            return\n          }\n          onPageChange?.(next, details)\n          if (details.canceled) return\n          if (details.reason === 'item-press') refocusRef.current = next\n          setOwn(next)\n        }}\n        style={{ '--pagination-digits': String(count).length, ...style } as CSSProperties}\n        className={cn(\n          // Its parts in a row, and the pages on a row of their own when there's too little room.\n          'flex w-full min-w-0 flex-wrap items-center justify-center gap-x-4 gap-y-2',\n          className,\n        )}\n        {...props}\n      />\n    </PaginationContext>\n  )\n}\n\n/**\n * The row of pages, Previous and Next, in ui-sdk's list. It looks and moves\n * like the Tabs, and fits the room it is given: first the words beside\n * Previous and Next go, then pages.\n */\nfunction PaginationList({\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof PaginationListPrimitive>, 'className' | 'children'> & {\n  children?: ReactNode\n  /** For where the list sits among its neighbours: the box it measures its room in. */\n  className?: string\n}) {\n  const { page, pageCount, siblings, boundaries, fit, setFit, refocusRef } =\n    usePagination()\n  const areaRef = useRef<HTMLDivElement>(null)\n  const rowRef = useRef<HTMLUListElement>(null)\n  const pillRef = useRef<HTMLLIElement>(null)\n  const backdropRef = useRef<HTMLLIElement>(null)\n  const fitRef = useRef(fit)\n  useLayoutEffect(() => {\n    fitRef.current = fit\n  })\n\n  // As many places as the room holds, measured where the row is laid out.\n  useLayoutEffect(() => {\n    const area = areaRef.current\n    const row = rowRef.current\n    if (!area || !row) return\n    const measure = () => {\n      const next = fittingRange({\n        ...placesIn(area, row),\n        pageCount,\n        siblings,\n        boundaries,\n      })\n      const was = fitRef.current\n      if (\n        was.words !== next.words ||\n        was.siblings !== next.siblings ||\n        was.boundaries !== next.boundaries ||\n        was.edges !== next.edges\n      ) {\n        setFit(next)\n      }\n    }\n    measure()\n    const resized = new ResizeObserver(measure)\n    resized.observe(area)\n    resized.observe(row)\n    return () => resized.disconnect()\n  }, [pageCount, siblings, boundaries, setFit])\n\n  useEffect(() => {\n    const row = rowRef.current\n    if (!row || !pillRef.current || !backdropRef.current) return\n    const stopPick = followPick(row, pillRef.current, {\n      picked: () => row.querySelector<HTMLElement>(CURRENT),\n      attributes: ['aria-current'],\n    })\n    // Behind the part under the pointer, or the one with visible focus.\n    const stopHover = followPointer(row, backdropRef.current, {\n      itemOf: itemMatching(row, ITEM),\n      focus: true,\n    })\n    return () => {\n      stopPick()\n      stopHover()\n    }\n  }, [])\n\n  // Each place keeps its element as the pages change, so its number rolls: a\n  // pressed page can roll to another place, and focus goes with it.\n  useLayoutEffect(() => {\n    const pressed = refocusRef.current\n    refocusRef.current = null\n    if (pressed !== page) return\n    const row = rowRef.current\n    if (!row?.contains(document.activeElement)) return\n    row.querySelector<HTMLElement>(CURRENT)?.focus()\n  }, [page, refocusRef])\n\n  return (\n    <RowContext value={true}>\n      <div\n        ref={areaRef}\n        className={cn(\n          // Grows into the room its neighbours leave, and wraps below them when that is less than a short row.\n          '@container/pagination flex min-w-0 flex-[1_1_10rem] justify-center',\n          // Until the pages are measured to fit, a row too wide is cut at the edge rather than spilling over.\n          '[[data-slot=pagination]:not([data-mounted])_&]:overflow-x-clip',\n          // The numbers the first measure changes take their place at once: nothing rolls on load.\n          '[[data-slot=pagination]:not([data-mounted])_&]:[&_[data-slot=roll]_*]:transition-none',\n          className,\n        )}\n      >\n        <PaginationListPrimitive\n          {...props}\n          ref={rowRef}\n          data-words={fit.words ? '' : undefined}\n          data-edges={fit.edges ? '' : undefined}\n          className={cn(paginationRow, 'relative isolate')}\n        >\n          {children}\n          <li\n            ref={backdropRef}\n            aria-hidden\n            data-slot='pagination-backdrop'\n            className={cn(highlightClassName, pillBackdropClassName)}\n          />\n          <li\n            ref={pillRef}\n            aria-hidden\n            // Whatever the row holds is copied here, so nothing in the copy may take focus.\n            inert\n            data-slot='pagination-pill'\n            className={cn(pickClassName, pillClassName, 'z-10')}\n          >\n            <span className={cn(paginationRow, 'h-full')}>\n              <PaginationCopyContext value={true}>{children}</PaginationCopyContext>\n            </span>\n          </li>\n        </PaginationListPrimitive>\n      </div>\n    </RowContext>\n  )\n}\n\nconst controlClassName = cn(\n  itemLayout,\n  pillItemClassName,\n  // Until the page hydrates and the pill is placed, the current page draws itself.\n  '[[data-slot=pagination]:not([data-mounted])_&]:aria-[current=page]:bg-primary [[data-slot=pagination]:not([data-mounted])_&]:aria-[current=page]:text-primary-foreground',\n)\n\ntype StepPart = typeof PaginationPreviousPrimitive\n\ntype StepProps = Omit<ComponentProps<StepPart>, 'className' | 'children'> & {\n  className?: string\n  /** The word beside the arrow, also its name when only the arrow shows. */\n  children?: ReactNode\n}\n\n/**\n * A step to another page: an arrow in a page's square, with its word on\n * the side away from the pages when `word` is set and there is room. Without\n * it, the word is only the step's name. At its end it stays focusable as a\n * button, so focus isn't lost when Next reaches the last page.\n */\nfunction PaginationStep({\n  Part,\n  icon,\n  word,\n  edge = false,\n  className,\n  children,\n  ...props\n}: StepProps & {\n  Part: StepPart\n  icon: ReactElement\n  /** Where the word shows: before the arrow, after it, or never. */\n  word?: 'before' | 'after'\n  /** First or Last, which go when there's no room for them. */\n  edge?: boolean\n}) {\n  const { renderLink, linked } = usePagination()\n  const arrow = <span className={stepArrow}>{icon}</span>\n  const label = (\n    <span\n      data-pagination-word={word ? '' : undefined}\n      className={!word ? 'sr-only' : word === 'before' ? nextWord : previousWord}\n    >\n      {children}\n    </span>\n  )\n  const parts =\n    word === 'before' ? (\n      <>\n        {label}\n        {arrow}\n      </>\n    ) : (\n      <>\n        {arrow}\n        {label}\n      </>\n    )\n  const hidden = edge && edgeHidden\n  if (use(PaginationCopyContext)) {\n    return <span className={cn(itemLayout, stepLayout, hidden, className)}>{parts}</span>\n  }\n  return (\n    <PaginationItemPrimitive className={cn('flex', hidden)}>\n      <Part\n        render={linked ? renderLink : undefined}\n        className={cn(controlClassName, stepLayout, className)}\n        {...props}\n      >\n        {parts}\n      </Part>\n    </PaginationItemPrimitive>\n  )\n}\n\n/** Goes to the first page: an arrow only. */\nfunction PaginationFirst({ children = 'First page', ...props }: StepProps) {\n  return (\n    <PaginationStep\n      Part={PaginationFirstPrimitive}\n      edge\n      icon={\n        <IconPlaceholder\n          lucide='ChevronsLeftIcon'\n          tabler='IconChevronsLeft'\n          hugeicons='ArrowLeftDoubleIcon'\n          phosphor='CaretDoubleLeftIcon'\n          remixicon='RiArrowLeftDoubleLine'\n          aria-hidden\n          className='rtl:-scale-x-100'\n        />\n      }\n      {...props}\n    >\n      {children}\n    </PaginationStep>\n  )\n}\n\nfunction PaginationPrevious({ children = 'Previous', ...props }: StepProps) {\n  return (\n    <PaginationStep\n      Part={PaginationPreviousPrimitive}\n      word='after'\n      icon={\n        <IconPlaceholder\n          lucide='ChevronLeftIcon'\n          tabler='IconChevronLeft'\n          hugeicons='ArrowLeft01Icon'\n          phosphor='CaretLeftIcon'\n          remixicon='RiArrowLeftSLine'\n          aria-hidden\n          className='rtl:-scale-x-100'\n        />\n      }\n      {...props}\n    >\n      {children}\n    </PaginationStep>\n  )\n}\n\nfunction PaginationNext({ children = 'Next', ...props }: StepProps) {\n  return (\n    <PaginationStep\n      Part={PaginationNextPrimitive}\n      word='before'\n      icon={\n        <IconPlaceholder\n          lucide='ChevronRightIcon'\n          tabler='IconChevronRight'\n          hugeicons='ArrowRight01Icon'\n          phosphor='CaretRightIcon'\n          remixicon='RiArrowRightSLine'\n          aria-hidden\n          className='rtl:-scale-x-100'\n        />\n      }\n      {...props}\n    >\n      {children}\n    </PaginationStep>\n  )\n}\n\n/** A link at its end, as ui-sdk renders one: no address, out of the tab order. */\nfunction atEnd(renderLink: RenderProp | undefined): RenderProp {\n  return (props, state) => {\n    const { children, ...rest } = props\n    const ended = { ...rest, href: undefined, tabIndex: -1, role: 'link' }\n    if (typeof renderLink === 'function') return renderLink({ ...ended, children }, state)\n    if (renderLink) return cloneElement(renderLink, ended, children)\n    return <a {...ended}>{children}</a>\n  }\n}\n\n/** Goes to the last page: an arrow only. While the count is unknown it has nowhere to go. */\nfunction PaginationLast({ children = 'Last page', ...props }: StepProps) {\n  const { known, linked, renderLink } = usePagination()\n  return (\n    <PaginationStep\n      Part={PaginationLastPrimitive}\n      edge\n      icon={\n        <IconPlaceholder\n          lucide='ChevronsRightIcon'\n          tabler='IconChevronsRight'\n          hugeicons='ArrowRightDoubleIcon'\n          phosphor='CaretDoubleRightIcon'\n          remixicon='RiArrowRightDoubleLine'\n          aria-hidden\n          className='rtl:-scale-x-100'\n        />\n      }\n      // ui-sdk counts the pages known so far as all there are: while the count\n      // is unknown, this marks it at its end as ui-sdk marks a step there, and\n      // the Pagination keeps the page when it is pressed.\n      {...(known ? {} : { 'aria-disabled': true, 'data-disabled': '' })}\n      {...(!known && linked && { render: atEnd(renderLink) })}\n      {...props}\n    >\n      {children}\n    </PaginationStep>\n  )\n}\n\n/**\n * A page in the row. One leaving as its place turns into an ellipsis is a\n * still copy, so ui-sdk counts only the pages that show.\n */\nfunction PaginationPage({\n  page,\n  label,\n  className,\n}: {\n  page: number\n  label: string\n  className?: string\n}) {\n  const { linked, renderLink } = usePagination()\n  const number = <RollingNumber value={page} text={String(page)} />\n  if (useSwapLeaving()) {\n    return <span className={cn(controlClassName, className)}>{number}</span>\n  }\n  return (\n    <PaginationLinkPrimitive\n      page={page}\n      render={linked ? renderLink : undefined}\n      className={cn(controlClassName, className)}\n    >\n      {/* The number rolls for the eye; its name is read whole. */}\n      <span className='sr-only'>{label}</span>\n      {number}\n    </PaginationLinkPrimitive>\n  )\n}\n\n/**\n * The numbered pages from ui-sdk's range, with an ellipsis for each run it\n * skips. Each place stays the same element as the pages change, so its\n * number rolls.\n */\nfunction PaginationPages({\n  className,\n  pageLabel = (page, of) => (of ? `Page ${page} of ${of}` : `Page ${page}`),\n}: {\n  className?: string\n  /**\n   * Each page's accessible name. `of` is the page count, given for the\n   * current page only, so its name says how many there are even when the\n   * last page doesn't show.\n   */\n  pageLabel?: (page: number, of?: number) => string\n}) {\n  const { page, pageCount, known, fit } = usePagination()\n  const copy = use(PaginationCopyContext)\n  const items = pagesOf({\n    page,\n    pageCount,\n    siblings: fit.siblings,\n    boundaries: fit.boundaries,\n  })\n  return items.map((item, place) => {\n    const number = typeof item === 'number'\n    let content: ReactNode\n    if (!number) {\n      const ellipsis = cn(itemLayout, 'text-foreground/60', className)\n      const icon = (\n        <IconPlaceholder\n          lucide='EllipsisIcon'\n          tabler='IconDots'\n          hugeicons='MoreHorizontalIcon'\n          phosphor='DotsThreeIcon'\n          remixicon='RiMoreLine'\n          aria-hidden\n        />\n      )\n      content = copy ? (\n        <span className={ellipsis}>{icon}</span>\n      ) : (\n        <PaginationEllipsisPrimitive className={ellipsis}>\n          {icon}\n        </PaginationEllipsisPrimitive>\n      )\n    } else if (copy) {\n      content = (\n        <span className={cn(itemLayout, className)}>\n          <RollingNumber value={item} text={String(item)} />\n        </span>\n      )\n    } else {\n      content = (\n        <PaginationPage\n          page={item}\n          label={pageLabel(item, item === page && known ? pageCount : undefined)}\n          className={className}\n        />\n      )\n    }\n    // Keyed by place, not by page, so a place's number rolls as the range\n    // moves, and one that turns from a page into an ellipsis, or back, crossfades.\n    const swap = <Swap id={number ? 'page' : 'ellipsis'}>{content}</Swap>\n    const placeClassName = cn('flex', item !== page && beforeFit)\n    return copy ? (\n      <span key={place} className={placeClassName}>\n        {swap}\n      </span>\n    ) : (\n      <PaginationItemPrimitive\n        key={place}\n        className={placeClassName}\n        aria-hidden={number ? undefined : true}\n      >\n        {swap}\n      </PaginationItemPrimitive>\n    )\n  })\n}\n\n// The page count after the page field: in a row narrower than a phone's, only the field's description.\nconst pageCountClassName =\n  'text-muted-foreground tabular-nums @max-3xs/pagination:sr-only'\n\n// The page field's box: as wide as the last page's number, at the input's own text size, so `1ch` is its digit.\nconst pageBox =\n  'w-[calc(max(var(--pagination-digits,1),2)*1ch+2*var(--control-padding)+2px)] shrink-0 text-base md:text-sm'\n\n/**\n * The current page as a field, \"Page 3 of 12\", in the row: type a page and\n * press Enter or leave the field to go there, or step with the arrow keys.\n * Between Previous and Next it is the whole row, for a small space; beside\n * the pages it jumps far in a long range.\n */\nfunction PaginationPageField({\n  className,\n  label = 'Page',\n  of = (pageCount) => `of ${pageCount}`,\n  disabled,\n  ...props\n}: Omit<HTMLAttributes<HTMLElement>, 'className' | 'children'> & {\n  className?: string\n  /** The word before the field, also its name. */\n  label?: string\n  /** The words after it, given the page count written out. Left out while the count is unknown. */\n  of?: (pageCount: string) => string\n  disabled?: boolean\n}) {\n  const {\n    page,\n    pageCount,\n    known,\n    controller,\n    disabled: allDisabled,\n    locale,\n  } = usePagination()\n  const copy = use(PaginationCopyContext)\n  // In the row it is one of its places; beside it, a part of its own.\n  const Place = use(RowContext) ? 'li' : 'div'\n  const labelId = useId()\n  const ofId = useId()\n  // What the field holds: the page, or what is being typed until it is sent.\n  const [draft, setDraft] = useState<number | null>(page)\n  const [seen, setSeen] = useState(page)\n  if (seen !== page) {\n    setSeen(page)\n    setDraft(page)\n  }\n  const ofText = known ? of(numberFormatter(locale).format(pageCount)) : null\n  // Goes to the page typed, the nearest there is; with nothing typed, the field shows the page again.\n  const send = (value: number | null) => {\n    // While the count is unknown, the pages known so far: as far as Next goes.\n    const to = value === null ? page : clampPage(value, pageCount)\n    setDraft(to)\n    controller.setPage(to)\n  }\n  const layout = cn(\n    'flex shrink-0 items-center gap-2 text-sm whitespace-nowrap',\n    className,\n  )\n\n  if (copy) {\n    // The same width as the field, so every part after it sits on its twin.\n    return (\n      <span className={cn(layout, 'invisible')}>\n        <span>{label}</span>\n        <span className={cn(pageBox, 'h-(--control-height)')} />\n        {ofText ? <span className={pageCountClassName}>{ofText}</span> : null}\n      </span>\n    )\n  }\n  return (\n    <Place data-slot='pagination-page-field' className={layout} {...props}>\n      <span id={labelId}>{label}</span>\n      <NumberInput\n        value={draft}\n        min={1}\n        max={pageCount}\n        step={1}\n        disabled={disabled ?? allDisabled}\n        locale={numberFormatter(locale).resolvedOptions().locale}\n        format={{ maximumFractionDigits: 0, useGrouping: false }}\n        onValueChange={(value, details) => {\n          setDraft(value)\n          // A step goes at once; what is typed or pasted goes when it is sent.\n          if (value !== null && isStep(details.reason)) controller.setPage(value)\n        }}\n        onValueCommit={send}\n      >\n        <NumberInputGroup className={pageBox}>\n          <NumberInputControl\n            aria-labelledby={labelId}\n            aria-describedby={ofText ? ofId : undefined}\n          />\n        </NumberInputGroup>\n      </NumberInput>\n      {ofText ? (\n        <span id={ofId} className={pageCountClassName}>\n          {ofText}\n        </span>\n      ) : null}\n    </Place>\n  )\n}\n\n/**\n * A number that rolls up when it grows and down when it shrinks, each on its\n * own: as the page size changes, the range's start can fall while its end rises.\n */\nfunction RollingNumber({ value, text }: { value: number; text: string }) {\n  const [seen, setSeen] = useState({ value, trend: 1 })\n  if (seen.value !== value) setSeen({ value, trend: value < seen.value ? -1 : 1 })\n  return <Roll value={text} trend={seen.trend} />\n}\n\n/** The numbers a range's words are written around, as text or as rolling numbers. */\ninterface PaginationRangeParts {\n  /** The first item on the page, counted from 1, when the Pagination has `total`. */\n  from: ReactNode | null\n  /** The last item on the page, when the Pagination has `total`. */\n  to: ReactNode | null\n  /** How many items there are, when the Pagination has `total`. */\n  total: ReactNode | null\n  page: ReactNode\n  /** How many pages there are, or `null` while that is unknown. */\n  pageCount: ReactNode | null\n}\n\nfunction rangeWords(range: PaginationRangeParts) {\n  if (range.total === null) {\n    return range.pageCount === null ? (\n      <>Page {range.page}</>\n    ) : (\n      <>\n        Page {range.page} of {range.pageCount}\n      </>\n    )\n  }\n  return (\n    <>\n      {range.from}–{range.to} of {range.total}\n    </>\n  )\n}\n\n/**\n * Where the page sits in the whole: \"21–40 of 4,800\" when the Pagination has\n * `total`, \"Page 3 of 12\" when it has only `pageCount`, and \"Page 3\" while\n * the count is unknown. Its numbers roll as the page moves, and a screen\n * reader hears the new range.\n */\nfunction PaginationRange({\n  className,\n  children = rangeWords,\n  announce = true,\n  shown,\n  ...props\n}: Omit<ComponentProps<'p'>, 'className' | 'children'> & {\n  className?: string\n  /** Whether a screen reader hears the new range: leave it off where something else says the page changed, as a Table's own announcements do. */\n  announce?: boolean\n  /** The page, and its size, whose items are on screen while they aren't yet the page asked for, as while a server sends the next. */\n  shown?: { page: number; pageSize: number }\n  /**\n   * The words, such as in another language, given the numbers to write them\n   * around. Called twice: once with text for screen readers and once with\n   * rolling numbers for the eye.\n   */\n  children?: (range: PaginationRangeParts) => ReactNode\n}) {\n  const asked = usePagination()\n  const { pageCount, known, total, locale } = asked\n  const { page, pageSize } = shown ?? asked\n  const format = numberFormatter(locale)\n  const byItem = total !== null\n  const items = pageRange(page, pageSize, total ?? 0)\n  const values = {\n    from: byItem ? items.from : null,\n    to: byItem ? items.to : null,\n    total,\n    page,\n    pageCount: known ? pageCount : null,\n  }\n  const text = (value: number | null) => (value === null ? null : format.format(value))\n  const rolled = (value: number | null) =>\n    value === null ? null : <RollingNumber value={value} text={format.format(value)} />\n  const parts = (write: (value: number | null) => ReactNode) => ({\n    from: write(values.from),\n    to: write(values.to),\n    total: write(values.total),\n    page: write(values.page),\n    pageCount: write(values.pageCount),\n  })\n  return (\n    <p\n      data-slot='pagination-range'\n      className={cn('text-muted-foreground shrink-0 text-sm tabular-nums', className)}\n      {...props}\n    >\n      {/* Read whole and announced as it changes; the rolling copy is for the eye. */}\n      <span role={announce ? 'status' : undefined} className='sr-only'>\n        {children(parts(text))}\n      </span>\n      {/* Each rolling number is a box of its own: the line takes its direction from its words, as plain text would. */}\n      <span aria-hidden className='[unicode-bidi:plaintext]'>\n        {children(parts(rolled))}\n      </span>\n    </p>\n  )\n}\n\n/**\n * How many items a page holds, picked with Kino's Select. A new size keeps\n * the first item the page showed on screen.\n */\nfunction PaginationPageSize({\n  className,\n  options = [10, 20, 50, 100],\n  children = 'Rows per page',\n  disabled,\n  ...props\n}: Omit<ComponentProps<'div'>, 'className' | 'children'> & {\n  className?: string\n  disabled?: boolean\n  /** The sizes to pick from. */\n  options?: readonly number[]\n  /** The label beside the Select, also its name. */\n  children?: ReactNode\n}) {\n  const { pageSize, setPageSize, disabled: allDisabled, locale } = usePagination()\n  const labelId = useId()\n  const format = numberFormatter(locale)\n  // The size it has, even when it isn't one of the options.\n  const sizes = options.includes(pageSize)\n    ? options\n    : [...options, pageSize].toSorted((a, b) => a - b)\n  return (\n    <div\n      data-slot='pagination-page-size'\n      className={cn('flex shrink-0 items-center gap-2 text-sm', className)}\n      {...props}\n    >\n      <span id={labelId} className='text-muted-foreground'>\n        {children}\n      </span>\n      <Select\n        value={pageSize}\n        disabled={disabled ?? allDisabled}\n        onValueChange={(size) => {\n          if (size !== null) setPageSize(size)\n        }}\n        items={sizes.map((size) => ({\n          value: size,\n          label: format.format(size),\n        }))}\n      >\n        <SelectTrigger\n          aria-labelledby={labelId}\n          // As wide as the longest size, so picking another never moves what sits beside it.\n          style={\n            {\n              '--pagination-size-digits': Math.max(\n                ...sizes.map((size) => format.format(size).length),\n              ),\n            } as CSSProperties\n          }\n          className='min-w-[calc(var(--pagination-size-digits)*1ch+2*var(--control-padding)+1.5rem+2px)] tabular-nums'\n        >\n          <SelectValue />\n        </SelectTrigger>\n        <SelectContent>\n          {sizes.map((size) => (\n            <SelectItem key={size} value={size} className='tabular-nums'>\n              {format.format(size)}\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n    </div>\n  )\n}\n\n/** How many pages there are, from `total` items when given, else `pageCount`; `null` with neither. */\nfunction countOf({\n  pageCount,\n  total,\n  pageSize,\n}: {\n  pageCount?: number\n  total?: number\n  pageSize: number\n}): number | null {\n  if (total !== undefined) return pageCountOf(total, pageSize)\n  if (pageCount !== undefined) return Math.max(1, Math.floor(pageCount))\n  return null\n}\n\n/**\n * How many places the row keeps once there are more pages: ui-sdk's range\n * with the ends and their ellipses, or a window of pages with none.\n */\nfunction placesFor(siblings: number, boundaries: number) {\n  return boundaries > 0 ? 2 * boundaries + 2 * siblings + 3 : 2 * siblings + 1\n}\n\n/**\n * The row's places: ui-sdk's range while it keeps ends, and with none, a\n * window of `siblings` pages either side of the current one, held inside the\n * range, since an ellipsis with no end beyond it stands for nothing a person\n * can reach.\n */\nfunction pagesOf({\n  page,\n  pageCount,\n  siblings,\n  boundaries,\n}: {\n  page: number\n  pageCount: number\n  siblings: number\n  boundaries: number\n}): ReturnType<typeof paginationRange> {\n  if (boundaries > 0) return paginationRange({ page, pageCount, siblings, boundaries })\n  const count = Math.max(1, pageCount)\n  const places = Math.min(count, placesFor(siblings, 0))\n  const start = Math.min(Math.max(1, page - siblings), count - places + 1)\n  return Array.from({ length: places }, (_, at) => start + at)\n}\n\n/**\n * What fits in `room` px, each place `place` px wide and `gap` px apart:\n * the words beside Previous and Next, which take `words` px more, while\n * every page asked for fits with them; then the most `siblings`, then\n * `boundaries`, up to those asked for. At the least it is the current page\n * alone. `room` is what the pages and the words share.\n */\nfunction fittingRange({\n  room,\n  place,\n  gap,\n  words,\n  edges = 0,\n  pageCount,\n  siblings,\n  boundaries,\n}: {\n  room: number\n  /** 0 when the row has no pages, as between Previous, the page field and Next. */\n  place: number\n  gap: number\n  words: number\n  /** How much First and Last take with their gaps, 0 without them. */\n  edges?: number\n  pageCount: number\n  siblings: number\n  boundaries: number\n}) {\n  const wide = (sides: number, ends: number) => {\n    if (place === 0) return 0\n    const places = Math.min(Math.max(1, pageCount), placesFor(sides, ends))\n    return places * place + (places - 1) * gap\n  }\n  // Half a pixel either way is rounding, not a lack of room.\n  const fits = (width: number) => width + edges <= room + 0.5\n  if (fits(wide(siblings, boundaries) + words)) {\n    return { words: true, siblings, boundaries, edges: true }\n  }\n  for (let ends = boundaries; ends >= 0; ends--) {\n    for (let sides = siblings; sides >= 0; sides--) {\n      if (fits(wide(sides, ends)))\n        return { words: false, siblings: sides, boundaries: ends, edges: true }\n    }\n  }\n  // Last, First and Last go: Previous and Next still reach every page.\n  return { words: false, siblings: 0, boundaries: 0, edges: edges === 0 }\n}\n\n/**\n * The room the pages and the words have in `nav`, how wide each page's place\n * is and how far apart, how much more the words beside Previous and Next\n * take, and how much First and Last take, as laid out. Previous and Next are\n * counted as squares, and their words from the text, whether they show or\n * not; First and Last as squares of the row's height, shown or not.\n */\nfunction placesIn(nav: HTMLElement, row: HTMLElement) {\n  const gap = Number.parseFloat(getComputedStyle(row).columnGap) || 0\n  const quarter =\n    Number.parseFloat(getComputedStyle(document.documentElement).fontSize) / 4\n  let others = 0\n  let place = 0\n  let words = 0\n  let edges = 0\n  for (const child of row.children) {\n    // The backdrop and the pill lie over the row and take no room in it.\n    if (!(child instanceof HTMLElement) || child.matches(LAYERS)) continue\n    const control = child.firstElementChild\n    if (control?.matches('[data-slot=pagination-first], [data-slot=pagination-last]')) {\n      edges += row.getBoundingClientRect().height + gap\n      continue\n    }\n    if (\n      child.querySelector('[data-slot=pagination-link], [data-slot=pagination-ellipsis]')\n    ) {\n      place = Math.max(place, child.getBoundingClientRect().width)\n      continue\n    }\n    const word = control?.querySelector('[data-pagination-word]')\n    const arrow = control?.querySelector('svg')\n    if (control instanceof HTMLElement && word && arrow) {\n      // A square, and the word with its padding beside it.\n      const square = control.getBoundingClientRect().height\n      const range = document.createRange()\n      range.selectNodeContents(word)\n      words +=\n        range.getBoundingClientRect().width +\n        (square - arrow.getBoundingClientRect().width) / 2 -\n        quarter\n      others += square + gap\n    } else {\n      others += child.getBoundingClientRect().width + gap\n    }\n  }\n  return { room: nav.clientWidth - others, place, gap, words, edges }\n}\n\nexport {\n  Pagination,\n  PaginationFirst,\n  PaginationLast,\n  PaginationList,\n  PaginationNext,\n  PaginationPageField,\n  PaginationPages,\n  PaginationPageSize,\n  PaginationPrevious,\n  PaginationRange,\n  countOf,\n  fittingRange,\n  pagesOf,\n}\nexport type { PaginationRangeParts }\n",
      "type": "registry:component",
      "target": "@components/kino/pagination.tsx"
    }
  ],
  "type": "registry:component"
}