Skip to content

Commit 8c80a72

Browse files
authored
Merge pull request #15 from OpenCoreStack/feat/context-menu
feat: context menu for cells (3.11.0)
2 parents 924e036 + b8229e4 commit 8c80a72

52 files changed

Lines changed: 2283 additions & 77 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,19 @@
77

88
## [Unreleased]
99

10+
## [3.11.0] — 2026-10-26
11+
1012
### Added
1113

14+
- **Context menu** (`contextMenu`). Right-click, Shift+F10 / the Menu key on a focused cell, or Ctrl+click on Apple devices opens a menu of cell actions: Copy, Copy with headers, and Undo / Redo with `undoRedo` (disabled when there is nothing to undo or redo). Inside the current cell range, Copy writes the range (the same text as Ctrl/Cmd+C) and the range and focus stay; elsewhere it copies the clicked cell and focus moves there. `getContextMenuItems(params, defaultItems)` returns the entries (items and `'divider'`; leading, trailing and consecutive dividers are dropped); a list with no items shows no menu and leaves the browser's own menu. Headers, the header filter row, the footer, detail panels, editors, checkbox / expand / reorder cells and nested grids keep the browser menu. The menu closes on a choice, Escape or Tab (focus returns to the cell), an outside press, grid scroll, window resize and when its row leaves the rendered rows. New public types `GridContextMenuParams`, `GridContextMenuItem`, `GridContextMenuEntry`; `apiRef.openContextMenu(id, field)` and `closeContextMenu()`; `localeText` keys `contextMenuCopy`, `contextMenuCopyWithHeaders`, `contextMenuUndo`, `contextMenuRedo`, `contextMenuLabel`. Not covered: the header menu, touch long-press, Paste and Export built-ins. Guide: `docs/features/context-menu.md`; demo page **Context Menu**.
15+
1216
- **Dev warning for re-created `localeText` functions.** A `localeText` whose function entries (`paginationOf`, `rowSelectLabel`, …) are written inline is a new object on every render, and every rendered row reads the locale, so each parent render re-rendered all of them. The grid now warns once in development, naming the entries, after three renders in a row re-create the same function. Behaviour is unchanged: the functions are not frozen, so one that reads new state (a language switch) still updates the rows.
1317

18+
### Changed
19+
20+
- `GridApi` gained `openContextMenu` / `closeContextMenu`; this affects only code that implements `GridApi` itself. `openContextMenu` opens the menu on a later animation frame, after the cell is scrolled into view, and opens nothing if the cell is not rendered within a few frames or its row moved; tests should wait for `role="menu"`.
21+
- `ColumnMenu` and the context menu share one keyboard handler (`useMenuKeyboard`). Internal; the column menu's behaviour is unchanged.
22+
1423
## [3.10.1] — 2026-10-13
1524

1625
### Fixed

‎CLAUDE.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ This file is auto-loaded by Claude Code and other AI coding assistants. It provi
1414
- **Build:** `npm run build:lib` produces the published `dist/opengridx.es.js` / `dist/opengridx.umd.js`. `npm run build` type-checks the lib and builds the **demo site**.
1515
- **Published:** yes — on npm as `@opencorestack/opengridx` with external consumers. Treat public types and behaviour changes as semver-relevant.
1616
- **Lint:** `npm run lint` (ESLint). Must pass before every commit.
17-
- **Current version:** 3.10.1
17+
- **Current version:** 3.11.0
1818

1919
---
2020

@@ -157,6 +157,14 @@ The GitHub wiki is generated from `docs/` + `wiki/` by `scripts/build-wiki.mjs`
157157

158158
---
159159

