{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "virtual-list",
  "type": "registry:ui",
  "title": "Virtual List",
  "description": "A long list or grid that renders only the rows in view: thousands of items of any height in a box that scrolls, or down a page that scrolls with the window, each still announced with its position in the whole list, with a way to go to an item and to come back to where the person was.",
  "categories": [
    "ui"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/ui/virtual-list.tsx",
      "type": "registry:ui",
      "target": "components/ui/virtual-list.tsx",
      "content": "\"use client\";\n/**\n * @name virtual-list\n * @category ui\n * @description A long list or grid that renders only the rows in view: thousands of items of any height in a box that scrolls, or down a page that scrolls with the window, each still announced with its position in the whole list, with a way to go to an item and to come back to where the person was.\n * @when More items than the page should hold at once (a few hundred or more): a feed, a log, search results, a picture library. Rows may have any height: each is measured once it is drawn and the rest are estimated, and the view does not jump when a row above it turns out taller. Give the box a height and a name (`aria-label`); or, where the list is the page (a feed, results under a header), `scroll=\"window\"` and no height: it then grows to its full length and the window scrolls it. For a short list render the rows plainly; for a conversation that grows at the bottom use thread; for pages of results use pagination. Written here on ResizeObserver instead of adding a virtualisation package: a headless one would bring the offsets but not the roles, the positions for screen readers, the kept focus or the restoration, which are most of this file.\n * @example\n * // Rows of any height\n * <VirtualList count={messages.length} estimateSize={72} getKey={(index) => messages[index].id} aria-label=\"Messages\" className=\"h-96 rounded-surface border\">\n *   {(index) => <article className=\"border-b p-3\">{messages[index].text}</article>}\n * </VirtualList>\n *\n * // A grid, as many columns as fit; the place is remembered for this tab\n * <VirtualGrid count={pictures.length} columns={{ minWidth: 160 }} gap={8} estimateSize={160} restoreKey=\"library\" aria-label=\"Pictures\" className=\"h-[32rem]\">\n *   {(index) => <img src={pictures[index].src} alt={pictures[index].alt} className=\"aspect-square w-full rounded-control object-cover\" />}\n * </VirtualGrid>\n *\n * // The page scrolls, not a box: no height, and rows above and below the window are not rendered\n * <VirtualList scroll=\"window\" count={results.length} estimateSize={96} getKey={(index) => results[index].id} aria-label=\"Results\">\n *   {(index) => <ResultCard result={results[index]} />}\n * </VirtualList>\n *\n * // Going to an item\n * const list = useRef<VirtualListHandle>(null);\n * <VirtualList handleRef={list} count={10000} aria-label=\"Lines\">{(index) => <p className=\"p-2\">Line {index + 1}</p>}</VirtualList>\n * <Button onClick={() => list.current?.scrollToIndex(4999, { align: \"center\" })}>Go to line 5,000</Button>\n */\nimport { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type FocusEvent, type KeyboardEvent, type ReactNode, type Ref, type UIEvent } from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { cn } from \"@/lib/cn\";\n\n/** Where an item is put in the box when it is gone to. \"nearest\" moves only if it is not wholly in view. */\nexport type VirtualAlign = \"start\" | \"center\" | \"end\" | \"nearest\";\n\nexport type VirtualListHandle = {\n  /** Brings an item into view, without animation. It stays put while the rows around it are measured. */\n  scrollToIndex: (index: number, options?: { align?: VirtualAlign }) => void;\n  /** The list's own element: the box that scrolls, or, with `scroll=\"window\"`, the block the window scrolls past. */\n  element: HTMLDivElement | null;\n};\n\n/** The items in view (not counting the extra rows kept above and below), as indexes. */\nexport type VirtualRange = { start: number; end: number };\n\ntype Shared = Omit<ComponentProps<\"div\">, \"children\" | \"ref\"> & {\n  /** How many items there are in all. It may change: rows keep their measured heights by key. */\n  count: number;\n  /**\n   * What scrolls. \"box\" (default): the list's own box, which needs a height. \"window\": the page; the list\n   * takes its full length in the page, renders the rows the window shows, and is not a Tab stop (the page\n   * already scrolls by keyboard). `scrollToIndex` then scrolls the window, leaving room for a sticky header\n   * when the list has a `scroll-margin-top` (`className=\"scroll-mt-16\"`), and `onScroll` is not called.\n   */\n  scroll?: \"box\" | \"window\";\n  /** Extra rows kept drawn above and below the view, so a fast scroll does not show a blank. Default 4. */\n  overscan?: number;\n  /** The space between rows (and between columns of a grid), in pixels. Default 0. */\n  gap?: number;\n  /** A stable key for an item: its id. Left out, it is the index, which is right only for a list that does not reorder. */\n  getKey?: (index: number) => string | number;\n  /** A name for this list's place. With it, where the person was is kept for the tab (sessionStorage) and returned to when the list is shown again. */\n  restoreKey?: string;\n  /** Receives `scrollToIndex` and the scrolling element. */\n  handleRef?: Ref<VirtualListHandle>;\n  /** Called when the items in view change: load more near the end, or mark what was seen. */\n  onRangeChange?: (range: VirtualRange) => void;\n  /** Draws one item. It is called only for the items being rendered. */\n  children: (index: number) => ReactNode;\n};\n\nexport type VirtualListProps = Shared & {\n  /** The height a row is taken to have until it has been measured, in pixels: one number, or a function of the index. A close guess keeps the scrollbar steady. Default 48. */\n  estimateSize?: number | ((index: number) => number);\n};\n\nexport type VirtualGridProps = Shared & {\n  /** How many columns, or the narrowest a column may be in pixels: as many as fit are used. Default `{ minWidth: 160 }`. */\n  columns?: number | { minWidth: number };\n  /** The height a row of cells is taken to have until it has been measured, in pixels. Default 160. */\n  estimateSize?: number;\n};\n\ntype Target = { row: number; align: \"start\" | \"center\" | \"end\"; offset: number };\ntype Latest = { offsets: Float64Array; rowCount: number; perRow: number; height: number; gap: number; first: number; last: number; sizes: ReadonlyMap<string | number, number>; keyOf: (row: number) => string | number };\n\nconst STORE = \"rui-virtual:\";\nconst EMPTY_SIZES: ReadonlyMap<string | number, number> = new Map();\n\n/** The row a distance from the top falls in: the last one that starts at or before it. */\nfunction rowAt(offsets: Float64Array, rowCount: number, y: number): number {\n  let low = 0;\n  let high = rowCount - 1;\n  while (low < high) {\n    const middle = (low + high + 1) >> 1;\n    if ((offsets[middle] ?? 0) <= y) low = middle;\n    else high = middle - 1;\n  }\n  return Math.max(0, low);\n}\n\n/** How far down the box its content starts: the box's own padding, which scrolls with the rows. */\nconst insetOf = (box: HTMLElement): number => (box.firstElementChild as HTMLElement | null)?.offsetTop ?? 0;\n\n/**\n * Where the view is, as the distance scrolled past the top of the box. In its own box that is `scrollTop`;\n * with the window it is how far the box's top edge is above the window's, and negative while the list has\n * not yet reached the top of the window.\n */\nfunction topOf(box: HTMLElement, windowed: boolean): number {\n  if (!windowed) return box.scrollTop;\n  const sizer = box.firstElementChild;\n  return insetOf(box) - (sizer ? sizer.getBoundingClientRect().top : box.getBoundingClientRect().top);\n}\n\n/** The height of the view: the box's, or the window's. */\nconst viewOf = (box: HTMLElement, windowed: boolean): number => (windowed ? document.documentElement.clientHeight : box.clientHeight);\n\n/** Moves the view. Outside any component: the box and the window are the browser's, scrolled in place. */\nfunction moveTo(box: HTMLElement, windowed: boolean, top: number): void {\n  if (!windowed) box.scrollTop = top;\n  else window.scrollBy({ top: top - topOf(box, true), behavior: \"instant\" });\n}\n\n/** How far the view can go either way, and where it is when the end of the list is at the end of the view. */\nfunction reachOf(box: HTMLElement, windowed: boolean): { least: number; most: number; end: number } {\n  if (!windowed) {\n    const most = box.scrollHeight - box.clientHeight;\n    return { least: 0, most, end: most };\n  }\n  const now = topOf(box, true);\n  const view = viewOf(box, true);\n  const least = now - window.scrollY;\n  const most = now + Math.max(0, document.documentElement.scrollHeight - view - window.scrollY);\n  return { least, most, end: box.offsetHeight - view };\n}\n\n/** The room a sticky header takes at the top of the window: the list's own `scroll-margin-top`. */\nconst headroomOf = (box: HTMLElement, windowed: boolean): number => (windowed ? Number.parseFloat(getComputedStyle(box).scrollMarginTop) || 0 : 0);\n\nfunction readPlace(key: string): { index: number; offset: number } | null {\n  try {\n    const saved = JSON.parse(window.sessionStorage.getItem(STORE + key) ?? \"null\") as { index?: unknown; offset?: unknown } | null;\n    return saved && typeof saved.index === \"number\" && typeof saved.offset === \"number\" ? { index: saved.index, offset: saved.offset } : null;\n  } catch {\n    return null;\n  }\n}\n\nfunction writePlace(key: string, place: { index: number; offset: number }): void {\n  try {\n    window.sessionStorage.setItem(STORE + key, JSON.stringify(place));\n  } catch {\n    // Storage is full or switched off: the list simply starts at the top next time.\n  }\n}\n\ntype Windowing = {\n  /** The rows to render, in order. */\n  rows: number[];\n  offsets: Float64Array;\n  total: number;\n  onScroll: (event: UIEvent<HTMLDivElement>) => void;\n  onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;\n  onFocus: (event: FocusEvent<HTMLDivElement>) => void;\n  onBlur: (event: FocusEvent<HTMLDivElement>) => void;\n};\n\n/**\n * The windowing both components share. A \"row\" is one item of a list or one line of cells of a grid. Row\n * heights are kept by key; the offset of every row is a running sum of measured heights and estimates.\n */\nfunction useWindowing(options: {\n  box: HTMLDivElement | null;\n  /** The window scrolls the list, not its own box. */\n  windowed: boolean;\n  height: number;\n  ready: boolean;\n  count: number;\n  rowCount: number;\n  perRow: number;\n  grid: boolean;\n  estimateSize: number | ((index: number) => number);\n  getKey: ((index: number) => string | number) | undefined;\n  gap: number;\n  overscan: number;\n  restoreKey: string | undefined;\n  handleRef: Ref<VirtualListHandle> | undefined;\n  onRangeChange: ((range: VirtualRange) => void) | undefined;\n  onScroll: ((event: UIEvent<HTMLDivElement>) => void) | undefined;\n  onKeyDown: ((event: KeyboardEvent<HTMLDivElement>) => void) | undefined;\n}): Windowing {\n  const { box, windowed, height, ready, count, rowCount, perRow, grid, estimateSize, getKey, gap, overscan, restoreKey, handleRef, onRangeChange, onScroll, onKeyDown } = options;\n  const [sizes, setSizes] = useState<ReadonlyMap<string | number, number>>(EMPTY_SIZES);\n  const [scrollTop, setScrollTop] = useState(0);\n  const [focusedRow, setFocusedRow] = useState<number | null>(null);\n\n  const { offsets, keyOf } = useMemo(() => {\n    // A grid's rows change when its column count does, so their heights are kept per column count.\n    const keyOf = (row: number): string | number => (grid ? `${perRow}:${row}` : getKey ? getKey(row) : row);\n    const offsets = new Float64Array(rowCount + 1);\n    for (let row = 0; row < rowCount; row += 1) {\n      const size = sizes.get(keyOf(row)) ?? (typeof estimateSize === \"function\" ? estimateSize(row) : estimateSize);\n      offsets[row + 1] = (offsets[row] ?? 0) + size + (row < rowCount - 1 ? gap : 0);\n    }\n    return { offsets, keyOf };\n  }, [rowCount, perRow, grid, getKey, estimateSize, gap, sizes]);\n  const total = offsets[rowCount] ?? 0;\n\n  const first = rowCount === 0 ? 0 : rowAt(offsets, rowCount, scrollTop);\n  const last = rowCount === 0 ? -1 : rowAt(offsets, rowCount, scrollTop + height);\n  const rows: number[] = [];\n  for (let row = Math.max(0, first - overscan); row <= Math.min(rowCount - 1, last + overscan); row += 1) rows.push(row);\n  // The row that holds focus stays rendered wherever the view goes: focus is never dropped by scrolling.\n  if (focusedRow !== null && focusedRow < rowCount && !rows.includes(focusedRow)) {\n    rows.push(focusedRow);\n    rows.sort((a, b) => a - b);\n  }\n\n  /** The box, for the handlers that scroll it: they run between renders, and a value from state may not be changed. */\n  const element = useRef<HTMLDivElement | null>(null);\n  useLayoutEffect(() => {\n    element.current = box;\n  }, [box]);\n\n  /** What the observers and handlers read between renders. */\n  const latest = useRef<Latest>({ offsets, rowCount, perRow, height, gap, first, last, sizes, keyOf });\n  useLayoutEffect(() => {\n    latest.current = { offsets, rowCount, perRow, height, gap, first, last, sizes, keyOf };\n  });\n\n  /** An item being gone to: held in place until the rows around it have been measured, or the person scrolls. */\n  const target = useRef<Target | null>(null);\n  const settle = useRef(0);\n  const lastTop = useRef(0);\n  const saving = useRef(0);\n  /** With the window: Home or End was pressed, and the page is on its way to that end of itself. */\n  const bound = useRef<\"top\" | \"bottom\" | null>(null);\n\n  const applyTarget = useCallback((): void => {\n    const goal = target.current;\n    const now = latest.current;\n    const box = element.current;\n    if (!goal || !box || now.rowCount === 0) return;\n    const row = Math.min(goal.row, now.rowCount - 1);\n    const start = now.offsets[row] ?? 0;\n    const size = (now.offsets[row + 1] ?? start) - start - (row < now.rowCount - 1 ? now.gap : 0);\n    const inset = insetOf(box);\n    const view = viewOf(box, windowed);\n    const reach = reachOf(box, windowed);\n    const headroom = headroomOf(box, windowed);\n    const within = (value: number): number => Math.max(reach.least, Math.min(value, reach.most));\n    const wanted = inset + (goal.align === \"start\" ? start + goal.offset - headroom : goal.align === \"center\" ? start - (view - headroom - size) / 2 - headroom : start + size - view);\n    // The first and last rows go to the very ends, the box's padding included.\n    const top = within(row === 0 && goal.align === \"start\" && goal.offset === 0 ? -headroom : row === now.rowCount - 1 && goal.align === \"end\" ? reach.end : wanted);\n    if (Math.abs(topOf(box, windowed) - top) > 1) moveTo(box, windowed, top);\n    window.clearTimeout(settle.current);\n    settle.current = window.setTimeout(() => {\n      target.current = null;\n    }, 300);\n  }, [windowed]);\n\n  // Heights changed (rows were measured): keep the item being gone to where it was asked to be.\n  useLayoutEffect(() => {\n    applyTarget();\n  }, [applyTarget, offsets, height]);\n\n  const save = useCallback((): void => {\n    const now = latest.current;\n    if (!restoreKey || now.rowCount === 0) return;\n    const row = rowAt(now.offsets, now.rowCount, lastTop.current);\n    writePlace(restoreKey, { index: row * now.perRow, offset: lastTop.current - (now.offsets[row] ?? 0) });\n  }, [restoreKey]);\n\n  // Return to the saved place once the box has a size (and a grid knows its columns).\n  const restored = useRef<string | null>(null);\n  useLayoutEffect(() => {\n    if (!ready || !restoreKey || restored.current === restoreKey) return;\n    restored.current = restoreKey;\n    const place = readPlace(restoreKey);\n    if (!place || place.index < 0) return;\n    target.current = { row: Math.floor(place.index / latest.current.perRow), align: \"start\", offset: Math.max(0, place.offset) };\n    applyTarget();\n  }, [ready, restoreKey, applyTarget]);\n\n  useEffect(() => {\n    if (!restoreKey) return;\n    window.addEventListener(\"pagehide\", save);\n    return () => {\n      window.removeEventListener(\"pagehide\", save);\n      // Leaving the page inside the application: keep the last place seen.\n      if (saving.current !== 0) {\n        window.clearTimeout(saving.current);\n        saving.current = 0;\n        save();\n      }\n    };\n  }, [restoreKey, save]);\n\n  // A scroll the person makes ends any going-to in progress.\n  useEffect(() => {\n    if (!box) return;\n    const release = (event: Event): void => {\n      target.current = null;\n      // Home and End are the page's own keys. While the page is on its way, the list must not hold it back.\n      const key = windowed && event instanceof KeyboardEvent && !event.defaultPrevented && !(event.target instanceof Element && event.target.closest(\"input, textarea, select, [contenteditable]\")) ? event.key : \"\";\n      bound.current = key === \"Home\" ? \"top\" : key === \"End\" ? \"bottom\" : null;\n    };\n    const events = [\"wheel\", \"touchmove\", \"keydown\", \"pointerdown\"] as const;\n    // With the window scrolling, the scroll may be made anywhere on the page.\n    const source: HTMLElement | Window = windowed ? window : box;\n    for (const name of events) source.addEventListener(name, release, { passive: true });\n    return () => {\n      for (const name of events) source.removeEventListener(name, release);\n      window.clearTimeout(settle.current);\n    };\n  }, [box, windowed]);\n\n  /** Rows report their heights here. A row above the view that changes height moves the view by as much, so what the person is reading stays still. */\n  const measure = useCallback(\n    (entries: ResizeObserverEntry[]): void => {\n      const box = element.current;\n      if (!box) return;\n      const now = latest.current;\n      const top = topOf(box, windowed);\n      const inset = insetOf(box);\n      const anchor = rowAt(now.offsets, now.rowCount, top - inset);\n      // At the very end, stay there: rows measured taller than their estimate must not push the end out of reach.\n      // With the window the end is the page's: it is there, or End was pressed and it is on its way.\n      const page = document.documentElement;\n      const pinned = windowed ? bound.current === \"bottom\" || (window.scrollY > 0 && window.scrollY + page.clientHeight >= page.scrollHeight - 1) : top > 0 && top + box.clientHeight >= box.scrollHeight - 1;\n      let next: Map<string | number, number> | null = null;\n      let shift = 0;\n      for (const entry of entries) {\n        const node = entry.target as HTMLElement;\n        const row = Number(node.dataset[\"row\"]);\n        if (!node.isConnected || !Number.isInteger(row) || row >= now.rowCount) continue;\n        const size = entry.borderBoxSize?.[0]?.blockSize ?? node.getBoundingClientRect().height;\n        // Nothing has a height while the list is hidden (a closed tab, a collapsed panel): keep what is known.\n        if (size <= 0) continue;\n        const before = (now.offsets[row + 1] ?? 0) - (now.offsets[row] ?? 0) - (row < now.rowCount - 1 ? now.gap : 0);\n        if (Math.abs(before - size) < 0.5) continue;\n        next ??= new Map(now.sizes);\n        next.set(now.keyOf(row), size);\n        if (row < anchor) shift += size - before;\n      }\n      if (!next) return;\n      const measured = next;\n      // Both in the same frame, before it is painted: the rows move and the view moves with them.\n      flushSync(() => {\n        setSizes(measured);\n        setScrollTop(top - inset + (target.current ? 0 : shift));\n      });\n      if (target.current) return;\n      if (pinned) {\n        if (windowed) window.scrollTo({ top: page.scrollHeight, behavior: \"instant\" });\n        else box.scrollTop = box.scrollHeight - box.clientHeight;\n      }\n      // On its way to the top of the page: there is nothing to hold still, and a scroll made here would stop it short.\n      else if (windowed && bound.current === \"top\") return;\n      // With the window, the browser may have moved the page itself to keep something below the list still:\n      // the rows the person is reading are what must not move, so the place is set again from where it is.\n      else if (windowed ? Math.abs(topOf(box, true) - (top + shift)) > 0.5 : shift !== 0) moveTo(box, windowed, top + shift);\n    },\n    [windowed],\n  );\n\n  const observer = useRef<ResizeObserver | null>(null);\n  const observed = useRef(new Set<Element>());\n  useLayoutEffect(() => {\n    if (!box || typeof ResizeObserver === \"undefined\") return;\n    const seen = observed.current;\n    observer.current = new ResizeObserver(measure);\n    return () => {\n      observer.current?.disconnect();\n      observer.current = null;\n      seen.clear();\n    };\n  }, [box, measure]);\n  // After every render: watch the rows that arrived, let go of the ones that left.\n  useLayoutEffect(() => {\n    const watcher = observer.current;\n    const sizer = box?.firstElementChild;\n    if (!watcher || !sizer) return;\n    const seen = observed.current;\n    for (const node of seen) {\n      if (node.isConnected) continue;\n      watcher.unobserve(node);\n      seen.delete(node);\n    }\n    for (const node of sizer.children) {\n      if (seen.has(node)) continue;\n      watcher.observe(node);\n      seen.add(node);\n    }\n  });\n\n  const scrollToIndex = useCallback(\n    (index: number, scroll?: { align?: VirtualAlign }): void => {\n      const now = latest.current;\n      const box = element.current;\n      if (!box || now.rowCount === 0) return;\n      const row = Math.min(now.rowCount - 1, Math.max(0, Math.floor(index / now.perRow)));\n      let align = scroll?.align ?? \"start\";\n      if (align === \"nearest\") {\n        const start = now.offsets[row] ?? 0;\n        const end = (now.offsets[row + 1] ?? start) - (row < now.rowCount - 1 ? now.gap : 0);\n        const top = topOf(box, windowed) - insetOf(box);\n        if (start >= top + headroomOf(box, windowed) && end <= top + viewOf(box, windowed)) return;\n        align = start < top + headroomOf(box, windowed) ? \"start\" : \"end\";\n      }\n      target.current = { row, align, offset: 0 };\n      applyTarget();\n    },\n    [applyTarget, windowed],\n  );\n  useImperativeHandle(handleRef, () => ({ scrollToIndex, element: box }), [scrollToIndex, box]);\n\n  const start = first * perRow;\n  const end = Math.min(count - 1, (last + 1) * perRow - 1);\n  const report = useRef(onRangeChange);\n  useEffect(() => {\n    report.current = onRangeChange;\n  });\n  useEffect(() => {\n    if (ready && end >= start) report.current?.({ start, end });\n  }, [ready, start, end]);\n\n  /** The view moved: remember the place, and render other rows if other rows are now in view. */\n  const scrolled = useCallback(\n    (flush: boolean): void => {\n      const box = element.current;\n      if (!box) return;\n      const top = topOf(box, windowed) - insetOf(box);\n      lastTop.current = top;\n      if (restoreKey) {\n        window.clearTimeout(saving.current);\n        saving.current = window.setTimeout(() => {\n          saving.current = 0;\n          save();\n        }, 120);\n      }\n      // Render only when other rows come into view, and then before the frame is painted.\n      const now = latest.current;\n      if (now.rowCount === 0) return;\n      if (rowAt(now.offsets, now.rowCount, top) === now.first && rowAt(now.offsets, now.rowCount, top + viewOf(box, windowed)) === now.last) return;\n      if (flush) flushSync(() => setScrollTop(top));\n      else setScrollTop(top);\n    },\n    [windowed, restoreKey, save],\n  );\n\n  // With the window: its scroll is the list's, and so is wherever the page already is when the list arrives.\n  useEffect(() => {\n    if (!windowed || !box || !ready) return;\n    const onWindowScroll = (): void => scrolled(true);\n    const first = window.requestAnimationFrame(() => scrolled(false));\n    window.addEventListener(\"scroll\", onWindowScroll, { passive: true });\n    return () => {\n      window.cancelAnimationFrame(first);\n      window.removeEventListener(\"scroll\", onWindowScroll);\n    };\n  }, [windowed, box, ready, scrolled]);\n\n  return {\n    rows,\n    offsets,\n    total,\n    onScroll: (event) => {\n      onScroll?.(event);\n      if (!windowed) scrolled(true);\n    },\n    onKeyDown: (event) => {\n      onKeyDown?.(event);\n      // With the window, Home and End are the page's: they go to its top and its bottom.\n      if (windowed) return;\n      if (event.defaultPrevented || (event.key !== \"Home\" && event.key !== \"End\") || event.altKey || event.metaKey) return;\n      // In a field inside a row, Home and End belong to the text.\n      if ((event.target as HTMLElement).closest(\"input, textarea, select, [contenteditable]\")) return;\n      // The browser would scroll to where the end is estimated to be; going to the last row lands on the real one.\n      event.preventDefault();\n      scrollToIndex(event.key === \"Home\" ? 0 : count - 1, { align: event.key === \"Home\" ? \"start\" : \"end\" });\n    },\n    onFocus: (event) => {\n      const row = Number((event.target as HTMLElement).closest<HTMLElement>(\"[data-row]\")?.dataset[\"row\"]);\n      if (Number.isInteger(row)) setFocusedRow(row);\n    },\n    onBlur: (event) => {\n      if (!event.currentTarget.contains(event.relatedTarget)) setFocusedRow(null);\n    },\n  };\n}\n\n/** The size of the view (the height of the box that scrolls, or of the window) and of what is inside it (its width), kept current. */\nfunction useBox(windowed: boolean): { box: HTMLDivElement | null; setBox: (node: HTMLDivElement | null) => void; height: number; width: number } {\n  const [box, setBox] = useState<HTMLDivElement | null>(null);\n  const [size, setSize] = useState({ height: 0, width: 0 });\n  useEffect(() => {\n    if (!box || typeof ResizeObserver === \"undefined\") return;\n    const inner = box.firstElementChild;\n    const look = (): void => {\n      const height = viewOf(box, windowed);\n      const width = inner?.clientWidth ?? box.clientWidth;\n      setSize((previous) => (previous.height === height && previous.width === width ? previous : { height, width }));\n    };\n    const observer = new ResizeObserver(look);\n    observer.observe(box);\n    if (inner) observer.observe(inner);\n    if (windowed) window.addEventListener(\"resize\", look);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"resize\", look);\n    };\n  }, [box, windowed]);\n  return { box, setBox, height: size.height, width: size.width };\n}\n\nconst BOX = \"relative min-h-0 overflow-x-hidden overflow-y-auto overscroll-contain [overflow-anchor:none]\";\n/** With the window scrolling: a plain block as long as its rows. The browser does not anchor the page's scroll to rows that are placed by transform. */\nconst PAGE = \"relative [overflow-anchor:none]\";\nconst ROW = \"absolute inset-x-0 top-0\";\n\n/**\n * A list (`role=\"list\"`) whose box scrolls and takes focus, so the arrow keys and Page Up and Down scroll it\n * as they do any region; Home and End go to the first and the last row themselves, not to where the end was\n * estimated to be. Each rendered item is a `listitem` carrying `aria-setsize` (the whole\n * count) and `aria-posinset`, so a screen reader says \"37 of 10,000\" although only a few are in the page.\n * Rows are placed with a transform and are not animated. Give the box a height (`className=\"h-96\"`) and a\n * name (`aria-label`); without a height nothing scrolls and every row is rendered. With `scroll=\"window\"`\n * it needs no height: the page scrolls, and the keys are the page's.\n */\nexport function VirtualList({ className, count, scroll = \"box\", estimateSize = 48, overscan = 4, gap = 0, getKey, restoreKey, handleRef, onRangeChange, onScroll, onKeyDown, children, ...props }: VirtualListProps) {\n  const windowed = scroll === \"window\";\n  const { box, setBox, height } = useBox(windowed);\n  const list = useWindowing({ box, windowed, height, ready: height > 0, count, rowCount: count, perRow: 1, grid: false, estimateSize, getKey, gap, overscan, restoreKey, handleRef, onRangeChange, onScroll, onKeyDown });\n  return (\n    <div ref={setBox} data-slot=\"virtual-list\" data-scroll={scroll} role=\"list\" tabIndex={windowed ? undefined : 0} onScroll={list.onScroll} onKeyDown={list.onKeyDown} className={cn(windowed ? PAGE : BOX, className)} {...props}>\n      <div data-slot=\"virtual-list-sizer\" role=\"presentation\" className=\"relative w-full\" style={{ height: list.total }} onFocus={list.onFocus} onBlur={list.onBlur}>\n        {list.rows.map((row) => (\n          <div\n            key={getKey ? getKey(row) : row}\n            data-slot=\"virtual-list-item\"\n            role=\"listitem\"\n            aria-setsize={count}\n            aria-posinset={row + 1}\n            data-row={row}\n            data-index={row}\n            className={cn(ROW, \"flow-root\")}\n            style={{ transform: `translateY(${list.offsets[row] ?? 0}px)` }}\n          >\n            {children(row)}\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n\n/**\n * The same for cells in columns: lines of cells are windowed, each line as tall as its tallest cell. It is\n * still one list to a screen reader (each cell a `listitem` with its position among all the cells), read in\n * order, and it mirrors in right-to-left pages. With `columns={{ minWidth }}` the number of columns follows\n * the width of the box.\n */\nexport function VirtualGrid({ className, count, scroll = \"box\", columns = { minWidth: 160 }, estimateSize = 160, overscan = 2, gap = 0, getKey, restoreKey, handleRef, onRangeChange, onScroll, onKeyDown, children, ...props }: VirtualGridProps) {\n  const windowed = scroll === \"window\";\n  const { box, setBox, height, width } = useBox(windowed);\n  const perRow = typeof columns === \"number\" ? Math.max(1, Math.floor(columns)) : Math.max(1, Math.floor((width + gap) / (Math.max(1, columns.minWidth) + gap)));\n  const rowCount = Math.ceil(count / perRow);\n  const grid = useWindowing({ box, windowed, height, ready: height > 0 && width > 0, count, rowCount, perRow, grid: true, estimateSize, getKey: undefined, gap, overscan, restoreKey, handleRef, onRangeChange, onScroll, onKeyDown });\n  return (\n    <div ref={setBox} data-slot=\"virtual-grid\" data-scroll={scroll} role=\"list\" tabIndex={windowed ? undefined : 0} data-columns={perRow} onScroll={grid.onScroll} onKeyDown={grid.onKeyDown} className={cn(windowed ? PAGE : BOX, className)} {...props}>\n      <div data-slot=\"virtual-grid-sizer\" role=\"presentation\" className=\"relative w-full\" style={{ height: grid.total }} onFocus={grid.onFocus} onBlur={grid.onBlur}>\n        {grid.rows.map((row) => (\n          <div\n            key={row}\n            data-slot=\"virtual-grid-row\"\n            role=\"presentation\"\n            data-row={row}\n            className={cn(ROW, \"grid\")}\n            style={{ transform: `translateY(${grid.offsets[row] ?? 0}px)`, gridTemplateColumns: `repeat(${perRow}, minmax(0, 1fr))`, columnGap: gap }}\n          >\n            {Array.from({ length: Math.min(perRow, count - row * perRow) }, (_, column) => {\n              const index = row * perRow + column;\n              return (\n                <div key={getKey ? getKey(index) : index} data-slot=\"virtual-grid-item\" role=\"listitem\" aria-setsize={count} aria-posinset={index + 1} data-index={index} className=\"min-w-0\">\n                  {children(index)}\n                </div>\n              );\n            })}\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "More items than the page should hold at once (a few hundred or more): a feed, a log, search results, a picture library. Rows may have any height: each is measured once it is drawn and the rest are estimated, and the view does not jump when a row above it turns out taller. Give the box a height and a name (`aria-label`); or, where the list is the page (a feed, results under a header), `scroll=\"window\"` and no height: it then grows to its full length and the window scrolls it. For a short list render the rows plainly; for a conversation that grows at the bottom use thread; for pages of results use pagination. Written here on ResizeObserver instead of adding a virtualisation package: a headless one would bring the offsets but not the roles, the positions for screen readers, the kept focus or the restoration, which are most of this file.",
    "example": "// Rows of any height\n<VirtualList count={messages.length} estimateSize={72} getKey={(index) => messages[index].id} aria-label=\"Messages\" className=\"h-96 rounded-surface border\">\n  {(index) => <article className=\"border-b p-3\">{messages[index].text}</article>}\n</VirtualList>\n\n// A grid, as many columns as fit; the place is remembered for this tab\n<VirtualGrid count={pictures.length} columns={{ minWidth: 160 }} gap={8} estimateSize={160} restoreKey=\"library\" aria-label=\"Pictures\" className=\"h-[32rem]\">\n  {(index) => <img src={pictures[index].src} alt={pictures[index].alt} className=\"aspect-square w-full rounded-control object-cover\" />}\n</VirtualGrid>\n\n// The page scrolls, not a box: no height, and rows above and below the window are not rendered\n<VirtualList scroll=\"window\" count={results.length} estimateSize={96} getKey={(index) => results[index].id} aria-label=\"Results\">\n  {(index) => <ResultCard result={results[index]} />}\n</VirtualList>\n\n// Going to an item\nconst list = useRef<VirtualListHandle>(null);\n<VirtualList handleRef={list} count={10000} aria-label=\"Lines\">{(index) => <p className=\"p-2\">Line {index + 1}</p>}</VirtualList>\n<Button onClick={() => list.current?.scrollToIndex(4999, { align: \"center\" })}>Go to line 5,000</Button>",
    "client": true
  }
}
