From 370254097eabe0a19eab984a1072da5c9b4fe7b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 01:24:43 +0000 Subject: [PATCH 01/17] wip(ui): select-first cell model in data-table Claude-Session: https://claude.ai/code/session_01L6bhgTC8kn7AdeMpMmyhJG Co-authored-by: Claude --- .../src/context/gridCellSelection.tsx | 74 ++++ ui/packages/components/src/index.ts | 9 + .../src/renderers/complex/data-table.tsx | 379 +++++++++++++++++- .../complex/dataTableCellSelection.ts | 95 +++++ 4 files changed, 543 insertions(+), 14 deletions(-) create mode 100644 ui/packages/components/src/context/gridCellSelection.tsx create mode 100644 ui/packages/components/src/renderers/complex/dataTableCellSelection.ts diff --git a/ui/packages/components/src/context/gridCellSelection.tsx b/ui/packages/components/src/context/gridCellSelection.tsx new file mode 100644 index 00000000000..8302bd61347 --- /dev/null +++ b/ui/packages/components/src/context/gridCellSelection.tsx @@ -0,0 +1,74 @@ +/** + * 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. + */ + +/** + * GridCellSelection — the select-first cell model of a data-table, opted into + * by a HOST, never by metadata (objectstack#35684, objectstack#35687). + * + * Inside a provider whose value is not `null`, a data cell is SELECTED by a + * single click, never edited by it and never opening the record. An editor + * opens on double-click, Enter, F2 or typing; Space opens the record; Esc + * cancels; Enter and Tab commit and move (in a multi-line editor Enter is a + * newline and Ctrl/Cmd+Enter commits). A cell that opens no editor says why + * in place. Outside a provider (`null`, the default) the table keeps its + * click-to-edit / click-to-open behaviour byte for byte, so every host that + * does not mount this keeps what it had. + * + * `ObjectGrid` mounts it around the table it draws, when its host asks for the + * model (`ListView`, the list page, does). + */ + +import React from 'react'; + +/** What a host knows about one cell that the table cannot read off a column. */ +export interface GridCellFacts { + /** + * Why this cell opens no editor, as a sentence in the reader's language. + * Present ⇒ the cell selects but never edits, and an attempt to edit it + * (double-click, Enter, F2, typing) shows this sentence on the cell. + */ + readOnlyReason?: string | null; + /** + * What a printable key typed on the selected cell does: `replace` opens the + * editor with the typed text in place of the value (text, numbers); `open` + * opens the editor over the value and the key is not written (a picker, a + * date). Absent ⇒ the table decides from the column's type. + */ + typing?: 'replace' | 'open'; + /** A two-state value: a click on the selected cell, or Space, flips it and commits. */ + toggles?: boolean; + /** + * The value pasted text stands for in this cell, or `undefined` when the + * text is not one (Ctrl/Cmd+V on the selected cell then writes nothing). + */ + fromText?: (text: string) => unknown; +} + +export interface GridCellSelection { + /** The host's facts for one cell; asked when the reader acts on it, never per render. */ + describeCell?: (row: any, columnKey: string) => GridCellFacts | null | undefined; + /** Called when a cell becomes the selected one (a host may prefetch what an edit will need). */ + onCellSelect?: (row: any, columnKey: string) => void; +} + +const GridCellSelectionContext = React.createContext(null); + +export function GridCellSelectionProvider({ + value, + children, +}: { + value: GridCellSelection | null; + children: React.ReactNode; +}): React.ReactElement { + return {children}; +} + +/** The select-first cell model in force here, or `null` when no host asked for it. */ +export function useGridCellSelection(): GridCellSelection | null { + return React.useContext(GridCellSelectionContext); +} diff --git a/ui/packages/components/src/index.ts b/ui/packages/components/src/index.ts index 43a185eb2f0..eef1cc2531f 100644 --- a/ui/packages/components/src/index.ts +++ b/ui/packages/components/src/index.ts @@ -167,6 +167,15 @@ export { type GridFieldAuthoring, } from './context/gridFieldAuthoring'; +// The select-first cell model (objectstack#35684): a host opts a data-table +// into it by wrapping the table in the provider. +export { + GridCellSelectionProvider, + useGridCellSelection, + type GridCellSelection, + type GridCellFacts, +} from './context/gridCellSelection'; + // Export raw Shadcn UI components export * from './ui'; export * from './custom'; diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index b231bfe9ff1..a622f240239 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -13,6 +13,8 @@ import { resolveIcon } from '../action/resolve-icon'; import { hasDeclaredVisibilityGate } from '../action/visibility-gate'; import { DisabledReasonMenuLabel, menuItemReasonAria, useDisabledReason } from '../action/disabled-reason'; import { useGridFieldAuthoring } from '../../context/gridFieldAuthoring'; +import { useGridCellSelection } from '../../context/gridCellSelection'; +import { caretToEnd, defaultTyping, defaultValueFromText, firstEditorControl, isCellWidgetTarget, isImeKey, isPrintableKey } from './dataTableCellSelection'; import { useHorizontalOverflow, HOVER_SCROLLBAR_CLASSES } from '../../custom/use-horizontal-overflow'; import { ActiveListRow, listRecordIdOf } from '../../custom/record-list-face'; import { describeIgnoredBind, describeNonArrayData } from './dataTableBindDiagnostic'; @@ -31,6 +33,8 @@ import { TableCaption } from '../../ui/table'; import { Button } from '../../ui/button'; +import { Popover, PopoverContent } from '../../ui/popover'; +import { Anchor as PopoverAnchor } from '@radix-ui/react-popover'; import { Input } from '../../ui/input'; import { Checkbox } from '../../ui/checkbox'; import { TriStateCheckbox } from '../../custom/tri-state-checkbox'; @@ -335,6 +339,9 @@ const TABLE_DEFAULT_TRANSLATIONS: Record = { 'table.openRecord': 'Open record', 'table.cancelChanges': 'Cancel changes', 'table.saveRow': 'Save row', + // objectstack#35684 — a selected cell that opens no editor, when its host + // gives no reason of its own. + 'table.cellReadOnly': 'This cell can\'t be edited here.', 'common.actions': 'Actions', // objectui#10625 — the inline date editors' notice for a stored value // written on a day that does not exist. The SAME keys `DateField` / @@ -1332,6 +1339,33 @@ function sameDrawnSizes(a: DrawnColumnSizes, b: DrawnColumnSizes): boolean { * @param {DataTableSchema} props.schema - Table schema configuration * @returns {JSX.Element} Rendered data table component */ +/** + * objectstack#35684 — why a selected cell opens no editor, drawn on the cell + * when an edit is asked of it. It takes no focus (typing carries on in the + * cell) and closes on the next key, press or selection. + */ +function CellNotice({ text, onDismiss }: { text: string; onDismiss: () => void }) { + return ( + { if (!open) onDismiss(); }}> + + + e.preventDefault()} + onCloseAutoFocus={(e) => e.preventDefault()} + className="w-auto max-w-xs px-2.5 py-1.5 text-xs" + > + {text} + + + ); +} + const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const { caption, @@ -1363,7 +1397,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { reorderableColumns = true, editable = false, singleClickEdit = false, - keyboardNavigation = false, + keyboardNavigation: keyboardNavigationProp = false, rowClassName, rowStyle, className, @@ -1382,6 +1416,14 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { bind: authoredBind, } = schema; + // objectstack#35684 — the select-first cell model, when a host mounted one + // (`GridCellSelection`): a click selects a cell, an editor opens on + // double-click, Enter, F2 or typing, Space opens the record. It needs the + // arrow keys, so it turns the roving-cell navigation on. + const cellSelection = useGridCellSelection(); + const selectFirst = cellSelection !== null; + const keyboardNavigation = keyboardNavigationProp || selectFirst; + // 'single' caps the selection at one row (replace-on-select) and drops the // select-all header; every truthy legacy value keeps meaning 'multiple'. const selectionMode = resolveSelectionMode(selectableProp); @@ -1893,6 +1935,9 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // The last pointer that pressed a row: a touch long-press raises // `contextmenu` too, and touch keeps the row's "⋮" instead. const rowPointerTypeRef = useRef(''); + /** objectstack#35684 — a touch press opens the record and never selects or edits a cell. */ + const isTouchPress = (e: React.MouseEvent) => + ((e.nativeEvent as PointerEvent).pointerType || rowPointerTypeRef.current) === 'touch'; // When the keyboard last opened the menu: the browser may raise its own // `contextmenu` for the same key press right after. const rowContextMenuKeyboardAtRef = useRef(Number.NEGATIVE_INFINITY); @@ -2522,8 +2567,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // `editable`; a refused row reads exactly like a row of a read-only table. const rowMayEdit = (row: any): boolean => isRowEditable?.(row) !== false; - // Cell editing handlers - const startEdit = (row: any, columnKey: string) => { + // Cell editing handlers. `seed` (the select-first model's typing and + // Backspace, objectstack#35687) opens the editor on that value instead of + // the cell's; the cell's own value still decides what Escape restores. + const startEdit = (row: any, columnKey: string, seed?: { value: unknown }) => { if (!editable || !rowMayEdit(row)) return; const rowKey = pendingRowKeyOf(row); @@ -2554,7 +2601,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // Check if there's a pending change for this cell, otherwise use current data value const rowChanges = pendingChanges.get(rowKey)?.changes; const currentValue = row[columnKey]; - const valueToEdit = rowChanges?.[columnKey] ?? currentValue ?? ''; + const valueToEdit = seed ? seed.value : rowChanges?.[columnKey] ?? currentValue ?? ''; setEditValue(valueToEdit); // Snapshot the cell's pending state so Escape/cancel can revert an injected // widget edit (which stages on every change) back to exactly what it was. @@ -3067,8 +3114,200 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { } }; + // ── The select-first cell model (objectstack#35684, objectstack#35687) ── + // + // Behind `GridCellSelection` (a host's choice, never metadata). One cell is + // SELECTED: it carries an outline ring that moves no layout, and focus sits + // in an invisible text box inside it, the type catcher. An input method only + // composes into an editable element, so the box is what lets a composition + // that starts on a selected cell keep its first syllable: the composed text + // opens the editor when the input method hands it over, and the keys pressed + // while composing are never read as Enter, Esc, Tab or arrows. What is + // typed or pasted there opens the editor (or, pasted, writes the cell); the + // box itself never holds a value. + // + // Kept by record and column, like an edit (objectui#12310): a re-read that + // moves or drops the row moves or drops the selection with it. Focus moves + // to the catcher only after the reader acted on the grid + // (`focusSelectionRef`), never because the rows changed under it. + const [selectedCell, setSelectedCellKey] = useState<{ rowKey: PendingRowKey; columnKey: string } | null>(null); + const selectedRowIndex = selectedCell ? paginatedData.findIndex((r) => pendingRowKeyOf(r) === selectedCell.rowKey) : -1; + const selectedColIndex = selectedCell ? columns.findIndex((c) => c.accessorKey === selectedCell.columnKey) : -1; + const selectedPos = selectedRowIndex >= 0 && selectedColIndex >= 0 + ? { rowIndex: selectedRowIndex, colIndex: selectedColIndex } + : null; + const setSelectedCell = (pos: { rowIndex: number; colIndex: number } | null) => + setSelectedCellKey(pos ? { rowKey: pendingRowKeyOf(paginatedData[pos.rowIndex]), columnKey: columns[pos.colIndex].accessorKey } : null); + const focusSelectionRef = useRef(false); + useEffect(() => { + if (!focusSelectionRef.current || editingCell) return; + focusSelectionRef.current = false; + tableRef.current?.querySelector('[data-slot="cell-type-catcher"]')?.focus(); + }); + const [composing, setComposing] = useState(false); + const composingRef = useRef(false); + // Why the cell an edit was asked of opens no editor, drawn on that cell. + const [cellNotice, setCellNotice] = useState<{ rowIndex: number; colIndex: number; text: string } | null>(null); + + const selectCell = (rowIndex: number, colIndex: number) => { + const row = paginatedData[rowIndex]; + const col = columns[colIndex]; + if (row === undefined || col === undefined) return; + setCellNotice(null); + rove(rowIndex, colIndex); + focusSelectionRef.current = true; + if (selectedPos?.rowIndex === rowIndex && selectedPos.colIndex === colIndex) return; + setSelectedCell({ rowIndex, colIndex }); + cellSelection?.onCellSelect?.(row, col.accessorKey); + }; + + const factsOf = (row: any, col: TableColumn) => cellSelection?.describeCell?.(row, col.accessorKey) ?? null; + + /** Why this cell opens no editor, or `null` when it opens one. */ + const readOnlyReasonOf = (row: any, col: TableColumn): string | null => { + const reason = factsOf(row, col)?.readOnlyReason; + if (reason) return reason; + return editable && col.editable !== false && !col.masked && rowMayEdit(row) ? null : t('table.cellReadOnly'); + }; + + /** Open the editor on a cell, or say on the cell why it opens none. */ + const attemptEdit = (rowIndex: number, colIndex: number, seed?: { value: unknown }) => { + const row = paginatedData[rowIndex]; + const col = columns[colIndex]; + if (row === undefined || col === undefined) return; + const reason = readOnlyReasonOf(row, col); + if (reason) { + setCellNotice({ rowIndex, colIndex, text: reason }); + return; + } + setCellNotice(null); + setSelectedCell({ rowIndex, colIndex }); + startEdit(row, col.accessorKey, seed); + }; + + /** Write a value into a cell without an editor: the commit `saveEdit` makes. */ + const commitCellValue = (row: any, columnKey: string, value: unknown) => { + const rowKey = pendingRowKeyOf(row); + const held = heldRowOf(rowKey) ?? row; + const inFlight = inFlightRef.current.get(rowKey); + setPendingChanges((prev) => stageCellChange(prev, rowKey, held, columnKey, value, inFlight)); + clearCellError(rowKey, columnKey); + schema.onCellChange?.(rowIndexOf(rowKey), columnKey, value, held); + }; + + /** What a cell does with a value it is handed rather than edited: a toggle or a paste. */ + const writeCell = (rowIndex: number, colIndex: number, valueOf: (row: any, col: TableColumn) => unknown) => { + const row = paginatedData[rowIndex]; + const col = columns[colIndex]; + if (row === undefined || col === undefined) return; + const reason = readOnlyReasonOf(row, col); + if (reason) { + setCellNotice({ rowIndex, colIndex, text: reason }); + return; + } + const value = valueOf(row, col); + if (value !== undefined) commitCellValue(row, col.accessorKey, value); + }; + + const togglesCell = (row: any, col: TableColumn) => factsOf(row, col)?.toggles ?? col.type === 'boolean'; + const toggleCell = (rowIndex: number, colIndex: number) => writeCell(rowIndex, colIndex, (row, col) => { + const staged = pendingChanges.get(pendingRowKeyOf(row))?.changes; + const current = staged && col.accessorKey in staged ? staged[col.accessorKey] : row[col.accessorKey]; + return current !== true; + }); + 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); + }); + + /** Text typed or composed on the selected cell. */ + const typeIntoCell = (rowIndex: number, colIndex: number, text: string) => { + const row = paginatedData[rowIndex]; + const col = columns[colIndex]; + if (text === '' || row === undefined || col === undefined) return; + const facts = factsOf(row, col); + if ((facts?.typing ?? defaultTyping(col)) === 'open') { + attemptEdit(rowIndex, colIndex); + return; + } + const converted = facts?.fromText?.(text); + attemptEdit(rowIndex, colIndex, { value: converted !== undefined ? converted : text }); + }; + + /** After Enter or Tab committed the selected cell's edit: the cell it moves to. */ + const moveSelection = (direction: 'down' | 'right' | 'left') => { + if (!selectedPos) return; + const { rowIndex, colIndex } = selectedPos; + if (direction === 'down') selectCell(Math.min(paginatedData.length - 1, rowIndex + 1), colIndex); + else selectCell(rowIndex, Math.max(0, Math.min(columns.length - 1, colIndex + (direction === 'right' ? 1 : -1)))); + }; + + /** The selected cell's keys, while no editor is open (an open editor owns every key). */ + const handleSelectFirstKeyDown = (e: React.KeyboardEvent, rowIndex: number, colIndex: number) => { + if (isImeKey(e) || editingCell) return; + // The cell or its catcher, not a widget inside it: a record link keeps Enter. + const target = e.target as HTMLElement; + const onCatcher = target.matches('[data-slot="cell-type-catcher"]'); + if (target !== e.currentTarget && !onCatcher) return; + const row = paginatedData[rowIndex]; + const col = columns[colIndex]; + if (row === undefined || col === undefined) return; + const bare = !e.ctrlKey && !e.metaKey && !e.altKey; + if (e.key === 'Escape') { + if (cellNotice) setCellNotice(null); + else if (selectedPos) { + e.preventDefault(); + focusGridCell(rowIndex, colIndex); + setSelectedCell(null); + } + return; + } + setCellNotice(null); + const next = navigationTarget(e, rowIndex, colIndex); + if (next) { + e.preventDefault(); + selectCell(next.rowIndex, next.colIndex); + return; + } + if (e.key === 'Tab' && bare) { + // Along the row, then on to the next one; at either end of the page + // Tab leaves the grid, as it does any widget. + const at = rowIndex * columns.length + colIndex + (e.shiftKey ? -1 : 1); + if (at < 0 || at >= paginatedData.length * columns.length) return; + e.preventDefault(); + selectCell(Math.floor(at / columns.length), at % columns.length); + return; + } + if (!onCatcher) { + // Focus on the bare cell (after Esc): the first key selects it again. + if (bare && (isPrintableKey(e) || e.key === 'Enter' || e.key === 'F2')) { + e.preventDefault(); + selectCell(rowIndex, colIndex); + } + return; + } + if ((e.key === 'Enter' || e.key === 'F2') && bare && !e.shiftKey) { + e.preventDefault(); + attemptEdit(rowIndex, colIndex); + } else if (e.key === ' ' && bare) { + e.preventDefault(); + if (togglesCell(row, col)) toggleCell(rowIndex, colIndex); + else schema.onRowClick?.(row, e); + } else if ((e.key === 'Backspace' || e.key === 'Delete') && bare) { + // An empty editor; nothing is written until it commits. + e.preventDefault(); + attemptEdit(rowIndex, colIndex, { value: '' }); + } + // A printable key lands in the catcher, which reads it (`typeIntoCell`). + }; + const handleCellKeyDown = (e: React.KeyboardEvent, rowIndex: number, colIndex: number, columnKey: string) => { - if (keyboardNavigation) { + if (selectFirst) { + if (!((e.ctrlKey || e.metaKey) && (e.key === 'c' || e.key === 'C'))) { + handleSelectFirstKeyDown(e, rowIndex, colIndex); + return; + } + } else if (keyboardNavigation) { // An edit in this cell that the key now bubbling through it just ended // (Enter committed it, Escape cancelled it): `editingCellRef` is cleared // synchronously by the editor's own handler, while `editingCell` is still @@ -3116,7 +3355,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { return; } - if (!editable || !rowMayEdit(paginatedData[rowIndex])) return; + if (selectFirst || !editable || !rowMayEdit(paginatedData[rowIndex])) return; const column = columns.find(col => col.accessorKey === columnKey); if (column?.editable === false) return; @@ -3128,25 +3367,52 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { }; const handleEditKeyDown = (e: React.KeyboardEvent) => { - if (e.key === 'Enter') { + // A key the input method owns picks or moves a candidate (objectstack#35687). + if (isImeKey(e)) return; + if (e.key === 'Enter' || (selectFirst && e.key === 'Tab')) { e.preventDefault(); // Already saving here; suppress the redundant save the ensuing blur triggers. skipBlurSaveRef.current = true; saveEdit(true); + // The select-first model: Enter saves and moves down, Tab right, Shift+Tab left. + if (selectFirst) moveSelection(e.key === 'Enter' ? 'down' : e.shiftKey ? 'left' : 'right'); } else if (e.key === 'Escape') { e.preventDefault(); + focusSelectionRef.current = selectFirst; cancelEdit(); } }; - // Auto-focus on edit input when entering edit mode + // Auto-focus on edit input when entering edit mode. The select-first model + // keeps what was typed or what the cell held, caret after it. useEffect(() => { if (editingCell && editInputRef.current) { editInputRef.current.focus(); - editInputRef.current.select(); + if (selectFirst) caretToEnd(editInputRef.current); + else editInputRef.current.select(); } }, [editingCell]); + // …and an injected editor takes the caret the same way (objectstack#35687): + // its first control, once it has drawn one (a lazily loaded picker draws it + // a few frames late). Before this the caret stayed on the cell. + useEffect(() => { + if (!selectFirst || !editingCell) return undefined; + let frame = 0; + let frames = 0; + const place = () => { + const host = injectedEditorElRef.current; + if (!host || host.contains(document.activeElement)) return; + const control = firstEditorControl(host); + if (control) { + control.focus({ preventScroll: true }); + caretToEnd(control); + } else if (++frames < 30) frame = requestAnimationFrame(place); + }; + place(); + return () => cancelAnimationFrame(frame); + }, [editingCell, selectFirst]); + // Commit a host-injected widget editor on click-outside (objectui#2321). // // Built-in `` editors commit via their own onBlur (handleEditBlur). The @@ -3919,7 +4185,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // The open record's row, frozen cells included. "data-[active-record]:bg-primary/10 data-[active-record]:[--os-row-tint:color-mix(in_oklab,var(--color-primary)_10%,transparent)]", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-inset", - schema.onRowClick && "cursor-pointer", + !selectFirst && schema.onRowClick && "cursor-pointer", rowHasChanges && !rowErrored && "bg-amber-50 dark:bg-amber-950/20", rowErrored && "bg-destructive/10 dark:bg-destructive/15 ring-1 ring-inset ring-destructive/40", rowClassName && rowClassName(row, rowIndex) @@ -4128,6 +4394,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // the host's per-row verdict refuses (objectstack#27365). const isEditable = editable && col.editable !== false && !col.masked && rowMayEdit(row); const isFrozen = frozenColumns > 0 && colIndex < frozenColumns; + // objectstack#35684 — the selected cell of the select-first model. + const isSelectedCell = selectFirst && selectedPos?.rowIndex === rowIndex && selectedPos.colIndex === colIndex; const frozenOffset = isFrozen ? measuredStickyLefts?.[leadingCellCount + colIndex] ?? columns.slice(0, colIndex).reduce((sum, c, i) => { @@ -4151,7 +4419,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // content (row-action buttons); every other column // keeps overflow-hidden for truncation. isFit ? 'whitespace-nowrap' : 'overflow-hidden', - isEditable && !isEditing && "cursor-text hover:bg-muted/50", + !selectFirst && isEditable && !isEditing && "cursor-text hover:bg-muted/50", + // A ring that moves no layout (outline, not border). + isSelectedCell && "outline-2 -outline-offset-2 outline-primary", + selectFirst && !isFrozen && "relative", hasPendingChange && "font-semibold text-amber-700 dark:text-amber-400", cellError !== undefined && "ring-2 ring-inset ring-destructive", isFrozen && ['sticky z-10 bg-background', STICKY_ROW_TINT], @@ -4171,6 +4442,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { ...(pinnedRightOffset ? { right: pinnedRightOffset } : {}), }} onDoubleClick={(e) => { + if (selectFirst) { + // objectstack#35684 — a double-click on the cell (not on a + // link it draws) edits; a two-state cell already flipped on + // the second click. A touch never edits in place. + if (isEditing || isTouchPress(e) || isCellWidgetTarget(e.target, e.currentTarget)) return; + if (hasTextSelectionIn(e.currentTarget)) return; + e.stopPropagation(); + if (!togglesCell(row, col)) attemptEdit(rowIndex, colIndex); + return; + } // Entering edit mode must NOT also fire the row's // onRowClick (record-detail drawer). The row heuristic // can't see the editor yet (the only renders @@ -4182,6 +4463,19 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { } }} onClick={(e) => { + if (selectFirst) { + // objectstack#35684 — a click SELECTS the cell; it neither + // edits nor opens the record. A link or button the cell + // draws keeps its own click, and a touch tap still opens + // the record through the row. + if (isTouchPress(e) || isCellWidgetTarget(e.target, e.currentTarget)) return; + e.stopPropagation(); + if (isEditing) return; + const wasSelected = isSelectedCell; + selectCell(rowIndex, colIndex); + if (wasSelected && togglesCell(row, col)) toggleCell(rowIndex, colIndex); + return; + } if (isEditable && singleClickEdit && !hasTextSelectionIn(e.currentTarget)) { e.stopPropagation(); startEdit(row, col.accessorKey); @@ -4193,16 +4487,61 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // `handleCellKeyDown`); every cell its own stop when // it is off, exactly as before. The address and the // focus tracking exist only in the first case. - tabIndex={keyboardNavigation ? (rowIndex === rovingRowIndex && colIndex === rovingColIndex ? 0 : -1) : 0} + tabIndex={keyboardNavigation ? (rowIndex === rovingRowIndex && colIndex === rovingColIndex && !isSelectedCell ? 0 : -1) : 0} data-grid-cell={keyboardNavigation ? `${rowIndex}:${colIndex}` : undefined} onFocus={keyboardNavigation ? () => rove(rowIndex, colIndex) : undefined} aria-invalid={cellError !== undefined || undefined} // objectstack#28434 — a cell in edit mode keeps the // browser's context menu (`keepsBrowserContextMenu`). data-editing-cell={isEditing ? '' : undefined} + data-selected-cell={isSelectedCell ? '' : undefined} + aria-selected={selectFirst ? isSelectedCell : undefined} data-cell-error={cellError} title={cellError} > + {isSelectedCell && !isEditing && ( + { + composingRef.current = true; + setComposing(true); + setCellNotice(null); + }} + onCompositionEnd={(e) => { + composingRef.current = false; + setComposing(false); + const text = e.currentTarget.value; + e.currentTarget.value = ''; + typeIntoCell(rowIndex, colIndex, text); + }} + onChange={(e) => { + if (composingRef.current || (e.nativeEvent as InputEvent).isComposing) return; + const text = e.currentTarget.value; + e.currentTarget.value = ''; + typeIntoCell(rowIndex, colIndex, text); + }} + onPaste={(e) => { + const text = e.clipboardData?.getData('text/plain') ?? ''; + e.preventDefault(); + if (text !== '') pasteIntoCell(rowIndex, colIndex, text); + }} + /> + )} + {cellNotice?.rowIndex === rowIndex && cellNotice.colIndex === colIndex && ( + setCellNotice(null)} /> + )} {isEditing ? ( (() => { // Type-aware inline editor. `col.type` is forwarded @@ -4266,7 +4605,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // textarea it's left alone so Enter opens the // dropdown / inserts a newline as usual. // - // Tab is deliberately NOT in that list, and + // Outside the select-first model, Tab is + // deliberately NOT in that list, and // tabbing out therefore does not leave edit // mode — measured, `64d937c53`. It costs // nothing: the widget has already staged @@ -4282,14 +4622,25 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { className="w-full" onKeyDown={(e) => { if (!e.currentTarget.contains(e.target as Node)) return; - if (e.key === 'Enter' && (e.target as HTMLElement).tagName === 'INPUT') { + // The input method's keys (objectstack#35687). + if (isImeKey(e)) return; + const tag = (e.target as HTMLElement).tagName; + // The select-first model (objectstack#35687): in a + // multi-line editor Ctrl/Cmd+Enter commits, and Tab + // commits and moves, superseding the Tab-stays rule. + const commits = (e.key === 'Enter' && (tag === 'INPUT' + || (selectFirst && tag === 'TEXTAREA' && (e.ctrlKey || e.metaKey)))) + || (selectFirst && e.key === 'Tab'); + if (commits) { e.preventDefault(); // A commit-on-blur widget stages // on this blur (objectui#12664). flushInjectedEditor(); saveEdit(true); + if (selectFirst) moveSelection(e.key === 'Enter' ? 'down' : e.shiftKey ? 'left' : 'right'); } else if (e.key === 'Escape') { e.preventDefault(); + focusSelectionRef.current = selectFirst; exitEdit(true); } }} diff --git a/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts b/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts new file mode 100644 index 00000000000..709bc3bbea5 --- /dev/null +++ b/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts @@ -0,0 +1,95 @@ +/** + * 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. + */ + +/** + * The pure halves of `data-table`'s select-first cell model + * (objectstack#35684, objectstack#35687; the model itself is + * `GridCellSelection` in `../../context/gridCellSelection`). + */ +import type { TableColumn } from '@object-ui/types'; + +/** + * A key the input method owns: pressed while a composition is open + * (`isComposing`), or the 229 a browser reports for the key that ends one + * (Safari raises the candidate-picking Enter after `compositionend`, as 229). + * Enter, Esc, Tab and the arrows pressed then pick or move a candidate; the + * table must not commit, cancel or move on them. + */ +export function isImeKey(e: { nativeEvent: KeyboardEvent; keyCode?: number }): boolean { + return e.nativeEvent.isComposing === true || e.nativeEvent.keyCode === 229 || e.keyCode === 229; +} + +/** + * A press on a control a cell draws (a record link, a phone or mail link, a + * button, a checkbox) keeps its own click: it is not a press on the cell. + */ +export function isCellWidgetTarget(target: EventTarget | null, cell: Element): boolean { + if (!(target instanceof Element) || !cell.contains(target)) return false; + const widget = target.closest( + 'a[href], button, input, select, textarea, label, [role="link"], [role="button"], [role="checkbox"], [role="switch"], [contenteditable]:not([contenteditable="false"])', + ); + return widget !== null && widget !== cell && cell.contains(widget) && !widget.matches('[data-slot="cell-type-catcher"]'); +} + +/** A printable key with no command modifier — what typing on a selected cell is. */ +export function isPrintableKey(e: { key: string; ctrlKey: boolean; metaKey: boolean; altKey: boolean }): boolean { + return e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey; +} + +const TEXT_TYPED_COLUMN_TYPES: ReadonlySet = new Set(['text', 'number', 'currency', 'percent']); +const NUMBER_COLUMN_TYPES: ReadonlySet = new Set(['number', 'currency', 'percent']); + +/** What typing does on a column the host says nothing about: text and figures take the typed text. */ +export function defaultTyping(col: TableColumn): 'replace' | 'open' { + if (col.foreignKey) return 'open'; + return col.type === undefined || TEXT_TYPED_COLUMN_TYPES.has(col.type) ? 'replace' : 'open'; +} + +/** + * The value pasted text stands for in a column the host says nothing about, + * or `undefined` when it stands for none (nothing is written then). + */ +export function defaultValueFromText(col: TableColumn, raw: string): unknown { + const text = raw.replace(/\r?\n$/, ''); + if (col.foreignKey || col.type === 'action') return undefined; + if (col.type && NUMBER_COLUMN_TYPES.has(col.type)) { + const trimmed = text.trim(); + const n = trimmed === '' ? Number.NaN : Number(trimmed); + return Number.isFinite(n) ? n : undefined; + } + if (col.type === 'boolean') { + const word = text.trim().toLowerCase(); + if (word === 'true' || word === '1' || word === 'yes') return true; + if (word === 'false' || word === '0' || word === 'no') return false; + return undefined; + } + if (col.type === 'date') return /^\d{4}-\d{2}-\d{2}$/.test(text.trim()) ? text.trim() : undefined; + if (col.type === 'datetime') { + const at = Date.parse(text.trim()); + return Number.isNaN(at) ? undefined : new Date(at).toISOString(); + } + return text; +} + +/** Put the caret after the last character of a text control (no-op where the control has no caret). */ +export function caretToEnd(el: Element): void { + if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) return; + try { + const end = el.value.length; + el.setSelectionRange(end, end); + } catch { + // `number`, `date` and friends have no selection API; focus is enough there. + } +} + +/** The control an injected editor hands the caret to, or `null` while it has not mounted one. */ +export function firstEditorControl(host: Element): HTMLElement | null { + return host.querySelector( + 'input:not([type="hidden"]):not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled]), [tabindex]:not([tabindex="-1"])', + ); +} From 0311f54ad0fb0241f7dab05252baa590ff3d81d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 01:38:07 +0000 Subject: [PATCH 02/17] wip(ui): list page grid selects first; cell facts, read-only reasons, toggle retired Claude-Session: https://claude.ai/code/session_01L6bhgTC8kn7AdeMpMmyhJG Co-authored-by: Claude --- content/docs/frontend/plugins/plugin-grid.mdx | 32 ++++ content/docs/frontend/plugins/plugin-view.mdx | 42 ++-- .../areas/records-forms.json | 10 +- .../areas/ux-conventions.json | 10 +- .../app-shell/src/views/objectViewChrome.tsx | 27 --- .../src/views/objectViewListRenderer.tsx | 4 +- .../src/renderers/complex/data-table.tsx | 2 +- .../complex/dataTableCellSelection.ts | 6 +- ui/packages/i18n/src/locales/ar.ts | 14 +- ui/packages/i18n/src/locales/de.ts | 14 +- ui/packages/i18n/src/locales/en.ts | 14 +- ui/packages/i18n/src/locales/es.ts | 14 +- ui/packages/i18n/src/locales/fr.ts | 14 +- ui/packages/i18n/src/locales/ja.ts | 14 +- ui/packages/i18n/src/locales/ko.ts | 14 +- ui/packages/i18n/src/locales/pt-BR.ts | 14 +- ui/packages/i18n/src/locales/ru.ts | 14 +- ui/packages/i18n/src/locales/zh-Hans.ts | 14 +- ui/packages/i18n/src/locales/zh-Hant.ts | 14 +- ui/packages/plugin-grid/src/ObjectGrid.tsx | 54 +++++- .../src/hooks/useRowApprovalLocks.ts | 88 +++++++++ .../plugin-grid/src/inline-edit-options.ts | 27 ++- .../plugin-grid/src/objectGridCellFacts.ts | 127 ++++++++++++ .../plugin-grid/src/objectGridTranslations.ts | 10 + ui/packages/plugin-list/src/ListView.tsx | 180 ++++-------------- 25 files changed, 555 insertions(+), 218 deletions(-) create mode 100644 ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts create mode 100644 ui/packages/plugin-grid/src/objectGridCellFacts.ts diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 29c39fb02ea..40d537767d3 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -350,6 +350,38 @@ through the host's data source (`dataSource.update`) with no callback to wire. To own persistence in a React host, supply `onCellChange` as a **component prop** — it is not a schema key. +#### On an object's list page + +The console's list page draws its grid with the **select-first** cell model +(objectstack#35684, objectstack#35687), which its host turns on (the +`cellSelection` component prop, not a schema key). There is no inline-edit +mode and no toggle: the grid is editable wherever the reader may edit the +object and the view does not declare `userActions.editInline: false`, and +`singleClickEdit` is not read there. + +- **A click selects** a cell (a ring around it); it neither edits nor opens the + record. A link a cell draws (the name, a lookup, a phone or an email) keeps + its own click. On a touch screen a tap opens the record. +- **Editing** starts on a double-click, Enter or F2 (the value kept, caret at + its end), or by typing, which replaces the value; an input method's + composition is kept whole. Backspace or Delete opens an empty editor and + saves nothing yet. +- **While editing**, Enter commits and moves down, Tab / Shift+Tab commit and + move right / left, and Escape cancels and keeps the cell selected. In a + multi-line editor Enter is a new line and Ctrl/Cmd+Enter commits. A click + elsewhere commits. +- **Selected cell keys:** the arrows and Tab move the selection; Space opens the + record (a checkbox cell flips instead, as does a second click on it); + Ctrl/Cmd+C copies; Ctrl/Cmd+V converts the text to the field's type and + commits it; Escape clears the selection. +- **A cell that opens no editor says why** on the cell: the field is read-only, + calculated or not editable in a list, the reader may not edit the field, the + object or the record, the view turned editing off, or the record is locked + by an approval. + +Commits are the grid's own staged edits: the row's Save / Cancel and the Save +All bar save them, as before. + ### Keyboard navigation `keyboardNavigation` turns the grid's data cells into one roving Tab stop, on the diff --git a/content/docs/frontend/plugins/plugin-view.mdx b/content/docs/frontend/plugins/plugin-view.mdx index 80501a07684..ffd6dcc3d83 100644 --- a/content/docs/frontend/plugins/plugin-view.mdx +++ b/content/docs/frontend/plugins/plugin-view.mdx @@ -654,29 +654,27 @@ panel offers every field the user may read, minus the fields the object marks **Inline editing on that node is on by default.** Both keys below are the author's permission. `ListView` reads the node's `userActions.editInline` with the spec's default, on since the v18 ruling (objectstack#22605), so a view that -declares neither key offers the inline-edit toggle (objectui#12086), and -`userActions.editInline: false` is how a view withdraws it. When the node -carries no `editInline` of its own, its `inlineEdit` stands in for it -(objectui#5144). The named view's keys win over the host `views` entry's, as -for every member above: +declares neither key is editable in place, and `userActions.editInline: false` +is how a view withdraws it. When the node carries no `editInline` of its own, +its `inlineEdit` stands in for it (objectui#5144). The named view's keys win +over the host `views` entry's, as for every member above: -| The view declares | Inline-edit toggle | Grid opens in edit mode | -| --- | --- | --- | -| neither key | offered | no | -| `inlineEdit: true` | offered | yes | -| `inlineEdit: false` | not offered | no | -| `userActions.editInline: true` | offered | only with `inlineEdit: true` | -| `userActions.editInline: false` | not offered | no, whatever `inlineEdit` says | - -The toggle switches the edit mode for the session and reports it through -`ListView`'s `onInlineEditChange`. The console stores nothing for it: each load -opens in the mode the view's `inlineEdit` declares, so a user's choice is not -remembered across loads. A view where an earlier console stored -`inlineEdit: false` still reads off; that data is not migrated, and declaring -`userActions.editInline: true` brings the toggle back. A list whose records are -read-only by nature declares `userActions.editInline: false`. Neither key opens -editing past the object's own editability or the user's permission to update -the object. +| The view declares | Grid editable in place | +| --- | --- | +| neither key | yes | +| `inlineEdit: true` | yes | +| `inlineEdit: false` | no | +| `userActions.editInline: true` | yes, whatever `inlineEdit` says | +| `userActions.editInline: false` | no, whatever `inlineEdit` says | + +There is no inline-edit mode and no toggle (objectstack#35684): a click selects +a cell and a double-click, Enter or typing edits it (the list page's +select-first model, see the grid's Inline Editing). A view where an earlier +console stored `inlineEdit: false` still reads off; that data is not migrated, +and declaring `userActions.editInline: true` turns editing back on. A list +whose records are read-only by nature declares `userActions.editInline: false`. +Neither key opens editing past the object's own editability or the user's +permission to update the object. ### Update diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 53285359f79..46e49ee8aff 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -615,7 +615,7 @@ "title": "List-view capability matrix: filter, search, sort, pagination, saved views, inline edit, export, visualization switcher, bulk/row actions, conditional formatting", "since": "v15", "status": "active", - "revision": 11, + "revision": 12, "priority": "P1", "surface": "browser", "personas": [ @@ -650,7 +650,7 @@ "quick-search 'huaning' on Accounts (or '张' on Contacts); capture the `search` request and the hits (pinyin + CJK recall, ADR-0061)", "open the tabular saved view (sort [{field: 'estimate_hours', order: 'desc'}] — the array form: #17053 retired the bare string clause 'estimate_hours desc' platform-wide, so the objectui#2601 string-crash fixture no longer exists on stock); confirm it renders and the request carries the sort as sort=-estimate_hours", "load a list past its first window. No stock list holds more rows than the 50-row window (the largest seeded task and contact lists are under it), so stage one first: POST /api/v1/data/showcase_inquiry/createMany with a bare JSON array of 55 rows (name + email + message each — showcase_inquiry requires `message` too, and a name + email body answers 400 \"Message is required\", QA run #24616). A list view that declares no `pagination` (the stock Inquiries list) draws NO pager since #35554: it loads as it scrolls, so scroll the Inquiries list to its end and capture `top`/`skip` on every data request (top=50, then top=50&skip=50); the count beside the view name reads the server total. Then page a view that DECLARES `pagination` (stage one: PUT a view with pagination: {pageSize: 50} on showcase_inquiry) past page 1 and capture the same; confirm no unpaged full fetch on either", - "in the grid saved view (inlineEdit: true), edit one cell in place; save; capture the PATCH; re-read the row via API", + "in the grid saved view, double-click one cell (a single click only selects it, #35684), edit it in place; save; capture the PATCH; re-read the row via API", "on in_progress, with the export grant from fixtures.requires[3] bound, open the view bar's Options (选项) popover — the Display popover, a text trigger since objectstack#35548 — Export sits in its footer ('Export as CSV / XLSX / JSON'), not as a separate toolbar button — and export each declared format (csv, xlsx, json); capture the requests and files. Without the grant the Export entries are absent and the route answers 403 EXPORT_NOT_PERMITTED — the opt-in working as designed, not a fail of the export variant", "open the visualization switcher on All Tasks; enumerate the offered types; switch through each", "on bulk_actions, select rows that are NOT done and run showcase_mark_done (per-record) — its visible gate, has(record.done) && record.done != true, judges each selected row, so a done row in the selection drops Mark Done from the selection actions the page bar shows (since #35554 the list page has no bottom bulk bar), or, over a mixed selection, the confirm reports the done rows not eligible and skipped (QA run #27438); either way the dispatch count stops matching the selection — and showcase_recalc_selection (aggregate — ONE dispatch: an api-type action, which the console sends through the action door, POST /api/v1/actions/showcase_task/showcase_recalc_selection with body {params:{_selectedIds:[…]}}; the server forwards those params flat to the action's own target /api/v1/apps/showcase/recalc in-process, buildApiActionRequest in packages/runtime/src/action-execution.ts, so the browser's network log shows the door request and no /recalc request); on legacy_row_actions confirm both named row actions resolve to live menu entries", @@ -812,6 +812,12 @@ "date": "2026-11-19", "change": "steps[4] and acceptance[3] (clause and verify) follow #35554: a list view that declares no `pagination` has no pager and loads its next window as it scrolls (top=50, then top=50&skip=50), and only a view that declares `pagination` pages; the paging variant now walks both. steps[8] names where the bulk actions are offered now — the page bar, while rows are selected — instead of the retired bottom bulk bar. Read at base e01b8bed (after #35548)", "ref": "#35554" + }, + { + "revision": 12, + "date": "2026-11-20", + "change": "steps[5] follows #35684: a cell is edited by a double-click (or Enter, or typing on the selected cell), a single click selects it, and the list has no inline-edit toggle. The clauses are unchanged. Read at base 238661f4", + "ref": "#35684" } ] }, diff --git a/docs/qa/platform-checklist/areas/ux-conventions.json b/docs/qa/platform-checklist/areas/ux-conventions.json index e8c3d2acfee..e1fea4d9173 100644 --- a/docs/qa/platform-checklist/areas/ux-conventions.json +++ b/docs/qa/platform-checklist/areas/ux-conventions.json @@ -9,7 +9,7 @@ "title": "Every user-initiated write answers visibly — success names what changed, a refusal says why, and a no-op claims nothing", "since": "v17.7", "status": "active", - "revision": 13, + "revision": 14, "priority": "P1", "surface": "browser", "personas": [ @@ -32,7 +32,7 @@ }, "variants": [ "record create — New form save on showcase_task", - "record inline edit — on the task object's Grid view (the named view `grid`, labelled 'Grid': the one task list that declares inlineEdit: true, examples/app-showcase/src/ui/views/task.view.ts; the default All Tasks list declares none), double-click a Priority cell (the grid has no 'Edit inline' button), change it, then Save row or Save All", + "record inline edit — on any task list (since #35684 a list is editable in place wherever its reader may edit and its view declares no userActions.editInline: false; there is no 'Edit inline' toggle), double-click a Priority cell (a single click only selects it), change it, then Save row or Save All", "bulk delete — select two rows → Delete in the selection bar → confirm", "kanban move — drag a card Backlog → To Do (direct manipulation: the card in its new column IS the success feedback; a move the transition rule blocks never leaves the client — its lane is dimmed, data-kanban-drop-blocked, and the drop sends nothing, #25933)", "declared record action — Mark Done on a task record (declared successMessage `{{ record.title | default:'Task' }} marked done.`, which names the task, examples/app-showcase/src/ui/actions/index.ts#MarkDoneAction). The action patches only done and progress, so the record's Status still reads its old value (e.g. 'To Do') beside the toast: that is the declaration, not a failed write (QA run #33861)", @@ -183,6 +183,12 @@ "date": "2026-11-15", "change": "steps[1], [2], [5] and variants[4], [6], [8] and [11] re-pointed: the update-mode import's inline result is its feedback (no toast); the settings PUT is outside /api/v1; the import Undo answers with the row's 'Undone' label; Mark Done leaves Status unchanged by declaration; the record title opens the subject record's page, where Approve also sits; Studio autosave needs a record and the column's 'Edit field properties'; and the stock currency is locked (QA run #33861, comment 6894395705, and QA run #33914, comment 6895723718; ledger 6896511848 of #33761 rows 182, 229, 230 and 231). The clauses are unchanged. Read at base 895783a1", "ref": "#33981" + }, + { + "revision": 14, + "date": "2026-11-20", + "change": "variants[1] follows #35684: every task list is editable in place, not only the Grid view that declares inlineEdit: true, and a single click selects a cell while a double-click edits it. The clauses are unchanged. Read at base 238661f4", + "ref": "#35684" } ] }, diff --git a/ui/packages/app-shell/src/views/objectViewChrome.tsx b/ui/packages/app-shell/src/views/objectViewChrome.tsx index b90a531bb8e..0677b76ec64 100644 --- a/ui/packages/app-shell/src/views/objectViewChrome.tsx +++ b/ui/packages/app-shell/src/views/objectViewChrome.tsx @@ -42,29 +42,6 @@ export function ObjectNotFoundState({ objectName, packageDisabled = false }: { o ); } -/** - * The list toolbar's inline-edit toggle, as this page wires it: it writes - * nothing (objectui#5144, triage's ruling E). - * - * The view's `inlineEdit` and `userActions.editInline` are the AUTHOR's - * permission keys, and `normalizeListViewSchema` folds the first into the - * second. `editInline` is on by default since the v18 ruling (objectstack#22605, - * objectui#12086), so a view that declares neither key offers the toggle, and - * `editInline: false` withdraws it. This toggle used to persist a USER's edit - * mode into `inlineEdit` through `persistViewPatch`. After the fold, switching - * it off stored `inlineEdit: false`, which reads as "not offered", so the - * toggle was gone from the next load and nothing in the console could bring it - * back. - * - * The edit mode is now session state. `ListView` keeps it, and seeds it from - * the view's `inlineEdit` on each load. The callback stays wired because - * `ListView` offers the wide toolbar toggle only to a host that wires one. - * - * Recorded costs: the edit mode is not remembered across loads, and an overlay - * that already stores `inlineEdit: false` still reads off. That is existing - * data, and the maintainer's ruling rejects migrating it. Declaring - * `userActions.editInline: true` on such a view brings the toggle back. - */ /** * Tailwind's `sm` breakpoint (px): from here up the list page draws its page * header, whose title is the view switcher (objectstack#27594); below it the @@ -96,7 +73,3 @@ export function useViewTabsFit(): boolean { }, []); return fits; } - -export function keepInlineEditModeForTheSession(): void { - // Deliberately empty: see the docblock. -} diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index 981886da995..7eb77aa5811 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -40,7 +40,7 @@ import { kanbanViewOptions, isSameOptionsValue, } from './objectViewOptions.js'; -import { keepInlineEditModeForTheSession, useViewTabsFit } from './objectViewChrome.js'; +import { useViewTabsFit } from './objectViewChrome.js'; import { ListRecordCountContext } from './objectViewTitleSwitcher.js'; import { OpenAsPageLink } from './objectViewOpenAsPage.js'; import type { useObjectViewIdentity } from './objectViewIdentity.js'; @@ -1101,8 +1101,6 @@ export function useObjectViewListRenderer({ // the door that stores a change to them (see `persistAddedFields`). addedFields={listColumns.addedFields} onAddedFieldsChange={addedFieldsStored ? persistAddedFields : undefined} - // objectui#5144 (ruling E): session-only, writes nothing. - onInlineEditChange={keepInlineEditModeForTheSession} onColumnStateChange={persistListColumnState} userFilterSelections={initialUfSelections} onUserFilterSelectionsChange={handleUserFilterSelectionsChange} diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index a622f240239..34cb33a1dfe 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -3230,7 +3230,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { attemptEdit(rowIndex, colIndex); return; } - const converted = facts?.fromText?.(text); + const converted = facts?.fromText ? facts.fromText(text) : defaultValueFromText(col, text); attemptEdit(rowIndex, colIndex, { value: converted !== undefined ? converted : text }); }; diff --git a/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts b/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts index 709bc3bbea5..85f655b4d75 100644 --- a/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts +++ b/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts @@ -26,14 +26,16 @@ export function isImeKey(e: { nativeEvent: KeyboardEvent; keyCode?: number }): b /** * A press on a control a cell draws (a record link, a phone or mail link, a - * button, a checkbox) keeps its own click: it is not a press on the cell. + * button, a checkbox) keeps its own click: it is not a press on the cell. A + * disabled control (a read face's checkbox) has no click of its own. */ export function isCellWidgetTarget(target: EventTarget | null, cell: Element): boolean { if (!(target instanceof Element) || !cell.contains(target)) return false; const widget = target.closest( 'a[href], button, input, select, textarea, label, [role="link"], [role="button"], [role="checkbox"], [role="switch"], [contenteditable]:not([contenteditable="false"])', ); - return widget !== null && widget !== cell && cell.contains(widget) && !widget.matches('[data-slot="cell-type-catcher"]'); + return widget !== null && widget !== cell && cell.contains(widget) + && !widget.matches('[data-slot="cell-type-catcher"], :disabled, [aria-disabled="true"]'); } /** A printable key with no command modifier — what typing on a selected cell is. */ diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 05c1d44924f..2096bad48be 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -542,8 +542,21 @@ const ar = { openRecord: "فتح السجل", cancelChanges: "إلغاء التغييرات", saveRow: "حفظ الصف", + cellReadOnly: "لا يمكن تحرير هذه الخلية هنا.", }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: "هذا الحقل للقراءة فقط.", + computed: "هذه القيمة محسوبة، لذا لا يمكن تحريرها.", + notInline: "لا يمكن تحرير هذا الحقل في قائمة. افتح السجل لتغييره.", + noFieldPermission: "ليس لديك إذن بتحرير هذا الحقل.", + viewOff: "التحرير في القائمة متوقف لهذا العرض.", + objectReadOnly: "لا يمكن تحرير هذه السجلات هنا.", + noPermission: "ليس لديك إذن بتحرير هذه السجلات.", + approvalLocked: "هذا السجل مقفل أثناء الموافقة عليه.", + noRecordPermission: "ليس لديك إذن بتحرير هذا السجل.", + }, bulkSelected: "تم تحديد {{count}}", bulkSelected_zero: "تم تحديد {{count}}", bulkSelected_one: "تم تحديد {{count}}", @@ -1066,7 +1079,6 @@ const ar = { draftOnlyQueryDropped: "لم تتم التصفية أو الفرز حسب {{fields}}: هذا الحقل موجود في المسودة فقط حتى النشر.", withheldFieldsLeftOut: "لا يتم العرض أو التصفية أو الفرز أو التجميع حسب {{fields}}: الحزمة التي تضيف هذا الحقل معطلة. سيعود عند تفعيل الحزمة.", inlineEditShort: "تحرير مضمّن", - inlineEditLabel: "حرّر السجلات مباشرة (انقر خلية للتحرير)", // The list's Options menu. optionsMenu: { viewName: 'اسم العرض', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index c945d69760f..7e475243da6 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -512,8 +512,21 @@ const de = { openRecord: "Datensatz öffnen", cancelChanges: "Änderungen verwerfen", saveRow: "Zeile speichern", + cellReadOnly: "Diese Zelle kann hier nicht bearbeitet werden.", }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: "Dieses Feld ist schreibgeschützt.", + computed: "Dieser Wert wird berechnet und kann nicht bearbeitet werden.", + notInline: "Dieses Feld kann in einer Liste nicht bearbeitet werden. Öffnen Sie den Datensatz, um es zu ändern.", + noFieldPermission: "Sie haben keine Berechtigung, dieses Feld zu bearbeiten.", + viewOff: "Das Bearbeiten in der Liste ist für diese Ansicht ausgeschaltet.", + objectReadOnly: "Diese Datensätze können hier nicht bearbeitet werden.", + noPermission: "Sie haben keine Berechtigung, diese Datensätze zu bearbeiten.", + approvalLocked: "Dieser Datensatz ist während der Genehmigung gesperrt.", + noRecordPermission: "Sie haben keine Berechtigung, diesen Datensatz zu bearbeiten.", + }, bulkSelected: "{{count}} ausgewählt", bulkSelected_one: "{{count}} ausgewählt", bulkSelected_other: "{{count}} ausgewählt", @@ -949,7 +962,6 @@ const de = { draftOnlyQueryDropped: "Nicht nach {{fields}} gefiltert oder sortiert: Das Feld existiert bis zur Veröffentlichung nur im Entwurf.", withheldFieldsLeftOut: "Nicht angezeigt, gefiltert, sortiert oder gruppiert nach {{fields}}: Das Paket, das das Feld hinzufügt, ist deaktiviert. Es kehrt zurück, sobald das Paket aktiviert wird.", inlineEditShort: "Inline bearbeiten", - inlineEditLabel: "Datensätze inline bearbeiten (Zelle anklicken zum Bearbeiten)", // The list's Options menu. optionsMenu: { viewName: 'Ansichtsname', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 35dcddd9092..aee17075106 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -775,8 +775,21 @@ const en = { openRecord: 'Open record', cancelChanges: 'Cancel changes', saveRow: 'Save row', + cellReadOnly: 'This cell can\'t be edited here.', }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: 'This field is read-only.', + computed: 'This value is calculated, so it can\'t be edited.', + notInline: 'This field can\'t be edited in a list. Open the record to change it.', + noFieldPermission: 'You don\'t have permission to edit this field.', + viewOff: 'Editing in the list is turned off for this view.', + objectReadOnly: 'These records can\'t be edited here.', + noPermission: 'You don\'t have permission to edit these records.', + approvalLocked: 'This record is locked while it\'s in approval.', + noRecordPermission: 'You don\'t have permission to edit this record.', + }, actions: 'Actions', edit: 'Edit', delete: 'Delete', @@ -1238,7 +1251,6 @@ const en = { draftOnlyQueryDropped: 'Not filtered or sorted by {{fields}}: it exists only in the draft until you publish.', withheldFieldsLeftOut: 'Not shown, filtered, sorted or grouped by {{fields}}: the package that adds it is disabled. It comes back when the package is enabled.', inlineEditShort: 'Edit inline', - inlineEditLabel: 'Edit records inline (click a cell to edit)', // The list's Options menu. optionsMenu: { viewName: 'View name', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 0148d9e0251..11068926dd5 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -523,8 +523,21 @@ const es = { openRecord: "Abrir registro", cancelChanges: "Descartar cambios", saveRow: "Guardar fila", + cellReadOnly: "Esta celda no se puede editar aquí.", }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: "Este campo es de solo lectura.", + computed: "Este valor se calcula, así que no se puede editar.", + notInline: "Este campo no se puede editar en una lista. Abra el registro para cambiarlo.", + noFieldPermission: "No tiene permiso para editar este campo.", + viewOff: "La edición en la lista está desactivada para esta vista.", + objectReadOnly: "Estos registros no se pueden editar aquí.", + noPermission: "No tiene permiso para editar estos registros.", + approvalLocked: "Este registro está bloqueado mientras está en aprobación.", + noRecordPermission: "No tiene permiso para editar este registro.", + }, bulkSelected: "{{count}} seleccionados", bulkSelected_one: "{{count}} seleccionado", bulkSelected_many: "{{count}} seleccionados", @@ -981,7 +994,6 @@ const es = { draftOnlyQueryDropped: "Sin filtrar ni ordenar por {{fields}}: solo existe en el borrador hasta que publiques.", withheldFieldsLeftOut: "Sin mostrar, filtrar, ordenar ni agrupar por {{fields}}: el paquete que lo añade está desactivado. Vuelve cuando se activa el paquete.", inlineEditShort: "Edición en línea", - inlineEditLabel: "Editar registros en línea (haga clic en una celda para editar)", // The list's Options menu. optionsMenu: { viewName: 'Nombre de la vista', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index a70f933c7b9..db1b965b7f6 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -518,8 +518,21 @@ const fr = { openRecord: "Ouvrir l'enregistrement", cancelChanges: "Annuler les modifications", saveRow: "Enregistrer la ligne", + cellReadOnly: "Cette cellule ne peut pas être modifiée ici.", }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: "Ce champ est en lecture seule.", + computed: "Cette valeur est calculée et ne peut pas être modifiée.", + notInline: "Ce champ ne peut pas être modifié dans une liste. Ouvrez l'enregistrement pour le changer.", + noFieldPermission: "Vous n'avez pas l'autorisation de modifier ce champ.", + viewOff: "La modification dans la liste est désactivée pour cette vue.", + objectReadOnly: "Ces enregistrements ne peuvent pas être modifiés ici.", + noPermission: "Vous n'avez pas l'autorisation de modifier ces enregistrements.", + approvalLocked: "Cet enregistrement est verrouillé pendant son approbation.", + noRecordPermission: "Vous n'avez pas l'autorisation de modifier cet enregistrement.", + }, bulkSelected: "{{count}} sélectionné(s)", bulkSelected_one: "{{count}} sélectionné", bulkSelected_many: "{{count}} sélectionnés", @@ -976,7 +989,6 @@ const fr = { draftOnlyQueryDropped: "Non filtré ni trié par {{fields}} : ce champ n’existe que dans le brouillon jusqu’à la publication.", withheldFieldsLeftOut: "Non affiché, filtré, trié ni groupé par {{fields}} : le paquet qui ajoute ce champ est désactivé. Il revient lorsque le paquet est réactivé.", inlineEditShort: "Édition en ligne", - inlineEditLabel: "Modifier les enregistrements en ligne (cliquez sur une cellule pour modifier)", // The list's Options menu. optionsMenu: { viewName: 'Nom de la vue', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 33304c0d610..0a0ccc50777 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -512,8 +512,21 @@ const ja = { openRecord: "レコードを開く", cancelChanges: "変更を取り消す", saveRow: "行を保存", + cellReadOnly: "このセルはここでは編集できません。", }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: "このフィールドは読み取り専用です。", + computed: "この値は計算で求められるため、編集できません。", + notInline: "このフィールドは一覧では編集できません。レコードを開いて変更してください。", + noFieldPermission: "このフィールドを編集する権限がありません。", + viewOff: "このビューでは一覧での編集がオフになっています。", + objectReadOnly: "これらのレコードはここでは編集できません。", + noPermission: "これらのレコードを編集する権限がありません。", + approvalLocked: "このレコードは承認中のためロックされています。", + noRecordPermission: "このレコードを編集する権限がありません。", + }, bulkSelected: "{{count}} 件を選択中", bulkSelected_one: "{{count}} 件を選択中", bulkSelected_other: "{{count}} 件を選択中", @@ -949,7 +962,6 @@ const ja = { draftOnlyQueryDropped: "{{fields}} での絞り込みと並べ替えは行われていません。下書きにのみ存在し、公開後に有効になります。", withheldFieldsLeftOut: "{{fields}} は表示、絞り込み、並べ替え、グループ化されていません。この項目を追加するパッケージが無効になっています。パッケージを有効にすると戻ります。", inlineEditShort: "インライン編集", - inlineEditLabel: "レコードをインラインで編集(セルをクリックして編集)", // The list's Options menu. optionsMenu: { viewName: 'ビュー名', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index c23d7f320da..a5207ab6157 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -512,8 +512,21 @@ const ko = { openRecord: "레코드 열기", cancelChanges: "변경 취소", saveRow: "행 저장", + cellReadOnly: "이 셀은 여기에서 편집할 수 없습니다.", }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: "이 필드는 읽기 전용입니다.", + computed: "이 값은 계산된 값이라 편집할 수 없습니다.", + notInline: "이 필드는 목록에서 편집할 수 없습니다. 레코드를 열어 변경하세요.", + noFieldPermission: "이 필드를 편집할 권한이 없습니다.", + viewOff: "이 보기에서는 목록 편집이 꺼져 있습니다.", + objectReadOnly: "이 레코드는 여기에서 편집할 수 없습니다.", + noPermission: "이 레코드를 편집할 권한이 없습니다.", + approvalLocked: "이 레코드는 승인 중이라 잠겨 있습니다.", + noRecordPermission: "이 레코드를 편집할 권한이 없습니다.", + }, bulkSelected: "{{count}}건 선택됨", bulkSelected_one: "{{count}}건 선택됨", bulkSelected_other: "{{count}}건 선택됨", @@ -949,7 +962,6 @@ const ko = { draftOnlyQueryDropped: "{{fields}} 기준 필터와 정렬이 적용되지 않았습니다. 초안에만 있으며 게시 후 적용됩니다.", withheldFieldsLeftOut: "{{fields}} 기준 표시, 필터, 정렬, 그룹화가 적용되지 않았습니다. 이 필드를 추가하는 패키지가 비활성화되어 있습니다. 패키지를 활성화하면 다시 나타납니다.", inlineEditShort: "인라인 편집", - inlineEditLabel: "레코드를 인라인으로 편집(셀을 클릭하여 편집)", // The list's Options menu. optionsMenu: { viewName: '보기 이름', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 1fa13b3e472..25aa7291384 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -518,8 +518,21 @@ const pt = { openRecord: "Abrir registro", cancelChanges: "Descartar alterações", saveRow: "Salvar linha", + cellReadOnly: "Esta célula não pode ser editada aqui.", }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: "Este campo é somente leitura.", + computed: "Este valor é calculado, então não pode ser editado.", + notInline: "Este campo não pode ser editado em uma lista. Abra o registro para alterá-lo.", + noFieldPermission: "Você não tem permissão para editar este campo.", + viewOff: "A edição na lista está desativada para esta visualização.", + objectReadOnly: "Estes registros não podem ser editados aqui.", + noPermission: "Você não tem permissão para editar estes registros.", + approvalLocked: "Este registro está bloqueado enquanto está em aprovação.", + noRecordPermission: "Você não tem permissão para editar este registro.", + }, bulkSelected: "{{count}} selecionados", bulkSelected_one: "{{count}} selecionado", bulkSelected_many: "{{count}} selecionados", @@ -976,7 +989,6 @@ const pt = { draftOnlyQueryDropped: "Sem filtrar nem ordenar por {{fields}}: existe apenas no rascunho até você publicar.", withheldFieldsLeftOut: "Sem exibir, filtrar, ordenar nem agrupar por {{fields}}: o pacote que o adiciona está desativado. Ele volta quando o pacote for ativado.", inlineEditShort: "Edição em linha", - inlineEditLabel: "Editar registros em linha (clique em uma célula para editar)", // The list's Options menu. optionsMenu: { viewName: 'Nome da visualização', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 88f078726f5..ffff969e412 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -527,8 +527,21 @@ const ru = { openRecord: "Открыть запись", cancelChanges: "Отменить изменения", saveRow: "Сохранить строку", + cellReadOnly: "Эту ячейку нельзя изменить здесь.", }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: "Это поле только для чтения.", + computed: "Это значение вычисляется, его нельзя изменить.", + notInline: "Это поле нельзя изменить в списке. Откройте запись, чтобы изменить его.", + noFieldPermission: "У вас нет прав на изменение этого поля.", + viewOff: "Редактирование в списке отключено для этого представления.", + objectReadOnly: "Эти записи нельзя изменить здесь.", + noPermission: "У вас нет прав на изменение этих записей.", + approvalLocked: "Эта запись заблокирована, пока находится на согласовании.", + noRecordPermission: "У вас нет прав на изменение этой записи.", + }, bulkSelected: "Выбрано: {{count}}", bulkSelected_one: "Выбрано: {{count}}", bulkSelected_few: "Выбрано: {{count}}", @@ -1009,7 +1022,6 @@ const ru = { draftOnlyQueryDropped: "Без фильтрации и сортировки по {{fields}}: поле есть только в черновике до публикации.", withheldFieldsLeftOut: "Не показано, без фильтрации, сортировки и группировки по {{fields}}: пакет, который добавляет это поле, отключён. Поле вернётся, когда пакет будет включён.", inlineEditShort: "Встроенное редактирование", - inlineEditLabel: "Редактировать записи в таблице (щёлкните ячейку для редактирования)", // The list's Options menu. optionsMenu: { viewName: 'Название представления', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index d8e916a5013..7eb6499ba31 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -525,8 +525,21 @@ const zh = { openRecord: '打开记录', cancelChanges: '取消更改', saveRow: '保存行', + cellReadOnly: '此单元格不能在这里编辑。', }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: '此字段为只读。', + computed: '此值由计算得出,不能编辑。', + notInline: '此字段不能在列表中编辑,请打开记录修改。', + noFieldPermission: '您没有编辑此字段的权限。', + viewOff: '此视图已关闭列表内编辑。', + objectReadOnly: '这些记录不能在这里编辑。', + noPermission: '您没有编辑这些记录的权限。', + approvalLocked: '此记录正在审批中,已锁定。', + noRecordPermission: '您没有编辑此记录的权限。', + }, actions: '操作', edit: '编辑', delete: '删除', @@ -976,7 +989,6 @@ const zh = { draftOnlyQueryDropped: '未按 {{fields}} 筛选或排序:它仅存在于草稿中,发布后才生效。', withheldFieldsLeftOut: '未显示 {{fields}},也未按其筛选、排序或分组:添加该字段的软件包已停用,启用后即恢复。', inlineEditShort: '行内编辑', - inlineEditLabel: '行内编辑记录(点击单元格进行编辑)', // The list's Options menu. optionsMenu: { viewName: '视图名称', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 66068ee941c..e5c2fa4b270 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -525,8 +525,21 @@ const zhHant = { openRecord: '開啟記錄', cancelChanges: '取消更改', saveRow: '儲存行', + cellReadOnly: '此儲存格不能在這裡編輯。', }, grid: { + // objectstack#35684 — why a list cell opens no editor, said on the cell. + readOnlyReason: { + readonly: '此欄位為唯讀。', + computed: '此值由計算得出,不能編輯。', + notInline: '此欄位不能在清單中編輯,請開啟記錄修改。', + noFieldPermission: '您沒有編輯此欄位的權限。', + viewOff: '此檢視已關閉清單內編輯。', + objectReadOnly: '這些記錄不能在這裡編輯。', + noPermission: '您沒有編輯這些記錄的權限。', + approvalLocked: '此記錄正在審批中,已鎖定。', + noRecordPermission: '您沒有編輯此記錄的權限。', + }, actions: '操作', edit: '編輯', delete: '刪除', @@ -976,7 +989,6 @@ const zhHant = { draftOnlyQueryDropped: '未按 {{fields}} 篩選或排序:它僅存在於草稿中,釋出後才生效。', withheldFieldsLeftOut: '未顯示 {{fields}},也未按其篩選、排序或分組:新增該欄位的軟體包已停用,啟用後即恢復。', inlineEditShort: '行內編輯', - inlineEditLabel: '行內編輯記錄(點選單元格進行編輯)', // The list's Options menu. optionsMenu: { viewName: '檢視名稱', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 0eae5abd24f..179b6156281 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -47,6 +47,7 @@ import { useLocalization, useDisplayLocale } from '@object-ui/i18n'; // to reach them as an object and the compiler could not say so. import { resolveI18nLabel as resolveInlineI18nLabel } from '@objectstack/spec/ui'; import { stateMachineNextValues } from './inline-edit-options'; +import { cellReadOnlyKind, readOnlyReasonText, inlineTyping, choiceFromText } from './objectGridCellFacts'; import { Badge, Button, NavigationOverlay, EmptyValue, legacyRecordDrawerWidthKey, recordOverlayWidthStorageKey, @@ -57,8 +58,10 @@ import { HorizontalOverflowBox, toast, cn, + GridCellSelectionProvider, + type GridCellSelection, } from '@object-ui/components'; -import { resolveConditionalFormatting, declaredNameField, buildExportFileName, resolveAffordance, type SchemaLike, isExpandableFieldType, isUnmaterializedFieldType, readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, filterRefusalSubject, FilterOperatorError, resolveRecordSourceConfig, resolveRecordSourceObjectName, partitionRowsByPredicate, csvBlob, readActionPayload } from '@object-ui/core'; +import { resolveConditionalFormatting, declaredNameField, buildExportFileName, resolveAffordance, resolveFieldAffordance, type SchemaLike, isExpandableFieldType, isUnmaterializedFieldType, readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, filterRefusalSubject, FilterOperatorError, resolveRecordSourceConfig, resolveRecordSourceObjectName, partitionRowsByPredicate, csvBlob, readActionPayload } from '@object-ui/core'; import { usePermissions } from '@object-ui/permissions'; import { RECORD_OVERLAY_DEFAULT_WIDTH, @@ -73,6 +76,7 @@ import { useRowColor } from './useRowColor'; import { GroupRow } from './GroupRow'; import { resolveRowCrudAffordances, resolveRowRecordCrudAffordance } from './rowCrudAffordances'; import { useRecordCrudVerdicts } from './hooks/useRecordCrudVerdicts'; +import { useRowApprovalLocks } from './hooks/useRowApprovalLocks'; import { resolveLegacyRowActions } from './resolveLegacyRowActions'; import { resolveBulkActions, resolvePromotedBulkParams } from './resolveBulkActions'; import { useUndeclaredActionNamesWarning } from './undeclaredActionNames'; @@ -334,6 +338,18 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr * key reaches it. */ rowOpensRecord?: boolean; + /** + * [objectstack#35684] The select-first cell model, as the HOST that owns + * the page asks for it (the list page does). `true` ⇒ a click selects a + * cell and never edits it or opens the record; double-click, Enter, F2 or + * typing edits; Space opens the record; a cell that opens no editor says + * why (`describeCell`, `./objectGridCellFacts`). Absent ⇒ the table keeps + * its click-to-edit / click-to-open behaviour, as before this prop existed. + * + * A RUNTIME prop, never authored metadata: the host decides it, and no node + * key reaches it. + */ + cellSelection?: boolean; /** * TWO parameters since objectui#9357, and the second is not decoration: this * prop reaches `useNavigationOverlay` as its `onRowClick`, and `handleClick` @@ -695,6 +711,7 @@ export const ObjectGrid: React.FC = ({ rowAdornment, recordLinkAdornment, rowOpensRecord, + cellSelection: hostCellSelection, onBulkDelete, onRowSelect, onRowClick, @@ -1132,6 +1149,39 @@ export const ObjectGrid: React.FC = ({ updateOnMount: inlineEditable, }); + // objectstack#35684 — what the select-first table asks about a cell when + // the reader acts on it: why it opens no editor (the field, the grid, the + // object, an approval lock, the record — `cellReadOnlyKind`), what typing + // does there and what pasted text stands for. `null` without the host's + // ask, so every other grid keeps the table it had. + const approvalLocks = useRowApprovalLocks(hostCellSelection ? objectName : undefined); + const gridCellSelection: GridCellSelection | null = hostCellSelection + ? { + describeCell: (row, columnKey) => { + const fieldDef = objectFields?.[columnKey]; + const recordId = rowRecordId(row); + const kind = cellReadOnlyKind({ + fieldDef, + fieldWritable: !objectName || resolveFieldAffordance('listInlineEdit', perms, objectName, columnKey), + gridEditable: schema.editable ?? false, + objectEditable: objectInlineEditable, + canUpdate: !objectName || perms.can(objectName, 'update'), + approvalLocked: approvalLocks.isLocked(recordId, row), + recordUpdate: recordVerdict(recordId, 'update'), + }); + const fromText = choiceFromText(fieldDef); + const type = fieldDef?.type; + return { + readOnlyReason: kind ? readOnlyReasonText(kind, t) : null, + typing: inlineTyping(type), + ...(type === 'boolean' || type === 'toggle' ? { toggles: true } : {}), + ...(fromText ? { fromText } : {}), + }; + }, + onCellSelect: (row) => approvalLocks.probe(rowRecordId(row)), + } + : null; + // The projection keys and the filter, sort, search and server-paging state, // read here in hook order (`./objectGridQueryInputs`). const { @@ -4242,7 +4292,7 @@ export const ObjectGrid: React.FC = ({ {gridDescription} {groupingDraftOnlyNote} {gridToolbar} - {renderedGridContent} + {renderedGridContent} {isGrouped && onRowGroupsChange && ( )} diff --git a/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts b/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts new file mode 100644 index 00000000000..d0457018be4 --- /dev/null +++ b/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts @@ -0,0 +1,88 @@ +/** + * 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. + */ + +/** + * Is THIS row held by an approval that locks it? (objectstack#35684) + * + * The record-grained `update` verdict a list reads (`useRecordCrudVerdicts`, + * the explain engine) does not see approvals: the lock is the approvals + * plugin's own `beforeUpdate` hook. So a cell asks the approvals service's + * per-record answer (`GET /api/v1/approvals/records/:object/:recordId/lock`) + * when the reader selects a cell of the row: one read for a row the reader + * touches, never one for every row on screen. The answer is read through + * `resolveApprovalLock`, the record page's one rule, so a list and a record + * page cannot disagree about a lock; while no read has answered, the row's + * `approval_status` column stands in, as it does there. + * + * Fail open: a read in flight, refused or failing leaves the column fallback, + * and the server refuses a locked write whatever this says. A 501 (no + * approvals service in this deployment) is latched and the read is not sent + * again, like the record page's. + */ +import * as React from 'react'; +import { SchemaRendererContext, resolveApprovalLock, useDataInvalidation } from '@object-ui/react'; + +/** Set once a lock read answered 501: the deployment runs no approvals service. */ +let approvalsServiceAbsent = false; + +type LockAnswer = { locked: boolean } | 'asking' | 'unanswered'; + +export interface RowApprovalLocks { + /** Ask the lock of a row's record, unless it has been asked (the cell-select prefetch). */ + probe: (recordId: unknown) => void; + /** Whether the row is locked by an approval, from what has answered so far. */ + isLocked: (recordId: unknown, row: any) => boolean; +} + +export function useRowApprovalLocks(objectName: string | undefined): RowApprovalLocks { + const apiFetch = React.useContext(SchemaRendererContext)?.apiFetch; + // A change to the object (a submit, a recall, a decision) drops every answer. + const invalidation = useDataInvalidation(objectName); + const answersRef = React.useRef(new Map()); + React.useEffect(() => { + answersRef.current = new Map(); + }, [objectName, invalidation]); + + const probe = React.useCallback((recordId: unknown) => { + if (!objectName || recordId == null || recordId === '' || approvalsServiceAbsent) return; + const id = String(recordId); + const answers = answersRef.current; + if (answers.has(id)) return; + answers.set(id, 'asking'); + const doFetch = apiFetch ?? fetch; + const path = `/api/v1/approvals/records/${encodeURIComponent(objectName)}/${encodeURIComponent(id)}/lock`; + void (async () => { + try { + const res = await doFetch(path, { credentials: 'include' }); + if (res.status === 501) approvalsServiceAbsent = true; + if (!res.ok) { + answers.set(id, 'unanswered'); + return; + } + const body: any = await res.json(); + // `{ success: true, data: { locked } }`, the declared envelope. + const data = body && typeof body.success === 'boolean' && 'data' in body ? body.data : body; + answers.set(id, { locked: data?.locked === true }); + } catch { + answers.set(id, 'unanswered'); + } + })(); + }, [objectName, apiFetch]); + + const isLocked = React.useCallback((recordId: unknown, row: any) => { + const answer = recordId == null ? undefined : answersRef.current.get(String(recordId)); + const readAnswered = typeof answer === 'object'; + return resolveApprovalLock({ + readAnswered, + openApproval: readAnswered && answer.locked ? { locked: true } : null, + recordStatus: row?.approval_status, + }).locked; + }, []); + + return React.useMemo(() => ({ probe, isLocked }), [probe, isLocked]); +} diff --git a/ui/packages/plugin-grid/src/inline-edit-options.ts b/ui/packages/plugin-grid/src/inline-edit-options.ts index e5ce96cd7b6..8ba0887eab0 100644 --- a/ui/packages/plugin-grid/src/inline-edit-options.ts +++ b/ui/packages/plugin-grid/src/inline-edit-options.ts @@ -37,13 +37,32 @@ export { stateMachineNextValues } from '@object-ui/core'; * that, a `composite` cell degraded to a plain text editor, a * value-corruption path. */ +const COMPUTED_FIELD_TYPES = new Set(['formula', 'summary', 'rollup', 'autonumber', 'auto_number']); const NON_EDITABLE_FIELD_TYPES = new Set([ // computed / system-generated - 'formula', 'summary', 'rollup', 'autonumber', 'auto_number', + ...COMPUTED_FIELD_TYPES, // binary / attachment 'file', 'image', 'avatar', 'video', 'audio', 'signature', ]); +/** + * Why a field is not edited in place (objectstack#35684), or `null` when it + * is: `readonly` (declared so), `computed` (an expression, a formula, a + * summary, an auto number) or `notInline` (a file, or a type the fields + * package keeps out of a cell). The reasons {@link isFieldInlineEditable} + * answers `false` for, told apart so a cell can say which. + */ +export function fieldInlineReadOnlyKind( + fieldDef: { type?: unknown; readonly?: unknown } | null | undefined, +): 'readonly' | 'computed' | 'notInline' | null { + if (!fieldDef) return null; + if (fieldDef.readonly === true) return 'readonly'; + if (isExpressionComputedField(fieldDef)) return 'computed'; + if (typeof fieldDef.type !== 'string') return null; + if (COMPUTED_FIELD_TYPES.has(fieldDef.type)) return 'computed'; + return NON_EDITABLE_FIELD_TYPES.has(fieldDef.type) || isInlineExcludedFieldType(fieldDef.type) ? 'notInline' : null; +} + /** * Whether a field may be edited in place in the grid. False for explicitly * `readonly` fields, for inherently computed / binary types (see @@ -59,9 +78,5 @@ const NON_EDITABLE_FIELD_TYPES = new Set([ export function isFieldInlineEditable( fieldDef: { type?: unknown; readonly?: unknown } | null | undefined, ): boolean { - if (!fieldDef) return true; - if (fieldDef.readonly === true) return false; - if (isExpressionComputedField(fieldDef)) return false; - if (typeof fieldDef.type !== 'string') return true; - return !NON_EDITABLE_FIELD_TYPES.has(fieldDef.type) && !isInlineExcludedFieldType(fieldDef.type); + return fieldInlineReadOnlyKind(fieldDef) === null; } diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts.ts b/ui/packages/plugin-grid/src/objectGridCellFacts.ts new file mode 100644 index 00000000000..b80afebc820 --- /dev/null +++ b/ui/packages/plugin-grid/src/objectGridCellFacts.ts @@ -0,0 +1,127 @@ +/** + * 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. + */ + +/** + * What `ObjectGrid` tells the select-first table about a cell + * (objectstack#35684, objectstack#35687): why it opens no editor, what typing + * on it does, and what pasted text stands for. The table asks when the reader + * acts on a cell, never while it draws. + */ +import { fieldInlineReadOnlyKind } from './inline-edit-options'; + +/** Why a cell opens no editor, in the order a cell names them. */ +export type CellReadOnlyKind = + | 'readonly' + | 'computed' + | 'notInline' + | 'noFieldPermission' + | 'viewOff' + | 'objectReadOnly' + | 'noPermission' + | 'approvalLocked' + | 'noRecordPermission'; + +/** The sentence a cell shows for a reason, in the reader's language. */ +export function readOnlyReasonText(kind: CellReadOnlyKind, t: (key: string) => string): string { + switch (kind) { + case 'readonly': return t('grid.readOnlyReason.readonly'); + case 'computed': return t('grid.readOnlyReason.computed'); + case 'notInline': return t('grid.readOnlyReason.notInline'); + case 'noFieldPermission': return t('grid.readOnlyReason.noFieldPermission'); + case 'viewOff': return t('grid.readOnlyReason.viewOff'); + case 'objectReadOnly': return t('grid.readOnlyReason.objectReadOnly'); + case 'noPermission': return t('grid.readOnlyReason.noPermission'); + case 'approvalLocked': return t('grid.readOnlyReason.approvalLocked'); + case 'noRecordPermission': return t('grid.readOnlyReason.noRecordPermission'); + } +} + +/** The grid-wide and row answers a cell's reason is read from. */ +export interface CellReadOnlyInputs { + /** The object's field definition for the column, when it has one. */ + fieldDef: { type?: unknown; readonly?: unknown } | null | undefined; + /** May this reader write the field (`resolveFieldAffordance('listInlineEdit', …)`)? */ + fieldWritable: boolean; + /** The authored `editable` the grid was handed (the list page folds `userActions.editInline` into it). */ + gridEditable: boolean; + /** The object's own answer: lifecycle bucket, `userActions.edit` and the API operation set. */ + objectEditable: boolean; + /** The reader's `update` grant on the object. */ + canUpdate: boolean; + /** The record is held by an approval that locks it. */ + approvalLocked: boolean; + /** The server's record-grained `update` verdict for this row; `undefined` while unknown. */ + recordUpdate: boolean | undefined; +} + +/** + * Why this cell opens no editor, or `null` when it opens one. A field's own + * reason comes first (it holds on every row and in every view), then the + * grid's, then the record's. + */ +export function cellReadOnlyKind(inputs: CellReadOnlyInputs): CellReadOnlyKind | null { + const fieldKind = fieldInlineReadOnlyKind(inputs.fieldDef); + if (fieldKind) return fieldKind; + if (!inputs.fieldWritable) return 'noFieldPermission'; + if (!inputs.canUpdate) return 'noPermission'; + if (!inputs.objectEditable) return 'objectReadOnly'; + if (!inputs.gridEditable) return 'viewOff'; + if (inputs.approvalLocked) return 'approvalLocked'; + if (inputs.recordUpdate === false) return 'noRecordPermission'; + return null; +} + +/** Field types a typed key writes into: the text replaces the value. */ +const TYPED_FIELD_TYPES: ReadonlySet = new Set([ + 'text', 'textarea', 'email', 'url', 'phone', 'number', 'currency', 'percent', +]); + +/** What typing on a cell of this field type does; `undefined` leaves it to the table. */ +export function inlineTyping(fieldType: unknown): 'replace' | 'open' | undefined { + if (typeof fieldType !== 'string') return undefined; + return TYPED_FIELD_TYPES.has(fieldType) ? 'replace' : 'open'; +} + +const CHOICE_FIELD_TYPES: ReadonlySet = new Set(['select', 'radio']); +const MULTI_CHOICE_FIELD_TYPES: ReadonlySet = new Set(['multiselect', 'checkboxes', 'tags']); + +/** The declared option a pasted word names, by value or by label, ignoring case. */ +function optionOf(options: unknown, word: string): unknown { + if (!Array.isArray(options)) return undefined; + const wanted = word.trim().toLowerCase(); + if (wanted === '') return undefined; + for (const option of options) { + const value = option !== null && typeof option === 'object' ? (option as any).value : option; + const label = option !== null && typeof option === 'object' ? (option as any).label : option; + if (String(value).toLowerCase() === wanted || (typeof label === 'string' && label.toLowerCase() === wanted)) return value; + } + return undefined; +} + +/** + * The value pasted text stands for in a choice field: the option it names + * (for a multi-choice field, every option of a comma-separated list), or + * `undefined` when it names none, so nothing is written. `null` for a type + * this answers nothing about: the table's own reading of the column applies. + */ +export function choiceFromText( + fieldDef: { type?: unknown; options?: unknown } | null | undefined, +): ((text: string) => unknown) | null { + const type = typeof fieldDef?.type === 'string' ? fieldDef.type : ''; + if (CHOICE_FIELD_TYPES.has(type)) return (text) => optionOf(fieldDef!.options, text.replace(/\r?\n$/, '')); + if (MULTI_CHOICE_FIELD_TYPES.has(type)) { + return (text) => { + const words = text.split(/[,;\n]/).map((w) => w.trim()).filter(Boolean); + const values = words.map((w) => optionOf(fieldDef!.options, w)); + return words.length > 0 && values.every((v) => v !== undefined) ? values : undefined; + }; + } + // A record reference holds an id, which pasted text is not. + if (type === 'lookup' || type === 'master_detail' || type === 'user' || type === 'owner') return () => undefined; + return null; +} diff --git a/ui/packages/plugin-grid/src/objectGridTranslations.ts b/ui/packages/plugin-grid/src/objectGridTranslations.ts index ed61028f715..ecb48bb1b71 100644 --- a/ui/packages/plugin-grid/src/objectGridTranslations.ts +++ b/ui/packages/plugin-grid/src/objectGridTranslations.ts @@ -102,6 +102,16 @@ const GRID_DEFAULT_TRANSLATIONS: Record = { 'detail.recordDetailWithLabel': '{{label}} Detail', // objectstack#35548 — the summary row's lead, under the first column. 'grid.summary.countLead': 'Count {{value}}', + // objectstack#35684 — why a list cell opens no editor (`objectGridCellFacts`). + 'grid.readOnlyReason.readonly': 'This field is read-only.', + 'grid.readOnlyReason.computed': 'This value is calculated, so it can\'t be edited.', + 'grid.readOnlyReason.notInline': 'This field can\'t be edited in a list. Open the record to change it.', + 'grid.readOnlyReason.noFieldPermission': 'You don\'t have permission to edit this field.', + 'grid.readOnlyReason.viewOff': 'Editing in the list is turned off for this view.', + 'grid.readOnlyReason.objectReadOnly': 'These records can\'t be edited here.', + 'grid.readOnlyReason.noPermission': 'You don\'t have permission to edit these records.', + 'grid.readOnlyReason.approvalLocked': 'This record is locked while it\'s in approval.', + 'grid.readOnlyReason.noRecordPermission': 'You don\'t have permission to edit this record.', }; /** diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index c55f1729a25..a5fd7bc3c9d 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -9,7 +9,7 @@ import * as React from 'react'; import { cn, Button, Input, Popover, PopoverContent, PopoverTrigger, FilterBuilder, SortBuilder, NavigationOverlay, GroupingEditor, RefreshIndicator, DataErrorState, resolveIcon, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@object-ui/components'; import type { SortItem } from '@object-ui/components'; -import { Search, Funnel, ArrowUpDown, X, EyeOff, Pencil, Group, Paintbrush, Download, Rows4, Rows3, Rows2, Lock, Printer, Plus, Trash2, CheckSquare, AlertTriangle, ShieldAlert, RotateCw, Loader2, Info, Inbox } from 'lucide-react'; +import { Search, Funnel, ArrowUpDown, X, EyeOff, Group, Paintbrush, Download, Rows4, Rows3, Rows2, Lock, Printer, Plus, Trash2, CheckSquare, AlertTriangle, ShieldAlert, RotateCw, Loader2, Info, Inbox } from 'lucide-react'; import type { FilterBuilderRowGroup } from '@object-ui/components'; import { VALUELESS_FILTER_BUILDER_OPERATORS, isFilterValueComplete, isCurrencyCompanion } from '@object-ui/components'; import { ViewSwitcherDropdown } from './ViewSwitcher'; @@ -380,11 +380,9 @@ export interface ListViewProps { */ onAddedFieldsChange?: (added: string[]) => void; /** - * Called when the user toggles inline record editing. Wiring it is also what - * offers the wide toolbar's toggle. The toggle switches the grid's edit MODE, - * which `ListView` keeps in its own state. A host should not persist it into - * the view's `inlineEdit`: that key is the author's permission, and it folds - * into `userActions.editInline` (objectui#5144). + * @deprecated Never called since objectstack#35684: a list has no inline-edit + * mode and no toggle. Its grid is editable wherever the reader may edit and + * the view does not declare `userActions.editInline: false`. */ onInlineEditChange?: (next: boolean) => void; /** Called when the user resizes/reorders columns in the underlying grid. */ @@ -572,10 +570,11 @@ export interface ListViewProps { * search (the Filter panel's finished conditions, the user-filter chips, the * "In a queue" toggle; the view's declared `filter` is never one); `search` * is a term the list applies. The Display-only settings (`layout`, - * `rowColor`, `rowNumbers`, `inlineEdit`) are those the Display control - * counts. The gallery card size is not a part: it is kept per object, not - * per view. `columns` is never reported here, since the column layout is - * the host's own stored state; it is in the type so a host can add it. + * `rowColor`, `rowNumbers`) are those the Display control counts. The + * gallery card size is not a part: it is kept per object, not per view. + * `columns` is never reported here, since the column layout is the host's + * own stored state; it is in the type so a host can add it. Nor is + * `inlineEdit` since objectstack#35684, which retired the mode it named. * * When it is passed the host owns the reset, so the Display control draws * no "Reset to view default" of its own. The sort popover's reset and the @@ -2106,7 +2105,6 @@ export const ListView = React.forwardRef(({ onHiddenFieldsChange, addedFields, onAddedFieldsChange, - onInlineEditChange, onColumnStateChange, onRowClick, showViewSwitcher: showViewSwitcherProp, @@ -3023,25 +3021,6 @@ export const ListView = React.forwardRef(({ ); const [showHideFields, setShowHideFields] = React.useState(false); - // Inline-edit MODE: session state, seeded from the view's `inlineEdit` on each - // load (objectui#5144, ruling E). The toolbar toggle flips it here and reports - // it through `onInlineEditChange`. The console writes nothing back, because - // `inlineEdit` is the author's permission key, so the mode is not remembered - // across loads. Whether the toggle is offered at all is `inlineEditOffered` - // below. - const [inlineEdit, setInlineEdit] = React.useState(() => !!schema.inlineEdit); - React.useEffect(() => { - setInlineEdit(!!schema.inlineEdit); - }, [schema.inlineEdit]); - // Setter that also notifies the host. - const updateInlineEdit = React.useCallback( - (next: boolean) => { - setInlineEdit(next); - onInlineEditChange?.(next); - }, - [onInlineEditChange] - ); - // Row numbers on the grid's leading cell — the Display control's switch // (objectui#12423). Session-only and in memory: nothing stores it, and it // opens on the host's `defaultRowNumbers` (on unless a host says otherwise) @@ -3221,70 +3200,26 @@ export const ListView = React.forwardRef(({ ); /** - * [#4647] Is the grid toolbar's inline-edit toggle offered at all? - * - * Two gaps closed together, because both end at this one render condition. - * - * ## Gap 1 — the permission gate - * - * The toggle used to render on the sole conditions "grid view", "the host - * wired `onInlineEditChange`" and "not the compact toolbar" — and every host - * passes that callback unconditionally. It was the ONE affordance on this - * toolbar with no permission check: New and Import are hidden for an account - * without the grant, the bulk-delete entry directly above ANDs - * `can(obj, 'delete')`, and inline edit alone stayed available to a read-only - * principal, who could flip it, edit cells and press "Save all" to earn a - * server 403. No data ever landed (the server gate is solid), but the UI - * walked the user through a round-trip guaranteed to fail. - * - * The gate is `permittedBulkActions`' verbatim, with the operation moved from - * `delete` to `update`: the object's resolved affordance — ADR-0103 bucket ∧ - * `userActions.edit` ∧ the server's effective API operations (objectstack#3391) — AND - * the CURRENT PRINCIPAL's grant (#4096). The first half is spelled - * `isObjectInlineEditable`, which IS - * `resolveEffectiveCrudAffordances(...).edit` under the name that says what - * this surface is asking; it is the same helper the record body's - * double-click/pencil affordances read, so a list and a record page cannot - * disagree about whether an object's rows are editable in place. - * - * `can()` answers `true` with no `PermissionProvider`, so standalone embeds - * and the Studio designer keep today's behavior — the same fail-open the - * bulk gate above relies on. - * - * ## Gap 2 — the declared `userActions.editInline`, with the spec's default - * - * `ListViewSchema.userActions.editInline` defaults to `true`: a list view is - * editable in place by default, under the gate above, and - * `editInline: false` is the opt-out (the maintainer's v18 ruling, - * objectstack#22605, which flipped the earlier `.default(false)`). It is read - * here with that default (`!== false`), so a view that declares nothing is - * offered inline editing wherever the gate admits the principal. The ADR-0047 - * interface page reads the same default. + * Is the grid editable in place? (objectstack#35684: there is no mode and no + * toggle; the grid IS editable wherever this says so, and a click selects a + * cell rather than editing it.) * - * A view's `inlineEdit` reaches this read through the fold, not around it - * (objectui#5144). `normalizeListViewSchema` folds a boolean `inlineEdit` - * into `userActions.editInline` when the view declares no `editInline` of its - * own. So: - * - a view with `inlineEdit: true` offers the toggle; - * - a view with `inlineEdit: false` reads off; - * - an explicit `editInline` wins over `inlineEdit`, either way; - * - a view with neither key offers the toggle and opens out of edit mode. + * [#4647] The permission gate: the object's resolved affordance — ADR-0103 + * bucket ∧ `userActions.edit` ∧ the server's effective API operations + * (objectstack#3391) — AND the current principal's grant (#4096), the + * `listInlineEdit` row of the affordance-to-grant map, the same question the + * record body's in-place editing asks. `can()` answers `true` with no + * `PermissionProvider`, so standalone embeds and the Studio designer keep + * their behavior. * - * Both keys are the author's permission. This gate decides whether the toggle - * is offered. Whether the grid is in edit mode is the `inlineEdit` state above: - * session state, seeded from the view's `inlineEdit` on each load, and flipped - * by the toggle. The console no longer persists the toggle into the view - * (objectui#5144, ruling E). That write made the toggle one-way, because - * switching it off stored `inlineEdit: false`, which this gate then read as - * "not offered". A view with `editInline: true` and no `inlineEdit` offers the - * toggle and opens out of edit mode, the same as a view with neither key. - * - * ⚠️ A list that is read-only by nature declares - * `userActions.editInline: false`. Two costs are recorded with the - * objectui#5144 ruling. The edit mode is not remembered across loads. A view - * or overlay that already stores `inlineEdit: false`, written by the old - * toggle, still reads off; that is existing data, it is not migrated, and - * declaring `userActions.editInline: true` brings the toggle back. + * The view's opt-out: `ListViewSchema.userActions.editInline` defaults to + * `true` (objectstack#22605), read here with that default (`!== false`), and + * `editInline: false` turns editing off for the view. A view's boolean + * `inlineEdit` reaches this read through the fold (objectui#5144): + * `normalizeListViewSchema` folds it into `userActions.editInline` when the + * view declares no `editInline` of its own, so a view or overlay that stores + * `inlineEdit: false` (written by the console's old toggle) reads off, and + * `userActions.editInline: true` turns it back on. */ const inlineEditOffered = React.useMemo(() => { if ((schema.userActions as Record | undefined)?.editInline === false) { @@ -3299,10 +3234,9 @@ export const ListView = React.forwardRef(({ * Whether the rows this list fetches must carry their concurrency token * (objectui#12292): exactly when the grid it hands them to is editable in * place — the same expression as that grid's `editable` below. The grid's - * save sends each row's `updated_at` as `If-Match`, so the fetch projects it; - * turning the mode on re-reads the rows with it. + * save sends each row's `updated_at` as `If-Match`, so the fetch projects it. */ - const rowsCarryConcurrencyToken = inlineEdit && inlineEditOffered; + const rowsCarryConcurrencyToken = inlineEditOffered; // Normalize exportOptions: support both ObjectUI object format and spec string[] format const resolvedExportOptions = React.useMemo(() => { @@ -5182,14 +5116,10 @@ export const ListView = React.forwardRef(({ ? { columns: effectiveFields } : { fields: undefined, columns: undefined }), ...(schema.conditionalFormatting ? { conditionalFormatting: schema.conditionalFormatting } : {}), - // [#4647] The MODE, not just its toggle. Gating only the toggle would - // leave the issue's own consequence reachable by a different door: a - // stored view carrying `inlineEdit: true` (authored, or left by the - // console's old toggle) drops a read-only principal straight into editable cells - // with no toggle to press, and "Save all" still earns the 403. The - // toggle can only ever be the cheapest entrance to this state; the - // state is what needs the grant. - editable: inlineEdit && inlineEditOffered, + // [#4647] Editable exactly where the reader may edit and the view + // does not opt out (`inlineEditOffered`); objectstack#35684 retired + // the mode that used to gate this as well. + editable: inlineEditOffered, ...(schema.wrapHeaders != null ? { wrapHeaders: schema.wrapHeaders } : {}), ...(schema.resizable != null ? { resizable: schema.resizable } : {}), ...(schema.selection ? { selection: schema.selection } : {}), @@ -5758,7 +5688,7 @@ export const ListView = React.forwardRef(({ // asynchronously (`/me/permissions`) and `objectDef` loads into state, so a // grid schema built before either resolved must be rebuilt when they do — // otherwise `editable` keeps the pre-verdict answer for the session. - }, [currentView, schema, authoredFilter, serverSort, searchFieldsSent, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEdit, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged]); + }, [currentView, schema, authoredFilter, serverSort, searchFieldsSent, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged]); // The count the toolbar shows: a record-mode amount's code condition is // part of its amount row (objectstack#27188), not a filter of its own, and a @@ -6517,7 +6447,6 @@ export const ListView = React.forwardRef(({ ? galleryCardSize !== authoredGalleryCardSize : density.mode !== viewDefaultDensity), rowNumbers: currentView === 'grid' && rowNumbers !== defaultRowNumbers, - inlineEdit: currentView === 'grid' && inlineEditOffered && inlineEdit !== !!schema.inlineEdit, }; const displayChangedCount = Object.values(displayDeviation).filter(Boolean).length; @@ -6553,7 +6482,6 @@ export const ListView = React.forwardRef(({ if (displayDeviation.layout) personalizationParts.push('layout'); if (displayDeviation.color) personalizationParts.push('rowColor'); if (displayDeviation.rowNumbers) personalizationParts.push('rowNumbers'); - if (displayDeviation.inlineEdit) personalizationParts.push('inlineEdit'); const personalizationKey = personalizationParts.join(','); const onPersonalizationChangeRef = React.useRef(onPersonalizationChange); React.useEffect(() => { @@ -6593,7 +6521,6 @@ export const ListView = React.forwardRef(({ } } if (displayDeviation.rowNumbers) setRowNumbers(defaultRowNumbers); - if (displayDeviation.inlineEdit) updateInlineEdit(!!schema.inlineEdit); if (onRestoreViewDefaults && restoredParts.length > 0) onRestoreViewDefaults(restoredParts); }; @@ -7052,30 +6979,6 @@ export const ListView = React.forwardRef(({
)} - {/* Inline edit — toggle record editing for this (grid) view, for the - session (objectui#5144, ruling E). Reported via onInlineEditChange. - [#4647] `inlineEditOffered` carries BOTH the `can(obj,'update')` - permission gate this affordance was missing and the declared - `userActions.editInline` switch — see its definition above. */} - {currentView === 'grid' && onInlineEditChange && !toolbarFlags.compactToolbar && inlineEditOffered && ( - - )} {/* Hide Fields — hidden on mobile (collapsed into ViewSettingsPopover) */} {toolbarFlags.showHideFields && !toolbarFlags.compactToolbar && ( @@ -7474,15 +7377,6 @@ export const ListView = React.forwardRef(({ onAddField={addListedField} rowNumbers={rowNumbers} setRowNumbers={currentView === 'grid' ? setRowNumbers : undefined} - /* [#4647] The Display panel's inline-edit entry — the SECOND - render site for this affordance, and the one with no gate at - all: it never even required `onInlineEditChange`. Same - `inlineEditOffered` verdict as the wide toolbar's toggle, or a - read-only principal would keep the entry here after losing it - there. */ - showInlineEdit={currentView === 'grid' && inlineEditOffered} - inlineEdit={inlineEdit} - setInlineEdit={updateInlineEdit} changedCount={displayChangedCount} // objectstack#35551 — the view's name and its rename head the // menu; the field order is the grid's column order, the state @@ -8162,6 +8056,12 @@ export const ListView = React.forwardRef(({ // link, on the grid's host channel (a React prop, never a node key). ? { recordLinkAdornment } : {})} + {...(viewComponentSchema.type === 'object-grid' + // objectstack#35684 — the list page's grid selects a cell on a + // click and edits on double-click, Enter or typing, on the + // grid's host channel (a React prop, never a node key). + ? { cellSelection: true } + : {})} {...(ROW_OPENS_RECORD_VIEW_TYPES.has(viewComponentSchema.type) && rowOpensRecord !== undefined // objectstack#33317, objectstack#33548 — whether the host's row // click opens anything, on the view's host channel (a React From 8b9121eb23b768b0ec9baddec24758eadf1a589b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 01:38:56 +0000 Subject: [PATCH 03/17] wip(docs): leave records-forms list-view item to #35706's revision bump Claude-Session: https://claude.ai/code/session_01L6bhgTC8kn7AdeMpMmyhJG Co-authored-by: Claude --- docs/qa/platform-checklist/areas/records-forms.json | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 46e49ee8aff..53285359f79 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -615,7 +615,7 @@ "title": "List-view capability matrix: filter, search, sort, pagination, saved views, inline edit, export, visualization switcher, bulk/row actions, conditional formatting", "since": "v15", "status": "active", - "revision": 12, + "revision": 11, "priority": "P1", "surface": "browser", "personas": [ @@ -650,7 +650,7 @@ "quick-search 'huaning' on Accounts (or '张' on Contacts); capture the `search` request and the hits (pinyin + CJK recall, ADR-0061)", "open the tabular saved view (sort [{field: 'estimate_hours', order: 'desc'}] — the array form: #17053 retired the bare string clause 'estimate_hours desc' platform-wide, so the objectui#2601 string-crash fixture no longer exists on stock); confirm it renders and the request carries the sort as sort=-estimate_hours", "load a list past its first window. No stock list holds more rows than the 50-row window (the largest seeded task and contact lists are under it), so stage one first: POST /api/v1/data/showcase_inquiry/createMany with a bare JSON array of 55 rows (name + email + message each — showcase_inquiry requires `message` too, and a name + email body answers 400 \"Message is required\", QA run #24616). A list view that declares no `pagination` (the stock Inquiries list) draws NO pager since #35554: it loads as it scrolls, so scroll the Inquiries list to its end and capture `top`/`skip` on every data request (top=50, then top=50&skip=50); the count beside the view name reads the server total. Then page a view that DECLARES `pagination` (stage one: PUT a view with pagination: {pageSize: 50} on showcase_inquiry) past page 1 and capture the same; confirm no unpaged full fetch on either", - "in the grid saved view, double-click one cell (a single click only selects it, #35684), edit it in place; save; capture the PATCH; re-read the row via API", + "in the grid saved view (inlineEdit: true), edit one cell in place; save; capture the PATCH; re-read the row via API", "on in_progress, with the export grant from fixtures.requires[3] bound, open the view bar's Options (选项) popover — the Display popover, a text trigger since objectstack#35548 — Export sits in its footer ('Export as CSV / XLSX / JSON'), not as a separate toolbar button — and export each declared format (csv, xlsx, json); capture the requests and files. Without the grant the Export entries are absent and the route answers 403 EXPORT_NOT_PERMITTED — the opt-in working as designed, not a fail of the export variant", "open the visualization switcher on All Tasks; enumerate the offered types; switch through each", "on bulk_actions, select rows that are NOT done and run showcase_mark_done (per-record) — its visible gate, has(record.done) && record.done != true, judges each selected row, so a done row in the selection drops Mark Done from the selection actions the page bar shows (since #35554 the list page has no bottom bulk bar), or, over a mixed selection, the confirm reports the done rows not eligible and skipped (QA run #27438); either way the dispatch count stops matching the selection — and showcase_recalc_selection (aggregate — ONE dispatch: an api-type action, which the console sends through the action door, POST /api/v1/actions/showcase_task/showcase_recalc_selection with body {params:{_selectedIds:[…]}}; the server forwards those params flat to the action's own target /api/v1/apps/showcase/recalc in-process, buildApiActionRequest in packages/runtime/src/action-execution.ts, so the browser's network log shows the door request and no /recalc request); on legacy_row_actions confirm both named row actions resolve to live menu entries", @@ -812,12 +812,6 @@ "date": "2026-11-19", "change": "steps[4] and acceptance[3] (clause and verify) follow #35554: a list view that declares no `pagination` has no pager and loads its next window as it scrolls (top=50, then top=50&skip=50), and only a view that declares `pagination` pages; the paging variant now walks both. steps[8] names where the bulk actions are offered now — the page bar, while rows are selected — instead of the retired bottom bulk bar. Read at base e01b8bed (after #35548)", "ref": "#35554" - }, - { - "revision": 12, - "date": "2026-11-20", - "change": "steps[5] follows #35684: a cell is edited by a double-click (or Enter, or typing on the selected cell), a single click selects it, and the list has no inline-edit toggle. The clauses are unchanged. Read at base 238661f4", - "ref": "#35684" } ] }, From d0ed9ac5e3722b048fb2eb675c1e34b858126be7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 01:47:19 +0000 Subject: [PATCH 04/17] wip(ui): select-first pins, and toggle-era tests migrated Claude-Session: https://claude.ai/code/session_01L6bhgTC8kn7AdeMpMmyhJG Co-authored-by: Claude --- ...View.fallbackTabSessionOnly-11643.test.tsx | 7 +- ...ctView.inlineEditSessionOnly-5144.test.tsx | 30 +- .../__tests__/data-table-keys-35687.test.tsx | 243 +++++++++++++ .../data-table-select-first-35684.test.tsx | 221 ++++++++++++ .../ObjectGrid.cellSelection-35684.test.tsx | 191 +++++++++++ .../src/hooks/useRowApprovalLocks.ts | 5 + .../src/objectGridCellFacts-35684.test.ts | 104 ++++++ .../ListView.displayPopover-12423.test.tsx | 26 +- .../src/__tests__/ListView.harness.test.tsx | 9 +- .../__tests__/ListView.permissions.test.tsx | 322 +++--------------- .../src/__tests__/ListView.test.tsx | 97 ++---- .../ListViewBlock.specInputs-13047.test.tsx | 11 +- 12 files changed, 874 insertions(+), 392 deletions(-) create mode 100644 ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx create mode 100644 ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx create mode 100644 ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx create mode 100644 ui/packages/plugin-grid/src/objectGridCellFacts-35684.test.ts diff --git a/ui/packages/app-shell/src/views/ObjectView.fallbackTabSessionOnly-11643.test.tsx b/ui/packages/app-shell/src/views/ObjectView.fallbackTabSessionOnly-11643.test.tsx index d9309eefd15..10d40ca179c 100644 --- a/ui/packages/app-shell/src/views/ObjectView.fallbackTabSessionOnly-11643.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.fallbackTabSessionOnly-11643.test.tsx @@ -344,9 +344,9 @@ describe('objectui#11643 — the console-made tab of a view-less object keeps it expect(listSchema.label).toBe(FALLBACK_TAB_LABEL); // Every control that used to reach the toolbar's view write, through both - // the schema's and the list's own spelling of it. `onInlineEditChange` no longer reaches - // it at all (objectui#5144, ruling E: the toggle is session-only); it stays - // here because it must still write nothing. + // the schema's and the list's own spelling of it. (`onInlineEditChange` + // is no longer handed to the list at all: objectstack#35684 retired the + // toggle it reported.) act(() => { listSchema.onDensityChange('comfortable'); listSchema.onSortChange(SORT); @@ -354,7 +354,6 @@ describe('objectui#11643 — the console-made tab of a view-less object keeps it listSchema.onColumnStateChange({ widths: { title: 240 } }); listProps.onSortChange(SORT); listProps.onHiddenFieldsChange(['status']); - listProps.onInlineEditChange(true); listProps.onColumnStateChange({ order: ['status', 'title'] }); }); // Past the 300 ms debounce and any round trip it would have started. diff --git a/ui/packages/app-shell/src/views/ObjectView.inlineEditSessionOnly-5144.test.tsx b/ui/packages/app-shell/src/views/ObjectView.inlineEditSessionOnly-5144.test.tsx index 3ea7cf7e26d..8eb5cc13c12 100644 --- a/ui/packages/app-shell/src/views/ObjectView.inlineEditSessionOnly-5144.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.inlineEditSessionOnly-5144.test.tsx @@ -8,7 +8,10 @@ /** * objectui#5144, triage's ruling E — the console's inline-edit toggle is - * session state and writes nothing. + * session state and writes nothing. Since objectstack#35684 there is no + * toggle and no mode at all: the page hands `ListView` no inline-edit + * callback, and these cases pin that nothing the page does stores an + * `inlineEdit`, and what the fold reads. * * The view's `inlineEdit` and `userActions.editInline` are the author's * permission keys, and `normalizeListViewSchema` folds the first into the @@ -308,17 +311,13 @@ afterEach(() => { vi.clearAllMocks(); }); -describe('objectui#5144 (ruling E) — the console inline-edit toggle writes nothing', () => { - it('switching the toggle on a served view sends no write; the store records a view write when one is made', async () => { +describe('objectui#5144 (ruling E), objectstack#35684 — the console stores no inline-edit mode', () => { + it('a served view hands `ListView` no inline-edit callback and sends no write; the store records a view write when one is made', async () => { const { meta, rows, bodies } = makeStore([SERVED_OVERLAY]); const ds = await openPage(meta, OPTED_IN_OBJECT, 'all'); expect(listSchema.label).toBe('All notes'); - expect(typeof listProps.onInlineEditChange).toBe('function'); - - act(() => { - listProps.onInlineEditChange(true); - listProps.onInlineEditChange(false); - }); + // objectstack#35684 — no toggle, so no callback to report it. + expect(listProps.onInlineEditChange).toBeUndefined(); // Past the old toolbar write's 300 ms debounce, with room to spare. await wait(700); expect(meta.saveItem).not.toHaveBeenCalled(); @@ -338,33 +337,26 @@ describe('objectui#5144 (ruling E) — the console inline-edit toggle writes not expect(toast.error).not.toHaveBeenCalled(); }); - it('two-way: on a view that declares `userActions.editInline: true`, the toggle is still offered after it is switched off and the view remounts', async () => { + it('a view that declares `userActions.editInline: true` reads on, and still does after the view remounts', async () => { const { meta, rows } = makeStore([SERVED_OVERLAY]); await openPage(meta, OPTED_IN_OBJECT, 'all'); expect(folded().editInline).toBe(true); - - act(() => listProps.onInlineEditChange(false)); await wait(700); expect(rows.get('all')).toEqual(SERVED_OVERLAY); cleanup(); await openPage(meta, OPTED_IN_OBJECT, 'all'); expect(folded().editInline).toBe(true); - // Nothing was stored, so the mode is seeded from the view again. + // Nothing was stored. expect(folded().inlineEdit).toBeUndefined(); }); - it('a saved view: the toggle switched off writes nothing, and the stored `inlineEdit: true` is what the next load reads', async () => { - // Recorded cost of ruling E: the edit mode is not remembered across loads. + it('a saved view writes nothing, and the stored `inlineEdit: true` is what the next load reads', async () => { const { meta, rows, bodies } = makeStore([SAVED_ROW]); await openPage(meta, PLAIN_OBJECT, SAVED_ID); expect(listSchema.label).toBe('Mine'); expect(folded()).toEqual({ editInline: true, inlineEdit: true }); - act(() => listProps.onInlineEditChange(false)); - await wait(700); - expect(meta.saveItem).not.toHaveBeenCalled(); - // Since objectui#12474 a density change on the same saved view writes no // row either (it is the user's own list state), so the row's own // `inlineEdit` is untouched and no body carries the toggle's `false`. diff --git a/ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx b/ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx new file mode 100644 index 00000000000..0bfaf22f20b --- /dev/null +++ b/ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx @@ -0,0 +1,243 @@ +/** + * 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. + */ + +/** + * The keys of `data-table`'s select-first cell model (objectstack#35687); + * what a click does is `data-table-select-first-35684.test.tsx`. + * + * 1. On the selected cell: the arrows and Tab move the selection; Escape + * clears it; typing opens the editor with the typed text in place of the + * value (a number column gets the number); Backspace opens it empty and + * writes nothing; Ctrl/Cmd+V converts and commits; Ctrl/Cmd+C copies. + * 2. While editing: Enter commits and moves down, Tab / Shift+Tab commit and + * move right / left, Escape cancels and keeps the selection. In a + * multi-line editor Enter is the editor's and Ctrl/Cmd+Enter commits. + * 3. An input method: the keys pressed while it composes, and the 229 + * Enter a browser raises after `compositionend`, never commit; a + * composition started on the selected cell opens the editor with the + * whole composed text. + */ +import React from 'react'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { render, fireEvent, cleanup } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { ComponentRegistry } from '@object-ui/core'; +// Registers `data-table` at module scope, not in a hook (objectui#3010). +import '../renderers'; +import { GridCellSelectionProvider, type GridCellSelection } from '../context/gridCellSelection'; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const ROWS = [ + { id: '1', name: 'Alpha', amount: 10, notes: 'one' }, + { id: '2', name: 'Beta', amount: 20, notes: 'two' }, + { id: '3', name: 'Gamma', amount: 30, notes: 'three' }, +]; + +function renderTable(extra: Record = {}, selection: GridCellSelection = {}) { + const DataTable = ComponentRegistry.get('data-table')!; + const onCellChange = vi.fn(); + const schema = { + type: 'data-table', + columns: [ + { header: 'Name', accessorKey: 'name' }, + { header: 'Amount', accessorKey: 'amount', type: 'number' }, + { header: 'Notes', accessorKey: 'notes' }, + ], + data: ROWS, + editable: true, + searchable: false, + pagination: false, + onCellChange, + ...extra, + }; + const utils = render( + + + , + ); + const cell = (row: number, col: number) => + utils.container.querySelectorAll('tbody tr')[row].querySelectorAll('td[data-grid-cell]')[col] as HTMLElement; + const selected = () => { + const td = utils.container.querySelector('td[data-selected-cell]'); + return td ? td.getAttribute('data-grid-cell') : null; + }; + const editor = () => + utils.container.querySelector('td[data-editing-cell] input, td[data-editing-cell] textarea'); + const catcher = () => utils.container.querySelector('[data-slot="cell-type-catcher"]')!; + const select = (row: number, col: number) => fireEvent.click(cell(row, col)); + return { ...utils, cell, selected, editor, catcher, select, onCellChange }; +} + +describe('data-table select-first keys — on the selected cell (objectstack#35687)', () => { + it('the arrows move the selection, Tab moves along the row, Escape clears it', () => { + const t = renderTable(); + t.select(0, 0); + fireEvent.keyDown(t.catcher(), { key: 'ArrowDown' }); + expect(t.selected()).toBe('1:0'); + fireEvent.keyDown(t.catcher(), { key: 'ArrowRight' }); + expect(t.selected()).toBe('1:1'); + fireEvent.keyDown(t.catcher(), { key: 'Tab' }); + expect(t.selected()).toBe('1:2'); + fireEvent.keyDown(t.catcher(), { key: 'Tab' }); + expect(t.selected()).toBe('2:0'); + fireEvent.keyDown(t.catcher(), { key: 'Tab', shiftKey: true }); + expect(t.selected()).toBe('1:2'); + expect(t.editor()).toBeNull(); + fireEvent.keyDown(t.catcher(), { key: 'Escape' }); + expect(t.selected()).toBeNull(); + }); + + it('typing replaces the value with the typed text, and Escape puts the value back', () => { + const t = renderTable(); + t.select(0, 0); + fireEvent.change(t.catcher(), { target: { value: 'Z' } }); + expect(t.editor()).toHaveValue('Z'); + fireEvent.keyDown(t.editor()!, { key: 'Escape' }); + expect(t.editor()).toBeNull(); + expect(t.cell(0, 0)).toHaveTextContent('Alpha'); + expect(t.selected()).toBe('0:0'); + expect(t.onCellChange).not.toHaveBeenCalled(); + }); + + it('typing 5 on a number cell edits 5, and Escape leaves the old figure', () => { + const t = renderTable(); + t.select(1, 1); + fireEvent.change(t.catcher(), { target: { value: '5' } }); + expect(t.editor()).toHaveValue(5); + fireEvent.keyDown(t.editor()!, { key: 'Escape' }); + expect(t.cell(1, 1)).toHaveTextContent('20'); + expect(t.onCellChange).not.toHaveBeenCalled(); + }); + + it.each(['Backspace', 'Delete'])('%s opens an empty editor and writes nothing', (key) => { + const t = renderTable(); + t.select(1, 1); + fireEvent.keyDown(t.catcher(), { key }); + expect(t.editor()).not.toBeNull(); + expect(t.editor()!.value).toBe(''); + expect(t.onCellChange).not.toHaveBeenCalled(); + }); + + it('Ctrl/Cmd+V converts the text to the column and commits it; text that is no value writes nothing', () => { + const t = renderTable(); + t.select(0, 1); + fireEvent.paste(t.catcher(), { clipboardData: { getData: () => '42\n' } }); + expect(t.onCellChange).toHaveBeenCalledWith(0, 'amount', 42, ROWS[0]); + t.onCellChange.mockClear(); + fireEvent.paste(t.catcher(), { clipboardData: { getData: () => 'forty-two' } }); + expect(t.onCellChange).not.toHaveBeenCalled(); + // The host's reading of the text wins. + const h = renderTable({}, { describeCell: () => ({ fromText: (text) => text.toUpperCase() }) }); + h.select(0, 0); + fireEvent.paste(h.catcher(), { clipboardData: { getData: () => 'zed' } }); + expect(h.onCellChange).toHaveBeenCalledWith(0, 'name', 'ZED', ROWS[0]); + }); + + it('Ctrl/Cmd+C copies the selected value', () => { + const writeText = vi.fn().mockResolvedValue(undefined); + const had = Object.getOwnPropertyDescriptor(navigator, 'clipboard'); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + try { + const t = renderTable(); + t.select(2, 0); + fireEvent.keyDown(t.catcher(), { key: 'c', ctrlKey: true }); + expect(writeText).toHaveBeenCalledWith('Gamma'); + } finally { + if (had) Object.defineProperty(navigator, 'clipboard', had); + else delete (navigator as { clipboard?: unknown }).clipboard; + } + }); +}); + +describe('data-table select-first keys — while editing', () => { + it('Enter commits and moves down; Tab commits and moves right; Shift+Tab left', () => { + const t = renderTable(); + t.select(0, 0); + fireEvent.change(t.catcher(), { target: { value: 'A' } }); + fireEvent.keyDown(t.editor()!, { key: 'Enter' }); + expect(t.onCellChange).toHaveBeenLastCalledWith(0, 'name', 'A', ROWS[0]); + expect(t.editor()).toBeNull(); + expect(t.selected()).toBe('1:0'); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + fireEvent.keyDown(t.editor()!, { key: 'Tab' }); + expect(t.selected()).toBe('1:1'); + expect(t.editor()).toBeNull(); + fireEvent.keyDown(t.catcher(), { key: 'F2' }); + fireEvent.keyDown(t.editor()!, { key: 'Tab', shiftKey: true }); + expect(t.selected()).toBe('1:0'); + expect(t.onCellChange).toHaveBeenCalledTimes(3); + }); + + it('Escape cancels and keeps the cell selected, with focus on it', () => { + const t = renderTable(); + t.select(2, 2); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + fireEvent.change(t.editor()!, { target: { value: 'changed' } }); + fireEvent.keyDown(t.editor()!, { key: 'Escape' }); + expect(t.editor()).toBeNull(); + expect(t.cell(2, 2)).toHaveTextContent('three'); + expect(t.selected()).toBe('2:2'); + expect(document.activeElement).toBe(t.catcher()); + }); + + it('a multi-line editor keeps Enter, and Ctrl/Cmd+Enter commits it', () => { + const renderCellEditor = (ctx: { value: unknown; stage: (v: unknown) => void }) => ( +