Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/36289-list-cell-context-menu.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@object-ui/plugin-grid': patch
'@object-ui/components': patch
'@object-ui/types': patch
'@object-ui/i18n': patch
---

feat(grid): a list cell's right-click menu copies, pastes and clears that cell

Clause-②: yes (widening) — an optional `cell` member (`copy`, `paste`, `clear`) on the context `data-table` hands a host's `renderRowContextMenu`; five new `table.*` language-pack keys in every locale `@object-ui/i18n` ships (`copyCell`, `pasteCell`, `clearCell`, `pasteNotValue`, `pasteUnavailable`); nothing is removed or renamed
Metadata-protocol: none

Right-clicking a cell in a list now offers what can be done to that cell, above the row's own items.

- The menu has two sections. Above a line: **Copy**, **Paste**, **Clear** and, where it was already offered, **Change history**. Below it: the row's items as before (Open, Open in new tab, the row's actions). A right-click off a data cell opens the row's section only.
- **Copy** copies the cell's value, as Ctrl/Cmd+C does.
- **Paste** writes the clipboard's text into the cell and saves it, through the same checks as typing into the cell: text that is not an email address in an email cell, a value over a field's length, an empty required field are refused and the cell says why. If the browser will not let the list read the clipboard, the cell says so and names Ctrl/Cmd+V. Paste is offered on text, numbers, dates and single-choice fields (an option by its value or label); on a record reference, a person, a multi-choice and other types it is unavailable.
- **Clear** empties the cell and saves it, as Backspace does; it is unavailable on a required field.
- On a read-only field, a calculated field, a grid that is not editable or a record the reader may not change, Paste and Clear are unavailable and Copy still works.
- A paste into the selected cell with Ctrl/Cmd+V now goes through the same checks: text the cell's editor would refuse is no longer sent to be saved, and text the column cannot read (letters in a number cell, a name in a lookup cell) says why instead of doing nothing.
31 changes: 31 additions & 0 deletions content/docs/frontend/plugins/plugin-grid.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,37 @@ authored `navigation: { mode: 'none' }` or `navigation.preventNavigation: true`
(whatever its mode, objectstack#33549) and for an object whose data API serves
no single-record read (objectstack#33317).

### A cell's own menu items

Right-clicking a data cell opens the row's context menu in two sections
(objectstack#36289). Above a separator, the cell's own items: **Copy**,
**Paste**, **Clear**, then **Change history** (below). Under it, the row's
items, unchanged: Open, Open in new tab and the row's actions. A right-click
off a data cell (the selection cell, the row's "⋮" cell) opens the row's
section only.

- **Copy** writes the cell's value to the clipboard, as Ctrl/Cmd+C on the
selected cell does. A masked cell copies nothing, so it is unavailable there.
- **Paste** reads the clipboard and writes it into the cell as a paste on the
selected cell does: the same conversion, the checks the cell's editor makes
(required, length, range, the email and URL shape) and the same save. Text
the column cannot read, or a value the checks refuse, is not saved and the
cell says why. When the browser will not hand the clipboard over, the cell
says so and names Ctrl/Cmd+V. It is offered on text, number, currency,
percent, email, URL, phone, date and single-choice fields (an option is
matched by value or label), and is unavailable on any other type.
- **Clear** empties the cell and saves it, as Backspace on the selected cell
does. It is unavailable on a required field and on a yes/no field.
- Paste and Clear are unavailable on a cell the reader may not edit: a
read-only or calculated field, a grid that is not editable, a record the
reader may not update.

`data-table` hands these to the host's `renderRowContextMenu` as
`context.cell` (`copy`, `paste`, `clear`, each absent where the table refuses
it), beside `context.column`. A grid that offers no row action and no
selection opens the menu for a cell only when the cell can be changed or has a
change history; otherwise the browser's own menu stays.

### A cell's change history

Right-clicking a cell of a field the object declares adds **Change history**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,13 @@ describe('objectstack#28434 · a host renderer decides alone', () => {
// The host's items only — the table's own are not mixed in.
expect(itemIds(menu)).toEqual(['host-item']);
expect(menu).toHaveTextContent('Host item for r2');
// objectstack#36290 — the context also names the data cell's column.
expect(renderRowContextMenu).toHaveBeenCalledWith(expect.objectContaining({ id: 'r2' }), { selected: false, column: 'name' });
// objectstack#36290 — the context also names the data cell's column, and
// objectstack#36289 what the table does with that cell (a table the reader
// cannot edit: Copy only).
expect(renderRowContextMenu).toHaveBeenCalledWith(
expect.objectContaining({ id: 'r2' }),
{ selected: false, column: 'name', cell: { copy: expect.any(Function) } },
);
});

it('objectstack#36290 · names the column of the data cell it opened on, and none off a data cell', async () => {
Expand All @@ -143,7 +148,10 @@ describe('objectstack#28434 · a host renderer decides alone', () => {
});
act(() => { rightClick(cellOf('C-r1')); });
await screen.findByTestId('row-context-menu');
expect(renderRowContextMenu).toHaveBeenLastCalledWith(expect.objectContaining({ id: 'r1' }), { selected: false, column: 'code' });
expect(renderRowContextMenu).toHaveBeenLastCalledWith(
expect.objectContaining({ id: 'r1' }),
{ selected: false, column: 'code', cell: { copy: expect.any(Function) } },
);
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(contextMenu()).toBeNull());
// The row's own "⋮" cell is not a data cell: no column.
Expand Down Expand Up @@ -171,3 +179,33 @@ describe('objectstack#28434 · a host renderer decides alone', () => {
expect(cell).toHaveFocus();
});
});

describe('objectstack#36289 · what the table does with the data cell a host menu opened on', () => {
const lastCell = (fn: ReturnType<typeof vi.fn>) => (fn.mock.calls.at(-1) as any[])[1].cell;

it('an editable cell offers Copy, Paste and Clear; Copy writes the value as Ctrl/Cmd+C does', async () => {
const writeText = vi.fn(async () => {});
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText, readText: vi.fn(async () => '') } });
const renderRowContextMenu = vi.fn(() => <DropdownMenuItem data-testid="host-item">Host item</DropdownMenuItem>);
renderTable({ editable: true, renderRowContextMenu });
act(() => { rightClick(cellOf('Open contract')); });
await screen.findByTestId('row-context-menu');
const cell = lastCell(renderRowContextMenu);
expect(Object.keys(cell).sort()).toEqual(['clear', 'copy', 'paste']);
cell.copy();
expect(writeText).toHaveBeenCalledWith('Open contract');
});

it('a masked cell offers no Copy; a cell the table will not edit offers no Paste or Clear', async () => {
const renderRowContextMenu = vi.fn(() => <DropdownMenuItem data-testid="host-item">Host item</DropdownMenuItem>);
renderTable({
editable: true,
columns: [{ header: 'Name', accessorKey: 'name' }, { header: 'Code', accessorKey: 'code', masked: true, editable: false }],
data: ROWS.map((row) => ({ ...row, code: `C-${row.id}` })),
renderRowContextMenu,
});
act(() => { rightClick(cellOf('Open contract').closest('tr')!.querySelector('td[data-cell-column="code"]') as HTMLElement); });
await screen.findByTestId('row-context-menu');
expect(lastCell(renderRowContextMenu)).toEqual({});
});
});
133 changes: 120 additions & 13 deletions ui/packages/components/src/renderers/complex/data-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,9 @@ const TABLE_DEFAULT_TRANSLATIONS: Record<string, string> = {
// objectstack#36023 — why a list cell's typed value was not saved, said under the editor.
'table.cellNotNumber': 'Enter a number.',
'table.cellInvalid': 'This value isn\'t valid.',
// objectstack#36289 — why a cell menu's Paste left the cell as it was.
'table.pasteNotValue': 'The copied text can\'t go in this cell.',
'table.pasteUnavailable': 'The browser didn\'t let the list read the clipboard. Select the cell and press Ctrl+V (⌘V) to paste.',
'validation.email': 'Please enter a valid email address',
'validation.url': 'Please enter a valid URL',
// objectstack#35685 — a list cell's own save state, and the way out of a
Expand Down Expand Up @@ -2246,6 +2249,15 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
// Set when the menu closes because the pointer went elsewhere: focus then
// stays where that press put it instead of jumping back to the row.
const rowContextMenuClosedOutsideRef = useRef(false);
// objectstack#36289 — while the menu is open or closing, what a cell item
// chose waits here and runs once focus has gone back: a note it puts on the
// cell would otherwise be dismissed by that very focus move.
const rowContextMenuShownRef = useRef(false);
const afterRowContextMenuRef = useRef<Array<() => void>>([]);
const whenRowContextMenuClosed = (run: () => void) => {
if (rowContextMenuShownRef.current) afterRowContextMenuRef.current.push(run);
else run();
};
// The built-in row menu's verdicts are asked at open time, so the open
// decision and the items it opens read one answer (see `rowContextMenuItems`).
const rowMenuScope = usePredicateScope();
Expand Down Expand Up @@ -3998,11 +4010,61 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
}
return null;
});
/**
* Pasted text written into a cell: converted as the column reads text, then
* held to the checks the cell's editor holds a committed value to
* (`GridCellFacts.validate`), so a paste never saves what typing the same
* text would refuse (objectstack#36289). Text that stands for no value of
* the column, or a value the checks refuse, leaves the cell as it is and
* says why on it.
*/
const pasteIntoCell = (rowIndex: number, colIndex: number, text: string) => writeCell(rowIndex, colIndex, (row, col) => {
const fromText = factsOf(row, col)?.fromText;
return fromText ? fromText(text) : defaultValueFromText(col, text);
const facts = factsOf(row, col);
const value = facts?.fromText ? facts.fromText(text) : defaultValueFromText(col, text);
const refusal = value === undefined ? t('table.pasteNotValue') : facts?.validate?.(value) || null;
if (refusal) {
setCellNotice({ rowIndex, colIndex, text: refusal });
return undefined;
}
return value;
});

