Skip to content

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

TypeScript

feat(menus): arrows wrap, PageUp/PageDown page, typeahead reads the label alone (#6823)

Christopher Chedeau64fdf5aa7901
diff --git a/.changeset/menu-keyboard.md b/.changeset/menu-keyboard.md
new file mode 100644
index 0000000000..04d70b270f
--- /dev/null
+++ b/.changeset/menu-keyboard.md
@@ -0,0 +1,17 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Menu arrows wrap and PageUp/PageDown page.
+
+In `DropdownMenu`, `ContextMenu` and `DropdownMenuSubMenu`, ArrowDown on the
+last row wraps to the first and ArrowUp on the first to the last, as macOS
+menus do (`Selector` keeps clamping like a native select). PageDown and
+PageUp move to the last and first fully visible row of a scrolling menu, and
+pressed there again one viewport further, never wrapping. ArrowUp on the
+trigger opens the menu with the last row highlighted. The key that opened
+the menu no longer activates the first row through its auto-repeat, and
+typeahead ignores a key that is part of an input-method composition.
+`useListFocus` gains `hasPaging`.
+
+@vjeux @cixzhang
diff --git a/packages/core/src/ContextMenu/ContextMenu.spec.md b/packages/core/src/ContextMenu/ContextMenu.spec.md
index c506aeb816..51c89df3e9 100644
--- a/packages/core/src/ContextMenu/ContextMenu.spec.md
+++ b/packages/core/src/ContextMenu/ContextMenu.spec.md
@@ -81,15 +81,16 @@ Consumer props, content modes, and presentation policy remain documented in
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------- |
-| FR1 | Every render contains a caller-provided Trigger area. Pointer presentation opens a Pointer menu surface at the current local cursor anchor; touch presentation opens a Touch sheet frame containing a Touch menu surface and, for data mode, a Touch action list and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR2 | The current `context-menu` target remains on the painted Pointer menu surface and alternative Touch menu surface, not on the Trigger area or cursor anchor. | Current source, docs, and tests | Verified current inventory; no target change |
-| FR3 | Pointer action rows retain DropdownMenu ownership. The touch frame retains BottomSheet ownership, while data-driven touch lists and rows retain List ownership. | Current source and owner docs | Verified current delegation; no ownership change |
-| FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | Verified current branches; no behavior change |
-| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. Right-click, Shift+F10, long-press invocation and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `ContextMenu.test.tsx` press model suite | Proposed; verified in jsdom |
-| FR6 | With `triggerAs="span"` the Trigger area MUST be an inline element that owns a box, so the cursor anchor measures from the trigger's own rect on every invocation path. Every invocation path (right-click, Shift+F10, long-press) and the `context-menu` target's placement are unchanged. | `component:ContextMenu/DEC-1` | Accepted; verified in jsdom |
-| FR7 | Sub-menu rows follow `component:DropdownMenu` FR12 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. | `component:DropdownMenu/DEC-2` | Proposed; verified in jsdom |
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
+| FR1 | Every render contains a caller-provided Trigger area. Pointer presentation opens a Pointer menu surface at the current local cursor anchor; touch presentation opens a Touch sheet frame containing a Touch menu surface and, for data mode, a Touch action list and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR2 | The current `context-menu` target remains on the painted Pointer menu surface and alternative Touch menu surface, not on the Trigger area or cursor anchor. | Current source, docs, and tests | Verified current inventory; no target change |
+| FR3 | Pointer action rows retain DropdownMenu ownership. The touch frame retains BottomSheet ownership, while data-driven touch lists and rows retain List ownership. | Current source and owner docs | Verified current delegation; no ownership change |
+| FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | Verified current branches; no behavior change |
+| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. Right-click, Shift+F10, long-press invocation and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `ContextMenu.test.tsx` press model suite | Proposed; verified in jsdom |
+| FR6 | With `triggerAs="span"` the Trigger area MUST be an inline element that owns a box, so the cursor anchor measures from the trigger's own rect on every invocation path. Every invocation path (right-click, Shift+F10, long-press) and the `context-menu` target's placement are unchanged. | `component:ContextMenu/DEC-1` | Accepted; verified in jsdom |
+| FR7 | Sub-menu rows follow `component:DropdownMenu` FR12 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. | `component:DropdownMenu/DEC-2` | Proposed; verified in jsdom |
+| FR8 | In the pointer menu ArrowDown on the last enabled row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp page as in DropdownMenu FR6; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. | Proposed in this change; `ContextMenu.test.tsx` keyboard case; shared `useListFocus` and `useTypeahead` suites | Proposed; verified in jsdom, pending owner review |
### Allowed variation
@@ -202,6 +203,7 @@ anchor is positioning infrastructure rather than consumer anatomy.
| FR3 | ContextMenu, DropdownMenu, BottomSheet, and List owner tests | Pointer rows, touch frame, touch list/rows | A composed part loses its owner target or is documented as a new ContextMenu target. | `audit:ContextMenu/theming` |
| Layer relationships | `ContextMenu.test.tsx` and current layer/dismissal architecture records | Outside click, Escape, context anchor, sheet | Documentation claims shared dismissal where current source retains local behavior. | `audit:ContextMenu/behavior` |
| FR5 | `ContextMenu.test.tsx` press model case; `module:DropdownMenu/useMenuPress` map | Finger slide across rows, stray click | A row acting on the press row or the stray click fails. | `audit:ContextMenu/behavior` |
+| FR6 | `ContextMenu.test.tsx` keyboard case; shared `useListFocus` and `useTypeahead` suites | wrap at both ends | Clamping arrows fail. | `audit:ContextMenu/behavior` |
| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` |
| FR6, AR1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" suite | `span` in a paragraph, default `div` | A block trigger inside prose, or a lost invocation path, fails. | `audit:ContextMenu/behavior` |
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index db7ff49852..7ed8d34967 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -1064,6 +1064,26 @@ describe('ContextMenu press model', () => {
});
});
+describe('ContextMenu keyboard', () => {
+ const item = (name: string) =>
+ screen.getByRole('menuitem', {name, hidden: true});
+
+ it('wraps arrow navigation at the ends', () => {
+ render(
+ <ContextMenu items={[{label: 'Cut'}, {label: 'Copy'}, {label: 'Paste'}]}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ const menu = screen.getByRole('menu', {hidden: true});
+ item('Paste').focus();
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ expect(item('Cut')).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'ArrowUp'});
+ expect(item('Paste')).toHaveFocus();
+ });
+});
+
describe('ContextMenu inline trigger (triggerAs)', () => {
it('an inline trigger keeps its flow', () => {
render(
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index b36315c945..77fdc76ad4 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -413,13 +413,15 @@ export function ContextMenu({
} = useListFocus<HTMLDivElement>({
itemSelector: MENU_ITEM_SELECTOR,
boundarySelector: MENU_BOUNDARY_SELECTOR,
- wrap: false,
+ // Menus wrap from the last row to the first and back.
+ wrap: true,
+ hasPaging: true,
onEscape: closeMenu,
});
- // First-character typeahead over the enabled menu items (menus-11). Reuses
- // the hook's scoped item collection so an inline submenu flyout's items
- // aren't swept in.
+ // Typeahead over the enabled menu items, matched on each row's LABEL alone.
+ // Reuses the hook's scoped item collection so an inline submenu flyout's
+ // items aren't swept in.
const typeahead = useTypeahead({
getItemLabels: () => getMenuItems().map(el => el.textContent),
onMatch: focusItem,
@@ -485,6 +487,10 @@ export function ContextMenu({
}
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
+ // A held key's auto-repeat never activates.
+ if (e.repeat) {
+ return;
+ }
const focused = document.activeElement as HTMLElement | null;
if (
focused &&
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
index 09d5fc69d5..dcabc28306 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md
+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
@@ -110,6 +110,7 @@ released default.
| FR10 | An action row with `href` MUST render as one anchor carrying `role="menuitem"` (the pointer menu) or the touch sheet's link row, routed through `LinkProvider`; a plain click MUST run `onClick`, then close the menu (`hasCloseOnSelect`), then let the browser navigate; a modified click or middle click MUST be left to the browser and MUST NOT run `onClick`; Enter and Space MUST activate through a synthesized click that carries the key's modifiers. A disabled link row has no `href`. | `component:DropdownMenu/DEC-2`; `family:navigation-destinations` | Proposed; verified in jsdom; owner to confirm DEC-1 |
| Sub-menu presentation | `presentation` on a sub-menu row: `flyout`, `drill-in`, `adaptive` | Whether a sub-menu opens beside its row or replaces the menu's rows with its own and a Back row, in the same box. `adaptive` drills in when a coarse pointer opened the menu. | Pointer presentation, compound and data mode | `adaptive` | `component:DropdownMenu` | stable | An unknown value reads as `adaptive`. |
| FR11 | When a compact touch display opened the pointer menu (`COMPACT_TOUCH_PRESENTATION_QUERY`, the same query the root presentation uses for its bottom sheet, sampled once as it opens) an `adaptive` sub-menu row MUST drill in: its rows and a leading Back row named "Back to <parent>" replace the menu's rows in the same Pointer menu surface, no flyout opens, the drilled list is a `menu` named by the row's label, and Back, Escape and ArrowLeft MUST return to the row with focus on it; a pick inside closes the whole menu. Roving focus and typeahead scope to the shown rows; sibling rows and dividers need no knowledge of it. `presentation="flyout"` keeps the flyout; `"drill-in"` drills in on any pointer. | `component:DropdownMenu/DEC-2`; `architecture:interaction-modality` | Proposed; verified in jsdom and Chromium (coarse pointer); owner to confirm DEC-5 |
+| FR12 | In the pointer menu ArrowDown on the last enabled row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp move to the last and first fully visible enabled row and, pressed there again, one viewport further without wrapping; ArrowUp on the trigger opens with the last enabled row highlighted; the key that opened the menu and its auto-repeats do not activate; typeahead matches the row's label element alone and ignores Control/Command chords and input-method composition. | Proposed in this change; `DropdownMenu.test.tsx` keyboard suite, `useListFocus.test.tsx`, `useTypeahead.test.tsx` | Proposed; verified in jsdom, pending owner review |
### Allowed variation
@@ -276,6 +277,8 @@ than adding a DropdownMenu-owned heading target.
### DEC-1 — Pointer dismissal returns focus to the trigger, ring suppressed
+### DEC-2 — Arrow keys wrap in a menu
+
**Reference:** `component:DropdownMenu/DEC-1`
**Decider:** pending owner review
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 1e406d6a6b..2febe8eaf5 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -2901,3 +2901,65 @@ describe("DropdownMenu link rows — the browser's own clicks", () => {
expect((window as unknown as {__fired?: boolean}).__fired).toBeUndefined();
});
});
+
+describe('DropdownMenu keyboard', () => {
+ const items = [{label: 'Edit'}, {label: 'Duplicate'}, {label: 'Delete'}];
+ const item = (name: string | RegExp) =>
+ screen.getByRole('menuitem', {name, hidden: true});
+
+ it('ArrowDown on the last row wraps to the first, ArrowUp on the first to the last', async () => {
+ const user = userEvent.setup();
+ render(<DropdownMenu button={{label: 'Actions'}} items={items} />);
+ screen.getByRole('button', {name: /Actions/}).focus();
+ await user.keyboard('{Enter}');
+ await waitFor(() => expect(item('Edit')).toHaveFocus());
+ const menu = screen.getByRole('menu', {hidden: true});
+ fireEvent.keyDown(menu, {key: 'ArrowUp'});
+ expect(item('Delete')).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ expect(item('Edit')).toHaveFocus();
+ });
+
+ it('ArrowUp on the trigger opens with the last row highlighted', async () => {
+ const user = userEvent.setup();
+ render(<DropdownMenu button={{label: 'Actions'}} items={items} />);
+ screen.getByRole('button', {name: /Actions/}).focus();
+ await user.keyboard('{ArrowUp}');
+ await waitFor(() => expect(item('Delete')).toHaveFocus());
+ });
+
+ it('PageDown moves to the last row and PageUp back to the first', async () => {
+ const user = userEvent.setup();
+ render(<DropdownMenu button={{label: 'Actions'}} items={items} />);
+ screen.getByRole('button', {name: /Actions/}).focus();
+ await user.keyboard('{Enter}');
+ await waitFor(() => expect(item('Edit')).toHaveFocus());
+ const menu = screen.getByRole('menu', {hidden: true});
+ fireEvent.keyDown(menu, {key: 'PageDown'});
+ expect(item('Delete')).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'PageDown'});
+ expect(item('Delete')).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'PageUp'});
+ expect(item('Edit')).toHaveFocus();
+ });
+
+ it("the opening key's auto-repeat does not act on the highlighted row", async () => {
+ const onClick = vi.fn();
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ items={[{label: 'Edit', onClick}]}
+ />,
+ );
+ screen.getByRole('button', {name: /Actions/}).focus();
+ await user.keyboard('{Enter>}');
+ await waitFor(() => expect(item('Edit')).toHaveFocus());
+ fireEvent.keyDown(item('Edit'), {key: 'Enter', repeat: true});
+ fireEvent.keyDown(item('Edit'), {key: 'Enter', repeat: true});
+ fireEvent.keyUp(item('Edit'), {key: 'Enter'});
+ expect(onClick).not.toHaveBeenCalled();
+ fireEvent.keyDown(item('Edit'), {key: 'Enter'});
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index d387c0e70e..d2227a876e 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -828,6 +828,8 @@ function DropdownMenuPopover({
// if pre-selected (#4477). Reset to 'keyboard' after every open so
// programmatic controlled opens keep the item-focus behavior.
const openModalityRef = useRef<'keyboard' | 'pointer'>('keyboard');
+ // ArrowUp opens with the LAST enabled row highlighted.
+ const focusLastOnOpenRef = useRef(false);
const handleLayerShow = useCallback(() => {
acceptedOpenRef.current = true;
@@ -865,19 +867,24 @@ function DropdownMenuPopover({
listRef,
handleKeyDown: listNavKeyDown,
focusFirst,
+ focusLast,
focusItem,
ownsEvent,
getItems: getMenuItems,
} = useListFocus<HTMLDivElement>({
itemSelector: MENU_ITEM_SELECTOR,
boundarySelector: MENU_BOUNDARY_SELECTOR,
- wrap: false,
+ // Menus wrap from the last row to the first and back, as macOS menus do;
+ // a picker's list clamps instead.
+ wrap: true,
+ hasPaging: true,
onEscape: closeMenu,
});
- // First-character typeahead over the (enabled) menu items — jump to the next
- // item whose label starts with the typed text (menus-11). Reuses the hook's
- // scoped item collection so an inline submenu flyout's items aren't swept in.
+ // Typeahead over the (enabled) menu items — jump to the next item whose
+ // LABEL starts with the typed text, never its description, shortcut or
+ // badge. Reuses the hook's scoped item collection so an inline submenu
+ // flyout's items aren't swept in.
const typeahead = useTypeahead({
getItemLabels: () => getMenuItems().map(el => el.textContent),
onMatch: focusItem,
@@ -935,12 +942,14 @@ function DropdownMenuPopover({
}
shouldFocusOnOpenRef.current = false;
requestAnimationFrame(() => {
- if (openModalityRef.current === 'pointer' || !focusFirst()) {
+ const focusEnd = focusLastOnOpenRef.current ? focusLast : focusFirst;
+ focusLastOnOpenRef.current = false;
+ if (openModalityRef.current === 'pointer' || !focusEnd()) {
listRef.current?.focus();
}
openModalityRef.current = 'keyboard';
});
- }, [popover.isOpen, focusFirst, listRef]);
+ }, [popover.isOpen, focusFirst, focusLast, listRef]);
// Extend useListFocus with Enter/Space activation + typeahead
const listKeyDown = useCallback(
@@ -952,6 +961,11 @@ function DropdownMenuPopover({
}
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
+ // The key that opened the menu, held down, auto-repeats into the menu
+ // once focus has moved there; a repeat is never an activation.
+ if (e.repeat) {
+ return;
+ }
const focused = document.activeElement as HTMLElement | null;
if (
focused &&
@@ -1105,8 +1119,17 @@ function DropdownMenuPopover({
const handleButtonKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (!popover.isOpen) {
- if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
+ if (
+ e.key === 'ArrowDown' ||
+ e.key === 'ArrowUp' ||
+ e.key === 'Enter' ||
+ e.key === ' '
+ ) {
e.preventDefault();
+ if (e.repeat) {
+ return;
+ }
+ focusLastOnOpenRef.current = e.key === 'ArrowUp';
openAndFocus();
}
return;
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
index f1123d0733..9f89e4fb0d 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -408,7 +408,9 @@ export function DropdownMenuSubMenu(
} = useListFocus<HTMLDivElement>({
itemSelector: MENU_ITEM_SELECTOR,
boundarySelector: MENU_BOUNDARY_SELECTOR,
- wrap: false,
+ // Menus wrap.
+ wrap: true,
+ hasPaging: true,
onEscape: () => close({focusTrigger: true}),
});
// A drilled-in list scrolls with the root menu, not on its own.
@@ -628,6 +630,10 @@ export function DropdownMenuSubMenu(
}
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
+ // A held key's auto-repeat never activates.
+ if (e.repeat) {
+ return;
+ }
const focused = document.activeElement as HTMLElement | null;
if (
focused &&
diff --git a/packages/core/src/hooks/useListFocus.doc.mjs b/packages/core/src/hooks/useListFocus.doc.mjs
index e0ba80a528..0fd58f5e18 100644
--- a/packages/core/src/hooks/useListFocus.doc.mjs
+++ b/packages/core/src/hooks/useListFocus.doc.mjs
@@ -68,6 +68,14 @@ export const docs = {
default: 'true',
required: false,
},
+ {
+ name: 'options.hasPaging',
+ type: 'boolean',
+ description:
+ 'Whether PageDown/PageUp page through a scrolling list: PageDown moves to the last enabled item fully visible in the container, and pressed there again one viewport further; PageUp mirrors it. Neither wraps; in a list that does not scroll they act as End/Home.',
+ default: 'false',
+ required: false,
+ },
{
name: 'options.hasRovingTabIndex',
type: 'boolean',
@@ -179,6 +187,8 @@ export const docsDense = {
'options.orientation':
"navigation orientation. 'horizontal' uses ArrowLeft/ArrowRight, 'vertical' uses ArrowUp/ArrowDown, 'both' accepts all four arrows.",
'options.hasHomeEnd': 'whether Home/End jump to first/last enabled item.',
+ 'options.hasPaging':
+ 'whether PageDown/PageUp page through a scrolling list (last/first fully visible item, then one viewport further; never wraps).',
'options.hasRovingTabIndex':
'opt into roving-tabindex ownership: hook stamps + repairs a single tab stop across items.',
'options.hasCaretGuard':
diff --git a/packages/core/src/hooks/useListFocus.test.tsx b/packages/core/src/hooks/useListFocus.test.tsx
index e85a56406d..8b383a4877 100644
--- a/packages/core/src/hooks/useListFocus.test.tsx
+++ b/packages/core/src/hooks/useListFocus.test.tsx
@@ -561,3 +561,104 @@ describe('useListFocus Escape', () => {
expect(screen.getByTestId('Two')).toHaveFocus();
});
});
+
+describe('useListFocus paging (hasPaging)', () => {
+ const ROW_HEIGHT = 40;
+ const VIEWPORT = 100;
+
+ function PagedMenu({hasPaging = true}: {hasPaging?: boolean}) {
+ const {listRef, handleKeyDown} = useListFocus<HTMLDivElement>({
+ hasPaging,
+ wrap: true,
+ });
+ const items = ['One', 'Two', 'Three', 'Four', 'Five', 'Six'];
+ return (
+ <div ref={listRef} role="menu" onKeyDown={handleKeyDown}>
+ {items.map(label => (
+ <div key={label} role="menuitem" tabIndex={-1} data-testid={label}>
+ {label}
+ </div>
+ ))}
+ </div>
+ );
+ }
+
+ /**
+ * jsdom has no layout: give the container a 100px viewport and each row
+ * 40px, so rows One and Two are fully visible, Three is cut, and the rest
+ * sit below the fold.
+ */
+ function layOut() {
+ const menu = screen.getByRole('menu');
+ const rect = (top: number, bottom: number) =>
+ ({
+ top,
+ bottom,
+ left: 0,
+ right: 200,
+ width: 200,
+ height: bottom - top,
+ x: 0,
+ y: top,
+ toJSON: () => ({}),
+ }) as DOMRect;
+ vi.spyOn(menu, 'getBoundingClientRect').mockReturnValue(rect(0, VIEWPORT));
+ Object.defineProperty(menu, 'clientHeight', {value: VIEWPORT});
+ screen.getAllByRole('menuitem').forEach((item, index) => {
+ vi.spyOn(item, 'getBoundingClientRect').mockReturnValue(
+ rect(index * ROW_HEIGHT, (index + 1) * ROW_HEIGHT),
+ );
+ });
+ return menu;
+ }
+
+ it('PageDown moves to the last fully visible item', () => {
+ render(<PagedMenu />);
+ const menu = layOut();
+ screen.getByTestId('One').focus();
+ fireEvent.keyDown(menu, {key: 'PageDown'});
+ expect(screen.getByTestId('Two')).toHaveFocus();
+ });
+
+ it('PageDown pressed at the visible edge moves one viewport further, never wrapping', () => {
+ render(<PagedMenu />);
+ const menu = layOut();
+ screen.getByTestId('Two').focus();
+ fireEvent.keyDown(menu, {key: 'PageDown'});
+ expect(screen.getByTestId('Four')).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'PageDown'});
+ expect(screen.getByTestId('Six')).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'PageDown'});
+ expect(screen.getByTestId('Six')).toHaveFocus();
+ });
+
+ it('PageUp mirrors PageDown', () => {
+ render(<PagedMenu />);
+ const menu = layOut();
+ screen.getByTestId('Two').focus();
+ fireEvent.keyDown(menu, {key: 'PageUp'});
+ expect(screen.getByTestId('One')).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'PageUp'});
+ expect(screen.getByTestId('One')).toHaveFocus();
+ });
+
+ it('PageDown in a list that does not scroll acts as End', () => {
+ render(<PagedMenu />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('One').focus();
+ fireEvent.keyDown(menu, {key: 'PageDown'});
+ expect(screen.getByTestId('Six')).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'PageDown'});
+ expect(screen.getByTestId('Six')).toHaveFocus();
+ });
+
+ it('leaves PageDown to the host when paging is off', () => {
+ render(<PagedMenu hasPaging={false} />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('One').focus();
+ const event = fireEvent.keyDown(menu, {key: 'PageDown'});
+ expect(screen.getByTestId('One')).toHaveFocus();
+ // Not consumed: fireEvent returns false when preventDefault was called.
+ expect(event).toBe(true);
+ });
+});
diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.ts
index c72c5808c1..528e8398f3 100644
--- a/packages/core/src/hooks/useListFocus.ts
+++ b/packages/core/src/hooks/useListFocus.ts
@@ -85,6 +85,15 @@ export interface UseListFocusOptions {
*/
hasHomeEnd?: boolean;
+ /**
+ * Whether PageDown/PageUp page through a list that scrolls: PageDown moves
+ * to the last enabled item fully visible in the container, and pressed
+ * there again one viewport further; PageUp is the mirror. Neither wraps.
+ * In a list that does not scroll they act as End/Home.
+ * @default false
+ */
+ hasPaging?: boolean;
+
/**
* Roving-tabindex ownership. When true, the hook manages a single tab stop
* across the items: exactly one enabled item carries `tabindex="0"` and the
@@ -324,6 +333,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
onEscape,
orientation = 'vertical',
hasHomeEnd = true,
+ hasPaging = false,
hasRovingTabIndex = false,
hasCaretGuard = false,
} = options;
@@ -530,6 +540,86 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
return false;
}, [getItems, findEnabledIndex, focusIndex]);
+ /**
+ * PageDown / PageUp: move to the last / first enabled item fully
+ * visible in the scrolling container. Pressed there again, scroll one
+ * viewport further and land on the last / first item then visible. Never
+ * wraps; at the end of the list it stays on the last enabled item.
+ */
+ const focusPage = useCallback(
+ (direction: 1 | -1) => {
+ const container = listRef.current;
+ const items = getItems();
+ if (!container || items.length === 0) {
+ return;
+ }
+ const currentIndex = getCurrentIndex();
+ const enabledIndices = items
+ .map((item, index) => (isItemDisabled(item) ? -1 : index))
+ .filter(index => index !== -1);
+ if (enabledIndices.length === 0) {
+ return;
+ }
+ const edgeVisible = (): number => {
+ const bounds = container.getBoundingClientRect();
+ const visible = enabledIndices.filter(index => {
+ const rect = items[index].getBoundingClientRect();
+ return rect.top >= bounds.top - 1 && rect.bottom <= bounds.bottom + 1;
+ });
+ if (visible.length === 0) {
+ return -1;
+ }
+ return direction === 1 ? visible[visible.length - 1] : visible[0];
+ };
+ const isAhead = (index: number): boolean =>
+ currentIndex === -1 ||
+ (direction === 1 ? index > currentIndex : index < currentIndex);
+ if (currentIndex === -1 && direction === -1) {
+ focusFirst();
+ return;
+ }
+ let target = edgeVisible();
+ if (target === -1 || !isAhead(target)) {
+ // Already at the visible edge: one viewport further.
+ const before = container.scrollTop;
+ container.scrollTop = before + direction * container.clientHeight;
+ target = edgeVisible();
+ if (target === -1 || !isAhead(target)) {
+ // No usable geometry (or nothing moved): step by the number of rows
+ // a viewport shows, never wrapping.
+ const pageSize = Math.max(
+ 1,
+ enabledIndices.filter(index => {
+ const bounds = container.getBoundingClientRect();
+ const rect = items[index].getBoundingClientRect();
+ return (
+ rect.height > 0 &&
+ rect.top >= bounds.top - 1 &&
+ rect.bottom <= bounds.bottom + 1
+ );
+ }).length,
+ );
+ const position = enabledIndices.indexOf(currentIndex);
+ const from =
+ position === -1
+ ? direction === 1
+ ? -1
+ : enabledIndices.length
+ : position;
+ const next = Math.max(
+ 0,
+ Math.min(enabledIndices.length - 1, from + direction * pageSize),
+ );
+ target = enabledIndices[next];
+ }
+ }
+ if (target !== -1 && target !== currentIndex) {
+ focusIndex(items, target);
+ }
+ },
+ [getItems, getCurrentIndex, isItemDisabled, focusIndex, focusFirst],
+ );
+
/**
* Keep the roving stop pointing at whatever ended up focused (e.g. a click
* or programmatic focus) so the next Tab behaves correctly. No-op unless
@@ -596,8 +686,10 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
const isPrev = prevKeys.includes(e.key);
const isHome = hasHomeEnd && e.key === 'Home';
const isEnd = hasHomeEnd && e.key === 'End';
+ const isPageDown = hasPaging && e.key === 'PageDown';
+ const isPageUp = hasPaging && e.key === 'PageUp';
- if (!isNext && !isPrev && !isHome && !isEnd) {
+ if (!isNext && !isPrev && !isHome && !isEnd && !isPageDown && !isPageUp) {
return;
}
@@ -631,6 +723,10 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
focusFirst();
} else if (isEnd) {
focusLast();
+ } else if (isPageDown) {
+ focusPage(1);
+ } else if (isPageUp) {
+ focusPage(-1);
}
e.preventDefault();
@@ -641,11 +737,13 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
wrap,
orientation,
hasHomeEnd,
+ hasPaging,
hasCaretGuard,
findEnabledIndex,
focusIndex,
focusFirst,
focusLast,
+ focusPage,
onEscape,
ownsEvent,
],
diff --git a/packages/core/src/hooks/useTypeahead.test.tsx b/packages/core/src/hooks/useTypeahead.test.tsx
index 51c527d87f..348eaa384c 100644
--- a/packages/core/src/hooks/useTypeahead.test.tsx
+++ b/packages/core/src/hooks/useTypeahead.test.tsx
@@ -256,4 +256,55 @@ describe('useTypeahead', () => {
expect(handled).toBe(true);
expect(onMatch).toHaveBeenCalledWith(0);
});
+
+ it('ignores a key that is part of an input method composition', () => {
+ const {onMatch, api} = setup();
+ const handled = api.onKeyDown(
+ new KeyboardEvent('keydown', {key: 'b', isComposing: true}),
+ );
+ expect(handled).toBe(false);
+ expect(onMatch).not.toHaveBeenCalled();
+ });
+
+ it('ignores a composing Space even mid-buffer', () => {
+ const {onMatch, api} = setup();
+ api.onKeyDown(key('a'));
+ const handled = api.onKeyDown(
+ new KeyboardEvent('keydown', {key: ' ', isComposing: true}),
+ );
+ expect(handled).toBe(false);
+ expect(onMatch).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores Control and Command chords on a letter', () => {
+ const {onMatch, api} = setup();
+ expect(
+ api.onKeyDown(new KeyboardEvent('keydown', {key: 'b', ctrlKey: true})),
+ ).toBe(false);
+ expect(
+ api.onKeyDown(new KeyboardEvent('keydown', {key: 'b', metaKey: true})),
+ ).toBe(false);
+ expect(onMatch).not.toHaveBeenCalled();
+ });
+
+ it('leaves the highlight where it was when nothing matches', () => {
+ const {onMatch, api} = setup({current: 1});
+ const handled = api.onKeyDown(key('z'));
+ // The key is still consumed — it is typing, not a shortcut for the host.
+ expect(handled).toBe(true);
+ expect(onMatch).not.toHaveBeenCalled();
+ });
+
+ it('reads a React synthetic event’s isComposing through nativeEvent', () => {
+ const {onMatch, api} = setup();
+ const synthetic = {
+ key: 'b',
+ ctrlKey: false,
+ metaKey: false,
+ altKey: false,
+ nativeEvent: {isComposing: true},
+ } as unknown as React.KeyboardEvent;
+ expect(api.onKeyDown(synthetic)).toBe(false);
+ expect(onMatch).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/core/src/hooks/useTypeahead.ts b/packages/core/src/hooks/useTypeahead.ts
index 0e40d6e26f..ee523bcf12 100644
--- a/packages/core/src/hooks/useTypeahead.ts
+++ b/packages/core/src/hooks/useTypeahead.ts
@@ -74,11 +74,22 @@ function isPrintableCharacter(e: React.KeyboardEvent | KeyboardEvent): boolean {
// which sets ctrlKey on Windows and Linux.
!e.ctrlKey &&
!e.metaKey &&
+ // A key that is part of an input method's composition is the IME's, not
+ // a jump. React's synthetic event surfaces `isComposing` too.
+ !isComposingKey(e) &&
// A lone space is used for activation in menus, not typeahead-from-empty.
e.key !== ' '
);
}
+function isComposingKey(e: React.KeyboardEvent | KeyboardEvent): boolean {
+ if ((e as {isComposing?: boolean}).isComposing === true) {
+ return true;
+ }
+ const native = (e as {nativeEvent?: {isComposing?: boolean}}).nativeEvent;
+ return native?.isComposing === true;
+}
+
/**
* First-character ("type-ahead") search for a collection.
*
@@ -144,6 +155,7 @@ export function useTypeahead(options: UseTypeaheadOptions): UseTypeaheadReturn {
e.key === ' ' &&
!e.ctrlKey &&
!e.metaKey &&
+ !isComposingKey(e) &&
bufferRef.current.length > 0;
if (!isPrintableCharacter(e) && !isSpaceMidType) {
return false;