Skip to content

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

TypeScript

feat(core): add plugin-contributed context menus to Table (#3256)

Humberto Virtudes071c5bff9895
diff --git a/.changeset/table-context-menu.md b/.changeset/table-context-menu.md
new file mode 100644
index 0000000000..61e95c64b6
--- /dev/null
+++ b/.changeset/table-context-menu.md
@@ -0,0 +1,30 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Add a plugin-contributed right-click context-menu system to `Table`.
+Right-clicking a column header or a row shows a menu of actions aggregated from
+every enabled plugin (instead of the browser's generic menu).
+
+- New `TableContextAction` type and an optional `contextMenuActions` field on
+ `HeaderCellRenderProps` / `BodyCellRenderProps`. Plugins append their actions
+ inside the existing `transformHeaderCell` / `transformBodyCell` transforms;
+ the table concatenates them across plugins (never overridden), the same way
+ `styles` are merged.
+- The cell components (`TableHeaderCell` / `TableCell`) own the menu wrapper and
+ render it around their own content via the `ContextMenuActions` prop, so the
+ cell controls how the wrapper interacts with padding / content sizing — and
+ row menus work without invalid `<tr>` nesting. Actions group with dividers and
+ show a checkmark for the active item; when none are contributed, the native
+ browser menu passes through.
+- `contextMenuActions` accepts either an array or a getter
+ (`() => TableContextAction[]`); the getter is resolved lazily when the menu
+ opens, so plugins with state-derived actions don't build arrays on every
+ render. `useTableSortable` uses a getter so its checked/clear state always
+ reflects the latest sort.
+- First contributor: `useTableSortable` adds "Sort ascending / Sort descending
+ / Clear sort" on sortable headers.
+
+Built on the `ContextMenu` component. Other plugins opt in by setting
+`contextMenuActions` in their cell transforms — no core changes needed.
+@humbertovirtudes
diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsx
index 284b1c293d..95a65e1c35 100644
--- a/packages/core/src/Table/BaseTable.tsx
+++ b/packages/core/src/Table/BaseTable.tsx
@@ -205,6 +205,7 @@ function TableRowInner<T extends Record<string, unknown>>({
<CellComponent
key={col.key}
{...cellRenderProps.htmlProps}
+ contextMenuActions={cellRenderProps.contextMenuActions}
xstyle={cellRenderProps.styles}>
{content}
</CellComponent>
@@ -409,29 +410,32 @@ function BaseTableInner<T extends Record<string, unknown>>({
const hasSlots =
before != null || after != null || overlay != null || below != null;
+ const headerInner = hasSlots ? (
+ <>
+ {before}
+ {after != null ? (
+ <div {...stylex.props(styles.headerLabelRow)}>
+ {resolvedContent}
+ {after}
+ </div>
+ ) : (
+ resolvedContent
+ )}
+ {overlay}
+ {below}
+ </>
+ ) : (
+ resolvedContent
+ );
+
return (
<HeaderCellComponent
key={col.key}
{...mergedHtmlProps}
{...headerTitleProp}
+ contextMenuActions={cellRenderProps.contextMenuActions}
xstyle={cellRenderProps.styles}>
- {hasSlots ? (
- <>
- {before}
- {after != null ? (
- <div {...stylex.props(styles.headerLabelRow)}>
- {resolvedContent}
- {after}
- </div>
- ) : (
- resolvedContent
- )}
- {overlay}
- {below}
- </>
- ) : (
- resolvedContent
- )}
+ {headerInner}
</HeaderCellComponent>
);
});
diff --git a/packages/core/src/Table/TableCell.tsx b/packages/core/src/Table/TableCell.tsx
index 41c337c403..9f090b19cb 100644
--- a/packages/core/src/Table/TableCell.tsx
+++ b/packages/core/src/Table/TableCell.tsx
@@ -24,6 +24,8 @@ import {
typeScaleVars,
} from '../theme/tokens.stylex';
import type {StyleXStyles} from '../theme/types';
+import type {TableContextActions} from './types';
+import {wrapInTableContextMenu} from './tableContextMenu';
import {
overflowStyles,
wrapStyles,
@@ -56,6 +58,12 @@ export interface TableCellProps extends BaseProps<HTMLTableCellElement> {
* Must be a `stylex.create()` value — not an inline style object.
*/
xstyle?: StyleXStyles | StyleXStyles[];
+ /**
+ * Right-click actions rendered as a context menu around the cell content.
+ * The cell owns the wrapper so it controls how the menu interacts with its
+ * padding / content. Empty or undefined renders no menu.
+ */
+ contextMenuActions?: TableContextActions;
}
const densityStyles = stylex.create({
@@ -138,33 +146,27 @@ export function TableCell({
ref,
className: incomingClassName,
style: incomingStyle,
+ contextMenuActions,
...props
}: TableCellProps) {
const ctx = useTableContext();
- if (!ctx) {
- return (
- <td
- ref={ref}
- {...props}
- {...mergeProps(
- themeProps('table-cell'),
- stylex.props(xstyle),
- incomingClassName,
- incomingStyle,
- )}>
- {children}
- </td>
- );
- }
+ // Standalone (no table context) renders plain, with no density/divider styles.
+ const cellStyles: StyleXStyles[] = ctx
+ ? [
+ densityStyles[ctx.density],
+ ctx.textOverflow === 'truncate'
+ ? overflowStyles.cell
+ : wrapStyles.cell,
+ containerEdgeStyles[ctx.density],
+ verticalAlignStyles[ctx.verticalAlign],
+ ...buildDividerStyles(ctx, dividerRowStyles.cell, dividerColumnStyles.cell),
+ ]
+ : [];
- const cellStyles: StyleXStyles[] = [
- densityStyles[ctx.density],
- ctx.textOverflow === 'truncate' ? overflowStyles.cell : wrapStyles.cell,
- containerEdgeStyles[ctx.density],
- verticalAlignStyles[ctx.verticalAlign],
- ...buildDividerStyles(ctx, dividerRowStyles.cell, dividerColumnStyles.cell),
- ];
+ // The cell owns the context-menu wrapper so it controls how the menu
+ // interacts with its padding / content. No-op when no actions.
+ const content = wrapInTableContextMenu(children, contextMenuActions);
return (
<td
@@ -176,7 +178,7 @@ export function TableCell({
incomingClassName,
incomingStyle,
)}>
- {children}
+ {content}
</td>
);
}
diff --git a/packages/core/src/Table/TableHeaderCell.tsx b/packages/core/src/Table/TableHeaderCell.tsx
index c366e2e752..3485224cf1 100644
--- a/packages/core/src/Table/TableHeaderCell.tsx
+++ b/packages/core/src/Table/TableHeaderCell.tsx
@@ -25,8 +25,10 @@ import {
borderVars,
} from '../theme/tokens.stylex';
import type {StyleXStyles} from '../theme/types';
+import type {TableContextActions} from './types';
import {overflowStyles, containerEdgeStyles} from './table.stylex';
import {useTableContext, mergeXStyle} from './useTableCellStyles';
+import {wrapInTableContextMenu} from './tableContextMenu';
import {mergeProps} from '../utils';
import {themeProps} from '../utils/themeProps';
@@ -42,6 +44,12 @@ export interface TableHeaderCellProps extends BaseProps<HTMLTableCellElement> {
* Must be a `stylex.create()` value — not an inline style object.
*/
xstyle?: StyleXStyles | StyleXStyles[];
+ /**
+ * Right-click actions rendered as a context menu around the cell content.
+ * The cell owns the wrapper so it controls how the menu interacts with its
+ * padding / content. Empty or undefined renders no menu.
+ */
+ contextMenuActions?: TableContextActions;
}
const densityStyles = stylex.create({
@@ -117,41 +125,32 @@ export function TableHeaderCell({
ref,
className: incomingClassName,
style: incomingStyle,
+ contextMenuActions,
...props
}: TableHeaderCellProps) {
const ctx = useTableContext();
- if (!ctx) {
- return (
- <th
- ref={ref}
- {...props}
- {...mergeProps(
- themeProps('table-header-cell'),
- stylex.props(xstyle),
- incomingClassName,
- incomingStyle,
- )}>
- {children}
- </th>
+ // Header cells always get the bottom divider (separates header from body).
+ // When used standalone (no table context) the cell renders plain, with no
+ // density/divider styles.
+ const cellStyles: StyleXStyles[] = [];
+ if (ctx) {
+ cellStyles.push(
+ headerStyles.cell,
+ densityStyles[ctx.density],
+ headerDividerStyles.cell,
+ overflowStyles.cell,
+ containerEdgeStyles[ctx.density],
);
+ // Column dividers come from the shared builder (column axis only).
+ if (ctx.dividers === 'columns' || ctx.dividers === 'grid') {
+ cellStyles.push(dividerColumnStyles.cell);
+ }
}
- // Header cells always get the bottom divider (separates header from body).
- // Column dividers use the shared buildDividerStyles — but only for
- // the column axis, since the row divider is the headerDividerStyles.
- const cellStyles: StyleXStyles[] = [
- headerStyles.cell,
- densityStyles[ctx.density],
- headerDividerStyles.cell,
- overflowStyles.cell,
- containerEdgeStyles[ctx.density],
- ];
-
- // Only add column dividers from the shared builder
- if (ctx.dividers === 'columns' || ctx.dividers === 'grid') {
- cellStyles.push(dividerColumnStyles.cell);
- }
+ // The cell owns the context-menu wrapper so it controls how the menu
+ // interacts with its padding / content. No-op when no actions.
+ const content = wrapInTableContextMenu(children, contextMenuActions);
return (
<th
@@ -163,7 +162,7 @@ export function TableHeaderCell({
incomingClassName,
incomingStyle,
)}>
- {children}
+ {content}
</th>
);
}
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index 0b537c3c66..d2412b128b 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -28,6 +28,7 @@ export {useTableColumnSettings} from './plugins/columnSettings';
export {useTableColumnSettingsState} from './plugins/columnSettings';
export {useTableColumnResize} from './plugins/columnResize';
export {useTableStickyColumns} from './plugins/stickyColumns';
+export {resolveContextActions} from './tableContextMenu';
export {
useTableFiltering,
useTableFilterState,
@@ -49,6 +50,8 @@ export type {
ProportionalWidth,
PixelWidth,
TablePlugin,
+ TableContextAction,
+ TableContextActions,
TableRenderProps,
HeaderRowRenderProps,
HeaderCellRenderProps,
diff --git a/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx b/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx
index b479601f47..e19de9dcb4 100644
--- a/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx
+++ b/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx
@@ -7,8 +7,8 @@
* @position Testing; validates sortable plugin implementation
*/
-import {describe, it, expect, vi} from 'vitest';
-import {render, screen} from '@testing-library/react';
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {useState} from 'react';
import {Table} from '../../Table';
@@ -620,3 +620,92 @@ describe('useTableSortable', () => {
});
});
});
+
+// =============================================================================
+// Context-menu actions (colocated with the sortable plugin)
+// =============================================================================
+
+describe('useTableSortable — context menu actions', () => {
+ // jsdom doesn't implement the Popover API; mock it so the menu can "open"
+ // and its items become queryable (as hidden).
+ 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;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+ });
+
+ it('offers Sort ascending/descending on a sortable header, and Clear sort once sorted', () => {
+ render(<SortableTable allowUnsortedState />);
+
+ // Unsorted: asc + desc, no "Clear sort".
+ fireEvent.contextMenu(screen.getByText('Name'));
+ expect(
+ screen.getAllByRole('menuitem', {name: 'Sort ascending', hidden: true})
+ .length,
+ ).toBeGreaterThan(0);
+ expect(
+ screen.getAllByRole('menuitem', {name: 'Sort descending', hidden: true})
+ .length,
+ ).toBeGreaterThan(0);
+ expect(
+ screen.queryByRole('menuitem', {name: 'Clear sort', hidden: true}),
+ ).not.toBeInTheDocument();
+
+ // Apply ascending → "Clear sort" now appears.
+ fireEvent.click(
+ screen.getAllByRole('menuitem', {name: 'Sort ascending', hidden: true})[0],
+ );
+ fireEvent.contextMenu(screen.getByText('Name'));
+ expect(
+ screen.getAllByRole('menuitem', {name: 'Clear sort', hidden: true}).length,
+ ).toBeGreaterThan(0);
+ });
+
+ it('resolves fresh actions on each open as sort state changes (lazy getter)', () => {
+ const onSortChange = vi.fn();
+ render(<SortableTable allowUnsortedState onSortChange={onSortChange} />);
+
+ // Open (unsorted) and pick descending.
+ fireEvent.contextMenu(screen.getByText('Name'));
+ fireEvent.click(
+ screen.getAllByRole('menuitem', {
+ name: 'Sort descending',
+ hidden: true,
+ })[0],
+ );
+ expect(onSortChange).toHaveBeenLastCalledWith([
+ {sortKey: 'name', direction: 'descending'},
+ ]);
+
+ // Re-open: the getter recomputes against the now-descending state, so
+ // "Clear sort" is present and clicking it clears — proving the actions are
+ // freshly derived on each open, not memoized from the first render.
+ fireEvent.contextMenu(screen.getByText('Name'));
+ const clear = screen.getAllByRole('menuitem', {
+ name: 'Clear sort',
+ hidden: true,
+ });
+ expect(clear.length).toBeGreaterThan(0);
+ fireEvent.click(clear[0]);
+ expect(onSortChange).toHaveBeenLastCalledWith([]);
+ });
+});
diff --git a/packages/core/src/Table/plugins/sortable/useTableSortable.tsx b/packages/core/src/Table/plugins/sortable/useTableSortable.tsx
index d4c6ffcd1c..6a6a6fca86 100644
--- a/packages/core/src/Table/plugins/sortable/useTableSortable.tsx
+++ b/packages/core/src/Table/plugins/sortable/useTableSortable.tsx
@@ -17,10 +17,12 @@ import {useRef, useMemo, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars, radiusVars} from '../../../theme/tokens.stylex';
import {Icon} from '../../../Icon';
+import {resolveContextActions} from '../../tableContextMenu';
import type {
TablePlugin,
HeaderCellRenderProps,
TableColumn,
+ TableContextAction,
} from '../../types';
// =============================================================================
@@ -356,10 +358,56 @@ export function useTableSortable<
return props;
}
- // Find sort entry for this column
const cfg = configRef.current;
const entry = cfg.sort.find(e => e.sortKey === sortKey);
+ // Context-menu actions are built lazily (only when the menu opens) via
+ // a getter, reading the current sort state at call time — so we don't
+ // build an action array for every header on every render, and the
+ // checked/clear state always reflects the latest sort.
+ const getSortActions = (): TableContextAction[] => {
+ const c = configRef.current;
+ const dir = c.sort.find(e => e.sortKey === sortKey)?.direction ?? null;
+ const actions: TableContextAction[] = [
+ {
+ id: 'sort-asc',
+ group: 'sort',
+ label: 'Sort ascending',
+ icon: <Icon icon="arrowUp" size="xsm" aria-hidden />,
+ checked: dir === 'ascending',
+ onSelect: () =>
+ c.onSortChange([
+ {sortKey: sortKey as TSortKey, direction: 'ascending'},
+ ]),
+ },
+ {
+ id: 'sort-desc',
+ group: 'sort',
+ label: 'Sort descending',
+ icon: <Icon icon="arrowDown" size="xsm" aria-hidden />,
+ checked: dir === 'descending',
+ onSelect: () =>
+ c.onSortChange([
+ {sortKey: sortKey as TSortKey, direction: 'descending'},
+ ]),
+ },
+ ];
+ if (dir != null) {
+ actions.push({
+ id: 'sort-clear',
+ group: 'sort-clear',
+ label: 'Clear sort',
+ icon: <Icon icon="close" size="xsm" aria-hidden />,
+ onSelect: () =>
+ c.onSortChange(c.sort.filter(e => e.sortKey !== sortKey)),
+ });
+ }
+ return actions;
+ };
+
+ // Merge with any actions a prior plugin contributed (array or getter),
+ // resolving both lazily at open time.
+ const priorActions = props.contextMenuActions;
return {
...props,
htmlProps: {
@@ -375,6 +423,10 @@ export function useTableSortable<
{props.content}
</SortHeaderButton>
),
+ contextMenuActions: () => [
+ ...resolveContextActions(priorActions),
+ ...getSortActions(),
+ ],
};
},
}),
diff --git a/packages/core/src/Table/tableContextMenu.test.tsx b/packages/core/src/Table/tableContextMenu.test.tsx
new file mode 100644
index 0000000000..a3036b5d03
--- /dev/null
+++ b/packages/core/src/Table/tableContextMenu.test.tsx
@@ -0,0 +1,157 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file tableContextMenu.test.tsx
+ * @output Tests for the Table context-menu system
+ * @position Validates contextMenuActions aggregation + header context menus
+ */
+
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {Table} from './Table';
+import type {TablePlugin, TableColumn} from './types';
+import {resolveContextActions} from './tableContextMenu';
+
+// jsdom doesn't implement the Popover API; mirror the ContextMenu test's mock
+// so the menu can "open" and its items become queryable (as hidden).
+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;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+interface Row extends Record<string, unknown> {
+ id: string;
+ name: string;
+}
+
+const data: Row[] = [
+ {id: '1', name: 'Alice'},
+ {id: '2', name: 'Bob'},
+];
+
+const columns: TableColumn<Row>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'id', header: 'ID'},
+];
+
+// =============================================================================
+// contextMenuActions via transformHeaderCell
+// =============================================================================
+
+describe('Table header context menu', () => {
+ it('renders a menu from a plugin that sets contextMenuActions', () => {
+ const onSelect = vi.fn();
+ const plugin: TablePlugin<Row> = {
+ transformHeaderCell: props => ({
+ ...props,
+ contextMenuActions: [{id: 'pin', label: 'Pin column', onSelect}],
+ }),
+ };
+ render(
+ <Table data={data} columns={columns} idKey="id" plugins={{plugin}} />,
+ );
+ fireEvent.contextMenu(screen.getByText('Name'));
+ const items = screen.getAllByRole('menuitem', {
+ name: 'Pin column',
+ hidden: true,
+ });
+ expect(items.length).toBeGreaterThan(0);
+ fireEvent.click(items[0]);
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ });
+
+ it('concatenates actions from multiple plugins (never overridden)', () => {
+ const a: TablePlugin<Row> = {
+ transformHeaderCell: props => ({
+ ...props,
+ contextMenuActions: [
+ ...resolveContextActions(props.contextMenuActions),
+ {id: 'a', label: 'Action A', onSelect: () => {}},
+ ],
+ }),
+ };
+ const b: TablePlugin<Row> = {
+ transformHeaderCell: props => ({
+ ...props,
+ contextMenuActions: [
+ ...resolveContextActions(props.contextMenuActions),
+ {id: 'b', label: 'Action B', onSelect: () => {}},
+ ],
+ }),
+ };
+ render(
+ <Table data={data} columns={columns} idKey="id" plugins={{a, b}} />,
+ );
+ fireEvent.contextMenu(screen.getByText('Name'));
+ expect(
+ screen.getAllByRole('menuitem', {name: 'Action A', hidden: true}).length,
+ ).toBeGreaterThan(0);
+ expect(
+ screen.getAllByRole('menuitem', {name: 'Action B', hidden: true}).length,
+ ).toBeGreaterThan(0);
+ });
+
+ it('does not render a menu when no plugin contributes actions', () => {
+ render(<Table data={data} columns={columns} idKey="id" />);
+ fireEvent.contextMenu(screen.getByText('Name'));
+ expect(
+ screen.queryByRole('menuitem', {hidden: true}),
+ ).not.toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// Body / row context menu
+// =============================================================================
+
+describe('Table body context menu', () => {
+ it('renders row actions from a plugin that sets contextMenuActions in transformBodyCell', () => {
+ const onSelect = vi.fn();
+ const plugin: TablePlugin<Row> = {
+ transformBodyCell: (props, _column, item) => ({
+ ...props,
+ contextMenuActions: [
+ {
+ id: `delete-${item.id}`,
+ label: 'Delete row',
+ onSelect: () => {
+ onSelect(item.id);
+ },
+ },
+ ],
+ }),
+ };
+ render(
+ <Table data={data} columns={columns} idKey="id" plugins={{plugin}} />,
+ );
+ // Right-click the first body cell (Alice).
+ fireEvent.contextMenu(screen.getByText('Alice'));
+ const items = screen.getAllByRole('menuitem', {
+ name: 'Delete row',
+ hidden: true,
+ });
+ expect(items.length).toBeGreaterThan(0);
+ fireEvent.click(items[0]);
+ expect(onSelect).toHaveBeenCalledWith('1');
+ });
+});
diff --git a/packages/core/src/Table/tableContextMenu.tsx b/packages/core/src/Table/tableContextMenu.tsx
new file mode 100644
index 0000000000..45f5634866
--- /dev/null
+++ b/packages/core/src/Table/tableContextMenu.tsx
@@ -0,0 +1,146 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file tableContextMenu.tsx
+ * @input React, ContextMenu, Icon, types
+ * @output wrapInTableContextMenu helper
+ * @position Renders the aggregated `contextMenuActions` for a header cell / row
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Table/BaseTable.tsx (call sites)
+ * - /packages/core/src/Table/types.ts (TableContextAction)
+ */
+
+import {useState, type ReactNode} from 'react';
+import {ContextMenu, type ContextMenuOption} from '../ContextMenu';
+import {Icon} from '../Icon';
+import type {TableContextAction, TableContextActions} from './types';
+
+/**
+ * Resolve a `contextMenuActions` value (array or getter) to a plain array.
+ * Use this when composing actions from a prior plugin's render props so you
+ * don't have to branch on the array-vs-getter form:
+ *
+ * ```
+ * contextMenuActions: () => [
+ * ...resolveContextActions(props.contextMenuActions),
+ * ...myActions,
+ * ]
+ * ```
+ */
+export function resolveContextActions(
+ actions: TableContextActions | undefined,
+): TableContextAction[] {
+ if (typeof actions === 'function') {
+ return actions();
+ }
+ return actions ?? [];
+}
+
+/**
+ * Convert the flat action list into ContextMenu options, inserting a divider
+ * between groups (first-seen group order). Ungrouped actions form a trailing
+ * group. A `checked` action shows a trailing check icon.
+ */
+function toContextMenuOptions(
+ actions: TableContextAction[],
+): ContextMenuOption[] {
+ const order: string[] = [];
+ const buckets = new Map<string, TableContextAction[]>();
+ for (const action of actions) {
+ const key = action.group ?? '__ungrouped__';
+ let bucket = buckets.get(key);
+ if (!bucket) {
+ bucket = [];
+ buckets.set(key, bucket);
+ order.push(key);
+ }
+ bucket.push(action);
+ }
+
+ const options: ContextMenuOption[] = [];
+ order.forEach((key, groupIndex) => {
+ if (groupIndex > 0) {
+ options.push({type: 'divider'});
+ }
+ for (const action of buckets.get(key) ?? []) {
+ options.push({
+ label: typeof action.label === 'string' ? action.label : action.id,
+ // A checked action (e.g. the active sort direction) shows a checkmark;
+ // otherwise the action's own icon. ContextMenu's data form takes a
+ // single leading icon, so checked state replaces the icon.
+ icon: action.checked ? (
+ <Icon icon="check" size="xsm" aria-hidden />
+ ) : (
+ action.icon
+ ),
+ isDisabled: action.disabled,
+ onClick: action.onSelect,
+ });
+ }
+ });
+ return options;
+}
+
+/**
+ * Wrap a table element (a header cell's content or a row) in a right-click
+ * context menu rendering the aggregated `actions`. When no plugin contributes
+ * actions the element is returned untouched so the native browser menu passes
+ * through.
+ */
+/**
+ * A context menu whose actions are resolved lazily — only when the user opens
+ * the menu (right-click). Deferring the work means plugins that pass a getter
+ * don't build an action array (with its closures) for every cell on every
+ * render; it's computed on demand and memoized until the menu closes.
+ */
+function LazyTableContextMenu({
+ element,
+ getActions,
+}: {
+ element: ReactNode;
+ getActions: () => TableContextAction[];
+}): ReactNode {
+ const [options, setOptions] = useState<ContextMenuOption[] | null>(null);
+ return (
+ <ContextMenu
+ items={options ?? []}
+ hasAutoFocus={false}
+ onOpenChange={open => {
+ // Resolve actions when opening; clear on close so state derived later
+ // (e.g. current sort direction) is always fresh next open.
+ setOptions(open ? toContextMenuOptions(getActions()) : null);
+ }}>
+ {element}
+ </ContextMenu>
+ );
+}
+
+/**
+ * Wrap a table element (a header cell's content or a body cell) in a right-click
+ * context menu rendering the aggregated `actions`. Accepts a static array or a
+ * getter (resolved lazily on open). When there are no actions the element is
+ * returned untouched so the native browser menu passes through.
+ */
+export function wrapInTableContextMenu(
+ element: ReactNode,
+ actions: TableContextActions | undefined,
+): ReactNode {
+ // Getter form → resolve lazily on open.
+ if (typeof actions === 'function') {
+ return <LazyTableContextMenu element={element} getActions={actions} />;
+ }
+ if (!actions || actions.length === 0) {
+ return element;
+ }
+ // hasAutoFocus={false}: a right-click menu shouldn't pre-highlight the first
+ // item (it looked like "ascending" was always selected). Focus moves only
+ // when the user arrow-keys into the menu.
+ return (
+ <ContextMenu items={toContextMenuOptions(actions)} hasAutoFocus={false}>
+ {element}
+ </ContextMenu>
+ );
+}
diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.ts
index 898dc8e2f2..ba47893233 100644
--- a/packages/core/src/Table/types.ts
+++ b/packages/core/src/Table/types.ts
@@ -261,6 +261,12 @@ export interface HeaderCellRenderProps {
overlay?: ReactNode;
/** Content rendered below the header label row (e.g. inline filter controls). */
below?: ReactNode;
+ /**
+ * Right-click context-menu actions for this header cell. Plugins append
+ * their actions in `transformHeaderCell`; BaseTable concatenates the arrays
+ * across plugins (never overridden) and renders one menu per header cell.
+ */
+ contextMenuActions?: TableContextActions;
/**
* Index of this column within the final, ordered list of rendered columns
* (after column injection/reordering by other plugins). Populated by
@@ -290,6 +296,13 @@ export interface BodyRowRenderProps {
export interface BodyCellRenderProps {
htmlProps: TdHTMLAttributes<HTMLTableCellElement>;
styles: StyleXStyles[];
+ /**
+ * Right-click context-menu actions for this body cell. Plugins append their
+ * actions in `transformBodyCell`; BaseTable concatenates the arrays across
+ * plugins and across the row's cells (never overridden) and renders one menu
+ * per row.
+ */
+ contextMenuActions?: TableContextActions;
/**
* Index of this cell's column within the final ordered column list.
* Mirrors the `columnIndex` passed to `transformHeaderCell`. Populated by
@@ -335,6 +348,50 @@ export interface ScrollWrapperRenderProps {
afterTable?: ReactNode;
}
+// =============================================================================
+// Context-menu actions
+// =============================================================================
+
+/**
+ * A single right-click context-menu action contributed by a plugin.
+ *
+ * Plugins contribute actions via the `contextMenuActions` field on
+ * `HeaderCellRenderProps` / `BodyCellRenderProps` (set in
+ * `transformHeaderCell` / `transformBodyCell`); the table aggregates actions
+ * from every enabled plugin into a single menu per header cell / row.
+ */
+export interface TableContextAction {
+ /** Stable identifier, unique within a single menu. */
+ id: string;
+ /** Visible label for the menu item. */
+ label: ReactNode;
+ /** Optional leading icon. */
+ icon?: ReactNode;
+ /** Invoked when the item is selected. */
+ onSelect: () => void;
+ /** When true, the item is rendered but not selectable. */
+ disabled?: boolean;
+ /**
+ * Group key used to cluster related actions and insert a divider between
+ * groups (e.g. 'sort', 'selection'). Actions without a group form a trailing
+ * group. Group order follows first-seen order across the aggregated list.
+ */
+ group?: string;
+ /** When true, the item renders as checked (e.g. the active sort direction). */
+ checked?: boolean;
+}
+
+/**
+ * Context-menu actions for a cell — either a static array, or a getter that
+ * returns the actions lazily. Prefer the getter for actions derived from state
+ * (e.g. the active sort direction): it's only invoked when the menu is opened,
+ * so the plugin doesn't build an action array (with closures) for every cell on
+ * every render.
+ */
+export type TableContextActions =
+ | TableContextAction[]
+ | (() => TableContextAction[]);
+
// =============================================================================
// Plugin Interface
// =============================================================================
@@ -353,6 +410,10 @@ export interface ScrollWrapperRenderProps {
* 6. `transformBodyCell` — transform each body `<td>` props
* 7. `transformScrollWrapper` — transform the scroll-container wrapper around the table
* 8. `transformTableContext` — wrap the table output in context providers
+ *
+ * Plugins may also contribute right-click menu actions by appending to
+ * `contextMenuActions` in `transformHeaderCell` / `transformBodyCell`
+ * (aggregated into one menu per header cell / row).
*/
export interface TablePlugin<
T extends Record<string, unknown> = Record<string, unknown>,
@@ -432,12 +493,25 @@ export interface TableRowComponentProps extends HTMLAttributes<HTMLTableRowEleme
export interface TableCellComponentProps extends TdHTMLAttributes<HTMLTableCellElement> {
children?: ReactNode;
xstyle?: StyleXStyles | StyleXStyles[];
+ /**
+ * Right-click actions to render as a context menu around the cell content.
+ * The cell owns the menu wrapper so it can control how it interacts with
+ * padding / content sizing. Empty/undefined renders no menu (native passes
+ * through).
+ */
+ contextMenuActions?: TableContextActions;
}
/** Props for header cell components used in the components prop */
export interface TableHeaderCellComponentProps extends ThHTMLAttributes<HTMLTableCellElement> {
children?: ReactNode;
xstyle?: StyleXStyles | StyleXStyles[];
+ /**
+ * Right-click actions to render as a context menu around the header content.
+ * The cell owns the menu wrapper so it can control how it interacts with
+ * padding / content sizing. Empty/undefined renders no menu.
+ */
+ contextMenuActions?: TableContextActions;
}
// =============================================================================