/** Where a row and a column are drawn on this page, or `null` when either is not. */
const cellIndexOf = (rowKey: PendingRowKey, columnKey: string): { rowIndex: number; colIndex: number } | null => {
const rowIndex = paginatedData.findIndex((r) => pendingRowKeyOf(r) === rowKey);
const colIndex = columns.findIndex((c) => c.accessorKey === columnKey);
return rowIndex < 0 || colIndex < 0 ? null : { rowIndex, colIndex };
};

/**
* The clipboard's text pasted into a cell, as a paste on the selected cell
* is (objectstack#36289). The browser may refuse to hand the text over (no
* clipboard API, the reader declined, the page lacks focus); the cell then
* says so and names the keyboard paste, which needs no permission.
*/
const pasteClipboardInto = (row: any, columnKey: string) => {
const rowKey = pendingRowKeyOf(row);
const sayUnavailable = () => {
const at = cellIndexOf(rowKey, columnKey);
if (at) setCellNotice({ ...at, text: t('table.pasteUnavailable') });
};
const clipboard = typeof navigator !== 'undefined' ? navigator.clipboard : undefined;
if (typeof clipboard?.readText !== 'function') {
whenRowContextMenuClosed(sayUnavailable);
return;
}
// Asked at once, inside the click that chose Paste (a browser may grant the
// read only then); written once the menu has closed.
clipboard.readText().then(
(text) => whenRowContextMenuClosed(() => {
// Read where the cell is once the text arrives: the rows may have moved.
const at = cellIndexOf(rowKey, columnKey);
if (at && text !== '') pasteIntoCell(at.rowIndex, at.colIndex, text);
}),
() => whenRowContextMenuClosed(sayUnavailable),
);
};

