Skip to content

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

TypeScript

feat(core): add XDSContextMenu component (#2195)

Andrey Goder062f311682b1
diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx
new file mode 100644
index 0000000000..ef84c3db40
--- /dev/null
+++ b/apps/storybook/stories/ContextMenu.stories.tsx
@@ -0,0 +1,305 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSContextMenu, XDSContextMenuItem} from '@xds/core/ContextMenu';
+import {XDSDivider} from '@xds/core/Divider';
+import {
+ PencilIcon,
+ TrashIcon,
+ DocumentDuplicateIcon,
+ ArrowDownTrayIcon,
+ ShareIcon,
+ ScissorsIcon,
+ ClipboardIcon,
+ ClipboardDocumentIcon,
+} from '@heroicons/react/24/outline';
+import * as stylex from '@stylexjs/stylex';
+
+const triggerStyles = stylex.create({
+ area: {
+ padding: '48px',
+ borderWidth: '2px',
+ borderStyle: 'dashed',
+ borderColor: '#d1d5db',
+ borderRadius: '8px',
+ textAlign: 'center',
+ color: '#6b7280',
+ userSelect: 'none',
+ },
+});
+
+const meta: Meta<typeof XDSContextMenu> = {
+ title: 'Core/ContextMenu',
+ component: XDSContextMenu,
+ tags: ['autodocs'],
+ parameters: {
+ layout: 'centered',
+ },
+ argTypes: {
+ items: {
+ description: 'Menu items (items, dividers, or sections)',
+ },
+ menuWidth: {
+ control: 'text',
+ description: 'Custom menu width (number for px or CSS string)',
+ },
+ size: {
+ control: 'select',
+ options: ['sm', 'md', 'lg'],
+ description: 'Menu item size',
+ },
+ isDisabled: {
+ control: 'boolean',
+ description: 'Disable custom context menu',
+ },
+ 'data-testid': {
+ control: 'text',
+ description: 'Test ID for testing frameworks',
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSContextMenu>;
+
+export const Default: Story = {
+ render: () => (
+ <XDSContextMenu
+ items={[
+ {label: 'Cut', onClick: () => console.log('Cut')},
+ {label: 'Copy', onClick: () => console.log('Copy')},
+ {label: 'Paste', onClick: () => console.log('Paste')},
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>Right-click this area</div>
+ </XDSContextMenu>
+ ),
+};
+
+export const WithIcons: Story = {
+ render: () => (
+ <XDSContextMenu
+ items={[
+ {
+ label: 'Cut',
+ icon: ScissorsIcon,
+ onClick: () => console.log('Cut'),
+ },
+ {
+ label: 'Copy',
+ icon: ClipboardDocumentIcon,
+ onClick: () => console.log('Copy'),
+ },
+ {
+ label: 'Paste',
+ icon: ClipboardIcon,
+ onClick: () => console.log('Paste'),
+ },
+ {type: 'divider'},
+ {
+ label: 'Delete',
+ icon: TrashIcon,
+ onClick: () => console.log('Delete'),
+ },
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>Right-click for actions</div>
+ </XDSContextMenu>
+ ),
+};
+
+export const WithSections: Story = {
+ render: () => (
+ <XDSContextMenu
+ items={[
+ {
+ type: 'section',
+ title: 'Edit',
+ items: [
+ {
+ label: 'Cut',
+ icon: ScissorsIcon,
+ onClick: () => console.log('Cut'),
+ },
+ {
+ label: 'Copy',
+ icon: ClipboardDocumentIcon,
+ onClick: () => console.log('Copy'),
+ },
+ {
+ label: 'Paste',
+ icon: ClipboardIcon,
+ onClick: () => console.log('Paste'),
+ },
+ ],
+ },
+ {
+ type: 'section',
+ title: 'Share',
+ items: [
+ {
+ label: 'Share',
+ icon: ShareIcon,
+ onClick: () => console.log('Share'),
+ },
+ {
+ label: 'Download',
+ icon: ArrowDownTrayIcon,
+ onClick: () => console.log('Download'),
+ },
+ ],
+ },
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>
+ Right-click for grouped actions
+ </div>
+ </XDSContextMenu>
+ ),
+};
+
+export const WithDividers: Story = {
+ render: () => (
+ <XDSContextMenu
+ items={[
+ {label: 'Edit', onClick: () => console.log('Edit')},
+ {label: 'Duplicate', onClick: () => console.log('Duplicate')},
+ {type: 'divider'},
+ {label: 'Delete', onClick: () => console.log('Delete')},
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>Right-click this area</div>
+ </XDSContextMenu>
+ ),
+};
+
+export const WithDisabledItems: Story = {
+ render: () => (
+ <XDSContextMenu
+ items={[
+ {
+ label: 'Edit',
+ icon: PencilIcon,
+ onClick: () => console.log('Edit'),
+ },
+ {
+ label: 'Duplicate',
+ icon: DocumentDuplicateIcon,
+ onClick: () => console.log('Duplicate'),
+ },
+ {label: 'Delete (no permission)', icon: TrashIcon, isDisabled: true},
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>Right-click this area</div>
+ </XDSContextMenu>
+ ),
+};
+
+export const CustomWidth: Story = {
+ render: () => (
+ <XDSContextMenu
+ menuWidth={280}
+ items={[
+ {
+ label: 'This is a longer option that needs more space',
+ onClick: () => console.log('Option 1'),
+ },
+ {
+ label: 'Another long option',
+ onClick: () => console.log('Option 2'),
+ },
+ {label: 'Short', onClick: () => console.log('Option 3')},
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>Right-click for wide menu</div>
+ </XDSContextMenu>
+ ),
+};
+
+export const SmallSize: Story = {
+ render: () => (
+ <XDSContextMenu
+ size="sm"
+ items={[
+ {label: 'Cut', onClick: () => console.log('Cut')},
+ {label: 'Copy', onClick: () => console.log('Copy')},
+ {label: 'Paste', onClick: () => console.log('Paste')},
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>
+ Right-click for compact menu
+ </div>
+ </XDSContextMenu>
+ ),
+};
+
+export const Disabled: Story = {
+ render: () => (
+ <XDSContextMenu
+ isDisabled
+ items={[
+ {label: 'Cut', onClick: () => console.log('Cut')},
+ {label: 'Copy', onClick: () => console.log('Copy')},
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>
+ Right-click shows native menu (disabled)
+ </div>
+ </XDSContextMenu>
+ ),
+};
+
+export const CompoundBasic: Story = {
+ render: () => (
+ <XDSContextMenu
+ menuContent={
+ <>
+ <XDSContextMenuItem
+ icon={PencilIcon}
+ label="Edit"
+ onClick={() => console.log('Edit')}
+ />
+ <XDSContextMenuItem
+ icon={DocumentDuplicateIcon}
+ label="Duplicate"
+ onClick={() => console.log('Duplicate')}
+ />
+ <XDSDivider />
+ <XDSContextMenuItem
+ icon={TrashIcon}
+ label="Delete"
+ onClick={() => console.log('Delete')}
+ />
+ </>
+ }>
+ <div {...stylex.props(triggerStyles.area)}>
+ Right-click for compound menu
+ </div>
+ </XDSContextMenu>
+ ),
+};
+
+export const CompoundWithDescriptions: Story = {
+ render: () => (
+ <XDSContextMenu
+ menuWidth={280}
+ menuContent={
+ <>
+ <XDSContextMenuItem
+ icon={PencilIcon}
+ label="Edit"
+ description="Modify this item"
+ onClick={() => console.log('Edit')}
+ />
+ <XDSContextMenuItem
+ icon={ShareIcon}
+ label="Share"
+ description="Share with others"
+ onClick={() => console.log('Share')}
+ />
+ <XDSDivider />
+ <XDSContextMenuItem
+ icon={TrashIcon}
+ label="Delete"
+ description="Permanently remove"
+ onClick={() => console.log('Delete')}
+ />
+ </>
+ }>
+ <div {...stylex.props(triggerStyles.area)}>
+ Right-click for detailed menu
+ </div>
+ </XDSContextMenu>
+ ),
+};
diff --git a/apps/storybook/stories/DateTimePicker.stories.tsx b/apps/storybook/stories/DateTimePicker.stories.tsx
index 5f5ff8fc47..55bdb51c7d 100644
--- a/apps/storybook/stories/DateTimePicker.stories.tsx
+++ b/apps/storybook/stories/DateTimePicker.stories.tsx
@@ -1,4 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+
import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import {XDSDateTimePicker} from '@xds/core/DateTimePicker';
diff --git a/internal/vibe-tests/src/cli.ts b/internal/vibe-tests/src/cli.ts
old mode 100644
new mode 100755
diff --git a/packages/cli/bin/xds.mjs b/packages/cli/bin/xds.mjs
old mode 100644
new mode 100755
diff --git a/packages/cli/templates/blocks/components/ContextMenu/ContextMenuShowcase.doc.mjs b/packages/cli/templates/blocks/components/ContextMenu/ContextMenuShowcase.doc.mjs
new file mode 100644
index 0000000000..4b7d15174c
--- /dev/null
+++ b/packages/cli/templates/blocks/components/ContextMenu/ContextMenuShowcase.doc.mjs
@@ -0,0 +1,13 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'ContextMenu',
+ name: 'ContextMenu',
+ description:
+ 'A right-click area that opens a context menu with action items.',
+ isReady: true,
+ isShowcase: true,
+ aspectRatio: 1,
+ componentsUsed: ['ContextMenu'],
+};
diff --git a/packages/cli/templates/blocks/components/ContextMenu/ContextMenuShowcase.tsx b/packages/cli/templates/blocks/components/ContextMenu/ContextMenuShowcase.tsx
new file mode 100644
index 0000000000..c4043745dd
--- /dev/null
+++ b/packages/cli/templates/blocks/components/ContextMenu/ContextMenuShowcase.tsx
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+'use client';
+
+import * as stylex from '@stylexjs/stylex';
+import {XDSContextMenu} from '@xds/core/ContextMenu';
+
+const styles = stylex.create({
+ area: {
+ padding: '48px',
+ borderWidth: '2px',
+ borderStyle: 'dashed',
+ borderColor: '#d1d5db',
+ borderRadius: '8px',
+ textAlign: 'center',
+ color: '#6b7280',
+ userSelect: 'none',
+ },
+});
+
+export default function ContextMenuShowcase() {
+ return (
+ <XDSContextMenu
+ items={[
+ {label: 'Cut', onClick: () => {}},
+ {label: 'Copy', onClick: () => {}},
+ {label: 'Paste', onClick: () => {}},
+ ]}>
+ <div {...stylex.props(styles.area)}>Right-click this area</div>
+ </XDSContextMenu>
+ );
+}
diff --git a/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.doc.mjs b/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.doc.mjs
index 43381444c3..bce17bf54e 100644
--- a/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.doc.mjs
+++ b/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.doc.mjs
@@ -1,4 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+
/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
export const doc = {
type: 'block',
diff --git a/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.tsx b/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.tsx
index f361894117..ad16843298 100644
--- a/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.tsx
+++ b/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.tsx
@@ -1,4 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+
'use client';
import {useState} from 'react';
diff --git a/packages/core/package.json b/packages/core/package.json
index 9e33bd647a..1577e41fc5 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -193,6 +193,12 @@
"import": "./dist/CommandPalette/index.mjs",
"require": "./dist/CommandPalette/index.js"
},
+ "./ContextMenu": {
+ "source": "./src/ContextMenu/index.ts",
+ "types": "./dist/ContextMenu/index.d.ts",
+ "import": "./dist/ContextMenu/index.mjs",
+ "require": "./dist/ContextMenu/index.js"
+ },
"./DateInput": {
"source": "./src/DateInput/index.ts",
"types": "./dist/DateInput/index.d.ts",
diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjs
new file mode 100644
index 0000000000..99788c4283
--- /dev/null
+++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs
@@ -0,0 +1,268 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @type {import('../docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'ContextMenu',
+ group: 'ContextMenu',
+ keywords: ["contextmenu","right-click","menu","popover","actions","context"],
+ theming: {
+ targets: [
+ {className: 'xds-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},
+ ],
+ derived: [
+ {property: 'borderRadius', vars: ['--_dropdown-menu-radius']},
+ {property: 'padding', vars: ['--_dropdown-menu-padding']},
+ ],
+ },
+ components: [
+ {
+ name: 'XDSContextMenu',
+ 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.',
+ required: true,
+ },
+ {
+ name: 'items',
+ type: 'XDSContextMenuOption[]',
+ description:
+ 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, isDisabled?}`, 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.',
+ },
+ {
+ name: 'menuWidth',
+ type: 'number | string',
+ description: 'Custom menu width.',
+ default: "'160px'",
+ },
+ {
+ name: 'size',
+ type: "'sm' | 'md' | 'lg'",
+ description: 'Size of menu items — controls padding density.',
+ default: "'md'",
+ },
+ {
+ name: 'hasAutoFocus',
+ type: 'boolean',
+ description: 'Whether to auto-focus the first menu item when the menu opens. Set to false for inline showcases.',
+ default: 'true',
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description: 'When true, right-click shows the native browser context menu instead.',
+ default: 'false',
+ },
+ ],
+ },
+ {
+ name: 'XDSContextMenuItem',
+ description:
+ 'Menu item component for compound mode. Re-exported from XDSDropdownMenuItem for discoverability.',
+ props: [
+ {
+ name: 'icon',
+ type: 'XDSIconType',
+ description: 'Icon to display before the label.',
+ },
+ {
+ name: 'label',
+ type: 'ReactNode',
+ description: 'Primary label text.',
+ },
+ {
+ name: 'description',
+ type: 'ReactNode',
+ description: 'Secondary description text displayed below the label.',
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description:
+ 'Additional content rendered after the label and description.',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description: 'StyleX styles for layout customization.',
+ },
+ ],
+ },
+ ],
+ usage: {
+ 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: 'Ensure all context menu actions are also accessible via other UI elements for keyboard-only users.' },
+ { 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.' },
+ ],
+ },
+};
+
+/** @type {import('../docs-types').ComponentDoc} */
+export const docsZh = {
+ name: 'ContextMenu',
+ theming: {
+ targets: [
+ {className: 'xds-context-menu'},
+ ],
+ vars: [
+ {name: '--_dropdown-menu-radius', description: '菜单弹出层的圆角', default: 'var(--radius-container)', private: true},
+ {name: '--_dropdown-menu-padding', description: '菜单弹出层的内边距', default: 'var(--spacing-1)', private: true},
+ ],
+ derived: [
+ {property: 'borderRadius', vars: ['--_dropdown-menu-radius']},
+ {property: 'padding', vars: ['--_dropdown-menu-padding']},
+ ],
+ },
+ components: [
+ {
+ name: 'XDSContextMenu',
+ description:
+ '右键点击时在光标位置出现的上下文菜单。将触发内容作为子元素包裹。',
+ props: [
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description: '触发区域 — 右键点击此内容以打开菜单。',
+ required: true,
+ },
+ {
+ name: 'items',
+ type: 'XDSContextMenuOption[]',
+ description:
+ '菜单项数组。每项为:操作项 `{label, onClick?, icon?, isDisabled?}`、分隔线 `{type: "divider"}`、或分组 `{type: "section", title?, items: [...操作项]}`。',
+ required: true,
+ },
+ {
+ name: 'menuContent',
+ type: 'ReactNode',
+ description: '复合模式的自定义 JSX 菜单内容。',
+ },
+ {
+ name: 'menuWidth',
+ type: 'number | string',
+ description: '自定义菜单宽度。',
+ default: "'160px'",
+ },
+ {
+ name: 'size',
+ type: "'sm' | 'md' | 'lg'",
+ description: '菜单项大小 — 控制内边距密度。',
+ default: "'md'",
+ },
+ {
+ name: 'hasAutoFocus',
+ type: 'boolean',
+ description: '菜单打开时是否自动聚焦第一个菜单项。',
+ default: 'true',
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description: '为 true 时,右键显示浏览器原生上下文菜单。',
+ default: 'false',
+ },
+ ],
+ },
+ {
+ name: 'XDSContextMenuItem',
+ description:
+ '复合模式的菜单项组件。从 XDSDropdownMenuItem 重新导出以便发现。',
+ props: [
+ {
+ name: 'icon',
+ type: 'XDSIconType',
+ description: '显示在标签前的图标。',
+ },
+ {
+ name: 'label',
+ type: 'ReactNode',
+ description: '主标签文本。',
+ },
+ {
+ name: 'description',
+ type: 'ReactNode',
+ description: '显示在标签下方的次要描述文本。',
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description: '在标签和描述之后渲染的附加内容。',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description: '根容器的 StyleX 样式。',
+ },
+ ],
+ },
+ ],
+ usage: {
+ description: '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。',
+ bestPractices: [
+ { guidance: true, description: '保持菜单项简洁和面向操作。' },
+ { guidance: true, description: '有很多项时使用分组和分隔线。' },
+ { guidance: true, description: '确保所有上下文菜单操作也可通过其他 UI 元素访问。' },
+ { guidance: false, description: '将上下文菜单作为访问重要操作的唯一方式。' },
+ { guidance: false, description: '在单个菜单中放置超过 10-12 个项而不分组。' },
+ ],
+ },
+};
+
+/** @type {import('../docs-types').TranslationDoc} */
+export const docsDense = {
+ description: 'right-click context menu at cursor position',
+ usage: {
+ 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: 'Ensure actions are also accessible via other UI elements.' },
+ { guidance: false, description: 'Use as the only way to access important actions.' },
+ { guidance: false, description: 'Place more than 10–12 items without grouping.' },
+ ],
+ },
+ components: [
+ {
+ name: 'XDSContextMenu',
+ description: 'right-click trigger + fixed-position popup menu',
+ propDescriptions: {
+ children: 'trigger area — right-click to open menu',
+ items: 'array of menu entries: action item {label, onClick?, icon?, isDisabled?}, divider {type: "divider"}, or section {type: "section", title?, items: [...]}',
+ menuContent: 'custom JSX menu content (compound mode)',
+ menuWidth: 'custom menu width',
+ size: 'menu item size (sm/md/lg)',
+ hasAutoFocus: 'auto-focus first item on open; false for showcases',
+ isDisabled: 'when true, shows native context menu instead',
+ },
+ },
+ {
+ name: 'XDSContextMenuItem',
+ description: 're-exported XDSDropdownMenuItem for compound mode',
+ propDescriptions: {
+ icon: 'icon before label',
+ label: 'primary label text',
+ description: 'secondary text below label',
+ children: 'additional content after label+description',
+ xstyle: 'StyleX styles for root container',
+ },
+ },
+ ],
+};
diff --git a/packages/core/src/ContextMenu/XDSContextMenu.test.tsx b/packages/core/src/ContextMenu/XDSContextMenu.test.tsx
new file mode 100644
index 0000000000..bfa28fa7d8
--- /dev/null
+++ b/packages/core/src/ContextMenu/XDSContextMenu.test.tsx
@@ -0,0 +1,277 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file XDSContextMenu.test.tsx
+ * @input Uses vitest, @testing-library/react, XDSContextMenu component
+ * @output Unit tests for XDSContextMenu component behavior
+ * @position Testing; validates XDSContextMenu.tsx implementation
+ *
+ * SYNC: When XDSContextMenu.tsx changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSContextMenu} from './XDSContextMenu';
+import {XDSDropdownMenuItem} from '../DropdownMenu/XDSDropdownMenuItem';
+import {XDSDivider} from '../Divider';
+
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ const originalMatches = HTMLElement.prototype.matches;
+ HTMLElement.prototype.matches = function (selector: string) {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+describe('XDSContextMenu', () => {
+ it('renders trigger children', () => {
+ render(
+ <XDSContextMenu items={[{label: 'Item 1'}]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+ expect(screen.getByText('Right-click me')).toBeInTheDocument();
+ });
+
+ it('renders menu with role="menu"', () => {
+ render(
+ <XDSContextMenu items={[{label: 'Item 1'}]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+ expect(screen.getByRole('menu', {hidden: true})).toBeInTheDocument();
+ });
+
+ it('opens menu on right-click', () => {
+ render(
+ <XDSContextMenu items={[{label: 'Item 1'}]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ });
+
+ it('prevents default context menu on right-click', () => {
+ render(
+ <XDSContextMenu items={[{label: 'Item 1'}]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ const event = new MouseEvent('contextmenu', {bubbles: true});
+ const preventDefault = vi.spyOn(event, 'preventDefault');
+ screen.getByText('Right-click me').dispatchEvent(event);
+ expect(preventDefault).toHaveBeenCalled();
+ });
+
+ it('does not open when isDisabled is true', () => {
+ render(
+ <XDSContextMenu items={[{label: 'Item 1'}]} isDisabled>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ });
+
+ it('applies data-testid to trigger wrapper', () => {
+ render(
+ <XDSContextMenu items={[{label: 'Item 1'}]} data-testid="my-context-menu">
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+ expect(screen.getByTestId('my-context-menu')).toBeInTheDocument();
+ });
+});
+
+describe('XDSContextMenu items', () => {
+ it('renders items with labels', () => {
+ render(
+ <XDSContextMenu items={[{label: 'Cut'}, {label: 'Copy'}]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+ expect(
+ screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('menuitem', {name: 'Copy', hidden: true}),
+ ).toBeInTheDocument();
+ });
+
+ it('calls onClick when item is clicked', async () => {
+ const user = userEvent.setup();
+ const handleClick = vi.fn();
+ render(
+ <XDSContextMenu items={[{label: 'Cut', onClick: handleClick}]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ await user.click(screen.getByRole('menuitem', {name: 'Cut', hidden: true}));
+ expect(handleClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not call onClick when disabled', async () => {
+ const user = userEvent.setup();
+ const handleClick = vi.fn();
+ render(
+ <XDSContextMenu
+ items={[{label: 'Cut', onClick: handleClick, isDisabled: true}]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ await user.click(screen.getByRole('menuitem', {name: 'Cut', hidden: true}));
+ expect(handleClick).not.toHaveBeenCalled();
+ });
+
+ it('has aria-disabled when disabled', () => {
+ render(
+ <XDSContextMenu items={[{label: 'Cut', isDisabled: true}]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+ expect(
+ screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
+ ).toHaveAttribute('aria-disabled', 'true');
+ });
+});
+
+describe('XDSContextMenu sections', () => {
+ it('renders section with title', () => {
+ render(
+ <XDSContextMenu
+ items={[
+ {
+ type: 'section',
+ title: 'Edit',
+ items: [{label: 'Cut'}, {label: 'Copy'}],
+ },
+ ]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ expect(screen.getByText('Edit')).toBeInTheDocument();
+ expect(
+ screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('menuitem', {name: 'Copy', hidden: true}),
+ ).toBeInTheDocument();
+ });
+
+ it('has role="group" with aria-label', () => {
+ render(
+ <XDSContextMenu
+ items={[
+ {
+ type: 'section',
+ title: 'Edit',
+ items: [{label: 'Cut'}],
+ },
+ ]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ const group = screen.getByRole('group', {name: 'Edit', hidden: true});
+ expect(group).toBeInTheDocument();
+ });
+});
+
+describe('XDSContextMenu dividers', () => {
+ it('renders dividers between items', () => {
+ render(
+ <XDSContextMenu
+ items={[{label: 'Cut'}, {type: 'divider'}, {label: 'Paste'}]}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ expect(
+ screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('menuitem', {name: 'Paste', hidden: true}),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('separator', {hidden: true})).toBeInTheDocument();
+ });
+});
+
+describe('XDSContextMenu compound mode', () => {
+ it('renders menuContent as menu items', () => {
+ render(
+ <XDSContextMenu
+ menuContent={
+ <>
+ <XDSDropdownMenuItem label="Cut" onClick={() => {}} />
+ <XDSDropdownMenuItem label="Copy" onClick={() => {}} />
+ </>
+ }>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+ expect(
+ screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('menuitem', {name: 'Copy', hidden: true}),
+ ).toBeInTheDocument();
+ });
+
+ it('calls onClick when compound item is clicked', async () => {
+ const user = userEvent.setup();
+ const handleClick = vi.fn();
+ render(
+ <XDSContextMenu
+ menuContent={<XDSDropdownMenuItem label="Cut" onClick={handleClick} />}>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ await user.click(screen.getByRole('menuitem', {name: 'Cut', hidden: true}));
+ expect(handleClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders dividers between compound items', () => {
+ render(
+ <XDSContextMenu
+ menuContent={
+ <>
+ <XDSDropdownMenuItem label="Cut" onClick={() => {}} />
+ <XDSDivider />
+ <XDSDropdownMenuItem label="Paste" onClick={() => {}} />
+ </>
+ }>
+ <div>Right-click me</div>
+ </XDSContextMenu>,
+ );
+
+ expect(
+ screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('menuitem', {name: 'Paste', hidden: true}),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('separator', {hidden: true})).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/ContextMenu/XDSContextMenu.tsx b/packages/core/src/ContextMenu/XDSContextMenu.tsx
new file mode 100644
index 0000000000..4ef46ef9b5
--- /dev/null
+++ b/packages/core/src/ContextMenu/XDSContextMenu.tsx
@@ -0,0 +1,309 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+'use client';
+
+/**
+ * @file XDSContextMenu.tsx
+ * @input Uses React, StyleX, useXDSLayer (fixed mode), useListFocus
+ * @output Exports XDSContextMenu component
+ * @position Core implementation; consumed by index.ts
+ *
+ * Right-click context menu positioned at cursor coordinates.
+ * Reuses DropdownMenu item rendering and keyboard navigation.
+ *
+ * Supports two content modes with a single keyboard/focus path:
+ * - **Data-driven**: pass `items` array (converted to components internally)
+ * - **Compound-component**: pass `menuContent` JSX directly
+ *
+ * Both modes use useListFocus for DOM-based keyboard navigation.
+ * Open state is managed internally — right-click opens, click-outside/Escape closes.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/ContextMenu/ContextMenu.doc.mjs
+ * - /packages/core/src/ContextMenu/XDSContextMenu.test.tsx
+ * - /packages/core/src/ContextMenu/index.ts
+ * - /apps/storybook/stories/ContextMenu.stories.tsx
+ * - /packages/cli/templates/blocks/components/ContextMenu/ (showcase blocks)
+ */
+
+import React, {
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {useXDSLayer} from '../Layer/useXDSLayer';
+import {renderXDSDropdownItems} from '../DropdownMenu/renderXDSDropdownItems';
+import {
+ XDSDropdownMenuContext,
+ type XDSDropdownMenuContextValue,
+} from '../DropdownMenu/XDSDropdownMenuContext';
+import {useListFocus} from '../hooks/useListFocus';
+import {layerAnimations} from '../Layer/layerAnimations.stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ durationVars,
+ easeVars,
+ shadowVars,
+} from '../theme/tokens.stylex';
+import {xdsClassName, mergeProps} from '../utils';
+import type {XDSBaseProps} from '../XDSBaseProps';
+import type {
+ XDSDropdownMenuOption,
+ XDSDropdownMenuItemData,
+ XDSDropdownMenuDivider,
+ XDSDropdownMenuSection,
+} from '../DropdownMenu/XDSDropdownMenu';
+
+const styles = stylex.create({
+ menu: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0-5'],
+ maxHeight: '300px',
+ overflowY: 'auto',
+ '--_dropdown-menu-radius': radiusVars['--radius-container'],
+ '--_dropdown-menu-padding': spacingVars['--spacing-1'],
+ padding: spacingVars['--spacing-1'],
+ borderRadius: 'var(--_dropdown-menu-radius)',
+ backgroundColor: colorVars['--color-background-popover'],
+ boxShadow: shadowVars['--shadow-low'],
+ opacity: 1,
+ transitionProperty: 'opacity',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ popover: {
+ minWidth: '160px',
+ },
+ popoverCustomWidth: (width: string | number) => ({
+ minWidth: typeof width === 'number' ? `${width}px` : width,
+ }),
+});
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export type XDSContextMenuItemData = XDSDropdownMenuItemData;
+
+export type XDSContextMenuDivider = XDSDropdownMenuDivider;
+
+export type XDSContextMenuSection = XDSDropdownMenuSection;
+
+export type XDSContextMenuOption = XDSDropdownMenuOption;
+
+// =============================================================================
+// Props
+// =============================================================================
+
+interface XDSContextMenuBaseProps extends XDSBaseProps {
+ /** Ref forwarded to the trigger wrapper element. */
+ ref?: React.Ref<HTMLDivElement>;
+ /** The trigger area — right-click on this to open the menu. */
+ children: ReactNode;
+ /** Custom menu width. @default '160px' */
+ menuWidth?: number | string;
+ /** Size of menu items. @default 'md' */
+ size?: 'sm' | 'md' | 'lg';
+ /**
+ * Whether to auto-focus the first menu item when the menu opens.
+ * Set to `false` for inline showcases or documentation previews.
+ * @default true
+ */
+ hasAutoFocus?: boolean;
+ /** When true, right-click shows the native browser context menu instead. */
+ isDisabled?: boolean;
+ /** Called when the menu opens or closes. */
+ onOpenChange?: (isOpen: boolean) => void;
+ 'data-testid'?: string;
+}
+
+interface XDSContextMenuDataProps extends XDSContextMenuBaseProps {
+ /** Array of menu entries (data-driven mode). */
+ items: XDSContextMenuOption[];
+ menuContent?: undefined;
+}
+
+interface XDSContextMenuCompoundProps extends XDSContextMenuBaseProps {
+ items?: undefined;
+ /** Custom JSX menu content (compound mode). */
+ menuContent: ReactNode;
+}
+
+export type XDSContextMenuProps =
+ | XDSContextMenuDataProps
+ | XDSContextMenuCompoundProps;
+
+// =============================================================================
+// XDSContextMenu
+// =============================================================================
+
+/**
+ * A context menu component that appears on right-click at cursor position.
+ *
+ * Supports two modes:
+ * - **Data-driven**: pass `items` for static menus
+ * - **Compound-component**: pass `menuContent` JSX for dynamic menus
+ *
+ * Both modes share the same DOM-based keyboard navigation via useListFocus.
+ *
+ * @example
+ * ```
+ * <XDSContextMenu
+ * items={[
+ * { label: 'Cut', onClick: () => handleCut() },
+ * { label: 'Copy', onClick: () => handleCopy() },
+ * { type: 'divider' },
+ * { label: 'Paste', onClick: () => handlePaste() },
+ * ]}
+ * >
+ * <div>Right-click this area</div>
+ * </XDSContextMenu>
+ * ```
+ */
+export function XDSContextMenu({
+ children,
+ menuWidth,
+ size = 'md',
+ hasAutoFocus = true,
+ isDisabled = false,
+ onOpenChange,
+ ref,
+ className,
+ style,
+ xstyle,
+ 'data-testid': testId,
+ ...props
+}: XDSContextMenuProps) {
+ const items = ('items' in props ? props.items : undefined) ?? [];
+ const menuContent = 'menuContent' in props ? props.menuContent : undefined;
+
+ const menuId = useId();
+ const positionRef = useRef({x: 0, y: 0});
+ const [isOpen, setIsOpen] = useState(false);
+
+ const layer = useXDSLayer({
+ mode: 'fixed',
+ onHide: useCallback(() => {
+ setIsOpen(false);
+ onOpenChange?.(false);
+ }, [onOpenChange]),
+ onShow: useCallback(() => {
+ setIsOpen(true);
+ onOpenChange?.(true);
+ }, [onOpenChange]),
+ lightDismiss: false,
+ });
+
+ const closeMenu = useCallback(() => {
+ layer.hide();
+ }, [layer]);
+
+ const {
+ listRef,
+ handleKeyDown: listNavKeyDown,
+ focusFirst,
+ } = useListFocus({
+ itemSelector: '[role="menuitem"]:not([aria-disabled="true"])',
+ wrap: false,
+ onEscape: closeMenu,
+ });
+
+ // Dismiss on any click outside the menu. We use popover="manual" (not
+ // "auto") because the native light-dismiss treats the mouseup from the
+ // opening right-click as a dismiss event. Handling it ourselves via
+ // mousedown avoids that race.
+ useEffect(() => {
+ if (!isOpen) return;
+ const handleClickOutside = (e: MouseEvent) => {
+ const menu = listRef.current;
+ if (menu && !menu.contains(e.target as Node)) {
+ closeMenu();
+ }
+ };
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => {
+ document.removeEventListener('mousedown', handleClickOutside);
+ };
+ }, [isOpen, closeMenu, listRef]);
+
+ const listKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ const focused = document.activeElement as HTMLElement | null;
+ if (focused?.getAttribute('role') === 'menuitem') {
+ focused.click();
+ }
+ return;
+ }
+ listNavKeyDown(e);
+ },
+ [listNavKeyDown],
+ );
+
+ const handleContextMenu = useCallback(
+ (e: React.MouseEvent) => {
+ if (isDisabled) return;
+ e.preventDefault();
+ positionRef.current = {x: e.clientX, y: e.clientY};
+ layer.show();
+ if (hasAutoFocus) {
+ requestAnimationFrame(() => focusFirst());
+ }
+ },
+ [isDisabled, layer, hasAutoFocus, focusFirst],
+ );
+
+ const popoverXstyle = menuWidth
+ ? styles.popoverCustomWidth(menuWidth)
+ : styles.popover;
+
+ const contextValue = useMemo<XDSDropdownMenuContextValue>(
+ () => ({closeMenu, menuSize: size}),
+ [closeMenu, size],
+ );
+
+ const resolvedMenuContent =
+ props.items !== undefined ? renderXDSDropdownItems(items) : menuContent;
+
+ return (
+ <>
+ <div ref={ref} onContextMenu={handleContextMenu} data-testid={testId}>
+ {children}
+ </div>
+
+ {layer.render(
+ <div
+ ref={listRef as React.RefObject<HTMLDivElement>}
+ id={menuId}
+ role="menu"
+ onKeyDown={listKeyDown}
+ {...mergeProps(
+ xdsClassName('context-menu'),
+ stylex.props(styles.menu, xstyle),
+ className,
+ style,
+ )}>
+ <XDSDropdownMenuContext.Provider value={contextValue}>
+ {resolvedMenuContent}
+ </XDSDropdownMenuContext.Provider>
+ </div>,
+ {
+ x: positionRef.current.x,
+ y: positionRef.current.y,
+ xstyle: [popoverXstyle, layerAnimations.below],
+ },
+ )}
+ </>
+ );
+}
+
+XDSContextMenu.displayName = 'XDSContextMenu';
diff --git a/packages/core/src/ContextMenu/index.ts b/packages/core/src/ContextMenu/index.ts
new file mode 100644
index 0000000000..90a82f91f4
--- /dev/null
+++ b/packages/core/src/ContextMenu/index.ts
@@ -0,0 +1,22 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+'use client';
+
+/**
+ * @file index.ts
+ * @output Exports XDSContextMenu, XDSContextMenuItem and related types
+ * @position Public API entry point
+ */
+
+export {
+ XDSContextMenu,
+ type XDSContextMenuProps,
+ type XDSContextMenuItemData,
+ type XDSContextMenuDivider,
+ type XDSContextMenuSection,
+ type XDSContextMenuOption,
+} from './XDSContextMenu';
+
+export {
+ XDSDropdownMenuItem as XDSContextMenuItem,
+ type XDSDropdownMenuItemProps as XDSContextMenuItemProps,
+} from '../DropdownMenu/XDSDropdownMenuItem';
diff --git a/packages/core/src/DateTimePicker/DateTimePicker.doc.mjs b/packages/core/src/DateTimePicker/DateTimePicker.doc.mjs
index e3e58e370f..77b83657d4 100644
--- a/packages/core/src/DateTimePicker/DateTimePicker.doc.mjs
+++ b/packages/core/src/DateTimePicker/DateTimePicker.doc.mjs
@@ -1,4 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+
/** @type {import('../docs-types').ComponentDoc} */
export const docs = {
diff --git a/packages/core/src/DateTimePicker/XDSDateTimePicker.test.tsx b/packages/core/src/DateTimePicker/XDSDateTimePicker.test.tsx
index b79c75f09b..124c7a0bea 100644
--- a/packages/core/src/DateTimePicker/XDSDateTimePicker.test.tsx
+++ b/packages/core/src/DateTimePicker/XDSDateTimePicker.test.tsx
@@ -1,4 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+
/**
* @file XDSDateTimePicker.test.tsx
* @input Uses vitest, @testing-library/react, XDSDateTimePicker component
diff --git a/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx b/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx
index d3a7a8f27a..bbc02d732c 100644
--- a/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx
+++ b/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx
@@ -1,4 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+
'use client';
/**
diff --git a/packages/core/src/DateTimePicker/index.ts b/packages/core/src/DateTimePicker/index.ts
index d9ee88ec3c..9a172837a2 100644
--- a/packages/core/src/DateTimePicker/index.ts
+++ b/packages/core/src/DateTimePicker/index.ts
@@ -1,4 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+
'use client';
/**
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index e0a497f3a5..25f287421e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -82,6 +82,7 @@ export * from './TreeList';
export * from './Kbd';
export * from './AlertDialog';
export * from './Dialog';
+export * from './ContextMenu';
export * from './DropdownMenu';
export * from './MoreMenu';
export * from './SizeContext';