Skip to content

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

TypeScript

[Component Audit] ContextMenu: preserve nested layers and trigger events (#7167)

Cindy Zhang5c3d4582182d
diff --git a/.changeset/context-menu-layer-dismissal.md b/.changeset/context-menu-layer-dismissal.md
new file mode 100644
index 0000000000..f5a8e52086
--- /dev/null
+++ b/.changeset/context-menu-layer-dismissal.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] ContextMenu: preserve nested overlays on Escape and compose trigger event handlers
+
+@cixzhang
diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx
index 369ed0dd64..45abc4a023 100644
--- a/apps/storybook/stories/ContextMenu.stories.tsx
+++ b/apps/storybook/stories/ContextMenu.stories.tsx
@@ -87,6 +87,46 @@ export const Default: Story = {
),
};
+export const PointerPresentation: Story = {
+ name: 'Presentation / pointer menu',
+ tags: ['visual-theme-matrix'],
+ render: () => (
+ <ContextMenu
+ data-testid="pointer-context-menu"
+ label="Document actions"
+ items={[
+ {label: 'Edit', icon: PencilIcon, onClick: () => {}},
+ {
+ label: 'Duplicate',
+ icon: DocumentDuplicateIcon,
+ onClick: () => {},
+ },
+ {type: 'divider'},
+ {
+ label: 'Delete',
+ icon: TrashIcon,
+ variant: 'destructive',
+ onClick: () => {},
+ },
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>
+ Right-click for document actions
+ </div>
+ </ContextMenu>
+ ),
+ play: async ({canvasElement}) => {
+ canvasElement
+ .querySelector('[data-testid="pointer-context-menu"]')
+ ?.dispatchEvent(
+ new MouseEvent('contextmenu', {
+ bubbles: true,
+ clientX: 40,
+ clientY: 40,
+ }),
+ );
+ },
+};
+
export const WithIcons: Story = {
render: () => (
<ContextMenu
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 34a120b91e..12c6edf151 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -16,6 +16,7 @@ applies_to:
packages/core/src/Dialog/,
packages/lab/src/Drawer/,
packages/core/src/DropdownMenu/,
+ packages/core/src/ContextMenu/,
packages/core/src/Tooltip/,
packages/core/src/HoverCard/,
packages/core/src/Toast/,
@@ -34,6 +35,7 @@ verified_by:
packages/core/src/Layer/layerDismissalInvariants.test.tsx,
packages/core/src/Popover/Popover.test.tsx,
packages/core/src/DropdownMenu/DropdownMenu.test.tsx,
+ packages/core/src/ContextMenu/ContextMenu.test.tsx,
packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx,
packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,
packages/core/src/hooks/useFocusTrap.test.tsx,
@@ -238,8 +240,8 @@ contract. The current shared stack registers present layers with `close` or
active-cycle registration sequence. `useFocusTrap` adapts an active trap with `onEscape` into
that stack.
-Tooltip, HoverCard, Dialog, Lab Drawer, Popover, DropdownMenu, Lightbox,
-MobileNav, BottomSheet, and BottomSheetSwitcher all register with the shared
+Tooltip, HoverCard, Dialog, Lab Drawer, Popover, DropdownMenu, ContextMenu,
+Lightbox, MobileNav, BottomSheet, and BottomSheetSwitcher all register with the shared
stack. Tooltip and HoverCard report current DOM presence; Popover and
DropdownMenu register through `useFocusTrap`; Dialog, Lightbox, MobileNav,
BottomSheet, BottomSheetSwitcher, and Lab Drawer additionally ask
diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.md
index af6a5410c4..ec45f70e65 100644
--- a/docs/families/overlay-dismissal.md
+++ b/docs/families/overlay-dismissal.md
@@ -18,6 +18,7 @@ verified_by:
packages/lab/src/Drawer/Drawer.test.tsx,
packages/core/src/hooks/useFocusTrap.test.tsx,
packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,
+ packages/core/src/ContextMenu/ContextMenu.test.tsx,
]
members:
[
@@ -201,12 +202,12 @@ this record's current membership snapshot must be updated with it.
| Components or surface | Adoption | Current deviation or limitation |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Dialog, AlertDialog, Popover, DropdownMenu root, MoreMenu, Lightbox, MobileNav, Lab Drawer | shared owner | none |
+| Dialog, AlertDialog, Popover, DropdownMenu root, ContextMenu, MoreMenu, Lightbox, MobileNav, Lab Drawer | shared owner | none |
| Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers |
| Focus traps with `onEscape` | shared owner through `useFocusTrap` | They provide DOM containment, not descendant depth |
| BreadcrumbItem, ChatComposerInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, Selector, MultiSelector, PowerSearch, BaseTypeahead, Typeahead, Tokenizer, SideNavHeading, SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table, Lab TourStep, Lab ChatEmojiPicker | shared owner through `usePopover` or a composed Popover owner | Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state |
| BottomSheet, BottomSheetSwitcher | shared owner | none |
-| CommandPalette, ContextMenu, DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |
+| CommandPalette, DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |
The rows marked partial or local are current adoption gaps against FR1. They are
not approved exceptions. Migration must preserve each component's existing focus,
@@ -214,12 +215,12 @@ modality, positioning, outside-dismissal, and open-state contracts.
## Verification map
-| Contract | Verification | Representative members and states | Mutation or failure expectation |
-| ------------------ | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
-| FR1, FR2, FR4, FR5 | `useLayerDismissal.test.tsx`; `BottomSheetSwitcher.test.tsx` | synthetic provider depth, same-DOM containment, non-modal switcher nesting, unrelated, blocking, content-handled, present/absent | Removing depth, presence filtering, or event deferral sends Escape to the wrong surface |
-| FR2, FR3, FR4, FR6 | `layerDismissalInvariants.test.tsx` | nested same-DOM Dialogs, Lightbox over Dialog, Dialog in BottomSheet, platform cancel, IME | One request closes two surfaces, closes a host before its child, or dismisses during composition |
-| FR1, FR2, FR3, FR7 | `layerDismissalFamilies.test.tsx` | Dialog, Lightbox, MobileNav, BottomSheet, Tooltip, HoverCard; controlled and blocking states | A family bypasses the stack, a lower member handles a request, or controlled ownership is ignored |
-| FR1 | `useFocusTrap.test.tsx` | active, nested, and deactivated traps with `onEscape` | A dismissible trap stays off the shared stack or nested traps respond together |
+| Contract | Verification | Representative members and states | Mutation or failure expectation |
+| ------------------ | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
+| FR1, FR2, FR4, FR5 | `useLayerDismissal.test.tsx`; `BottomSheetSwitcher.test.tsx`; `ContextMenu.test.tsx` | synthetic provider depth, same-DOM containment, non-modal switcher nesting, ContextMenu nested layers, unrelated, blocking, content-handled, present/absent | Removing depth, presence filtering, or event deferral sends Escape to the wrong surface |
+| FR2, FR3, FR4, FR6 | `layerDismissalInvariants.test.tsx` | nested same-DOM Dialogs, Lightbox over Dialog, Dialog in BottomSheet, platform cancel, IME | One request closes two surfaces, closes a host before its child, or dismisses during composition |
+| FR1, FR2, FR3, FR7 | `layerDismissalFamilies.test.tsx` | Dialog, Lightbox, MobileNav, BottomSheet, Tooltip, HoverCard; controlled and blocking states | A family bypasses the stack, a lower member handles a request, or controlled ownership is ignored |
+| FR1 | `useFocusTrap.test.tsx` | active, nested, and deactivated traps with `onEscape` | A dismissible trap stays off the shared stack or nested traps respond together |
## Decision links
diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjs
index 2ca69e913d..3cf905c345 100644
--- a/packages/core/src/ContextMenu/ContextMenu.doc.mjs
+++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs
@@ -143,6 +143,12 @@ export const docs = {
'When true, right-click shows the native browser context menu instead.',
default: 'false',
},
+ {
+ name: 'triggerXstyle',
+ type: 'StyleXStyles | StyleXStyles[]',
+ description:
+ 'Styles applied to the trigger wrapper. Accepts `stylex.create()` values, not inline style objects.',
+ },
{
name: 'triggerAs',
type: "'div' | 'span'",
diff --git a/packages/core/src/ContextMenu/ContextMenu.spec.md b/packages/core/src/ContextMenu/ContextMenu.spec.md
index 7f1081c4d3..00182e292b 100644
--- a/packages/core/src/ContextMenu/ContextMenu.spec.md
+++ b/packages/core/src/ContextMenu/ContextMenu.spec.md
@@ -26,6 +26,7 @@ architecture:
architecture:component-theming-surface,
architecture:interaction-modality,
architecture:layer-runtime,
+ architecture:public-component-api,
]
contributing: []
system_specs: []
@@ -36,17 +37,16 @@ system_specs: []
## Intent
ContextMenu presents actions for a caller-provided region in either a
-cursor-positioned pointer menu or a BottomSheet-hosted touch action list. This
-draft records current consumer anatomy, presentation-specific ownership, and
-theming reachability without changing runtime behavior, styling, targets, or
-public API.
+cursor-positioned pointer menu or a BottomSheet-hosted touch action list. The
+record describes current consumer anatomy, presentation-specific ownership, and
+theming reachability.
## Compatibility and migration
-- Released default preserved: `yes`
-- Compatibility class: additive documentation only; runtime, DOM, styling,
- targets, and public API remain unchanged
-- Controlled/uncontrolled behavior: unchanged
+- Released default: `popover`
+- Compatibility class: compatible behavior correction; public API, defaults,
+ DOM shape, styling, and targets are preserved
+- Controlled/uncontrolled behavior: internally managed open state
- Migration decision: none
Consumer migration instructions belong in consumer docs and release notes.
@@ -81,16 +81,17 @@ 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 |
-| 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 |
+| 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 | Current behavior; verified |
+| 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 | Current inventory; verified |
+| 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 | Current delegation; verified |
+| 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 | Current branches; verified |
+| 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 keep their existing behavior. | `module:DropdownMenu/useMenuPress`; `ContextMenu.test.tsx` press model suite | Current module projection; 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. Right-click, Shift+F10, long-press, and `context-menu` target placement all use that box. | `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; owner decision pending |
+| 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. | Current source and tests; shared `useListFocus` and `useTypeahead` suites | Proposed; verified in jsdom; owner decision pending |
+| FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | Current family projection; verified in jsdom |
### Allowed variation
@@ -115,19 +116,21 @@ Consumer props, content modes, and presentation policy remain documented in
### Transformation and precedence order
-- No new presentation-resolution, cursor-position, long-press, item-rendering,
- or styling precedence rule is introduced.
+- Presentation resolution, cursor positioning, long-press handling, item
+ rendering, and styling keep their current precedence.
### Performance and resources
-- No new loading, listener, measurement, or render constraint is introduced.
+- The component introduces no separate loading, listener, measurement, or render
+ constraint beyond the owners named above.
## Accessibility contract
-This draft does not change ContextMenu's menu and dialog naming, keyboard
-invocation, long-press path, keyboard navigation, item semantics, focus
-return, or dismissal ordering. While a pointer is held in the pointer menu,
-the highlight is DOM focus per `module:DropdownMenu/useMenuPress` AR1.
+ContextMenu keeps its menu and dialog naming, keyboard invocation, long-press
+path, keyboard navigation, item semantics, focus return, and presentation-specific
+dismissal behavior. Pointer-menu Escape requests participate in the shared layer
+stack; while a pointer is held in the pointer menu, the highlight is DOM focus per
+`module:DropdownMenu/useMenuPress` AR1.
- **AR1 — An inline trigger keeps its semantics.** `triggerAs` changes the
Trigger area's element and box only; it carries no role or `aria-haspopup`
@@ -185,27 +188,28 @@ anchor is positioning infrastructure rather than consumer anatomy.
- `architecture:component-theming-surface` owns anatomy qualification, local
target mapping, presentation-specific rows, and delegation rules.
- `architecture:interaction-modality` owns the shared right-click, keyboard,
- long-press, pointer, touch, and adaptive-presentation boundaries; this draft
- changes none of them.
+ long-press, pointer, touch, and adaptive-presentation boundaries.
- `architecture:layer-runtime` owns the current context-mode `useLayer` host and
- cursor-anchor positioning. ContextMenu currently retains local outside-click
- and Escape listeners; touch hosting delegates to BottomSheet.
-- `family:overlay-dismissal` owns shared Escape and platform-close ordering and
- records ContextMenu and BottomSheet as current local-only adoption gaps. This
- anatomy backfill does not migrate either path.
+ cursor-anchor positioning. ContextMenu retains local outside-click handling and
+ joins shared Escape ordering through `useLayerDismissal`; touch hosting delegates
+ to BottomSheet.
+- `family:overlay-dismissal` owns shared Escape and platform-close ordering.
+ ContextMenu's pointer presentation is a shared-stack adopter; the touch
+ presentation delegates dismissal to BottomSheet, which is also a shared-stack
+ owner.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---------------------------- |
-| FR1, FR4 | `ContextMenu.test.tsx` pointer, long-press, bottom-sheet, adaptive, compound, and drill-in suites | Pointer data/compound and touch data/compound | Collapsing presentation-specific parts or content owners fails structure, role, or behavior tests. | `audit:ContextMenu/anatomy` |
-| FR2 | ContextMenu target tests, source inspection, and theming target inventories | Pointer and touch menu surfaces | Moving `context-menu` to the trigger or removing it from a painted branch fails evidence. | `audit:ContextMenu/theming` |
-| 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` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---------------------------- |
+| FR1, FR4 | `ContextMenu.test.tsx` pointer, long-press, bottom-sheet, adaptive, compound, and drill-in suites | Pointer data/compound and touch data/compound | Collapsing presentation-specific parts or content owners fails structure, role, or behavior tests. | `audit:ContextMenu/anatomy` |
+| FR2 | ContextMenu target tests, source inspection, and theming target inventories | Pointer and touch menu surfaces | Moving `context-menu` to the trigger or removing it from a painted branch fails evidence. | `audit:ContextMenu/theming` |
+| 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` nested-layer case and current layer/dismissal architecture records | Outside click, Escape, nested context layers, sheet | A Pointer menu bypassing the shared stack or dismissing with its nested child fails. | `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` |
## Decision log
@@ -222,17 +226,11 @@ doors of a context menu without becoming a block that breaks the paragraph.
`triggerAs` renders the Trigger area as a `span`. The default `div` and its
`position: relative` are unchanged.
-Rejected: a `triggerXstyle` recipe — cannot change the element, and a
-`display: inline` div inside a `<p>` is invalid HTML.
-
-Rejected: a third `contents` value, a span with `display: contents`. A
-box-less wrapper has no rect to measure the cursor anchor from, so the anchor
-falls back to the nearest positioned ancestor — which in running prose is
-usually the page. A mouse user gets the menu at the pointer and a keyboard
-user pressing Shift+F10 gets it at the page corner, and the keyboard path is
-the one with no way around it. A `span` is inline, owns a box, measures
-correctly, and is invisible to layout in every way the prose case cares
-about.
+Rejected: styling a block `div` as inline because it remains invalid inside a
+`<p>`.
+
+Rejected: `display: contents` because a box-less wrapper has no rect for pointer
+or keyboard anchoring.
## Open questions
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index 2907da8c3f..e81bfc3791 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -8,6 +8,8 @@
* SYNC: When ContextMenu.tsx changes, update tests to match new behavior
*/
+import {useRef, useState} from 'react';
+import {createPortal} from 'react-dom';
import {describe, it, expect, vi, beforeEach} from 'vitest';
import {render, screen, fireEvent, act, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -23,6 +25,32 @@ import {
} from './index';
import {DropdownMenuItem} from '../DropdownMenu/DropdownMenuItem';
import {Divider} from '../Divider';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
+
+function NestedDismissibleLayer({onDismiss}: {onDismiss: () => void}) {
+ const [isOpen, setIsOpen] = useState(true);
+ const containerRef = useRef<HTMLButtonElement>(null);
+
+ useLayerDismissal({
+ isActive: isOpen,
+ onDismiss: () => {
+ setIsOpen(false);
+ onDismiss();
+ },
+ getContainer: () => containerRef.current,
+ });
+
+ // Portaled outside the menu's DOM, so only the layer depth ContextMenu
+ // provides can rank it above the menu.
+ return isOpen
+ ? createPortal(
+ <button ref={containerRef} type="button">
+ Nested layer
+ </button>,
+ document.body,
+ )
+ : null;
+}
beforeEach(() => {
HTMLDialogElement.prototype.showModal = vi.fn(function (
@@ -149,6 +177,56 @@ describe('ContextMenu', () => {
expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
});
+ it('composes the consumer context-menu handler with menu opening', () => {
+ const onContextMenu = vi.fn();
+ render(
+ <ContextMenu items={[{label: 'Item 1'}]} onContextMenu={onContextMenu}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ expect(onContextMenu).toHaveBeenCalledOnce();
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledOnce();
+ });
+
+ it('keeps component-owned opening when a consumer prevents default', () => {
+ render(
+ <ContextMenu
+ items={[{label: 'Item 1'}]}
+ onContextMenu={event => event.preventDefault()}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledOnce();
+ });
+
+ it('lets a nested layer consume Escape before the context menu', () => {
+ const onNestedDismiss = vi.fn();
+ render(
+ <ContextMenu
+ menuContent={<NestedDismissibleLayer onDismiss={onNestedDismiss} />}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ const nestedLayer = screen.getByRole('button', {
+ name: 'Nested layer',
+ hidden: true,
+ });
+ nestedLayer.focus();
+ fireEvent.keyDown(nestedLayer, {key: 'Escape'});
+
+ expect(onNestedDismiss).toHaveBeenCalledOnce();
+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalledOnce();
+ });
+
it('opens the real menu content in a BottomSheet when requested', async () => {
render(
<ContextMenu
@@ -393,6 +471,60 @@ describe('ContextMenu', () => {
}
});
+ it('composes consumer touch handlers with long-press detection', () => {
+ vi.useFakeTimers();
+ try {
+ const onTouchStart = vi.fn();
+ render(
+ <ContextMenu
+ items={[{label: 'Item 1'}]}
+ data-testid="ctx"
+ onTouchStart={onTouchStart}>
+ <div>Long-press me</div>
+ </ContextMenu>,
+ );
+
+ fireEvent.touchStart(screen.getByTestId('ctx'), {
+ touches: [{clientX: 20, clientY: 20}],
+ });
+ expect(onTouchStart).toHaveBeenCalledOnce();
+
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('clears a pending long-press when a consumer prevents default on touch end', () => {
+ vi.useFakeTimers();
+ try {
+ render(
+ <ContextMenu
+ items={[{label: 'Item 1'}]}
+ data-testid="ctx"
+ onTouchEnd={event => event.preventDefault()}>
+ <div>Long-press me</div>
+ </ContextMenu>,
+ );
+
+ const trigger = screen.getByTestId('ctx');
+ fireEvent.touchStart(trigger, {
+ touches: [{clientX: 20, clientY: 20}],
+ });
+ fireEvent.touchEnd(trigger);
+
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('suppresses native text selection on the long-press trigger', () => {
const source = readFileSync(
'packages/core/src/ContextMenu/ContextMenu.tsx',
@@ -1103,7 +1235,6 @@ describe('ContextMenuGroup', () => {
// Three public surfaces alias this component at once. An alias that
// re-exports without the semantics would pass a render test and fail a
// screen reader.
- const user = userEvent.setup();
render(
<ContextMenu
menuContent={
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index 5dee00383b..b86a2d8304 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -3,8 +3,8 @@
/**
* @file ContextMenu.tsx
- * @input Uses React, StyleX, useLayer, BottomSheet, useListFocus, and the
- * shared menu-presentation resolver
+ * @input Uses React, StyleX, useLayer, shared layer dismissal, BottomSheet,
+ * useListFocus, and the shared menu-presentation resolver
* @output Exports ContextMenu with cursor-popover and touch-sheet presentations
* @position Core implementation; consumed by index.ts
*
@@ -50,6 +50,8 @@ import {Button} from '../Button';
import {Heading} from '../Heading';
import {Icon} from '../Icon';
import {useLayer} from '../Layer/useLayer';
+import {LayerDepthProvider} from '../Layer/LayerDepthContext';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {MenuBottomSheetActionList} from '../DropdownMenu/MenuBottomSheetActionList';
import {renderDropdownItems} from '../DropdownMenu/renderDropdownItems';
import {
@@ -77,7 +79,7 @@ import {
easeVars,
shadowVars,
} from '../theme/tokens.stylex';
-import {mergeProps, isImeKeyEvent, rtlStyles} from '../utils';
+import {mergeProps, rtlStyles} from '../utils';
import type {BaseProps} from '../BaseProps';
import type {StyleXStyles} from '../theme/types';
import {themeProps} from '../utils/themeProps';
@@ -313,6 +315,11 @@ export function ContextMenu({
style,
xstyle,
triggerXstyle,
+ onContextMenu: onContextMenuProp,
+ onTouchStart: onTouchStartProp,
+ onTouchMove: onTouchMoveProp,
+ onTouchEnd: onTouchEndProp,
+ onTouchCancel: onTouchCancelProp,
'data-testid': testId,
...rest
}: ContextMenuProps) {
@@ -346,7 +353,6 @@ export function ContextMenu({
// 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 sheetHeadingRef = useRef<HTMLHeadingElement>(null);
const [isOpen, setIsOpen] = useState(false);
const [submenuPath, setSubmenuPath] = useState<ContextMenuItemData[]>([]);
@@ -406,15 +412,14 @@ export function ContextMenu({
[closeMenu],
);
- useEffect(() => {
- if (!isOpen || submenuPath.length === 0) {
- return;
- }
- const frame = requestAnimationFrame(() => {
- sheetHeadingRef.current?.focus({preventScroll: true});
- });
- return () => cancelAnimationFrame(frame);
- }, [isOpen, submenuPath.length]);
+ const setSheetHeadingRef = useCallback(
+ (node: HTMLHeadingElement | null) => {
+ if (node && isOpen && submenuPath.length > 0) {
+ node.focus({preventScroll: true});
+ }
+ },
+ [isOpen, submenuPath.length],
+ );
const {
listRef,
@@ -429,7 +434,14 @@ export function ContextMenu({
// Menus wrap from the last row to the first and back.
wrap: true,
hasPaging: true,
- onEscape: closeMenu,
+ });
+
+ // Join the shared stack so an Escape press dismisses exactly one top-most
+ // surface. BottomSheet owns its own dismissal path.
+ useLayerDismissal({
+ isActive: isOpen && !usesBottomSheet,
+ onDismiss: closeMenu,
+ getContainer: () => listRef.current,
});
// Typeahead over the enabled menu items, matched on each row's LABEL alone.
@@ -465,32 +477,6 @@ export function ContextMenu({
};
}, [isOpen, closeMenu, listRef, usesBottomSheet]);
- // Dismiss on Escape from anywhere while open. The menu div's own onKeyDown
- // only fires when focus is inside the menu; a document-level listener is
- // kept as a reliable fallback Escape path (e.g. if focus has moved out of
- // the menu). Guards against IME composition-cancel.
- useEffect(() => {
- if (!isOpen || usesBottomSheet) {
- return;
- }
- const handleEscape = (e: KeyboardEvent) => {
- if (e.key !== 'Escape') {
- return;
- }
- if (isImeKeyEvent(e)) {
- // Ignore Escape that is committing/cancelling an IME composition;
- // see utils/ime.ts for why.
- return;
- }
- e.preventDefault();
- closeMenu();
- };
- document.addEventListener('keydown', handleEscape);
- return () => {
- document.removeEventListener('keydown', handleEscape);
- };
- }, [isOpen, closeMenu, usesBottomSheet]);
-
const listKeyDown = useCallback(
(e: React.KeyboardEvent) => {
// A submenu flyout renders inline inside this menu; its key events bubble
@@ -601,7 +587,12 @@ export function ContextMenu({
// held long enough (see useLongPress for timer/move-cancel/cleanup logic).
// The hook also returns the imperative start/moveTo/cancel API the menu press
// model drives; only its four touch handlers belong on the trigger element.
- const longPress = useLongPress({
+ const {
+ onTouchStart: handleLongPressTouchStart,
+ onTouchMove: handleLongPressTouchMove,
+ onTouchEnd: handleLongPressTouchEnd,
+ onTouchCancel: handleLongPressTouchCancel,
+ } = useLongPress({
disabled: isDisabled,
onLongPress: useCallback(
(point: {x: number; y: number}) => {
@@ -616,6 +607,45 @@ export function ContextMenu({
),
});
+ // ContextMenu owns invocation and long-press cleanup. Consumer handlers are
+ // notified too, but preventing their default does not cancel component-owned
+ // behavior that the public API does not promise as cancelable.
+ const handleTriggerContextMenu = useCallback(
+ (event: React.MouseEvent<HTMLElement>) => {
+ handleContextMenu(event);
+ onContextMenuProp?.(event);
+ },
+ [handleContextMenu, onContextMenuProp],
+ );
+ const handleTriggerTouchStart = useCallback(
+ (event: React.TouchEvent<HTMLElement>) => {
+ handleLongPressTouchStart(event);
+ onTouchStartProp?.(event);
+ },
+ [handleLongPressTouchStart, onTouchStartProp],
+ );
+ const handleTriggerTouchMove = useCallback(
+ (event: React.TouchEvent<HTMLElement>) => {
+ handleLongPressTouchMove(event);
+ onTouchMoveProp?.(event);
+ },
+ [handleLongPressTouchMove, onTouchMoveProp],
+ );
+ const handleTriggerTouchEnd = useCallback(
+ (event: React.TouchEvent<HTMLElement>) => {
+ handleLongPressTouchEnd();
+ onTouchEndProp?.(event);
+ },
+ [handleLongPressTouchEnd, onTouchEndProp],
+ );
+ const handleTriggerTouchCancel = useCallback(
+ (event: React.TouchEvent<HTMLElement>) => {
+ handleLongPressTouchCancel();
+ onTouchCancelProp?.(event);
+ },
+ [handleLongPressTouchCancel, onTouchCancelProp],
+ );
+
const popoverXstyle = menuWidth
? styles.popoverCustomWidth(menuWidth)
: styles.popover;
@@ -702,7 +732,7 @@ export function ContextMenu({
/>
)}
<Heading
- ref={sheetHeadingRef}
+ ref={setSheetHeadingRef}
level={3}
tabIndex={-1}
xstyle={[
@@ -731,11 +761,11 @@ export function ContextMenu({
<TriggerElement
ref={useMergedRefs(ref, triggerRef)}
{...triggerProps}
- onContextMenu={handleContextMenu}
- onTouchStart={longPress.onTouchStart}
- onTouchMove={longPress.onTouchMove}
- onTouchEnd={longPress.onTouchEnd}
- onTouchCancel={longPress.onTouchCancel}
+ onContextMenu={handleTriggerContextMenu}
+ onTouchStart={handleTriggerTouchStart}
+ onTouchMove={handleTriggerTouchMove}
+ onTouchEnd={handleTriggerTouchEnd}
+ onTouchCancel={handleTriggerTouchCancel}
data-testid={testId}
{...stylex.props(
styles.trigger,
@@ -768,7 +798,7 @@ export function ContextMenu({
</LazyMenuBottomSheet>
</Suspense>
) : (
- layer.render(renderedMenu, {
+ layer.render(<LayerDepthProvider>{renderedMenu}</LayerDepthProvider>, {
placement: 'below',
alignment: 'start',
xstyle: [popoverXstyle, layerAnimations.below],
diff --git a/packages/core/src/Layer/useLayerDismissal.ts b/packages/core/src/Layer/useLayerDismissal.ts
index 1cb3feb6e0..2e265580a2 100644
--- a/packages/core/src/Layer/useLayerDismissal.ts
+++ b/packages/core/src/Layer/useLayerDismissal.ts
@@ -97,10 +97,10 @@ export interface UseLayerDismissalReturn {
* The layer does NOT attach a key listener — the stack owns one listener and
* routes each Escape press to the top-most REGISTERED layer, so one press
* dismisses exactly one of them. Dialog (and what is built on it), Popover and
- * the menus built on it, Tooltip, HoverCard, Lightbox, MobileNav, BottomSheet,
- * BottomSheetSwitcher and lab's `Drawer` register today.
+ * the menus built on it, ContextMenu, Tooltip, HoverCard, Lightbox, MobileNav,
+ * BottomSheet, BottomSheetSwitcher and lab's `Drawer` register today.
*
- * `CommandPalette`, `ContextMenu`, `DropdownMenuSubMenu`, and
+ * `CommandPalette`, `DropdownMenuSubMenu`, and
* `PowerSearchEditPopover` still run their own Escape listeners. They stay safe
* next to the stack only because each claims the press at element level, and the
* stack stands down on an already-`defaultPrevented` press — but a registered