Skip to content

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

TypeScript

perf(Selector): a long list has its scrolling touch-action before the first open (#9591)

Cindy Zhang4d56e6b9b8e5
diff --git a/.changeset/selector-touch-action-first-open.md b/.changeset/selector-touch-action-first-open.md
new file mode 100644
index 0000000000..6d60c8a0d2
--- /dev/null
+++ b/.changeset/selector-touch-action-first-open.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[perf] Opening a Selector with a long option list is faster: the list no longer restyles every option a second time on its first open to switch to its scrolling touch behavior.
+
+@cixzhang
diff --git a/packages/core/src/DropdownMenu/useMenuOverflow.ts b/packages/core/src/DropdownMenu/useMenuOverflow.ts
index 5e6dbdcb8f..ed1b72a881 100644
--- a/packages/core/src/DropdownMenu/useMenuOverflow.ts
+++ b/packages/core/src/DropdownMenu/useMenuOverflow.ts
@@ -4,31 +4,62 @@
/**
* @file useMenuOverflow.ts
- * @input Menu element ref, rendered content, and open state
+ * @input Menu element ref, rendered content, open state, and optionally the
+ * overflow its owner expects from the content alone
* @output Returns whether the open menu overflows its block-size constraint
* @position Shared responsive helper for DropdownMenu and DropdownMenuSubMenu
*/
-import {useCallback, useState, type ReactNode, type RefObject} from 'react';
+import {
+ useCallback,
+ useRef,
+ useState,
+ type ReactNode,
+ type RefObject,
+} from 'react';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
-/** Detect block-axis overflow without making a fitting menu a scroll container. */
+/**
+ * Detect block-axis overflow without making a fitting menu a scroll container.
+ *
+ * `expectedOverflow` is the answer the owner can give before any measure (a
+ * long option list cannot fit). Until a measure of the same `content` says
+ * otherwise, it is the result, so the first open already renders the right
+ * class: a class that flips after the open measure restyles the whole list
+ * a second time. A measure still runs on every open and corrects a wrong
+ * guess.
+ */
export function useMenuOverflow(
menuRef: RefObject<HTMLElement | null>,
content: ReactNode,
isOpen: boolean,
+ expectedOverflow?: boolean,
): boolean {
- const [hasOverflow, setHasOverflow] = useState(false);
+ // The content each measure stands for, kept only for an owner that gives
+ // an expected answer (a caller whose content is a new element on every
+ // render compares nothing); set before the measuring effects run.
+ const contentRef = useRef<ReactNode>(null);
+ useIsomorphicLayoutEffect(() => {
+ contentRef.current = expectedOverflow === undefined ? null : content;
+ });
+ const [measured, setMeasured] = useState<{
+ content: ReactNode;
+ hasOverflow: boolean;
+ } | null>(null);
const measureOverflow = useCallback(() => {
const menu = menuRef.current;
if (!menu) {
return;
}
- const nextHasOverflow = menu.scrollHeight > menu.clientHeight + 1;
+ const hasOverflow = menu.scrollHeight > menu.clientHeight + 1;
// eslint-disable-next-line @eslint-react/set-state-in-effect -- DOM overflow measurement controls whether this menu becomes a scroll container
- setHasOverflow(current =>
- current === nextHasOverflow ? current : nextHasOverflow,
+ setMeasured(current =>
+ current != null &&
+ current.hasOverflow === hasOverflow &&
+ Object.is(current.content, contentRef.current)
+ ? current
+ : {content: contentRef.current, hasOverflow},
);
}, [menuRef]);
@@ -73,5 +104,10 @@ export function useMenuOverflow(
}
}, [content, isOpen, measureOverflow]);
- return hasOverflow;
+ if (expectedOverflow === undefined) {
+ return measured?.hasOverflow ?? false;
+ }
+ return measured != null && Object.is(measured.content, content)
+ ? measured.hasOverflow
+ : expectedOverflow;
}
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index a50e946c1b..943eef22a0 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -5153,6 +5153,71 @@ describe('Selector press model', () => {
expect(listbox).not.toHaveClass(hash(touchStyles.panYPinchZoom));
});
+ 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}`);
+ const touchStyles = stylex.create({
+ pinchZoom: {touchAction: 'pinch-zoom'},
+ panYPinchZoom: {touchAction: 'pan-y pinch-zoom'},
+ });
+ const hash = (style: stylex.StyleXStyles) =>
+ stylex.props(style).className!.split(' ').pop()!;
+ // A 249-row list overflows its 300 px box.
+ Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
+ configurable: true,
+ get() {
+ return (this as HTMLElement).getAttribute('role') === 'listbox'
+ ? 7968
+ : 0;
+ },
+ });
+ Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
+ configurable: true,
+ get() {
+ return (this as HTMLElement).getAttribute('role') === 'listbox'
+ ? 300
+ : 0;
+ },
+ });
+ try {
+ render(<Selector label="Country" options={many} onChange={() => {}} />);
+ const listbox = screen.getByRole('listbox', h);
+ // The class is already the scrolling one while closed, so the open
+ // never swaps it (a swap restyles every row a second time).
+ expect(listbox).toHaveClass(hash(touchStyles.panYPinchZoom));
+ const swaps: string[] = [];
+ const observer = new MutationObserver(() => {
+ if (listbox.classList.contains(hash(touchStyles.pinchZoom))) {
+ swaps.push(listbox.className);
+ }
+ });
+ observer.observe(listbox, {attributes: true, attributeFilter: ['class']});
+ await user.click(screen.getByRole('combobox'));
+ observer.disconnect();
+ expect(swaps).toEqual([]);
+ expect(listbox).toHaveClass(hash(touchStyles.panYPinchZoom));
+ } finally {
+ // jsdom defines both on Element.prototype; drop the overrides.
+ delete (HTMLElement.prototype as {scrollHeight?: number}).scrollHeight;
+ delete (HTMLElement.prototype as {clientHeight?: number}).clientHeight;
+ }
+ });
+
+ it('a list guessed long that fits after the open measure gets the fitting touch-action', async () => {
+ const user = userEvent.setup();
+ const many = Array.from({length: 20}, (_, i) => `Option ${i}`);
+ render(<Selector label="Country" options={many} onChange={() => {}} />);
+ await user.click(screen.getByRole('combobox'));
+ const touchStyles = stylex.create({
+ pinchZoom: {touchAction: 'pinch-zoom'},
+ });
+ // jsdom measures every element at 0 px, so the measure says it fits and
+ // corrects the guess.
+ expect(screen.getByRole('listbox', h)).toHaveClass(
+ stylex.props(touchStyles.pinchZoom).className!.split(' ').pop()!,
+ );
+ });
+
it('marks the listbox as carrying the press model', async () => {
const user = userEvent.setup();
render(<Selector label="Fruit" options={OPTIONS} onChange={() => {}} />);
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 26c52b0825..78e00f7d90 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -113,6 +113,14 @@ import english from '../i18n/generated-english/Selector/Selector.generated';
registerEnglishFallback(english);
+/**
+ * A guess, confirmed by the open measure: more options than this overflow
+ * the popover listbox's 300 px block size even at 24 px rows, under the
+ * smallest default row (28 px). A wrong guess (a theme with shorter rows, a
+ * taller bottom sheet) costs only the measure's correction.
+ */
+const MOST_ROWS_THAT_FIT = 12;
+
const styles = stylex.create({
// Trigger container — the enhanced click target wrapping the combobox button and clear button as siblings
triggerContainer: {
@@ -1407,10 +1415,13 @@ export function Selector<T extends SelectorOptionType>(
return match == null ? -1 : Number(match[1]);
}, []);
// Re-measured when the option set changes; the count is the dependency.
+ // A list longer than the most rows that can fit cannot fit, so it starts
+ // as a scroll container and the open measure only confirms it.
const listboxHasOverflow = useMenuOverflow(
listboxRef,
filteredItems.length,
surface.isOpen,
+ filteredItems.length > MOST_ROWS_THAT_FIT,
);
const listboxPress = useMenuPress({
menuRef: listboxRef,