An open source design system that's fully customizable and agent ready
TypeScript
feat(ContextMenu): triggerAs — an inline trigger that keeps the prose flow (#6839)
Christopher Chedeau10719cc1fca0
diff --git a/.changeset/context-menu-trigger-as.md b/.changeset/context-menu-trigger-as.mdnew file mode 100644index 0000000000..a0e9a70fc1--- /dev/null+++ b/.changeset/context-menu-trigger-as.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] ContextMenu takes `triggerAs` (`div` | `span`) so a reference inside prose can own a context menu without breaking the text flow.++@vjeuxdiff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsxindex 9ea22aa8dc..fe56074798 100644--- a/apps/storybook/stories/ContextMenu.stories.tsx+++ b/apps/storybook/stories/ContextMenu.stories.tsx@@ -478,3 +478,40 @@ export const AdaptivePresentation: Story = {</div>),};++export const InlineTrigger: Story = {+ name: 'Inline trigger in prose (triggerAs)',+ parameters: {+ docs: {+ description: {+ story:+ 'A reference inside running text owns a context menu without breaking the flow: `triggerAs="span"` wraps it inline. Right-click, a held press or Shift+F10 on the reference opens the menu at the pointer.',+ },+ },+ },+ render: () => (+ <p style={{maxWidth: 480, lineHeight: 1.6}}>+ The regression was tracked in{' '}+ <ContextMenu+ triggerAs="span"+ label="Task actions"+ items={[+ {label: 'Open', onClick: () => {}},+ {label: 'Copy link', onClick: () => {}},+ ]}>+ <a href="/tasks/123">T123</a>+ </ContextMenu>{' '}+ and fixed by{' '}+ <ContextMenu+ triggerAs="span"+ label="Diff actions"+ items={[+ {label: 'Open', onClick: () => {}},+ {label: 'Copy link', onClick: () => {}},+ ]}>+ <a href="/diff/456">D456</a>+ </ContextMenu>{' '}+ the same afternoon.+ </p>+ ),+};diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjsindex 99c8888747..2ca69e913d 100644--- a/packages/core/src/ContextMenu/ContextMenu.doc.mjs+++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs@@ -53,38 +53,57 @@ export const docs = {group: 'ContextMenu',category: 'Action',isHiddenFromOverview: true,- keywords: ["contextmenu","right-click","menu","popover","actions","context"],+ keywords: [+ 'contextmenu',+ 'right-click',+ 'menu',+ 'popover',+ 'actions',+ 'context',+ ],theming: {- targets: [- {className: 'astryx-context-menu'},- ],+ targets: [{className: 'astryx-context-menu'}],vars: [- {name: '--_dropdown-menu-radius', description: 'Border radius of the menu popup', default: 'var(--radius-container)', private: true},- {name: '--_dropdown-menu-padding', description: 'Inner padding of the menu popup', default: 'var(--spacing-1)', private: true},+ {+ name: '--_dropdown-menu-radius',+ description: 'Border radius of the menu popup',+ default: 'var(--radius-container)',+ private: true,+ },+ {+ name: '--_dropdown-menu-padding',+ description: 'Inner padding of the menu popup',+ default: 'var(--spacing-1)',+ private: true,+ },],derived: [{property: 'borderRadius', vars: ['--_dropdown-menu-radius']},{property: 'padding', vars: ['--_dropdown-menu-padding']},],},- description: 'A context menu that appears on right-click at the cursor position. Wraps trigger content as children.',+ description:+ 'A context menu that appears on right-click at the cursor position. Wraps trigger content as children.',props: [{name: 'children',type: 'ReactNode',- description: 'The trigger area: right-click on this content to open the menu.',+ description:+ 'The trigger area: right-click on this content to open the menu.',required: true,},{name: 'items',type: 'ContextMenuOption[]',- description: 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, isDisabled?, variant?, items?}` (nested `items` open a flyout in popover presentation and drill into a new view in bottom-sheet presentation; variant `"destructive"` renders it in the error color), a divider `{type: "divider"}`, or a section `{type: "section", title?, items: [...action items]}`.',+ description:+ 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, isDisabled?, variant?, items?}` (nested `items` open a flyout in popover presentation and drill into a new view in bottom-sheet presentation; variant `"destructive"` renders it in the error color), a divider `{type: "divider"}`, or a section `{type: "section", title?, items: [...action items]}`.',required: true,},{name: 'menuContent',type: 'ReactNode',- description: 'Custom JSX menu content for compound mode. Use instead of items for dynamic or stateful menus.',+ description:+ 'Custom JSX menu content for compound mode. Use instead of items for dynamic or stateful menus.',},{name: 'menuWidth',@@ -101,7 +120,8 @@ export const docs = {{name: 'label',type: 'string',- description: 'Accessible name for the menu surface, announced when it opens.',+ description:+ 'Accessible name for the menu surface, announced when it opens.',default: "'Context menu'",},{@@ -112,30 +132,66 @@ export const docs = {{name: 'presentation',type: "'popover' | 'bottom-sheet' | 'adaptive'",- description: 'Presentation policy. `popover` opens at the pointer position, `bottom-sheet` always uses an action sheet, and `adaptive` uses the BottomSheet at 768px and below when the primary pointer is coarse.',+ description:+ 'Presentation policy. `popover` opens at the pointer position, `bottom-sheet` always uses an action sheet, and `adaptive` uses the BottomSheet at 768px and below when the primary pointer is coarse.',default: "'popover'",},{name: 'isDisabled',type: 'boolean',- description: 'When true, right-click shows the native browser context menu instead.',+ description:+ 'When true, right-click shows the native browser context menu instead.',default: 'false',},+ {+ name: 'triggerAs',+ type: "'div' | 'span'",+ description:+ "The element the trigger wrapper renders as. 'div' is a block; 'span' an inline wrapper, so a reference inside prose can own a context menu without breaking the text flow.",+ default: "'div'",+ },],- components: [- {name: 'ContextMenuItem'},- ],+ components: [{name: 'ContextMenuItem'}],usage: {anatomy,- description: 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions without cluttering the UI with visible buttons.',+ description:+ 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions without cluttering the UI with visible buttons.',bestPractices: [- { guidance: true, description: 'Keep menu items concise and action-oriented; users expect quick access to contextual actions.' },- { guidance: true, description: 'Use sections and dividers to group related actions when the menu has many items.' },- { guidance: true, description: 'Use `presentation="adaptive"` when right-click should remain cursor-positioned on desktop while long-press opens a reachable BottomSheet on compact touch devices.' },- { guidance: true, description: 'Ensure all context menu actions are also accessible via other UI elements for keyboard-only users.' },- { guidance: true, description: 'Keep a visible MoreMenu or equivalent trigger for important mobile actions; long-press must not be the only route.' },- { guidance: false, description: 'Use a ContextMenu as the only way to access important actions; not all users know to right-click.' },- { guidance: false, description: 'Place more than 10–12 items in a single menu without grouping them into sections.' },+ {+ guidance: true,+ description:+ 'Keep menu items concise and action-oriented; users expect quick access to contextual actions.',+ },+ {+ guidance: true,+ description:+ 'Use sections and dividers to group related actions when the menu has many items.',+ },+ {+ guidance: true,+ description:+ 'Use `presentation="adaptive"` when right-click should remain cursor-positioned on desktop while long-press opens a reachable BottomSheet on compact touch devices.',+ },+ {+ guidance: true,+ description:+ 'Ensure all context menu actions are also accessible via other UI elements for keyboard-only users.',+ },+ {+ guidance: true,+ description:+ 'Keep a visible MoreMenu or equivalent trigger for important mobile actions; long-press must not be the only route.',+ },+ {+ guidance: false,+ description:+ 'Use a ContextMenu as the only way to access important actions; not all users know to right-click.',+ },+ {+ guidance: false,+ description:+ 'Place more than 10–12 items in a single menu without grouping them into sections.',+ },],},playground: {@@ -143,7 +199,11 @@ export const docs = {children: {__element: 'Card',props: {padding: 6},- children: {__element: 'Text', props: {color: 'secondary'}, children: 'Right-click this area'},+ children: {+ __element: 'Text',+ props: {color: 'secondary'},+ children: 'Right-click this area',+ },},items: [{label: 'Edit'},@@ -158,15 +218,33 @@ export const docs = {/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsZh = {usage: {- description: '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。',+ description:+ '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。',bestPractices: [- { guidance: true, description: '保持菜单项简洁和面向操作。' },- { guidance: true, description: '有很多项时使用分组和分隔线。' },- { guidance: true, description: '在桌面端需要光标定位、紧凑触控设备上需要 BottomSheet 时,使用 `presentation="adaptive"`。' },- { guidance: true, description: '确保所有上下文菜单操作也可通过其他 UI 元素访问。' },- { guidance: true, description: '重要的移动端操作还应提供可见的 MoreMenu 或同等入口,不要只依赖长按。' },- { guidance: false, description: '将上下文菜单作为访问重要操作的唯一方式。' },- { guidance: false, description: '在单个菜单中放置超过 10-12 个项而不分组。' },+ {guidance: true, description: '保持菜单项简洁和面向操作。'},+ {guidance: true, description: '有很多项时使用分组和分隔线。'},+ {+ guidance: true,+ description:+ '在桌面端需要光标定位、紧凑触控设备上需要 BottomSheet 时,使用 `presentation="adaptive"`。',+ },+ {+ guidance: true,+ description: '确保所有上下文菜单操作也可通过其他 UI 元素访问。',+ },+ {+ guidance: true,+ description:+ '重要的移动端操作还应提供可见的 MoreMenu 或同等入口,不要只依赖长按。',+ },+ {+ guidance: false,+ description: '将上下文菜单作为访问重要操作的唯一方式。',+ },+ {+ guidance: false,+ description: '在单个菜单中放置超过 10-12 个项而不分组。',+ },],},};@@ -176,15 +254,36 @@ export const docsDense = {description: 'right-click context menu at cursor position',usage: {anatomy,- description: 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions.',+ description:+ 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions.',bestPractices: [- { guidance: true, description: 'Keep items concise and action-oriented.' },- { guidance: true, description: 'Group related actions with sections and dividers.' },- { guidance: true, description: 'Use adaptive presentation for cursor popover on desktop and BottomSheet on compact touch.' },- { guidance: true, description: 'Ensure actions are also accessible via other UI elements.' },- { guidance: true, description: 'Keep a visible mobile entry point for important actions.' },- { guidance: false, description: 'Use as the only way to access important actions.' },- { guidance: false, description: 'Place more than 10–12 items without grouping.' },+ {guidance: true, description: 'Keep items concise and action-oriented.'},+ {+ guidance: true,+ description: 'Group related actions with sections and dividers.',+ },+ {+ guidance: true,+ description:+ 'Use adaptive presentation for cursor popover on desktop and BottomSheet on compact touch.',+ },+ {+ guidance: true,+ description:+ 'Ensure actions are also accessible via other UI elements.',+ },+ {+ guidance: true,+ description: 'Keep a visible mobile entry point for important actions.',+ },+ {+ guidance: false,+ description: 'Use as the only way to access important actions.',+ },+ {+ guidance: false,+ description: 'Place more than 10–12 items without grouping.',+ },],},};diff --git a/packages/core/src/ContextMenu/ContextMenu.spec.md b/packages/core/src/ContextMenu/ContextMenu.spec.mdindex 770344bb3b..f97923891c 100644--- a/packages/core/src/ContextMenu/ContextMenu.spec.md+++ b/packages/core/src/ContextMenu/ContextMenu.spec.md@@ -9,7 +9,7 @@ superseded_by: nullapproved_by: nullapproved_at: nullowners: [cixzhang]-review_triggers: [theming]+review_triggers: [theming, public-api, behavior, accessibility]verified_by:[packages/core/src/ContextMenu/ContextMenu.test.tsx,@@ -72,8 +72,12 @@ Consumer migration instructions belong in consumer docs and release notes.## Public concepts-No new public concept is introduced. Consumer props, content modes, and-presentation policy remain documented in `ContextMenu.doc.mjs`.+Consumer props, content modes, and presentation policy remain documented in+`ContextMenu.doc.mjs`. One component-local concept is added by DEC-1:++| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| --------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------- | ----------------------- | --------- | -------------------------------- |+| Trigger element | `div`, `span` | What the Trigger area renders as: a block, or an inline wrapper so a reference inside prose can own a context menu without breaking the text flow. | Both presentations | `div` | `component:ContextMenu` | stable | An unknown value reads as `div`. |## Behavioral and layout contract@@ -84,6 +88,7 @@ presentation policy remain documented in `ContextMenu.doc.mjs`.| 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 |### Allowed variation@@ -122,6 +127,10 @@ invocation, long-press path, keyboard navigation, item semantics, focusreturn, or dismissal ordering. 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`+ (menus-15) in any form, and the menu keeps its own name (`label`).+## Design relationships| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |@@ -193,12 +202,34 @@ anchor is positioning infrastructure rather than consumer anatomy.| 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` || 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-None component-local. The press model decision lives in-`module:DropdownMenu/useMenuPress`; this record introduces no design,-theming, or layer-system decision of its own.+The press model decision lives in `module:DropdownMenu/useMenuPress`.++### DEC-1 — The trigger may be inline++**Reference:** `component:ContextMenu/DEC-1`++**Decider:** `cixzhang`, 2026-10-02++An entity reference inside running prose (a task id, a diff id) needs the three+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.## Open questionsdiff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex e2a8509ed8..db7ff49852 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -1063,3 +1063,35 @@ describe('ContextMenu press model', () => {expect(onCut).not.toHaveBeenCalled();});});++describe('ContextMenu inline trigger (triggerAs)', () => {+ it('an inline trigger keeps its flow', () => {+ render(+ <p>+ Filed under{' '}+ <ContextMenu+ triggerAs="span"+ data-testid="ref"+ items={[{label: 'Open', onClick: () => {}}]}>+ T123+ </ContextMenu>{' '}+ yesterday.+ </p>,+ );+ const trigger = screen.getByTestId('ref');+ expect(trigger.tagName).toBe('SPAN');+ expect(trigger.parentElement?.tagName).toBe('P');+ expect(trigger).not.toHaveStyle({display: 'block'});+ fireEvent.contextMenu(trigger, {clientX: 20, clientY: 10, detail: 1});+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();+ });++ it('defaults to a block trigger', () => {+ render(+ <ContextMenu data-testid="area" items={[{label: 'Open'}]}>+ Area+ </ContextMenu>,+ );+ expect(screen.getByTestId('area').tagName).toBe('DIV');+ });+});diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 75d32843cf..bdfc9a33cc 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -22,6 +22,9 @@** Both modes use useListFocus for DOM-based keyboard navigation.* Open state is managed internally — right-click opens, click-outside/Escape closes.+ * The trigger wrapper is a `div` by default; `triggerAs` makes it an inline+ * `span`, so a reference inside prose can own a context menu without+ * breaking the text flow.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/ContextMenu/ContextMenu.doc.mjs@@ -198,7 +201,14 @@ export type ContextMenuOption = DropdownMenuOption;interface ContextMenuBaseProps extends BaseProps {/** Ref forwarded to the trigger wrapper element. */- ref?: React.Ref<HTMLDivElement>;+ ref?: React.Ref<HTMLElement>;+ /**+ * The element the trigger wrapper renders as. `div` is a block; `span` an+ * inline wrapper, so a reference inside prose can own a context menu+ * without breaking the text flow.+ * @default 'div'+ */+ triggerAs?: 'div' | 'span';/*** Styles applied to the trigger wrapper element (the right-click target).* By default the trigger is a plain block that hugs its content — pass a@@ -282,6 +292,7 @@ export function ContextMenu({isDisabled = false,onOpenChange,presentation = 'popover',+ triggerAs = 'div',ref,className,style,@@ -316,7 +327,7 @@ export function ContextMenu({// — it scrolls with the content instead of sitting at a fixed viewport point.const positionRef = useRef({x: 0, y: 0});const cursorAnchorRef = useRef<HTMLSpanElement>(null);- const triggerRef = useRef<HTMLDivElement>(null);+ const triggerRef = useRef<HTMLElement>(null);// 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);@@ -528,14 +539,20 @@ export function ContextMenu({[layer, focusFirst, updateOpenState, usesBottomSheet],);+ // The box the cursor anchor's offsets are measured from: the trigger, which+ // is its containing block.+ const getAnchorBaseRect = useCallback(+ (): DOMRect | undefined => triggerRef.current?.getBoundingClientRect(),+ [],+ );+const handleContextMenu = useCallback((e: React.MouseEvent) => {if (isDisabled) {return;}e.preventDefault();- const trigger = triggerRef.current;- const rect = trigger?.getBoundingClientRect();+ const rect = getAnchorBaseRect();// A keyboard-initiated contextmenu (Shift+F10 / the Menu key) fires a// `contextmenu` event whose coordinates are (0, 0) in several browsers.// Detect that and anchor the menu to the trigger's bottom-left instead,@@ -549,7 +566,7 @@ export function ContextMenu({isKeyboardInvoked || !rect ? (rect?.height ?? 0) : e.clientY - rect.top;openAtLocalPoint(localX, localY, e.currentTarget as HTMLElement);},- [isDisabled, openAtLocalPoint],+ [isDisabled, openAtLocalPoint, getAnchorBaseRect],);// Touch long-press invocation (menus-8). iOS Safari never synthesizes a@@ -560,14 +577,14 @@ export function ContextMenu({disabled: isDisabled,onLongPress: useCallback((point: {x: number; y: number}) => {- const rect = triggerRef.current?.getBoundingClientRect();+ const rect = getAnchorBaseRect();openAtLocalPoint(rect ? point.x - rect.left : point.x,rect ? point.y - rect.top : point.y,triggerRef.current,);},- [openAtLocalPoint],+ [openAtLocalPoint, getAnchorBaseRect],),});@@ -673,9 +690,13 @@ export function ContextMenu({renderedMenu);+ // An inline trigger (`span`) lets prose own a context menu without+ // breaking its flow.+ const TriggerElement = triggerAs === 'div' ? 'div' : 'span';+return (<>- <div+ <TriggerElementref={useMergedRefs(ref, triggerRef)}{...triggerProps}onContextMenu={handleContextMenu}@@ -700,7 +721,7 @@ export function ContextMenu({},})}/>- </div>+ </TriggerElement>{usesBottomSheet ? (<Suspense fallback={null}>