An open source design system that's fully customizable and agent ready
TypeScript
fix(contextmenu): reliable Escape dismissal + focus restore (#3361)
Cindy Zhang6d03942046bd
diff --git a/.changeset/contextmenu-escape-focus-restore.md b/.changeset/contextmenu-escape-focus-restore.mdnew file mode 100644index 0000000000..6597086fa7--- /dev/null+++ b/.changeset/contextmenu-escape-focus-restore.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] ContextMenu: Escape now closes the menu even when it was opened without auto-focus (e.g. table row menus), via a document-level Escape listener instead of one that only fires when focus is inside the menu. Focus is also restored to the previously focused element on close, instead of falling to `<body>`. Escape during IME composition is ignored (#3343).+@cixzhangdiff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex b83e37a918..e11cac49ec 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -71,6 +71,48 @@ describe('ContextMenu', () => {expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();});+ it('closes on Escape even when opened without auto-focus', () => {+ render(+ <ContextMenu items={[{label: 'Item 1'}]} hasAutoFocus={false}>+ <div>Right-click me</div>+ </ContextMenu>,+ );++ fireEvent.contextMenu(screen.getByText('Right-click me'));+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();+ // Focus is not inside the menu, so the Escape path must be document-level.+ fireEvent.keyDown(document, {key: 'Escape'});+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();+ });++ it('ignores Escape during IME composition', () => {+ render(+ <ContextMenu items={[{label: 'Item 1'}]} hasAutoFocus={false}>+ <div>Right-click me</div>+ </ContextMenu>,+ );++ fireEvent.contextMenu(screen.getByText('Right-click me'));+ fireEvent.keyDown(document, {key: 'Escape', isComposing: true});+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();+ });++ it('restores focus to the trigger on close', () => {+ render(+ <ContextMenu items={[{label: 'Item 1'}]} hasAutoFocus={false}>+ <button type="button">Right-click me</button>+ </ContextMenu>,+ );++ const trigger = screen.getByRole('button', {name: 'Right-click me'});+ trigger.focus();+ expect(trigger).toHaveFocus();++ fireEvent.contextMenu(trigger);+ fireEvent.keyDown(document, {key: 'Escape'});+ expect(trigger).toHaveFocus();+ });+it('prevents default context menu on right-click', () => {render(<ContextMenu items={[{label: 'Item 1'}]}>diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 156086d55c..e55407c285 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -138,9 +138,7 @@ interface ContextMenuCompoundProps extends ContextMenuBaseProps {menuContent: ReactNode;}-export type ContextMenuProps =- | ContextMenuDataProps- | ContextMenuCompoundProps;+export type ContextMenuProps = ContextMenuDataProps | ContextMenuCompoundProps;// =============================================================================// ContextMenu@@ -188,6 +186,9 @@ export function ContextMenu({const menuId = useId();const positionRef = useRef({x: 0, y: 0});+ // Element focused before the menu opened, restored when it closes so focus+ // does not fall to <body> after Escape or outside-click dismissal.+ const triggerFocusRef = useRef<HTMLElement | null>(null);const [isOpen, setIsOpen] = useState(false);@@ -196,6 +197,12 @@ export function ContextMenu({onHide: useCallback(() => {setIsOpen(false);onOpenChange?.(false);+ // Restore focus to the element that was focused before opening.+ const toRestore = triggerFocusRef.current;+ triggerFocusRef.current = null;+ if (toRestore && document.contains(toRestore)) {+ toRestore.focus();+ }}, [onOpenChange]),onShow: useCallback(() => {setIsOpen(true);@@ -238,6 +245,31 @@ export function ContextMenu({};}, [isOpen, closeMenu, listRef]);+ // Dismiss on Escape from anywhere while open. The menu div's own onKeyDown+ // only fires when focus is inside the menu, which never happens when the+ // menu is opened with hasAutoFocus={false} (e.g. table context menus), so a+ // document-level listener is required for a reliable Escape path. Guards+ // against IME composition-cancel.+ useEffect(() => {+ if (!isOpen) {+ return;+ }+ const handleEscape = (e: KeyboardEvent) => {+ if (e.key !== 'Escape') {+ return;+ }+ if (e.isComposing || e.keyCode === 229) {+ return;+ }+ e.preventDefault();+ closeMenu();+ };+ document.addEventListener('keydown', handleEscape);+ return () => {+ document.removeEventListener('keydown', handleEscape);+ };+ }, [isOpen, closeMenu]);+const listKeyDown = useCallback((e: React.KeyboardEvent) => {if (e.key === 'Enter' || e.key === ' ') {@@ -260,6 +292,12 @@ export function ContextMenu({}e.preventDefault();positionRef.current = {x: e.clientX, y: e.clientY};+ // Remember the element focused before opening so we can restore it on+ // close (Escape or outside-click), instead of dropping focus to <body>.+ triggerFocusRef.current =+ document.activeElement instanceof HTMLElement+ ? document.activeElement+ : (e.currentTarget as HTMLElement);layer.show();if (hasAutoFocus) {requestAnimationFrame(() => focusFirst());