Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

perf(Selector): memoize option rows, so an open or a highlight move re-renders only the rows it changes (#9598)

Cindy Zhangf4edef89981f
diff --git a/.changeset/selector-memo-option-rows.md b/.changeset/selector-memo-option-rows.md
new file mode 100644
index 0000000000..2e4742d705
--- /dev/null
+++ b/.changeset/selector-memo-option-rows.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[perf] Opening a Selector's list or moving its highlight re-renders only the options whose highlight or selection changes, not every option, so a long list opens sooner and arrow keys respond faster.
+
+@cixzhang
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index d3fb508c47..364e3552a7 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -5177,6 +5177,37 @@ describe('Selector press model', () => {
expect(listbox).not.toHaveClass(hash(touchStyles.panYPinchZoom));
});
+ it('re-renders only the rows a highlight move or the open changes, not the whole list', async () => {
+ const user = userEvent.setup();
+ const many = Array.from({length: 50}, (_, i) => `Option ${i}`);
+ // A stable renderOption: it runs once per row render.
+ const rendered: string[] = [];
+ const renderOption = (option: {value: string}) => {
+ rendered.push(option.value);
+ return option.value;
+ };
+ function Harness() {
+ return (
+ <Selector
+ label="Item"
+ options={many}
+ onChange={() => {}}
+ renderOption={renderOption}
+ />
+ );
+ }
+ render(<Harness />);
+ expect(new Set(rendered).size).toBe(50);
+ rendered.length = 0;
+ await user.click(screen.getByRole('combobox'));
+ // Opening highlights the first row; no other row's props change.
+ expect(rendered.length).toBeLessThanOrEqual(2);
+ rendered.length = 0;
+ await user.keyboard('{ArrowDown}');
+ // The highlight moves from row 0 to row 1: those two rows only.
+ expect([...new Set(rendered)].sort()).toEqual(['Option 0', 'Option 1']);
+ });
+
it('a long list renders its scrolling touch-action from the first open, with no class swap after the open measure', async () => {
const user = userEvent.setup();
const many = Array.from({length: 249}, (_, i) => `Option ${i}`);
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 2a6acdf22a..a287ea6eee 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -20,6 +20,7 @@
*/
import React, {
+ memo,
use,
useCallback,
useEffect,
@@ -37,6 +38,7 @@ import {useTooltip} from '../Tooltip';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {useIndicator} from '../Indicator';
import type {IndicatorPosition} from '../Indicator';
+import type {IndicatorComponent, IndicatorMap} from '../Indicator/types';
import type {IconName} from '../Icon';
import {
Field,
@@ -66,13 +68,8 @@ import {
borderVars,
} from '../theme/tokens.stylex';
import type {SelectorOptionType, SelectorOptionData} from './types';
-import {
- isOptionData,
- isDivider,
- isSection,
- normalizeOption,
- getSelectableOptions,
-} from './utils';
+import {isOptionData, isDivider, isSection, normalizeOption} from './utils';
+import {getSelectableOptionEntries} from './selectableOptionEntries';
import {useCombobox, useSelectedItemOffset} from './hooks';
import {useMenuPress} from '../hooks/useMenuPress';
import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow';
@@ -917,6 +914,108 @@ function DefaultOption({option}: {option: SelectorOptionData}) {
);
}
+interface SelectorOptionRowProps {
+ item: SelectorOptionData;
+ flatIndex: number;
+ id: string;
+ isHighlighted: boolean;
+ isSelected: boolean;
+ size: SelectorSize;
+ indicatorPosition: IndicatorPosition;
+ renderOption: ((option: SelectorOptionData) => ReactNode) | undefined;
+ SelectionMark: IndicatorComponent<IndicatorMap['check']>;
+ onSelect: (item: SelectorOptionData) => void;
+ onHover: (item: SelectorOptionData, flatIndex: number) => void;
+}
+
+/**
+ * Keep each prop stable across renders that do not change this row. A new
+ * `onSelect` or `renderOption` re-renders every row.
+ */
+const SelectorOptionRow = memo(function SelectorOptionRow({
+ item,
+ flatIndex,
+ id,
+ isHighlighted,
+ isSelected,
+ size,
+ indicatorPosition,
+ renderOption,
+ SelectionMark,
+ onSelect,
+ onHover,
+}: SelectorOptionRowProps) {
+ /*
+ * Rendered UNCONDITIONALLY, with the state passed down: the default
+ * check draws nothing when unchecked, but a theme that replaces the
+ * `check` indicator with a radio needs the unselected state to draw
+ * its empty circle. `{isSelected && …}` would make that impossible.
+ *
+ * `selector-check` stays the stable target for the mark's position
+ * in the row; the indicator owns what the mark looks like.
+ */
+ const mark = (
+ <span {...stylex.props(styles.itemMarkColumn)}>
+ <SelectionMark
+ state={isSelected ? 'checked' : 'unchecked'}
+ size="sm"
+ isDisabled={item.disabled ?? false}
+ {...themeProps('selector-check')}
+ />
+ </span>
+ );
+
+ const optionContent = (
+ <span {...stylex.props(styles.itemContent)}>
+ {renderOption ? renderOption(item) : <DefaultOption option={item} />}
+ </span>
+ );
+
+ return (
+ <div
+ id={id}
+ role="option"
+ aria-selected={isSelected}
+ aria-disabled={item.disabled}
+ onClick={() => onSelect(item)}
+ onMouseEnter={() => onHover(item, flatIndex)}
+ {...mergeProps(
+ // Stable theme target on the option row itself, mirroring
+ // `multi-selector-option`: it carries the row's size and runtime
+ // state so a theme can express "selected option at large" or
+ // restyle a given row density without structural selectors. The
+ // row's padding is split across a base and a per-size override (the
+ // default `md` trims the block axis), so `size` is what a theme
+ // needs to reach it. Named `-option-row` because `selector-option`
+ // is the public SelectorOption content primitive, not this row.
+ themeProps('selector-option-row', {
+ size,
+ selected: isSelected ? 'selected' : null,
+ disabled: item.disabled ? 'disabled' : null,
+ }),
+ stylex.props(
+ styles.item,
+ itemSizeStyles[size],
+ isHighlighted && styles.itemHighlighted,
+ isSelected && styles.itemSelected,
+ item.disabled && styles.itemDisabled,
+ ),
+ )}>
+ {indicatorPosition === 'start' ? (
+ <>
+ {mark}
+ {optionContent}
+ </>
+ ) : (
+ <>
+ {optionContent}
+ {mark}
+ </>
+ )}
+ </div>
+ );
+});
+
// Case-insensitive substring match for a single option. The one predicate used
// by both the flat filter (count + keyboard nav) and the grouped renderer, so
// what is shown while searching stays in lockstep with the announced count.
@@ -1118,10 +1217,19 @@ export function Selector<T extends SelectorOptionType>(
: ariaLabelledBy;
// Flatten options for keyboard navigation
- const selectableItems = useMemo(
- () => getSelectableOptions(options),
+ const selectableEntries = useMemo(
+ () => getSelectableOptionEntries(options),
[options],
);
+ const selectableItems = useMemo(
+ () => selectableEntries.map(entry => entry.item),
+ [selectableEntries],
+ );
+ // Rows need the same item object on every render, or their memo fails.
+ const normalizedOf = useMemo(
+ () => new Map(selectableEntries.map(entry => [entry.source, entry.item])),
+ [selectableEntries],
+ );
// `action` is declared on the shared option type for `MultiSelector`;
// this listbox has not adopted it, so it renders the option without the
@@ -1613,84 +1721,22 @@ export function Selector<T extends SelectorOptionType>(
// Render an individual item
const renderItem = useCallback(
- (item: SelectorOptionData, flatIndex: number) => {
- const isHighlighted = flatIndex === highlightedIndex;
- const isSelected = item.value === normalizedValue;
-
- /*
- * Rendered UNCONDITIONALLY, with the state passed down: the default
- * check draws nothing when unchecked, but a theme that replaces the
- * `check` indicator with a radio needs the unselected state to draw
- * its empty circle. `{isSelected && …}` would make that impossible.
- *
- * `selector-check` stays the stable target for the mark's position
- * in the row; the indicator owns what the mark looks like.
- */
- const mark = (
- <span {...stylex.props(styles.itemMarkColumn)}>
- <SelectionMark
- state={isSelected ? 'checked' : 'unchecked'}
- size="sm"
- isDisabled={item.disabled ?? false}
- {...themeProps('selector-check')}
- />
- </span>
- );
-
- const optionContent = (
- <span {...stylex.props(styles.itemContent)}>
- {renderOption ? renderOption(item) : <DefaultOption option={item} />}
- </span>
- );
-
- const content =
- indicatorPosition === 'start' ? (
- <>
- {mark}
- {optionContent}
- </>
- ) : (
- <>
- {optionContent}
- {mark}
- </>
- );
-
- return (
- <div
- key={item.value}
- id={getItemId(flatIndex)}
- role="option"
- aria-selected={isSelected}
- aria-disabled={item.disabled}
- onClick={() => onItemSelect(item)}
- onMouseEnter={() => onItemMouseEnter(item, flatIndex)}
- {...mergeProps(
- // Stable theme target on the option row itself, mirroring
- // `multi-selector-option`: it carries the row's size and runtime
- // state so a theme can express "selected option at large" or
- // restyle a given row density without structural selectors. The
- // row's padding is split across a base and a per-size override (the
- // default `md` trims the block axis), so `size` is what a theme
- // needs to reach it. Named `-option-row` because `selector-option`
- // is the public SelectorOption content primitive, not this row.
- themeProps('selector-option-row', {
- size,
- selected: isSelected ? 'selected' : null,
- disabled: item.disabled ? 'disabled' : null,
- }),
- stylex.props(
- styles.item,
- itemSizeStyles[size],
- isHighlighted && styles.itemHighlighted,
- isSelected && styles.itemSelected,
- item.disabled && styles.itemDisabled,
- ),
- )}>
- {content}
- </div>
- );
- },
+ (item: SelectorOptionData, flatIndex: number) => (
+ <SelectorOptionRow
+ key={item.value}
+ item={item}
+ flatIndex={flatIndex}
+ id={getItemId(flatIndex)}
+ isHighlighted={flatIndex === highlightedIndex}
+ isSelected={item.value === normalizedValue}
+ size={size}
+ indicatorPosition={indicatorPosition}
+ renderOption={renderOption}
+ SelectionMark={SelectionMark}
+ onSelect={onItemSelect}
+ onHover={onItemMouseEnter}
+ />
+ ),
[
renderOption,
indicatorPosition,
@@ -1757,7 +1803,7 @@ export function Selector<T extends SelectorOptionType>(
} else if (isSection(option)) {
const sectionItems: ReactNode[] = [];
for (const opt of option.options) {
- const normalized = normalizeOption(opt);
+ const normalized = normalizedOf.get(opt) ?? normalizeOption(opt);
if (isSearching && !optionMatchesQuery(normalized, searchQuery)) {
continue;
}
@@ -1790,7 +1836,7 @@ export function Selector<T extends SelectorOptionType>(
</div>,
);
} else if (isOptionData(option)) {
- const normalized = normalizeOption(option);
+ const normalized = normalizedOf.get(option) ?? normalizeOption(option);
if (isSearching && !optionMatchesQuery(normalized, searchQuery)) {
continue;
}
@@ -1802,6 +1848,7 @@ export function Selector<T extends SelectorOptionType>(
return elements;
}, [
options,
+ normalizedOf,
renderItem,
hasSearch,
searchQuery,
diff --git a/packages/core/src/Selector/optionShape.ts b/packages/core/src/Selector/optionShape.ts
new file mode 100644
index 0000000000..10031e8ce4
--- /dev/null
+++ b/packages/core/src/Selector/optionShape.ts
@@ -0,0 +1,64 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file optionShape.ts
+ * @input Selector option values
+ * @output The option type guards and `normalizeOption`
+ * @position Internal; re-exported by utils.ts, the public entry point
+ */
+
+import type {
+ SelectorOptionType,
+ SelectorOptionData,
+ SelectorDivider,
+ SelectorSection,
+} from './types';
+
+/**
+ * Type guard: check if option is a selectable option (string or OptionData)
+ */
+export function isOptionData(
+ option: SelectorOptionType,
+): option is SelectorOptionData | string {
+ if (typeof option === 'string') {
+ return true;
+ }
+ return !('type' in option);
+}
+
+/**
+ * Type guard: check if option is a divider
+ */
+export function isDivider(
+ option: SelectorOptionType,
+): option is SelectorDivider {
+ return (
+ typeof option === 'object' && 'type' in option && option.type === 'divider'
+ );
+}
+
+/**
+ * Type guard: check if option is a section
+ */
+export function isSection(
+ option: SelectorOptionType,
+): option is SelectorSection {
+ return (
+ typeof option === 'object' && 'type' in option && option.type === 'section'
+ );
+}
+
+/**
+ * Normalize string or option to consistent shape
+ */
+export function normalizeOption(
+ option: string | SelectorOptionData,
+): SelectorOptionData {
+ if (typeof option === 'string') {
+ return {value: option, label: option};
+ }
+ return {
+ ...option,
+ label: option.label ?? option.value,
+ };
+}
diff --git a/packages/core/src/Selector/selectableOptionEntries.ts b/packages/core/src/Selector/selectableOptionEntries.ts
new file mode 100644
index 0000000000..23466be614
--- /dev/null
+++ b/packages/core/src/Selector/selectableOptionEntries.ts
@@ -0,0 +1,39 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file selectableOptionEntries.ts
+ * @input Selector options, with sections and dividers
+ * @output `getSelectableOptionEntries`: each selectable item with the option
+ * it was given as
+ * @position Internal; the one walk behind utils.ts's `getSelectableOptions`
+ * and Selector's rows
+ */
+
+import type {SelectorOptionType, SelectorOptionData} from './types';
+import {isOptionData, isSection, normalizeOption} from './optionShape';
+
+/** A selectable option as given, and its normalized data. */
+export interface SelectableOptionEntry {
+ readonly source: string | SelectorOptionData;
+ readonly item: SelectorOptionData;
+}
+
+/**
+ * Every selectable option (sections flattened, dividers skipped), each with
+ * the option it was given as.
+ */
+export function getSelectableOptionEntries(
+ options: SelectorOptionType[],
+): SelectableOptionEntry[] {
+ const result: SelectableOptionEntry[] = [];
+ for (const option of options) {
+ if (isOptionData(option)) {
+ result.push({source: option, item: normalizeOption(option)});
+ } else if (isSection(option)) {
+ for (const opt of option.options) {
+ result.push({source: opt, item: normalizeOption(opt)});
+ }
+ }
+ }
+ return result;
+}
diff --git a/packages/core/src/Selector/utils.ts b/packages/core/src/Selector/utils.ts
index 71a43ffabd..e68fbc7d0d 100644
--- a/packages/core/src/Selector/utils.ts
+++ b/packages/core/src/Selector/utils.ts
@@ -6,61 +6,15 @@
* @position Utilities; used by Selector.tsx
*/
-import type {
- SelectorOptionType,
- SelectorOptionData,
- SelectorDivider,
- SelectorSection,
-} from './types';
+import type {SelectorOptionType, SelectorOptionData} from './types';
+import {getSelectableOptionEntries} from './selectableOptionEntries';
-/**
- * Type guard: check if option is a selectable option (string or OptionData)
- */
-export function isOptionData(
- option: SelectorOptionType,
-): option is SelectorOptionData | string {
- if (typeof option === 'string') {
- return true;
- }
- return !('type' in option);
-}
-
-/**
- * Type guard: check if option is a divider
- */
-export function isDivider(
- option: SelectorOptionType,
-): option is SelectorDivider {
- return (
- typeof option === 'object' && 'type' in option && option.type === 'divider'
- );
-}
-
-/**
- * Type guard: check if option is a section
- */
-export function isSection(
- option: SelectorOptionType,
-): option is SelectorSection {
- return (
- typeof option === 'object' && 'type' in option && option.type === 'section'
- );
-}
-
-/**
- * Normalize string or option to consistent shape
- */
-export function normalizeOption(
- option: string | SelectorOptionData,
-): SelectorOptionData {
- if (typeof option === 'string') {
- return {value: option, label: option};
- }
- return {
- ...option,
- label: option.label ?? option.value,
- };
-}
+export {
+ isOptionData,
+ isDivider,
+ isSection,
+ normalizeOption,
+} from './optionShape';
/**
* Get all selectable options (flattening sections)
@@ -68,18 +22,5 @@ export function normalizeOption(
export function getSelectableOptions(
options: SelectorOptionType[],
): SelectorOptionData[] {
- const result: SelectorOptionData[] = [];
-
- for (const option of options) {
- if (isOptionData(option)) {
- result.push(normalizeOption(option));
- } else if (isSection(option)) {
- for (const opt of option.options) {
- result.push(normalizeOption(opt));
- }
- }
- // Skip dividers
- }
-
- return result;
+ return getSelectableOptionEntries(options).map(entry => entry.item);
}
diff --git a/packages/core/src/hooks/useHighlightedOptionScroll.test.ts b/packages/core/src/hooks/useHighlightedOptionScroll.test.ts
new file mode 100644
index 0000000000..9e84de8ee9
--- /dev/null
+++ b/packages/core/src/hooks/useHighlightedOptionScroll.test.ts
@@ -0,0 +1,77 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useHighlightedOptionScroll.test.ts
+ * @input useHighlightedOptionScroll with stubbed option elements
+ * @output Proof that a keyboard or list change scrolls the highlighted option
+ * into view and a hover's own move does not
+ * @position Unit tests for /packages/core/src/hooks/useHighlightedOptionScroll.ts
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {renderHook} from '@testing-library/react';
+import {useHighlightedOptionScroll} from './useHighlightedOptionScroll';
+
+function addOptions(count: number) {
+ const scrolled: string[] = [];
+ for (let i = 0; i < count; i++) {
+ const option = document.createElement('div');
+ option.id = `opt-${i}`;
+ option.scrollIntoView = vi.fn(() => {
+ scrolled.push(option.id);
+ });
+ document.body.append(option);
+ }
+ return scrolled;
+}
+
+afterEach(() => {
+ document.body.innerHTML = '';
+});
+
+const getOptionId = (index: number) => `opt-${index}`;
+
+describe('useHighlightedOptionScroll', () => {
+ it('does not scroll for a hover’s own move, and scrolls for the next keyboard move', () => {
+ const scrolled = addOptions(3);
+ const setHighlightedIndex = vi.fn();
+ const {result, rerender} = renderHook(
+ ({highlightedIndex}: {highlightedIndex: number}) =>
+ useHighlightedOptionScroll({
+ isOpen: true,
+ highlightedIndex,
+ setHighlightedIndex,
+ getOptionId,
+ }),
+ {initialProps: {highlightedIndex: 0}},
+ );
+ scrolled.length = 0;
+ result.current(2);
+ rerender({highlightedIndex: 2});
+ expect(scrolled).toEqual([]);
+ rerender({highlightedIndex: 1});
+ expect(scrolled).toEqual(['opt-1']);
+ });
+
+ it('a hover over the row already highlighted does not stop a new list from scrolling that row into view', () => {
+ const scrolled = addOptions(3);
+ const setHighlightedIndex = vi.fn();
+ const {result, rerender} = renderHook(
+ ({itemCount}: {itemCount: number}) =>
+ useHighlightedOptionScroll({
+ isOpen: true,
+ highlightedIndex: 0,
+ setHighlightedIndex,
+ getOptionId,
+ itemCount,
+ }),
+ {initialProps: {itemCount: 3}},
+ );
+ scrolled.length = 0;
+ // The pointer moves over the highlighted row: no state changes.
+ result.current(0);
+ // A new query's list keeps the same row highlighted.
+ rerender({itemCount: 2});
+ expect(scrolled).toEqual(['opt-0']);
+ });
+});
diff --git a/packages/core/src/hooks/useHighlightedOptionScroll.ts b/packages/core/src/hooks/useHighlightedOptionScroll.ts
index 4c72733ddd..3935c051b2 100644
--- a/packages/core/src/hooks/useHighlightedOptionScroll.ts
+++ b/packages/core/src/hooks/useHighlightedOptionScroll.ts
@@ -8,7 +8,7 @@
* option-id resolver for the owning listbox
* @output Exports useHighlightedOptionScroll: keeps the highlighted option
* scrolled into view for keyboard navigation while hover-driven highlights
- * never scroll
+ * never scroll; the hover callback is stable while `setHighlightedIndex` is
* @position Internal hook; used by useCombobox, useMultiCombobox,
* BaseTypeahead, and DateTimeInput — the owners of combobox highlight state
*/
@@ -42,24 +42,28 @@ export function useHighlightedOptionScroll({
getOptionId,
itemCount,
}: UseHighlightedOptionScrollOptions): (index: number) => void {
- const hoverHighlightRef = useRef(false);
+ // The callback reads no render state, so memoized rows keep one function.
+ const hoveredIndexRef = useRef<number | null>(null);
+ const shownIndexRef = useRef(highlightedIndex);
const highlightFromHover = useCallback(
(index: number) => {
- if (index !== highlightedIndex) {
- hoverHighlightRef.current = true;
- }
+ hoveredIndexRef.current = index;
setHighlightedIndex(index);
},
- [highlightedIndex, setHighlightedIndex],
+ [setHighlightedIndex],
);
useEffect(() => {
- if (hoverHighlightRef.current) {
- hoverHighlightRef.current = false;
- return;
- }
- if (!isOpen || highlightedIndex < 0) {
+ // Only a move to the hovered row came from the hover. A hover on the row
+ // already highlighted changes nothing, so a later run for the same row
+ // (a new list) still scrolls it into view.
+ const hasMoved = shownIndexRef.current !== highlightedIndex;
+ shownIndexRef.current = highlightedIndex;
+ const isFromHover =
+ hasMoved && hoveredIndexRef.current === highlightedIndex;
+ hoveredIndexRef.current = null;
+ if (isFromHover || !isOpen || highlightedIndex < 0) {
return;
}
document