Skip to content

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

TypeScript

fix(Selector): a row that scrolls under a still mouse does not take the keyboard's highlight (#9671)

Cindy Zhangb11e000b5140
diff --git a/.changeset/selector-still-mouse-highlight.md b/.changeset/selector-still-mouse-highlight.md
new file mode 100644
index 0000000000..f5df6bceba
--- /dev/null
+++ b/.changeset/selector-still-mouse-highlight.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] In an open Selector, MultiSelector, CommandPalette, DateTimeInput time list or Chat trigger menu, a key that scrolls the list (End, Home, PageDown, type-to-select) keeps the highlight where the key put it, even when the mouse is resting over the list. Before, the row that scrolled under the still pointer took the highlight. A mouse that moves or presses still takes it.
+
+@cixzhang
diff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsx
index 2cd9916909..bc5828f595 100644
--- a/apps/storybook/stories/Selector.stories.tsx
+++ b/apps/storybook/stories/Selector.stories.tsx
@@ -143,6 +143,28 @@ export const Default: Story = {
},
};
+const LONG_LIST = Array.from({length: 120}, (_, i) => `Team ${i + 1}`);
+
+/**
+ * A long option list: the list scrolls, End and PageDown scroll it, and a
+ * mouse resting over it keeps the highlight where the keys put it.
+ */
+export const LongList: Story = {
+ tags: ['!autodocs'],
+ render: () => {
+ const [value, setValue] = useState<string | undefined>(undefined);
+ return (
+ <Selector
+ label="Team"
+ options={LONG_LIST}
+ value={value}
+ onChange={v => setValue(v)}
+ presentation="popover"
+ />
+ );
+ },
+};
+
export const ReadOnly: Story = {
args: {
label: 'Assigned owner',
diff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsx
index d51141c1b7..214c82374d 100644
--- a/packages/core/src/Chat/ChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx
@@ -2081,6 +2081,7 @@ describe('ChatComposerInput', () => {
const options = await getMenuOptions(textbox);
fireEvent.mouseEnter(options[1]);
+ fireEvent.pointerMove(options[1], {screenX: 107, screenY: 107});
expect(options[1]).toHaveAttribute('aria-selected', 'true');
expect(spy.mock.calls.length).toBe(callsAfterOpen);
diff --git a/packages/core/src/CommandPalette/CommandPalette.test.tsx b/packages/core/src/CommandPalette/CommandPalette.test.tsx
index b9d4fe45e5..641e023341 100644
--- a/packages/core/src/CommandPalette/CommandPalette.test.tsx
+++ b/packages/core/src/CommandPalette/CommandPalette.test.tsx
@@ -51,6 +51,25 @@ beforeEach(() => {
});
describe('CommandPalette', () => {
+ it('a closed palette adds no document pointermove listener', () => {
+ const addListener = vi.spyOn(document, 'addEventListener');
+ try {
+ render(
+ <CommandPalette
+ isOpen={false}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ />,
+ );
+ const moveListeners = addListener.mock.calls.filter(
+ ([type]) => type === 'pointermove',
+ );
+ expect(moveListeners).toEqual([]);
+ } finally {
+ addListener.mockRestore();
+ }
+ });
+
it('renders when isOpen is true', () => {
render(
<CommandPalette
@@ -320,6 +339,42 @@ describe('CommandPalette', () => {
expect(handleOpenChange).not.toHaveBeenCalled();
});
+ it('an inline preview highlights its value again after a key and a cleared query', async () => {
+ const user = userEvent.setup();
+ render(
+ <CommandPalette
+ isOpen={true}
+ isInline
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ value="settings"
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ const settingsId = async () =>
+ (await screen.findByRole('option', {name: 'Settings', hidden: true})).id;
+ await waitFor(async () => {
+ expect(input.getAttribute('aria-activedescendant')).toBe(
+ await settingsId(),
+ );
+ });
+ await user.click(input);
+ // Keys only from here: a press would end the keyboard's hold.
+ await user.keyboard('{ArrowDown}');
+ await user.keyboard('h');
+ await waitFor(() => {
+ expect(
+ screen.queryByRole('option', {name: 'Settings', hidden: true}),
+ ).toBeNull();
+ });
+ await user.keyboard('{Backspace}');
+ await waitFor(async () => {
+ expect(input.getAttribute('aria-activedescendant')).toBe(
+ await settingsId(),
+ );
+ });
+ });
+
it('preserves local Escape closing for inline previews', () => {
const handleOpenChange = vi.fn();
render(
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
index 70fee92db0..40a8bc1b40 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
@@ -1643,6 +1643,7 @@ describe('DateTimeInput', () => {
.querySelector('[role="listbox"]')!
.querySelectorAll('[role="option"]');
fireEvent.mouseEnter(options[5]);
+ fireEvent.pointerMove(options[5], {screenX: 114, screenY: 114});
expect(timeInput.getAttribute('aria-activedescendant')).toBe(
options[5].id,
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index b866115302..c8785b57a7 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -1834,6 +1834,33 @@ describe('MultiSelector', () => {
});
describe('keyboard accessibility', () => {
+ it('a row that scrolls under a still mouse after a key does not take the highlight; a mouse that moves does', async () => {
+ const user = userEvent.setup();
+ const many = Array.from({length: 30}, (_, i) => `Option ${i}`);
+ render(
+ <MultiSelector
+ label="Items"
+ options={many}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ const trigger = screen.getByRole('combobox', {name: 'Items'});
+ trigger.focus();
+ await user.keyboard('{ArrowDown}');
+ const rows = screen.getAllByRole('option', {hidden: true});
+ const active = () => trigger.getAttribute('aria-activedescendant');
+ await user.keyboard('{End}');
+ expect(active()).toBe(rows[29].id);
+ // The browser reports the row now under the still mouse as entered.
+ fireEvent.mouseEnter(rows[20]);
+ expect(active()).toBe(rows[29].id);
+ // The mouse moves onto the next row.
+ fireEvent.mouseEnter(rows[21]);
+ fireEvent.pointerMove(rows[21], {screenX: 60, screenY: 90});
+ expect(active()).toBe(rows[21].id);
+ });
+
it('trigger is focusable via Tab when enabled', async () => {
const user = userEvent.setup();
render(
@@ -2005,6 +2032,7 @@ describe('MultiSelector', () => {
const options = screen.getAllByRole('option', {hidden: true});
fireEvent.mouseEnter(options[3]);
+ fireEvent.pointerMove(options[3], {screenX: 121, screenY: 121});
expect(trigger.getAttribute('aria-activedescendant')).toBe(
options[3].id,
@@ -4633,6 +4661,7 @@ describe('MultiSelector option actions (grid)', () => {
const bug = screen.getByRole('row', {name: 'Bug', ...h});
const actionCell = bug.children[1] as HTMLElement;
fireEvent.mouseEnter(actionCell);
+ fireEvent.pointerMove(actionCell, {screenX: 210, screenY: 210});
// The hover moved the highlight onto the action cell, without the ring.
expect(trigger).toHaveAttribute('aria-activedescendant', actionCell.id);
for (const token of ringClasses) {
@@ -4757,6 +4786,7 @@ describe('MultiSelector option actions (grid)', () => {
const {trigger, row} = await openWithKeyboardOnBugAction();
const docsAction = row('Docs').children[1] as HTMLElement;
fireEvent.mouseEnter(docsAction);
+ fireEvent.pointerMove(docsAction, {screenX: 149, screenY: 149});
expect(trigger).toHaveAttribute('aria-activedescendant', docsAction.id);
expect(hasRing(docsAction)).toBe(true);
});
@@ -4907,13 +4937,16 @@ describe('MultiSelector option actions (grid)', () => {
const bug = screen.getByRole('row', {name: 'Bug', ...h});
const feature = screen.getByRole('row', {name: 'Feature', ...h});
fireEvent.mouseEnter(feature.children[0]);
+ fireEvent.pointerMove(feature.children[0], {screenX: 128, screenY: 128});
expect(trigger).toHaveAttribute('aria-activedescendant', feature.id);
fireEvent.mouseEnter(bug.children[1]);
+ fireEvent.pointerMove(bug.children[1], {screenX: 135, screenY: 135});
expect(trigger).toHaveAttribute(
'aria-activedescendant',
bug.children[1].id,
);
fireEvent.mouseEnter(bug.children[0]);
+ fireEvent.pointerMove(bug.children[0], {screenX: 142, screenY: 142});
expect(trigger).toHaveAttribute('aria-activedescendant', bug.id);
});
diff --git a/packages/core/src/MultiSelector/hooks.ts b/packages/core/src/MultiSelector/hooks.ts
index c5954ec333..7849f00e6c 100644
--- a/packages/core/src/MultiSelector/hooks.ts
+++ b/packages/core/src/MultiSelector/hooks.ts
@@ -174,13 +174,11 @@ export function useMultiCombobox({
// The action cell is the caller's control, usable whether or not the
// option itself is disabled (spec:AST-058 FR4).
if (cell === 'action') {
- highlightOnHover(index);
- setHighlightedCell('action');
+ highlightOnHover(index, () => setHighlightedCell('action'));
return;
}
if (!item.disabled) {
- highlightOnHover(index);
- setHighlightedCell('option');
+ highlightOnHover(index, () => setHighlightedCell('option'));
}
},
[highlightOnHover],
diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsx
index 094de061f6..fa841e83f2 100644
--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx
+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx
@@ -1072,6 +1072,7 @@ describe('field menu highlight under a resting pointer', () => {
name: 'Status',
hidden: true,
});
+ fireEvent.pointerMove(status, {screenX: 30, screenY: 40});
fireEvent.mouseMove(status);
expect(input.getAttribute('aria-activedescendant')).toBe(status.id);
});
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 364e3552a7..c87c7c9256 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -2052,6 +2052,8 @@ describe('Selector', () => {
scrollIntoView.mockClear();
const options = screen.getAllByRole('option', {hidden: true});
+ // The mouse moves onto the row: a hover after keyboard use.
+ fireEvent.pointerMove(options[3], {screenX: 40, screenY: 80});
fireEvent.mouseEnter(options[3]);
const trigger = screen.getByRole('combobox');
@@ -5177,6 +5179,63 @@ describe('Selector press model', () => {
expect(listbox).not.toHaveClass(hash(touchStyles.panYPinchZoom));
});
+ it('a press held still after a key lights the pressed row', async () => {
+ const user = userEvent.setup();
+ const many = Array.from({length: 30}, (_, i) => `Option ${i}`);
+ render(<Selector label="Item" options={many} onChange={() => {}} />);
+ const trigger = screen.getByRole('combobox');
+ trigger.focus();
+ await user.keyboard('{ArrowDown}');
+ const listbox = screen.getByRole('listbox', h);
+ const rows = within(listbox).getAllByRole('option', h);
+ await user.keyboard('{End}');
+ expect(trigger).toHaveAttribute('aria-activedescendant', rows[29].id);
+ // The browser reports the row under the still mouse as entered.
+ fireEvent.mouseOver(rows[20]);
+ expect(trigger).toHaveAttribute('aria-activedescendant', rows[29].id);
+ // The mouse presses without moving: the pressed row lights.
+ fireEvent.pointerDown(rows[20], {
+ pointerType: 'mouse',
+ button: 0,
+ buttons: 1,
+ });
+ expect(trigger).toHaveAttribute('aria-activedescendant', rows[20].id);
+ });
+
+ it('a row that scrolls under a still mouse after a key does not take the highlight; a mouse that moves does', async () => {
+ const user = userEvent.setup();
+ const many = Array.from({length: 30}, (_, i) => `Option ${i}`);
+ render(<Selector label="Item" options={many} onChange={() => {}} />);
+ const trigger = screen.getByRole('combobox');
+ trigger.focus();
+ await user.keyboard('{ArrowDown}');
+ const listbox = screen.getByRole('listbox', h);
+ const rows = within(listbox).getAllByRole('option', h);
+ const active = () =>
+ document
+ .querySelector('[aria-activedescendant]')
+ ?.getAttribute('aria-activedescendant');
+ // The mouse rests over row 3.
+ fireEvent.pointerMove(rows[3], {screenX: 100, screenY: 200});
+ fireEvent.mouseOver(rows[3]);
+ expect(active()).toBe(rows[3].id);
+ // End moves the highlight to the last row and scrolls; the browser then
+ // reports whichever row is now under the still mouse as entered.
+ await user.keyboard('{End}');
+ expect(active()).toBe(rows[29].id);
+ fireEvent.pointerMove(rows[20], {screenX: 100, screenY: 200});
+ fireEvent.mouseOver(rows[20]);
+ expect(active()).toBe(rows[29].id);
+ // The mouse moves. The browser reports entering the next row before the
+ // move that reaches it; that row takes the highlight with the move.
+ fireEvent.mouseOver(rows[21]);
+ expect(active()).toBe(rows[29].id);
+ fireEvent.pointerMove(rows[21], {screenX: 100, screenY: 230});
+ expect(active()).toBe(rows[21].id);
+ fireEvent.mouseOver(rows[22]);
+ expect(active()).toBe(rows[22].id);
+ });
+
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}`);
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index 6e08d51b89..da427f2066 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -2375,6 +2375,7 @@ describe('BaseTypeahead paste behavior', () => {
scrollIntoView.mockClear();
const options = screen.getAllByRole('option', {hidden: true});
+ fireEvent.pointerMove(options[1], {screenX: 156, screenY: 156});
fireEvent.mouseMove(options[1]);
expect(input.getAttribute('aria-activedescendant')).toBe(options[1].id);
@@ -2415,8 +2416,10 @@ describe('BaseTypeahead highlight under a resting pointer', () => {
expect(input.getAttribute('aria-activedescendant')).toBe(options[0].id);
fireEvent.mouseEnter(options[2]);
+ fireEvent.pointerMove(options[2], {screenX: 163, screenY: 163});
expect(input.getAttribute('aria-activedescendant')).toBe(options[0].id);
+ fireEvent.pointerMove(options[2], {screenX: 170, screenY: 170});
fireEvent.mouseMove(options[2]);
expect(input.getAttribute('aria-activedescendant')).toBe(options[2].id);
});
diff --git a/packages/core/src/hooks/useHighlightedOptionScroll.test.ts b/packages/core/src/hooks/useHighlightedOptionScroll.test.ts
index 9e84de8ee9..93face41a1 100644
--- a/packages/core/src/hooks/useHighlightedOptionScroll.test.ts
+++ b/packages/core/src/hooks/useHighlightedOptionScroll.test.ts
@@ -9,7 +9,7 @@
*/
import {afterEach, describe, expect, it, vi} from 'vitest';
-import {renderHook} from '@testing-library/react';
+import {fireEvent, renderHook} from '@testing-library/react';
import {useHighlightedOptionScroll} from './useHighlightedOptionScroll';
function addOptions(count: number) {
@@ -46,6 +46,8 @@ describe('useHighlightedOptionScroll', () => {
{initialProps: {highlightedIndex: 0}},
);
scrolled.length = 0;
+ // The pointer moves, so a hover no longer waits for the keyboard.
+ fireEvent.pointerMove(document.body, {screenX: 5, screenY: 5});
result.current(2);
rerender({highlightedIndex: 2});
expect(scrolled).toEqual([]);
@@ -53,6 +55,45 @@ describe('useHighlightedOptionScroll', () => {
expect(scrolled).toEqual(['opt-1']);
});
+ it('a hover after a keyboard move waits for the pointer to move, then applies', () => {
+ addOptions(3);
+ const setHighlightedIndex = vi.fn();
+ const onHighlight = vi.fn();
+ const {result} = renderHook(() =>
+ useHighlightedOptionScroll({
+ isOpen: true,
+ highlightedIndex: 0,
+ setHighlightedIndex,
+ getOptionId,
+ }),
+ );
+ // The open highlighted row 0, as a keyboard move does.
+ result.current(2, onHighlight);
+ expect(setHighlightedIndex).not.toHaveBeenCalled();
+ fireEvent.pointerMove(document.body, {screenX: 9, screenY: 9});
+ expect(setHighlightedIndex).toHaveBeenCalledWith(2);
+ expect(onHighlight).toHaveBeenCalledTimes(1);
+ });
+
+ it('a cleared highlight ends the hold, so the next hover applies at once', () => {
+ addOptions(3);
+ const setHighlightedIndex = vi.fn();
+ const {result, rerender} = renderHook(
+ ({highlightedIndex}: {highlightedIndex: number}) =>
+ useHighlightedOptionScroll({
+ isOpen: true,
+ highlightedIndex,
+ setHighlightedIndex,
+ getOptionId,
+ }),
+ {initialProps: {highlightedIndex: 0}},
+ );
+ // A new search clears the highlight; a value then highlights by hover.
+ rerender({highlightedIndex: -1});
+ result.current(1);
+ expect(setHighlightedIndex).toHaveBeenCalledWith(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();
@@ -69,6 +110,7 @@ describe('useHighlightedOptionScroll', () => {
);
scrolled.length = 0;
// The pointer moves over the highlighted row: no state changes.
+ fireEvent.pointerMove(document.body, {screenX: 5, screenY: 5});
result.current(0);
// A new query's list keeps the same row highlighted.
rerender({itemCount: 2});
diff --git a/packages/core/src/hooks/useHighlightedOptionScroll.ts b/packages/core/src/hooks/useHighlightedOptionScroll.ts
index 3935c051b2..1834c853dd 100644
--- a/packages/core/src/hooks/useHighlightedOptionScroll.ts
+++ b/packages/core/src/hooks/useHighlightedOptionScroll.ts
@@ -8,7 +8,8 @@
* 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; the hover callback is stable while `setHighlightedIndex` is
+ * never scroll, and a hover after a keyboard move waits for the pointer to
+ * move or press; the hover callback is stable while `setHighlightedIndex` is
* @position Internal hook; used by useCombobox, useMultiCombobox,
* BaseTypeahead, and DateTimeInput — the owners of combobox highlight state
*/
@@ -27,6 +28,21 @@ interface UseHighlightedOptionScrollOptions {
itemCount?: number;
}
+/**
+ * Highlights the hovered option at `index`. `onHighlight` runs when the hover
+ * takes effect: at once, or after the pointer moves or presses when a
+ * keyboard move holds the highlight.
+ */
+export type HighlightFromHover = (
+ index: number,
+ onHighlight?: () => void,
+) => void;
+
+interface WaitingHover {
+ index: number;
+ onHighlight?: () => void;
+}
+
/**
* Keep the highlighted option visible during keyboard navigation — but not for
* hover highlights. Hover must highlight only: scrollIntoView moves the next
@@ -34,6 +50,10 @@ interface UseHighlightedOptionScrollOptions {
* scrolls again — a runaway auto-scroll loop with no user input.
* Keyboard paths call the raw setter directly and keep their scrolling; hover
* paths call the returned callback.
+ *
+ * A keyboard move holds the highlight. A key that scrolls the list moves rows
+ * under a still mouse, and the browser reports the row under it as entered;
+ * that row takes the highlight only once the pointer moves or presses.
*/
export function useHighlightedOptionScroll({
isOpen,
@@ -41,19 +61,93 @@ export function useHighlightedOptionScroll({
setHighlightedIndex,
getOptionId,
itemCount,
-}: UseHighlightedOptionScrollOptions): (index: number) => void {
+}: UseHighlightedOptionScrollOptions): HighlightFromHover {
// The callback reads no render state, so memoized rows keep one function.
const hoveredIndexRef = useRef<number | null>(null);
const shownIndexRef = useRef(highlightedIndex);
+ // The hover that came while a keyboard move held the highlight.
+ const waitingHoverRef = useRef<WaitingHover | null>(null);
+ // Set only while a keyboard move holds the highlight.
+ const removeHoldListenersRef = useRef<(() => void) | null>(null);
+ const setHighlightedIndexRef = useRef(setHighlightedIndex);
+ // The pointer's last screen position a hold saw, kept across holds.
+ const lastPointerRef = useRef<{x: number; y: number} | null>(null);
+
+ const applyHover = useCallback((hover: WaitingHover) => {
+ hoveredIndexRef.current = hover.index;
+ setHighlightedIndexRef.current(hover.index);
+ hover.onHighlight?.();
+ }, []);
+
+ const endHold = useCallback(() => {
+ removeHoldListenersRef.current?.();
+ removeHoldListenersRef.current = null;
+ }, []);
+
+ const releaseHold = useCallback(() => {
+ endHold();
+ const waiting = waitingHoverRef.current;
+ waitingHoverRef.current = null;
+ if (waiting != null) {
+ applyHover(waiting);
+ }
+ }, [applyHover, endHold]);
- const highlightFromHover = useCallback(
- (index: number) => {
+ // Holds the highlight until the pointer moves or presses. The listeners
+ // live only while the hold does. Movement is read by screen coordinates: a
+ // scroll moves the rows, not the pointer. The browser reports a row as
+ // entered before the move that reaches it, so the first real move gives
+ // that row the highlight. A press releases at once, so a held press lights
+ // the pressed row.
+ const startHold = useCallback(() => {
+ waitingHoverRef.current = null;
+ if (removeHoldListenersRef.current != null) {
+ return;
+ }
+ const onPointerMove = (event: PointerEvent) => {
+ const last = lastPointerRef.current;
+ lastPointerRef.current = {x: event.screenX, y: event.screenY};
+ if (
+ last != null &&
+ last.x === event.screenX &&
+ last.y === event.screenY
+ ) {
+ return;
+ }
+ releaseHold();
+ };
+ const options = {capture: true, passive: true} as const;
+ document.addEventListener('pointermove', onPointerMove, options);
+ document.addEventListener('pointerdown', releaseHold, options);
+ removeHoldListenersRef.current = () => {
+ document.removeEventListener('pointermove', onPointerMove, options);
+ document.removeEventListener('pointerdown', releaseHold, options);
+ };
+ }, [releaseHold]);
+
+ const highlightFromHover = useCallback<HighlightFromHover>(
+ (index, onHighlight) => {
+ if (removeHoldListenersRef.current != null) {
+ waitingHoverRef.current = {index, onHighlight};
+ return;
+ }
hoveredIndexRef.current = index;
setHighlightedIndex(index);
+ onHighlight?.();
},
[setHighlightedIndex],
);
+ // Effect: keeps the hold's document listeners calling the current setter.
+ useEffect(() => {
+ setHighlightedIndexRef.current = setHighlightedIndex;
+ }, [setHighlightedIndex]);
+
+ // Effect: removes the hold's document listeners on unmount.
+ useEffect(() => endHold, [endHold]);
+
+ // Effect: scrolls the highlighted option into view in the document, and
+ // starts or ends the hold on its document listeners.
useEffect(() => {
// 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
@@ -63,13 +157,23 @@ export function useHighlightedOptionScroll({
const isFromHover =
hasMoved && hoveredIndexRef.current === highlightedIndex;
hoveredIndexRef.current = null;
- if (isFromHover || !isOpen || highlightedIndex < 0) {
+ if (isFromHover) {
+ return;
+ }
+ // A cleared highlight, a closed list, or a list that is not shown (a
+ // closed CommandPalette reports itself as open) has nothing to hold.
+ const option =
+ isOpen && highlightedIndex >= 0
+ ? document.getElementById(getOptionId(highlightedIndex))
+ : null;
+ if (option == null) {
+ waitingHoverRef.current = null;
+ endHold();
return;
}
- document
- .getElementById(getOptionId(highlightedIndex))
- ?.scrollIntoView?.({block: 'nearest'});
- }, [isOpen, highlightedIndex, getOptionId, itemCount]);
+ startHold();
+ option.scrollIntoView?.({block: 'nearest'});
+ }, [isOpen, highlightedIndex, getOptionId, itemCount, endHold, startHold]);
return highlightFromHover;
}