/** Text typed or composed on the selected cell. */
const typeIntoCell = (rowIndex: number, colIndex: number, text: string) => {
const row = paginatedData[rowIndex];
Expand Down Expand Up @@ -4122,6 +4184,21 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
// A printable key lands in the catcher, which reads it (`typeIntoCell`).
};

/**
* A cell's value to the clipboard: Ctrl/Cmd+C on the selected cell, and the
* cell menu's Copy (objectstack#36289). A MASKED column copies NOTHING
* (objectui#10583): the producer drew a mask, so no copy hands out what the
* cell hides.
*/
const copyCellValue = (row: any, columnKey: string) => {
if (columns.find((col) => col.accessorKey === columnKey)?.masked) return;
const value = row[columnKey];
const text = value != null ? String(value) : '';
navigator.clipboard?.writeText(text).catch(() => {
// Fallback for environments without clipboard API
});
};

const handleCellKeyDown = (e: React.KeyboardEvent, rowIndex: number, colIndex: number, columnKey: string) => {
if (selectFirst) {
if (!isCommandLetter(e, 'c')) {
Expand Down Expand Up @@ -4161,18 +4238,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
// detail page's house shape (objectui#8440, option A): no copy at all,
// ⛔ not the bullets — which is also why `preventDefault()` above stays:
// measured in Chromium, letting the default run copies a selected mask
// as `••••••`, the payload that ruling refused. Unmasked cells are
// untouched below.
if (columns.find((col) => col.accessorKey === columnKey)?.masked) return;
// as `••••••`, the payload that ruling refused. `copyCellValue` then
// copies nothing of a masked cell.
const globalIdx = (effectivePage - 1) * pageSize + rowIndex;
const row = sortedData[manualPagination ? rowIndex : globalIdx];
if (row) {
const value = row[columnKey];
const text = value != null ? String(value) : '';
navigator.clipboard.writeText(text).catch(() => {
// Fallback for environments without clipboard API
});
}
if (row) copyCellValue(row, columnKey);
return;
}

Expand Down Expand Up @@ -4416,6 +4486,36 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
&& !(autosaves && rowActionsColumnIsEditOnly)
&& !(selectFirst && !autosaves && rowActionsColumnIsEditOnly && !hasPendingChanges);

/**
* objectstack#36289 — what the table does with the data cell a row context
* menu opened on, for the host to draw as that cell's items: Copy as
* Ctrl/Cmd+C does, Paste as a paste on the selected cell does, Clear as
* Backspace does. Each is left out where the table would refuse it, so a
* host draws it unavailable rather than offering what does nothing.
*/
const cellMenuOf = (
row: any,
columnKey: string,
): { copy?: () => void; paste?: () => void; clear?: () => void } | undefined => {
const col = columns.find((c) => c.accessorKey === columnKey);
if (!col) return undefined;
const rowKey = pendingRowKeyOf(row);
const writable = readOnlyReasonOf(row, col) === null;
const clearable = writable && !togglesCell(row, col) && !factsOf(row, col)?.clearRefusal;
return {
...(col.masked ? {} : { copy: () => copyCellValue(row, columnKey) }),
...(writable ? { paste: () => pasteClipboardInto(row, columnKey) } : {}),
...(clearable
? {
clear: () => whenRowContextMenuClosed(() => {
const at = cellIndexOf(rowKey, columnKey);
if (at) clearCell(at.rowIndex, at.colIndex);
}),
}
: {}),
};
};

/**
* objectstack#28434 — the items ONE row's context menu opens with, or `null`
* for the browser's own menu.
Expand All @@ -4428,7 +4528,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
*/
const rowContextMenuItems = (row: any, selected: boolean, column?: string): React.ReactNode => {
if (schema.renderRowContextMenu) {
const items = schema.renderRowContextMenu(row, column !== undefined ? { selected, column } : { selected });
const cell = column !== undefined ? cellMenuOf(row, column) : undefined;
const items = schema.renderRowContextMenu(row, cell ? { selected, column, cell } : { selected });
return items === false || items === undefined ? null : items;
}
if (!rowActions || rowActionsColumnIsEditOnly) return null;
Expand Down Expand Up @@ -4494,6 +4595,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
const focusable = fromKeyboard ? target : target.closest<HTMLElement>('[tabindex]');
rowContextMenuReturnFocusRef.current = focusable && rowEl.contains(focusable) ? focusable : null;
rowContextMenuClosedOutsideRef.current = false;
rowContextMenuShownRef.current = true;
afterRowContextMenuRef.current = [];
setRowContextMenu({ row, selected, column, x, y });
};
// The open menu's items, re-asked each render so they follow the row.
Expand Down Expand Up @@ -6077,6 +6180,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
e.preventDefault();
if (!rowContextMenuClosedOutsideRef.current) rowContextMenuReturnFocusRef.current?.focus();
rowContextMenuClosedOutsideRef.current = false;
rowContextMenuShownRef.current = false;
const after = afterRowContextMenuRef.current;
afterRowContextMenuRef.current = [];
for (const run of after) run();
}}
>
{openRowContextMenuItems}
Expand Down
6 changes: 6 additions & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,12 @@ const ar = {
// objectstack#36023 — why a list cell's typed value was not saved, under the editor.
cellNotNumber: "أدخل رقمًا.",
cellInvalid: "هذه القيمة غير صالحة.",
// objectstack#36289 — a list cell's menu, and why its Paste left the cell as it was.
copyCell: "نسخ",
pasteCell: "لصق",
clearCell: "مسح",
pasteNotValue: "لا يمكن وضع النص المنسوخ في هذه الخلية.",
pasteUnavailable: "لم يسمح المتصفح بقراءة الحافظة. حدّد الخلية واضغط Ctrl+V (⌘V) للصق.",
// objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete.
cellSaving: "جارٍ الحفظ…",
cellSaved: "تم الحفظ",
Expand Down
6 changes: 6 additions & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,12 @@ const de = {
// objectstack#36023 — why a list cell's typed value was not saved, under the editor.
cellNotNumber: "Geben Sie eine Zahl ein.",
cellInvalid: "Dieser Wert ist ungültig.",
// objectstack#36289 — a list cell's menu, and why its Paste left the cell as it was.
copyCell: "Kopieren",
pasteCell: "Einfügen",
clearCell: "Leeren",
pasteNotValue: "Der kopierte Text passt nicht in diese Zelle.",
pasteUnavailable: "Der Browser hat das Lesen der Zwischenablage nicht erlaubt. Wählen Sie die Zelle aus und drücken Sie Strg+V (⌘V), um einzufügen.",
// objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete.
cellSaving: "Wird gespeichert…",
cellSaved: "Gespeichert",
Expand Down
Loading
Loading