From 304f9a8a3892d58ba89309650443e2c700f7f2da Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 21:42:04 +0000 Subject: [PATCH 1/4] feat(grid): a list cell's right-click menu copies, pastes and clears that cell Claude-Session: https://claude.ai/code/session_01JQwxbXwSwKtFLjfawUUTVG Co-authored-by: Claude --- .../src/renderers/complex/data-table.tsx | 116 ++++++++++++++++-- ui/packages/i18n/src/locales/ar.ts | 6 + ui/packages/i18n/src/locales/de.ts | 6 + ui/packages/i18n/src/locales/en.ts | 6 + ui/packages/i18n/src/locales/es.ts | 6 + ui/packages/i18n/src/locales/fr.ts | 6 + ui/packages/i18n/src/locales/ja.ts | 6 + ui/packages/i18n/src/locales/ko.ts | 6 + ui/packages/i18n/src/locales/pt-BR.ts | 6 + ui/packages/i18n/src/locales/ru.ts | 6 + ui/packages/i18n/src/locales/zh-Hans.ts | 6 + ui/packages/i18n/src/locales/zh-Hant.ts | 6 + ui/packages/plugin-grid/src/ObjectGrid.tsx | 33 ++++- .../src/components/RowContextMenu.tsx | 90 ++++++++++---- .../plugin-grid/src/objectGridCellFacts.ts | 15 +++ ui/packages/types/src/data-display.ts | 21 +++- 16 files changed, 299 insertions(+), 42 deletions(-) diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index ce628475adf..8cc5d046aba 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -368,6 +368,9 @@ const TABLE_DEFAULT_TRANSLATIONS: Record = { // 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 @@ -3998,11 +4001,59 @@ 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') { + sayUnavailable(); + return; + } + clipboard.readText().then( + (text) => { + // 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); + }, + sayUnavailable, + ); + }; + /** Text typed or composed on the selected cell. */ const typeIntoCell = (rowIndex: number, colIndex: number, text: string) => { const row = paginatedData[rowIndex]; @@ -4122,6 +4173,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')) { @@ -4161,18 +4227,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; } @@ -4416,6 +4475,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: () => { + 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. @@ -4428,7 +4517,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; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index efee6c3c046..6b972ee4ca9 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -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: "تم الحفظ", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 7ae83d74eb5..c733fbff81f 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -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", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index c9f95bef988..8b8c7eca660 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -829,6 +829,12 @@ const en = { // objectstack#36023 — why a list cell's typed value was not saved, under the editor. cellNotNumber: 'Enter a number.', cellInvalid: 'This value isn\'t valid.', + // objectstack#36289 — a list cell's menu, and why its Paste left the cell as it was. + copyCell: 'Copy', + pasteCell: 'Paste', + clearCell: 'Clear', + pasteNotValue: 'The copied text can\'t go in this cell.', + pasteUnavailable: 'The browser didn\'t let the list read the clipboard. Select the cell and press Ctrl+V (⌘V) to paste.', // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: 'Saving…', cellSaved: 'Saved', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 51d71563100..c2f58716956 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -567,6 +567,12 @@ const es = { // objectstack#36023 — why a list cell's typed value was not saved, under the editor. cellNotNumber: "Introduce un número.", cellInvalid: "Este valor no es válido.", + // objectstack#36289 — a list cell's menu, and why its Paste left the cell as it was. + copyCell: "Copiar", + pasteCell: "Pegar", + clearCell: "Borrar", + pasteNotValue: "El texto copiado no puede ir en esta celda.", + pasteUnavailable: "El navegador no permitió leer el portapapeles. Selecciona la celda y pulsa Ctrl+V (⌘V) para pegar.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Guardando…", cellSaved: "Guardado", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index fd1cd1ea38d..efdfc9a5997 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -562,6 +562,12 @@ const fr = { // objectstack#36023 — why a list cell's typed value was not saved, under the editor. cellNotNumber: "Saisissez un nombre.", cellInvalid: "Cette valeur n'est pas valide.", + // objectstack#36289 — a list cell's menu, and why its Paste left the cell as it was. + copyCell: "Copier", + pasteCell: "Coller", + clearCell: "Effacer", + pasteNotValue: "Le texte copié ne peut pas aller dans cette cellule.", + pasteUnavailable: "Le navigateur n'a pas autorisé la lecture du presse-papiers. Sélectionnez la cellule et appuyez sur Ctrl+V (⌘V) pour coller.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Enregistrement…", cellSaved: "Enregistré", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 9d8d18b5e8d..be92144fc05 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -555,6 +555,12 @@ const ja = { // 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: "保存しました", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index b0a0b2cb186..c28366d9dea 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -555,6 +555,12 @@ const ko = { // 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: "저장됨", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 60e5738e807..e871f478324 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -562,6 +562,12 @@ const pt = { // objectstack#36023 — why a list cell's typed value was not saved, under the editor. cellNotNumber: "Digite um número.", cellInvalid: "Este valor não é válido.", + // objectstack#36289 — a list cell's menu, and why its Paste left the cell as it was. + copyCell: "Copiar", + pasteCell: "Colar", + clearCell: "Limpar", + pasteNotValue: "O texto copiado não pode ir nesta célula.", + pasteUnavailable: "O navegador não permitiu ler a área de transferência. Selecione a célula e pressione Ctrl+V (⌘V) para colar.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Salvando…", cellSaved: "Salvo", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 9b59f062fd4..ff20237bc2f 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -572,6 +572,12 @@ const ru = { // 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: "Сохранено", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 605b9b5442c..77e68265bb1 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -568,6 +568,12 @@ const zh = { // 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: '已保存', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 08b91e420bc..527091c522d 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -568,6 +568,12 @@ const zhHant = { // 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: '已儲存', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 1ff0b150b82..79a05162bff 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -48,7 +48,7 @@ import { resolveI18nLabel as resolveInlineI18nLabel } from '@objectstack/spec/ui import { stateMachineNextValues } from './inline-edit-options'; import { isStateMachineField, stateLabelOf, type StateChangeConfirm } from './objectGridStateConfirm'; import { useCellRequiredPrompt } from './objectGridRequiredPrompt'; -import { cellReadOnlyKind, readOnlyReasonText, inlineTyping, choiceFromText, inlineEditorPlacement, clearRefusalText, cellValueRefusal } from './objectGridCellFacts'; +import { cellReadOnlyKind, readOnlyReasonText, inlineTyping, choiceFromText, inlineEditorPlacement, clearRefusalText, cellValueRefusal, pastesFromText } from './objectGridCellFacts'; import { Badge, Button, NavigationOverlay, EmptyValue, legacyRecordDrawerWidthKey, recordOverlayWidthStorageKey, @@ -3604,7 +3604,14 @@ export const ObjectGrid: React.FC = ({ * browser's menu: the menu is a second way to reach the row's actions, not * a new surface. */ - const renderRowContextMenu = (row: any, context: { selected: boolean; column?: string }): React.ReactNode => { + const renderRowContextMenu = ( + row: any, + context: { + selected: boolean; + column?: string; + cell?: { copy?: () => void; paste?: () => void; clear?: () => void }; + }, + ): React.ReactNode => { if (context.selected && selectedRows.length >= 2) { return ( = ({ ? (at: { x: number; y: number }) => setFieldHistoryAt({ recordId: String(recordId), field: historyField, ...at }) : undefined; + // objectstack#36289 — the data cell's own Copy, Paste and Clear, as the + // table offers them; Paste only for a field type pasted text can stand + // for (`pastesFromText`). + const cellFieldType = context.column + && Object.prototype.hasOwnProperty.call(objectSchema?.fields ?? {}, context.column) + ? (objectSchema as any).fields[context.column]?.type + : undefined; + const cell = context.cell ? { ...context.cell, pasteable: pastesFromText(cellFieldType) } : undefined; + // Something the cell can be changed by: what makes a cell's own section + // worth replacing the browser's menu for (its Copy alone is not). + const cellWrites = !!cell && ((!!cell.paste && cell.pasteable) || !!cell.clear); // The browser's menu stays on a table that offers no row action at all and // whose rows cannot be selected — a face-level answer, so a row whose own // actions are all hidden by their predicates still opens Open / Open in - // new tab like its neighbours — unless the cell offers its field's history. - if (!tableOffersRowActions && !selectionMode && !onFieldHistory) return null; + // new tab like its neighbours — unless the cell offers its field's history + // or a change of its value. + if (!tableOffersRowActions && !selectionMode && !onFieldHistory && !cellWrites) return null; const newTabHref = schema.objectName && recordId != null && recordId !== '' && recordLinkHost?.recordHref ? recordLinkHost.recordHref(schema.objectName, recordId) @@ -3654,14 +3673,16 @@ export const ObjectGrid: React.FC = ({ const opens = rowOpensRecord !== false && (!!onRowClick || (navigation.mode !== 'none' && !schema.navigation?.preventNavigation)); const openHref = rowOpensRecord === false ? null : newTabHref; - // Nothing at all to list for this row: no Open, no URL, no history, no action. - if (!opens && !openHref && !onFieldHistory && !rowOffersAction(row)) return null; + // Nothing at all to list for this row: no Open, no URL, no history, no + // change of the cell, no action. + if (!opens && !openHref && !onFieldHistory && !cellWrites && !rowOffersAction(row)) return null; return ( navigation.handleClick(row) : undefined} newTabHref={openHref} onFieldHistory={onFieldHistory} + cell={cell} /> ); }; diff --git a/ui/packages/plugin-grid/src/components/RowContextMenu.tsx b/ui/packages/plugin-grid/src/components/RowContextMenu.tsx index 38780daeca3..003627c7ee0 100644 --- a/ui/packages/plugin-grid/src/components/RowContextMenu.tsx +++ b/ui/packages/plugin-grid/src/components/RowContextMenu.tsx @@ -14,7 +14,7 @@ import { LazyIcon, toKebabIconName, } from '@object-ui/components'; -import { ExternalLink, History, PanelRightOpen, Trash2, X } from 'lucide-react'; +import { ClipboardPaste, Copy, Eraser, ExternalLink, History, PanelRightOpen, Trash2, X } from 'lucide-react'; import type { BulkActionDef } from '@object-ui/types'; import { useObjectTranslation } from '@object-ui/react'; import { @@ -38,6 +38,9 @@ const CONTEXT_MENU_FALLBACKS: Record = { 'table.open': 'Open', 'detail.openInNewTab': 'Open in new tab', 'detail.fieldHistory': 'Change history', + 'table.copyCell': 'Copy', + 'table.pasteCell': 'Paste', + 'table.clearCell': 'Clear', }; function useContextMenuTranslation() { @@ -49,11 +52,31 @@ function useContextMenuTranslation() { } /** - * ONE row's context menu: Open, Open in new tab, then every action the row's - * cell offers — the "⋮" items and the inline primaries the cell's width budget - * keeps out of the "⋮". Same resolver ({@link useRowActionPlan}), same items - * ({@link RowActionMenuItems}), same handlers (so the same confirm dialogs); - * the only input read differently is the inline budget, `0` here. + * What the table does with the data cell the menu opened on + * (objectstack#36289): the `cell` member of `renderRowContextMenu`'s context. + * An absent action is one the table refuses on this cell. + */ +export interface RowContextMenuCell { + copy?: () => void; + paste?: () => void; + clear?: () => void; + /** + * Whether the field's type takes pasted text at all; `false` draws Paste + * unavailable even where the cell may be edited. + */ + pasteable: boolean; +} + +/** + * ONE row's context menu, in two sections (objectstack#36289). Above, when + * the menu opened on a data cell: that cell's Copy, Paste, Clear and Change + * history, each drawn unavailable (or, for Change history, left out) where + * the cell refuses it. Below, the row's: Open, Open in new tab, then every + * action the row's cell offers — the "⋮" items and the inline primaries the + * cell's width budget keeps out of the "⋮". Same resolver + * ({@link useRowActionPlan}), same items ({@link RowActionMenuItems}), same + * handlers (so the same confirm dialogs); the only input read differently is + * the inline budget, `0` here. */ export const RowContextMenuItems: React.FC<{ /** Exactly the props the row's "⋮" cell renders with. */ @@ -68,25 +91,35 @@ export const RowContextMenuItems: React.FC<{ * Change history item. */ onFieldHistory?: (at: { x: number; y: number }) => void; -}> = ({ menu, onOpen, newTabHref, onFieldHistory }) => { + /** The data cell the menu opened on. Absent ⇒ no Copy, Paste or Clear item. */ + cell?: RowContextMenuCell; +}> = ({ menu, onOpen, newTabHref, onFieldHistory, cell }) => { const t = useContextMenuTranslation(); const plan = useRowActionPlan(menu, 0); - const hasOpen = !!onOpen || !!newTabHref || !!onFieldHistory; + const hasOpen = !!onOpen || !!newTabHref; + const hasCellSection = !!cell || !!onFieldHistory; + const hasRowSection = hasOpen || plan.menuCount > 0; return ( <> - {onOpen && ( - onOpen()} data-testid="row-context-open"> - - {t('table.open')} - - )} - {newTabHref && ( - - - - {t('detail.openInNewTab')} - - + {cell && ( + <> + cell.copy?.()} data-testid="row-context-cell-copy"> + + {t('table.copyCell')} + + cell.paste?.()} + data-testid="row-context-cell-paste" + > + + {t('table.pasteCell')} + + cell.clear?.()} data-testid="row-context-cell-clear"> + + {t('table.clearCell')} + + )} {onFieldHistory && ( )} + {hasCellSection && hasRowSection && } + {onOpen && ( + onOpen()} data-testid="row-context-open"> + + {t('table.open')} + + )} + {newTabHref && ( + + + + {t('detail.openInNewTab')} + + + )} {hasOpen && plan.menuCount > 0 && } diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts.ts b/ui/packages/plugin-grid/src/objectGridCellFacts.ts index 211a3474760..09a070ed45c 100644 --- a/ui/packages/plugin-grid/src/objectGridCellFacts.ts +++ b/ui/packages/plugin-grid/src/objectGridCellFacts.ts @@ -127,6 +127,21 @@ export function choiceFromText( return null; } +/** + * Field types a list cell's menu Paste writes pasted text into + * (objectstack#36289): text, figures, dates and a single choice, matched by + * an option's value or label. A record reference, a person, a multi-choice and + * every other type draw Paste unavailable. + */ +const PASTE_FIELD_TYPES: ReadonlySet = new Set([ + ...TYPED_FIELD_TYPES, 'date', 'datetime', ...CHOICE_FIELD_TYPES, +]); + +/** Whether a list cell's menu offers Paste on a field of this type. */ +export function pastesFromText(fieldType: unknown): boolean { + return typeof fieldType === 'string' && PASTE_FIELD_TYPES.has(fieldType); +} + /** * Field types whose cell editor is a panel opened under the cell, which keeps * showing its value (objectstack#36023): a list to pick from, a calendar, a diff --git a/ui/packages/types/src/data-display.ts b/ui/packages/types/src/data-display.ts index b09a2c5ab34..26ae50aef3f 100644 --- a/ui/packages/types/src/data-display.ts +++ b/ui/packages/types/src/data-display.ts @@ -1691,8 +1691,25 @@ export interface DataTableSchema extends BaseSchema { * menu opened on, absent when it opened elsewhere on the row (the selection * or "⋮" cell, or the keyboard on the row itself), so a host can add items * about that cell, such as the field's change history. - */ - renderRowContextMenu?: (row: any, context: { selected: boolean; column?: string }) => React.ReactNode; + * + * `context.cell` (objectstack#36289) is what the table itself does with that + * data cell, present exactly when `column` is: `copy` writes the cell's value + * to the clipboard as Ctrl/Cmd+C on the selected cell does, `paste` reads the + * clipboard and writes it into the cell as a paste on the selected cell does + * (the same conversion, the editor's checks and the same save), and `clear` + * empties the cell as Backspace on the selected cell does. Each is absent + * where the table would refuse it: `copy` on a masked cell; `paste` on a cell + * the reader may not edit; `clear` there too, and on a required or a + * two-state (yes/no) cell. A host draws them as items about that cell. + */ + renderRowContextMenu?: ( + row: any, + context: { + selected: boolean; + column?: string; + cell?: { copy?: () => void; paste?: () => void; clear?: () => void }; + }, + ) => React.ReactNode; /** * Group bands (objectui#12620): draw the table as ONE table, with one header, * whose body is a band row per group followed by that group's rows. From e350615f9194b0523373c3eb392af17266c7bd65 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 21:50:32 +0000 Subject: [PATCH 2/4] test(grid): pin the list cell menu's Copy, Paste and Clear; docs and changeset Claude-Session: https://claude.ai/code/session_01JQwxbXwSwKtFLjfawUUTVG Co-authored-by: Claude --- .changeset/36289-list-cell-context-menu.md | 20 ++ content/docs/frontend/plugins/plugin-grid.mdx | 31 +++ ...data-table-row-context-menu-28434.test.tsx | 44 ++- ui/packages/plugin-grid/README.md | 31 +++ .../__tests__/cellContextMenu-36289.test.tsx | 255 ++++++++++++++++++ 5 files changed, 378 insertions(+), 3 deletions(-) create mode 100644 .changeset/36289-list-cell-context-menu.md create mode 100644 ui/packages/plugin-grid/src/__tests__/cellContextMenu-36289.test.tsx diff --git a/.changeset/36289-list-cell-context-menu.md b/.changeset/36289-list-cell-context-menu.md new file mode 100644 index 00000000000..e9302edee3d --- /dev/null +++ b/.changeset/36289-list-cell-context-menu.md @@ -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. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 7da2aa31002..cbabc4304fd 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -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** diff --git a/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx b/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx index 111b2d1ad59..f0462345e8b 100644 --- a/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx +++ b/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx @@ -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 () => { @@ -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. @@ -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) => (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(() => Host item); + 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(() => Host item); + 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({}); + }); +}); diff --git a/ui/packages/plugin-grid/README.md b/ui/packages/plugin-grid/README.md index 9e7117ba9c0..1f32d6d6f11 100644 --- a/ui/packages/plugin-grid/README.md +++ b/ui/packages/plugin-grid/README.md @@ -957,6 +957,37 @@ schema key: list metadata cannot set it. The console passes `false` for a view authored `navigation: { mode: 'none' }` 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** diff --git a/ui/packages/plugin-grid/src/__tests__/cellContextMenu-36289.test.tsx b/ui/packages/plugin-grid/src/__tests__/cellContextMenu-36289.test.tsx new file mode 100644 index 00000000000..d066bb60e0e --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/cellContextMenu-36289.test.tsx @@ -0,0 +1,255 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36289 — a right-click on a list cell opens a menu in two + * sections: the cell's own Copy, Paste, Clear (and Change history), then the + * row's items as before. Driven through the real `ObjectGrid` → `data-table` + * chain, with a data source whose `update` records each save. + * + * 1. The cell's section comes first, a separator, then the row's section; + * a right-click off a data cell (the selection cell) opens the row's only. + * 2. Copy writes the cell's value to the clipboard, as Ctrl/Cmd+C does. + * 3. Paste writes the clipboard's text into the cell and saves it; text the + * cell's editor would refuse (an email box holding no address) is not + * saved and the cell says why, in the editor's words. Ctrl+V on the + * selected cell refuses it the same way. + * 4. A clipboard the browser will not read says so on the cell, never silent. + * 5. Clear empties and saves the cell; on a required field it is unavailable. + * 6. A read-only field: Paste and Clear unavailable, Copy available. A field + * type pasted text cannot stand for (a lookup, a multi-select): Paste + * unavailable. + * 7. A grid the reader cannot edit: Paste and Clear unavailable everywhere. + */ + +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, screen, waitFor, cleanup, fireEvent, within, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider } from '@object-ui/react'; + +registerAllFields(); + +const clipboard = vi.hoisted(() => ({ + written: [] as string[], + text: '' as string, + refuse: false, +})); + +beforeEach(() => { + clipboard.written = []; + clipboard.text = ''; + clipboard.refuse = false; + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { + writeText: vi.fn(async (text: string) => { clipboard.written.push(text); }), + readText: vi.fn(async () => { + if (clipboard.refuse) throw new DOMException('Read permission denied.', 'NotAllowedError'); + return clipboard.text; + }), + }, + }); +}); + +afterEach(() => { + cleanup(); +}); + +const FIELDS = { + id: { type: 'text' }, + name: { type: 'text', label: 'Name', required: true }, + email: { type: 'email', label: 'Email' }, + notes: { type: 'text', label: 'Notes' }, + code: { type: 'text', label: 'Code', readonly: true }, + owner: { type: 'lookup', label: 'Owner', reference: 'sys_user' }, + tags: { type: 'multiselect', label: 'Tags', options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }] }, +}; + +function makeDataSource() { + const store: Record = { + r1: { id: 'r1', name: 'Acme', email: 'ops@acme.test', notes: 'Call back Monday', code: 'C-1', owner: null, tags: ['a'] }, + r2: { id: 'r2', name: 'Globex', email: 'hi@globex.test', notes: 'Quiet', code: 'C-2', owner: null, tags: [] }, + }; + return { + store, + find: vi.fn(async (object: string) => + object === 'sys_activity' + ? { data: [] } + : { data: Object.values(store).map((r) => ({ ...r })), total: 2, hasMore: false, pageSize: 50 }), + update: vi.fn(async (_object: string, id: string, changes: Record) => { + store[id] = { ...store[id], ...changes }; + return { ...store[id] }; + }), + getObjectSchema: async (name: string) => ({ name, fields: FIELDS }), + } as any; +} + +async function renderGrid(opts: { editable?: boolean } = {}) { + const ds = makeDataSource(); + const utils = render( + + + , + ); + await screen.findByText('Globex', {}, { timeout: 5000 }); + await waitFor(() => expect(screen.getByText('Tags')).toBeInTheDocument()); + await act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + const row = (name: string) => screen.getByText(name).closest('tr') as HTMLElement; + const cell = (name: string, column: string) => + row(name).querySelector(`td[data-cell-column="${column}"]`)!; + const openMenu = async (el: HTMLElement) => { + act(() => { fireEvent.contextMenu(el, { button: 2, clientX: 40, clientY: 60 }); }); + return screen.findByTestId('row-context-menu'); + }; + return { ...utils, ds, row, cell, openMenu }; +} + +const item = (menu: HTMLElement, id: string) => within(menu).getByTestId(id); +const isUnavailable = (el: HTMLElement) => el.hasAttribute('data-disabled'); +const settleClipboard = () => act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + +describe('a list cell\'s right-click menu (objectstack#36289)', () => { + it('lists the cell\'s Copy, Paste, Clear and Change history, a separator, then the row\'s items', async () => { + const g = await renderGrid(); + const menu = await g.openMenu(g.cell('Acme', 'notes')); + const ids = Array.from(menu.querySelectorAll('[data-testid^="row-context-"]')).map((el) => el.dataset.testid); + const separator = ids.indexOf('row-context-cell-separator'); + expect(ids.slice(0, separator)).toEqual([ + 'row-context-cell-copy', + 'row-context-cell-paste', + 'row-context-cell-clear', + 'row-context-field-history', + ]); + // The row's section is below the line, and nothing of the cell's is there. + expect(ids.indexOf('row-context-open')).toBeGreaterThan(separator); + expect(ids.slice(separator + 1).some((id) => id?.startsWith('row-context-cell-'))).toBe(false); + }); + + it('off a data cell (the selection cell) only the row\'s section opens', async () => { + const g = await renderGrid(); + const selectCell = g.row('Acme').querySelector('td:not([data-cell-column])')!; + const menu = await g.openMenu(selectCell); + expect(within(menu).queryByTestId('row-context-cell-copy')).toBeNull(); + expect(within(menu).queryByTestId('row-context-cell-separator')).toBeNull(); + // CONTROL: the row's own items are there. + expect(item(menu, 'row-context-open')).toBeInTheDocument(); + }); + + it('Copy writes the cell\'s value to the clipboard', async () => { + const g = await renderGrid(); + const menu = await g.openMenu(g.cell('Acme', 'notes')); + fireEvent.click(item(menu, 'row-context-cell-copy')); + expect(clipboard.written).toEqual(['Call back Monday']); + }); + + it('Paste writes the clipboard\'s text into the cell and saves it', async () => { + const g = await renderGrid(); + clipboard.text = 'Call back Monday'; + const menu = await g.openMenu(g.cell('Globex', 'notes')); + fireEvent.click(item(menu, 'row-context-cell-paste')); + await settleClipboard(); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledTimes(1)); + expect(g.ds.update).toHaveBeenCalledWith('account', 'r2', expect.objectContaining({ notes: 'Call back Monday' })); + await waitFor(() => expect(g.cell('Globex', 'notes')).toHaveTextContent('Call back Monday')); + }); + + it('Paste of text that is no email into an email cell saves nothing and says why, as the editor does', async () => { + const g = await renderGrid(); + clipboard.text = 'not an address'; + const menu = await g.openMenu(g.cell('Globex', 'email')); + fireEvent.click(item(menu, 'row-context-cell-paste')); + await settleClipboard(); + expect(await within(g.cell('Globex', 'email')).findByTestId('cell-readonly-reason')) + .toHaveTextContent('Please enter a valid email address'); + expect(g.ds.update).not.toHaveBeenCalled(); + expect(g.cell('Globex', 'email')).toHaveTextContent('hi@globex.test'); + }); + + it('Ctrl+V on the selected cell refuses the same text the same way (control: a real address saves)', async () => { + const g = await renderGrid(); + fireEvent.click(g.cell('Globex', 'email')); + const catcher = () => g.container.querySelector('[data-slot="cell-type-catcher"]')!; + fireEvent.paste(catcher(), { clipboardData: { getData: () => 'not an address' } }); + expect(await within(g.cell('Globex', 'email')).findByTestId('cell-readonly-reason')) + .toHaveTextContent('Please enter a valid email address'); + expect(g.ds.update).not.toHaveBeenCalled(); + fireEvent.paste(catcher(), { clipboardData: { getData: () => 'team@globex.test' } }); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledWith('account', 'r2', expect.objectContaining({ email: 'team@globex.test' }))); + }); + + it('a clipboard the browser will not read says so on the cell', async () => { + const g = await renderGrid(); + clipboard.refuse = true; + const menu = await g.openMenu(g.cell('Globex', 'notes')); + fireEvent.click(item(menu, 'row-context-cell-paste')); + await settleClipboard(); + expect(await within(g.cell('Globex', 'notes')).findByTestId('cell-readonly-reason')) + .toHaveTextContent('The browser didn\'t let the list read the clipboard'); + expect(g.ds.update).not.toHaveBeenCalled(); + }); + + it('Clear empties the cell and saves it', async () => { + const g = await renderGrid(); + const menu = await g.openMenu(g.cell('Acme', 'notes')); + fireEvent.click(item(menu, 'row-context-cell-clear')); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledWith('account', 'r1', expect.objectContaining({ notes: null }))); + }); + + it('Clear is unavailable on a required field (control: available on an optional one)', async () => { + const g = await renderGrid(); + let menu = await g.openMenu(g.cell('Acme', 'name')); + expect(isUnavailable(item(menu, 'row-context-cell-clear'))).toBe(true); + expect(isUnavailable(item(menu, 'row-context-cell-paste'))).toBe(false); + fireEvent.keyDown(menu, { key: 'Escape' }); + await waitFor(() => expect(screen.queryByTestId('row-context-menu')).toBeNull()); + menu = await g.openMenu(g.cell('Acme', 'notes')); + expect(isUnavailable(item(menu, 'row-context-cell-clear'))).toBe(false); + }); + + it('a read-only field: Paste and Clear unavailable, Copy available', async () => { + const g = await renderGrid(); + const menu = await g.openMenu(g.cell('Acme', 'code')); + expect(isUnavailable(item(menu, 'row-context-cell-copy'))).toBe(false); + expect(isUnavailable(item(menu, 'row-context-cell-paste'))).toBe(true); + expect(isUnavailable(item(menu, 'row-context-cell-clear'))).toBe(true); + fireEvent.click(item(menu, 'row-context-cell-copy')); + expect(clipboard.written).toEqual(['C-1']); + }); + + it('a lookup and a multi-select take no pasted text: Paste unavailable, Clear available', async () => { + const g = await renderGrid(); + for (const column of ['owner', 'tags']) { + const menu = await g.openMenu(g.cell('Acme', column)); + expect(isUnavailable(item(menu, 'row-context-cell-paste'))).toBe(true); + expect(isUnavailable(item(menu, 'row-context-cell-clear'))).toBe(false); + fireEvent.keyDown(menu, { key: 'Escape' }); + await waitFor(() => expect(screen.queryByTestId('row-context-menu')).toBeNull()); + } + }); + + it('a grid the reader cannot edit: Paste and Clear unavailable, Copy available', async () => { + const g = await renderGrid({ editable: false }); + const menu = await g.openMenu(g.cell('Acme', 'notes')); + expect(isUnavailable(item(menu, 'row-context-cell-copy'))).toBe(false); + expect(isUnavailable(item(menu, 'row-context-cell-paste'))).toBe(true); + expect(isUnavailable(item(menu, 'row-context-cell-clear'))).toBe(true); + }); +}); From 3a524f386f8b3eeb0d8f6b94edd1a92dae25d69b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 21:54:46 +0000 Subject: [PATCH 3/4] fix(grid): a cell menu's Paste and Clear act once the menu has closed, so their note stays on the cell Claude-Session: https://claude.ai/code/session_01JQwxbXwSwKtFLjfawUUTVG Co-authored-by: Claude --- .../src/renderers/complex/data-table.tsx | 29 +++++++++++++++---- .../__tests__/cellContextMenu-36289.test.tsx | 22 ++++++++++---- .../__tests__/rowContextMenu-28434.test.tsx | 9 +++++- 3 files changed, 47 insertions(+), 13 deletions(-) diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index 8cc5d046aba..90c2666f1fb 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -2249,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 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(); @@ -4041,16 +4050,18 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { }; const clipboard = typeof navigator !== 'undefined' ? navigator.clipboard : undefined; if (typeof clipboard?.readText !== 'function') { - sayUnavailable(); + 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) => { + (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); - }, - sayUnavailable, + }), + () => whenRowContextMenuClosed(sayUnavailable), ); }; @@ -4496,10 +4507,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { ...(writable ? { paste: () => pasteClipboardInto(row, columnKey) } : {}), ...(clearable ? { - clear: () => { + clear: () => whenRowContextMenuClosed(() => { const at = cellIndexOf(rowKey, columnKey); if (at) clearCell(at.rowIndex, at.colIndex); - }, + }), } : {}), }; @@ -4584,6 +4595,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const focusable = fromKeyboard ? target : target.closest('[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. @@ -6167,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} diff --git a/ui/packages/plugin-grid/src/__tests__/cellContextMenu-36289.test.tsx b/ui/packages/plugin-grid/src/__tests__/cellContextMenu-36289.test.tsx index d066bb60e0e..9234d2f796b 100644 --- a/ui/packages/plugin-grid/src/__tests__/cellContextMenu-36289.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/cellContextMenu-36289.test.tsx @@ -45,6 +45,13 @@ const clipboard = vi.hoisted(() => ({ })); beforeEach(() => { + // The record verdict and approval-lock reads an editable grid makes answer + // nothing: every row stays editable (fail open). + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ + ok: true, status: 200, statusText: 'OK', + headers: { get: () => 'application/json' }, + json: async () => ({ success: true }), + })); clipboard.written = []; clipboard.text = ''; clipboard.refuse = false; @@ -62,6 +69,7 @@ beforeEach(() => { afterEach(() => { cleanup(); + vi.unstubAllGlobals(); }); const FIELDS = { @@ -167,7 +175,7 @@ describe('a list cell\'s right-click menu (objectstack#36289)', () => { fireEvent.click(item(menu, 'row-context-cell-paste')); await settleClipboard(); await waitFor(() => expect(g.ds.update).toHaveBeenCalledTimes(1)); - expect(g.ds.update).toHaveBeenCalledWith('account', 'r2', expect.objectContaining({ notes: 'Call back Monday' })); + expect(g.ds.update.mock.calls[0].slice(0, 3)).toEqual(['account', 'r2', { notes: 'Call back Monday' }]); await waitFor(() => expect(g.cell('Globex', 'notes')).toHaveTextContent('Call back Monday')); }); @@ -177,7 +185,7 @@ describe('a list cell\'s right-click menu (objectstack#36289)', () => { const menu = await g.openMenu(g.cell('Globex', 'email')); fireEvent.click(item(menu, 'row-context-cell-paste')); await settleClipboard(); - expect(await within(g.cell('Globex', 'email')).findByTestId('cell-readonly-reason')) + expect(await screen.findByTestId('cell-readonly-reason')) .toHaveTextContent('Please enter a valid email address'); expect(g.ds.update).not.toHaveBeenCalled(); expect(g.cell('Globex', 'email')).toHaveTextContent('hi@globex.test'); @@ -188,11 +196,12 @@ describe('a list cell\'s right-click menu (objectstack#36289)', () => { fireEvent.click(g.cell('Globex', 'email')); const catcher = () => g.container.querySelector('[data-slot="cell-type-catcher"]')!; fireEvent.paste(catcher(), { clipboardData: { getData: () => 'not an address' } }); - expect(await within(g.cell('Globex', 'email')).findByTestId('cell-readonly-reason')) + expect(await screen.findByTestId('cell-readonly-reason')) .toHaveTextContent('Please enter a valid email address'); expect(g.ds.update).not.toHaveBeenCalled(); fireEvent.paste(catcher(), { clipboardData: { getData: () => 'team@globex.test' } }); - await waitFor(() => expect(g.ds.update).toHaveBeenCalledWith('account', 'r2', expect.objectContaining({ email: 'team@globex.test' }))); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledTimes(1)); + expect(g.ds.update.mock.calls[0].slice(0, 3)).toEqual(['account', 'r2', { email: 'team@globex.test' }]); }); it('a clipboard the browser will not read says so on the cell', async () => { @@ -201,7 +210,7 @@ describe('a list cell\'s right-click menu (objectstack#36289)', () => { const menu = await g.openMenu(g.cell('Globex', 'notes')); fireEvent.click(item(menu, 'row-context-cell-paste')); await settleClipboard(); - expect(await within(g.cell('Globex', 'notes')).findByTestId('cell-readonly-reason')) + expect(await screen.findByTestId('cell-readonly-reason')) .toHaveTextContent('The browser didn\'t let the list read the clipboard'); expect(g.ds.update).not.toHaveBeenCalled(); }); @@ -210,7 +219,8 @@ describe('a list cell\'s right-click menu (objectstack#36289)', () => { const g = await renderGrid(); const menu = await g.openMenu(g.cell('Acme', 'notes')); fireEvent.click(item(menu, 'row-context-cell-clear')); - await waitFor(() => expect(g.ds.update).toHaveBeenCalledWith('account', 'r1', expect.objectContaining({ notes: null }))); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledTimes(1)); + expect(g.ds.update.mock.calls[0].slice(0, 3)).toEqual(['account', 'r1', { notes: null }]); }); it('Clear is unavailable on a required field (control: available on an optional one)', async () => { diff --git a/ui/packages/plugin-grid/src/__tests__/rowContextMenu-28434.test.tsx b/ui/packages/plugin-grid/src/__tests__/rowContextMenu-28434.test.tsx index 7202d686504..d5894ec58a9 100644 --- a/ui/packages/plugin-grid/src/__tests__/rowContextMenu-28434.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/rowContextMenu-28434.test.tsx @@ -128,8 +128,15 @@ async function settle() { } const contextMenu = () => screen.queryByTestId('row-context-menu'); +/** + * The row's items of a menu: a menu opened on a data cell lists that cell's + * own items first (objectstack#36289, pinned in `cellContextMenu-36289`), + * which these pins leave out. + */ const itemIds = (menu: HTMLElement) => - within(menu).queryAllByRole('menuitem').map((el) => el.getAttribute('data-testid')); + within(menu).queryAllByRole('menuitem') + .map((el) => el.getAttribute('data-testid')) + .filter((id) => !id?.startsWith('row-context-cell-') && id !== 'row-context-field-history'); /** The "⋮" items of a row, read off its real menu, which is closed again. */ async function kebabItemIds(name: string): Promise<(string | null)[]> { From 2f73214d8a7d09d30e3fe605a2a68239b9f2177c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 22:25:36 +0000 Subject: [PATCH 4/4] test(grid): the phone-card pin reads the row's section; zh-Hant regenerated Claude-Session: https://claude.ai/code/session_01JQwxbXwSwKtFLjfawUUTVG Co-authored-by: Claude --- ui/packages/i18n/src/locales/zh-Hant.ts | 6 +++--- .../src/__tests__/phoneCardRowActions-29150.test.tsx | 10 ++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 527091c522d..2243d21dbf8 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -571,9 +571,9 @@ const zhHant = { // 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)貼上。', + 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: '已儲存', diff --git a/ui/packages/plugin-grid/src/__tests__/phoneCardRowActions-29150.test.tsx b/ui/packages/plugin-grid/src/__tests__/phoneCardRowActions-29150.test.tsx index 7da188b5821..cb970b201fd 100644 --- a/ui/packages/plugin-grid/src/__tests__/phoneCardRowActions-29150.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/phoneCardRowActions-29150.test.tsx @@ -103,7 +103,11 @@ const itemIds = (menu: HTMLElement) => within(menu).queryAllByRole('menuitem').map((el) => el.getAttribute('data-testid')); const OPEN_ITEMS = ['row-context-open', 'row-context-open-new-tab']; -/** Desktop: the row's context menu, minus Open / Open in new tab. */ +/** + * Desktop: the row's context menu, minus Open / Open in new tab and minus the + * cell's own section a menu opened on a data cell lists first + * (objectstack#36289): the row's actions only. + */ async function desktopRowActions(): Promise> { setWidth(1280); renderGrid(); @@ -116,7 +120,9 @@ async function desktopRowActions(): Promise> { const cell = within(screen.getByText(row.name).closest('tr') as HTMLElement).getByText(row.status); act(() => { fireEvent.contextMenu(cell, { button: 2, clientX: 40, clientY: 60 }); }); const menu = await screen.findByTestId('row-context-menu'); - out[row.name] = itemIds(menu).filter((id) => !OPEN_ITEMS.includes(id ?? '')); + out[row.name] = itemIds(menu).filter( + (id) => !OPEN_ITEMS.includes(id ?? '') && !id?.startsWith('row-context-cell-') && id !== 'row-context-field-history', + ); await userEvent.keyboard('{Escape}'); await waitFor(() => expect(screen.queryByTestId('row-context-menu')).toBeNull()); }