160+
## v3.11.0 — significant changes
161+
162+
- **Context menu** (`contextMenu`, `getContextMenuItems`; guide `docs/features/context-menu.md`). Hook step 37a `useGridContextMenu`: a native `contextmenu` listener on the grid root; the row comes from `data-rowindex`, which already indexes [top-pinned, page rows, bottom-pinned], so there is no pinned offset. `openAt` reaches keyboard navigation (Shift+F10 / Menu key) through a ref created before `useGridKeyboardNavigation`
163+
- `useMenuKeyboard` (`lib/components/ui`) is shared by `ColumnMenu` and `GridContextMenu`; its Escape handler is document-level
164+
- A right press (or Apple Ctrl+left) inside the cell range is `preventDefault`-ed on mousedown in the capture phase, so focus does not collapse the range. Menu state is cleared during render when its row leaves the rendered rows (no effect)
165+
- Copy goes through `buildCellCopyText` / `getCopyText({ includeHeaders })` (header line `headerName ?? field`); synthetic rows are skipped
166+
- Browser tests right-click with `userEvent.click(el, { button: 'right' })` (`pointer({ keys: '[MouseRight]' })` does not exist in Vitest's Playwright provider)
167+
160168
## v3.10.0 — significant changes
161169

162170
- **CI guards** (each fails the build): `check:versions` (`llms.txt` + its demo copy, CLAUDE.md "Current version" and a CHANGELOG entry must match `package.json`; bump them together), `check:compiler` (React Compiler: only the allowlisted `EXPECTED` results in `scripts/check-react-compiler.mjs`), `check:package` (no test artifacts, DataGrid-only size budget), ESLint `no-explicit-any` (now `error`, also in the demo) and `no-restricted-syntax` against `as unknown as` in `lib/` outside the boundary files listed in `eslint.config.js`

‎demo/App.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ const PdfExportDemo = lazy(() => import('./examples/PdfExportDemo/PdfExportDemo'
5454
const MultiSortDemo = lazy(() => import('./examples/MultiSortDemo/MultiSortDemo'));
5555
const HeaderWrapDemo = lazy(() => import('./examples/HeaderWrapDemo/HeaderWrapDemo'));
5656
const HeaderFiltersDemo = lazy(() => import('./examples/HeaderFiltersDemo/HeaderFiltersDemo'));
57+
const ContextMenuDemo = lazy(() => import('./examples/ContextMenuDemo/ContextMenuDemo'));
5758
const RtlDemo = lazy(() => import('./examples/RtlDemo/RtlDemo'));
5859

5960
// Sidebar order: categories and pages most developers look for first come first. Paths never change
@@ -103,6 +104,7 @@ const examplesConfig = [
103104
// Selection & spreadsheet
104105
{ path: '/cell-selection', name: 'Cell Range Selection', component: CellSelectionDemo, category: 'Selection & spreadsheet' },
105106
{ path: '/fill-handle', name: 'Fill Handle', component: FillHandleDemo, category: 'Selection & spreadsheet' },
107+
{ path: '/context-menu', name: 'Context Menu', component: ContextMenuDemo, category: 'Selection & spreadsheet' },
106108

107109
// Layout
108110
{ path: '/col-grouping', name: 'Column Grouping', component: ColumnGroupingExample, category: 'Layout' },
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import { useState } from 'react';
2+
import {
3+
DataGrid,
4+
exportToCsv,
5+
useGridApiRef,
6+
type GridColDef,
7+
type GridContextMenuEntry,
8+
type GridContextMenuParams,
9+
} from '@opencorestack/opengridx';
10+
import { DocsLayout } from '../../components/DocsLayout';
11+
import { CodeBlock } from '../../components/CodeBlock';
12+
import '../PasteDemos.css';
13+
14+
import sourceCode from './ContextMenuDemo.tsx?raw';
15+
16+
interface Employee {
17+
id: number;
18+
name: string;
19+
department: string;
20+
salary: number;
21+
city: string;
22+
}
23+
24+
const initialRows: Employee[] = [
25+
{ id: 1, name: 'Ada Lovelace', department: 'Engineering', salary: 128000, city: 'London' },
26+
{ id: 2, name: 'Grace Hopper', department: 'Engineering', salary: 134000, city: 'New York' },
27+
{ id: 3, name: 'Alan Turing', department: 'Research', salary: 121000, city: 'Manchester' },
28+
{ id: 4, name: 'Margaret Hamilton', department: 'Engineering', salary: 139000, city: 'Boston' },
29+
{ id: 5, name: 'Katherine Johnson', department: 'Research', salary: 117000, city: 'Hampton' },
30+
{ id: 6, name: 'Edsger Dijkstra', department: 'Research', salary: 125000, city: 'Austin' },
31+
{ id: 7, name: 'Barbara Liskov', department: 'Design', salary: 119000, city: 'Cambridge' },
32+
{ id: 8, name: 'Donald Knuth', department: 'Design', salary: 131000, city: 'Stanford' },
33+
{ id: 9, name: 'Radia Perlman', department: 'Support', salary: 98000, city: 'Seattle' },
34+
{ id: 10, name: 'Tim Berners-Lee', department: 'Support', salary: 102000, city: 'London' },
35+
];
36+
37+
const columns: GridColDef<Employee>[] = [
38+
{ field: 'name', headerName: 'Name', width: 180, editable: true },
39+
{ field: 'department', headerName: 'Department', width: 140, editable: true },
40+
{ field: 'salary', headerName: 'Salary', type: 'number', width: 120, editable: true },
41+
{ field: 'city', headerName: 'City', width: 140, editable: true },
42+
];
43+
44+
const snippet = `<DataGrid
45+
rows={rows}
46+
columns={columns}
47+
cellSelection // Copy then copies the selected range
48+
undoRedo // adds Undo and Redo to the menu
49+
contextMenu
50+
getContextMenuItems={(params, defaultItems) => [
51+
...defaultItems,
52+
'divider',
53+
{ id: 'export', label: 'Export CSV',
54+
onClick: () => exportToCsv(params.api.getAllFilteredRows(), columns) },
55+
{ id: 'delete', label: 'Delete row', danger: true,
56+
onClick: () => removeRow(params.id) },
57+
]}
58+
/>
59+
60+
// Return [] to show no menu (the browser menu then shows instead).`;
61+
62+
export default function ContextMenuDemo() {
63+
const apiRef = useGridApiRef<Employee>();
64+
const [rows, setRows] = useState(initialRows);
65+
const [log, setLog] = useState<string[]>([]);
66+
67+
const note = (text: string) => setLog(prev => [text, ...prev].slice(0, 6));
68+
69+
const getContextMenuItems = (
70+
params: GridContextMenuParams<Employee>,
71+
defaultItems: readonly GridContextMenuEntry[],
72+
): GridContextMenuEntry[] => [
73+
...defaultItems,
74+
'divider',
75+
{
76+
id: 'export',
77+
label: 'Export CSV',
78+
onClick: () => {
79+
exportToCsv(params.api.getAllFilteredRows(), columns, { fileName: 'employees.csv' });
80+
note('Exported employees.csv');
81+
},
82+
},
83+
{
84+
id: 'delete',
85+
label: `Delete ${params.row.name}`,
86+
danger: true,
87+
onClick: () => {
88+
setRows(prev => prev.filter(r => r.id !== params.id));
89+
note(`Deleted row ${params.id} (${params.row.name})`);
90+
},
91+
},
92+
];
93+
94+
return (
95+
<DocsLayout
96+
title="Context Menu"
97+
description={
98+
<>
99+
With <code>contextMenu</code> on, right-clicking a body cell (or pressing <kbd>Shift + F10</kbd>)
100+
opens a menu of cell actions: Copy, Copy with headers, and Undo / Redo when <code>undoRedo</code> is
101+
on. <code>getContextMenuItems</code> adds your own items, here Export CSV and a danger Delete row.
102+
</>
103+
}
104+
sourceCode={sourceCode}
105+
>
106+
<div className="paste-demo">
107+
<section className="paste-demo__sample">
108+
<strong>Try it</strong>
109+
<ul>
110+
<li>Drag over a few cells, then right-click inside the range: Copy copies the whole range and the range stays.</li>
111+
<li>Right-click a cell outside the range: the range collapses to that cell.</li>
112+
<li>Edit a cell, then right-click and choose Undo.</li>
113+
<li>Focus a cell with the arrow keys and press <kbd>Shift + F10</kbd>; <kbd>Esc</kbd> closes the menu and returns to the cell.</li>
114+
<li>Right-click a column header: the browser's own menu shows.</li>
115+
</ul>
116+
</section>
117+
118+
<DataGrid<Employee>
119+
rows={rows}
120+
columns={columns}
121+
apiRef={apiRef}
122+
cellSelection
123+
undoRedo
124+
contextMenu
125+
getContextMenuItems={getContextMenuItems}
126+
processRowUpdate={(row) => {
127+
setRows(prev => prev.map(r => (r.id === row.id ? row : r)));
128+
return row;
129+
}}
130+
height={380}
131+
/>
132+
133+
<section className="paste-demo__summary">
134+
<strong>Actions (latest first)</strong>
135+
{log.length === 0 && <p>Choose Export CSV or Delete from the menu.</p>}
136+
<ol className="paste-demo__history">
137+
{log.map((entry, i) => <li key={`${i}-${entry}`}>{entry}</li>)}
138+
</ol>
139+
</section>
140+
141+
<CodeBlock code={snippet} />
142+
</div>
143+
</DocsLayout>
144+
);
145+
}

‎demo/public/llms.txt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# OpenGridX — AI Agent Context
22
# Package: @opencorestack/opengridx
3-
# Version: 3.10.1
3+
# Version: 3.11.0
44
# Docs: https://opencorestack.github.io/OpenGridX/
55
# This file is machine-readable. AI developers: start here.
66

@@ -736,3 +736,4 @@ Arrows move between cells (skipping hidden columns); Home/End, Ctrl+Home/End, Pa
736736
28. **3.10**: the AI assistant's change chips are `localeText` keys too (`aiAssistantChipSort(field, direction)`, `aiAssistantChipSummary(fn, field)`, …). Select-all at 1M rows takes ~130 ms. The library forbids `as unknown as` outside documented boundaries and `any` everywhere (ESLint), and CI checks that `llms.txt`, CLAUDE.md and the CHANGELOG name the `package.json` version.
737737
29. **Large client-side datasets**: sorting or filtering 1M rows blocks for ~0.4–0.5 s (one native sort). There is no time-sliced mode (measured and rejected: 1.5–2× slower overall). For interactive sorting and filtering at that size use a `dataSource`.
738738
30. **3.10.1**: at 1M rows select-all ~60–90 ms, deselect-all < 50 ms, applying a grouping ~190 ms, the quick filter's first search ~1.6–2 s (later keystrokes ~210 ms). Grouping creates leaf tree nodes and row metadata only when read, still one `params.rowMeta` object per row. A Next.js 16 App Router fixture in the package smoke suite re-checks the Next.js guide on every CI run.
739+
31. **Context menu (3.11+)**: `contextMenu` shows Copy, Copy with headers and (with `undoRedo`) Undo / Redo on right-click, Shift+F10 / the Menu key or macOS Ctrl+click over a body cell. `getContextMenuItems(params, defaultItems)` returns items and `'divider'`; an empty list shows no menu and the browser menu shows. Right-click inside a cell range copies the range and keeps it; elsewhere it copies the clicked cell. `apiRef.openContextMenu(id, field)` / `closeContextMenu()`; `localeText` keys `contextMenu*`. Types `GridContextMenuParams`, `GridContextMenuItem`, `GridContextMenuEntry`. Headers, footer, editors and detail panels keep the browser menu; no touch long-press. Guide: `docs/features/context-menu.md`.

‎docs/API_REFERENCE.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,31 @@ interface GridHistoryChangeParams { canUndo: boolean; canRedo: boolean; size: nu
113113
interface GridUndoRedoOptions { limit?: number }
114114
```
115115

116+
#### Context Menu (v3.11)
117+
118+
| Prop | Type | Default | Description |
119+
| :--- | :--- | :--- | :--- |
120+
| `contextMenu` | `boolean` | `false` | Shows a menu on right-click, Shift+F10 / the Menu key or macOS Ctrl+click over a body cell: Copy, Copy with headers, and Undo / Redo with `undoRedo`. Headers, the header filter row, the footer, detail panels, editors, checkbox / expand / reorder cells and nested grids keep the browser menu. See [Context Menu](features/context-menu.md). |
121+
| `getContextMenuItems` | `(params: GridContextMenuParams<R>, defaultItems: readonly GridContextMenuEntry[]) => readonly GridContextMenuEntry[]` | — | Builds the menu for the cell it opens on from the built-in items. An empty list shows no menu (the browser menu shows). A throw falls back to the built-in items with one dev warning. Does nothing without `contextMenu` (dev warning). |
122+
123+
```ts
124+
interface GridContextMenuParams<R> {
125+
id: GridRowId; field: string; row: R; colDef: GridColDef<R>;
126+
value: unknown; // read through valueGetter
127+
rowMeta: GridRowMeta | undefined;
128+
cellRange: GridCellSelectionModel | null;
129+
api: GridApi<R>;
130+
}
131+
interface GridContextMenuItem {
132+
id: string; // built-ins: 'copy', 'copyWithHeaders', 'undo', 'redo'
133+
label: string; onClick?: () => void; disabled?: boolean;
134+
shortcut?: string; icon?: React.ReactNode; danger?: boolean;
135+
}
136+
type GridContextMenuEntry = GridContextMenuItem | 'divider';
137+
```
138+
139+
Public CSS: `ogx-context-menu`, `ogx-context-menu__item` (`--danger`, `--disabled`), `ogx-context-menu__shortcut`. Locale keys: `contextMenuCopy`, `contextMenuCopyWithHeaders`, `contextMenuUndo`, `contextMenuRedo`, `contextMenuLabel`.
140+
116141
#### Fill Handle (v3.5)
117142

118143
| Prop | Type | Default | Description |
@@ -419,6 +444,8 @@ Access these methods via the `apiRef` prop.
419444
| `setPivotModel(model)` | `void` | Replace the pivot model. Fires `onPivotModelChange` (v3.5). |
420445
| `getGridAiState()` | `GridAiState` | The current `filterModel`, `sortModel`, `rowGroupingModel`, `aggregationModel`, `pivotModel` and `columnVisibilityModel`, as the AI toolkit reads them. Like the other getters it sees a setter's value in the same tick (v3.5). |
421446
| `openAiAssistant()` / `closeAiAssistant()` | `void` | Open or close the `aiAssistant` panel; `openAiAssistant` does nothing without `aiAssistant` (v3.5). |
447+
| `openContextMenu(id, field)` | `void` | Scroll a cell into view and open the context menu on it on a later animation frame. Does nothing without `contextMenu`, and the menu does not open if the cell is not rendered within a few frames or its row moved in the meantime; tests should wait for `role="menu"` (v3.11). |
448+
| `closeContextMenu()` | `void` | Close the context menu (v3.11). |
422449
| `copySelectedRows()` | `Promise<void>` | Copy every selected row that passes the filter (other pages, collapsed groups and pinned rows included) as TSV, with the visible columns in screen order. Resolves without writing when no selected row is found; rejects when the clipboard write fails. |
423450

424451
---
@@ -998,6 +1025,7 @@ interface GridLocaleText {
9981025
paginationLastPageLabel; paginationLastPageTooltip;
9991026
// Cell selection stats bar
10001027
cellSelectionStatsCount; cellSelectionStatsSum; cellSelectionStatsAverage;
1028+
contextMenuCopy; contextMenuCopyWithHeaders; contextMenuUndo; contextMenuRedo; contextMenuLabel; // v3.11
10011029
}
10021030
```
10031031

0 commit comments

Comments
 (0)