diff --git a/components/combobox.test.ts b/components/combobox.test.ts index 3d4bcbdbc..1679c5424 100644 --- a/components/combobox.test.ts +++ b/components/combobox.test.ts @@ -4,12 +4,18 @@ import test from "node:test"; import { applyComboboxWheelScroll, + comboboxNextRenderLimit, comboboxWheelDeltaToPixels, filterComboboxOptions, focusComboboxInput, selectComboboxInputIfFocused, canComboboxOpen, getNextComboboxActiveIndex, + shouldExpandComboboxWindow, + shouldResetComboboxWindow, + comboboxWindowStartForActiveIndex, + COMBOBOX_INITIAL_RENDER_LIMIT, + COMBOBOX_RENDER_LIMIT_STEP, type ComboboxScrollableTarget, } from "./ui/combobox.tsx"; @@ -85,7 +91,7 @@ test("combobox exposes active-option semantics for keyboard navigation", () => { assert.match(source, /role="combobox"/); assert.match(source, /aria-activedescendant=/); assert.match(source, /role=\{listbox \? "listbox" : undefined\}/); - assert.match(source, //); + assert.match(source, //); assert.match(source, /\s*\{/); assert.match(source, /role="option"/); assert.match(source, /open && !disabled && hasActiveOption/); @@ -93,6 +99,130 @@ test("combobox exposes active-option semantics for keyboard navigation", () => { assert.match(source, /const handleCreate = \(\) => \{[\s\S]*?setOpen\(false\)\s*setActiveIndex\(-1\)/); }); +test("combobox render window grows in bounded steps and stops at the end", () => { + assert.equal(comboboxNextRenderLimit(COMBOBOX_INITIAL_RENDER_LIMIT, 10), null); + assert.equal( + comboboxNextRenderLimit(COMBOBOX_INITIAL_RENDER_LIMIT, 500), + COMBOBOX_INITIAL_RENDER_LIMIT + COMBOBOX_RENDER_LIMIT_STEP, + ); + assert.equal(comboboxNextRenderLimit(480, 500), 500); + assert.equal(comboboxNextRenderLimit(500, 500), null); + assert.equal(comboboxNextRenderLimit(600, 500), null); +}); + +test("combobox render window expands when the list is scrolled near its bottom", () => { + const target = (scrollTop: number): ComboboxScrollableTarget => ({ + clientHeight: 280, + scrollHeight: 500 * 40, + scrollTop, + }); + + // Far from the bottom: keep the window as-is. + assert.equal(shouldExpandComboboxWindow(target(0), COMBOBOX_INITIAL_RENDER_LIMIT, 500), false); + // Near the bottom of the mounted slice: expand it. + assert.equal( + shouldExpandComboboxWindow(target(500 * 40 - 280 - 10), COMBOBOX_INITIAL_RENDER_LIMIT, 500), + true, + ); + // Everything already rendered: never expand. + assert.equal(shouldExpandComboboxWindow(target(0), 500, 500), false); + // Empty list cannot expand. + assert.equal(shouldExpandComboboxWindow(target(0), 0, 0), false); +}); + +test("combobox slid windows reset when the list is scrolled back to its top", () => { + const target = (scrollTop: number): ComboboxScrollableTarget => ({ + clientHeight: 280, + scrollHeight: 60 * 40, + scrollTop, + }); + + assert.equal(shouldResetComboboxWindow(target(0)), true); + assert.equal(shouldResetComboboxWindow(target(40)), true); + assert.equal(shouldResetComboboxWindow(target(120)), false); +}); + +test("combobox keyboard scrolling into view does not reset a slid window", () => { + // The scroll-into-view effect marks its scroll events as navigational so + // sliding toward the top by ArrowUp cannot trigger the manual-scroll + // reset (which would clear the active option and lose backward reach). + assert.match(source, /const navigationalScrollRef = React\.useRef\(false\)/); + assert.match( + source, + /React\.useEffect\(\(\) => \{\s*\/\/ Scrolling the active option into view emits scroll events[\s\S]*?navigationalScrollRef\.current = true\s*activeOptionRef\.current\?\.scrollIntoView\(\{ block: 'nearest' \}\)\s*requestAnimationFrame\(\(\) => \{\s*navigationalScrollRef\.current = false\s*\}\)/, + ); + assert.match( + source, + /if \(windowStart > 0 && shouldResetComboboxWindow\(scrollTarget\)\) \{\s*if \(navigationalScrollRef\.current\) return\s*setActiveIndex\(-1\)/, + ); +}); + +test("combobox keyboard scrolling into view does not expand a slid window", () => { + // Programmatic scrolls from scrolling the active option into view can land + // near the bottom of the last window; they are not manual scrolls, so the + // keyboard window must stay a fixed size instead of growing on every + // ArrowUp/ArrowDown wrap boundary. + assert.match( + source, + /\/\/ skip expansion to keep the keyboard window at a fixed size instead[\s\S]*?if \(navigationalScrollRef\.current\) return\s*if \(!shouldExpandComboboxWindow\(/, + ); +}); + +test("combobox render window resets during render, before committing a changed result set", () => { + // The reset must not live in a post-commit effect, otherwise a cleared or + // changed query commits the new result sliced with a stale oversized + // window before the effect can shrink it back. + assert.doesNotMatch( + source.slice(source.indexOf("const [windowKey, setWindowKey]"), + source.indexOf("const renderedOptions")), + /useEffect/, + ); + assert.match( + source, + /if \(windowKey\.open !== open \|\| windowKey\.filteredOptions !== filteredOptions\) \{\s*setWindowKey\(\{ open, filteredOptions \}\)\s*setRenderLimit\(COMBOBOX_INITIAL_RENDER_LIMIT\)\s*setWindowStart\(0\)/, + ); +}); + +test("combobox resets the listbox scroll position alongside the render window", () => { + // The render-window reset only touches React state; the listbox DOM node + // would keep (or clamp) its previous scrollTop, so a fresh initial slice + // would be displayed near its bottom instead of at its first match. + assert.match(source, /const optionsScrollRef = React\.useRef\(null\)/); + assert.match(source, /ref=\{scrollRef\}/); + assert.match( + source, + /\/\/ Resetting the render window alone is not enough[\s\S]*?React\.useEffect\(\(\) => \{\s*if \(optionsScrollRef\.current\) optionsScrollRef\.current\.scrollTop = 0\s*\}, \[open, filteredOptions\]\)/, + ); +}); + +test("combobox renders options incrementally so large font lists cannot freeze the picker", () => { + assert.match(source, /const \[renderLimit, setRenderLimit\] = React\.useState\(COMBOBOX_INITIAL_RENDER_LIMIT\)/); + assert.match(source, /filteredOptions\.slice\(windowStart, windowStart \+ renderLimit\)/); + assert.match(source, /renderedOptions\.map\(\(option, optionIndex\)/); + assert.match(source, /onScrollCapture=\{handleOptionsScrollCapture\}/); + assert.match( + source, + /const nextWindowStart = comboboxWindowStartForActiveIndex\(\s*optionIndex,\s*windowStart,\s*renderLimit,\s*filteredOptions\.length,\s*\)\s*if \(nextWindowStart !== null\) setWindowStart\(nextWindowStart\)/, + ); +}); + +test("combobox keyboard navigation slides a bounded window instead of mounting the whole list", () => { + // Within the initial window: no shift. + assert.equal(comboboxWindowStartForActiveIndex(10, 0, 60, 500), null); + // ArrowUp wrap to the last option: slide so it is mounted, without + // growing the mounted count beyond the window size. + assert.equal(comboboxWindowStartForActiveIndex(499, 0, 60, 500), 440); + // Already mounted at the window edge: no further shift. + assert.equal(comboboxWindowStartForActiveIndex(499, 440, 60, 500), null); + // ArrowUp wrap back above the window start: slide so it is mounted. + assert.equal(comboboxWindowStartForActiveIndex(0, 440, 60, 500), 0); + // Small lists never need a window. + assert.equal(comboboxWindowStartForActiveIndex(2, 0, 60, 10), null); + // No active option or empty list: no shift. + assert.equal(comboboxWindowStartForActiveIndex(-1, 0, 60, 500), null); + assert.equal(comboboxWindowStartForActiveIndex(0, 0, 60, 0), null); +}); + test("combobox trigger shows a focus-within ring for keyboard users", () => { assert.match(source, /focus-within:outline-none focus-within:ring-1 focus-within:ring-ring/); }); diff --git a/components/ui/combobox.tsx b/components/ui/combobox.tsx index 08299aa2d..4435048e6 100644 --- a/components/ui/combobox.tsx +++ b/components/ui/combobox.tsx @@ -101,14 +101,71 @@ export const selectComboboxInputIfFocused = ( export const canComboboxOpen = (disabled: boolean, nextOpen: boolean): boolean => !disabled || !nextOpen +/** + * Incremental rendering limits for large option lists (e.g. the font pickers + * can list hundreds of locally installed fonts). Rendering every option at + * once freezes the UI, so we mount an initial slice and grow the window as + * the user scrolls deeper, and slide the bounded window when arrow + * navigation jumps to an option beyond it. + */ +export const COMBOBOX_INITIAL_RENDER_LIMIT = 60 +export const COMBOBOX_RENDER_LIMIT_STEP = 120 +const COMBOBOX_EXPAND_SCROLL_THRESHOLD_PX = 80 + +export const comboboxNextRenderLimit = ( + currentLimit: number, + optionCount: number, +): number | null => { + if (optionCount <= currentLimit) return null + return Math.min(currentLimit + COMBOBOX_RENDER_LIMIT_STEP, optionCount) +} + +export const shouldExpandComboboxWindow = ( + target: ComboboxScrollableTarget, + renderedCount: number, + optionCount: number, +): boolean => { + if (renderedCount >= optionCount) return false + const distanceFromBottom = target.scrollHeight - (target.scrollTop + target.clientHeight) + return distanceFromBottom <= COMBOBOX_EXPAND_SCROLL_THRESHOLD_PX +} + +export const shouldResetComboboxWindow = (target: ComboboxScrollableTarget): boolean => + target.scrollTop <= COMBOBOX_EXPAND_SCROLL_THRESHOLD_PX + +/** + * Keyboard navigation can land beyond the mounted window (e.g. ArrowUp wraps + * straight to the last option). Instead of growing the prefix until that + * index is mounted — which mounts every row for large lists — slide the + * bounded window so the destination sits at its edge. Returns the new window + * start, or null when the active option is already mounted. + */ +export const comboboxWindowStartForActiveIndex = ( + activeOptionIndex: number, + windowStart: number, + renderLimit: number, + optionCount: number, +): number | null => { + if (optionCount <= 0 || activeOptionIndex < 0) return null + if (activeOptionIndex < windowStart) return activeOptionIndex + if (activeOptionIndex >= windowStart + renderLimit) { + return Math.max(0, Math.min(activeOptionIndex - renderLimit + 1, optionCount - renderLimit)) + } + return null +} + function ComboboxOptionsList({ children, id, listbox = false, + onScrollCapture, + scrollRef, }: { children: React.ReactNode; id?: string; listbox?: boolean; + onScrollCapture?: React.UIEventHandler; + scrollRef?: React.RefObject; }) { const handleWheelCapture = (event: React.WheelEvent) => { const handled = applyComboboxWheelScroll(event.currentTarget, event.deltaY, event.deltaMode) @@ -122,9 +179,11 @@ function ComboboxOptionsList({ return (
{children}
@@ -155,9 +214,19 @@ export function Combobox({ const [activeIndex, setActiveIndex] = React.useState(-1) // Track if user is actively searching (typed something after opening) const [isSearching, setIsSearching] = React.useState(false) + // Incremental rendering window for very large option lists + const [renderLimit, setRenderLimit] = React.useState(COMBOBOX_INITIAL_RENDER_LIMIT) + // First mounted option index, so keyboard jumps slide the window instead + // of mounting the entire prefix of a large list. + const [windowStart, setWindowStart] = React.useState(0) const inputRef = React.useRef(null) const wasOpenRef = React.useRef(false) const activeOptionRef = React.useRef(null) + const optionsScrollRef = React.useRef(null) + // True while scroll events on the options list are caused by this + // component scrolling the active option into view (keyboard navigation, + // mouse hover) rather than by the user scrolling manually. + const navigationalScrollRef = React.useRef(false) const listboxId = React.useId() // Sync input value with external value when not focused @@ -188,6 +257,76 @@ export function Combobox({ return filterComboboxOptions(options, inputValue, isSearching) }, [options, inputValue, isSearching]) + // Restart the window from its initial size whenever the picker opens or + // the filtered result set changes (option set, search mode, or query), so + // a previously grown or slid window never persists across a changed list. + // The reset happens during render (React discards the render output and + // re-renders immediately after a render-phase state update), so a changed + // result set is never committed with a stale, oversized window. + const [windowKey, setWindowKey] = React.useState({ open, filteredOptions }) + if (windowKey.open !== open || windowKey.filteredOptions !== filteredOptions) { + setWindowKey({ open, filteredOptions }) + setRenderLimit(COMBOBOX_INITIAL_RENDER_LIMIT) + setWindowStart(0) + } + + const renderedOptions = React.useMemo(() => { + return filteredOptions.slice(windowStart, windowStart + renderLimit) + }, [filteredOptions, windowStart, renderLimit]) + + // Resetting the render window alone is not enough: the listbox DOM node + // keeps (or clamps) its previous scrollTop, so a fresh initial slice + // would be displayed near its bottom instead of at its first match. + React.useEffect(() => { + if (optionsScrollRef.current) optionsScrollRef.current.scrollTop = 0 + }, [open, filteredOptions]) + + const expandRenderWindow = React.useCallback(() => { + setRenderLimit((current) => { + const next = comboboxNextRenderLimit(current, options.length) + return next ?? current + }) + }, [options.length]) + + const handleOptionsScrollCapture = React.useCallback((event: React.UIEvent) => { + const target = event.currentTarget + const scrollTarget = { + clientHeight: target.clientHeight, + scrollHeight: target.scrollHeight, + scrollTop: target.scrollTop, + } + // Scrolling back to the top restores the initial window so options + // above a slid window become reachable again. The active index must + // be cleared too, otherwise the active-option effect immediately + // slides the window back to a stale active option. + // Scrolls emitted by scrolling the active option into view are not + // manual scrolls: skipping the reset keeps ArrowUp navigation able to + // slide into the preceding window without losing the active option. + if (windowStart > 0 && shouldResetComboboxWindow(scrollTarget)) { + if (navigationalScrollRef.current) return + setActiveIndex(-1) + setWindowStart(0) + setRenderLimit(COMBOBOX_INITIAL_RENDER_LIMIT) + return + } + // Programmatic scrolls from scrolling the active option into view can + // also land near the bottom of a slid window (e.g. at the last window + // while keyboard-navigating). Those are not manual scrolls either, so + // skip expansion to keep the keyboard window at a fixed size instead + // of growing it on every ArrowUp/ArrowDown wrap boundary. + if (navigationalScrollRef.current) return + if (!shouldExpandComboboxWindow(scrollTarget, renderedOptions.length, filteredOptions.length)) { + return + } + // A slid window that already reaches the final option cannot mount + // more rows by growing renderLimit (the slice is capped by the option + // count), so growing it here without mounting anything would leave an + // inflated limit behind; a later wrap back to index 0 would then reset + // windowStart to zero and mount the entire grown prefix in one commit. + if (windowStart + renderedOptions.length >= filteredOptions.length) return + expandRenderWindow() + }, [windowStart, renderedOptions.length, filteredOptions.length, expandRenderWindow]) + const showCreateOption = React.useMemo(() => { if (!allowCreate || !inputValue.trim() || !isSearching) return false const lower = inputValue.toLowerCase().trim() @@ -197,9 +336,60 @@ export function Combobox({ const selectableOptionCount = filteredOptions.length + (showCreateOption ? 1 : 0) const hasActiveOption = activeIndex >= 0 && activeIndex < selectableOptionCount + // Keyboard navigation must never land on an option that is not mounted + // yet, otherwise its aria-activedescendant id would not exist. Slide the + // bounded window so the destination is mounted without mounting the + // entire prefix of a large list. This runs during render (React discards + // the render and re-renders immediately after a render-phase state + // update), so the commit that exposes a new active descendant already + // has that option mounted — a post-commit effect would commit an + // aria-activedescendant id that does not exist in the DOM yet. + const [activeWindowKey, setActiveWindowKey] = React.useState({ + activeIndex, + showCreateOption, + windowStart, + renderLimit, + filteredCount: filteredOptions.length, + }) + if ( + activeIndex >= 0 && + (activeWindowKey.activeIndex !== activeIndex || + activeWindowKey.showCreateOption !== showCreateOption || + activeWindowKey.windowStart !== windowStart || + activeWindowKey.renderLimit !== renderLimit || + activeWindowKey.filteredCount !== filteredOptions.length) + ) { + setActiveWindowKey({ + activeIndex, + showCreateOption, + windowStart, + renderLimit, + filteredCount: filteredOptions.length, + }) + const optionIndex = activeIndex - (showCreateOption ? 1 : 0) + const nextWindowStart = comboboxWindowStartForActiveIndex( + optionIndex, + windowStart, + renderLimit, + filteredOptions.length, + ) + if (nextWindowStart !== null) setWindowStart(nextWindowStart) + } + React.useEffect(() => { + // Scrolling the active option into view emits scroll events even when + // keyboard navigation slides the window toward the top of the list. + // Mark them as navigational so the manual-scroll reset below does not + // mistake them for the user scrolling back to the top, which would + // clear the active option and make preceding windows unreachable by + // ArrowUp. The flag is cleared on the next frame, once the scroll + // events for this update have been dispatched. + navigationalScrollRef.current = true activeOptionRef.current?.scrollIntoView({ block: 'nearest' }) - }, [activeIndex]) + requestAnimationFrame(() => { + navigationalScrollRef.current = false + }) + }, [activeIndex, renderedOptions.length, windowStart]) React.useEffect(() => { if (!disabled || !open) return @@ -357,7 +547,7 @@ export function Combobox({ style={{ width: 'var(--radix-popover-trigger-width)' }} > {/* Options List */} - + {filteredOptions.length === 0 && !showCreateOption ? (
{emptyText} @@ -371,6 +561,8 @@ export function Combobox({ id={`${listboxId}-option-0`} role="option" aria-selected={false} + aria-posinset={1} + aria-setsize={selectableOptionCount} tabIndex={-1} type="button" className={cn( @@ -391,9 +583,9 @@ export function Combobox({
)} - {/* Existing options */} - {filteredOptions.map((option, optionIndex) => { - const selectableIndex = optionIndex + (showCreateOption ? 1 : 0) + {/* Existing options (rendered incrementally for large lists) */} + {renderedOptions.map((option, optionIndex) => { + const selectableIndex = optionIndex + windowStart + (showCreateOption ? 1 : 0) return (