Skip to content

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

TypeScript

fix: runaway auto-scroll loop in hover-highlighted menus (#6078)

fagaae4ad8375d1c
diff --git a/.changeset/hover-highlight-no-autoscroll-option-lists.md b/.changeset/hover-highlight-no-autoscroll-option-lists.md
new file mode 100644
index 0000000000..8dc4f9ef3d
--- /dev/null
+++ b/.changeset/hover-highlight-no-autoscroll-option-lists.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Keep hover from auto-scrolling open option lists (#6077)
+
+In a scrollable listbox whose highlight follows the pointer, scrolling the highlighted option into view moved the next option under the stationary pointer, whose mouseenter re-highlighted and scrolled again — an endless loop with no user input. This was already fixed for DropdownMenu and Chat; it now covers the remaining combobox-style paths through a shared highlight owner: Selector, MultiSelector, Typeahead, DateTimeInput, and CommandPalette hover highlights move only the highlight, while keyboard navigation still scrolls the highlighted option into view.
+
+@faga295
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index d5c4cb276a..f6c5c31ded 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -21,6 +21,20 @@
"next": "[role=\"group\"] button:last-child"
}
},
+ {
+ "component": "CommandPalette",
+ "storyId": "core-commandpalette--default",
+ "dims": [
+ "D2"
+ ],
+ "setup": {
+ "click": "button:has-text(\"Open Command Palette\")"
+ },
+ "selectors": {
+ "prev": ".astryx-command-palette-input > span:first-child",
+ "next": ".astryx-command-palette-input > input[role=\"combobox\"]"
+ }
+ },
{
"component": "CheckboxInput",
"storyId": "core-checkboxinput--size-comparison",
diff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsx
index d7ec37ed22..4a02e92886 100644
--- a/packages/core/src/Chat/ChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect, vi, afterEach} from 'vitest';
-import {render, screen, fireEvent} from '@testing-library/react';
+import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {ChatComposer} from './ChatComposer';
import {useChatComposerContext} from './ChatContext';
@@ -1395,4 +1395,77 @@ describe('ChatComposerInput', () => {
expect(textbox.getAttribute('aria-expanded')).toBe('true');
});
});
+
+ describe('trigger menu hover scrolling', () => {
+ // Regression: the scroll-highlighted-item-into-view effect ran for
+ // mouse-hover highlights too. A pointer resting near the bottom of the
+ // menu kept scrolling: each scrollIntoView moved a new option under the
+ // stationary cursor, whose mouseenter re-highlighted and scrolled again.
+ // Hover must highlight only; keyboard navigation keeps its scrolling.
+ function openMenu() {
+ // jsdom does not implement scrollIntoView — install a spy directly.
+ const original = Element.prototype.scrollIntoView;
+ const spy = vi.fn();
+ Element.prototype.scrollIntoView = spy;
+ cleanupFns.push(() => {
+ Element.prototype.scrollIntoView = original;
+ });
+ render(<ChatComposerInput triggers={[createMentionTrigger()]} />);
+ const textbox = screen.getByRole('combobox');
+ textbox.focus();
+ const textNode = document.createTextNode('@');
+ textbox.appendChild(textNode);
+ const sel = window.getSelection()!;
+ const range = document.createRange();
+ range.setStart(textNode, 1);
+ range.collapse(true);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ fireEvent.input(textbox);
+ expect(textbox.getAttribute('aria-expanded')).toBe('true');
+ return {textbox, spy};
+ }
+
+ // The menu layer is a `[popover]` element; jsdom has no popover semantics
+ // so testing-library's role queries see it as hidden. Query via
+ // aria-controls instead.
+ async function getMenuOptions(textbox: HTMLElement) {
+ const listbox = await waitFor(() => {
+ const el = document.getElementById(
+ textbox.getAttribute('aria-controls')!,
+ );
+ const options = el?.querySelectorAll<HTMLElement>('[role="option"]');
+ expect(options?.length ?? 0).toBeGreaterThan(1);
+ return options!;
+ });
+ return Array.from(listbox);
+ }
+
+ const cleanupFns: (() => void)[] = [];
+
+ afterEach(() => {
+ cleanupFns.splice(0).forEach(fn => fn());
+ });
+
+ it('does not scroll when hover highlights an option', async () => {
+ const {textbox, spy} = openMenu();
+ const callsAfterOpen = spy.mock.calls.length;
+
+ const options = await getMenuOptions(textbox);
+ fireEvent.mouseEnter(options[1]);
+
+ expect(options[1]).toHaveAttribute('aria-selected', 'true');
+ expect(spy.mock.calls.length).toBe(callsAfterOpen);
+ });
+
+ it('still scrolls on keyboard navigation', async () => {
+ const {textbox, spy} = openMenu();
+ const callsAfterOpen = spy.mock.calls.length;
+
+ await getMenuOptions(textbox);
+ fireEvent.keyDown(textbox, {key: 'ArrowDown'});
+
+ expect(spy.mock.calls.length).toBeGreaterThan(callsAfterOpen);
+ });
+ });
});
diff --git a/packages/core/src/Chat/useTriggerMenu.tsx b/packages/core/src/Chat/useTriggerMenu.tsx
index b27c362821..764be45b3a 100644
--- a/packages/core/src/Chat/useTriggerMenu.tsx
+++ b/packages/core/src/Chat/useTriggerMenu.tsx
@@ -30,6 +30,7 @@ import {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import {usePopover} from '../Popover/usePopover';
+import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import {
colorVars,
spacingVars,
@@ -597,14 +598,15 @@ export function useTriggerMenu(
[listboxId],
);
- // Scroll highlighted item into view on keyboard navigation
- useEffect(() => {
- if (!popover.isOpen || state.highlightedIndex < 0) {
- return;
- }
- const el = document.getElementById(getItemId(state.highlightedIndex));
- el?.scrollIntoView({block: 'nearest'});
- }, [state.highlightedIndex, popover.isOpen, getItemId]);
+ // Keep the highlighted option visible during keyboard navigation; hover
+ // highlights never scroll (#6077). Both sides live in useHighlightedOptionScroll.
+ const highlightOnHover = useHighlightedOptionScroll({
+ isOpen: popover.isOpen,
+ highlightedIndex: state.highlightedIndex,
+ setHighlightedIndex: index =>
+ setState(prev => ({...prev, highlightedIndex: index})),
+ getOptionId: getItemId,
+ });
// ARIA props for the editable element. Of the attributes the trigger menu
// needs, only aria-expanded forces the role: aria-controls and
@@ -666,9 +668,7 @@ export function useTriggerMenu(
e.preventDefault(); // Keep focus in the editable
selectItem(item);
}}
- onMouseEnter={() =>
- setState(prev => ({...prev, highlightedIndex: idx}))
- }
+ onMouseEnter={() => highlightOnHover(idx)}
{...stylex.props(
styles.item,
idx === state.highlightedIndex && styles.itemHighlighted,
@@ -718,7 +718,7 @@ export function useTriggerMenu(
xstyle: styles.popoverSurface,
},
);
- }, [popover, listboxId, state, selectItem, getItemId, t]);
+ }, [popover, listboxId, state, selectItem, getItemId, highlightOnHover, t]);
return {
state,
diff --git a/packages/core/src/CommandPalette/CommandPalette.perf.test.ts b/packages/core/src/CommandPalette/CommandPalette.perf.test.ts
new file mode 100644
index 0000000000..8472cd16e9
--- /dev/null
+++ b/packages/core/src/CommandPalette/CommandPalette.perf.test.ts
@@ -0,0 +1,96 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {createElement} from 'react';
+import {fireEvent, render, waitFor} from '@testing-library/react';
+import {beforeEach, describe, expect, it, vi} from 'vitest';
+import {createStaticSource} from '@astryxdesign/core/Typeahead';
+import {CommandPalette} from './CommandPalette';
+import type * as ListModule from './CommandPaletteList';
+import type {CommandPaletteListProps} from './CommandPaletteList';
+
+const lookupWork = vi.hoisted(() => ({reads: [] as number[]}));
+
+vi.mock('./CommandPaletteList', async importOriginal => {
+ const actual = await importOriginal<typeof ListModule>();
+ const {useCommandPaletteContext} = await import('./CommandPaletteContext');
+ return {
+ ...actual,
+ CommandPaletteList: function ObservedList(props: CommandPaletteListProps) {
+ const ctx = useCommandPaletteContext();
+ return createElement(actual.CommandPaletteList, {
+ ...props,
+ onMouseOver(event) {
+ // Observe the real handler's input, not a particular array method.
+ // Install after index construction and restore before React renders:
+ // this measures lookup work, not setup or option rendering.
+ let reads = 0;
+ const restorers = (ctx?.selectableItems ?? []).map(item => {
+ const descriptor = Object.getOwnPropertyDescriptor(item, 'value')!;
+ Object.defineProperty(item, 'value', {
+ configurable: true,
+ get(): string {
+ reads++;
+ return descriptor.value;
+ },
+ });
+ return () => Object.defineProperty(item, 'value', descriptor);
+ });
+ try {
+ props.onMouseOver?.(event);
+ } finally {
+ restorers.forEach(restore => restore());
+ lookupWork.reads.push(reads);
+ }
+ },
+ });
+ },
+ };
+});
+
+beforeEach(() => {
+ lookupWork.reads = [];
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+});
+
+describe('CommandPalette delegated mouseover performance', () => {
+ it.each([50, 500])('bounds lookup work with %i items', async count => {
+ const items = Array.from({length: count}, (_, index) => ({
+ id: `item-${index}`,
+ label: `Item ${index}`,
+ }));
+ const view = render(
+ createElement(CommandPalette, {
+ isOpen: true,
+ onOpenChange: () => {},
+ searchSource: createStaticSource(items),
+ }),
+ );
+ try {
+ await waitFor(() =>
+ expect(view.getAllByRole('option')).toHaveLength(count),
+ );
+ const options = view.getAllByRole('option');
+ const targets = [0, count - 1, Math.floor(count / 2), 0];
+ for (const index of targets) {
+ const option = options[index];
+ fireEvent.mouseOver(option);
+ expect(view.getByRole('combobox')).toHaveAttribute(
+ 'aria-activedescendant',
+ option.id,
+ );
+ }
+ expect(lookupWork.reads).toHaveLength(targets.length);
+ for (const reads of lookupWork.reads) {
+ // A direct lookup may inspect the matched value, but must not scan
+ // the list. The same fixed budget applies at both list sizes.
+ expect(reads).toBeLessThanOrEqual(1);
+ }
+ } finally {
+ view.unmount();
+ }
+ });
+});
diff --git a/packages/core/src/CommandPalette/CommandPalette.test.tsx b/packages/core/src/CommandPalette/CommandPalette.test.tsx
index 68951e9e4a..b317092b77 100644
--- a/packages/core/src/CommandPalette/CommandPalette.test.tsx
+++ b/packages/core/src/CommandPalette/CommandPalette.test.tsx
@@ -357,6 +357,66 @@ describe('CommandPalette', () => {
expect(input).not.toHaveAttribute('aria-activedescendant');
});
+ it('highlights on hover without scrolling and scrolls once per key (#6077)', async () => {
+ // Hover must be handled by the root's delegated list handler (routed to
+ // useCombobox's hover-aware path), and the shared useHighlightedOptionScroll effect
+ // must be the single keyboard scroll owner. Calling the raw setter on
+ // hover kept the stationary-pointer runaway path alive, and the item's
+ // own scrollIntoView effect doubled every scroll call.
+ const scrollIntoView = vi.fn();
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: scrollIntoView,
+ });
+ try {
+ render(
+ <CommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ await waitFor(() => expect(screen.getByText('Home')).toBeInTheDocument());
+ const home = screen.getByText('Home');
+ const settings = screen.getByText('Settings');
+
+ fireEvent.mouseOver(home);
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ expect(input.getAttribute('aria-activedescendant')).toBe(
+ home.closest('[role="option"]')?.id,
+ );
+
+ // Moving between siblings does not re-enter the list container. Include
+ // relatedTarget so the test exercises actual within-list transitions.
+ fireEvent.mouseOut(home, {relatedTarget: settings});
+ fireEvent.mouseOver(settings, {relatedTarget: home});
+ expect(input.getAttribute('aria-activedescendant')).toBe(
+ settings.closest('[role="option"]')?.id,
+ );
+ expect(scrollIntoView).not.toHaveBeenCalled();
+
+ fireEvent.mouseOut(settings, {relatedTarget: home});
+ fireEvent.mouseOver(home, {relatedTarget: settings});
+ expect(input.getAttribute('aria-activedescendant')).toBe(
+ home.closest('[role="option"]')?.id,
+ );
+ expect(scrollIntoView).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(1));
+ expect(input.getAttribute('aria-activedescendant')).toBe(
+ settings.closest('[role="option"]')?.id,
+ );
+
+ fireEvent.keyDown(input, {key: 'ArrowUp'});
+ await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(2));
+ } finally {
+ delete (HTMLElement.prototype as unknown as {scrollIntoView?: unknown})
+ .scrollIntoView;
+ }
+ });
+
describe('screen reader announcements', () => {
const politeRegion = () =>
document.querySelector('[data-astryx-live-region="polite"]');
diff --git a/packages/core/src/CommandPalette/CommandPalette.tsx b/packages/core/src/CommandPalette/CommandPalette.tsx
index 87371fd1cc..d2468af8a5 100644
--- a/packages/core/src/CommandPalette/CommandPalette.tsx
+++ b/packages/core/src/CommandPalette/CommandPalette.tsx
@@ -170,6 +170,26 @@ function buildSelectableItems(items: SearchableItem[]): SelectorOptionData[] {
return result;
}
+/**
+ * O(1) value → index lookup over selectable items, used by the delegated
+ * mouseover handler (#6077). The index is built once per results change;
+ * each hover then pays a Map probe instead of a linear findIndex scan,
+ * so cost no longer scales with list size. Keeps the first occurrence of
+ * duplicate values to match the previous findIndex behavior.
+ */
+function createValueLookup<T extends {value: string}>(
+ items: ReadonlyArray<T>,
+): (value: string) => number | undefined {
+ const indexByValue = new Map<string, number>();
+ for (let i = 0; i < items.length; i++) {
+ const value = items[i].value;
+ if (!indexByValue.has(value)) {
+ indexByValue.set(value, i);
+ }
+ }
+ return value => indexByValue.get(value);
+}
+
interface RendererProps<T extends SearchableItem> {
items: T[];
value: string;
@@ -318,6 +338,11 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({
[optimisticResults],
);
+ const valueLookup = useMemo(
+ () => createValueLookup(selectableItems),
+ [selectableItems],
+ );
+
const handleClose = useCallback(() => {
// Invalidate any in-flight search. Most sources don't implement cancel(),
// and a response that resolves after close would still pass runSearch's
@@ -421,11 +446,25 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({
// When opening with a preselected value, highlight it once
// bootstrap results arrive. No value → highlight stays at -1
- // and ArrowDown naturally moves to the first item.
+ // and ArrowDown naturally moves to the first item. Inline previews
+ // take the hover-aware path so the initial highlight does not
+ // scrollIntoView the surrounding page (#6077).
if (isBootstrap && value != null && value !== '') {
const selectedIdx = items.findIndex(item => item.id === value);
if (selectedIdx >= 0) {
- combobox.setHighlightedIndex(selectedIdx);
+ if (isInline) {
+ // `items` is the fresh bootstrap result; the closure's
+ // selectableItems may still be empty at commit time.
+ const selectedItem = items[selectedIdx];
+ if (selectedItem) {
+ combobox.onItemMouseEnter(
+ {value: selectedItem.id},
+ selectedIdx,
+ );
+ }
+ } else {
+ combobox.setHighlightedIndex(selectedIdx);
+ }
}
}
}
@@ -436,6 +475,7 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({
searchResults,
startTransition,
value,
+ isInline,
combobox,
setOptimisticResults,
announce,
@@ -487,6 +527,32 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({
[combobox, handleClose, selectableItems, selectItem],
);
+ // Hover highlight is owned here by a single delegated handler on the list
+ // container: it routes to useCombobox's hover-aware path, which moves the
+ // highlight without scrolling (#6077) — a stationary pointer cannot
+ // re-highlight and auto-scroll in a runaway loop. Keeping it off the public
+ // context preserves CommandPaletteContextValue's setHighlightedIndex shape;
+ // disabled items are skipped via aria-disabled (selectableItems carries no
+ // disabled info). Use mouseover so moves between options bubble to the list;
+ // mouseenter only runs when the pointer enters the list from outside.
+ const handleListMouseOver = useCallback(
+ (e: React.MouseEvent) => {
+ const option = (e.target as HTMLElement).closest?.('[role="option"]');
+ if (!option || option.getAttribute('aria-disabled') === 'true') {
+ return;
+ }
+ const itemValue = option.getAttribute('data-value');
+ if (itemValue == null) {
+ return;
+ }
+ const index = valueLookup(itemValue);
+ if (index !== undefined) {
+ combobox.onItemMouseEnter(selectableItems[index], index);
+ }
+ },
+ [combobox, selectableItems, valueLookup],
+ );
+
const contextValue = useMemo(
() => ({
// Input uses optimisticSearch — reflects keystrokes immediately.
@@ -584,7 +650,9 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({
}
content={
<LayoutContent padding={0}>
- <CommandPaletteList>{listContent}</CommandPaletteList>
+ <CommandPaletteList onMouseOver={handleListMouseOver}>
+ {listContent}
+ </CommandPaletteList>
</LayoutContent>
}
footer={
diff --git a/packages/core/src/CommandPalette/CommandPaletteItem.tsx b/packages/core/src/CommandPalette/CommandPaletteItem.tsx
index facb3c6420..7d615f4101 100644
--- a/packages/core/src/CommandPalette/CommandPaletteItem.tsx
+++ b/packages/core/src/CommandPalette/CommandPaletteItem.tsx
@@ -146,6 +146,14 @@ export function CommandPaletteItem({
const isSelected = controlledSelected ?? (ctx ? ctx.value === value : false);
useEffect(() => {
+ // Inside CommandPalette the shared useHighlightedOptionScroll (via
+ // useCombobox) is the single scrollIntoView owner (#6077); a second owner
+ // here doubled every keyboard scroll and scrolled on hover. Standalone
+ // items (no context) keep their own scroll.
+ if (ctx) {
+ return;
+ }
+
// Inline dialogs are documentation/showcase previews. Avoid scrolling the
// surrounding page when picker mode auto-highlights its selected item on
// mount, while preserving scroll-into-view after user navigation.
@@ -160,7 +168,7 @@ export function CommandPaletteItem({
if (isHighlighted && itemRef.current) {
itemRef.current.scrollIntoView?.({block: 'nearest'});
}
- }, [isHighlighted, isInlineDialog]);
+ }, [ctx, isHighlighted, isInlineDialog]);
const handleClick = useCallback(() => {
if (isDisabled) {
@@ -173,13 +181,6 @@ export function CommandPaletteItem({
}
}, [isDisabled, value, onSelect, ctx]);
- const handleMouseEnter = useCallback(() => {
- if (isDisabled || !ctx || itemIndex < 0) {
- return;
- }
- ctx.setHighlightedIndex(itemIndex);
- }, [isDisabled, itemIndex, ctx]);
-
return (
<div
ref={useMergedRefs(ref, itemRef)}
@@ -190,7 +191,7 @@ export function CommandPaletteItem({
aria-disabled={isDisabled || undefined}
data-value={value}
onClick={composeEventHandlers(onClickProp, handleClick)}
- onMouseEnter={composeEventHandlers(onMouseEnterProp, handleMouseEnter)}
+ onMouseEnter={onMouseEnterProp}
{...mergeProps(
themeProps('command-palette-item'),
stylex.props(
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
index 1e6e13efc2..10aef5f964 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
@@ -1387,6 +1387,47 @@ describe('DateTimeInput', () => {
expect(listbox).toHaveAttribute('aria-label');
});
+ it('highlights on hover without scrolling, keyboard still scrolls (#6077)', () => {
+ // Hover must highlight only: scrollIntoView under a stationary pointer
+ // moves the next option under it, re-highlighting and scrolling again —
+ // a runaway auto-scroll loop with no user input.
+ const scrollIntoView = vi.fn();
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: scrollIntoView,
+ });
+ try {
+ const {container} = render(
+ <DateTimeInput
+ label="Meeting"
+ value={'2026-03-15T14:00' as ISODateTimeString}
+ timeOptionInterval={60}
+ onChange={() => {}}
+ />,
+ );
+
+ const timeInput = screen.getByLabelText('Meeting time');
+ fireEvent.click(timeInput);
+ scrollIntoView.mockClear();
+
+ const options = container
+ .querySelector('[role="listbox"]')!
+ .querySelectorAll('[role="option"]');
+ fireEvent.mouseEnter(options[5]);
+
+ expect(timeInput.getAttribute('aria-activedescendant')).toBe(
+ options[5].id,
+ );
+ expect(scrollIntoView).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(timeInput, {key: 'ArrowDown'});
+ expect(scrollIntoView).toHaveBeenCalledWith({block: 'nearest'});
+ } finally {
+ delete (HTMLElement.prototype as unknown as {scrollIntoView?: unknown})
+ .scrollIntoView;
+ }
+ });
+
it('does not open the list when disabled', () => {
render(
<DateTimeInput
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsx
index 71669b3139..9d2c0fe9f5 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx
@@ -98,6 +98,7 @@ import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {useLocale, useTranslator} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import {NativeDateSegment} from './NativeDateSegment';
import {NativeTimeSegment} from './NativeTimeSegment';
import {TouchDateTimeField} from './TouchDateTimeField';
@@ -1145,22 +1146,15 @@ function PointerDateTimeField({
? timeOptions.length - 1
: highlightedTimeIndex;
- // Keep the active option visible. The listbox is a fixed-height scroll
- // container, so without this a list opens at midnight with the highlight far
- // below the fold, and keyboard navigation walks off-screen. Mirrors
- // BaseTypeahead's scrollIntoView({block: 'nearest'}).
- useEffect(() => {
- if (
- !timePopover.isOpen ||
- activeTimeIndex < 0 ||
- activeTimeIndex >= timeOptions.length
- ) {
- return;
- }
- document
- .getElementById(timeOptionId(activeTimeIndex))
- ?.scrollIntoView?.({block: 'nearest'});
- }, [timePopover.isOpen, activeTimeIndex, timeOptionId, timeOptions.length]);
+ // Keep the active option visible; hover highlights never scroll (#6077).
+ // Both sides live in useHighlightedOptionScroll.
+ const highlightTimeOnHover = useHighlightedOptionScroll({
+ isOpen: timePopover.isOpen,
+ highlightedIndex: activeTimeIndex,
+ setHighlightedIndex: setHighlightedTimeIndex,
+ getOptionId: timeOptionId,
+ itemCount: timeOptions.length,
+ });
/**
* The selected time in the same shape the options carry. splitDateTime slices
@@ -1881,7 +1875,7 @@ function PointerDateTimeField({
// option, or blur would fire its own commit first.
onPointerDown={e => e.preventDefault()}
onClick={() => commitTimeOption(option.time)}
- onMouseEnter={() => setHighlightedTimeIndex(index)}
+ onMouseEnter={() => highlightTimeOnHover(index)}
{...mergeProps(
themeProps('date-time-input-time-option'),
stylex.props(
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 595dadcb34..127aef0f06 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -1870,9 +1870,14 @@ describe('DropdownMenu keyboard access for menuitemradio/menuitemcheckbox (#3829
// A mouse hover over another item moves focus to it, so the single
// focus-driven highlight follows the pointer instead of leaving two.
+ // Focus must be scroll-free: scrolling the focused item into view moves
+ // the next item under the stationary pointer, which re-highlights and
+ // scrolls again — a runaway auto-scroll loop.
+ const focusSpy = vi.spyOn(del, 'focus');
fireEvent.pointerMove(del, {pointerType: 'mouse'});
expect(del).toHaveFocus();
expect(edit).not.toHaveFocus();
+ expect(focusSpy).toHaveBeenCalledWith({preventScroll: true});
});
it('does not move focus on hover for a disabled item', async () => {
diff --git a/packages/core/src/DropdownMenu/menuItemHover.ts b/packages/core/src/DropdownMenu/menuItemHover.ts
index 1a70f43f6e..bfe6c84dd7 100644
--- a/packages/core/src/DropdownMenu/menuItemHover.ts
+++ b/packages/core/src/DropdownMenu/menuItemHover.ts
@@ -35,6 +35,10 @@ export function focusMenuItemOnHover(
}
const el = e.currentTarget;
if (el !== el.ownerDocument.activeElement) {
- el.focus();
+ // preventScroll: focusing an off-screen item scrolls it under the
+ // stationary pointer, whose next pointerenter focuses it again — a
+ // runaway auto-scroll loop. Keyboard navigation scrolls via its own
+ // highlight handling; hover must never scroll.
+ el.focus({preventScroll: true});
}
}
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index f232d8c4db..fd9c68bcae 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -1574,6 +1574,50 @@ describe('MultiSelector', () => {
}
});
+ it('highlights on hover without scrolling, keyboard still scrolls (#6077)', async () => {
+ // Hover must highlight only: scrollIntoView under a stationary pointer
+ // moves the next option under it, re-highlighting and scrolling again —
+ // a runaway auto-scroll loop with no user input.
+ const scrollIntoView = vi.fn();
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: scrollIntoView,
+ });
+ try {
+ const user = userEvent.setup();
+ const longOptions = Array.from(
+ {length: 20},
+ (_, i) => `Option ${i + 1}`,
+ );
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={longOptions}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+
+ const trigger = screen.getByRole('combobox');
+ await user.click(trigger);
+ scrollIntoView.mockClear();
+
+ const options = screen.getAllByRole('option', {hidden: true});
+ fireEvent.mouseEnter(options[3]);
+
+ expect(trigger.getAttribute('aria-activedescendant')).toBe(
+ options[3].id,
+ );
+ expect(scrollIntoView).not.toHaveBeenCalled();
+
+ await user.keyboard('{ArrowDown}');
+ expect(scrollIntoView).toHaveBeenCalledWith({block: 'nearest'});
+ } finally {
+ delete (HTMLElement.prototype as unknown as {scrollIntoView?: unknown})
+ .scrollIntoView;
+ }
+ });
+
it('clears all values via Delete on the focused trigger', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 091772a5f8..42c4be9722 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -1241,18 +1241,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
listboxId,
});
- // Keep the highlighted option visible during keyboard navigation. The
- // listbox is a fixed-height scroll container, so without this the virtual
- // cursor walks off-screen once navigation passes the visible window. Mirrors
- // CommandPaletteItem's scrollIntoView({block: 'nearest'}) behavior.
- useEffect(() => {
- if (!surface.isOpen || highlightedIndex < 0) {
- return;
- }
- document
- .getElementById(getItemId(highlightedIndex))
- ?.scrollIntoView?.({block: 'nearest'});
- }, [surface.isOpen, highlightedIndex, getItemId]);
+ // Highlight scrolling (and its hover/keyboard split) lives in useMultiCombobox.
// Build trigger display content
const selectedItems = useMemo(() => {
diff --git a/packages/core/src/MultiSelector/hooks.ts b/packages/core/src/MultiSelector/hooks.ts
index fe6a2c97d3..ea24b938da 100644
--- a/packages/core/src/MultiSelector/hooks.ts
+++ b/packages/core/src/MultiSelector/hooks.ts
@@ -13,6 +13,7 @@
*/
import {useCallback, useRef, useState} from 'react';
+import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import type {MultiSelectorOptionData} from './types';
interface UseMultiComboboxOptions {
@@ -100,13 +101,22 @@ export function useMultiCombobox({
}
}, [isDisabled, isOpen, onOpen, closeAndReset, hasSearch]);
+ // The scroll effect lives here, the highlight owner, so the hover/keyboard
+ // split is shared instead of re-implemented in MultiSelector.tsx (#6077).
+ const highlightOnHover = useHighlightedOptionScroll({
+ isOpen,
+ highlightedIndex,
+ setHighlightedIndex,
+ getOptionId: getItemId,
+ });
+
const onItemMouseEnter = useCallback(
(item: MultiSelectorOptionData, index: number) => {
if (!item.disabled) {
- setHighlightedIndex(index);
+ highlightOnHover(index);
}
},
- [],
+ [highlightOnHover],
);
const onKeyDown = useCallback(
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index a808a82ff5..2c7ce2c347 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -1728,6 +1728,44 @@ describe('Selector', () => {
.scrollIntoView;
}
});
+
+ it('highlights on hover without scrolling, keyboard still scrolls (#6077)', async () => {
+ // Hover must highlight only: scrollIntoView under a stationary pointer
+ // moves the next option under it, re-highlighting and scrolling again —
+ // a runaway auto-scroll loop with no user input.
+ const scrollIntoView = vi.fn();
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: scrollIntoView,
+ });
+ try {
+ const user = userEvent.setup();
+ const longOptions = Array.from(
+ {length: 20},
+ (_, i) => `Option ${i + 1}`,
+ );
+ render(<Selector label="Fruit" options={longOptions} />);
+
+ await user.tab();
+ await user.keyboard('{Enter}'); // open
+ scrollIntoView.mockClear();
+
+ const options = screen.getAllByRole('option', {hidden: true});
+ fireEvent.mouseEnter(options[3]);
+
+ const trigger = screen.getByRole('combobox');
+ expect(trigger.getAttribute('aria-activedescendant')).toBe(
+ options[3].id,
+ );
+ expect(scrollIntoView).not.toHaveBeenCalled();
+
+ await user.keyboard('{ArrowDown}');
+ expect(scrollIntoView).toHaveBeenCalledWith({block: 'nearest'});
+ } finally {
+ delete (HTMLElement.prototype as unknown as {scrollIntoView?: unknown})
+ .scrollIntoView;
+ }
+ });
});
describe('typeahead', () => {
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index b7dc04aa42..4e2895140f 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -1247,18 +1247,7 @@ export function Selector<T extends SelectorOptionType>(
[isDisabled, isEffectivelyReadOnly, hasSearch, typeahead, onKeyDown],
);
- // Keep the highlighted option visible during keyboard navigation. The
- // listbox is a fixed-height scroll container, so without this the virtual
- // cursor walks off-screen once navigation passes the visible window. Mirrors
- // CommandPaletteItem's scrollIntoView({block: 'nearest'}) behavior.
- useEffect(() => {
- if (!surface.isOpen || highlightedIndex < 0) {
- return;
- }
- document
- .getElementById(getItemId(highlightedIndex))
- ?.scrollIntoView?.({block: 'nearest'});
- }, [surface.isOpen, highlightedIndex, getItemId]);
+ // Highlight scrolling (and its hover/keyboard split) lives in useCombobox.
// Handle clear button click
const handleClear = useCallback(
diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.ts
index 4ba16b95d6..1ead885c6a 100644
--- a/packages/core/src/Selector/hooks.ts
+++ b/packages/core/src/Selector/hooks.ts
@@ -11,6 +11,7 @@
*/
import {useCallback, useState} from 'react';
+import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import type {RefObject} from 'react';
import type {SelectorOptionData} from './types';
@@ -258,13 +259,22 @@ export function useCombobox({
}
}, [isDisabled, isOpen, onOpen, closeAndReset, findSelectedIndex, hasSearch]);
+ // The scroll effect lives here, the highlight owner, so every consumer
+ // (Selector, CommandPalette) shares one hover/keyboard split (#6077).
+ const highlightOnHover = useHighlightedOptionScroll({
+ isOpen,
+ highlightedIndex,
+ setHighlightedIndex,
+ getOptionId: getItemId,
+ });
+
const onItemMouseEnter = useCallback(
(item: SelectorOptionData, index: number) => {
if (!item.disabled) {
- setHighlightedIndex(index);
+ highlightOnHover(index);
}
},
- [],
+ [highlightOnHover],
);
const onKeyDown = useCallback(
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index cb0741ceff..b7099461d4 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -31,6 +31,7 @@ import {useBusyIndicatorLane} from './busyIndicatorLane';
import type {StyleXStyles} from '@stylexjs/stylex';
import {usePopover} from '../Popover/usePopover';
import {useAnnounce} from '../hooks/useAnnounce';
+import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {isImeKeyEvent} from '../utils/ime';
import {TypeaheadItem} from './TypeaheadItem';
@@ -916,22 +917,15 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
[listboxId],
);
- // Keep the highlighted option visible during keyboard navigation. The
- // listbox is a fixed-height scroll container, so without this the virtual
- // cursor walks off-screen once navigation passes the visible window. Mirrors
- // CommandPaletteItem's scrollIntoView({block: 'nearest'}) behavior.
- useEffect(() => {
- if (
- !popover.isOpen ||
- highlightedIndex < 0 ||
- highlightedIndex >= results.length
- ) {
- return;
- }
- document
- .getElementById(getItemId(highlightedIndex))
- ?.scrollIntoView?.({block: 'nearest'});
- }, [popover.isOpen, highlightedIndex, getItemId, results.length]);
+ // Keep the highlighted option visible during keyboard navigation; hover
+ // highlights never scroll (#6077). Both sides live in useHighlightedOptionScroll.
+ const highlightOnHover = useHighlightedOptionScroll({
+ isOpen: popover.isOpen,
+ highlightedIndex,
+ setHighlightedIndex,
+ getOptionId: getItemId,
+ itemCount: results.length,
+ });
const selectedKey =
value == null ? null : getKey(value.id, () => results.indexOf(value));
@@ -1035,7 +1029,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
aria-selected={isSelected}
tabIndex={-1}
onClick={() => handleSelect(item)}
- onMouseEnter={() => setHighlightedIndex(index)}
+ onMouseEnter={() => highlightOnHover(index)}
{...stylex.props(
styles.item,
itemSizeStyles[size],
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index c66e942a77..62c0327b2b 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -1376,6 +1376,48 @@ describe('BaseTypeahead paste behavior', () => {
.scrollIntoView;
}
});
+
+ it('highlights on hover without scrolling, keyboard still scrolls (#6077)', async () => {
+ // Hover must highlight only: scrollIntoView under a stationary pointer
+ // moves the next option under it, re-highlighting and scrolling again —
+ // a runaway auto-scroll loop with no user input.
+ const scrollIntoView = vi.fn();
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: scrollIntoView,
+ });
+ try {
+ const user = userEvent.setup();
+ render(
+ <BaseTypeahead
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await user.click(input);
+ await user.paste('e'); // matches Cherry, Date, Elderberry
+ await waitFor(() => {
+ expect(screen.getByRole('listbox', {hidden: true})).toBeInTheDocument();
+ });
+
+ scrollIntoView.mockClear();
+ const options = screen.getAllByRole('option', {hidden: true});
+ fireEvent.mouseEnter(options[1]);
+
+ expect(input.getAttribute('aria-activedescendant')).toBe(options[1].id);
+ expect(scrollIntoView).not.toHaveBeenCalled();
+
+ await user.keyboard('{ArrowDown}');
+ expect(scrollIntoView).toHaveBeenCalledWith({block: 'nearest'});
+ } finally {
+ delete (HTMLElement.prototype as unknown as {scrollIntoView?: unknown})
+ .scrollIntoView;
+ }
+ });
});
describe('Typeahead disabledMessage', () => {
diff --git a/packages/core/src/hooks/useHighlightedOptionScroll.ts b/packages/core/src/hooks/useHighlightedOptionScroll.ts
new file mode 100644
index 0000000000..03f26e8355
--- /dev/null
+++ b/packages/core/src/hooks/useHighlightedOptionScroll.ts
@@ -0,0 +1,73 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useHighlightedOptionScroll.ts
+ * @input Open state, the highlighted option index, its setter, and an
+ * 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
+ * @position Internal hook; used by useCombobox, useMultiCombobox,
+ * BaseTypeahead, and DateTimeInput — the owners of combobox highlight state
+ */
+
+import {useCallback, useEffect, useRef} from 'react';
+
+interface UseHighlightedOptionScrollOptions {
+ isOpen: boolean;
+ highlightedIndex: number;
+ setHighlightedIndex: (index: number) => void;
+ getOptionId: (index: number) => string;
+ /**
+ * Current option count, when the list can change while open (filtered or
+ * min/max-clamped lists). A count change re-runs the scroll, matching the
+ * list-length dependency the per-component effects carried before this hook
+ * existed.
+ */
+ itemCount?: number;
+}
+
+/**
+ * Keep the highlighted option visible during keyboard navigation — but not for
+ * hover highlights. Hover must highlight only: scrollIntoView moves the next
+ * option under the stationary pointer, whose mouseenter re-highlights and
+ * scrolls again — a runaway auto-scroll loop with no user input (#6077).
+ * Keyboard paths call the raw setter directly and keep their scrolling; hover
+ * paths call the returned callback.
+ */
+export function useHighlightedOptionScroll({
+ isOpen,
+ highlightedIndex,
+ setHighlightedIndex,
+ getOptionId,
+ itemCount,
+}: UseHighlightedOptionScrollOptions): (index: number) => void {
+ const hoverHighlightRef = useRef(false);
+
+ const highlightFromHover = useCallback(
+ (index: number) => {
+ if (index !== highlightedIndex) {
+ hoverHighlightRef.current = true;
+ }
+ setHighlightedIndex(index);
+ },
+ [highlightedIndex, setHighlightedIndex],
+ );
+
+ useEffect(() => {
+ if (hoverHighlightRef.current) {
+ hoverHighlightRef.current = false;
+ return;
+ }
+ if (!isOpen || highlightedIndex < 0) {
+ return;
+ }
+ document
+ .getElementById(getOptionId(highlightedIndex))
+ ?.scrollIntoView?.({block: 'nearest'});
+ }, [isOpen, highlightedIndex, getOptionId, itemCount]);
+
+ return highlightFromHover;
+}