diff --git a/.changeset/35827-data-table-staged-edit-retired.md b/.changeset/35827-data-table-staged-edit-retired.md new file mode 100644 index 00000000000..d7dc7106172 --- /dev/null +++ b/.changeset/35827-data-table-staged-edit-retired.md @@ -0,0 +1,37 @@ +--- +'@object-ui/types': minor +'@object-ui/components': minor +'@object-ui/plugin-grid': minor +'@object-ui/app-shell': minor +'@objectstack/spec': minor +--- + +feat(ui): the grid's staged edit model retires with its interface, so every editable grid selects a cell first and saves each cell on its own + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing on the grid's host interface: `ObjectGrid`'s `cellSelection` prop and `onBatchSave` prop (`@object-ui/plugin-grid`), and `DataTableSchema.onBatchSave` and `DataTableSchema.singleClickEdit` (`@object-ui/types`). The staged model behind them goes in the same release (`@object-ui/components`). + +- **Now.** There is one way to edit a grid. A grid that renders editable selects a cell on a click; double-click, Enter, F2 or typing opens its editor; Esc cancels; and each committed cell is saved at once as one update for its record, through the host's `onRowSave` or, when there is none, the grid's own `dataSource.update`. The pending-changes bar, its "Save All" and "Cancel All" buttons, the per-row save/cancel column and the amber "modified" tints are gone everywhere. A grid that renders read-only keeps its click-to-open row, and a host may still pass `cellSelection={true}` to ask for the select-first model on a read-only grid. +- **A bare `data-table`.** An editable `data-table` edits only inside a select-first host (`GridCellSelection`) that also passes `onRowSave`. Without both it renders read-only and logs one console warning naming what is missing, instead of staging edits it has nowhere to save. Render an `object-grid`, which mounts both and writes through its data source. +- **Unchanged.** Who may edit what: `editable`, the object's inline-edit affordance, the reader's `update` grant, per-field write grants, the record-grained verdict and approval locks all narrow editing exactly as before. + +| FROM | TO | +|:--|:--| +| `` to keep click-to-edit and the "Save All" bar | drop the prop; an editable grid is select-first, and a read-only one opens a record on a click | +| `` | pass `onRowSave(rowIndex, changes, row)` to own the write record by record, or pass nothing and let the grid save through its own `dataSource.update` | +| `data-table` schema `onBatchSave: (changes) => …` | `onRowSave` inside a `GridCellSelection` host, or render `object-grid` | +| `data-table` schema `singleClickEdit` | delete the key; a click selects the cell and double-click, Enter, F2 or typing opens its editor | +| an editable `data-table` with no `GridCellSelection` host or no `onRowSave` | mount `GridCellSelection` and pass `onRowSave`, or render `object-grid`; until then it renders read-only and warns | + +The one-line fix: delete `cellSelection={false}`, `onBatchSave` and `singleClickEdit` wherever a host writes them, and pass `onRowSave` where a batch handler did the write. Passing `cellSelection={false}`, `onBatchSave` or `singleClickEdit` after upgrade fails `tsc` (`cellSelection` accepts only `true`, `onBatchSave` is `never`, `singleClickEdit` is no longer declared), and the `data-table` mirror refuses `onBatchSave` by name as retired. None of these is authorable metadata, so `os migrate meta` has nothing to rewrite; its D3 entry `data-table-staged-edit-retired` names what the upgrade still owes: host code that relied on one transaction per Save All, and help text and tests that describe the old gestures. + +The retirement kit: + +- **`@object-ui/types`**: `DataTableSchema.onBatchSave` is `?: never` on the TS face and a `retired` handler-key refusal on the zod mirror; `DataTableSchema.singleClickEdit` is removed; the `editable`, `onRowSave` and `onCellChange` docs say a commit is the save. The parity ledgers drop both keys. +- **`@object-ui/components`**: `data-table` loses the staged arm (pending-changes bar, Save All / Cancel All, row save/cancel buttons, edit-only column, click-to-edit, the amber tints) and its fallback copy rows (`table.saveAll`, `table.cancelAll`, `table.modified`, `table.saveRow`, `table.cancelChanges`). An editable table without a select-first host and `onRowSave` renders read-only with a `[ObjectUI] DataTable editable:` console warning. +- **`@object-ui/plugin-grid`**: `cellSelection` accepts only `true`; `onBatchSave` and the default batch save are removed, and the default cell save keeps its rule check, `If-Match` guard, conflict dialog, Undo and toast. `keyboardNavigation`'s describe drops its staged sentence. +- **`@object-ui/app-shell`**: the metadata resource list stops passing `cellSelection={false}`; it is read-only, so it keeps click-to-open. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index cbabc4304fd..a5216e9b9bd 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -208,16 +208,16 @@ verdict. ### Row callbacks are component props -`onRowClick`, `onRowSelect`, `onCellChange`, `onRowSave`, `onBatchSave`, +`onRowClick`, `onRowSelect`, `onCellChange`, `onRowSave`, `onEdit`, `onDelete`, `onBulkDelete` and `onAddRecord` are React props on `ObjectGridComponentProps`. They are functions, so no metadata document can hold them, and writing one of them into a schema does nothing at all: the grid builds -the inner table's handlers itself and never reads any of these nine off the +the inner table's handlers itself and never reads any of these eight off the schema. The one callback the grid does read off the schema is `onNavigate`, declared on `ObjectGridSchema` for programmatic callers only. It is a function value too, so -it is no more authorable than the nine — it is deliberately absent from the +it is no more authorable than the eight — it is deliberately absent from the manifest and the designer panel, and prefer passing it as a prop (objectui#5234, maintainer ruling of 2026-08-19). @@ -411,16 +411,12 @@ retired (objectstack#36270): `@objectstack/spec` refuses it, and definition**, not by a column key — a field marked `readonly`, and computed/binary field types (formula, autonumber, file, …), never open an editor. There is no `editable` key on `ListColumn`. -- **Rich text edits in a panel** (objectstack#36023): on a select-first grid - (`cellSelection`), a `markdown`, `html` or `richtext` cell opens the record +- **Rich text edits in a panel** (objectstack#36023): a `markdown`, `html` or `richtext` cell opens the record form's text box over the stored source in a panel under the cell, at least as wide as the column, while the cell keeps showing its value. Enter there is a - new line, Ctrl/Cmd+Enter saves, Esc discards and a click outside saves. A grid - without `cellSelection` opens the text box over the cell on one click: Enter - is a new line, Ctrl/Cmd+Enter does nothing, Esc discards and a click outside - keeps the text as a pending change for the grid's save buttons. -- **Visual feedback**: editable cells show a hover state, and the input is - focused and selected when editing begins + new line, Ctrl/Cmd+Enter saves, Esc discards and a click outside saves. +- **Visual feedback**: the selected cell is ringed, and the editor opens with + the caret after the value - **The editor floats over its cell** (objectstack#35688): it opens on a layer anchored to the cell's top-left corner, at least as wide as the column and wider where its field type needs it (an address form, a record picker), so @@ -449,9 +445,10 @@ page, the grid an `object-view` draws, and an authored `object-grid`. There is no inline-edit mode and no toggle. On the list page the grid is editable wherever the reader may edit the object and the view does not declare `userActions.editInline: false`; elsewhere it is editable where `editable` is -set and the reader may edit the object. A React host can pass the -`cellSelection` component prop (not a schema key) as `false` to keep the staged -model described under [Batch Editing](#batch-editing--multi-row-save). +set and the reader may edit the object. There is no other editing model: the +staged one (click-to-edit, a pending-changes bar and "Save All") is retired, and +so is the React host's `cellSelection={false}` that kept it (objectstack#35827) — +see [Owning persistence](#owning-persistence-onrowsave). - **A click selects** a cell (a ring around it); it neither edits nor opens the record. Only the name link keeps its own click (it opens the record). Every @@ -612,22 +609,16 @@ WAI-ARIA grid pattern (objectui#11068): `editable` *and* the viewer's permission to update the object, the same value inline editing obeys — because that grid selects a cell first and moves the selection with these keys; `false` does not turn it off there - (objectstack#36270), except where a React host keeps the staged model with - `cellSelection={false}` (see Batch Editing below). A read-only grid keeps every - cell its own Tab stop unless you write `true`. + (objectstack#36270). A read-only grid keeps every cell its own Tab stop unless + you write `true`. - While it is on, the table is exposed to assistive technology as a `grid`. A grouped grid navigates within each group's table; the mobile card layout has no cells and is unaffected. -### Batch Editing & Multi-Row Save +### Owning persistence: `onRowSave` -Edit multiple cells across multiple rows and save them individually or all at -once. This is the staged model, which no metadata selects: since -objectstack#36270 every grid that renders editable saves each cell as it is -committed (above). A React host that draws `ObjectGrid` itself opts back into -it by passing `cellSelection={false}`; then a click opens a cell's editor, and -the save/cancel affordances appear on their own once a row has pending -changes: +An editable grid needs no prop to edit: it selects a cell first and saves each +committed cell as it goes. ```tsx import { ObjectGrid, type ObjectGridComponentProps } from '@object-ui/plugin-grid'; @@ -636,7 +627,6 @@ declare const dataSource: NonNullable; export const ProductsGrid = () => ( ( ); ``` -Left alone, saving goes through the host's data source. A React host that needs -to own persistence supplies `onRowSave` / `onBatchSave` as **component props** — -and because they are props, they take the adapter from the host's own scope -rather than from anything in the schema: +Each committed cell is written through the host's data source. A React host that +needs to own persistence supplies `onRowSave` as a **component prop** — and +because it is a prop, it takes the adapter from the host's own scope rather than +from anything in the schema. It is called once per commit, with every edit that +record still holds: ```tsx import type { ObjectGridComponentProps } from '@object-ui/plugin-grid'; -type Persistence = Pick; +type Persistence = Pick; const persistence = ( dataSource: NonNullable, @@ -669,33 +660,22 @@ const persistence = ( onRowSave: async (rowIndex, changes, row) => { await dataSource.update('products', row.id, changes); }, - onBatchSave: async (allChanges) => { - await Promise.all( - allChanges.map(({ row, changes }) => dataSource.update('products', row.id, changes)), - ); - }, }); ``` -**Features:** -- **Pending changes tracking**: edit multiple cells across rows before saving; a - cell edited back to the value it loaded with is not a pending change, and its - row is no longer counted as modified -- **Visual indicators**: modified rows highlighted in amber, modified cells in bold -- **Row-level save/cancel**: individual row save and cancel buttons -- **Batch operations**: Save All and Cancel All buttons for bulk actions -- **Flexible callbacks** — all three are `ObjectGridComponentProps`, never schema - keys: `onRowSave` for a single row, `onBatchSave` for many, `onCellChange` for - each committed cell edit, including one that leaves the value as loaded (only a - real change is staged). `onBatchSave` is `@deprecated`: only this staged model calls it; - on a select-first grid each cell saves through `onRowSave` (or the grid's own - write) and `onBatchSave` is never called -- **A concurrent write is refused, not overwritten**: the default saves send each +`cellSelection` takes only `true`: it asks for the select-first model on a grid +that renders read-only. **Upgrading from the staged model** (objectstack#35827): +drop `cellSelection={false}`; move a batch `onBatchSave(allChanges)` handler to a +per-record `onRowSave(rowIndex, changes, row)`, or drop it and let the grid write +through its data source. + +- **A refused save keeps the edit**: the cell keeps what was typed and says the + server's reason; the record's next commit sends it again with the new cell. +- **A concurrent write is refused, not overwritten**: the default save sends the row's `updated_at` as `If-Match`, and an editable grid asks for that column even when no column shows it. A row someone else saved after it was read answers `409`, which opens the record page's conflict dialog (Reload latest, Overwrite - anyway, Cancel). "Save All" reports each row on its own: a refused row stays - pending and flagged, and the rows that saved are cleared. + anyway, Cancel). ## TypeScript Support diff --git a/packages/spec/src/migrations/entries/semantic/19.data-table-staged-edit-retired.ts b/packages/spec/src/migrations/entries/semantic/19.data-table-staged-edit-retired.ts new file mode 100644 index 00000000000..d6554a76dec --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.data-table-staged-edit-retired.ts @@ -0,0 +1,36 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The data-table staged-edit retirement (ruling record 7178367040, route A: the +// staged model and its interface retire together), its D3 entry. No D2 +// conversion: nothing it retires is authorable metadata (`onBatchSave` is a +// host function the parse already refused by name, and `cellSelection` is a +// React prop of ``), so there is no source to rewrite. What the +// consumer still owes is the host code and the tests that drove the old model. +export const entry: SemanticMigration = { + id: 'data-table-staged-edit-retired', + surface: 'object-grid / data-table host interface — the staged edit model: ``, ' + + 'the `onBatchSave` handler on `` and on the `data-table` schema, `data-table`\'s ' + + '`singleClickEdit`, and an editable `data-table` mounted without a cell-selection host or an ' + + '`onRowSave` handler', + replacement: 'Select-first editing with one save per committed cell. Pass `onRowSave` to `` to own ' + + 'persistence record by record, or pass nothing and let the grid write through its own ' + + '`dataSource.update`. A host may still pass `cellSelection={true}`; without the prop an editable grid ' + + 'is select-first and a read-only grid opens a record on a click. A bare `data-table` edits only ' + + 'inside a cell-selection host with an `onRowSave` handler, or is rendered as `object-grid` instead.', + reason: 'The staged model kept edited cells as pending changes behind a "Save All" bar and handed them to ' + + '`onBatchSave` together. It is gone, not deprecated: `cellSelection` accepts only `true`, `onBatchSave` ' + + 'is a `never` key on both type faces and refused by name in the parse, and `singleClickEdit` is no ' + + 'longer declared. A host that passed `cellSelection={false}` to get click-to-edit and a save bar now ' + + 'gets select-first editing that saves each cell as it is committed, so a batch handler it relied on ' + + 'for one transaction per save is never called. An editable `data-table` without a cell-selection host ' + + 'and an `onRowSave` handler now renders read-only and logs a console warning instead of staging edits ' + + 'it had nowhere to save. Only the host\'s author can tell whether per-record saves are acceptable where ' + + 'a batch was, and which help text and tests describe the old gestures.', + acceptanceCriteria: 'No host passes `cellSelection={false}` or an `onBatchSave` handler, and no `data-table` ' + + 'schema carries `singleClickEdit` or `onBatchSave`; the type check refuses all of them. Every editable ' + + 'grid either passes `onRowSave` or relies on its data source to save each committed cell, and its help ' + + 'text and tests describe a click that selects a cell, a double-click, Enter, F2 or typing that opens its ' + + 'editor, and no "Save All". No editable `data-table` logs the read-only warning at mount.', +}; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx index 1ea69a52208..d9a0ed8fbc3 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -1521,7 +1521,6 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string return info?.invalid ? 'red' : info?.warnOnly ? 'amber' : null; }} rowOpensRecord={false} - cellSelection={false} onRowClick={(rec, event) => { const info = rowInfoOf(rec); if (!info || (event && (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey))) return; diff --git a/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx b/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx index c9e041c8e2c..5aaf9b659b3 100644 --- a/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx @@ -20,7 +20,8 @@ * 4. A commit made while the record's save runs is sent after it, alone. * 5. A refusal naming a field the list cannot edit offers to open the record. * 6. A client-sorted row a save updated stays where it is until the rows load. - * 7. Control: without the provider the save bar model is unchanged. + * 7. No staged fallback (objectstack#35827): without the provider, or + * without `onRowSave`, an editable table renders read-only and warns once. * 8. A commit the host asks to confirm (`confirmCommit`, slice S3) is held * with nothing staged: No leaves the cell as it was, Yes writes it; a * paste is asked too, an unchanged value is not. @@ -268,36 +269,44 @@ describe('data-table autosave — a saved row keeps its place until the rows loa }); }); -describe('data-table autosave — control: without the provider the save bar stays', () => { - it('a commit stages, the bar shows, and nothing is sent until Save', async () => { - const onRowSave = vi.fn(async () => {}); - const t = renderTable(onRowSave, { singleClickEdit: true }, false); +describe('data-table autosave — no staged fallback: a table that cannot save renders read-only (objectstack#35827)', () => { + // The staged model (pending changes behind a "Save All" bar) is retired, so + // an editable table missing either half of the per-cell save edits nothing + // and says why once in the console, instead of staging edits it cannot send. + afterEach(() => vi.restoreAllMocks()); + const opensNoEditor = (t: ReturnType) => { const cell = t.container.querySelectorAll('tbody tr')[0].querySelectorAll('td')[0] as HTMLElement; fireEvent.click(cell); - const input = cell.querySelector('input')!; - fireEvent.change(input, { target: { value: 'Alpha 2' } }); - fireEvent.blur(input); - await act(async () => {}); + fireEvent.doubleClick(cell); + expect(t.container.querySelector('td[data-editing-cell]')).toBeNull(); + expect(t.container.querySelector('td input:not([type="checkbox"]):not([data-slot="cell-type-catcher"])')).toBeNull(); + expect(screen.queryByText(/Save All/)).toBeNull(); + }; + + it('without the provider: no editor opens, no save bar, one console warning naming the select-first host', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const onRowSave = vi.fn(async () => {}); + const t = renderTable(onRowSave, {}, false); + opensNoEditor(t); expect(onRowSave).not.toHaveBeenCalled(); - expect(screen.getByText(/row modified/)).toBeInTheDocument(); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((m) => m.startsWith('[ObjectUI] DataTable editable:')); + expect(lines).toHaveLength(1); + expect(lines[0]).toMatch(/GridCellSelection/); }); -}); -describe('data-table autosave — a select-first table with no row save keeps the save bar', () => { - // Under the provider the per-cell save needs `onRowSave` to call; a table - // wired with `onBatchSave` alone stages as before, so an edit is never held - // where nothing can send it. - it('a commit stages, the bar and the row buttons show, and Save All sends it', async () => { - const onBatchSave = vi.fn(async (_changes: unknown[]) => {}); - const t = renderTable(undefined as unknown as Save, { onBatchSave }); - t.typeAndEnter(0, 0, 'Alpha 2'); - await act(async () => {}); - expect(onBatchSave).not.toHaveBeenCalled(); - expect(screen.getByText(/row modified/)).toBeInTheDocument(); - expect(t.container.querySelector('[data-slot="cell-save-state"]')).toBeNull(); - fireEvent.click(screen.getByText(/Save All/)); - await waitFor(() => expect(onBatchSave).toHaveBeenCalledTimes(1)); - expect((onBatchSave.mock.calls[0][0] as Array<{ changes: unknown }>)[0].changes).toEqual({ name: 'Alpha 2' }); + it('under the provider with no onRowSave: no editor opens, no save bar, one console warning naming onRowSave', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const t = renderTable(undefined as unknown as Save); + opensNoEditor(t); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((m) => m.startsWith('[ObjectUI] DataTable editable:')); + expect(lines).toHaveLength(1); + expect(lines[0]).toMatch(/onRowSave/); + }); + + it('a read-only table warns nothing', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + renderTable(undefined as unknown as Save, { editable: false }, false); + expect(warn.mock.calls.map((c) => String(c[0])).filter((m) => m.startsWith('[ObjectUI] DataTable editable:'))).toEqual([]); }); }); diff --git a/ui/packages/components/src/__tests__/data-table-batch-per-row-12292.test.tsx b/ui/packages/components/src/__tests__/data-table-batch-per-row-12292.test.tsx deleted file mode 100644 index 1b63fb5acc8..00000000000 --- a/ui/packages/components/src/__tests__/data-table-batch-per-row-12292.test.tsx +++ /dev/null @@ -1,105 +0,0 @@ -/** - * 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. - */ - -/** - * objectui#12292 — "Save All" reads the batch's outcome PER ROW. - * - * A batch is several independent writes: some can land while others are - * refused, and the server keeps the ones it accepted. The table used to read - * every batch as all-or-nothing, so one refused row kept every row pending and - * flagged, rows that had landed included, and a retry sent them again. An - * `onBatchSave` that knows which rows did not persist now resolves with - * `{ failed }`, and the table keeps exactly those rows. A rejection still reads - * as all-or-nothing, because it says nothing about which rows landed; the - * existing pins in `data-table-inline-edit.test.tsx` hold that half. - */ -import { describe, it, expect, vi } from 'vitest'; -import { fireEvent, waitFor } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import { renderComponent } from './test-utils'; -// Registers the renderers at module scope, NOT inside a `beforeAll`; see -// object-ui/no-dynamic-import-in-test-hook (objectui#3010/#3021). -import '../renderers'; - -const schema = { - type: 'data-table' as const, - editable: true, - singleClickEdit: true, - columns: [ - { header: 'Task', accessorKey: 'name', editable: false }, - { header: 'Estimate', accessorKey: 'qty', type: 'number' }, - ], - data: [ - { id: '1', name: 'Ingest pipeline', qty: 60 }, - { id: '2', name: 'Warehouse schema', qty: 33 }, - ], -} as any; - -type Entry = { rowIndex: number; changes: Record; row: any }; - -/** Stage a new value in the Estimate cell of the given body row. */ -function stage(container: HTMLElement, rowNumber: number, value: string) { - const row = container.querySelectorAll('tbody tr')[rowNumber] as HTMLElement; - const cell = row.querySelectorAll('td')[1] as HTMLElement; - fireEvent.click(cell); - const input = cell.querySelector('input') as HTMLInputElement; - fireEvent.change(input, { target: { value } }); - fireEvent.blur(input); -} - -describe('data-table — Save All reads a per-row batch outcome (objectui#12292)', () => { - it('keeps and flags only the rows the batch names as failed', async () => { - const onBatchSave = vi.fn(async (entries: Entry[]) => ({ - failed: entries - .filter((e) => e.row.id === '2') - .map((e) => ({ rowIndex: e.rowIndex, error: new Error('Warehouse schema was refused') })), - })); - const { container, getByText, getByRole } = renderComponent({ ...schema, onBatchSave }); - - stage(container, 0, '61'); - stage(container, 1, '31'); - expect(getByText(/2 rows modified/)).toBeInTheDocument(); - fireEvent.click(getByText(/Save All/)); - - await waitFor(() => expect(getByText(/1 row modified/)).toBeInTheDocument()); - expect(onBatchSave).toHaveBeenCalledTimes(1); - expect(getByRole('button', { name: /Save All \(1\)/ })).toBeInTheDocument(); - expect(container.textContent).toContain('Warehouse schema was refused'); - // The refused row keeps its edit; the row that persisted holds none. - const rows = container.querySelectorAll('tbody tr'); - expect(rows[1].textContent).toContain('31'); - expect(rows[0].textContent).not.toContain('61'); - }); - - it('clears every row when the outcome names no failure', async () => { - const onBatchSave = vi.fn(async () => ({ failed: [] })); - const { container, getByText, queryByText } = renderComponent({ ...schema, onBatchSave }); - - stage(container, 0, '61'); - stage(container, 1, '31'); - fireEvent.click(getByText(/Save All/)); - - await waitFor(() => expect(onBatchSave).toHaveBeenCalledTimes(1)); - await waitFor(() => expect(queryByText(/modified/)).toBeNull()); - expect(container.textContent).not.toContain('Save failed'); - }); - - it('keeps every row when a failure names a row the batch never handed over', async () => { - const onBatchSave = vi.fn(async () => ({ - failed: [{ rowIndex: 999, error: new Error('Unplaceable refusal') }], - })); - const { container, getByText } = renderComponent({ ...schema, onBatchSave }); - - stage(container, 0, '61'); - stage(container, 1, '31'); - fireEvent.click(getByText(/Save All/)); - - await waitFor(() => expect(container.textContent).toContain('Unplaceable refusal')); - expect(getByText(/2 rows modified/)).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx b/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx index 6dfd8e9773d..6da55197771 100644 --- a/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx @@ -75,7 +75,7 @@ function renderTable(extra: Record = {}, selection: React.Compo ], data: ROWS, editable: true, - singleClickEdit: true, + onRowSave: () => Promise.resolve(), searchable: false, pagination: false, onCellChange, diff --git a/ui/packages/components/src/__tests__/data-table-injected-editor-blur-commit-12664.test.tsx b/ui/packages/components/src/__tests__/data-table-injected-editor-blur-commit-12664.test.tsx index 77379715c35..f671945fe19 100644 --- a/ui/packages/components/src/__tests__/data-table-injected-editor-blur-commit-12664.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-injected-editor-blur-commit-12664.test.tsx @@ -14,7 +14,9 @@ * text on blur). Before Enter or a pointer press outside commits, the table * blurs the control that holds focus inside the editor, and it commits the * LAST value staged — not the value from before a stage made earlier in the - * same event. Escape discards without reading the control. + * same event. Escape discards without reading the control. The table is + * mounted select-first with a per-cell save, the one way it edits + * (objectstack#35827). * * `packages/components` does not depend on `@object-ui/fields`, so the * commit-on-blur widget is reproduced here with a plain input; the real @@ -25,14 +27,16 @@ import { describe, it, expect, vi } from 'vitest'; import { fireEvent, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; -import { renderComponent } from './test-utils'; +import { openCellEditor, renderSelectFirstTable } from './test-utils'; // Module scope, not a hook — see object-ui/no-dynamic-import-in-test-hook. import '../renderers'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; const baseSchema = { type: 'data-table' as const, editable: true, - singleClickEdit: true, columns: [ { header: 'Name', accessorKey: 'name', editable: false }, { header: 'Due', accessorKey: 'due' }, @@ -58,7 +62,7 @@ const blurCommitEditor = ({ column, value, stage }: any) => function openEditor(container: HTMLElement): HTMLInputElement { const dueCell = container.querySelectorAll('tbody td')[1] as HTMLElement; - fireEvent.click(dueCell); + openCellEditor(dueCell); const editor = dueCell.querySelector('[data-testid="blur-commit-editor"]') as HTMLInputElement; expect(editor).toBeTruthy(); editor.focus(); @@ -69,7 +73,7 @@ function openEditor(container: HTMLElement): HTMLInputElement { describe('data-table — a commit-on-blur injected editor (objectui#12664)', () => { it('Enter blurs the control first and commits what it staged', async () => { const onCellChange = vi.fn(); - const { container } = renderComponent({ ...baseSchema, onCellChange, renderCellEditor: blurCommitEditor }); + const { container } = renderSelectFirstTable({ ...baseSchema, onCellChange, renderCellEditor: blurCommitEditor }); const editor = openEditor(container); fireEvent.keyDown(editor, { key: 'Enter' }); expect(onCellChange).toHaveBeenCalledTimes(1); @@ -79,7 +83,7 @@ describe('data-table — a commit-on-blur injected editor (objectui#12664)', () it('a pointer press outside blurs the control first and commits what it staged', async () => { const onCellChange = vi.fn(); - const { container } = renderComponent({ ...baseSchema, onCellChange, renderCellEditor: blurCommitEditor }); + const { container } = renderSelectFirstTable({ ...baseSchema, onCellChange, renderCellEditor: blurCommitEditor }); openEditor(container); fireEvent.pointerDown(document.body); expect(onCellChange).toHaveBeenCalledTimes(1); @@ -87,14 +91,13 @@ describe('data-table — a commit-on-blur injected editor (objectui#12664)', () await waitFor(() => expect(container.querySelector('[data-testid="blur-commit-editor"]')).toBeNull()); }); - it('Escape discards: the control is not read and nothing is committed or staged', async () => { + it('Escape discards: the control is not read and nothing is committed', async () => { const onCellChange = vi.fn(); - const { container, queryByText } = renderComponent({ ...baseSchema, onCellChange, renderCellEditor: blurCommitEditor }); + const { container } = renderSelectFirstTable({ ...baseSchema, onCellChange, renderCellEditor: blurCommitEditor }); const editor = openEditor(container); fireEvent.keyDown(editor, { key: 'Escape' }); await waitFor(() => expect(container.querySelector('[data-testid="blur-commit-editor"]')).toBeNull()); fireEvent.pointerDown(document.body); expect(onCellChange).not.toHaveBeenCalled(); - expect(queryByText(/Save All/i)).toBeNull(); }); }); diff --git a/ui/packages/components/src/__tests__/data-table-injected-editor-focus-6859.test.tsx b/ui/packages/components/src/__tests__/data-table-injected-editor-focus-6859.test.tsx index 6369926d665..99c9b06d48a 100644 --- a/ui/packages/components/src/__tests__/data-table-injected-editor-focus-6859.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-injected-editor-focus-6859.test.tsx @@ -24,8 +24,10 @@ * * It does not, and this file is the measurement that says why. The value never * depends on the exit event: the host wires the widget's `onChange` to `stage`, - * so every keystroke is already in `pendingChanges` while the editor is still - * open. The `pointerdown` listener exits EDIT MODE; it does not rescue values. + * so every keystroke is already staged while the editor is still open. The + * `pointerdown` listener exits EDIT MODE; it does not rescue values. The table + * is mounted select-first with a per-cell save, the one way it edits + * (objectstack#35827). * * The same sequence was driven in a real Chromium against the real * `@object-ui/fields` widgets (text / date / number) before this file was @@ -35,21 +37,24 @@ * * Test A is the control and must stay green: a BUILT-IN editor DOES commit on * focus loss. Without it, test C's negative ("Tab commits nothing") would pass - * just as well on a harness that cannot observe a commit at all. + * just as well on a harness that cannot observe a commit at all. (Under the + * select-first model Tab commits in every editor, so C is now a positive pin.) */ import { describe, it, expect, vi } from 'vitest'; import { fireEvent, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import '@testing-library/jest-dom'; import React from 'react'; -import { renderComponent } from './test-utils'; +import { openCellEditor, renderSelectFirstTable } from './test-utils'; // Module scope, not a hook — see object-ui/no-dynamic-import-in-test-hook. import '../renderers'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; const baseSchema = { type: 'data-table' as const, editable: true, - singleClickEdit: true, columns: [ { header: 'Name', accessorKey: 'name', editable: false }, { header: 'Qty', accessorKey: 'qty', type: 'number' }, @@ -88,12 +93,12 @@ describe('data-table — focus loss on a host-injected cell editor (objectui#685 // Proves the harness can observe a commit driven by focus loss at all, so // the negative results below are measurements and not dead probes. const onCellChange = vi.fn(); - const { container } = renderComponent({ ...baseSchema, onCellChange }); + const { container } = renderSelectFirstTable({ ...baseSchema, onCellChange }); const qtyCell = container.querySelectorAll('tbody td')[1] as HTMLElement; - fireEvent.click(qtyCell); + openCellEditor(qtyCell); - const input = qtyCell.querySelector('input') as HTMLInputElement; + const input = qtyCell.querySelector('input:not([data-slot="cell-type-catcher"])') as HTMLInputElement; expect(input).toBeTruthy(); fireEvent.change(input, { target: { value: '42' } }); fireEvent.blur(input); @@ -101,41 +106,27 @@ describe('data-table — focus loss on a host-injected cell editor (objectui#685 expect(onCellChange).toHaveBeenCalledWith(0, 'qty', '42', expect.anything()); }); - it('B) an injected editor stages every keystroke — the value is pending BEFORE any exit event', () => { - // This is the path the source audit could not see, and the reason Tab-out - // is not lossy: `stage` writes straight into `pendingChanges` while the - // editor is still open and still focused. - const { container, getByText, queryByText } = renderComponent({ - ...baseSchema, - renderCellEditor: stagingEditor, - }); + // B) pinned that a keystroke was staged into the "Save All" bar before any + // exit event. The bar is retired with the staged model (objectstack#35827); + // that the value staged while open is the one an exit commits is D below. - const qtyCell = container.querySelectorAll('tbody td')[1] as HTMLElement; - // Nothing pending yet — the toolbar's save affordance is the readout. - expect(queryByText(/Save All/i)).toBeNull(); - - fireEvent.click(qtyCell); - const editor = qtyCell.querySelector('[data-testid="injected-editor"]') as HTMLInputElement; - expect(editor).toBeTruthy(); - fireEvent.change(editor, { target: { value: 'TYPED' } }); - - // Still in edit mode, nothing committed — and the value is already staged. - expect(qtyCell.querySelector('[data-testid="injected-editor"]')).toBeTruthy(); - expect(getByText(/Save All/i)).toBeInTheDocument(); - }); - - it('C) tabbing out of an injected editor neither commits nor leaves edit mode', async () => { + it('C) Tab in an injected editor commits the typed value, as it does in a built-in one (objectstack#36023)', async () => { + // The staged arm left an injected editor open on Tab; under the select-first + // model, the one way the table edits (objectstack#35827), Tab is a commit + // key in every editor, so nothing typed is left behind in an open editor. const onCellChange = vi.fn(); + const onRowSave = vi.fn(() => Promise.resolve()); const outside = withOutsideTabStop(); try { - const { container } = renderComponent({ + const { container } = renderSelectFirstTable({ ...baseSchema, onCellChange, + onRowSave, renderCellEditor: stagingEditor, }); const qtyCell = container.querySelectorAll('tbody td')[1] as HTMLElement; - fireEvent.click(qtyCell); + openCellEditor(qtyCell); const editor = qtyCell.querySelector('[data-testid="injected-editor"]') as HTMLInputElement; fireEvent.change(editor, { target: { value: 'TYPED' } }); @@ -143,47 +134,42 @@ describe('data-table — focus loss on a host-injected cell editor (objectui#685 expect(document.activeElement).toBe(editor); await userEvent.tab(); - // Focus really left the editor … - expect(document.activeElement).not.toBe(editor); - // … and nothing committed: no exit, no onCellChange. This is the fact the - // corrected comment at `injectedEditorElRef` now states, and the reason - // the document-level pointerdown listener is still load-bearing. - expect(onCellChange).not.toHaveBeenCalled(); - expect(qtyCell.querySelector('[data-testid="injected-editor"]')).toBeTruthy(); + expect(onCellChange).toHaveBeenCalledWith(0, 'qty', 'TYPED', expect.anything()); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + expect((onRowSave.mock.calls[0] as unknown[])[1]).toEqual({ qty: 'TYPED' }); + await waitFor(() => expect(qtyCell.querySelector('[data-testid="injected-editor"]')).toBeNull()); } finally { outside.remove(); } }); - it('D) …and the typed value is still there — the outside pointer press commits exactly it', async () => { + it('D) a pointer press outside commits exactly what the injected editor staged', async () => { const onCellChange = vi.fn(); + const onRowSave = vi.fn(() => Promise.resolve()); const outside = withOutsideTabStop(); try { - const { container } = renderComponent({ + const { container } = renderSelectFirstTable({ ...baseSchema, onCellChange, + onRowSave, renderCellEditor: stagingEditor, }); const qtyCell = container.querySelectorAll('tbody td')[1] as HTMLElement; - fireEvent.click(qtyCell); + openCellEditor(qtyCell); const editor = qtyCell.querySelector('[data-testid="injected-editor"]') as HTMLInputElement; fireEvent.change(editor, { target: { value: 'TYPED' } }); - editor.focus(); - await userEvent.tab(); - // A pointer press truly outside is what exits the editor today. fireEvent.pointerDown(outside); await waitFor(() => expect(onCellChange).toHaveBeenCalledWith(0, 'qty', 'TYPED', expect.anything()), ); - // Edit mode is over and the cell reads back what was typed — nothing lost - // across the Tab-out. + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + expect((onRowSave.mock.calls[0] as unknown[])[1]).toEqual({ qty: 'TYPED' }); await waitFor(() => expect(qtyCell.querySelector('[data-testid="injected-editor"]')).toBeNull(), ); - expect(qtyCell.textContent).toContain('TYPED'); } finally { outside.remove(); } diff --git a/ui/packages/components/src/__tests__/data-table-inline-edit.impossibleDay-10625.test.tsx b/ui/packages/components/src/__tests__/data-table-inline-edit.impossibleDay-10625.test.tsx index 4b1cc55b1d9..62415979b72 100644 --- a/ui/packages/components/src/__tests__/data-table-inline-edit.impossibleDay-10625.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-inline-edit.impossibleDay-10625.test.tsx @@ -20,23 +20,26 @@ * `DateField` / `DateTimeField`'s face: an empty control, `aria-invalid`, and a * notice naming the stored string, described by the control. * - * Rendered through the real registry (`renderComponent`), with no host - * `renderCellEditor`, which is exactly the path a schema-authored editable - * `data-table` node takes. Assertions hold in every timezone: a real datetime + * Rendered through the real registry inside a select-first host with a + * per-cell save (`renderSelectFirstTable`, the one way the table edits since + * objectstack#35827), with no host `renderCellEditor`: the table's own + * built-in editors. Assertions hold in every timezone: a real datetime * is judged by the instant it reads back as, never by a hard-coded wall clock. */ import { describe, it, expect, vi } from 'vitest'; import { fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom'; -import { renderComponent } from './test-utils'; +import { openCellEditor, renderSelectFirstTable } from './test-utils'; // Registers the renderers at module scope (object-ui/no-dynamic-import-in-test-hook). import '../renderers'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; function tableWith(type: 'date' | 'datetime', stored: string, onCellChange = vi.fn()) { const schema = { type: 'data-table' as const, editable: true, - singleClickEdit: true, columns: [ { header: 'Name', accessorKey: 'name', editable: false }, { header: 'When', accessorKey: 'when', type }, @@ -44,10 +47,10 @@ function tableWith(type: 'date' | 'datetime', stored: string, onCellChange = vi. data: [{ id: '1', name: 'Row one', when: stored }], onCellChange, } as any; - const { container } = renderComponent(schema); + const { container } = renderSelectFirstTable(schema); const cell = container.querySelectorAll('tbody td')[1] as HTMLElement; - fireEvent.click(cell); - const input = cell.querySelector('input') as HTMLInputElement; + openCellEditor(cell); + const input = container.querySelector('td[data-editing-cell] input') as HTMLInputElement; return { cell, input, onCellChange }; } diff --git a/ui/packages/components/src/__tests__/data-table-inline-edit.test.tsx b/ui/packages/components/src/__tests__/data-table-inline-edit.test.tsx index 6914f116865..f775d2a5ad4 100644 --- a/ui/packages/components/src/__tests__/data-table-inline-edit.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-inline-edit.test.tsx @@ -17,21 +17,25 @@ * B) The inline editor was a hardcoded text for every field type, so * date columns could only be typed by hand. A `type: 'date'` column must * render a native date picker (). + * + * Mounted select-first with a per-cell save, the one way the table edits + * (objectstack#35827): a click selects a cell and a double-click opens it. */ import { describe, it, expect, vi } from 'vitest'; -import { fireEvent, waitFor } from '@testing-library/react'; +import { fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom'; -import React from 'react'; -import { renderComponent } from './test-utils'; +import { openCellEditor, renderSelectFirstTable } from './test-utils'; // Registers the renderers at module scope, NOT inside a `beforeAll` — there the // cold transform is billed to `hookTimeout`, which is why this carried a raised // timeout. See object-ui/no-dynamic-import-in-test-hook (objectui#3010/#3021). import '../renderers'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; const editableSchema = { type: 'data-table' as const, editable: true, - singleClickEdit: true, columns: [ { header: '工序', accessorKey: 'name', editable: false }, { header: '实际开始时间', accessorKey: 'actual_start', type: 'date' }, @@ -43,7 +47,7 @@ const editableSchema = { describe('data-table — inline edit is per-row usable', () => { it('A) clicking an editable cell does NOT fire onRowClick (no detail drawer)', () => { const onRowClick = vi.fn(); - const { container } = renderComponent({ ...editableSchema, onRowClick }); + const { container } = renderSelectFirstTable({ ...editableSchema, onRowClick }); const cell = Array.from(container.querySelectorAll('td')).find((td) => td.textContent?.includes('将军柱下料') @@ -60,38 +64,30 @@ describe('data-table — inline edit is per-row usable', () => { expect(onRowClick).not.toHaveBeenCalled(); }); - it('A2) clicking a readonly (editable:false) cell still fires onRowClick (sanity)', () => { - const onRowClick = vi.fn(); - const { container } = renderComponent({ ...editableSchema, onRowClick }); - - const nameCell = Array.from(container.querySelectorAll('tbody td')).find((td) => - td.textContent?.includes('将军柱下料') - ) as HTMLElement; - fireEvent.click(nameCell); - - expect(onRowClick).toHaveBeenCalledTimes(1); - }); + // A2) pinned the staged arm's split, where a click on a read-only cell of an + // editable table opened the record. Select-first, a click selects any cell + // and opens nothing (objectstack#35827); that is data-table-select-first-35684. it('B) a date column renders a native date picker, not a free-text input', () => { - const { container } = renderComponent(editableSchema); + const { container } = renderSelectFirstTable(editableSchema); const cells = container.querySelectorAll('tbody td'); const dateCell = cells[1] as HTMLElement; // 实际开始时间 - fireEvent.click(dateCell); + openCellEditor(dateCell); - const input = dateCell.querySelector('input') as HTMLInputElement; + const input = container.querySelector('td[data-editing-cell] input') as HTMLInputElement; expect(input).toBeTruthy(); expect(input.type).toBe('date'); }); it('B2) a number column renders a numeric input', () => { - const { container } = renderComponent(editableSchema); + const { container } = renderSelectFirstTable(editableSchema); const cells = container.querySelectorAll('tbody td'); const qtyCell = cells[2] as HTMLElement; // 报工数量 - fireEvent.click(qtyCell); + openCellEditor(qtyCell); - const input = qtyCell.querySelector('input') as HTMLInputElement; + const input = container.querySelector('td[data-editing-cell] input') as HTMLInputElement; expect(input).toBeTruthy(); expect(input.type).toBe('number'); }); @@ -100,13 +96,13 @@ describe('data-table — inline edit is per-row usable', () => { // Regression: switching cells dropped the in-flight value because only // Enter/Escape committed the edit. Blur must save it too. const onCellChange = vi.fn(); - const { container } = renderComponent({ ...editableSchema, onCellChange }); + const { container } = renderSelectFirstTable({ ...editableSchema, onCellChange }); const cells = container.querySelectorAll('tbody td'); const qtyCell = cells[2] as HTMLElement; // 报工数量 - fireEvent.click(qtyCell); + openCellEditor(qtyCell); - const input = qtyCell.querySelector('input') as HTMLInputElement; + const input = container.querySelector('td[data-editing-cell] input') as HTMLInputElement; fireEvent.change(input, { target: { value: '42' } }); // Click away (focus leaves the editor) — value must persist, not vanish. fireEvent.blur(input); @@ -117,13 +113,13 @@ describe('data-table — inline edit is per-row usable', () => { it('C2) pressing Escape discards the edit and does NOT commit on blur', () => { const onCellChange = vi.fn(); - const { container } = renderComponent({ ...editableSchema, onCellChange }); + const { container } = renderSelectFirstTable({ ...editableSchema, onCellChange }); const cells = container.querySelectorAll('tbody td'); const qtyCell = cells[2] as HTMLElement; // 报工数量 - fireEvent.click(qtyCell); + openCellEditor(qtyCell); - const input = qtyCell.querySelector('input') as HTMLInputElement; + const input = container.querySelector('td[data-editing-cell] input') as HTMLInputElement; fireEvent.change(input, { target: { value: '99' } }); fireEvent.keyDown(input, { key: 'Escape' }); // The ensuing blur must not resurrect the cancelled value. @@ -132,87 +128,11 @@ describe('data-table — inline edit is per-row usable', () => { expect(onCellChange).not.toHaveBeenCalled(); }); - it('D) a failed save surfaces the server error and keeps the pending change', async () => { - // Regression: a rejected save (e.g. a 400 validation failure) was swallowed - // with only console.error — the toolbar stayed stuck, the cell kept the - // unsaved value, and the author got no feedback. The reason must surface. - const onBatchSave = vi.fn().mockRejectedValue({ - // Shape the ObjectStack adapter decorates onto thrown errors. - details: { message: 'Invalid task status transition.' }, - }); - const { container, getByText } = renderComponent({ ...editableSchema, onBatchSave }); - - // Stage an edit. - const cells = container.querySelectorAll('tbody td'); - const qtyCell = cells[2] as HTMLElement; // 报工数量 - fireEvent.click(qtyCell); - const input = qtyCell.querySelector('input') as HTMLInputElement; - fireEvent.change(input, { target: { value: '42' } }); - fireEvent.blur(input); - - // Save All → saveBatch → onBatchSave rejects. - fireEvent.click(getByText(/Save All/i)); - expect(onBatchSave).toHaveBeenCalledTimes(1); - - // The server's reason is surfaced, not swallowed. - await waitFor(() => - expect(container.textContent).toContain('Invalid task status transition'), - ); - // And the pending change is kept (Save All still offered) — no silent drop - // and no phantom "saved" state. - expect(getByText(/Save All/i)).toBeInTheDocument(); - }); - - it('D2) a successful save does NOT show a save-failure message', async () => { - const onBatchSave = vi.fn().mockResolvedValue(undefined); - const { container, getByText } = renderComponent({ ...editableSchema, onBatchSave }); - - const cells = container.querySelectorAll('tbody td'); - const qtyCell = cells[2] as HTMLElement; - fireEvent.click(qtyCell); - const input = qtyCell.querySelector('input') as HTMLInputElement; - fireEvent.change(input, { target: { value: '7' } }); - fireEvent.blur(input); - - fireEvent.click(getByText(/Save All/i)); - await waitFor(() => expect(onBatchSave).toHaveBeenCalledTimes(1)); - - expect(container.textContent).not.toContain('Save failed'); - }); - - it('E) a staged editor (e.g. a lookup picker) exits edit mode after Save All', async () => { - // Regression: relational pickers (lookup/master_detail/user/owner) keep their - // widget open on pick — they `stage` the value rather than commit-and-close. - // saveBatch cleared pendingChanges but never cleared `editingCell`, so after - // 全部保存 the saved cell stayed stuck showing the picker widget instead of - // reverting to the resolved display value. Save All must close any open editor. - const onBatchSave = vi.fn().mockResolvedValue(undefined); - // A host-injected editor that mimics a lookup: picking a value STAGES it and - // deliberately keeps the editor open (no commit/close). - const renderCellEditor = ({ column, stage }: any) => - column.accessorKey === 'qty' ? ( - - ) : null; - - const { container, getByText, getByTestId, queryByTestId } = renderComponent({ - ...editableSchema, - onBatchSave, - renderCellEditor, - }); - - const cells = container.querySelectorAll('tbody td'); - const qtyCell = cells[2] as HTMLElement; // uses the injected picker editor - fireEvent.click(qtyCell); - - // Editor is open; pick a value — it stages and stays open (no close). - fireEvent.click(getByTestId('picker')); - expect(queryByTestId('picker')).toBeInTheDocument(); - - // Save All persists the staged value AND must exit edit mode. - fireEvent.click(getByText(/Save All/i)); - await waitFor(() => expect(onBatchSave).toHaveBeenCalledTimes(1)); - await waitFor(() => expect(queryByTestId('picker')).not.toBeInTheDocument()); - }); + // D, D2 and E pinned the staged "Save All" bar: a rejected batch keeping its + // pending change, a resolved batch showing no failure, and Save All closing a + // picker that staged without closing. The bar is retired (objectstack#35827). + // Each cell now saves on commit: a refused save keeping the typed value and + // saying the server's reason on the cell is data-table-autosave-35685 (2); + // an injected editor that stages and stays open being committed by a press + // outside is data-table-injected-editor-focus-6859 (D). }); diff --git a/ui/packages/components/src/__tests__/data-table-keyboard-navigation-11068.test.tsx b/ui/packages/components/src/__tests__/data-table-keyboard-navigation-11068.test.tsx index 787123b9c79..842593c4325 100644 --- a/ui/packages/components/src/__tests__/data-table-keyboard-navigation-11068.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-keyboard-navigation-11068.test.tsx @@ -20,20 +20,22 @@ * 2. ON: the data cells are ONE roving Tab stop; Tab enters them once and the * next Tab leaves; the arrow keys, Home / End and Ctrl+Home / Ctrl+End * move focus; the stop follows focus and survives a shorter page. - * 3. ON, editable: Enter still opens the focused cell, the editor keeps the - * arrows, and an edit ended with Enter or Escape hands focus back to its - * cell, so the arrows carry on. + * 3. ON, editable: retired with the staged arm (objectstack#35827); an + * editable table is select-first, pinned in data-table-keys-35687. * * Every "unchanged" reading has a lit control that moves on the same probe. */ import React from 'react'; import { describe, it, expect, afterEach } from 'vitest'; -import { render, fireEvent, cleanup, waitFor, act } from '@testing-library/react'; +import { render, fireEvent, cleanup, act } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; 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'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; afterEach(cleanup); @@ -213,69 +215,12 @@ describe('data-table `keyboardNavigation` ON — one roving Tab stop the arrows /* ── 3. On, editable ─────────────────────────────────────────────────────── */ -describe('data-table `keyboardNavigation` ON with `editable` — Enter edits, and focus comes back (objectui#11068)', () => { - const editableNav = { keyboardNavigation: true, editable: true }; +// Section 3 pinned the staged arm: an editable table with no select-first host, +// where Enter on a focused cell opened its editor and an Enter or Escape handed +// focus back to the cell. That arm is retired (objectstack#35827); an editable +// table is select-first, which turns the navigation on by itself. Its Enter, +// commit and Escape keys, with focus kept on the cell, are pinned in +// data-table-keys-35687 ("Enter commits and stays on the cell…", "Escape +// cancels and keeps the cell selected…") and data-table-select-first-35684 +// ("Enter on the selected cell opens the editor on the value"). - it('Enter opens the focused cell, the editor keeps the arrows, and Enter hands focus back to the cell', async () => { - const { container } = renderTable(editableNav); - const cell = cellAt(container, 0, 1); - cell.focus(); - - press('Enter'); - const input = await waitFor(() => { - const el = cell.querySelector('input'); - expect(el).not.toBeNull(); - return el as HTMLInputElement; - }); - expect(document.activeElement).toBe(input); - - // The editor's own keys: the caret moves, the cell does not. - fireEvent.keyDown(input, { key: 'ArrowDown' }); - fireEvent.keyDown(input, { key: 'ArrowRight' }); - expect(cell.querySelector('input')).toBe(input); - - fireEvent.change(input, { target: { value: 'Pending' } }); - fireEvent.keyDown(input, { key: 'Enter' }); - await waitFor(() => expect(cell.querySelector('input')).toBeNull()); - expect(cell).toHaveTextContent('Pending'); - await waitFor(() => expect(document.activeElement).toBe(cell)); - - // …so the arrows carry on from the cell that was just edited. - press('ArrowDown'); - expect(document.activeElement).toBe(cellAt(container, 1, 1)); - }); - - it('Escape cancels the edit and hands focus back to the cell too', async () => { - const { container } = renderTable(editableNav); - const cell = cellAt(container, 2, 2); - cell.focus(); - press('Enter'); - const input = await waitFor(() => { - const el = cell.querySelector('input'); - expect(el).not.toBeNull(); - return el as HTMLInputElement; - }); - fireEvent.change(input, { target: { value: 'Nobody' } }); - fireEvent.keyDown(input, { key: 'Escape' }); - await waitFor(() => expect(cell.querySelector('input')).toBeNull()); - expect(cell).toHaveTextContent('Cy'); - await waitFor(() => expect(document.activeElement).toBe(cell)); - press('ArrowLeft'); - expect(document.activeElement).toBe(cellAt(container, 2, 1)); - }); - - it('LIT CONTROL — with the flag off, the same Enter-commit leaves focus on , where no arrow reaches a cell', async () => { - const { container } = renderTable({ editable: true }); - const cell = cellAt(container, 0, 1); - cell.focus(); - press('Enter'); - const input = await waitFor(() => { - const el = cell.querySelector('input'); - expect(el).not.toBeNull(); - return el as HTMLInputElement; - }); - fireEvent.keyDown(input, { key: 'Enter' }); - await waitFor(() => expect(cell.querySelector('input')).toBeNull()); - expect(document.activeElement).toBe(document.body); - }); -}); 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 index 6b21e39e189..0fa814f0716 100644 --- a/ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx @@ -68,6 +68,7 @@ function renderTable(extra: Record = {}, selection: GridCellSel searchable: false, pagination: false, onCellChange, + onRowSave: () => Promise.resolve(), ...extra, }; const utils = render( diff --git a/ui/packages/components/src/__tests__/data-table-noop-edit-11816.test.tsx b/ui/packages/components/src/__tests__/data-table-noop-edit-11816.test.tsx index 5ca70db54f3..d7e397b4e62 100644 --- a/ui/packages/components/src/__tests__/data-table-noop-edit-11816.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-noop-edit-11816.test.tsx @@ -9,23 +9,22 @@ /** * objectui#11816 — inline edit on an `editable` data-table: * - * 1. a row counts as modified only when a value differs from the one it - * loaded with. Every commit used to be staged, so opening a cell and - * leaving it as it was showed "1 row modified · Save All (1)"; - * 2. staging the loaded value back un-marks the row; - * 3. the trailing column that only ever holds a modified row's cancel/save - * pair is not headed "Actions" — `ObjectGrid` already draws a host column - * of that name beside it — and the "Actions" label takes the data-column - * header styling instead of the cell's larger default type. + * 1. a commit saves only when a value differs from the one the row loaded + * with. Every commit used to be staged, so opening a cell and leaving it + * as it was showed "1 row modified · Save All (1)"; under the per-cell + * save (objectstack#35827) such a commit sends no save; + * 2. the "Actions" label takes the data-column header styling instead of the + * cell's larger default type. (The staged arm's edit-only column, headed by + * its own name, is retired with that arm.) * - * Each case drives the real renderer through the user's own gestures and reads - * the toolbar the user reads. + * Each case drives the real renderer, select-first, through the user's own + * gestures and reads the saves it sends. */ import { describe, it, expect, vi } from 'vitest'; -import { fireEvent, screen } from '@testing-library/react'; +import { act, fireEvent, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; -import { renderComponent } from './test-utils'; +import { openCellEditor, renderSelectFirstTable } from './test-utils'; // Registers the renderers at module scope, NOT inside a `beforeAll` // (object-ui/no-dynamic-import-in-test-hook, objectui#3010/#3021). import '../renderers'; @@ -66,9 +65,8 @@ const makeSchema = (extra: Record = {}) => ({ type: 'data-table' as const, editable: true, - singleClickEdit: true, rowActions: true, - onBatchSave: vi.fn(), + onRowSave: vi.fn(() => Promise.resolve()), renderCellEditor, columns: [ { header: 'Name', accessorKey: 'name' }, @@ -90,99 +88,107 @@ const NOTE = 2; const TAGS = 3; const PRIORITY = 4; -/** What the toolbar says about staged edits; `null` when nothing is staged. */ -const modified = () => screen.queryByText(/rows? modified/)?.textContent ?? null; +/** Renders the table select-first; `saves()` is how many row saves it sent. */ +function renderTable(extra: Record = {}) { + const schema = makeSchema(extra); + const utils = renderSelectFirstTable(schema); + const saves = () => (schema.onRowSave as ReturnType).mock.calls.length; + const lastSave = () => (schema.onRowSave as ReturnType).mock.calls.at(-1)?.[1]; + return { ...utils, saves, lastSave }; +} /** Open `td`'s built-in editor, run `edit` on its input, then blur it. */ -function editBuiltIn(td: HTMLElement, edit: (input: HTMLInputElement) => void = () => {}) { - fireEvent.click(td); - const input = td.querySelector('input') as HTMLInputElement; +async function editBuiltIn(td: HTMLElement, edit: (input: HTMLInputElement) => void = () => {}) { + openCellEditor(td); + const input = document.querySelector('td[data-editing-cell] input') as HTMLInputElement; expect(input).toBeTruthy(); edit(input); fireEvent.blur(input); + await act(async () => {}); } -describe('data-table inline edit — a row is modified only by a real change (objectui#11816)', () => { - it('a text cell opened and left as it was stages nothing', () => { - const { container } = renderComponent(makeSchema()); - editBuiltIn(cell(container, NAME)); - expect(modified()).toBeNull(); - expect(screen.queryByText(/Save All/)).toBeNull(); +describe('data-table inline edit — a commit saves only a real change (objectui#11816)', () => { + // Under the staged model a no-op commit marked the row modified; now each + // commit saves at once (objectstack#35827), so a no-op commit must send no + // save at all. + it('a text cell opened and left as it was saves nothing', async () => { + const { container, saves } = renderTable(); + await editBuiltIn(cell(container, NAME)); + expect(saves()).toBe(0); }); - it('an empty cell left empty stages nothing (the editor seeds it with an empty string)', () => { - const { container } = renderComponent(makeSchema()); - editBuiltIn(cell(container, NOTE), (input) => expect(input.value).toBe('')); - expect(modified()).toBeNull(); + it('an empty cell left empty saves nothing (the editor seeds it with an empty string)', async () => { + const { container, saves } = renderTable(); + await editBuiltIn(cell(container, NOTE), (input) => expect(input.value).toBe('')); + expect(saves()).toBe(0); }); - it('a number retyped as the same numeral stages nothing; a different number does', () => { - const { container } = renderComponent(makeSchema()); + it('a number retyped as the same numeral saves nothing; a different number does', async () => { + const { container, saves, lastSave } = renderTable(); // Through `7` first so the editor really holds the input's STRING `'5'`. - editBuiltIn(cell(container, QTY), (input) => { + await editBuiltIn(cell(container, QTY), (input) => { fireEvent.change(input, { target: { value: '7' } }); fireEvent.change(input, { target: { value: '5' } }); }); - expect(modified()).toBeNull(); + expect(saves()).toBe(0); - editBuiltIn(cell(container, QTY), (input) => fireEvent.change(input, { target: { value: '6' } })); - expect(modified()).toBe('1 row modified'); + await editBuiltIn(cell(container, QTY), (input) => fireEvent.change(input, { target: { value: '6' } })); + expect(saves()).toBe(1); + expect(Number((lastSave() as { qty: unknown }).qty)).toBe(6); }); - it('staging the loaded value back un-marks the row', () => { - const { container } = renderComponent(makeSchema()); - editBuiltIn(cell(container, QTY), (input) => fireEvent.change(input, { target: { value: '6' } })); - expect(modified()).toBe('1 row modified'); - - editBuiltIn(cell(container, QTY), (input) => fireEvent.change(input, { target: { value: '5' } })); - expect(modified()).toBeNull(); - expect(screen.queryByText(/Save All/)).toBeNull(); - }); - - it('a discrete editor committing the loaded code stages nothing', () => { - const { container } = renderComponent(makeSchema()); - fireEvent.click(cell(container, PRIORITY)); + it('a discrete editor committing the loaded code saves nothing', async () => { + const { container, saves } = renderTable(); + openCellEditor(cell(container, PRIORITY)); fireEvent.click(screen.getByTestId('pick-high')); + await act(async () => {}); expect(screen.queryByTestId('pick-high')).toBeNull(); // committed and closed - expect(modified()).toBeNull(); + expect(saves()).toBe(0); }); - it('an injected editor left by a click outside stages nothing (the reported gesture)', () => { - const { container } = renderComponent(makeSchema()); - fireEvent.click(cell(container, PRIORITY)); + it('an injected editor left by a click outside saves nothing (the reported gesture)', async () => { + const { container, saves } = renderTable(); + openCellEditor(cell(container, PRIORITY)); expect(screen.getByTestId('pick-high')).toBeInTheDocument(); fireEvent.pointerDown(document.body); + await act(async () => {}); expect(screen.queryByTestId('pick-high')).toBeNull(); // left edit mode - expect(modified()).toBeNull(); + expect(saves()).toBe(0); }); - it('a multi-value set in another order is the same value; a smaller set is not', () => { - const { container } = renderComponent(makeSchema()); - fireEvent.click(cell(container, TAGS)); + it('a multi-value set in another order is the same value; a smaller set is not', async () => { + const { container, saves, lastSave } = renderTable(); + openCellEditor(cell(container, TAGS)); fireEvent.click(screen.getByTestId('tags-reorder')); - expect(modified()).toBeNull(); + fireEvent.pointerDown(document.body); + await act(async () => {}); + expect(saves()).toBe(0); + + openCellEditor(cell(container, TAGS)); fireEvent.click(screen.getByTestId('tags-drop')); - expect(modified()).toBe('1 row modified'); - fireEvent.click(screen.getByTestId('tags-restore')); - expect(modified()).toBeNull(); + fireEvent.pointerDown(document.body); + await act(async () => {}); + expect(saves()).toBe(1); + expect(lastSave()).toEqual({ tags: ['a'] }); }); + + // "staging the loaded value back un-marks the row" pinned the staged bar's + // count; with no staging there is no mark to take back. }); describe('data-table inline edit — the edit column is not a second "Actions" (objectui#11816)', () => { - it('the save-only column is headed by its own name, not "Actions"', () => { - renderComponent(makeSchema()); - expect(screen.queryByRole('columnheader', { name: 'Actions' })).toBeNull(); - expect(screen.getByRole('columnheader', { name: 'Edit' })).toBeInTheDocument(); - }); + // "the save-only column is headed by its own name" pinned the staged arm's + // edit-only column; select-first draws none (objectstack#35827), pinned in + // data-table-select-first-35684 "no edit-only column, ever". it('a column that can hold a row menu stays "Actions"', () => { - renderComponent(makeSchema({ onRowEdit: () => {} })); + renderTable({ onRowEdit: () => {} }); expect(screen.getByRole('columnheader', { name: 'Actions' })).toBeInTheDocument(); expect(screen.queryByRole('columnheader', { name: 'Edit' })).toBeNull(); }); it('the "Actions" label is set in the data-column header type', () => { - renderComponent(makeSchema({ editable: false, onRowEdit: () => {} })); + renderTable({ editable: false, onRowEdit: () => {} }); const label = (name: string) => screen.getByRole('columnheader', { name }).querySelector('span') as HTMLElement; // 12px since objectstack#36047 (a header is secondary type). diff --git a/ui/packages/components/src/__tests__/data-table-pending-by-record-12310.test.tsx b/ui/packages/components/src/__tests__/data-table-pending-by-record-12310.test.tsx index ee00e20823b..a386b28a2ec 100644 --- a/ui/packages/components/src/__tests__/data-table-pending-by-record-12310.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-pending-by-record-12310.test.tsx @@ -13,36 +13,46 @@ * The table used to key all three by page-local row index, so a re-read that * handed the rows over in a new order drew a kept edit on another record, and * Save All wrote it there. The end-to-end pins (the card's sequence through - * the real `ObjectGrid`, the invalidation bus, a page change) live in - * `plugin-grid`'s `inlineEditPendingKeyedByRecord-12310.test.tsx`; these pin - * the table's own half: what Save All hands over, an id-less row, a record a - * re-read drops, and an editor left open across a reorder. + * the real `ObjectGrid`, the invalidation bus, a page change) pinned Save All + * and went with it. + * + * The staged model is retired (objectstack#35827): each committed cell saves + * at once through `onRowSave`, so no edit is kept pending across a re-read and + * there is no Save All to hand rows over. What is left of this card's table + * half is the open editor: it stays on its record across a reorder and commits + * there. A saved row keeping its place in a client sort is + * data-table-autosave-35685 (6). */ import { describe, it, expect, vi } from 'vitest'; -import { fireEvent, render, waitFor, within } from '@testing-library/react'; +import { fireEvent, render, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; import { ComponentRegistry } from '@object-ui/core'; +import { GridCellSelectionProvider } from '../context/gridCellSelection'; // Registers the renderers at module scope, NOT inside a `beforeAll`; see // object-ui/no-dynamic-import-in-test-hook (objectui#3010/#3021). import '../renderers'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; const columns = [ { header: 'Task', accessorKey: 'name', editable: false }, { header: 'Estimate', accessorKey: 'qty', type: 'number' }, ]; -type Entry = { rowIndex: number; changes: Record; row: any }; - function mount(data: any[], extra: Record = {}) { const Table = ComponentRegistry.get('data-table')!; - const schemaFor = (rows: any[]) => - ({ type: 'data-table', editable: true, singleClickEdit: true, columns, data: rows, ...extra }) as any; - const utils = render(); + const tree = (rows: any[]) => ( + +
+ + ); + const utils = render(tree(data)); return { ...utils, /** Hand the table a new read of the rows, the way a host re-read does. */ - reread: (rows: any[]) => utils.rerender(
), + reread: (rows: any[]) => utils.rerender(tree(rows)), }; } @@ -52,126 +62,39 @@ const rowOf = (container: HTMLElement, name: string) => const estimateCell = (container: HTMLElement, name: string) => rowOf(container, name).querySelectorAll('td')[1] as HTMLElement; -/** Stage a new Estimate on the row named `name`. */ -function stage(container: HTMLElement, name: string, value: string) { - const cell = estimateCell(container, name); - fireEvent.click(cell); - const input = cell.querySelector('input') as HTMLInputElement; - fireEvent.change(input, { target: { value } }); - fireEvent.blur(input); -} +const editorIn = (cell: HTMLElement) => + cell.matches('[data-editing-cell]') ? (cell.querySelector('input') as HTMLInputElement | null) : null; const names = (container: HTMLElement) => Array.from(container.querySelectorAll('tbody tr')).map((tr) => tr.querySelectorAll('td')[0]?.textContent); -describe('data-table keeps each pending edit on its record (objectui#12310)', () => { - it('a re-read in a new order draws each edit on its record, and Save All hands each over with its own row', async () => { - const onBatchSave = vi.fn(async (_entries: Entry[]) => undefined); - const { container, getByText, reread } = mount( - [ - { id: 'a', name: 'Alpha', qty: 10 }, - { id: 'b', name: 'Bravo', qty: 20 }, - { id: 'c', name: 'Charlie', qty: 30 }, - ], - { onBatchSave }, - ); - stage(container, 'Bravo', '21'); - stage(container, 'Alpha', '11'); - - reread([ - { id: 'c', name: 'Charlie', qty: 30 }, - { id: 'a', name: 'Alpha', qty: 10 }, - { id: 'b', name: 'Bravo', qty: 20 }, - ]); - expect(names(container)).toEqual(['Charlie', 'Alpha', 'Bravo']); - expect(estimateCell(container, 'Charlie')).toHaveTextContent('30'); - expect(estimateCell(container, 'Alpha')).toHaveTextContent('11'); - expect(estimateCell(container, 'Bravo')).toHaveTextContent('21'); - - fireEvent.click(getByText(/Save All/)); - await waitFor(() => expect(onBatchSave).toHaveBeenCalledTimes(1)); - const entries = onBatchSave.mock.calls[0][0]; - // `rowIndex` is each record's index in the rows held when Save All ran. - expect(entries.map((e) => [e.row.id, e.rowIndex, e.changes]).sort()).toEqual([ - ['a', 1, { qty: '11' }], - ['b', 2, { qty: '21' }], - ]); - }); - - it('a re-read that drops a record keeps its edit pending, and Save All hands it over with the row it was staged on', async () => { - const bravo = { id: 'b', name: 'Bravo', qty: 20 }; - const onBatchSave = vi.fn(async (entries: Entry[]) => ({ - failed: entries - .filter((e) => e.row.id === 'b') - .map((e) => ({ rowIndex: e.rowIndex, error: new Error('Bravo was refused') })), - })); - const { container, getByText, reread } = mount( - [{ id: 'a', name: 'Alpha', qty: 10 }, bravo, { id: 'c', name: 'Charlie', qty: 30 }], - { onBatchSave }, - ); - stage(container, 'Bravo', '21'); - - reread([{ id: 'a', name: 'Alpha', qty: 10 }, { id: 'c', name: 'Charlie', qty: 30 }]); - // Kept, counted, and drawn on no other row. - expect(getByText(/1 row modified/)).toBeInTheDocument(); - expect(container.querySelector('tbody')?.textContent).not.toContain('21'); - - fireEvent.click(getByText(/Save All/)); - await waitFor(() => expect(container.textContent).toContain('Bravo was refused')); - // The row it was typed on, and an index no held row carries. - expect(onBatchSave.mock.calls[0][0]).toEqual([{ rowIndex: -1, changes: { qty: '21' }, row: bravo }]); - expect(getByText(/1 row modified/)).toBeInTheDocument(); - - // When the record comes back, the kept edit and its failure are drawn on it. - reread([{ id: 'b', name: 'Bravo', qty: 20 }, { id: 'a', name: 'Alpha', qty: 10 }, { id: 'c', name: 'Charlie', qty: 30 }]); - expect(estimateCell(container, 'Bravo')).toHaveTextContent('21'); - expect(rowOf(container, 'Bravo').className).toContain('bg-destructive/10'); - expect(rowOf(container, 'Alpha').className).not.toContain('bg-destructive/10'); - }); - - it("an open editor stays on its record across a reorder, and commits there", async () => { - const onBatchSave = vi.fn(async (_entries: Entry[]) => undefined); - const { container, getByText, reread } = mount( +describe('data-table keeps an open editor on its record (objectui#12310)', () => { + it('an open editor stays on its record across a reorder, and commits there', async () => { + const onRowSave = vi.fn(async (_i: number, _changes: Record, _row?: unknown) => undefined); + const { container, reread } = mount( [{ id: 'a', name: 'Alpha', qty: 10 }, { id: 'b', name: 'Bravo', qty: 20 }], - { onBatchSave }, + { onRowSave }, ); const cell = estimateCell(container, 'Alpha'); fireEvent.click(cell); - fireEvent.change(cell.querySelector('input') as HTMLInputElement, { target: { value: '11' } }); + fireEvent.doubleClick(cell); + fireEvent.change(editorIn(cell) as HTMLInputElement, { target: { value: '11' } }); reread([{ id: 'b', name: 'Bravo', qty: 20 }, { id: 'a', name: 'Alpha', qty: 10 }]); expect(names(container)).toEqual(['Bravo', 'Alpha']); - expect(estimateCell(container, 'Bravo').querySelector('input')).toBeNull(); - const input = estimateCell(container, 'Alpha').querySelector('input') as HTMLInputElement; + expect(editorIn(estimateCell(container, 'Bravo'))).toBeNull(); + const input = editorIn(estimateCell(container, 'Alpha')); expect(input).not.toBeNull(); - fireEvent.keyDown(input, { key: 'Enter' }); + fireEvent.keyDown(input as HTMLInputElement, { key: 'Enter' }); - expect(estimateCell(container, 'Alpha')).toHaveTextContent('11'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + expect(onRowSave.mock.calls[0][1]).toEqual({ qty: '11' }); + expect(onRowSave.mock.calls[0][2]).toEqual(expect.objectContaining({ id: 'a' })); expect(estimateCell(container, 'Bravo')).toHaveTextContent('20'); - fireEvent.click(getByText(/Save All/)); - await waitFor(() => expect(onBatchSave).toHaveBeenCalledTimes(1)); - expect(onBatchSave.mock.calls[0][0]).toEqual([ - { rowIndex: 1, changes: { qty: '11' }, row: expect.objectContaining({ id: 'a' }) }, - ]); }); - it("an id-less row's edit follows the row object through a client-side sort", async () => { - const alpha = { name: 'Alpha', qty: 10 }; - const bravo = { name: 'Bravo', qty: 20 }; - const onBatchSave = vi.fn(async (_entries: Entry[]) => undefined); - const { container, getByText } = mount([alpha, bravo], { onBatchSave }); - stage(container, 'Alpha', '11'); - - // Task ascending, then descending: Bravo above Alpha. - const header = within(container.querySelector('thead') as HTMLElement).getByText('Task'); - fireEvent.click(header); - fireEvent.click(header); - expect(names(container)).toEqual(['Bravo', 'Alpha']); - expect(estimateCell(container, 'Alpha')).toHaveTextContent('11'); - expect(estimateCell(container, 'Bravo')).toHaveTextContent('20'); - - fireEvent.click(getByText(/Save All/)); - await waitFor(() => expect(onBatchSave).toHaveBeenCalledTimes(1)); - expect(onBatchSave.mock.calls[0][0]).toEqual([{ rowIndex: 1, changes: { qty: '11' }, row: alpha }]); - }); + // The other pins held what Save All handed over after a re-read in a new + // order, after a re-read that dropped a record, and for an id-less row + // through a client sort. With no pending edits and no Save All + // (objectstack#35827) there is nothing kept across a re-read to hand over. }); diff --git a/ui/packages/components/src/__tests__/data-table-refusal-cells-27520.test.tsx b/ui/packages/components/src/__tests__/data-table-refusal-cells-27520.test.tsx deleted file mode 100644 index 937a3bd1a20..00000000000 --- a/ui/packages/components/src/__tests__/data-table-refusal-cells-27520.test.tsx +++ /dev/null @@ -1,160 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectstack-ai/objectstack#27520 (row 6) — a refused inline save says WHY, - * WHERE: the save bar says every reason whole, one line each, and the cells - * the refusal names are marked. - * - * The server refuses a row field by field (`VALIDATION_FAILED` with one - * `fields[]` entry per failed rule). The save bar used to cut that to one - * truncated line, the rest only in a native tooltip, and no cell said which - * value was wrong. - */ -import { describe, it, expect, vi } from 'vitest'; -import { fireEvent, waitFor, within } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import { renderComponent } from './test-utils'; -// Registers the renderers at module scope, NOT inside a `beforeAll`; see -// object-ui/no-dynamic-import-in-test-hook (objectui#3010/#3021). -import '../renderers'; - -const schema = { - type: 'data-table' as const, - editable: true, - singleClickEdit: true, - columns: [ - { header: 'Title', accessorKey: 'title' }, - { header: 'Estimate', accessorKey: 'estimate', type: 'number' }, - ], - data: [ - { id: '1', title: 'Ingest pipeline', estimate: 60 }, - { id: '2', title: 'Warehouse schema', estimate: 33 }, - ], -} as any; - -type Entry = { rowIndex: number; changes: Record; row: any }; - -const TITLE = 'Title is required and cannot be cleared'; -const ESTIMATE = 'Estimate (h) must be ≥ 0'; - -/** The refusal `PATCH /data/:object/:id` answers, as `@objectstack/client` decorates it. */ -function fieldRefusal(fields: Array<{ field: string; message: string }>) { - const message = fields.map((f) => f.message).join('; '); - return Object.assign(new Error(message), { - code: 'VALIDATION_FAILED', - httpStatus: 400, - details: { error: message, code: 'VALIDATION_FAILED', fields: fields.map((f) => ({ ...f, code: 'invalid' })) }, - }); -} - -const cellOf = (container: HTMLElement, rowNumber: number, colNumber: number) => - container.querySelectorAll('tbody tr')[rowNumber].querySelectorAll('td')[colNumber] as HTMLElement; - -/** Stage a new value in a body cell. */ -function stage(container: HTMLElement, rowNumber: number, colNumber: number, value: string) { - const cell = cellOf(container, rowNumber, colNumber); - fireEvent.click(cell); - const input = cell.querySelector('input') as HTMLInputElement; - fireEvent.change(input, { target: { value } }); - fireEvent.blur(input); -} - -const refusalBar = (container: HTMLElement) => - container.querySelector('[data-testid="table-save-refusal"]') as HTMLElement | null; - -describe('data-table — a refused save says every reason and marks its cells (#27520)', () => { - it('Save All: one line per reason, whole, and the two named cells of the refused row marked', async () => { - const onBatchSave = vi.fn(async (entries: Entry[]) => ({ - failed: entries - .filter((e) => e.row.id === '1') - .map((e) => ({ - rowIndex: e.rowIndex, - error: fieldRefusal([{ field: 'title', message: TITLE }, { field: 'estimate', message: ESTIMATE }]), - })), - })); - const { container, getByText } = renderComponent({ ...schema, onBatchSave }); - - stage(container, 0, 0, ''); - stage(container, 0, 1, '-5'); - stage(container, 1, 1, '31'); - fireEvent.click(getByText(/Save All/)); - - await waitFor(() => expect(refusalBar(container)).not.toBeNull()); - const bar = refusalBar(container)!; - expect(bar).toHaveAttribute('role', 'alert'); - expect(within(bar).getAllByRole('listitem').map((li) => li.textContent)).toEqual([TITLE, ESTIMATE]); - // Said whole: not the `; `-joined summary, and not cut. - expect(bar.textContent).not.toContain('; '); - expect(bar.querySelector('.truncate')).toBeNull(); - - // The refused row's two cells carry their reasons; the saved row's none. - expect(cellOf(container, 0, 0)).toHaveAttribute('aria-invalid', 'true'); - expect(cellOf(container, 0, 0)).toHaveAttribute('data-cell-error', TITLE); - expect(cellOf(container, 0, 1)).toHaveAttribute('aria-invalid', 'true'); - expect(cellOf(container, 0, 1)).toHaveAttribute('data-cell-error', ESTIMATE); - expect(container.querySelectorAll('tbody tr')[1].querySelector('[aria-invalid="true"]')).toBeNull(); - }); - - it('editing a marked cell takes its mark away and leaves the other', async () => { - const onBatchSave = vi.fn(async (entries: Entry[]) => ({ - failed: entries.map((e) => ({ - rowIndex: e.rowIndex, - error: fieldRefusal([{ field: 'title', message: TITLE }, { field: 'estimate', message: ESTIMATE }]), - })), - })); - const { container, getByText } = renderComponent({ ...schema, onBatchSave }); - - stage(container, 0, 0, ''); - stage(container, 0, 1, '-5'); - fireEvent.click(getByText(/Save All/)); - await waitFor(() => expect(cellOf(container, 0, 1)).toHaveAttribute('aria-invalid', 'true')); - - stage(container, 0, 1, '5'); - - await waitFor(() => expect(cellOf(container, 0, 1)).not.toHaveAttribute('aria-invalid')); - expect(cellOf(container, 0, 0)).toHaveAttribute('aria-invalid', 'true'); - }); - - it('a single-row save marks the cell its refusal names, and a later save that lands clears it', async () => { - const onRowSave = vi - .fn() - .mockRejectedValueOnce(fieldRefusal([{ field: 'estimate', message: ESTIMATE }])) - .mockResolvedValueOnce(undefined); - // `rowActions` draws the edit column that holds the row's own save button. - const { container } = renderComponent({ ...schema, rowActions: true, onRowSave }); - - stage(container, 0, 1, '-5'); - // The row's own save button (the edit column's save icon). - const saveRow = () => - fireEvent.click(within(container.querySelectorAll('tbody tr')[0] as HTMLElement).getByTitle(/^Save row$/i)); - saveRow(); - - await waitFor(() => expect(cellOf(container, 0, 1)).toHaveAttribute('data-cell-error', ESTIMATE)); - expect(refusalBar(container)?.textContent).toContain(ESTIMATE); - - stage(container, 0, 1, '5'); - saveRow(); - await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2)); - await waitFor(() => expect(container.querySelector('tbody [aria-invalid="true"]')).toBeNull()); - }); - - it('a whole-batch rejection says its reasons but marks no cell: no row is named', async () => { - const onBatchSave = vi.fn(async () => { - throw fieldRefusal([{ field: 'title', message: TITLE }]); - }); - const { container, getByText } = renderComponent({ ...schema, onBatchSave }); - - stage(container, 0, 0, ''); - stage(container, 1, 1, '31'); - fireEvent.click(getByText(/Save All/)); - - await waitFor(() => expect(refusalBar(container)?.textContent).toContain(TITLE)); - expect(container.querySelector('tbody [aria-invalid="true"]')).toBeNull(); - }); -}); diff --git a/ui/packages/components/src/__tests__/data-table-row-editable-27365.test.tsx b/ui/packages/components/src/__tests__/data-table-row-editable-27365.test.tsx index a7faf6ad697..e01dcd14cca 100644 --- a/ui/packages/components/src/__tests__/data-table-row-editable-27365.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-row-editable-27365.test.tsx @@ -15,18 +15,22 @@ * write verdict) hands the table a per-row predicate; a row it answers `false` * for must read exactly like a row of a read-only table: * - * - no trigger opens an editor on it — click, double-click, Enter; - * - its cells take no edit cursor, and a click on them is NOT swallowed, so - * the row's own click (ObjectGrid's record drawer) still fires; + * - no trigger opens an editor on it — double-click, Enter, typing; * - every other row is untouched, and with no predicate every row is * editable exactly as before. + * + * Mounted select-first with a per-cell save, the one way the table edits + * (objectstack#35827): a click selects a cell on any row, editable or not. */ -import { describe, it, expect, vi } from 'vitest'; +import { describe, it, expect } from 'vitest'; import { fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom'; -import { renderComponent } from './test-utils'; +import { renderSelectFirstTable } from './test-utils'; // Registers the renderers at module scope, NOT inside a `beforeAll` (objectui#3010). import '../renderers'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; const ROWS = [ { id: 'own', name: 'My Project' }, @@ -48,65 +52,60 @@ const cellOf = (container: HTMLElement, text: string) => (td) => td.textContent?.trim() === text, ) as HTMLElement; +const editor = (container: HTMLElement) => container.querySelector('td[data-editing-cell] input'); +const catcher = (container: HTMLElement) => + container.querySelector('[data-slot="cell-type-catcher"]')!; + const refuseOther = (row: { id: string }) => row.id !== 'other'; describe('data-table — isRowEditable narrows editing per row (objectstack#27365)', () => { - it('a refused row opens no editor on click, and its click reaches the row', () => { - const onRowClick = vi.fn(); - const { container } = renderComponent( - baseSchema({ singleClickEdit: true, isRowEditable: refuseOther, onRowClick }), - ); - const cell = cellOf(container, 'Legacy Sunset'); - expect(cell).not.toHaveClass('cursor-text'); - fireEvent.click(cell); - expect(cell.querySelector('input')).toBeNull(); - expect(onRowClick).toHaveBeenCalledTimes(1); - }); - it('a refused row opens no editor on double-click', () => { - const { container } = renderComponent(baseSchema({ isRowEditable: refuseOther })); + const { container } = renderSelectFirstTable(baseSchema({ isRowEditable: refuseOther })); const cell = cellOf(container, 'Legacy Sunset'); + fireEvent.click(cell); fireEvent.doubleClick(cell); - expect(cell.querySelector('input')).toBeNull(); + expect(editor(container)).toBeNull(); }); - it('a refused row opens no editor on Enter', () => { - const { container } = renderComponent(baseSchema({ isRowEditable: refuseOther })); - const cell = cellOf(container, 'Legacy Sunset'); - fireEvent.keyDown(cell, { key: 'Enter' }); - expect(cell.querySelector('input')).toBeNull(); + it('a refused row opens no editor on Enter or on a typed key', () => { + const { container } = renderSelectFirstTable(baseSchema({ isRowEditable: refuseOther })); + fireEvent.click(cellOf(container, 'Legacy Sunset')); + fireEvent.keyDown(catcher(container), { key: 'Enter' }); + expect(editor(container)).toBeNull(); + fireEvent.change(catcher(container), { target: { value: 'x' } }); + expect(editor(container)).toBeNull(); }); - it('CONTROL: the allowed row of the same table still opens its editor, on each trigger', () => { - const { container } = renderComponent( - baseSchema({ singleClickEdit: true, isRowEditable: refuseOther }), - ); + it('CONTROL: the allowed row of the same table still opens its editor on double-click', () => { + const { container } = renderSelectFirstTable(baseSchema({ isRowEditable: refuseOther })); const cell = cellOf(container, 'My Project'); - expect(cell).toHaveClass('cursor-text'); fireEvent.click(cell); - expect(cell.querySelector('input')).not.toBeNull(); + fireEvent.doubleClick(cell); + expect(editor(container)).not.toBeNull(); }); it('CONTROL: Enter on the allowed row opens its editor', () => { - const { container } = renderComponent(baseSchema({ isRowEditable: refuseOther })); - const cell = cellOf(container, 'My Project'); - fireEvent.keyDown(cell, { key: 'Enter' }); - expect(cell.querySelector('input')).not.toBeNull(); + const { container } = renderSelectFirstTable(baseSchema({ isRowEditable: refuseOther })); + fireEvent.click(cellOf(container, 'My Project')); + fireEvent.keyDown(catcher(container), { key: 'Enter' }); + expect(editor(container)).not.toBeNull(); }); it('CONTROL: with no predicate every row is editable, as before', () => { - const { container } = renderComponent(baseSchema({ singleClickEdit: true })); + const { container } = renderSelectFirstTable(baseSchema()); const cell = cellOf(container, 'Legacy Sunset'); fireEvent.click(cell); - expect(cell.querySelector('input')).not.toBeNull(); + fireEvent.doubleClick(cell); + expect(editor(container)).not.toBeNull(); }); it('narrows only: a predicate answering `true` cannot open a table that is not `editable`', () => { - const { container } = renderComponent( - baseSchema({ editable: false, singleClickEdit: true, isRowEditable: () => true }), + const { container } = renderSelectFirstTable( + baseSchema({ editable: false, isRowEditable: () => true }), ); const cell = cellOf(container, 'My Project'); fireEvent.click(cell); - expect(cell.querySelector('input')).toBeNull(); + fireEvent.doubleClick(cell); + expect(editor(container)).toBeNull(); }); }); diff --git a/ui/packages/components/src/__tests__/data-table-save-settles-current-12322.test.tsx b/ui/packages/components/src/__tests__/data-table-save-settles-current-12322.test.tsx index 41be6279881..5c3990ad713 100644 --- a/ui/packages/components/src/__tests__/data-table-save-settles-current-12322.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-save-settles-current-12322.test.tsx @@ -17,15 +17,25 @@ * edit on another row, a second edit on the row being saved, a new value for * the cell being saved. Each pin below holds the save's promise open, edits * during it, and releases it. + * + * The staged model is retired (objectstack#35827): each committed cell saves + * at once through `onRowSave`, and a commit made during a running save of the + * same record is sent after it, alone (data-table-autosave-35685 (4)). The + * pins on what Save All and the row save button kept are gone with them; what + * is left is an editor opened during a save, which must outlive the settle. */ import { describe, it, expect, vi } from 'vitest'; -import { act, fireEvent, render, waitFor, within } from '@testing-library/react'; +import { act, fireEvent, render, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; import { ComponentRegistry } from '@object-ui/core'; +import { GridCellSelectionProvider } from '../context/gridCellSelection'; // Registers the renderers at module scope, NOT inside a `beforeAll`; see // object-ui/no-dynamic-import-in-test-hook (objectui#3010/#3021). import '../renderers'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; const columns = [ { header: 'Task', accessorKey: 'name', editable: false }, @@ -33,8 +43,6 @@ const columns = [ { header: 'Note', accessorKey: 'note' }, ]; -type Entry = { rowIndex: number; changes: Record; row: any }; - const ALPHA = { id: 'a', name: 'Alpha', qty: 10, note: '' }; const BRAVO = { id: 'b', name: 'Bravo', qty: 20, note: '' }; const CHARLIE = { id: 'c', name: 'Charlie', qty: 30, note: '' }; @@ -55,13 +63,12 @@ function mount(extra: Record) { const schema = { type: 'data-table', editable: true, - singleClickEdit: true, rowActions: true, columns, data: [ALPHA, BRAVO, CHARLIE], ...extra, } as any; - return render(
); + return render(
); } const rowOf = (container: HTMLElement, name: string) => @@ -70,222 +77,50 @@ const rowOf = (container: HTMLElement, name: string) => const cellOf = (container: HTMLElement, name: string, column: 'qty' | 'note') => rowOf(container, name).querySelectorAll('td')[column === 'qty' ? 1 : 2] as HTMLElement; -/** Stage `value` in one cell, committed on blur the way a click elsewhere commits it. */ -function stage(container: HTMLElement, name: string, column: 'qty' | 'note', value: string) { +const editorIn = (cell: HTMLElement) => + cell.matches('[data-editing-cell]') ? (cell.querySelector('input') as HTMLInputElement | null) : null; + +/** Select a cell, open its editor, type `value`, and commit with Enter. */ +function commit(container: HTMLElement, name: string, column: 'qty' | 'note', value: string) { const cell = cellOf(container, name, column); fireEvent.click(cell); - const input = cell.querySelector('input') as HTMLInputElement; + fireEvent.doubleClick(cell); + const input = editorIn(cell) as HTMLInputElement; fireEvent.change(input, { target: { value } }); - fireEvent.blur(input); -} - -const saveRowOf = (container: HTMLElement, name: string) => - within(rowOf(container, name)).getByTitle('Save row'); - -/** What a Save All pressed now hands over: the edits still pending, row by row. */ -async function pendingAsSent( - onBatchSave: ReturnType, - getByText: (text: RegExp) => HTMLElement, -) { - const before = onBatchSave.mock.calls.length; - fireEvent.click(getByText(/Save All/)); - await waitFor(() => expect(onBatchSave).toHaveBeenCalledTimes(before + 1)); - const entries = onBatchSave.mock.calls[before][0] as Entry[]; - return entries.map((e) => [e.row.id, e.changes]); + fireEvent.keyDown(input, { key: 'Enter' }); } -describe('data-table — a save removes only what it sent (objectui#12322)', () => { - it('a row save held open: an edit staged on another row stays pending and drawn when it settles', async () => { - const gate = held(); - const onRowSave = vi.fn(() => gate.promise); - const onBatchSave = vi.fn(async (_entries: Entry[]) => undefined); - const { container, getByText } = mount({ onRowSave, onBatchSave }); - - stage(container, 'Alpha', 'qty', '11'); - fireEvent.click(saveRowOf(container, 'Alpha')); - expect(onRowSave).toHaveBeenCalledWith(0, { qty: '11' }, ALPHA); - - stage(container, 'Bravo', 'qty', '21'); - expect(getByText(/2 rows modified/)).toBeInTheDocument(); - - await act(async () => { - gate.resolve(); - await gate.promise; - }); - - expect(getByText(/1 row modified/)).toBeInTheDocument(); - expect(cellOf(container, 'Bravo', 'qty')).toHaveTextContent('21'); - expect(await pendingAsSent(onBatchSave, getByText)).toEqual([['b', { qty: '21' }]]); - }); - - it('Save All held open: an edit staged on another row stays pending and drawn when it settles', async () => { - const gate = held(); - const onBatchSave = vi.fn((_entries: Entry[]) => gate.promise); - const { container, getByText } = mount({ onBatchSave }); - - stage(container, 'Alpha', 'qty', '11'); - fireEvent.click(getByText(/Save All/)); - expect(onBatchSave).toHaveBeenCalledTimes(1); - - stage(container, 'Bravo', 'qty', '21'); - expect(getByText(/2 rows modified/)).toBeInTheDocument(); - - await act(async () => { - gate.resolve(); - await gate.promise; - }); - - expect(getByText(/1 row modified/)).toBeInTheDocument(); - expect(cellOf(container, 'Bravo', 'qty')).toHaveTextContent('21'); - onBatchSave.mockImplementation(async () => undefined); - expect(await pendingAsSent(onBatchSave, getByText)).toEqual([['b', { qty: '21' }]]); - }); - - it.each([ - ['row save', 'row'], - ['Save All', 'all'], - ] as const)('%s: the cell being saved, re-edited during the save, keeps its new value pending', async (_label, via) => { - const gate = held(); - const onRowSave = vi.fn(() => gate.promise); - const onBatchSave = vi.fn((_entries: Entry[]) => gate.promise); - const { container, getByText } = mount({ onRowSave, onBatchSave }); - - stage(container, 'Alpha', 'qty', '11'); - fireEvent.click(via === 'row' ? saveRowOf(container, 'Alpha') : getByText(/Save All/)); - stage(container, 'Alpha', 'qty', '12'); - - await act(async () => { - gate.resolve(); - await gate.promise; - }); - - expect(getByText(/1 row modified/)).toBeInTheDocument(); - expect(cellOf(container, 'Alpha', 'qty')).toHaveTextContent('12'); - onBatchSave.mockImplementation(async () => undefined); - expect(await pendingAsSent(onBatchSave, getByText)).toEqual([['a', { qty: '12' }]]); - }); - - it('a cell re-edited back to its loaded value during its save stays pending, since the save writes the old edit', async () => { - const gate = held(); - const onRowSave = vi.fn(() => gate.promise); - const onBatchSave = vi.fn(async (_entries: Entry[]) => undefined); - const { container, getByText } = mount({ onRowSave, onBatchSave }); - - stage(container, 'Alpha', 'qty', '11'); - fireEvent.click(saveRowOf(container, 'Alpha')); - // 10 is what Alpha loaded with, and 11 is on its way to the server: once - // the save lands, 10 is a change again. - stage(container, 'Alpha', 'qty', '10'); - expect(getByText(/1 row modified/)).toBeInTheDocument(); - - await act(async () => { - gate.resolve(); - await gate.promise; - }); - - expect(getByText(/1 row modified/)).toBeInTheDocument(); - expect(await pendingAsSent(onBatchSave, getByText)).toEqual([['a', { qty: '10' }]]); - }); - - it('another cell of the row being saved, staged during its save, stays pending on its own', async () => { - const gate = held(); - const onRowSave = vi.fn(() => gate.promise); - const onBatchSave = vi.fn(async (_entries: Entry[]) => undefined); - const { container, getByText } = mount({ onRowSave, onBatchSave }); - - stage(container, 'Alpha', 'qty', '11'); - fireEvent.click(saveRowOf(container, 'Alpha')); - stage(container, 'Alpha', 'note', 'reviewed'); - - await act(async () => { - gate.resolve(); - await gate.promise; - }); - - expect(getByText(/1 row modified/)).toBeInTheDocument(); - expect(cellOf(container, 'Alpha', 'note')).toHaveTextContent('reviewed'); - expect(await pendingAsSent(onBatchSave, getByText)).toEqual([['a', { note: 'reviewed' }]]); - }); - - it('Save All with a per-row { failed }: the failed row stays flagged, a row staged during the save stays unflagged', async () => { - const gate = held<{ failed: Array<{ rowIndex: number; error: Error }> }>(); - const onBatchSave = vi.fn((_entries: Entry[]) => gate.promise); - const { container, getByText } = mount({ onBatchSave }); - - stage(container, 'Alpha', 'qty', '11'); - stage(container, 'Bravo', 'qty', '21'); - fireEvent.click(getByText(/Save All/)); - const sent = onBatchSave.mock.calls[0][0]; - expect(sent.map((e) => e.row.id)).toEqual(['a', 'b']); - - stage(container, 'Charlie', 'qty', '31'); - expect(getByText(/3 rows modified/)).toBeInTheDocument(); - - const bravo = sent.find((e) => e.row.id === 'b')!; - await act(async () => { - gate.resolve({ failed: [{ rowIndex: bravo.rowIndex, error: new Error('Bravo was refused') }] }); - await gate.promise; - }); - - expect(getByText(/2 rows modified/)).toBeInTheDocument(); - expect(container.textContent).toContain('Bravo was refused'); - expect(cellOf(container, 'Bravo', 'qty')).toHaveTextContent('21'); - expect(cellOf(container, 'Charlie', 'qty')).toHaveTextContent('31'); - expect(rowOf(container, 'Bravo').className).toContain('bg-destructive/10'); - expect(rowOf(container, 'Charlie').className).not.toContain('bg-destructive/10'); - expect(rowOf(container, 'Alpha').className).not.toContain('bg-destructive/10'); - - onBatchSave.mockImplementation(async () => ({ failed: [] })); - expect(await pendingAsSent(onBatchSave, getByText)).toEqual([ - ['b', { qty: '21' }], - ['c', { qty: '31' }], - ]); - }); - - it('a rejected Save All flags the rows it sent, not a row staged during the save', async () => { - const gate = held(); - const onBatchSave = vi.fn((_entries: Entry[]) => gate.promise); - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); - const { container, getByText } = mount({ onBatchSave }); - - stage(container, 'Alpha', 'qty', '11'); - fireEvent.click(getByText(/Save All/)); - stage(container, 'Charlie', 'qty', '31'); - - await act(async () => { - gate.reject(new Error('Network down')); - await gate.promise.catch(() => undefined); - }); - - expect(getByText(/2 rows modified/)).toBeInTheDocument(); - expect(container.textContent).toContain('Network down'); - expect(rowOf(container, 'Alpha').className).toContain('bg-destructive/10'); - expect(rowOf(container, 'Charlie').className).not.toContain('bg-destructive/10'); - consoleError.mockRestore(); - }); - +describe('data-table — a save settling leaves an editor opened during it alone (objectui#12322)', () => { it('an editor opened during the save stays open, with what was typed, when the save settles', async () => { const gate = held(); - const onBatchSave = vi.fn((_entries: Entry[]) => gate.promise); - const { container, getByText } = mount({ onBatchSave }); + const onRowSave = vi.fn((_i: number, _changes: Record, _row?: unknown) => gate.promise); + const { container } = mount({ onRowSave }); - stage(container, 'Alpha', 'qty', '11'); - fireEvent.click(getByText(/Save All/)); + commit(container, 'Alpha', 'qty', '11'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); const bravo = cellOf(container, 'Bravo', 'qty'); fireEvent.click(bravo); - fireEvent.change(bravo.querySelector('input') as HTMLInputElement, { target: { value: '21' } }); + fireEvent.doubleClick(bravo); + fireEvent.change(editorIn(bravo) as HTMLInputElement, { target: { value: '21' } }); await act(async () => { gate.resolve(); await gate.promise; }); - const input = cellOf(container, 'Bravo', 'qty').querySelector('input') as HTMLInputElement; + const input = editorIn(cellOf(container, 'Bravo', 'qty')); expect(input).not.toBeNull(); - expect(input.value).toBe('21'); - fireEvent.blur(input); - expect(getByText(/1 row modified/)).toBeInTheDocument(); - expect(cellOf(container, 'Bravo', 'qty')).toHaveTextContent('21'); + expect(input!.value).toBe('21'); + fireEvent.keyDown(input!, { key: 'Enter' }); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2)); + expect(onRowSave.mock.calls[1][1]).toEqual({ qty: '21' }); + expect(onRowSave.mock.calls[1][2]).toEqual(expect.objectContaining({ id: 'b' })); }); + + // The pins on what a row save or Save All removed from the pending edits + // when it settled (another row, another cell of the same row, a cell + // re-edited back, a per-row { failed }, a rejected batch) went with the + // pending edits themselves (objectstack#35827). A commit made during a + // running save is sent after it, alone: data-table-autosave-35685 (4). }); diff --git a/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx b/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx index 9d2a2df6074..72ef227b2e4 100644 --- a/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx @@ -97,7 +97,7 @@ function renderTable({ ], data: ROWS, editable: true, - singleClickEdit: true, + onRowSave: () => Promise.resolve(), searchable: false, pagination: false, onRowClick, @@ -132,12 +132,20 @@ describe('data-table select-first — a click selects (objectstack#35684)', () = expect(t.cell(1, 1)).toHaveAttribute('data-selected-cell'); }); - it('control: without the provider the same click still opens the editor', () => { - // `keyboardNavigation` only addresses the cells (`data-grid-cell`) the probe reads. - const t = renderTable({ selection: null, extra: { keyboardNavigation: true } }); - fireEvent.click(t.cell(0, 0)); - expect(t.editor()).not.toBeNull(); - expect(t.cell(0, 0)).not.toHaveAttribute('data-selected-cell'); + it('without the provider the table is read-only: a click opens no editor (objectstack#35827)', () => { + // The staged click-to-edit fallback is retired; an editable table with no + // select-first host renders read-only and says so in the console. + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + // `keyboardNavigation` only addresses the cells (`data-grid-cell`) the probe reads. + const t = renderTable({ selection: null, extra: { keyboardNavigation: true } }); + fireEvent.click(t.cell(0, 0)); + fireEvent.doubleClick(t.cell(0, 0)); + expect(t.editor()).toBeNull(); + expect(t.cell(0, 0)).not.toHaveAttribute('data-selected-cell'); + } finally { + warn.mockRestore(); + } }); }); @@ -347,11 +355,10 @@ describe('data-table select-first — no edit-only column, ever (objectstack#355 expect(onRowSave).toHaveBeenCalledTimes(1); }); - it('control: without the provider the column is drawn at rest, as before', () => { - const t = renderTable({ selection: null, extra: EDIT_ONLY }); - expect(editHeader(t.container)).not.toBeNull(); - expect(lastHeader(t.container)).toBe(editHeader(t.container)); - }); + // The staged control that drew the edit-only column without the provider is + // gone with the column itself (objectstack#35827); a table with no + // select-first host is read-only, pinned in data-table-autosave-35685 + // "no staged fallback". }); describe('data-table select-first — a touch tap opens the record', () => { @@ -405,7 +412,7 @@ describe('data-table select-first — a reference chip opens its record in place ], data: ACCOUNTS, editable: true, - singleClickEdit: true, + onRowSave: () => Promise.resolve(), searchable: false, pagination: false, }; @@ -582,6 +589,7 @@ describe('data-table select-first — a read-only cell says so in the grid (obje editable: true, searchable: false, pagination: false, + onRowSave: () => Promise.resolve(), }); const Host = ({ value, schema }: { value: GridCellSelection; schema: Record }) => ( diff --git a/ui/packages/components/src/__tests__/renderer-copy-locale-25916.test.tsx b/ui/packages/components/src/__tests__/renderer-copy-locale-25916.test.tsx index 86793f2784c..6b9d34ade8c 100644 --- a/ui/packages/components/src/__tests__/renderer-copy-locale-25916.test.tsx +++ b/ui/packages/components/src/__tests__/renderer-copy-locale-25916.test.tsx @@ -10,9 +10,10 @@ * #25916, third pass — two renderers in this package drew English literals * whatever the session's language. * - * - `data-table`: the hover "open record" affordance's title and the inline - * edit row's cancel / save buttons (`table.openRecord`, - * `table.cancelChanges`, `table.saveRow`); + * - `data-table`: the hover "open record" affordance's title + * (`table.openRecord`). The staged edit row's cancel / save buttons + * (`table.cancelChanges`, `table.saveRow`) are retired with the staged + * model (objectstack#35827): each cell now saves on commit; * - the `kind:'react'` page renderer: its capability notice, its empty-source * refusal, its loading line and its error titles (`reactPage.*`). * @@ -25,7 +26,7 @@ * - control: with no provider each surface still reads its English. */ import { describe, it, expect, afterEach } from 'vitest'; -import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { cleanup, render, screen } from '@testing-library/react'; import React from 'react'; import { CAP_REACT_PAGES, ComponentRegistry, disableCapability, enableCapability } from '@object-ui/core'; import { AdapterCtx, SchemaRenderer } from '@object-ui/react'; @@ -64,30 +65,18 @@ const Table = ComponentRegistry.get('data-table')!; function DataTable({ onRowClick }: { onRowClick?: () => void }) { const schema = { type: 'data-table', - editable: true, - singleClickEdit: true, rowActions: true, showRowNumbers: true, columns: [ - { header: 'Task', accessorKey: 'name', editable: false }, + { header: 'Task', accessorKey: 'name' }, { header: 'Estimate', accessorKey: 'qty', type: 'number' }, ], data: [ALPHA], - onRowSave: async () => undefined, ...(onRowClick ? { onRowClick } : {}), } as any; return
; } -/** Stage an edit on Alpha's estimate, so the row draws its cancel / save buttons. */ -function stageEdit(container: HTMLElement) { - const cell = container.querySelectorAll('tbody tr td')[2] as HTMLElement; - fireEvent.click(cell); - const input = cell.querySelector('input') as HTMLInputElement; - fireEvent.change(input, { target: { value: '11' } }); - fireEvent.blur(input); -} - const PAGE = (source: string): PageDocumentNode => ({ type: 'home', kind: 'react', @@ -113,8 +102,6 @@ describe('renderer copy under zh (#25916)', () => { it('guard: the zh values read below are real zh rows, not English copies', () => { for (const [zhValue, enValue] of [ [zh.table.openRecord, en.table.openRecord], - [zh.table.cancelChanges, en.table.cancelChanges], - [zh.table.saveRow, en.table.saveRow], [zh.reactPage.disabledTitle, en.reactPage.disabledTitle], [zh.reactPage.disabledBody, en.reactPage.disabledBody], [zh.reactPage.sourceRequired, en.reactPage.sourceRequired], @@ -124,13 +111,9 @@ describe('renderer copy under zh (#25916)', () => { } }); - it('data-table: the open affordance and the edited row buttons are titled in zh', () => { - const { container } = withLanguage( undefined} />, 'zh'); + it('data-table: the open affordance is titled in zh', () => { + withLanguage( undefined} />, 'zh'); expect(screen.getByTestId('row-expand-button').getAttribute('title')).toBe(zh.table.openRecord); - stageEdit(container); - const row = container.querySelector('tbody tr') as HTMLElement; - expect(within(row).getByTitle(zh.table.cancelChanges)).toBeTruthy(); - expect(within(row).getByTitle(zh.table.saveRow)).toBeTruthy(); }); it('react page, capability off: the notice is zh, its three chips where the zh string put them', async () => { @@ -159,11 +142,8 @@ describe('renderer copy under zh (#25916)', () => { describe('control: with no provider each surface still reads its English (#25916)', () => { it('data-table', () => { - const { container } = withLanguage( undefined} />, null); + withLanguage( undefined} />, null); expect(screen.getByTestId('row-expand-button').getAttribute('title')).toBe('Open record'); - stageEdit(container); - expect(screen.getByTitle('Cancel changes')).toBeTruthy(); - expect(screen.getByTitle('Save row')).toBeTruthy(); }); it('react page notice', async () => { diff --git a/ui/packages/components/src/__tests__/test-utils.tsx b/ui/packages/components/src/__tests__/test-utils.tsx index abdebb802d0..2e70e0e8da8 100644 --- a/ui/packages/components/src/__tests__/test-utils.tsx +++ b/ui/packages/components/src/__tests__/test-utils.tsx @@ -6,9 +6,10 @@ * LICENSE file in the root directory of this source tree. */ -import { render, RenderOptions } from '@testing-library/react'; +import { fireEvent, render, RenderOptions } from '@testing-library/react'; import { ComponentRegistry } from '@object-ui/core'; import type { BaseSchema } from '@object-ui/types'; +import { GridCellSelectionProvider, type GridCellSelection } from '../context/gridCellSelection'; /** * Test utility for rendering components from schema. @@ -29,6 +30,34 @@ export function renderComponent(schema: BaseSchema, options?: RenderOptions) { return render(, options); } +/** + * Renders a `data-table` the one way an editable one edits (objectstack#35827): + * inside a select-first host (`GridCellSelection`) with a per-cell save + * (`onRowSave`, a resolved no-op unless the schema names one). Without both, an + * editable table renders read-only. `rerender` takes the next schema and keeps + * the same host and default save. + */ +export function renderSelectFirstTable( + schema: BaseSchema & Record, + { selection = {}, ...options }: RenderOptions & { selection?: GridCellSelection } = {}, +) { + const DataTable = ComponentRegistry.get('data-table')!; + const defaultSave = () => Promise.resolve(); + const tree = (next: BaseSchema & Record) => ( + + + + ); + const utils = render(tree(schema), options); + return { ...utils, rerender: (next: BaseSchema & Record) => utils.rerender(tree(next)) }; +} + +/** Opens a cell's editor the select-first way: a click selects it, a double-click edits. */ +export function openCellEditor(cell: HTMLElement) { + fireEvent.click(cell); + fireEvent.doubleClick(cell); +} + /** * Check if a component has proper accessibility attributes */ diff --git a/ui/packages/components/src/context/gridCellSelection.tsx b/ui/packages/components/src/context/gridCellSelection.tsx index b4d83686973..9258809b3c9 100644 --- a/ui/packages/components/src/context/gridCellSelection.tsx +++ b/ui/packages/components/src/context/gridCellSelection.tsx @@ -127,10 +127,10 @@ export interface GridCellSelection { * or saved. A promise holds the write until it settles: `true` writes the * value as any commit is written, `false` (or a rejection) writes nothing * and the cell keeps what it showed. `null` / `undefined` ⇒ no question; - * the value is written at once. Only a table that saves each cell as it is - * committed (one wired with `onRowSave`) asks; a table on `onBatchSave` - * alone never does. A host asks, for example, before a move of a - * state-machine field (objectstack#35685). + * the value is written at once. It is asked by a table that saves each cell + * as it is committed (one wired with `onRowSave`), the only way a table + * edits since the staged model was retired (objectstack#35827). A host asks, + * for example, before a move of a state-machine field (objectstack#35685). */ confirmCommit?: (row: any, columnKey: string, value: unknown) => Promise | null | undefined; /** diff --git a/ui/packages/components/src/renderers/complex/__tests__/data-table-lookup-picker-floor-34601.test.tsx b/ui/packages/components/src/renderers/complex/__tests__/data-table-lookup-picker-floor-34601.test.tsx index 0a0456ec1ee..6d70d20af0e 100644 --- a/ui/packages/components/src/renderers/complex/__tests__/data-table-lookup-picker-floor-34601.test.tsx +++ b/ui/packages/components/src/renderers/complex/__tests__/data-table-lookup-picker-floor-34601.test.tsx @@ -24,11 +24,20 @@ import '@testing-library/jest-dom'; import React from 'react'; import { ComponentRegistry } from '@object-ui/core'; import '../data-table'; +import { GridCellSelectionProvider } from '../../../context/gridCellSelection'; +/** + * Mounted select-first with a per-cell save, the one way an editable table + * edits (objectstack#35827); without both, `editable: true` renders read-only. + */ function DataTable(props: { schema: Record }) { const Impl = ComponentRegistry.get('data-table') as React.ComponentType<{ schema: unknown }> | undefined; if (!Impl) throw new Error('data-table not registered'); - return ; + return ( + + Promise.resolve(), ...props.schema }} /> + + ); } const headerWidth = (label: string): string => { diff --git a/ui/packages/components/src/renderers/complex/__tests__/data-table-masked-column-10583.test.tsx b/ui/packages/components/src/renderers/complex/__tests__/data-table-masked-column-10583.test.tsx index c3a05b94867..1fb76750eb4 100644 --- a/ui/packages/components/src/renderers/complex/__tests__/data-table-masked-column-10583.test.tsx +++ b/ui/packages/components/src/renderers/complex/__tests__/data-table-masked-column-10583.test.tsx @@ -28,6 +28,7 @@ */ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { render, screen, cleanup, fireEvent } from '@testing-library/react'; +import { GridCellSelectionProvider } from '../../../context/gridCellSelection'; import '@testing-library/jest-dom'; import React from 'react'; import { ComponentRegistry } from '@object-ui/core'; @@ -56,11 +57,15 @@ afterEach(() => { cleanup(); }); -/** `masked` undefined ⇒ the key is ABSENT from the column, not `false`. */ +/** + * `masked` undefined ⇒ the key is ABSENT from the column, not `false`. An + * editable table is mounted select-first with a per-cell save, the one way it + * edits (objectstack#35827). + */ function renderTable(masked: boolean | undefined, extra: Record = {}) { const DataTable = ComponentRegistry.get('data-table') as any; if (!DataTable) throw new Error('data-table not registered'); - return render( + const table = ( pagination: false, searchable: false, exportable: true, + ...(extra.editable ? { onRowSave: () => Promise.resolve() } : {}), ...extra, }} - />, + /> ); + return render(extra.editable ? {table} : table); } /** The body cell under the header `label`. */ @@ -173,41 +180,36 @@ describe('data-table — a masked column never enters edit mode (objectui#10583) el.value.includes(RAW), ); - it('single-click mode — click and Enter open no editor; the click reaches the row like a read-only cell', () => { - const onRowClick = vi.fn(); - renderTable(true, { editable: true, singleClickEdit: true, onRowClick }); + const catcher = () => document.querySelector('[data-slot="cell-type-catcher"]')!; + + it('double-click, Enter and typing open no editor on a masked cell; the ordinary cell still edits', () => { + renderTable(true, { editable: true }); const masked = cellUnder('Key'); expect(masked.textContent, 'CONTROL: the producer drew the mask').toContain(MASK); expect(masked.className, 'no edit cursor on a masked cell').not.toContain('cursor-text'); fireEvent.click(masked); - fireEvent.keyDown(masked, { key: 'Enter' }); - expect(masked.querySelector('input, textarea'), 'no editor in the masked cell').toBeNull(); + fireEvent.doubleClick(masked); + fireEvent.keyDown(catcher(), { key: 'Enter' }); + fireEvent.change(catcher(), { target: { value: 'x' } }); + expect(document.querySelector('td[data-editing-cell]'), 'no editor in the masked cell').toBeNull(); expect(rawInAnEditor(), 'no editor holds the raw value').toBe(false); expect(document.body.innerHTML).not.toContain(RAW); - expect(onRowClick, 'the click is not swallowed by an edit that never opens').toHaveBeenCalledTimes(1); // CONTROL — the ordinary column in the SAME table does open its editor. fireEvent.click(cellUnder('Name')); - expect(cellUnder('Name').querySelector('input'), 'CONTROL: the ordinary cell edits').not.toBeNull(); - }); - - it('double-click mode — double-click and Enter open no editor; the ordinary cell still edits', () => { - renderTable(true, { editable: true }); - const masked = cellUnder('Key'); - fireEvent.doubleClick(masked); - fireEvent.keyDown(masked, { key: 'Enter' }); - expect(masked.querySelector('input, textarea')).toBeNull(); - expect(rawInAnEditor()).toBe(false); - expect(document.body.innerHTML).not.toContain(RAW); - fireEvent.doubleClick(cellUnder('Name')); - expect(cellUnder('Name').querySelector('input'), 'CONTROL: the ordinary cell edits').not.toBeNull(); + expect(document.querySelector('td[data-editing-cell] input'), 'CONTROL: the ordinary cell edits').not.toBeNull(); }); + // The "single-click mode" case pinned the staged arm's click-to-edit and its + // click reaching the row; that arm is retired (objectstack#35827), and a + // click now only selects a cell. + it('CONTROL — the same column with the flag ABSENT edits exactly as before', () => { - renderTable(undefined, { editable: true, singleClickEdit: true }); + renderTable(undefined, { editable: true }); fireEvent.click(cellUnder('Key')); + fireEvent.doubleClick(cellUnder('Key')); expect(rawInAnEditor(), 'without the flag the editor is seeded with the stored value').toBe(true); }); }); diff --git a/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx b/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx index f0462345e8b..b419cbbd255 100644 --- a/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx +++ b/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx @@ -25,6 +25,7 @@ import React from 'react'; import { ComponentRegistry } from '@object-ui/core'; import { PredicateScopeProvider } from '@object-ui/react'; import { DropdownMenuItem } from '../../../ui/dropdown-menu'; +import { GridCellSelectionProvider } from '../../../context/gridCellSelection'; import '../data-table'; const ROWS = [ @@ -50,14 +51,21 @@ const RELATED_LIST_SCHEMA = { onRowActionDef: () => {}, }; +/** + * An editable table is mounted select-first with a per-cell save, the one way + * it edits (objectstack#35827); a read-only one is mounted bare. + */ function renderTable(schema: Record) { const DataTable = ComponentRegistry.get('data-table') as any; if (!DataTable) throw new Error('data-table not registered'); - return render( - - - , - ); + const table = schema.editable + ? ( + + Promise.resolve(), ...schema }} /> + + ) + : ; + return render({table}); } const cellOf = (name: string) => screen.getByText(name).closest('td') as HTMLElement; diff --git a/ui/packages/components/src/renderers/complex/__tests__/data-table-textSelection-13188.test.tsx b/ui/packages/components/src/renderers/complex/__tests__/data-table-textSelection-13188.test.tsx index 616800ff4b9..31319e39ddf 100644 --- a/ui/packages/components/src/renderers/complex/__tests__/data-table-textSelection-13188.test.tsx +++ b/ui/packages/components/src/renderers/complex/__tests__/data-table-textSelection-13188.test.tsx @@ -11,7 +11,7 @@ * selects text ends in a `click` on the row (or cell) it started in; that * click must neither open the record nor start an inline edit, and Ctrl/Cmd+C * must copy the selection rather than the cell's raw value. A plain click - * (no selection) still opens / edits exactly as before. + * (no selection) still opens the record exactly as before. * * jsdom has no mouse-driven selection, so the drag's outcome is set directly * with the Selection API and then the trailing click is fired. @@ -92,25 +92,13 @@ describe('data-table text selection (objectui#13188)', () => { expect(onRowClick).toHaveBeenCalledTimes(1); }); - describe.each([ - ['single-click edit', { singleClickEdit: true }, 'click'], - ['double-click edit', { singleClickEdit: false }, 'dblClick'], - ] as const)('editable, %s', (_label, mode, gesture) => { - it('selecting text does not enter edit mode', () => { - const { onRowClick } = renderTable({ editable: true, ...mode }); - selectText(screen.getByText('Ada Lovelace')); - fireEvent[gesture](cellOf('Ada Lovelace')); - expect(cellOf('Ada Lovelace').querySelector('input')).toBeNull(); - expect(onRowClick).not.toHaveBeenCalled(); - }); - - it('the same gesture without a selection still enters edit mode', () => { - renderTable({ editable: true, ...mode }); - const cell = cellOf('Ada Lovelace'); - fireEvent[gesture](cell); - expect(cell.querySelector('input')).not.toBeNull(); - }); - }); + // The `editable` cases pinned the staged arm's click-to-edit and + // double-click-to-edit against a text selection. That arm is retired + // (objectstack#35827): an editable table is select-first, where a click only + // selects a cell and a double-click edits even over the word the browser + // selected on the way, pinned in data-table-select-first-35684 ("a + // double-click over the text edits, though the browser selected a word on + // the way"). it('Ctrl+C with text selected in the cell leaves the browser copy alone', () => { renderTable(); diff --git a/ui/packages/components/src/renderers/complex/__tests__/table-column-type-read-set.test.tsx b/ui/packages/components/src/renderers/complex/__tests__/table-column-type-read-set.test.tsx index 6f6695c75a0..7bbf6cd2992 100644 --- a/ui/packages/components/src/renderers/complex/__tests__/table-column-type-read-set.test.tsx +++ b/ui/packages/components/src/renderers/complex/__tests__/table-column-type-read-set.test.tsx @@ -29,12 +29,15 @@ import { describe, it, expect } from 'vitest'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; -import { screen, fireEvent } from '@testing-library/react'; +import { screen } from '@testing-library/react'; import { TABLE_COLUMN_TYPES } from '@object-ui/types'; -import { renderComponent } from '../../../__tests__/test-utils'; +import { openCellEditor, renderSelectFirstTable } from '../../../__tests__/test-utils'; // Module-scope side-effect import, not a `beforeAll` — see // object-ui/no-dynamic-import-in-test-hook (objectui#3010/#3021). import '../../../renderers'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; // @ts-expect-error — plain-JS shared helper, intentionally untyped (`allowJs: false`) import { maskComments } from '../../../../../../scripts/js-comment-mask.mjs'; @@ -112,7 +115,6 @@ function schemaWithColumnType(type?: string) { return { type: 'data-table' as const, editable: true, - singleClickEdit: true, columns: [ { header: 'Name', accessorKey: 'name' }, { header: 'Stage', accessorKey: 'stage', ...(type ? { type } : {}) }, @@ -126,7 +128,7 @@ describe('an out-of-union type degrades to the no-type path — the column survi // ⛔ The rule the fold must never break: an undeclared type drops the // ANNOTATION, never the column. A producer that fails to fold still hands // this renderer a raw spec field type, and the column must still draw. - const { container } = renderComponent(schemaWithColumnType(OUT_OF_UNION)); + const { container } = renderSelectFirstTable(schemaWithColumnType(OUT_OF_UNION)); expect(screen.getByText('Stage')).toBeTruthy(); expect(container.textContent).toContain('won'); }); @@ -136,10 +138,12 @@ describe('an out-of-union type degrades to the no-type path — the column survi // renderer's non-date / non-numeric path IS the `undefined` path. Both // land on the built-in text input. const editorFor = (type?: string): string | null => { - const { container, unmount } = renderComponent(schemaWithColumnType(type)); + // Select-first with a per-cell save, the one way the table edits + // (objectstack#35827): a click selects, a double-click opens the editor. + const { container, unmount } = renderSelectFirstTable(schemaWithColumnType(type)); const cells = container.querySelectorAll('tbody td'); - fireEvent.click(cells[1] as HTMLElement); - const input = container.querySelector('tbody input'); + openCellEditor(cells[1] as HTMLElement); + const input = container.querySelector('td[data-editing-cell] input'); const result = input ? (input.getAttribute('type') ?? '(none)') : null; unmount(); return result; diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index 0efa1415c1b..61974a43c56 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -18,7 +18,7 @@ import { useGridHeaderMenu } from '../../context/gridHeaderMenu'; import { caretToEnd, cellOpenerAt, defaultTyping, defaultValueFromText, firstCellOpener, firstEditorControl, firstRecordChip, isCellWidgetTarget, isCommandLetter, isImeKey, isPrintableKey, recordChipAt } 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'; +import { describeIgnoredBind, describeNonArrayData, describeUnsavableEditable } from './dataTableBindDiagnostic'; import { CellOverlay } from './dataTableCellOverlay'; import { CELL_OVERLAY_HOST_CLASS, isCellContentTruncated, type CellOverlaySize } from './dataTableCellOverlayDom'; import { ComponentRegistry, compareSortValues, csvBlob, evalRowPredicate, formatDate, hasDeclaredPredicate, isActionSwitchedOff, formatDateTime, fromDateTimeInputValue, getSortValue, isEmptyValue, isImpossibleStoredDay, toDateInputValue, toDateTimeInputValue } from '@object-ui/core'; @@ -62,7 +62,6 @@ import { ChevronsLeft, ChevronsRight, GripVertical, - Save, X, Plus, MoreHorizontal, @@ -143,8 +142,8 @@ function pendingRowKeyOf(row: unknown): PendingRowKey { * One row's staged edits, per column key, and the row they were last staged * against. The row is read only when the rows the table holds no longer * include that record (a re-read dropped it, or it sits on another server - * page): Save All then hands the edit over with the row it was typed on, - * never with the row at its old position. + * page): the row's next save then hands the edit over with the row it was + * typed on, never with the row at its old position. */ interface PendingRow { row: any; @@ -338,17 +337,10 @@ const TABLE_DEFAULT_TRANSLATIONS: Record = { 'table.sortAsc': 'Sort ascending', 'table.sortDesc': 'Sort descending', 'table.hideColumn': 'Hide column', - 'table.cancelAll': 'Cancel All', - 'table.saveAll': 'Save All ({{count}})', 'table.exportCSV': 'Export CSV', 'table.addRecord': 'Add record', 'table.open': 'Open', 'table.search': 'Search…', - 'table.modified': '{{count}} row modified', - // A count family (objectui#11445): `fallbackT` reads the `_one` / `_other` - // row for a numeric `count`, as i18next reads the `en` pack. - 'table.modified_one': '{{count}} row modified', - 'table.modified_other': '{{count}} rows modified', 'table.saveFailed': 'Save failed', 'table.selected': '{{count}} selected', // objectui#11690 — the selection checkboxes' accessible names. @@ -358,10 +350,8 @@ const TABLE_DEFAULT_TRANSLATIONS: Record = { 'table.rowActions': 'Row actions', 'table.edit': 'Edit', 'table.delete': 'Delete', - // #25916 — the hover open affordance and the inline-edit row buttons. + // #25916 — the hover open affordance. '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.', @@ -466,15 +456,6 @@ type RowActionDef = NonNullable[number]; /** The element type of `DataTableSchema.rowGroups` (objectui#12620). */ type RowGroup = NonNullable[number]; -/** - * The per-row outcome `onBatchSave` may resolve with (objectui#12292), derived - * from the slot's declared return rather than restated here. - */ -type BatchSaveOutcome = Exclude< - Awaited>>, - void ->; - /** * The authoring shape of the built-in row Edit/Delete predicates — derived from * `DataTableSchema`, never restated by hand (objectui#4354). Everything below @@ -1645,8 +1626,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { rowActions = false, resizableColumns = true, reorderableColumns = true, - editable = false, - singleClickEdit = false, + editable: editableProp = false, keyboardNavigation: keyboardNavigationProp = false, rowClassName, rowStyle, @@ -1677,10 +1657,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // sorting, when a host mounted `GridHeaderMenu`. const headerOpensMenu = useGridHeaderMenu(); const selectFirst = cellSelection !== null; - // objectstack#35685 — the per-cell save needs a per-row save to call. A - // select-first table wired with `onBatchSave` alone keeps the staged save - // bar, so an edit is never held where nothing can send it. + // objectstack#35827 — the table has one way to edit: select-first, each + // committed cell saved at once through `onRowSave` (objectstack#35685). The + // staged model (click-to-edit, a pending-changes bar, "Save All", + // `onBatchSave`) is retired, so `editable` takes effect only where both are + // there; anywhere else the table draws read-only and says why once + // (`describeUnsavableEditable`), instead of holding an edit nothing sends. + // `ObjectGrid` mounts the model and its own write for every grid it renders + // editable. const autosaves = selectFirst && typeof schema.onRowSave === 'function'; + const editable = editableProp && autosaves; const keyboardNavigation = keyboardNavigationProp || selectFirst; // 'single' caps the selection at one row (replace-on-select) and drops the @@ -1830,6 +1816,18 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { if (nonArrayDataMessage) console.warn(nonArrayDataMessage); }, [nonArrayDataMessage]); + // objectstack#35827 — say out loud that an `editable` the table cannot save + // was refused (see `editable` above). Keyed on the message, as above: one + // line per distinct misconfiguration. + const unsavableEditableMessage = describeUnsavableEditable( + editableProp, + { selectFirst, rowSave: typeof schema.onRowSave === 'function' }, + { blockType: bindDiagnosticBlockType, id: bindDiagnosticId, caption }, + ); + useEffect(() => { + if (unsavableEditableMessage) console.warn(unsavableEditableMessage); + }, [unsavableEditableMessage]); + // The adapter reads ONLY the column keys `TableColumn` DECLARES. Both // undeclared aliases are now retired: `label` (objectui#5351) and `name` // (objectui#5120, this change). @@ -2122,7 +2120,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // Track pending changes for multi-cell editing, per record (objectui#12310): // record key -> { row, changes: { columnKey -> newValue } } const [pendingChanges, setPendingChanges] = useState(new Map()); - // What a running row save or Save All sent, per record key (objectui#12322). + // What a running row save sent, per record key (objectui#12322). // Cell editing stays open during a save, and a commit on a cell in here is // always staged (see `stageCellChange`). Set when the save is pressed and // cleared when it settles; read only by event handlers, never by render. @@ -2154,11 +2152,6 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { }, }; }, [pendingChanges]); - const [isSaving, setIsSaving] = useState(false); - // Last save failure, one line per reason (server validation text, etc.), - // shown in the toolbar; null when the last save attempt succeeded or - // nothing's been saved. - const [saveError, setSaveError] = useState(null); // The cells the last refusal named, per record key, field → reason // (objectstack-ai/objectstack#27520): each is marked where it is drawn, and // its mark goes the moment the cell is edited again or its row saves. @@ -2184,10 +2177,6 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { return next; }); }; - // Records whose last save attempt failed, by the key their pending edit is - // kept under (objectui#12310) — tinted destructive so the author sees exactly - // which rows didn't persist (no silent "phantom save"). - const [erroredRows, setErroredRows] = useState>(new Set()); // ── Per-cell autosave (objectstack#35685), the select-first model's save ── // A committed cell sends its record's update at once; nothing waits for a // save bar. A refused update keeps its edits pending, so the row's next @@ -3008,7 +2997,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // objectstack#36023 — a value that fails its rules is not written: the // editor stays open with the reader's input, and says why. - const refusal = selectFirst ? editRefusalOf(row, columnKey, valueToStage) : null; + const refusal = editRefusalOf(row, columnKey, valueToStage); if (refusal !== null) { setEditRefusal({ text: refusal, value: valueToStage }); // A commit blurs the editor's control first (`flushInjectedEditor`): give it the caret back. @@ -3214,184 +3203,6 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { } }; - // A row's own save, from the save button on the row the record is drawn on: - // the edit kept under that record's key, handed over with the row the table - // holds for it now (objectui#12310). - // - // Cell editing stays open while the save is in flight, so when it settles it - // removes only what it sent, from the pending edits as they stand then - // (objectui#12322). - const saveRow = async (rowKey: PendingRowKey) => { - const pending = pendingChanges.get(rowKey); - - if (!pending || Object.keys(pending.changes).length === 0) return; - const rowChanges = pending.changes; - const row = heldRowOf(rowKey) ?? pending.row; - const sent = new Map([[rowKey, rowChanges]]); - // The editor open when the save was pressed, if any. - const openEditor = editingCellRef.current; - - setIsSaving(true); - try { - await whileInFlight(sent, async () => { - if (schema.onRowSave) { - await schema.onRowSave(rowIndexOf(rowKey), rowChanges, row); - } - }); - - // Clear this row's saved edits, and only those. - setPendingChanges((prev) => removeSentEdits(prev, sent)); - // A staged editor (e.g. a lookup picker, which keeps its widget open on - // pick rather than committing) must exit edit mode once its value is - // persisted — otherwise the saved cell stays stuck showing the editor. - // Only the editor that was open on this row when the save was pressed: - // one opened during the save is still in use. - if (openEditor !== null && openEditor.rowKey === rowKey && editingCellRef.current === openEditor) { - editingCellRef.current = null; - setEditingCell(null); - setEditValue(''); - } - // Saved — drop any prior error for this row, and clear the banner once - // no errored rows remain. - setErroredRows((prev) => { - if (!prev.has(rowKey)) return prev; - const next = new Set(prev); - next.delete(rowKey); - if (next.size === 0) setSaveError(null); - return next; - }); - setRowCellErrors(rowKey, null); - } catch (error) { - // Keep the pending change so the author can fix and retry; surface the - // reason instead of failing silently, flag the row, and mark the cells - // the refusal names. - console.error('Failed to save row:', error); - setSaveError(saveRefusalLines([error])); - setErroredRows((prev) => new Set(prev).add(rowKey)); - setRowCellErrors(rowKey, refusedCellsOf(error)); - } finally { - setIsSaving(false); - } - }; - - const cancelRowChanges = (rowKey: PendingRowKey) => { - const newPendingChanges = new Map(pendingChanges); - newPendingChanges.delete(rowKey); - setPendingChanges(newPendingChanges); - setErroredRows((prev) => { - if (!prev.has(rowKey)) return prev; - const next = new Set(prev); - next.delete(rowKey); - if (next.size === 0) setSaveError(null); - return next; - }); - setRowCellErrors(rowKey, null); - }; - - // Save All. Like `saveRow`, it settles against the pending edits as they - // stand when the batch returns, and removes only what it sent - // (objectui#12322). - const saveBatch = async () => { - if (pendingChanges.size === 0) return; - const sent = new Map(Array.from(pendingChanges, ([rowKey, pending]) => [rowKey, pending.changes] as const)); - // The editor open when Save All was pressed, if any. - const openEditor = editingCellRef.current; - - setIsSaving(true); - try { - // The record key each handed-over `rowIndex` came from, so a per-row - // outcome can name its row back (objectui#12292). - // - // Each edit goes out with its OWN record, resolved by key when Save All - // is pressed (objectui#12310): the row the table holds for that record - // now, with its global index; or, when the held rows no longer include - // it, the row the edit was staged against, with a negative `rowIndex` - // (-1, -2, …) that no held row can carry, so the outcome still names - // each entry apart. A position is never what picks the record. - const keyOfRowIndex = new Map(); - let notHeld = 0; - const changesToSave = Array.from(pendingChanges.entries()).map(([rowKey, pending]) => { - const held = heldRowOf(rowKey); - const rowIndex = held === undefined ? -(++notHeld) : rowIndexOf(rowKey); - keyOfRowIndex.set(rowIndex, rowKey); - return { rowIndex, changes: pending.changes, row: held ?? pending.row }; - }); - - // `void` at runtime is `undefined`: the handler persisted every row. - const outcome = (schema.onBatchSave - ? await whileInFlight(sent, async () => schema.onBatchSave?.(changesToSave)) - : undefined) as BatchSaveOutcome | undefined; - const failed = outcome?.failed ?? []; - const failedKeys = new Set(); - for (const entry of failed) { - const key = keyOfRowIndex.get(entry.rowIndex); - // A failure naming a row this batch never handed over cannot be - // placed, so no row can be called persisted: fall back to the - // all-or-nothing reading below rather than clear an unsaved edit. - if (key === undefined) throw entry.error; - failedKeys.add(key); - } - - // Any staged editor left open (e.g. a lookup picker that keeps its widget - // open on pick) must exit edit mode now that the batch has settled — - // otherwise the edited cell stays stuck showing the editor after 全部保存. - // Only the editor that was open when Save All was pressed: one opened - // during the save is still in use. - if (openEditor !== null && editingCellRef.current === openEditor) { - editingCellRef.current = null; - setEditingCell(null); - setEditValue(''); - } - if (failedKeys.size > 0) { - // Per-row outcome: the rows that persisted are cleared, and only the - // rows that did not are kept and flagged. The server already accepted - // the others, so keeping them pending would report a landed write as - // a failed one, and a retry would send it again. - console.error('Failed to save rows:', failed.map((entry) => entry.error)); - const landed = new Map(Array.from(sent).filter(([key]) => !failedKeys.has(key))); - setPendingChanges((prev) => removeSentEdits(prev, landed)); - setErroredRows(failedKeys); - // Every refused row's reasons, and the cells each refusal names - // (objectstack-ai/objectstack#27520). - setSaveError(saveRefusalLines(failed.map((entry) => entry.error))); - const refusedCells = new Map>(); - for (const entry of failed) { - const cells = refusedCellsOf(entry.error); - const key = keyOfRowIndex.get(entry.rowIndex); - if (cells && key !== undefined) refusedCells.set(key, cells); - } - setCellErrors(refusedCells); - return; - } - // Clear every edit the batch saved, and only those. - setPendingChanges((prev) => removeSentEdits(prev, sent)); - // Saved — clear any prior errors. - setErroredRows(new Set()); - setCellErrors(new Map()); - setSaveError(null); - } catch (error) { - // A rejection says nothing about which rows landed, so it is read as - // all-or-nothing: keep every pending row, flag every row it sent (not - // one staged during the save), and surface the reason instead of - // failing silently. - console.error('Failed to save batch:', error); - setSaveError(saveRefusalLines([error])); - setErroredRows(new Set(sent.keys())); - // Which row a whole-batch refusal's fields belong to is unknown, so no - // cell is marked; the save bar says every reason. - setCellErrors(new Map()); - } finally { - setIsSaving(false); - } - }; - - const cancelAllChanges = () => { - setPendingChanges(new Map()); - setErroredRows(new Set()); - setCellErrors(new Map()); - setSaveError(null); - }; - // ── Per-cell autosave (objectstack#35685) ──────────────────────────────── const setCellSaveState = (rowKey: PendingRowKey, columnKeys: readonly string[], state: 'saving' | 'saved' | null) => { setCellSaveStates((prev) => { @@ -3664,10 +3475,6 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const [rovingCell, setRovingCell] = useState<{ rowIndex: number; colIndex: number }>({ rowIndex: 0, colIndex: 0 }); const rovingRowIndex = Math.max(0, Math.min(rovingCell.rowIndex, paginatedData.length - 1)); const rovingColIndex = Math.max(0, Math.min(rovingCell.colIndex, columns.length - 1)); - // A cell whose edit was just ended from the keyboard, to be focused once the - // editor has unmounted (the effect below). A ref, not state: it is consumed - // by the commit that follows, and must not cause a render of its own. - const pendingCellFocusRef = useRef<{ rowIndex: number; colIndex: number } | null>(null); const rove = (rowIndex: number, colIndex: number) => { setRovingCell((prev) => @@ -3681,19 +3488,6 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { cell.focus(); }; - // The edit's editor is gone once this runs, so focus has nowhere to land but - // `` — hand it back to the cell, where the arrows carry on. Only an edit - // ended by a key that bubbled through its cell arms this (see - // `handleCellKeyDown`): one committed by a pointer press elsewhere leaves - // focus where that press put it. - useEffect(() => { - const target = pendingCellFocusRef.current; - if (!target || editingCell) return; - pendingCellFocusRef.current = null; - if (!keyboardNavigation) return; - focusGridCell(target.rowIndex, target.colIndex); - }); - /** * The cell an arrow / Home / End press moves to, or `null` when the key is * not a navigation key. At an edge the answer is the cell itself: the key is @@ -4210,14 +4004,6 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { 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 - // this render's value. Focus goes back to the cell after the commit. - if (editingCell && editingCellRef.current === null && (e.key === 'Enter' || e.key === 'Escape')) { - pendingCellFocusRef.current = { rowIndex, colIndex }; - return; - } // The cell itself, not a widget inside it: a link, a picker or an editor // keeps the keys it handles. if (!editingCell && e.target === e.currentTarget) { @@ -4247,24 +4033,13 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const globalIdx = (effectivePage - 1) * pageSize + rowIndex; const row = sortedData[manualPagination ? rowIndex : globalIdx]; if (row) copyCellValue(row, columnKey); - return; - } - - if (selectFirst || !editable || !rowMayEdit(paginatedData[rowIndex])) return; - - const column = columns.find(col => col.accessorKey === columnKey); - if (column?.editable === false) return; - - if (e.key === 'Enter' && !editingCell) { - e.preventDefault(); - startEdit(paginatedData[rowIndex], columnKey); } }; const handleEditKeyDown = (e: React.KeyboardEvent) => { // 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')) { + if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); // Already saving here; suppress the redundant save the ensuing blur triggers. skipBlurSaveRef.current = true; @@ -4273,10 +4048,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { if (!committed) skipBlurSaveRef.current = false; // The select-first model (objectstack#36023): Enter saves and stays on // the cell, Tab moves right, Shift+Tab left. - if (committed && selectFirst) commitMoves(e); + if (committed) commitMoves(e); } else if (e.key === 'Escape') { e.preventDefault(); - focusSelectionRef.current = selectFirst; + focusSelectionRef.current = true; cancelEdit(); } }; @@ -4286,8 +4061,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { useEffect(() => { if (editingCell && editInputRef.current) { editInputRef.current.focus(); - if (selectFirst) caretToEnd(editInputRef.current); - else editInputRef.current.select(); + caretToEnd(editInputRef.current); } }, [editingCell]); @@ -4466,7 +4240,6 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { return selectedRowIds.has(rowId); }) && !allPageRowsSelected; - const hasPendingChanges = pendingChanges.size > 0; // objectui#11816 — the trailing `rowActions` column is an EDIT column, not an // actions column, when nothing can put a row menu in it: the table is // editable with a save path, and no menu handler is supplied. Its cells then @@ -4481,14 +4254,12 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { schema.onRowDelete || (Array.isArray(schema.rowActionDefs) && schema.rowActionDefs.length > 0 && schema.onRowActionDef) ); - const rowActionsColumnIsEditOnly = editable && !!(schema.onRowSave || schema.onBatchSave) && !rowMenuDeclared; + const rowActionsColumnIsEditOnly = editable && !rowMenuDeclared; // objectstack#35685 — a table that saves each cell as it is committed never // draws the edit-only column: a list ends on its last data column // (objectstack#35554). A select-first table that stages (no `onRowSave`) // shows it only while a row has pending changes, as objectstack#35684 did. - const drawRowActionsColumn = rowActions - && !(autosaves && rowActionsColumnIsEditOnly) - && !(selectFirst && !autosaves && rowActionsColumnIsEditOnly && !hasPendingChanges); + const drawRowActionsColumn = rowActions && !rowActionsColumnIsEditOnly; /** * objectstack#36289 — what the table does with the data cell a row context @@ -4607,7 +4378,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const openRowContextMenuItems = rowContextMenu ? rowContextMenuItems(rowContextMenu.row, rowContextMenu.selected, rowContextMenu.column) : null; - const showToolbar = searchEnabled || exportable || (showSelectionCount && selectable && selectedRowIds.size > 0) || hasPendingChanges; + const showToolbar = searchEnabled || exportable || (showSelectionCount && selectable && selectedRowIds.size > 0); // The span of a row drawn as one cell across the table: the leading utility // cell, every column, the row-actions cell and the add-column cell. @@ -4649,33 +4420,6 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
- {/* objectstack#35685 — the select-first model saves each cell, so it draws no save bar. */} - {hasPendingChanges && !autosaves && ( - <> -
- {t('table.modified', { count: pendingChanges.size })} -
- - - - )} - {exportable && (
- {/* The last save's refusal, on a line of its own and said whole — - one line per reason (objectstack-ai/objectstack#27520). The - cells it names are marked in the table below. */} - {hasPendingChanges && !autosaves && saveError && ( -
- - {saveError.length === 1 ? ( - - {t('table.saveFailed')}: {saveError[0]} - - ) : ( -
- {t('table.saveFailed')}: -
    - {saveError.map((line) =>
  • {line}
  • )} -
-
- )} -
- )} )} @@ -4964,20 +4684,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { {/* The label sits in the same 13px muted span every data column's header label uses (objectui#11816): a bare string here took the cell's larger default type. */} - {drawRowActionsColumn && (rowActionsColumnIsEditOnly ? ( - - - ) : ( + {drawRowActionsColumn && ( {t('common.actions')} - ))} + )} {addColumnEnabled && ( - - - ) : ( - /* Trigger + menu, or nothing when this row's - predicates leave no item to show (#3562). */ - - )} + {/* Trigger + menu, or nothing when this row's + predicates leave no item to show (#3562). */} + )} diff --git a/ui/packages/components/src/renderers/complex/dataTableBindDiagnostic.ts b/ui/packages/components/src/renderers/complex/dataTableBindDiagnostic.ts index 9741ff76d20..85c1e8f4143 100644 --- a/ui/packages/components/src/renderers/complex/dataTableBindDiagnostic.ts +++ b/ui/packages/components/src/renderers/complex/dataTableBindDiagnostic.ts @@ -288,3 +288,38 @@ export function describeNonArrayData( + 'takes its rows only from an array: every non-array value is dropped to zero rows, so the ' + `table renders its header over an empty body.\n${wayOut}`; } + +/** The first word of the refused-`editable` line, for a reader filtering the console. */ +export const DATA_TABLE_EDITABLE_DIAGNOSTIC_PREFIX = '[ObjectUI] DataTable editable:'; + +/** + * The message for a `data-table` node whose `editable: true` the table refuses, + * or `null` when there is nothing to say (objectstack#35827). + * + * The table has ONE editing model: select-first, each committed cell saved at + * once through `onRowSave`. The staged model — click-to-edit, a + * pending-changes bar and "Save All" through `onBatchSave` — is retired, so an + * `editable` table without both a select-first host (`GridCellSelection`) and + * an `onRowSave` slot has no way to save an edit. It draws read-only rather + * than hold an edit nothing sends; this line says so, once per node, on the + * channel the other diagnostics in this module use. + * + * It changes no behaviour of its own: the refusal is the renderer's + * (`editable` takes effect only where it can save), and this only names it. + */ +export function describeUnsavableEditable( + editable: boolean, + savePath: { selectFirst: boolean; rowSave: boolean }, + address: DataTableNodeAddress, +): string | null { + if (!editable || (savePath.selectFirst && savePath.rowSave)) return null; + const missing = [ + savePath.selectFirst ? null : 'no select-first cell model is mounted around it (`GridCellSelection`)', + savePath.rowSave ? null : 'no `onRowSave` slot is supplied to save each committed cell', + ].filter((part): part is string => part !== null); + return `${DATA_TABLE_EDITABLE_DIAGNOSTIC_PREFIX} ${describeAddress(address)} — ` + + `\`editable: true\` is refused and the table renders read-only: ${missing.join(', and ')}. ` + + 'Inline editing saves each committed cell on its own; there is no staged "Save All" mode.\n' + + ' Render an `object-grid` (`ObjectGrid`), which mounts both and writes through its data ' + + 'source, or mount `GridCellSelection` and pass `onRowSave` in code.'; +} diff --git a/ui/packages/data-objectstack/src/index.ts b/ui/packages/data-objectstack/src/index.ts index 7208d0acd4d..b26865fc105 100644 --- a/ui/packages/data-objectstack/src/index.ts +++ b/ui/packages/data-objectstack/src/index.ts @@ -3714,7 +3714,7 @@ export class ObjectStackAdapter implements DataSource { // Subscribers registered via onMutation(). Emitted after each successful // create/update/delete so data-bound views (ListView, ObjectView, kanban, // calendar) auto-refresh — the interface ListView relies on to reflect - // inline-edit "Save All" writes without a manual reload. + // inline-edit cell saves without a manual reload. private mutationListeners = new Set<(event: DataSourceMutationEvent) => void>(); // objectui#13442 — how many `batchMutationEvents` scopes are open, and the // events held back while any is. Keyed by type + resource, so a 100-row run @@ -4383,7 +4383,7 @@ export class ObjectStackAdapter implements DataSource { /** * Subscribe to create/update/delete events on any resource. Returns an * unsubscribe function. Data-bound views use this to auto-refresh after a - * mutation (e.g. inline-edit "Save All", which writes through `update` and + * mutation (e.g. an inline-edit cell save, which writes through `update` and * must repaint the list without a manual reload). */ onMutation(callback: (event: DataSourceMutationEvent) => void): () => void { diff --git a/ui/packages/plugin-grid/README.md b/ui/packages/plugin-grid/README.md index 1f32d6d6f11..b979bde197f 100644 --- a/ui/packages/plugin-grid/README.md +++ b/ui/packages/plugin-grid/README.md @@ -225,8 +225,8 @@ const grid: ObjectGridBlockNode = { | `grouping` | `GroupingConfig` | Row grouping — **server-side**: group set, counts and aggregations come from the query, rows are paged per group; see [Grouping is server-side](#grouping-is-server-side). | **There is no `sortable`, `filterable`, `onRowClick`, `onSelectionChange`, -`onCellChange`, `onRowSave`, `onBatchSave` or `object` on this schema.** The -booleans do not exist at all; the five `on*` names are **component props** +`onCellChange`, `onRowSave` or `object` on this schema.** The +booleans do not exist at all; the four `on*` names are **component props** (`ObjectGridComponentProps`), which no metadata document can carry — see [Row callbacks are component props](#row-callbacks-are-component-props). @@ -835,15 +835,15 @@ verdict. ### Row callbacks are component props -`onRowClick`, `onRowSelect`, `onCellChange`, `onRowSave`, `onBatchSave`, `onEdit`, +`onRowClick`, `onRowSelect`, `onCellChange`, `onRowSave`, `onEdit`, `onDelete`, `onBulkDelete` and `onAddRecord` are React props on `ObjectGridComponentProps` — they are functions, so no metadata document can hold them, and writing one into a schema does nothing at all: the grid builds the inner -table's handlers itself and never reads any of these nine off the schema. +table's handlers itself and never reads any of these eight off the schema. The one callback the grid does read off the schema is `onNavigate`, declared on `ObjectGridSchema` for programmatic callers only. It is a function value too, so -it is no more authorable than the nine — it is deliberately absent from the +it is no more authorable than the eight — it is deliberately absent from the manifest and the designer panel, and prefer passing it as a prop (objectui#5234, maintainer ruling of 2026-08-19). @@ -1042,16 +1042,13 @@ deletes it from existing sources. (formula, autonumber, file, …), never open an editor (`isFieldInlineEditable` in `src/inline-edit-options.ts`). There is no `editable` key on `ListColumn`. -- **Rich text edits in a panel**: on a select-first grid (`cellSelection`), a - `markdown`, `html` or `richtext` cell opens the record form's text box in a - panel under the cell (Enter is a new line, Ctrl/Cmd+Enter saves, Escape - discards, a click outside saves); the cell keeps showing its value and the row - its height. A grid without `cellSelection` opens the text box over the cell on - one click, where Enter is a new line, Ctrl/Cmd+Enter does nothing, Escape - discards and a click outside keeps the text as a pending change for the save - buttons. -- **Visual feedback**: editable cells show a hover state -- **Automatic focus**: the input is focused and selected when editing begins +- **Rich text edits in a panel**: a `markdown`, `html` or `richtext` cell opens + the record form's text box in a panel under the cell (Enter is a new line, + Ctrl/Cmd+Enter saves, Escape discards, a click outside saves); the cell keeps + showing its value and the row its height. +- **Visual feedback**: the selected cell is ringed +- **Automatic focus**: the editor takes the caret, after the value, when editing + begins **Use Cases:** - Quick data corrections @@ -1089,21 +1086,20 @@ WAI-ARIA grid pattern (objectui#11068): `editable` *and* the viewer's permission to update the object, the same value inline editing obeys — because that grid selects a cell first and moves the selection with these keys; `false` does not turn it off there - (objectstack#36270), except where a React host keeps the staged model with - `cellSelection={false}` (see Batch Editing below). A read-only grid keeps every - cell its own Tab stop unless you write `true`. + (objectstack#36270). A read-only grid keeps every cell its own Tab stop unless + you write `true`. - While it is on, the table is exposed to assistive technology as a `grid`. A grouped grid navigates within each group's table; the mobile card layout has no cells and is unaffected. -### Batch Editing & Multi-Row Save +### Owning persistence: `onRowSave` -Edit multiple cells across multiple rows and save them individually or all at once. -This is the staged model, which no metadata selects: since objectstack#36270 every -grid that renders editable saves each cell as it is committed. A React host that -draws `ObjectGrid` itself opts back into it with `cellSelection={false}`; then a -click opens a cell's editor, and the save/cancel affordances appear on their own -once a row has pending changes: +There is one editing model. Every grid that renders editable is select-first and +saves each committed cell on its own (objectstack#36270); the staged model it +replaced — click-to-edit, a pending-changes bar, "Save All" and the batch handler +`onBatchSave` — is retired (objectstack#35827), and so is the host's way back into +it, `cellSelection={false}`. `cellSelection` takes only `true` now: it asks for the +select-first model on a grid that renders read-only. An editable grid needs no prop: ```tsx import { ObjectGrid, type ObjectGridComponentProps } from '@object-ui/plugin-grid'; @@ -1112,7 +1108,6 @@ declare const dataSource: NonNullable; export const ProductsGrid = () => ( ( ); ``` -Left alone, saving goes through the host's data source. A React host that needs to -own persistence supplies `onRowSave` / `onBatchSave` as **component props** — and -because they are props, they take the adapter from the host's own scope rather than -from anything in the schema: +Left alone, each committed cell is written through the host's data source. A React +host that needs to own persistence supplies `onRowSave` as a **component prop** — and +because it is a prop, it takes the adapter from the host's own scope rather than from +anything in the schema. It is called once per commit, with every edit that record +still holds: ```tsx import type { ObjectGridComponentProps } from '@object-ui/plugin-grid'; -type Persistence = Pick; +type Persistence = Pick; const persistence = ( dataSource: NonNullable, @@ -1145,53 +1141,24 @@ const persistence = ( onRowSave: async (rowIndex, changes, row) => { await dataSource.update('products', row.id, changes); }, - onBatchSave: async (allChanges) => { - await Promise.all( - allChanges.map(({ row, changes }) => dataSource.update('products', row.id, changes)), - ); - }, }); ``` -**Batch Editing Features:** -- **Pending changes tracking**: Edit multiple cells across multiple rows before saving -- **Visual indicators**: - - Modified rows are highlighted with amber background - - Modified cells are shown in bold with amber text - - Toolbar shows count of modified rows -- **Row-level actions**: Save or cancel changes for individual rows -- **Batch operations**: - - "Save All" button to save all modified rows at once - - "Cancel All" button to discard all pending changes -- **Flexible callbacks** — all three are `ObjectGridComponentProps`, never schema keys: - - `onRowSave`: called when saving a single row - - `onBatchSave`: called when saving multiple rows at once — `@deprecated`: only - this staged model calls it; on a select-first grid each cell saves through - `onRowSave` (or the grid's own write) and `onBatchSave` is never called - - `onCellChange`: called for each staged cell edit -- **A concurrent write is refused, not overwritten**: the default saves send each +**Upgrading from the staged model:** drop `cellSelection={false}`; move a batch +`onBatchSave(allChanges)` handler to a per-record `onRowSave(rowIndex, changes, row)`, +or drop it and let the grid write through its data source. + +- **A refused save keeps the edit**: the cell keeps what was typed and says the + server's reason; the record's next commit sends it again together with the new + cell, as one update. +- **A concurrent write is refused, not overwritten**: the default save sends the row's `updated_at` as `If-Match`, and an editable grid asks for that column even when no column shows it. A row someone else saved after it was read answers `409`, which opens the record page's conflict dialog (Reload latest, Overwrite - anyway, Cancel). "Save All" reports each row on its own: a refused row stays - pending and flagged, and the rows that saved are cleared. -- **Each pending edit stays on its record**: edits are kept by the record's `id`, - not by row position, so a re-read in a new order (a row save's refresh, the - data-invalidation bus, a page change) draws and saves every edit on the record - it was typed on. An edit whose record the current page no longer holds stays - pending, and "Save All" still writes it to that record. -- **Editing during a save is kept**: cells stay editable while a row save or - "Save All" is in flight, and the save clears only the values it sent. An edit - made during the save, on any row or on the cell being saved, stays pending. - -**Example Workflow:** -1. User edits multiple cells across different rows -2. Modified rows are visually highlighted -3. Toolbar shows "X rows modified" with Save All/Cancel All buttons -4. User can: - - Save individual rows using row-level save button - - Save all changes at once using "Save All" button - - Cancel individual row changes or all changes + anyway, Cancel). +- **Each edit stays on its record**: edits are kept by the record's `id`, not by row + position, so a re-read in a new order draws and saves every edit on the record it + was typed on. ### Export diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index a13ea04860e..dc7b9bc6ba0 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -24,7 +24,7 @@ import React, { useEffect, useState, useCallback, useMemo } from 'react'; import type { ObjectGridSchema, DataSource, ViewData, TableSortItem, DataTableSchema, ListViewExportFormat, RecordNavigateAction } from '@object-ui/types'; import { isSystemManagedField, detectStatusField } from '@object-ui/types'; -import { SchemaRenderer, isPermissionError, useDataScope, useNavigationOverlay, useAction, useSafeFieldLabel, usePredicateScope, useCapabilityGate, useDrawsAction, useRelatedRecordActions, notifyDataChanged, useMetadata, claimAnswerWarnings, toastRecordSave, useOwnWrites, createOwnWrites, type AnswerWarningClaim, type RecordSaveFeedback } from '@object-ui/react'; +import { SchemaRenderer, isPermissionError, useDataScope, useNavigationOverlay, useAction, useSafeFieldLabel, usePredicateScope, useCapabilityGate, useDrawsAction, useRelatedRecordActions, notifyDataChanged, useMetadata, claimAnswerWarnings, toastRecordSave, useOwnWrites, createOwnWrites } from '@object-ui/react'; // objectui#8920 — the grid reaches a cell renderer through THIS module and // nowhere else. `getCellRenderer` / `resolveCellRendererType` are deliberately // NOT imported here: six sites spelling the resolve three different ways is @@ -107,7 +107,7 @@ import { rowRecordId } from './objectGridLinkCell'; import { useGridTranslation } from './objectGridTranslations'; import { inlineEditRuleRefusals, inlineRuleRefusalError } from './objectGridInlineRules'; import { DEFAULT_DISPLAY_PAGE_SIZE, DEFAULT_SELECTION_TYPE, type RowHeightMode, resolvePageSize, resolveRowHeightMode } from './objectGridDefaults'; -import { type BatchSaveOutcome, type RowConflictChoice, type WrittenRowVersion, rowVersionOf, rowVersionToSend } from './objectGridRowVersion'; +import { type RowConflictChoice, type WrittenRowVersion, rowVersionOf, rowVersionToSend } from './objectGridRowVersion'; import { type RowPatch, mergeSavedRow, rowsAsSaved } from './objectGridRowPatch'; import { usableGroupingFields } from './useGroupedData'; import { type CellSaveUndo, createCellUndoStack, isCellUndoKey, undoKeyCellOf } from './objectGridCellUndo'; @@ -437,15 +437,19 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr * cell and never edits it or opens the record; double-click, Enter, F2 or * typing edits (Space included); each committed cell saves at once and * updates its own row (objectstack#35685); a cell that opens no editor says - * why (`describeCell`, `./objectGridCellFacts`). `false` ⇒ the table keeps - * its staged click-to-edit / click-to-open behaviour. Absent ⇒ the model - * follows whether the grid renders editable (objectstack#36270): an editable - * grid is select-first, a read-only one keeps click-to-open. + * why (`describeCell`, `./objectGridCellFacts`). Absent ⇒ the model follows + * whether the grid renders editable (objectstack#36270): an editable grid is + * select-first, a read-only one keeps click-to-open. + * + * Only `true`: the staged opt-out `cellSelection={false}` (click-to-edit, a + * pending-changes bar and "Save All") is retired (objectstack#35827). An + * editable grid has one editing model; a read-only grid keeps click-to-open + * without the prop. * * A RUNTIME prop, never authored metadata: the host decides it, and no node * key reaches it. */ - cellSelection?: boolean; + cellSelection?: true; /** * [objectstack#35876] The column header opens the column menu (sort * ascending, sort descending, hide) instead of sorting on a click, as the @@ -535,19 +539,6 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr bulkChangeOwnerOffered?: boolean; onCellChange?: (rowIndex: number, columnKey: string, newValue: any, row: any) => void; onRowSave?: (rowIndex: number, changes: Record, row: any) => void | Promise; - /** - * Called by "Save All" with every staged row — the staged model only. - * - * @deprecated objectstack#36270 — a grid that renders editable is - * select-first by default, and there each edited cell saves on its own - * through {@link ObjectGridComponentProps.onRowSave} (or, when the host - * passes none, the grid's own write through `dataSource.update`). No - * "Save All" is drawn, so this handler is never called and no runtime - * notice says so. - * Pass `onRowSave` to own the write per cell, or pass `cellSelection={false}` - * to keep the staged model, where this handler is still called. - */ - onBatchSave?: (changes: Array<{ rowIndex: number; changes: Record; row: any }>) => void | Promise; onRowSelect?: (selectedRows: any[]) => void; onAddRecord?: () => void; } @@ -677,9 +668,9 @@ function getDataConfig(schema: ObjectGridSchema): ViewData | null { * - the card's speculative list (`pagination`, `manualPagination`, `rowCount`, * `frozenColumns`, `singleClickEdit`, `selectionResetKey`, * `disableInnerScroll`, `borderless`) was already declared then, and is - * still declared now (`singleClickEdit` here is the TABLE's own key, which - * `ObjectGrid` now always passes as `true`; the `object-grid` key of that - * name is retired, objectstack#36270); + * still declared now — except `singleClickEdit`, the TABLE's own key, which + * left with the staged editing model (objectstack#35827; the `object-grid` + * key of that name was retired by objectstack#36270); * - the two keys that survived that diff, `renderCellEditor` and * `cellClassName`, were DECLARED by `bf97b98c8` (maintainer ruling * 2026-08-30) on three surfaces: @@ -961,7 +952,6 @@ export const ObjectGrid: React.FC = ({ onNavigate, onCellChange, onRowSave, - onBatchSave, onAddRecord, // The host-driven mode (`ObjectGridExternalPaginationProps`). Every one of // these was read out of `...rest` through an `as any` cast until #4277 gave @@ -1339,10 +1329,10 @@ export const ObjectGrid: React.FC = ({ // Enter or typing opens its editor, and each committed cell saves on its own, // with no pending-changes bar and no "Save All" (the model `ListView` and the // related tab ask for by name, objectstack#35684). A grid that renders - // read-only keeps click-to-open. A host's own `cellSelection` wins either - // way: `true` asks for the model on a read-only grid too (`ListView`), and - // `false` keeps the staged click-to-edit on an editable one. - const hostCellSelection = cellSelectionProp ?? inlineEditable; + // read-only keeps click-to-open. A host's `cellSelection` asks for the model + // on a read-only grid too (`ListView`); there is no opting out of it on an + // editable one (objectstack#35827 retired the staged model). + const hostCellSelection = cellSelectionProp === true || inlineEditable; // When the consumer wired onEdit/onDelete callbacks but the view schema // omits an explicit `operations` block, default to allowing those actions. @@ -1474,10 +1464,10 @@ export const ObjectGrid: React.FC = ({ recordIds: pageRecordIds, update: canEdit || inlineEditable, delete: canDelete, - // objectstack#34208 — inline cells read `update` while rendering, before any row action is used. - // objectstack#35684 — select-first cells read it only when the reader acts - // on one, so they ask when a cell is first selected (`onCellSelect` below). - updateOnMount: inlineEditable && !hostCellSelection, + // objectstack#35684 — select-first cells read `update` only when the + // reader acts on one, so they ask when a cell is first selected + // (`onCellSelect` below); an editable grid is always select-first + // (objectstack#35827), so nothing is asked on mount. }); // objectstack#35684 — what the select-first table asks about a cell when @@ -1804,11 +1794,11 @@ export const ObjectGrid: React.FC = ({ // Publishing it into the designer panel and the generated // `sdui-intrinsics.d.ts` would advertise an offer nobody can take, which // is the option the ruling rejected as the most AI-error-prone of the - // three. Programmatic callers already have the channel its nine siblings + // three. Programmatic callers already have the channel its eight siblings // use: `onRowClick`, `onRowSelect`, `onCellChange`, `onRowSave`, - // `onBatchSave`, `onEdit`, `onDelete`, `onBulkDelete` and `onAddRecord` - // are props on `ObjectGridComponentProps`, and since objectui#9547 this one - // is the tenth prop there, which is where a caller should prefer to pass + // `onEdit`, `onDelete`, `onBulkDelete` and `onAddRecord` are props on + // `ObjectGridComponentProps`, and since objectui#9547 this one is the + // ninth prop there, which is where a caller should prefer to pass // it. When both are supplied the PROP WINS (maintainer ruling C on // objectui#9547), so `schema.onNavigate` below is the fallback read — kept, // because a host that builds the node in TypeScript still reaches the slot @@ -3048,14 +3038,13 @@ export const ObjectGrid: React.FC = ({ // Default inline-edit persistence. // - // When a consumer wires `onRowSave`/`onBatchSave` (React host), we defer to it. - // But a declaratively-configured `editable: true` view has no host wiring — so - // "Save All" would otherwise just clear pending changes without writing to the - // backend. Supply a default that persists through the grid's `dataSource`, then - // refresh so the grid reflects persisted values. Reporting failure is - // important: DataTable's saveRow keeps a row's pending changes when the save - // promise rejects, and saveBatch keeps exactly the rows the batch hands back - // as `failed`, so a failed write doesn't silently lose the user's edits. + // When a consumer wires `onRowSave` (React host), we defer to it. A + // declaratively-configured `editable: true` view has no host wiring, so the + // grid supplies a default that persists each committed cell through its own + // `dataSource` (objectstack#35827: the table's only save path). Reporting + // failure is important: the table keeps a record's edits when the save + // promise rejects and marks the refused cells, so a failed write doesn't + // silently lose the user's edits. // The one place a row's primary key is read for a write. `string`, as // `@objectstack/spec` declares every record door — the union this used to // annotate was a claim about `any`-typed row data, not a measurement of it @@ -3390,149 +3379,38 @@ export const ObjectGrid: React.FC = ({ // write is one toast. const claim = claimAnswerWarnings(dataSource, { operation: 'update', resource: objectName, id }); try { - if (hostCellSelection) { - // objectstack#35685 — the select-first model: the row redraws in - // place, and the save can be taken back. What Undo restores is read - // off the row before the write (relations as their stored ids); a - // written field the row does not carry offers no Undo at all. - const key = String(id); - const restore = captureUpdateUndoData(Object.keys(changes), row, objectSchema?.fields); - const written = await writeRowInPlace(key, changes, row); - // A reload re-reads through the bus; there is nothing of ours to show. - if (written.outcome === 'reloaded') return; - const feedback = claim.take(undefined); - if (!restore) { - toastRecordSave(toast, t('table.saved', { count: 1 }), feedback); - return; - } - const entry: CellSaveUndo = { - objectName, - id: key, - version: rowVersionOf(written.result), - restore, - shown: Object.fromEntries(Object.keys(changes).map((field) => [field, row[field]])), - }; - cellUndoRef.current.push(entry); - const savedRow = mergeSavedRow(row, changes, written.result); - toastRecordSave(toast, t('table.saved', { count: 1 }), feedback, { - label: t('actions.undo'), - onClick: () => { void undoCellSave(entry, savedRow); }, - }); + // objectstack#35685 — the select-first model: the row redraws in + // place, and the save can be taken back. What Undo restores is read + // off the row before the write (relations as their stored ids); a + // written field the row does not carry offers no Undo at all. + const key = String(id); + const restore = captureUpdateUndoData(Object.keys(changes), row, objectSchema?.fields); + const written = await writeRowInPlace(key, changes, row); + // A reload re-reads through the bus; there is nothing of ours to show. + if (written.outcome === 'reloaded') return; + const feedback = claim.take(undefined); + if (!restore) { + toastRecordSave(toast, t('table.saved', { count: 1 }), feedback); return; } - try { - await writeRowGuarded(dataSource, objectName, id, changes, row); - } catch (err) { - if (!isConcurrentUpdateError(err)) throw err; - // A reload re-reads through the bus; there is nothing of ours to show. - if ((await resolveRowConflict(dataSource, objectName, id, changes, row, err)).outcome === 'reloaded') return; - } - // Refresh so the grid shows the persisted values. - setRefreshKey(k => k + 1); - // objectui#12303 — the write is said, through the console's shared toast - // (the one the form, kanban and view surfaces raise). Only here, once the - // row landed: a refusal rejects above, and the table flags the row. - toastRecordSave(toast, t('table.saved', { count: 1 }), claim.take(undefined)); + const entry: CellSaveUndo = { + objectName, + id: key, + version: rowVersionOf(written.result), + restore, + shown: Object.fromEntries(Object.keys(changes).map((field) => [field, row[field]])), + }; + cellUndoRef.current.push(entry); + const savedRow = mergeSavedRow(row, changes, written.result); + toastRecordSave(toast, t('table.saved', { count: 1 }), feedback, { + label: t('actions.undo'), + onClick: () => { void undoCellSave(entry, savedRow); }, + }); } finally { claim.release(); } }; - const defaultBatchSave = async ( - changes: Array<{ rowIndex: number; changes: Record; row: any }>, - ): Promise => { - if (!dataSource || !objectName) { - throw new Error('Cannot persist inline edits: no dataSource/objectName configured on the grid.'); - } - // Update each modified row. The DataSource `bulk`/`bulkUpdate` primitives - // apply a single uniform patch across many ids, which does NOT fit per-row - // edits (each row has its own field changes), so issue one update per row. - // - // Each row is its own write and its own outcome (objectui#12292). All are - // attempted together and every one is waited for, so a refused row never - // hides what happened to the others; a conflict is then put to the user - // one row at a time. Nothing the server accepted is taken back: the rows - // that landed are reported as saved, and only the rows that did not are - // handed back to the table as `failed`. - const ids = changes.map(({ row }) => resolveRecordId(row)); - // objectstack-ai/objectstack#28252 — each row's write answer feedback rides - // the one "Save All" toast below, as the single-row save's does. - const claims: AnswerWarningClaim[] = ids.flatMap((id) => - id === undefined || id === null ? [] : [claimAnswerWarnings(dataSource, { operation: 'update', resource: objectName, id })], - ); - try { - return await saveRowsClaimed(dataSource, objectName, changes, ids, claims); - } finally { - for (const claim of claims) claim.release(); - } - }; - - /** The body of {@link defaultBatchSave}, run while its rows' claims are open. */ - const saveRowsClaimed = async ( - dataSource: DataSource, - objectName: string, - changes: Array<{ rowIndex: number; changes: Record; row: any }>, - ids: Array, - claims: AnswerWarningClaim[], - ): Promise => { - const attempts = await Promise.allSettled( - changes.map(({ changes: rowChanges, row }, i) => { - const id = ids[i]; - if (id === undefined || id === null) { - return Promise.reject(new Error('Cannot persist inline edit: row has no id/_id.')); - } - // A row whose edits break a field rule is refused here, unsent; the - // other rows still go (each row is its own outcome). - const refused = inlineRuleRefusal(rowChanges); - if (refused) return Promise.reject(refused); - return writeRowGuarded(dataSource, objectName, id, rowChanges, row); - }), - ); - const failed: BatchSaveOutcome['failed'] = []; - // How many rows the server accepted — the number the toast below names. - let saved = 0; - for (let i = 0; i < changes.length; i++) { - const attempt = attempts[i]; - if (attempt.status === 'fulfilled') { - saved += 1; - continue; - } - const { rowIndex, changes: rowChanges, row } = changes[i]; - const id = ids[i]; - const err: unknown = attempt.reason; - if (!isConcurrentUpdateError(err) || id === undefined || id === null) { - failed.push({ rowIndex, error: err }); - continue; - } - try { - if ((await resolveRowConflict(dataSource, objectName, id, rowChanges, row, err)).outcome === 'saved') { - saved += 1; - } - } catch (resolutionError) { - failed.push({ rowIndex, error: resolutionError }); - } - } - if (saved > 0) { - // Refresh so the grid shows the persisted values. - setRefreshKey(k => k + 1); - // objectui#12303 — "Save All" says what it saved, through the console's - // shared toast, counting only the rows the server accepted. A row that - // failed is not in the count: the table keeps it, flags it and shows - // the reason. A reloaded row wrote nothing, so it is not either. - // A row that wrote nothing parked nothing, so every claim is read. - const feedback: RecordSaveFeedback = { warnings: [] }; - const notices: string[] = []; - for (const claim of claims) { - const own = claim.take(undefined); - for (const w of own.warnings) if (!feedback.warnings.includes(w)) feedback.warnings.push(w); - if (own.notice && !notices.includes(own.notice)) notices.push(own.notice); - } - if (notices.length > 0) feedback.notice = notices.join('\n'); - toastRecordSave(toast, t('table.saved', { count: saved }), feedback); - } - return failed.length > 0 ? { failed } : undefined; - }; - // Determine pagination settings (support both new and legacy formats) // // "presence enables; an explicit off wins" — the same ONE rule @@ -4040,11 +3918,6 @@ export const ObjectGrid: React.FC = ({ ); } : undefined, - // objectstack#36270 — the authored `singleClickEdit` is retired: a grid - // that renders editable is select-first, where a click selects. A host - // that keeps the staged model (`cellSelection={false}`) edits on a single - // click, the retired key's default. - singleClickEdit: true, // objectui#11068 — arrow-key cell navigation on the WAI-ARIA grid pattern: // the data cells become ONE roving Tab stop that the arrows move (the // behaviour is `data-table`'s, documented on `DataTableSchema`). The @@ -4053,12 +3926,12 @@ export const ObjectGrid: React.FC = ({ // viewer's write verdict (#5143), the same value handed down above. So a // grid that renders read-only keeps every cell its own Tab stop unless the // author writes `true`. On an editable grid the select-first model is the - // default (objectstack#36270) and data-table keeps navigation on under it - // (`keyboardNavigationProp || selectFirst`), so an explicit `false` only - // turns it off where the host keeps the staged model (`cellSelection={false}`). + // model (objectstack#36270, the only one since objectstack#35827) and + // data-table keeps navigation on under it (`keyboardNavigationProp || + // selectFirst`), so an explicit `false` has no effect there. // Not an alias fallback: the right side is the key's own default. keyboardNavigation: schema.keyboardNavigation ?? inlineEditable, - // The save bar sits on the grid's own inset, as its cells do (`px-3`), + // The toolbar sits on the grid's own inset, as its cells do (`px-3`), // never flush against the view's edge (objectstack-ai/objectstack#27520). // objectstack#35548 / #36048 — a 36px header at 13px over faint row and column lines. className: ['[&>[data-slot=table-toolbar]]:px-3 [&>[data-slot=table-toolbar]]:pt-2', OBJECT_GRID_TABLE_DENSITY, schema.className].filter(Boolean).join(' '), @@ -4118,7 +3991,6 @@ export const ObjectGrid: React.FC = ({ // Install a dataSource-backed default only when the consumer did NOT wire // its own handler, so declarative `editable: true` views still persist. onRowSave: onRowSave ?? defaultRowSave, - onBatchSave: onBatchSave ?? defaultBatchSave, onColumnResize: (columnKey: string, width: number) => { saveColumnState({ ...columnState, diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx index d7d408251ca..959dbbec18c 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx @@ -19,8 +19,8 @@ * answer carried. * 3. A 409 the user keeps as theirs ("Overwrite anyway") re-reads nothing * either; "Reload latest" does read again. - * 4. Control: without `cellSelection` the save bar's row save still - * re-reads the grid. + * 4. (Retired with the staged model, objectstack#35827: the save bar's row + * save that re-read the grid without `cellSelection`.) * 5. Undo (slice S2): the save toast's Undo button and Ctrl+Z / Cmd+Z on a * cell take a save back as a NEW guarded update of the prior value, * newest first, each once, guarded by the version the grid's own write @@ -120,7 +120,7 @@ function makeDataSource() { } as any; } -function renderGrid(dataSource: any, cellSelection: boolean) { +function renderGrid(dataSource: any, cellSelection: true) { const schema: any = { type: 'object-grid', objectName: OBJECT, @@ -313,33 +313,6 @@ describe('ObjectGrid autosave — a 409 kept as mine re-reads nothing either (ob }); }); -describe('ObjectGrid autosave — control: without cellSelection the row save re-reads', () => { - it('stages, saves from the bar, and reads the grid again', async () => { - const ds = makeDataSource(); - const { container } = renderGrid(ds, false); - await screen.findByText('beta'); - const reads = ds.find.mock.calls.length; - const cell = dataCell(container, 0, 'alpha'); - fireEvent.click(cell); - const input = await waitFor(() => { - const el = cell.querySelector('input') as HTMLInputElement; - expect(el).toBeTruthy(); - return el; - }); - fireEvent.change(input, { target: { value: 'alpha one' } }); - fireEvent.keyDown(input, { key: 'Enter' }); - expect(ds.update).not.toHaveBeenCalled(); - const saveAll = await waitFor(() => { - const btn = Array.from(container.querySelectorAll('button')).find((b) => /Save All/.test(b.textContent || '')); - expect(btn).toBeTruthy(); - return btn as HTMLButtonElement; - }); - fireEvent.click(saveAll); - await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); - await waitFor(() => expect(ds.find.mock.calls.length).toBeGreaterThan(reads)); - }); -}); - /** The Undo button of the `n`th success toast (0-based), as the grid handed it to the toast. */ function undoOfToast(n: number): { label: string; onClick: () => void } | undefined { return (toasts.success.mock.calls[n]?.[1] as { action?: { label: string; onClick: () => void } } | undefined)?.action; @@ -520,28 +493,9 @@ describe('ObjectGrid autosave — Undo takes a save back as a new guarded update expect(screen.getByText('11')).toBeInTheDocument(); }); - it('control: without cellSelection the save toast carries no Undo', async () => { - const ds = makeDataSource(); - const { container } = renderGrid(ds, false); - await screen.findByText('beta'); - const cell = dataCell(container, 0, 'alpha'); - fireEvent.click(cell); - const input = await waitFor(() => { - const el = cell.querySelector('input') as HTMLInputElement; - expect(el).toBeTruthy(); - return el; - }); - fireEvent.change(input, { target: { value: 'alpha one' } }); - fireEvent.keyDown(input, { key: 'Enter' }); - const saveAll = await waitFor(() => { - const btn = Array.from(container.querySelectorAll('button')).find((b) => /Save All/.test(b.textContent || '')); - expect(btn).toBeTruthy(); - return btn as HTMLButtonElement; - }); - fireEvent.click(saveAll); - await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(1)); - expect(undoOfToast(0)).toBeUndefined(); - }); + // The staged control (no Undo on a save from the "Save All" bar) is gone + // with the bar (objectstack#35827): every save of an editable grid is a + // per-cell save, and each carries Undo. }); describe("ObjectGrid — a grid without cellSelection re-reads on the host list's own write (objectstack#35685)", () => { diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx index f9036fad3be..d738a3324eb 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx @@ -186,20 +186,8 @@ describe('ObjectGrid cellSelection — the relay (objectstack#35684)', () => { expect(container.querySelector('td[data-editing-cell]')).toBeNull(); }); - it('control: `cellSelection: false` keeps the staged click-to-edit', async () => { - const { container } = render( - , - ); - await screen.findByText('Gamma', {}, { timeout: 5000 }); - const first = container.querySelector('tbody tr td[data-grid-cell]')!; - fireEvent.click(first); - await waitFor(() => expect(container.querySelector('td[data-editing-cell]')).not.toBeNull()); - expect(first).not.toHaveAttribute('data-selected-cell'); - }); + // objectstack#35827 — the `cellSelection: false` control left with the staged + // click-to-edit it pinned: an editable grid has no other editing model. }); describe('ObjectGrid cellSelection — why a cell opens no editor', () => { diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.keyboardNavigation-11068.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.keyboardNavigation-11068.test.tsx index d41112c8ab8..28d29c85b65 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.keyboardNavigation-11068.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.keyboardNavigation-11068.test.tsx @@ -187,15 +187,9 @@ describe('an editable `object-grid` always has it on: it selects a cell first (o expect(cellAt(container, 1, 0)).toHaveAttribute('data-selected-cell'); }); - it('CONTROL: a host that keeps the staged model (`cellSelection: false`) keeps the roving cell focus, and `false` turns it off', async () => { - const on = render(); - await screen.findByText('Gamma', {}, { timeout: 5000 }); - expect(reading(on.container)).toEqual(ON); - cleanup(); - const off = render(); - await screen.findByText('Gamma', {}, { timeout: 5000 }); - expect(reading(off.container)).toEqual(OFF); - }); + // objectstack#35827 — the staged-model control (`cellSelection: false`, where + // `keyboardNavigation: false` turned the roving focus off on an editable grid) + // left with the staged model: an editable grid is always select-first. }); /* ── 3. The `editable` that counts is the one the grid renders ───────────── */ diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.peoplePickName-36046.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.peoplePickName-36046.test.tsx index 0a33623147e..f2333853c9b 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.peoplePickName-36046.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.peoplePickName-36046.test.tsx @@ -112,7 +112,6 @@ function renderGrid(ds: any) { type: 'object-grid', objectName: OBJECT, editable: true, - singleClickEdit: true, columns: [ { field: 'name', label: 'Name' }, { field: 'owner', label: 'Owner' }, diff --git a/ui/packages/plugin-grid/src/__tests__/authoredGridPerCellSave-36270.test.tsx b/ui/packages/plugin-grid/src/__tests__/authoredGridPerCellSave-36270.test.tsx index e1dd506ad4b..0c68d9627de 100644 --- a/ui/packages/plugin-grid/src/__tests__/authoredGridPerCellSave-36270.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/authoredGridPerCellSave-36270.test.tsx @@ -12,7 +12,7 @@ * renderer) that edits (`editable: true`) edits as the list page's grid does: * a click selects a cell, Enter opens its editor, and the committed cell saves * on its own. No pending-changes bar and no "Save All" is drawn. A read-only - * node keeps click-to-open, and a host that says `cellSelection` itself wins. + * node keeps click-to-open unless its host asks for `cellSelection`. * * Rendered through `SchemaRenderer` and the registry, the path an authored * node takes, never by importing `ObjectGrid` directly. @@ -129,12 +129,13 @@ describe('objectstack#36270 — an authored editable object-grid saves each cell expect(catcher()).toBeNull(); }); - it("CONTROL: a host's own `cellSelection` wins over the node's `editable`", async () => { + it("a host's `cellSelection` asks for the model on a read-only node too", async () => { + // objectstack#35827 — `true` is the prop's only value: the staged opt-out + // (`cellSelection: false` on an editable node) is retired. const { ds } = makeDataSource(); - mount({ editable: true }, ds, { cellSelection: false }); + mount({}, ds, { cellSelection: true }); await screen.findByText('Beta'); fireEvent.click(screen.getByText('Alpha').closest('td') as HTMLElement); - await new Promise((r) => setTimeout(r, 50)); - expect(catcher()).toBeNull(); + await waitFor(() => expect(catcher()).toBeTruthy()); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/columnTypeEmitSeam.test.tsx b/ui/packages/plugin-grid/src/__tests__/columnTypeEmitSeam.test.tsx index 0a0e854c42f..34c934fb351 100644 --- a/ui/packages/plugin-grid/src/__tests__/columnTypeEmitSeam.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/columnTypeEmitSeam.test.tsx @@ -54,7 +54,7 @@ function renderTyped(type: string) { return render( { type _ColumnsSurvive = Expect; - type _SingleClickTyped = Expect< - DeclaredDataTableSchema['singleClickEdit'] extends boolean | undefined ? true : false + type _ResizableTyped = Expect< + DeclaredDataTableSchema['resizableColumns'] extends boolean | undefined ? true : false >; // @ts-expect-error objectui#6459 — `columns` is required; the mapped type must not have made it optional. const missing: ObjectGridDataTableSchema = { type: 'data-table', data: [] }; diff --git a/ui/packages/plugin-grid/src/__tests__/gridDependentValues-7165.test.tsx b/ui/packages/plugin-grid/src/__tests__/gridDependentValues-7165.test.tsx index f64ddc442ea..12659be0ad1 100644 --- a/ui/packages/plugin-grid/src/__tests__/gridDependentValues-7165.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/gridDependentValues-7165.test.tsx @@ -56,7 +56,7 @@ * key — the shape objectui#6875 established and objectui#7154 reused. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, within, cleanup } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, within, cleanup, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -161,7 +161,7 @@ function renderGrid(ds: any, rows: any[]) { return render( - + , ); @@ -182,6 +182,7 @@ function cellAt(container: HTMLElement, rowIndex: number, index: number): HTMLEl */ async function openEditor(cell: HTMLElement): Promise { fireEvent.click(cell); + fireEvent.doubleClick(cell); // select-first: a click selects, a double-click edits (objectstack#35827) return await waitFor(() => { const panel = cell.querySelector('[data-testid="lookup-in-cell"]'); expect(panel).toBeTruthy(); @@ -279,49 +280,51 @@ describe('objectui#7165 — the grid feeds the inline editor its row as dependen expect(within(openPanel).getByTestId('browse-all-records')).not.toBeDisabled(); }); - it('4 — ⭐ objectui#7188: a STAGED parent re-scopes the child before anything is saved', async () => { - // Under option A (objectui#7165) this test pinned the OPPOSITE as current - // behaviour: `dependentValues={ctx.row}` is the SAVED record, so staging - // `region: 'south'` in this same row left the child scoped by the persisted - // 'north'. objectui#7188 carries the staged record across the seam — - // `data-table` passes `pendingRow` (the row merged with its `pendingChanges` - // entry) and the grid scopes by `ctx.pendingRow ?? ctx.row` — so this is - // the assertion that goes RED if anyone "simplifies" B back to A. Tests 1–3 - // cannot see that regression: their rows carry no staged edits, so - // `pendingRow` and `row` coincide there. + it('4 — ⭐ objectui#7188: a committed parent whose save is still on the wire re-scopes the child', async () => { + // `dependentValues={ctx.row}` would be the SAVED record, so a new + // `region: 'south'` in this same row would leave the child scoped by the + // persisted 'north'. objectui#7188 carries the edited record across the + // seam — `data-table` passes `pendingRow` (the row merged with its + // `pendingChanges` entry) and the grid scopes by `ctx.pendingRow ?? + // ctx.row` — so this is the assertion that goes RED if anyone + // "simplifies" B back to A. Since the staged model is retired + // (objectstack#35827) the parent's commit saves at once, so the save is + // held open here: while it is on the wire the row still reads 'north' + // and only the pending entry says 'south'. const rows = [ROW_NORTH]; const ds = makeDataSource(rows); + let landSave!: () => void; + ds.update.mockImplementation((_o: string, _id: string, changes: any) => + new Promise((resolve) => { landSave = () => resolve(changes); })); const { container } = renderGrid(ds, rows); await waitFor(() => expect(screen.getByText('Task one')).toBeInTheDocument()); - // Stage a new parent WITHOUT saving. `region` is a `text` field, so its - // widget is `TextField` and is NOT in `DISCRETE_EDIT_TYPES` — its `onChange` - // routes to `ctx.stage`, which writes `pendingChanges` without closing. + // A new parent, committed with Enter. const regionCell = cellAt(container, 0, 1); fireEvent.click(regionCell); - const regionInput = await waitFor(() => { - const el = regionCell.querySelector('input'); - expect(el).toBeTruthy(); - return el as HTMLInputElement; - }); - fireEvent.change(regionInput, { target: { value: 'south' } }); + fireEvent.doubleClick(regionCell); + // The editor sits on the cell's overlay layer (objectstack#35688), which + // mounts after the double-click: read the input off that layer. + const editorInput = () => container.querySelector('[data-slot="cell-editor-overlay"] input'); + await waitFor(() => expect(editorInput()).toBeTruthy()); + await act(async () => {}); + fireEvent.change(editorInput()!, { target: { value: 'south' } }); + fireEvent.keyDown(editorInput()!, { key: 'Enter' }); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); - // Open the child. Clicking another cell moves the edit; the staged value - // stays in `pendingChanges`. await openEditor(cellAt(container, 0, 3)); await waitFor(() => expect(screen.getByText('Person 07')).toBeInTheDocument()); - // ⭐ PROOF THE STAGING LANDED AND NOTHING WAS SAVED. Without the first half - // this test could pass for a trivial reason (nothing staged, the saved - // parent honoured as in test 2); without the second, a save would make the - // staged and persisted parents coincide and the test could not tell A from - // B. The region cell renders its PENDING value ('south') while the saved - // record still says 'north' and the data source saw no write. + // ⭐ PROOF THE SAVE IS STILL OUT. The region cell draws 'south' while the + // record the grid read still says 'north' and its write has not landed; + // a landed save would make the two coincide and the test could not tell + // A from B. await waitFor(() => { expect(cellAt(container, 0, 1).textContent).toMatch(/south/); }); expect(rows[0].region).toBe('north'); - expect(ds.update).not.toHaveBeenCalled(); + expect(ds.update).toHaveBeenCalledTimes(1); + expect(ds.update.mock.calls[0][2]).toEqual({ region: 'south' }); // Scoped by the STAGED 'south', not the saved 'north': Person 07 is south // (offered); Person 01 is north (not offered). The query carried the staged @@ -329,5 +332,6 @@ describe('objectui#7165 — the grid feeds the inline editor its row as dependen expect(screen.queryByText('Person 01')).not.toBeInTheDocument(); expect(ds.refQueries.some((q: any) => q?.$filter?.region === 'south')).toBe(true); expect(ds.refQueries.some((q: any) => q?.$filter?.region === 'north')).toBe(false); + await act(async () => { landSave(); }); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/gridNonAuthorKeys.test.tsx b/ui/packages/plugin-grid/src/__tests__/gridNonAuthorKeys.test.tsx index 75be8da9ea2..0e2ce7f8418 100644 --- a/ui/packages/plugin-grid/src/__tests__/gridNonAuthorKeys.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/gridNonAuthorKeys.test.tsx @@ -673,9 +673,12 @@ const objectGridSchemaSpan = (): [number, number] => { return [start, end]; }; -/** The nine sibling callbacks the type note and the README claim are props-only. */ -const NINE_SIBLINGS = [ - 'onRowClick', 'onRowSelect', 'onCellChange', 'onRowSave', 'onBatchSave', +/** + * The eight sibling callbacks the type note and the README claim are + * props-only (`onBatchSave` was the ninth until objectstack#35827 retired it). + */ +const EIGHT_SIBLINGS = [ + 'onRowClick', 'onRowSelect', 'onCellChange', 'onRowSave', 'onEdit', 'onDelete', 'onBulkDelete', 'onAddRecord', ] as const; @@ -733,10 +736,10 @@ describe('`onNavigate` — the ledger premises (objectui#5234)', () => { ).toBe(1); }); - it('…and does NOT declare the nine siblings, which is the contrast the note draws', () => { - // The type note and both docs pages say the nine live only on + it('…and does NOT declare the eight siblings, which is the contrast the note draws', () => { + // The type note and both docs pages say the eight live only on // `ObjectGridComponentProps`. Measured here so the claim cannot go stale - // under them: a tenth callback arriving on the schema would make the note + // under them: a ninth callback arriving on the schema would make the note // false while every other assertion in this file stayed green. const [start, end] = objectGridSchemaSpan(); const declaredInSpan = new Set( @@ -748,11 +751,11 @@ describe('`onNavigate` — the ledger premises (objectui#5234)', () => { // Non-vacuity: the scan found the interface's members at all. expect(declaredInSpan.size).toBeGreaterThan(20); expect(declaredInSpan.has('onNavigate')).toBe(true); - for (const sibling of NINE_SIBLINGS) { + for (const sibling of EIGHT_SIBLINGS) { expect( declaredInSpan.has(sibling), `\`${sibling}\` is now declared on ObjectGridSchema. The programmatic-only note on` - + ' `onNavigate` and the README both say the nine live ONLY on' + + ' `onNavigate` and the README both say the eight live ONLY on' + ' `ObjectGridComponentProps` — one of them is now wrong.', ).toBe(false); } diff --git a/ui/packages/plugin-grid/src/__tests__/inCellSelectMultipleRouting-35688.test.tsx b/ui/packages/plugin-grid/src/__tests__/inCellSelectMultipleRouting-35688.test.tsx index 843fd07a00d..2cead7b1547 100644 --- a/ui/packages/plugin-grid/src/__tests__/inCellSelectMultipleRouting-35688.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inCellSelectMultipleRouting-35688.test.tsx @@ -107,7 +107,7 @@ function makeDataSource() { } as any; } -function renderGrid(cellSelection = false) { +function renderGrid(cellSelection?: true) { const ds = makeDataSource(); const schema: any = { type: 'object-grid', @@ -143,14 +143,14 @@ function cellUnder(container: HTMLElement, label: string): HTMLElement { return container.querySelectorAll('tbody tr')[0].querySelectorAll('td')[at] as HTMLElement; } -// The grid batches edits (no `cellSelection`, so no per-cell autosave): what a -// pick wrote shows as the row's pending change, and nothing reaches `update`. +// An editable grid is select-first and saves each committed cell at once +// (objectstack#35827): what a pick wrote reaches `update` as the row's one write. describe('ObjectGrid cell editor: a select declared multiple (objectstack#35688 S2)', () => { it('each check stages and the editor stays open; moving on closes it with every check', async () => { - const { container } = renderGrid(); + const { container, ds } = renderGrid(); await waitFor(() => expect(screen.getByText('Design system')).toBeInTheDocument()); - fireEvent.click(cellUnder(container, 'Colors')); + { const opened = cellUnder(container, 'Colors'); fireEvent.click(opened); fireEvent.doubleClick(opened); } await waitFor(() => expect(screen.getByTestId('in-cell-option-red')).toBeInTheDocument()); fireEvent.click(screen.getByTestId('in-cell-option-red')); @@ -162,39 +162,43 @@ describe('ObjectGrid cell editor: a select declared multiple (objectstack#35688 fireEvent.pointerDown(screen.getByTestId('outside')); await waitFor(() => expect(screen.queryByTestId('in-cell-option-red')).toBeNull()); - // This grid batches its edits: the row carries the three colours, pending. - await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument()); + // One write, with the three colours: the checks were staged while open. + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][1]).toBe('r1'); + expect([...(ds.update.mock.calls[0][2] as { colors: string[] }).colors].sort()).toEqual(['blue', 'green', 'red']); const cell = cellUnder(container, 'Colors'); for (const label of ['Blue', 'Red', 'Green']) expect(cell.textContent).toContain(label); expect(screen.queryByTestId('in-cell-option-red')).toBeNull(); }); it('CONTROL: a single select saves on the pick and closes', async () => { - const { container } = renderGrid(); + const { container, ds } = renderGrid(); await waitFor(() => expect(screen.getByText('Design system')).toBeInTheDocument()); - fireEvent.click(cellUnder(container, 'Priority')); + { const opened = cellUnder(container, 'Priority'); fireEvent.click(opened); fireEvent.doubleClick(opened); } await waitFor(() => expect(screen.getByTestId('in-cell-option-low')).toBeInTheDocument()); fireEvent.click(screen.getByTestId('in-cell-option-low')); // The pick closes the editor, and the click that made it does not open it again. await waitFor(() => expect(screen.queryByTestId('in-cell-option-low')).toBeNull()); - await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument()); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0].slice(1, 3)).toEqual(['r1', { priority: 'low' }]); expect(cellUnder(container, 'Priority').textContent).toContain('Low'); }); }); describe('ObjectGrid cell editor: lookups and ratings (objectstack#35688 S3)', () => { it('a lookup cell opens its candidate list in place; a pick ends the edit', async () => { - const { container } = renderGrid(); + const { container, ds } = renderGrid(); await waitFor(() => expect(screen.getByText('Design system')).toBeInTheDocument()); - fireEvent.click(cellUnder(container, 'Tier')); + { const opened = cellUnder(container, 'Tier'); fireEvent.click(opened); fireEvent.doubleClick(opened); } await waitFor(() => expect(screen.getByTestId('lookup-in-cell')).toBeInTheDocument()); fireEvent.click(await screen.findByText('Silver')); await waitFor(() => expect(screen.queryByTestId('lookup-in-cell')).toBeNull()); - await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument()); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0].slice(1, 3)).toEqual(['r1', { tier: 'silver' }]); }); it('a single pick from Browse all ends the edit too, and saves the picked id', async () => { diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditConcurrency-12292.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditConcurrency-12292.test.tsx index 023f3fe5f99..22a659f19fe 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditConcurrency-12292.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditConcurrency-12292.test.tsx @@ -29,7 +29,7 @@ * on that projection too, not only on a save that drops the token. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, cleanup, within, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -166,8 +166,7 @@ function renderGrid(server: ReturnType) { return render( - {/* Row Edit/Delete handlers: the per-row save button exists. */} - {}} onDelete={() => {}} /> + {}} onDelete={() => {}} /> , ); @@ -175,7 +174,11 @@ function renderGrid(server: ReturnType) { const rowOf = (title: string) => screen.getByText(title).closest('tr') as HTMLElement; -/** Stage a new Estimate on the row titled `title`, the way a user types it. */ +/** + * Type a new Estimate on the row titled `title` and commit it with Enter, the + * way a user does on the select-first grid: a click selects, a double-click + * edits, and the commit is the save (objectstack#35827). + */ async function editEstimate(title: string, from: string, to: string) { const td = await waitFor(() => { const cell = Array.from(rowOf(title).querySelectorAll('td')).find( @@ -185,19 +188,18 @@ async function editEstimate(title: string, from: string, to: string) { return cell as HTMLElement; }); fireEvent.click(td); - const input = await waitFor(() => { - const el = td.querySelector('input') as HTMLInputElement | null; - if (!el) throw new Error('editor not open'); - return el; - }); + fireEvent.doubleClick(td); + // The editor mounts on the cell's overlay layer (objectstack#35688): let it + // settle, then read the input it holds. + await waitFor(() => expect(td.querySelector('[data-slot="cell-editor-overlay"] input')).toBeTruthy()); + await act(async () => {}); + const input = td.querySelector('[data-slot="cell-editor-overlay"] input') as HTMLInputElement; fireEvent.change(input, { target: { value: to } }); fireEvent.keyDown(input, { key: 'Enter' }); await waitFor(() => expect(within(rowOf(title)).getByText(to)).toBeInTheDocument()); } const conflictDialog = () => screen.findByRole('alertdialog'); -const clickSaveAll = () => - fireEvent.click(screen.getByRole('button', { name: /Save All/ })); async function loaded(server: ReturnType) { renderGrid(server); @@ -212,7 +214,6 @@ describe('ObjectGrid inline edit carries the row token (objectui#12292)', () => server.writeAsOtherUser('t1', { estimate_hours: 77 }); await editEstimate('Ingest pipeline', '60', '61'); - fireEvent.click(within(rowOf('Ingest pipeline')).getByTitle('Save row')); const dialog = await conflictDialog(); expect(server.patches).toEqual([ @@ -224,13 +225,13 @@ describe('ObjectGrid inline edit carries the row token (objectui#12292)', () => expect(within(dialog).getByText('61')).toBeInTheDocument(); expect(within(dialog).getByText('77')).toBeInTheDocument(); - // Cancel: nothing is written, the edit is kept and the row reads unsaved. + // Cancel: nothing is written, the edit is kept on its cell and says why. fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Record was modified by another user'), ); expect(server.store.t1.estimate_hours).toBe(77); - expect(screen.getByText(/1 row modified/)).toBeInTheDocument(); + expect(within(rowOf('Ingest pipeline')).getByText('61')).toBeInTheDocument(); expect(server.patches).toHaveLength(1); }); @@ -241,7 +242,6 @@ describe('ObjectGrid inline edit carries the row token (objectui#12292)', () => server.writeAsOtherUser('t1', { estimate_hours: 77 }); const theirVersion = server.store.t1.updated_at; await editEstimate('Ingest pipeline', '60', '61'); - clickSaveAll(); fireEvent.click(within(await conflictDialog()).getByRole('button', { name: 'Overwrite anyway' })); await waitFor(() => expect(server.store.t1.estimate_hours).toBe(61)); @@ -249,7 +249,7 @@ describe('ObjectGrid inline edit carries the row token (objectui#12292)', () => [expect.any(String), 409], [theirVersion, 200], ]); - await waitFor(() => expect(screen.queryByText(/row modified/)).toBeNull()); + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); }); it('Reload latest writes nothing and re-reads the record', async () => { @@ -258,70 +258,37 @@ describe('ObjectGrid inline edit carries the row token (objectui#12292)', () => server.writeAsOtherUser('t1', { estimate_hours: 77 }); await editEstimate('Ingest pipeline', '60', '61'); - clickSaveAll(); fireEvent.click(within(await conflictDialog()).getByRole('button', { name: 'Reload latest' })); await waitFor(() => expect(within(rowOf('Ingest pipeline')).getByText('77')).toBeInTheDocument()); expect(server.store.t1.estimate_hours).toBe(77); expect(server.patches).toHaveLength(1); - expect(screen.queryByText(/row modified/)).toBeNull(); }); it('a fresh save succeeds, and the next save sends the token the server answered with', async () => { const server = makeServer([{ id: 't1', title: 'Ingest pipeline', estimate_hours: 60 }]); await loaded(server); const readVersion = server.store.t1.updated_at; - // The grid's re-read after the save has not landed: reads keep answering - // the row as it was loaded, token and all. + // Reads keep answering the row as it was loaded, token and all: the next + // save's token can only come from the write's own answer. server.freezeReads(); await editEstimate('Ingest pipeline', '60', '61'); - clickSaveAll(); await waitFor(() => expect(server.store.t1.estimate_hours).toBe(61)); const answeredVersion = server.store.t1.updated_at; expect(server.patches[0]).toEqual({ id: 't1', ifMatch: readVersion, body: { estimate_hours: 61 }, status: 200 }); - await waitFor(() => expect(screen.queryByText(/row modified/)).toBeNull()); - // The row still shows the stale read; the second save must not 409 over - // the user's own first save. - await editEstimate('Ingest pipeline', '60', '62'); - clickSaveAll(); + // The row draws the write's answer in place; the second save must not 409 + // over the user's own first save. + await editEstimate('Ingest pipeline', '61', '62'); await waitFor(() => expect(server.store.t1.estimate_hours).toBe(62)); expect(server.patches[1]).toEqual({ id: 't1', ifMatch: answeredVersion, body: { estimate_hours: 62 }, status: 200 }); expect(screen.queryByRole('alertdialog')).toBeNull(); }); - it('a batch with one stale row reports that row and keeps the row that saved', async () => { - const server = makeServer([ - { id: 't1', title: 'Ingest pipeline', estimate_hours: 60 }, - { id: 't2', title: 'Warehouse schema', estimate_hours: 33 }, - ]); - await loaded(server); - - server.writeAsOtherUser('t1', { estimate_hours: 77 }); - await editEstimate('Ingest pipeline', '60', '61'); - await editEstimate('Warehouse schema', '33', '31'); - expect(screen.getByRole('button', { name: /Save All \(2\)/ })).toBeInTheDocument(); - clickSaveAll(); - - const dialog = await conflictDialog(); - // Both rows were sent with their own token; only the stale one was refused. - expect(server.patches.map((p) => [p.id, p.status]).sort()).toEqual([['t1', 409], ['t2', 200]]); - expect(server.patches.every((p) => typeof p.ifMatch === 'string')).toBe(true); - fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); - - // The stale row alone stays pending and flagged; the saved row is not - // rolled back and is not reported as failed. - await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument()); - expect(screen.getByRole('button', { name: /Save All \(1\)/ })).toBeInTheDocument(); - expect(screen.getByRole('alert')).toHaveTextContent('Record was modified by another user'); - expect(within(rowOf('Ingest pipeline')).getByText('61')).toBeInTheDocument(); - await waitFor(() => expect(within(rowOf('Warehouse schema')).getByText('31')).toBeInTheDocument()); - expect(server.store.t2.estimate_hours).toBe(31); - expect(server.store.t1.estimate_hours).toBe(77); - // No silent retry. - expect(server.patches).toHaveLength(2); - }); + // "a batch with one stale row" pinned Save All's per-row outcome; each + // commit is its own save now (objectstack#35827), and a stale one is the + // first case above. it('asks the server for the token even though no column shows it', async () => { const server = makeServer([{ id: 't1', title: 'Ingest pipeline', estimate_hours: 60 }]); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditConflictFields-33557.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditConflictFields-33557.test.tsx index 69c452ebe06..31a4f514e1e 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditConflictFields-33557.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditConflictFields-33557.test.tsx @@ -23,7 +23,7 @@ * field's own before and after, no list). */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, cleanup, within, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -143,7 +143,7 @@ function renderGrid(server: ReturnType) { return render( - {}} onDelete={() => {}} /> + {}} onDelete={() => {}} /> , ); @@ -151,7 +151,10 @@ function renderGrid(server: ReturnType) { const rowOf = (title: string) => screen.getByText(title).closest('tr') as HTMLElement; -/** Stage a new value on the cell of the row titled `title` that reads `from`, the way a user types it. */ +/** + * Type a new value on the cell of the row titled `title` that reads `from` and + * commit it with Enter: select-first, a commit is the save (objectstack#35827). + */ async function editCell(title: string, from: string, to: string) { const td = await waitFor(() => { const cell = Array.from(rowOf(title).querySelectorAll('td')).find( @@ -161,11 +164,11 @@ async function editCell(title: string, from: string, to: string) { return cell as HTMLElement; }); fireEvent.click(td); - const input = await waitFor(() => { - const el = td.querySelector('input') as HTMLInputElement | null; - if (!el) throw new Error('editor not open'); - return el; - }); + fireEvent.doubleClick(td); + // The editor mounts on the cell's overlay layer (objectstack#35688). + await waitFor(() => expect(td.querySelector('[data-slot="cell-editor-overlay"] input')).toBeTruthy()); + await act(async () => {}); + const input = td.querySelector('[data-slot="cell-editor-overlay"] input') as HTMLInputElement; fireEvent.change(input, { target: { value: to } }); fireEvent.keyDown(input, { key: 'Enter' }); await waitFor(() => expect(within(rowOf(title)).getByText(to)).toBeInTheDocument()); @@ -176,11 +179,19 @@ async function staleRowSave(edits: Array<[from: string, to: string]>) { renderGrid(server); await waitFor(() => expect(screen.getByText('Ingest pipeline')).toBeInTheDocument()); server.writeAsOtherUser('t1', { estimate_hours: 77, owner_note: 'blocked' }); - for (const [from, to] of edits) await editCell('Ingest pipeline', from, to); - fireEvent.click(within(rowOf('Ingest pipeline')).getByTitle('Save row')); - const dialog = await screen.findByRole('alertdialog'); - expect(server.statuses).toEqual([409]); - return dialog; + // Each commit is its own save. A refused cell is kept on its row and goes + // out again with the row's next commit, so the last save carries every edit. + let dialog: HTMLElement | null = null; + for (const [i, [from, to]] of edits.entries()) { + if (dialog) { + fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); + } + await editCell('Ingest pipeline', from, to); + dialog = await screen.findByRole('alertdialog'); + expect(server.statuses).toEqual(Array(i + 1).fill(409)); + } + return dialog!; } describe('a multi-field grid row conflict lists each field (objectstack#33557)', () => { diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditDatePicker-12664.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditDatePicker-12664.test.tsx index 17f852c8c5b..52f279c0ae4 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditDatePicker-12664.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditDatePicker-12664.test.tsx @@ -21,9 +21,11 @@ * * The text cell at the bottom is the CONTROL: a widget that stages on every * keystroke commits exactly as before, with no focus and so no blur at all. + * Each commit is the cell's save (objectstack#35827), so the readout is the + * write itself. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, within, cleanup } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, within, cleanup, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -113,7 +115,7 @@ function renderGrid(ds: any, language?: string) {
- +
@@ -139,14 +141,19 @@ function cellOf(container: HTMLElement, column: 'name' | 'due' | 'remind_at'): H return row.querySelectorAll('td')[index] as HTMLElement; } -/** Click the cell into edit mode and wait for the lazily loaded picker's text box. */ +/** + * Open the cell's editor the select-first way (a click selects, a double-click + * edits; objectstack#35827) and wait for the lazily loaded picker's text box, + * read once the editor's overlay layer (objectstack#35688) has settled. + */ async function openPicker(container: HTMLElement, column: 'due' | 'remind_at'): Promise { fireEvent.click(cellOf(container, column)); - return waitFor(() => { - const input = cellOf(container, column).querySelector('[data-slot="date-picker"] input'); - if (!input) throw new Error('date picker not rendered'); - return input as HTMLInputElement; + fireEvent.doubleClick(cellOf(container, column)); + await waitFor(() => { + if (!cellOf(container, column).querySelector('[data-slot="date-picker"] input')) throw new Error('date picker not rendered'); }); + await act(async () => {}); + return cellOf(container, column).querySelector('[data-slot="date-picker"] input') as HTMLInputElement; } /** What a user does: put the caret in the box and type. The picker stages nothing yet. */ @@ -155,20 +162,6 @@ function typeInto(input: HTMLInputElement, text: string) { fireEvent.change(input, { target: { value: text } }); } -async function saveAll(container: HTMLElement) { - const btn = await waitFor(() => { - const el = Array.from(container.querySelectorAll('button')).find((b) => - /Save All|全部保存/.test(b.textContent || ''), - ) as HTMLButtonElement | undefined; - if (!el) throw new Error('no Save All: nothing is staged'); - return el; - }); - fireEvent.click(btn); -} - -const saveAllButton = (container: HTMLElement) => - Array.from(container.querySelectorAll('button')).find((b) => /Save All|全部保存/.test(b.textContent || '')); - describe('ObjectGrid inline editor — date / datetime draw the platform picker (objectui#12664)', () => { it('a date cell edits with the picker, not input[type=date]', async () => { const ds = makeDataSource(); @@ -190,7 +183,7 @@ describe('ObjectGrid inline editor — date / datetime draw the platform picker expect(input.value).toBe('2026/10/01'); }); - it('(a) typed day + Enter: the edit is staged with that day', async () => { + it('(a) typed day + Enter: the edit is saved with that day', async () => { const ds = makeDataSource(); const { container } = renderGrid(ds); await waitFor(() => expect(screen.getByText('Row One')).toBeInTheDocument()); @@ -198,11 +191,10 @@ describe('ObjectGrid inline editor — date / datetime draw the platform picker typeInto(input, '10/20/2026'); fireEvent.keyDown(input, { key: 'Enter' }); await waitFor(() => expect(cellOf(container, 'due').querySelector('[data-slot="date-picker"]')).toBeNull()); - await saveAll(container); await waitFor(() => expect(ds.update).toHaveBeenCalledWith(OBJECT, 'r1', { due: '2026-10-20' }, undefined)); }); - it('(b) typed day + click outside: the edit is staged with that day', async () => { + it('(b) typed day + click outside: the edit is saved with that day', async () => { const ds = makeDataSource(); const { container } = renderGrid(ds); await waitFor(() => expect(screen.getByText('Row One')).toBeInTheDocument()); @@ -210,11 +202,10 @@ describe('ObjectGrid inline editor — date / datetime draw the platform picker typeInto(input, '10/20/2026'); fireEvent.pointerDown(screen.getByTestId('outside')); await waitFor(() => expect(cellOf(container, 'due').querySelector('[data-slot="date-picker"]')).toBeNull()); - await saveAll(container); await waitFor(() => expect(ds.update).toHaveBeenCalledWith(OBJECT, 'r1', { due: '2026-10-20' }, undefined)); }); - it('(b) datetime: typed date and time + click outside stages that local instant', async () => { + it('(b) datetime: typed date and time + click outside saves that local instant', async () => { const ds = makeDataSource(); const { container } = renderGrid(ds); await waitFor(() => expect(screen.getByText('Row One')).toBeInTheDocument()); @@ -222,7 +213,6 @@ describe('ObjectGrid inline editor — date / datetime draw the platform picker typeInto(input, '10/20/2026 14:30'); fireEvent.pointerDown(screen.getByTestId('outside')); await waitFor(() => expect(cellOf(container, 'remind_at').querySelector('[data-slot="date-picker"]')).toBeNull()); - await saveAll(container); await waitFor(() => expect(ds.update).toHaveBeenCalledWith( OBJECT, @@ -233,7 +223,7 @@ describe('ObjectGrid inline editor — date / datetime draw the platform picker ); }); - it('(c) typed day + Escape: nothing is staged', async () => { + it('(c) typed day + Escape: nothing is saved', async () => { const ds = makeDataSource(); const { container } = renderGrid(ds); await waitFor(() => expect(screen.getByText('Row One')).toBeInTheDocument()); @@ -243,29 +233,24 @@ describe('ObjectGrid inline editor — date / datetime draw the platform picker await waitFor(() => expect(cellOf(container, 'due').querySelector('[data-slot="date-picker"]')).toBeNull()); // A pointer press elsewhere afterwards must not resurrect the discarded text. fireEvent.pointerDown(screen.getByTestId('outside')); - expect(saveAllButton(container)).toBeUndefined(); + await act(async () => {}); expect(ds.update).not.toHaveBeenCalled(); }); - it('(d) CONTROL: a text cell still stages per keystroke, with no focus and no blur', async () => { + it('(d) CONTROL: a text cell stages per keystroke, so a press outside commits it with no focus and no blur', async () => { const ds = makeDataSource(); const { container } = renderGrid(ds); await waitFor(() => expect(screen.getByText('Row One')).toBeInTheDocument()); const nameTd = cellOf(container, 'name'); fireEvent.click(nameTd); - const input = await waitFor(() => { - const el = nameTd.querySelector('input') as HTMLInputElement | null; - if (!el) throw new Error('no text editor'); - return el; - }); + fireEvent.doubleClick(nameTd); + await waitFor(() => expect(nameTd.querySelector('[data-slot="cell-editor-overlay"] input')).toBeTruthy()); + await act(async () => {}); + const input = nameTd.querySelector('[data-slot="cell-editor-overlay"] input') as HTMLInputElement; fireEvent.change(input, { target: { value: 'Row One EDITED' } }); - // Staged already, while the editor is still open: Save All is offered. - await waitFor(() => expect(saveAllButton(container)).toBeTruthy()); - expect(nameTd.querySelector('input')).toBeTruthy(); fireEvent.pointerDown(screen.getByTestId('outside')); - await waitFor(() => expect(nameTd.querySelector('input')).toBeNull()); - expect(within(nameTd).getByText('Row One EDITED')).toBeInTheDocument(); - await saveAll(container); + await waitFor(() => expect(nameTd.querySelector('[data-slot="cell-editor-overlay"]')).toBeNull()); await waitFor(() => expect(ds.update).toHaveBeenCalledWith(OBJECT, 'r1', { name: 'Row One EDITED' }, undefined)); + expect(within(nameTd).getByText('Row One EDITED')).toBeInTheDocument(); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditDuringSave-12322.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditDuringSave-12322.test.tsx index cba196282f6..22ec9439da3 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditDuringSave-12322.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditDuringSave-12322.test.tsx @@ -7,8 +7,8 @@ */ /** - * objectui#12322 — an estimate typed while a row save or Save All is on the - * wire is still pending when the save lands. + * objectui#12322 — an estimate typed while a save is on the wire is not lost + * when the save lands. * * `ObjectGrid`'s default saves await `dataSource.update` over the network, and * every cell stays editable meanwhile. `data-table` used to settle a save by @@ -16,7 +16,9 @@ * pressed, so an edit staged during the round trip vanished with no signal. * The table's own pins are in `@object-ui/components` * (`data-table-save-settles-current-12322.test.tsx`); these run the console's - * path end to end. + * path end to end. The staged row save and Save All are retired + * (objectstack#35827): each commit is its own save, so the edit made during + * the round trip is a second save of its own record. * * ## What is real here * @@ -140,8 +142,7 @@ function renderGrid(server: ReturnType) { return render( - {/* Row Edit/Delete handlers: the per-row save button exists. */} - {}} onDelete={() => {}} /> + {}} onDelete={() => {}} /> , ); @@ -149,7 +150,7 @@ function renderGrid(server: ReturnType) { const rowOf = (title: string) => screen.getByText(title).closest('tr') as HTMLElement; -/** Stage a new Estimate on the row titled `title`, the way a user types it. */ +/** Type a new Estimate on the row titled `title` and commit it: select-first, the commit is the save. */ async function editEstimate(title: string, from: string, to: string) { const td = await waitFor(() => { const cell = Array.from(rowOf(title).querySelectorAll('td')).find( @@ -159,11 +160,11 @@ async function editEstimate(title: string, from: string, to: string) { return cell as HTMLElement; }); fireEvent.click(td); - const input = await waitFor(() => { - const el = td.querySelector('input') as HTMLInputElement | null; - if (!el) throw new Error('editor not open'); - return el; - }); + fireEvent.doubleClick(td); + // The editor mounts on the cell's overlay layer (objectstack#35688). + await waitFor(() => expect(td.querySelector('[data-slot="cell-editor-overlay"] input')).toBeTruthy()); + await act(async () => {}); + const input = td.querySelector('[data-slot="cell-editor-overlay"] input') as HTMLInputElement; fireEvent.change(input, { target: { value: to } }); fireEvent.keyDown(input, { key: 'Enter' }); await waitFor(() => expect(within(rowOf(title)).getByText(to)).toBeInTheDocument()); @@ -173,10 +174,7 @@ const estimates = (server: ReturnType) => Object.fromEntries(Object.entries(server.store).map(([id, r]) => [id, r.estimate_hours])); describe('ObjectGrid keeps an inline edit made while a save is on the wire (objectui#12322)', () => { - it.each([ - ['a row save', (title: string) => fireEvent.click(within(rowOf(title)).getByTitle('Save row'))], - ['Save All', () => fireEvent.click(screen.getByRole('button', { name: /Save All/ }))], - ] as const)('%s held open: an estimate staged on another row is still pending after the save lands', async (_label, save) => { + it('a save held open: an estimate committed on another row meanwhile is written too, and drawn when both land', async () => { const server = makeServer([ { id: 'a', title: 'Alpha', estimate_hours: 10 }, { id: 'b', title: 'Bravo', estimate_hours: 20 }, @@ -185,22 +183,17 @@ describe('ObjectGrid keeps an inline edit made while a save is on the wire (obje await waitFor(() => expect(within(rowOf('Alpha')).getByText('10')).toBeInTheDocument()); await editEstimate('Alpha', '10', '11'); - save('Alpha'); await waitFor(() => expect(server.patches).toEqual([{ id: 'a', body: { estimate_hours: 11 } }])); - // The write is on the wire; Bravo's cell is still editable. + // The write is on the wire; Bravo's cell is still editable, and its + // commit is its own save. await editEstimate('Bravo', '20', '21'); - expect(screen.getByText(/2 rows modified/)).toBeInTheDocument(); + await waitFor(() => expect(server.patches).toHaveLength(2)); + expect(server.patches[1]).toEqual({ id: 'b', body: { estimate_hours: 21 } }); await server.release(); - await waitFor(() => expect(estimates(server)).toEqual({ a: 11, b: 20 })); - await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument()); - expect(within(rowOf('Bravo')).getByText('21')).toBeInTheDocument(); - - // And the next Save All writes it. - fireEvent.click(screen.getByRole('button', { name: /Save All/ })); await waitFor(() => expect(estimates(server)).toEqual({ a: 11, b: 21 })); - expect(server.patches[1]).toEqual({ id: 'b', body: { estimate_hours: 21 } }); - await waitFor(() => expect(screen.queryByText(/row modified/)).toBeNull()); + expect(within(rowOf('Alpha')).getByText('11')).toBeInTheDocument(); + expect(within(rowOf('Bravo')).getByText('21')).toBeInTheDocument(); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditExitMode.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditExitMode.test.tsx index bb95ca14b49..0e249c9c942 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditExitMode.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditExitMode.test.tsx @@ -5,14 +5,15 @@ * type (text, number, date, lookup, …) as the in-cell editor. Non-discrete * types stage their value on every change and used to have NO way to leave edit * mode — click-outside, Enter, and the Save button all failed to dismiss the - * editor, leaving the cell permanently stuck showing the widget. + * editor, leaving the cell permanently stuck showing the widget. (The Save + * button went with the staged model, objectstack#35827: a commit is the save.) * * These tests drive the real DataTable ← ObjectGrid path against an in-memory * fake server and assert the editor actually exits (its / trigger is * gone) while the staged value is preserved (or reverted, for Escape). */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, within, cleanup } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, within, cleanup, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -111,7 +112,7 @@ function renderGrid(ds: any, columns: any[]) {
- +
, @@ -127,6 +128,22 @@ const cellByText = (row: HTMLElement, text: string) => const firstRow = (container: HTMLElement) => container.querySelector('tbody tr') as HTMLElement; +/** + * Open `td`'s editor the select-first way (a click selects, a double-click + * edits; objectstack#35827) and hand back the input on its overlay layer + * (objectstack#35688), read once that layer has settled. + */ +async function openEditor(td: HTMLElement): Promise { + fireEvent.click(td); + fireEvent.doubleClick(td); + await waitFor(() => expect(td.querySelector('[data-slot="cell-editor-overlay"] input')).toBeTruthy()); + await act(async () => {}); + return td.querySelector('[data-slot="cell-editor-overlay"] input') as HTMLInputElement; +} + +/** The cell's editor layer, or null once the edit has ended. */ +const editorOf = (td: HTMLElement) => td.querySelector('[data-slot="cell-editor-overlay"]'); + describe('ObjectGrid — injected text/number editor exits edit mode', () => { const textCols = [ { field: 'name', label: 'Name', type: 'text' }, @@ -139,21 +156,15 @@ describe('ObjectGrid — injected text/number editor exits edit mode', () => { await waitFor(() => expect(screen.getByText('Row One')).toBeInTheDocument()); const nameTd = cellByText(firstRow(container), 'Row One'); - fireEvent.click(nameTd); - - const input = await waitFor(() => { - const el = nameTd.querySelector('input') as HTMLInputElement; - expect(el).toBeTruthy(); - return el; - }); + const input = await openEditor(nameTd); fireEvent.change(input, { target: { value: 'Row One EDITED' } }); // Click truly outside the editor. fireEvent.pointerDown(screen.getByTestId('outside')); // Editor is gone… - await waitFor(() => expect(nameTd.querySelector('input')).toBeNull()); - // …and the staged value remains (pending change). + await waitFor(() => expect(editorOf(nameTd)).toBeNull()); + // …and the committed value is what the cell draws. expect(within(nameTd).getByText('Row One EDITED')).toBeInTheDocument(); }); @@ -163,17 +174,11 @@ describe('ObjectGrid — injected text/number editor exits edit mode', () => { await waitFor(() => expect(screen.getByText('Row One')).toBeInTheDocument()); const qtyTd = cellByText(firstRow(container), '10'); - fireEvent.click(qtyTd); - - const input = await waitFor(() => { - const el = qtyTd.querySelector('input') as HTMLInputElement; - expect(el).toBeTruthy(); - return el; - }); + const input = await openEditor(qtyTd); fireEvent.change(input, { target: { value: '42' } }); fireEvent.keyDown(input, { key: 'Enter' }); - await waitFor(() => expect(qtyTd.querySelector('input')).toBeNull()); + await waitFor(() => expect(editorOf(qtyTd)).toBeNull()); expect(within(qtyTd).getByText('42')).toBeInTheDocument(); }); @@ -183,49 +188,30 @@ describe('ObjectGrid — injected text/number editor exits edit mode', () => { await waitFor(() => expect(screen.getByText('Row One')).toBeInTheDocument()); const nameTd = cellByText(firstRow(container), 'Row One'); - fireEvent.click(nameTd); - - const input = await waitFor(() => { - const el = nameTd.querySelector('input') as HTMLInputElement; - expect(el).toBeTruthy(); - return el; - }); + const input = await openEditor(nameTd); fireEvent.change(input, { target: { value: 'discard me' } }); fireEvent.keyDown(input, { key: 'Escape' }); - await waitFor(() => expect(nameTd.querySelector('input')).toBeNull()); - // Reverted to the original value — no pending change left behind. + await waitFor(() => expect(editorOf(nameTd)).toBeNull()); + // Reverted to the original value — nothing written. expect(within(nameTd).getByText('Row One')).toBeInTheDocument(); expect(within(nameTd).queryByText('discard me')).toBeNull(); }); - it('a staged injected edit persists through Save All after exiting', async () => { + it('an injected edit committed by a press outside is saved', async () => { const ds = makeDataSource(); const { container } = renderGrid(ds, textCols); await waitFor(() => expect(screen.getByText('Row One')).toBeInTheDocument()); const nameTd = cellByText(firstRow(container), 'Row One'); - fireEvent.click(nameTd); - const input = await waitFor(() => { - const el = nameTd.querySelector('input') as HTMLInputElement; - expect(el).toBeTruthy(); - return el; - }); + const input = await openEditor(nameTd); fireEvent.change(input, { target: { value: 'Row One SAVED' } }); fireEvent.pointerDown(screen.getByTestId('outside')); - await waitFor(() => expect(nameTd.querySelector('input')).toBeNull()); - - const saveAll = await waitFor(() => { - const btn = Array.from(container.querySelectorAll('button')).find((b) => - /Save All|全部保存/.test(b.textContent || ''), - ) as HTMLButtonElement; - expect(btn).toBeTruthy(); - return btn; - }); - fireEvent.click(saveAll); - - // The fourth argument is the save's write options: this fixture's rows carry - // no `updated_at`, so no `ifMatch` is sent (objectui#12292). + await waitFor(() => expect(editorOf(nameTd)).toBeNull()); + + // The commit is the save (objectstack#35827). The fourth argument is the + // save's write options: this fixture's rows carry no `updated_at`, so no + // `ifMatch` is sent (objectui#12292). await waitFor(() => expect(ds.update).toHaveBeenCalledWith(OBJECT, 'r1', { name: 'Row One SAVED' }, undefined)); expect(ds.store.r1.name).toBe('Row One SAVED'); }); @@ -254,8 +240,10 @@ describe('ObjectGrid — injected lookup editor exits edit mode', () => { }; const panel = () => managerTd().querySelector('[data-testid="lookup-in-cell"]') as HTMLElement | null; - // Enter edit mode: the list is open at once, inside the cell. + // Enter edit mode (select-first: a click selects, a double-click edits): + // the list is open at once, inside the cell. fireEvent.click(managerTd()); + fireEvent.doubleClick(managerTd()); await waitFor(() => expect(panel()).toBeTruthy()); const option = await waitFor(() => within(panel()!).getByText('Dev Admin')); @@ -280,6 +268,7 @@ describe('ObjectGrid — injected lookup editor exits edit mode', () => { const panel = () => managerTd().querySelector('[data-testid="lookup-in-cell"]') as HTMLElement | null; fireEvent.click(managerTd()); + fireEvent.doubleClick(managerTd()); await waitFor(() => expect(panel()).toBeTruthy()); // The click-outside guard treats the editor's own content as inside: a diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditFieldWriteGrant-12103.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditFieldWriteGrant-12103.test.tsx index 1f2e4d52755..c0cb434dac1 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditFieldWriteGrant-12103.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditFieldWriteGrant-12103.test.tsx @@ -121,7 +121,7 @@ function renderGrid(perms: MePermissionsResponse | null) { const grid = ( - {}} onDelete={() => {}} /> + {}} onDelete={() => {}} /> ); @@ -140,11 +140,13 @@ async function cell(text: string): Promise { /** Click the cell and report whether an in-cell editor opened. */ async function opensEditor(text: string): Promise { const td = await cell(text); - // `data-table` draws the editable cursor only on a column it will open. - const offered = td.className.includes('cursor-text'); + // Select-first (objectstack#35827): a click selects the cell, which then + // says whether it will open (`aria-readonly`); a double-click edits. fireEvent.click(td); + const offered = !td.hasAttribute('aria-readonly'); + fireEvent.doubleClick(td); await new Promise((r) => setTimeout(r, 50)); - const opened = td.querySelector('input') != null; + const opened = td.hasAttribute('data-editing-cell') && td.querySelector('input') != null; // The two observables agree, or the probe cannot tell the shapes apart. expect(opened, `${text}: cursor and editor disagree`).toBe(offered); return opened; diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditLookupRepro.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditLookupRepro.test.tsx index 9162984cfda..fcc91a9dab7 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditLookupRepro.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditLookupRepro.test.tsx @@ -104,7 +104,7 @@ function renderGrid(dataSource: any) { return render( - + , ); @@ -123,26 +123,23 @@ describe('ObjectGrid — lookup inline edit survives clicking another row', () = return tds[tds.length - 1] as HTMLElement; }; - // Enter edit mode on row1's manager cell. + // Select row1's manager cell and open its editor (select-first, + // objectstack#35827): the lookup's editor is its in-cell candidate list + // (objectstack#35688 S3). fireEvent.click(managerCellOf(rows()[0])); + fireEvent.doubleClick(managerCellOf(rows()[0])); - // The lookup trigger button should appear inside the cell; open the popover. - const trigger = await waitFor(() => { - const btn = managerCellOf(rows()[0]).querySelector('button'); - expect(btn).toBeTruthy(); - return btn as HTMLButtonElement; - }); - fireEvent.click(trigger); - - // Pick "Dev Admin" from the popover options (fetched from `users`). + // Pick "Dev Admin" from the candidates (fetched from `users`); the pick + // is the commit, and the commit is the save. const option = await waitFor(() => { - const el = screen.getByText('Dev Admin'); + const el = within(managerCellOf(rows()[0])).getByText('Dev Admin'); expect(el).toBeInTheDocument(); return el; }); fireEvent.click(option); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); - // The staged value shows in row1's manager cell. + // The picked value shows in row1's manager cell. await waitFor(() => { expect(within(managerCellOf(rows()[0])).getByText('Dev Admin')).toBeInTheDocument(); }); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditNoopAndHeader-11816.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditNoopAndHeader-11816.test.tsx index fd4f4f41433..a565d7f97db 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditNoopAndHeader-11816.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditNoopAndHeader-11816.test.tsx @@ -12,12 +12,14 @@ * (showcase Tasks → Edit inline): * * - opening a select cell and clicking away without choosing used to show - * "1 row modified · Save All (1)" for a row nobody changed; + * "1 row modified · Save All (1)" for a row nobody changed; under the + * per-cell save (objectstack#35827) it must write nothing; * - with inline edit on, the grid drew TWO columns headed "Actions": its own - * row-menu column and the data-table's per-row cancel/save column. + * row-menu column and the data-table's per-row cancel/save column. The + * second is retired with the staged model; one "Actions" column is left. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -108,7 +110,7 @@ function renderGrid() {
{/* Row Edit/Delete handlers: the grid's own row-menu column exists. */} - {}} onDelete={() => {}} /> + {}} onDelete={() => {}} />
, @@ -116,10 +118,8 @@ function renderGrid() { return { ...utils, ds }; } -const modified = () => screen.queryByText(/rows? modified/); - describe('ObjectGrid inline edit (objectui#11816)', () => { - it('a select cell opened and left without a choice does not mark the row modified', async () => { + it('a select cell opened and left without a choice writes nothing', async () => { const { container, ds } = renderGrid(); await waitFor(() => expect(screen.getByText('Design system')).toBeInTheDocument()); @@ -128,24 +128,25 @@ describe('ObjectGrid inline edit (objectui#11816)', () => { (td) => td.textContent?.trim() === 'High', ) as HTMLElement; expect(priorityTd).toBeTruthy(); + // Select-first: a click selects, a double-click opens the in-cell list. fireEvent.click(priorityTd); - // The select editor is open on the cell… - await waitFor(() => expect(priorityTd.querySelector('[role="combobox"]')).toBeTruthy()); + fireEvent.doubleClick(priorityTd); + await waitFor(() => expect(screen.getByTestId('in-cell-option-low')).toBeInTheDocument()); // …and the user clicks away without choosing. fireEvent.pointerDown(screen.getByTestId('outside')); - await waitFor(() => expect(priorityTd.querySelector('[role="combobox"]')).toBeNull()); + await waitFor(() => expect(screen.queryByTestId('in-cell-option-low')).toBeNull()); - expect(modified()).toBeNull(); - expect(screen.queryByText(/Save All/)).toBeNull(); + await act(async () => {}); expect(ds.update).not.toHaveBeenCalled(); + expect(priorityTd.textContent).toContain('High'); }); - it('draws one "Actions" column; the cancel/save column is headed by its own name', async () => { + it('draws one "Actions" column and no cancel/save column', async () => { renderGrid(); await waitFor(() => expect(screen.getByText('Design system')).toBeInTheDocument()); expect(screen.getAllByRole('columnheader', { name: 'Actions' })).toHaveLength(1); - expect(screen.getByRole('columnheader', { name: 'Edit' })).toBeInTheDocument(); + expect(screen.queryByRole('columnheader', { name: 'Edit' })).toBeNull(); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditPendingKeyedByRecord-12310.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditPendingKeyedByRecord-12310.test.tsx deleted file mode 100644 index bfb7823a5ef..00000000000 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditPendingKeyedByRecord-12310.test.tsx +++ /dev/null @@ -1,358 +0,0 @@ -/** - * 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. - */ - -/** - * objectui#12310 — a pending inline edit belongs to its RECORD, not to the - * position its row had when the edit was staged. - * - * `data-table` used to key pending edits by page-local row index. Every - * re-read that put the page in a new order (a row save's refresh, the - * data-invalidation bus, a page change) then drew a kept edit on whichever - * record now sat at that index, and Save All wrote it there: a value typed on - * one record landed on another with a 200, and the If-Match token from - * objectui#12292 could not catch it, because the wrong row's own token was - * current. - * - * ## What is real here - * - * The real `ObjectGrid` renders the real `data-table`, and every write goes - * through the real `@object-ui/data-objectstack` adapter. Only `fetch` is - * stubbed for writes, and reads are served from the same store, the way the - * server answers them: most recently modified first, one page at a time - * (`$top` / `$skip`), projected to `$select`. So a save moves the saved record - * to the top of the next read, which is the reorder the card measured. - */ -import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup, within, act } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import React from 'react'; - -import { ObjectStackAdapter } from '@object-ui/data-objectstack'; -import { registerAllFields } from '@object-ui/fields'; -import { ActionProvider, SchemaRendererProvider, notifyDataChanged } from '@object-ui/react'; -import { ObjectGrid } from '../ObjectGrid'; -import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; -import { installExplainDouble } from './explainDouble'; - -registerAllFields(); - -beforeAll(() => { - if (!Element.prototype.scrollIntoView) { - Element.prototype.scrollIntoView = vi.fn() as any; - } -}); - -beforeEach(() => { - __clearRecordCrudVerdictCache(); - installExplainDouble(); -}); -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -const OBJECT = 'task_12310'; - -const json = (status: number, body: unknown) => - new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); - -interface Patch { - id: string; - ifMatch: string | undefined; - body: Record; - status: number; -} - -/** - * The fake server. Seeded oldest first, so the first seed row is the LAST row - * of the first read. `writeAsOtherUser` is a concurrent write that moves the - * record it touches to the top of the next read. - */ -function makeServer(seed: Array & { id: string }>) { - let clock = 0; - const stamp = () => `2026-10-13 00:00:${String(++clock).padStart(2, '0')}.000`; - const store: Record> = {}; - for (const row of seed) store[row.id] = { ...row, updated_at: stamp() }; - const patches: Patch[] = []; - - const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - const url = String(input); - const method = (init?.method ?? 'GET').toUpperCase(); - if (url.endsWith('/api/v1/discovery')) { - return json(200, { success: true, data: { capabilities: {}, routes: {} } }); - } - const match = url.match(/\/api\/v1\/data\/([^/?]+)\/([^/?]+)$/); - if (!match || method !== 'PATCH') throw new Error(`unexpected request ${method} ${url}`); - const [, object, rawId] = match; - const id = decodeURIComponent(rawId); - const headers = (init?.headers ?? {}) as Record; - const ifMatch = headers['If-Match']; - const body = JSON.parse(String(init?.body ?? '{}')) as Record; - const current = store[id]; - if (ifMatch !== undefined && ifMatch !== current.updated_at) { - patches.push({ id, ifMatch, body, status: 409 }); - return json(409, { - error: 'Record was modified by another user', - code: 'CONCURRENT_UPDATE', - currentVersion: current.updated_at, - currentRecord: { ...current }, - object, - }); - } - store[id] = { ...current, ...body, updated_at: stamp() }; - patches.push({ id, ifMatch, body, status: 200 }); - return json(200, { success: true, data: { object, id, record: { ...store[id] } } }); - }); - - const adapter = new ObjectStackAdapter({ baseUrl: 'http://test.local', fetch, autoReconnect: false }); - - const project = (row: Record, select: unknown) => - Array.isArray(select) - ? Object.fromEntries(select.filter((k) => k in row).map((k) => [k, row[k]])) - : { ...row }; - - const dataSource = { - find: vi.fn(async (_object: string, params?: { $select?: unknown; $top?: number; $skip?: number }) => { - // The server's order: most recently modified first. - const ordered = Object.values(store).sort((a, b) => - String(b.updated_at).localeCompare(String(a.updated_at)), - ); - const skip = params?.$skip ?? 0; - const top = params?.$top ?? ordered.length; - const rows = ordered.slice(skip, skip + top).map((r) => project(r, params?.$select)); - return { data: rows, total: ordered.length, hasMore: skip + top < ordered.length, pageSize: top }; - }), - findOne: vi.fn(async (_object: string, id: string) => ({ ...store[id] })), - update: vi.fn((object: string, id: string, data: any, opts?: { ifMatch?: string }) => - adapter.update(object, id, data, opts), - ), - getObjectSchema: vi.fn(async (name: string) => ({ - name, - fields: { - id: { type: 'text' }, - title: { type: 'text', label: 'Title' }, - estimate_hours: { type: 'number', label: 'Estimate' }, - }, - })), - } as any; - - return { - store, - patches, - dataSource, - writeAsOtherUser(id: string, changes: Record) { - store[id] = { ...store[id], ...changes, updated_at: stamp() }; - }, - }; -} - -function renderGrid(server: ReturnType, pageSize = 50) { - const schema: any = { - type: 'object-grid', - objectName: OBJECT, - editable: true, - columns: [ - { field: 'title', label: 'Title', editable: false }, - { field: 'estimate_hours', label: 'Estimate', type: 'number' }, - ], - pagination: { pageSize }, - }; - return render( - - - {/* Row Edit/Delete handlers: the per-row save button exists. */} - {}} onDelete={() => {}} /> - - , - ); -} - -const rowOf = (title: string) => screen.getByText(title).closest('tr') as HTMLElement; - -/** The titles of the body rows, top to bottom. */ -const bodyOrder = () => - Array.from(document.querySelectorAll('tbody tr')) - .map((tr) => ['Alpha', 'Bravo', 'Charlie', 'Delta'].find((t) => tr.textContent?.includes(t))) - .filter(Boolean); - -/** Stage a new Estimate on the row titled `title`, the way a user types it. */ -async function editEstimate(title: string, from: string, to: string) { - const td = await waitFor(() => { - const cell = Array.from(rowOf(title).querySelectorAll('td')).find( - (c) => c.textContent?.trim() === from, - ); - if (!cell) throw new Error(`no ${from} cell on ${title}`); - return cell as HTMLElement; - }); - fireEvent.click(td); - const input = await waitFor(() => { - const el = td.querySelector('input') as HTMLInputElement | null; - if (!el) throw new Error('editor not open'); - return el; - }); - fireEvent.change(input, { target: { value: to } }); - fireEvent.keyDown(input, { key: 'Enter' }); - await waitFor(() => expect(within(rowOf(title)).getByText(to)).toBeInTheDocument()); -} - -const clickSaveAll = () => fireEvent.click(screen.getByRole('button', { name: /Save All/ })); - -/** What each record holds, as `{ id: estimate }`. */ -const estimates = (server: ReturnType) => - Object.fromEntries(Object.entries(server.store).map(([id, r]) => [id, r.estimate_hours])); - -describe('ObjectGrid inline edit keeps each pending edit on its record (objectui#12310)', () => { - it("the card's sequence: a row save's re-read reorders the page, and Save All writes each edit to its own record", async () => { - // Seeded oldest first: the first read is Bravo, Alpha. - const server = makeServer([ - { id: 'a', title: 'Alpha', estimate_hours: 10 }, - { id: 'b', title: 'Bravo', estimate_hours: 20 }, - ]); - renderGrid(server); - await waitFor(() => expect(bodyOrder()).toEqual(['Bravo', 'Alpha'])); - - await editEstimate('Bravo', '20', '21'); - await editEstimate('Alpha', '10', '11'); - expect(screen.getByText(/2 rows modified/)).toBeInTheDocument(); - - // Save Alpha alone; the re-read that follows puts Alpha on top. - fireEvent.click(within(rowOf('Alpha')).getByTitle('Save row')); - await waitFor(() => expect(bodyOrder()).toEqual(['Alpha', 'Bravo'])); - expect(server.patches.map((p) => [p.id, p.body])).toEqual([['a', { estimate_hours: 11 }]]); - - // Bravo's edit is still drawn on Bravo, and on nothing else. - expect(screen.getByText(/1 row modified/)).toBeInTheDocument(); - expect(within(rowOf('Bravo')).getByText('21')).toBeInTheDocument(); - expect(within(rowOf('Alpha')).getByText('11')).toBeInTheDocument(); - expect(within(rowOf('Alpha')).queryByText('21')).toBeNull(); - - clickSaveAll(); - await waitFor(() => expect(server.patches).toHaveLength(2)); - expect(server.patches[1]).toMatchObject({ id: 'b', body: { estimate_hours: 21 }, status: 200 }); - expect(estimates(server)).toEqual({ a: 11, b: 21 }); - await waitFor(() => expect(screen.queryByText(/row modified/)).toBeNull()); - }); - - it('a re-read through the invalidation bus that reorders the page keeps each edit on its record', async () => { - // First read: Charlie, Bravo, Alpha, Delta. - const server = makeServer([ - { id: 'd', title: 'Delta', estimate_hours: 40 }, - { id: 'a', title: 'Alpha', estimate_hours: 10 }, - { id: 'b', title: 'Bravo', estimate_hours: 20 }, - { id: 'c', title: 'Charlie', estimate_hours: 30 }, - ]); - renderGrid(server); - await waitFor(() => expect(bodyOrder()).toEqual(['Charlie', 'Bravo', 'Alpha', 'Delta'])); - - await editEstimate('Bravo', '20', '21'); - await editEstimate('Alpha', '10', '11'); - - // Someone else writes Delta; the bus re-reads, and every row moves down one. - server.writeAsOtherUser('d', { estimate_hours: 41 }); - act(() => notifyDataChanged({ objectName: OBJECT, recordId: 'd' })); - await waitFor(() => expect(bodyOrder()).toEqual(['Delta', 'Charlie', 'Bravo', 'Alpha'])); - - expect(within(rowOf('Bravo')).getByText('21')).toBeInTheDocument(); - expect(within(rowOf('Alpha')).getByText('11')).toBeInTheDocument(); - expect(within(rowOf('Charlie')).getByText('30')).toBeInTheDocument(); - expect(within(rowOf('Delta')).getByText('41')).toBeInTheDocument(); - - clickSaveAll(); - await waitFor(() => expect(server.patches).toHaveLength(2)); - expect(server.patches.map((p) => [p.id, p.body, p.status]).sort()).toEqual([ - ['a', { estimate_hours: 11 }, 200], - ['b', { estimate_hours: 21 }, 200], - ]); - expect(estimates(server)).toEqual({ a: 11, b: 21, c: 30, d: 41 }); - }); - - it("a row's own save on a reordered page writes that row's edit", async () => { - const server = makeServer([ - { id: 'd', title: 'Delta', estimate_hours: 40 }, - { id: 'a', title: 'Alpha', estimate_hours: 10 }, - { id: 'b', title: 'Bravo', estimate_hours: 20 }, - { id: 'c', title: 'Charlie', estimate_hours: 30 }, - ]); - renderGrid(server); - await waitFor(() => expect(bodyOrder()).toEqual(['Charlie', 'Bravo', 'Alpha', 'Delta'])); - - await editEstimate('Bravo', '20', '21'); - await editEstimate('Alpha', '10', '11'); - server.writeAsOtherUser('d', { estimate_hours: 41 }); - act(() => notifyDataChanged({ objectName: OBJECT, recordId: 'd' })); - await waitFor(() => expect(bodyOrder()).toEqual(['Delta', 'Charlie', 'Bravo', 'Alpha'])); - - fireEvent.click(within(rowOf('Bravo')).getByTitle('Save row')); - await waitFor(() => expect(server.patches).toHaveLength(1)); - expect(server.patches[0]).toMatchObject({ id: 'b', body: { estimate_hours: 21 }, status: 200 }); - await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument()); - expect(within(rowOf('Alpha')).getByText('11')).toBeInTheDocument(); - expect(estimates(server)).toEqual({ a: 10, b: 21, c: 30, d: 41 }); - }); - - it('a page change keeps a pending edit with its record, and Save All from another page writes it there', async () => { - // Two rows a page. First read: page 1 is Charlie, Bravo; page 2 is Alpha. - const server = makeServer([ - { id: 'a', title: 'Alpha', estimate_hours: 10 }, - { id: 'b', title: 'Bravo', estimate_hours: 20 }, - { id: 'c', title: 'Charlie', estimate_hours: 30 }, - ]); - renderGrid(server, 2); - await waitFor(() => expect(bodyOrder()).toEqual(['Charlie', 'Bravo'])); - await editEstimate('Bravo', '20', '21'); - const readVersion = server.store.b.updated_at; - - fireEvent.click(screen.getByRole('button', { name: 'Next page' })); - await waitFor(() => expect(bodyOrder()).toEqual(['Alpha'])); - // Nothing on page 2 is drawn as edited; the edit is still counted. - expect(within(rowOf('Alpha')).getByText('10')).toBeInTheDocument(); - expect(within(rowOf('Alpha')).queryByText('21')).toBeNull(); - expect(screen.getByText(/1 row modified/)).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Previous page' })); - await waitFor(() => expect(bodyOrder()).toEqual(['Charlie', 'Bravo'])); - expect(within(rowOf('Bravo')).getByText('21')).toBeInTheDocument(); - expect(within(rowOf('Charlie')).queryByText('21')).toBeNull(); - - fireEvent.click(screen.getByRole('button', { name: 'Next page' })); - await waitFor(() => expect(bodyOrder()).toEqual(['Alpha'])); - clickSaveAll(); - await waitFor(() => expect(server.patches).toHaveLength(1)); - // Written to Bravo, with the token Bravo was read with. - expect(server.patches[0]).toEqual({ id: 'b', ifMatch: readVersion, body: { estimate_hours: 21 }, status: 200 }); - expect(estimates(server)).toEqual({ a: 10, b: 21, c: 30 }); - await waitFor(() => expect(screen.queryByText(/row modified/)).toBeNull()); - }); - - it('a re-read that drops a record with a pending edit keeps the edit pending against that record', async () => { - // Two rows a page. First read: page 1 is Charlie, Bravo. - const server = makeServer([ - { id: 'a', title: 'Alpha', estimate_hours: 10 }, - { id: 'b', title: 'Bravo', estimate_hours: 20 }, - { id: 'c', title: 'Charlie', estimate_hours: 30 }, - ]); - renderGrid(server, 2); - await waitFor(() => expect(bodyOrder()).toEqual(['Charlie', 'Bravo'])); - await editEstimate('Bravo', '20', '21'); - - // Someone else writes Alpha; the re-read pushes Bravo onto page 2. - server.writeAsOtherUser('a', { estimate_hours: 12 }); - act(() => notifyDataChanged({ objectName: OBJECT, recordId: 'a' })); - await waitFor(() => expect(bodyOrder()).toEqual(['Alpha', 'Charlie'])); - - // The edit is not drawn on the row now at Bravo's old position. - expect(within(rowOf('Charlie')).getByText('30')).toBeInTheDocument(); - expect(within(rowOf('Charlie')).queryByText('21')).toBeNull(); - expect(screen.getByText(/1 row modified/)).toBeInTheDocument(); - - clickSaveAll(); - await waitFor(() => expect(server.patches).toHaveLength(1)); - expect(server.patches[0]).toMatchObject({ id: 'b', body: { estimate_hours: 21 }, status: 200 }); - expect(estimates(server)).toEqual({ a: 12, b: 21, c: 30 }); - }); -}); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditPermissionGate.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditPermissionGate.test.tsx index 7833ca1480b..b96b423bd92 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditPermissionGate.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditPermissionGate.test.tsx @@ -160,7 +160,7 @@ function renderGrid(c: Case) { return render( - {}} onDelete={() => {}} /> + {}} onDelete={() => {}} /> , ); @@ -249,11 +249,12 @@ describe("ObjectGrid `editable` vs can(object, 'update') (#5143)", () => { expect(await entersEditState({ editable: true, permUpdate: true })).toBe(true); }); - it('e — the save/cancel column follows the same verdict, so the gated grid IS the non-editable grid', async () => { - // `rowActions` exists only to carry inline-edit save/cancel. Left on the - // raw schema key it would render a permanently empty trailing column for a - // read-only principal — a shape no grid has today. The gated grid must be - // column-for-column identical to one that never asked to be editable. + it('e — no verdict draws a save/cancel column: the gated grid IS the non-editable grid', async () => { + // The staged model drew a trailing save/cancel column on an editable grid, + // and this case pinned that a read-only principal did not get it. That + // column is retired with the staged model (objectstack#35827): each cell + // saves on its own, so an editable grid, a gated one and a never-editable + // one are column-for-column the same. const editableWithGrant = await headerCellCount({ editable: true, permUpdate: true }); cleanup(); const editableNoGrant = await headerCellCount({ editable: true, permUpdate: false }); @@ -261,9 +262,7 @@ describe("ObjectGrid `editable` vs can(object, 'update') (#5143)", () => { const neverEditable = await headerCellCount({ permUpdate: true }); expect(editableNoGrant).toBe(neverEditable); - // Control: the column really is observable, so the equality above is not a - // probe that cannot tell the two shapes apart. - expect(editableWithGrant).toBe(neverEditable + 1); + expect(editableWithGrant).toBe(neverEditable); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditPersistence.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditPersistence.test.tsx index 9158202b4aa..f301d92cf9f 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditPersistence.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditPersistence.test.tsx @@ -1,16 +1,17 @@ /** * Inline-edit persistence (生产报工 regression) * - * Repro of the reported bug: edit a cell, commit it (Enter / blur), then click - * the row-save or "全部保存" button — after the grid refreshes the value is gone. + * Repro of the reported bug: edit a cell, commit it, save it — and the value + * is gone. The staged row-save and "全部保存" buttons are retired + * (objectstack#35827): the commit itself is the save. * - * This drives the FULL path (DataTable edit → ObjectGrid defaultRowSave / - * defaultBatchSave → dataSource.update → refresh → refetch) against an + * This drives the FULL path (DataTable edit → ObjectGrid defaultRowSave → + * dataSource.update) against an * in-memory fake server, so a passing test means the grid code persists * correctly and a failing one pinpoints where the value is dropped. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -85,7 +86,7 @@ function renderGrid(dataSource: any) { }; return render( - + , ); } @@ -100,7 +101,7 @@ const dateCellInput = (container: HTMLElement) => { }; describe('ObjectGrid — inline edit persists through save + refresh', () => { - it('row-save writes the edited date to the backend and survives refresh', async () => { + it('a committed cell writes the edited date to the backend', async () => { const ds = makeDataSource(); const { container } = renderGrid(ds); await waitFor(() => expect(screen.getByText('过渡段箱体+底板拼板')).toBeInTheDocument()); @@ -110,26 +111,16 @@ describe('ObjectGrid — inline edit persists through save + refresh', () => { const tds = Array.from(firstRow.querySelectorAll('td')); const dateTd = tds.find((td) => td.querySelector('div')?.textContent === '—') as HTMLElement ?? tds[tds.length - 2]; + // Select-first (objectstack#35827): a click selects, a double-click edits, + // and the Enter that commits the cell is its save. fireEvent.click(dateTd); - - const input = await waitFor(() => { - const el = dateTd.querySelector('input') as HTMLInputElement; - expect(el).toBeTruthy(); - return el; - }); + fireEvent.doubleClick(dateTd); + await waitFor(() => expect(dateTd.querySelector('[data-slot="cell-editor-overlay"] input')).toBeTruthy()); + await act(async () => {}); + const input = dateTd.querySelector('[data-slot="cell-editor-overlay"] input') as HTMLInputElement; fireEvent.change(input, { target: { value: '2026-06-29' } }); fireEvent.keyDown(input, { key: 'Enter' }); - // Click "Save All" (全部保存) — the batch-save path the user used. - const saveAll = await waitFor(() => { - const btn = Array.from(container.querySelectorAll('button')).find((b) => - /Save All|全部保存/.test(b.textContent || ''), - ) as HTMLButtonElement; - expect(btn).toBeTruthy(); - return btn; - }); - fireEvent.click(saveAll); - await waitFor(() => expect(ds.update).toHaveBeenCalled()); // The fourth argument is the save's write options: this fixture's rows carry // no `updated_at`, so no `ifMatch` is sent (objectui#12292). diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditRecordVerdict-27365.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditRecordVerdict-27365.test.tsx index 54709597d03..ec390cc27f8 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditRecordVerdict-27365.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditRecordVerdict-27365.test.tsx @@ -150,7 +150,7 @@ function renderGrid(c: Case = {}) { {}, onDelete: () => {} } : {})} @@ -160,9 +160,14 @@ function renderGrid(c: Case = {}) { ); } -/** Wait for the rows, then for every explain answer to land. */ +/** + * Wait for the rows, select a cell (a select-first grid asks the record + * verdicts when a cell is first selected, objectstack#35684 / #35827), then + * wait for every explain answer to land. + */ async function settle() { await waitFor(() => expect(screen.getByText(OTHER_ROW.name)).toBeInTheDocument()); + fireEvent.click(cellOf(OWN_ROW.name)); await waitFor(() => expect(server.calls.length).toBeGreaterThan(0)); await act(async () => { await Promise.allSettled(server.responses); @@ -177,19 +182,25 @@ const cellOf = (label: string) => /** Click the row's Name cell and report whether an in-cell editor opened. */ async function clickOpensEditor(label: string): Promise { const td = cellOf(label); + // Select-first (objectstack#35827): a click selects, a double-click edits. fireEvent.click(td); + fireEvent.doubleClick(td); await new Promise((r) => setTimeout(r, 50)); - const opened = td.querySelector('input') != null; + const opened = td.hasAttribute('data-editing-cell') && td.querySelector('input') != null; if (opened) fireEvent.keyDown(td.querySelector('input')!, { key: 'Escape' }); return opened; } -/** Press Enter on the row's Name cell and report whether an editor opened. */ +/** Select the row's Name cell, press Enter, and report whether an editor opened. */ async function enterOpensEditor(label: string): Promise { const td = cellOf(label); - fireEvent.keyDown(td, { key: 'Enter' }); + fireEvent.click(td); + const catcher = td.querySelector('[data-slot="cell-type-catcher"]'); + fireEvent.keyDown(catcher ?? td, { key: 'Enter' }); await new Promise((r) => setTimeout(r, 50)); - return td.querySelector('input') != null; + const opened = td.hasAttribute('data-editing-cell') && td.querySelector('input') != null; + if (opened) fireEvent.keyDown(td.querySelector('input')!, { key: 'Escape' }); + return opened; } /** Whether the row's kebab offers the built-in Edit entry. */ @@ -218,14 +229,15 @@ describe('ObjectGrid inline cells read the record-grained `update` verdict (obje await settle(); expect(await clickOpensEditor(OTHER_ROW.name)).toBe(false); expect(await enterOpensEditor(OTHER_ROW.name)).toBe(false); - // …and reads as read-only: no edit cursor on its cells. - expect(cellOf(OTHER_ROW.name)).not.toHaveClass('cursor-text'); + // …and reads as read-only: the selected cell says so. + fireEvent.click(cellOf(OTHER_ROW.name)); + expect(cellOf(OTHER_ROW.name)).toHaveAttribute('aria-readonly', 'true'); }); it('CONTROL: an allowed row of the same grid stays editable', async () => { renderGrid(); await settle(); - expect(cellOf(OWN_ROW.name)).toHaveClass('cursor-text'); + expect(cellOf(OWN_ROW.name)).not.toHaveAttribute('aria-readonly'); expect(await clickOpensEditor(OWN_ROW.name)).toBe(true); }); @@ -263,6 +275,7 @@ describe('fail OPEN — no answer keeps the object-level behaviour (objectstack# server.network = false; renderGrid(); await waitFor(() => expect(screen.getByText(OTHER_ROW.name)).toBeInTheDocument()); + fireEvent.click(cellOf(OWN_ROW.name)); await waitFor(() => expect(server.calls.length).toBeGreaterThan(0)); expect(await clickOpensEditor(OTHER_ROW.name)).toBe(true); }); @@ -274,40 +287,16 @@ describe('fail OPEN — no answer keeps the object-level behaviour (objectstack# expect(await clickOpensEditor(OTHER_ROW.name)).toBe(true); }); - it('CONTROL: before the answer lands, the row is editable — never over-hidden', async () => { - server.hold(); - renderGrid(); - await waitFor(() => expect(screen.getByText(OTHER_ROW.name)).toBeInTheDocument()); - await waitFor(() => expect(server.calls.length).toBeGreaterThan(0)); - expect(await clickOpensEditor(OTHER_ROW.name)).toBe(true); - server.release(); - await act(async () => { - await Promise.allSettled(server.responses); - }); - expect(await clickOpensEditor(OTHER_ROW.name)).toBe(false); - }); + // "before the answer lands, the row is editable" pinned the staged arm. + // Select-first, an edit waits for the row's verdict instead of opening an + // editor the answer may refuse (objectstack#35795), pinned in + // ObjectGrid.cellSelection-35684 ("a slow record verdict holds the editor + // the same way"); every editable grid is select-first (objectstack#35827). }); -/** - * [objectstack#34208] A list asks the record verdicts only once its row actions - * are reached for — but the inline cells read `update` while they render, so an - * inline-editable grid still asks `update` when its rows arrive. `delete` is - * read only by the row menus, and waits for them. - */ -describe('[objectstack#34208] an inline-editable grid asks `update` on first render, `delete` on first use', () => { - it('the first paint asks `update` for the page and nothing else; opening a kebab then asks `delete` once', async () => { - renderGrid(); - await settle(); - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - expect(server.calls.map((call) => call.operation)).toEqual(['update']); - expect([...(server.calls[0].recordIds ?? [])].sort()).toEqual([OTHER_ROW.id, OWN_ROW.id].sort()); - - expect(await kebabOffersEdit(OWN_ROW.name)).toBe(true); - await act(async () => { - await Promise.allSettled(server.responses); - }); - expect(server.calls.map((call) => call.operation)).toEqual(['update', 'delete']); - }); -}); +// [objectstack#34208] pinned that an inline-editable grid asked `update` on +// first paint, because the staged cells read it while they rendered. Every +// editable grid is select-first now (objectstack#35827), and its cells ask +// when one is first selected (objectstack#35684): ObjectGrid.cellSelection-35684 +// and `settle()` above. `delete` waiting for the row menus is +// rowRecordCrudVerdict.test.tsx's. diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditRuleCheck-27520.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditRuleCheck-27520.test.tsx index 1d9db4f751f..beba6bd5732 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditRuleCheck-27520.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditRuleCheck-27520.test.tsx @@ -14,13 +14,14 @@ * (`min: 0`), "Save All". The `PATCH` went out with -5 and came back refused. * Now a row whose edits break a declared rule is refused here, unsent, in the * shape the server refuses it in, so the table marks its cells and names its - * reasons; the other rows still save. + * reasons. Each commit is its own save since the staged model was retired + * (objectstack#35827), so the check runs on each commit. * * The real `ObjectGrid` and `data-table` over an in-memory data source whose * `update` persists. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -97,7 +98,7 @@ async function loaded(dataSource: ReturnType) { render( {}} @@ -110,65 +111,56 @@ async function loaded(dataSource: ReturnType) { const rowOf = (title: string) => screen.getByText(title).closest('tr') as HTMLElement; -async function editEstimate(title: string, from: string, to: string) { +/** + * Type a new Estimate on the row titled `title` and commit it with Enter, the + * select-first way (a click selects, a double-click edits): the commit is the + * cell's save (objectstack#35827). + */ +async function commitEstimate(title: string, from: string, to: string) { const td = await waitFor(() => { const cell = Array.from(rowOf(title).querySelectorAll('td')).find((c) => c.textContent?.trim() === from); if (!cell) throw new Error(`no ${from} cell on ${title}`); return cell as HTMLElement; }); fireEvent.click(td); - const input = await waitFor(() => { - const el = td.querySelector('input') as HTMLInputElement | null; - if (!el) throw new Error('editor not open'); - return el; - }); + fireEvent.doubleClick(td); + // The editor mounts on the cell's overlay layer (objectstack#35688). + await waitFor(() => expect(td.querySelector('[data-slot="cell-editor-overlay"] input')).toBeTruthy()); + await act(async () => {}); + const input = td.querySelector('[data-slot="cell-editor-overlay"] input') as HTMLInputElement; fireEvent.change(input, { target: { value: to } }); fireEvent.keyDown(input, { key: 'Enter' }); - await waitFor(() => expect(within(rowOf(title)).getByText(to)).toBeInTheDocument()); + await act(async () => {}); return td; } describe('ObjectGrid default saves — a field rule is checked before sending (#27520)', () => { - it('"Save All": the row below `min` is refused unsent, its cell marked; the other row saves', async () => { + it('a commit below `min` is refused unsent and says why on its cell', async () => { const ds = makeDataSource(); await loaded(ds); - const refusedCell = await editEstimate('Ingest pipeline', '60', '-5'); - await editEstimate('Warehouse schema', '33', '31'); - fireEvent.click(screen.getByRole('button', { name: /Save All/ })); + await commitEstimate('Ingest pipeline', '60', '-5'); await waitFor(() => - expect(screen.getByTestId('table-save-refusal')).toHaveTextContent('Estimate (h) must be at least 0'), - ); - // Only the row that keeps every rule was sent. - expect(ds.update).toHaveBeenCalledTimes(1); - expect(ds.update).toHaveBeenCalledWith(OBJECT, 't2', { estimate_hours: 31 }, undefined); - expect(ds.store.t1.estimate_hours).toBe(60); - expect(refusedCell).toHaveAttribute('aria-invalid', 'true'); - expect(refusedCell).toHaveAttribute('data-cell-error', 'Estimate (h) must be at least 0'); - expect(toasts.success).toHaveBeenCalledWith('1 row saved'); - }); - - it('the per-row save refuses the same edit unsent', async () => { - const ds = makeDataSource(); - await loaded(ds); - await editEstimate('Ingest pipeline', '60', '-7'); - fireEvent.click(within(rowOf('Ingest pipeline')).getByTitle('Save row')); - - await waitFor(() => - expect(screen.getByTestId('table-save-refusal')).toHaveTextContent('Estimate (h) must be at least 0'), + expect(rowOf('Ingest pipeline').textContent).toContain('Estimate (h) must be at least 0'), ); expect(ds.update).not.toHaveBeenCalled(); + expect(ds.store.t1.estimate_hours).toBe(60); expect(toasts.success).not.toHaveBeenCalled(); }); + // The staged pins ("Save All" sending only the row that keeps every rule, + // the per-row save refusing the same edit) went with the staged model + // (objectstack#35827): each commit is its own save, judged on its own, + // as above. + it('CONTROL — an edit inside the rules is sent as before', async () => { const ds = makeDataSource(); await loaded(ds); - await editEstimate('Ingest pipeline', '60', '0'); - fireEvent.click(screen.getByRole('button', { name: /Save All/ })); + await commitEstimate('Ingest pipeline', '60', '0'); await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); - expect(screen.queryByTestId('table-save-refusal')).toBeNull(); + expect(ds.update).toHaveBeenCalledWith(OBJECT, 't1', { estimate_hours: 0 }, undefined); + expect(rowOf('Ingest pipeline').textContent).not.toContain('must be at least'); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditSaveFeedback-12303.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditSaveFeedback-12303.test.tsx index 1f2ccc2ee70..063e9a0ced5 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditSaveFeedback-12303.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditSaveFeedback-12303.test.tsx @@ -17,14 +17,16 @@ * default saves now raise the console's shared success toast (the `toast` * `@object-ui/components` re-exports from `sonner`, the one the form, kanban * and view surfaces raise), naming how many rows the server ACCEPTED: a row - * that failed is not counted, and a batch where nothing landed says nothing. + * that failed is not counted, and a save that did not land says nothing. + * Since the staged model was retired (objectstack#35827) each committed cell + * is its own save of one row. * * The real `ObjectGrid` and `data-table` over an in-memory data source whose * `update` persists, and can refuse named rows. Only that `toast` export is * replaced, so the toast call itself is read. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -108,7 +110,7 @@ async function loaded(dataSource: ReturnType) { {/* Row Edit/Delete handlers: the per-row save button exists. */} ) { const rowOf = (title: string) => screen.getByText(title).closest('tr') as HTMLElement; -/** Stage a new Estimate on the row titled `title`, the way a user types it. */ -async function editEstimate(title: string, from: string, to: string) { +/** + * Type a new Estimate on the row titled `title` and commit it with Enter, the + * select-first way (a click selects, a double-click edits): the commit is the + * cell's save. + */ +async function commitEstimate(title: string, from: string, to: string) { const td = await waitFor(() => { const cell = Array.from(rowOf(title).querySelectorAll('td')).find((c) => c.textContent?.trim() === from); if (!cell) throw new Error(`no ${from} cell on ${title}`); return cell as HTMLElement; }); fireEvent.click(td); - const input = await waitFor(() => { - const el = td.querySelector('input') as HTMLInputElement | null; - if (!el) throw new Error('editor not open'); - return el; - }); + fireEvent.doubleClick(td); + // The editor mounts on the cell's overlay layer (objectstack#35688). + await waitFor(() => expect(td.querySelector('[data-slot="cell-editor-overlay"] input')).toBeTruthy()); + await act(async () => {}); + const input = td.querySelector('[data-slot="cell-editor-overlay"] input') as HTMLInputElement; fireEvent.change(input, { target: { value: to } }); fireEvent.keyDown(input, { key: 'Enter' }); - await waitFor(() => expect(within(rowOf(title)).getByText(to)).toBeInTheDocument()); + await act(async () => {}); } -const clickSaveAll = () => fireEvent.click(screen.getByRole('button', { name: /Save All/ })); +/** The text of each success toast raised so far. */ +const successTexts = () => toasts.success.mock.calls.map((call: unknown[]) => call[0]); describe('ObjectGrid default saves — the write is said (objectui#12303)', () => { - it('"Save All" over two rows that both land raises one success toast naming two rows', async () => { + it('a committed cell that lands raises one success toast saying one row was saved', async () => { const ds = makeDataSource(); await loaded(ds); - await editEstimate('Ingest pipeline', '60', '61'); - await editEstimate('Warehouse schema', '33', '31'); - clickSaveAll(); + await commitEstimate('Ingest pipeline', '60', '61'); await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(1)); - expect(toasts.success).toHaveBeenCalledWith('2 rows saved'); + expect(successTexts()).toEqual(['1 row saved']); expect(ds.store.t1.estimate_hours).toBe(61); - expect(ds.store.t2.estimate_hours).toBe(31); - await waitFor(() => expect(screen.queryByText(/row modified|rows modified/)).toBeNull()); - }); - - it('the card’s case: "Save All (1)" says one row was saved', async () => { - const ds = makeDataSource(); - await loaded(ds); - await editEstimate('Ingest pipeline', '60', '61'); - expect(screen.getByRole('button', { name: /Save All \(1\)/ })).toBeInTheDocument(); - clickSaveAll(); - - await waitFor(() => expect(toasts.success).toHaveBeenCalledWith('1 row saved')); - expect(toasts.success).toHaveBeenCalledTimes(1); }); - it('the per-row save says one row was saved', async () => { + it('a commit on each of two rows: each save is said once, as one row', async () => { const ds = makeDataSource(); await loaded(ds); - await editEstimate('Ingest pipeline', '60', '61'); - fireEvent.click(within(rowOf('Ingest pipeline')).getByTitle('Save row')); + await commitEstimate('Ingest pipeline', '60', '61'); + await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(1)); + await commitEstimate('Warehouse schema', '33', '31'); - await waitFor(() => expect(toasts.success).toHaveBeenCalledWith('1 row saved')); + await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(2)); + expect(successTexts()).toEqual(['1 row saved', '1 row saved']); expect(ds.store.t1.estimate_hours).toBe(61); + expect(ds.store.t2.estimate_hours).toBe(31); }); - it('a batch where one row is refused counts only the row that landed, and the table still flags the other', async () => { + it('CONTROL — a save the server refuses raises no success toast, and the cell says why', async () => { const ds = makeDataSource(new Set(['t1'])); await loaded(ds); - await editEstimate('Ingest pipeline', '60', '61'); - await editEstimate('Warehouse schema', '33', '31'); - clickSaveAll(); + await commitEstimate('Ingest pipeline', '60', '61'); await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('estimate_hours is locked on t1')); - expect(toasts.success).toHaveBeenCalledTimes(1); - expect(toasts.success).toHaveBeenCalledWith('1 row saved'); - expect(ds.store.t2.estimate_hours).toBe(31); + expect(ds.update).toHaveBeenCalledTimes(1); expect(ds.store.t1.estimate_hours).toBe(60); - expect(screen.getByRole('button', { name: /Save All \(1\)/ })).toBeInTheDocument(); - }); - - it('CONTROL — a batch where nothing lands raises no success toast', async () => { - const ds = makeDataSource(new Set(['t1', 't2'])); - await loaded(ds); - await editEstimate('Ingest pipeline', '60', '61'); - await editEstimate('Warehouse schema', '33', '31'); - clickSaveAll(); - - await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument()); - expect(ds.update).toHaveBeenCalledTimes(2); expect(toasts.success).not.toHaveBeenCalled(); }); + + // The "Save All" pins (one toast naming two rows, "Save All (1)", a batch + // counting only the rows that landed) went with the staged model + // (objectstack#35827). }); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditSaveNotice-28252.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditSaveNotice-28252.test.tsx index dc268589014..5c9d2a64074 100644 --- a/ui/packages/plugin-grid/src/__tests__/inlineEditSaveNotice-28252.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditSaveNotice-28252.test.tsx @@ -10,8 +10,9 @@ * objectstack-ai/objectstack#28252 — the grid's inline-edit saves carry the * write answer's `notice` (the message a hook set, * objectstack-ai/objectstack#28000) on their own save toast, so the write is - * one toast: the per-row save and "Save All" claim their rows' answer - * feedback, and the write-warning channel raises none of its own. + * one toast: each cell's save claims its row's answer feedback, and the + * write-warning channel raises none of its own. (The staged "Save All" that + * claimed several rows at once is retired, objectstack#35827.) * * The channel is stood in for by its own door, `parkAnswerWarnings` from * `@object-ui/react`, called synchronously inside the write as the adapter's @@ -22,7 +23,7 @@ * no notice line); the CONTROL row GREEN on both sides. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -118,9 +119,8 @@ async function loaded(dataSource: ReturnType) { } as GridProps['schema']; render( - {/* Row Edit/Delete handlers: the per-row save button exists. */} ) { const rowOf = (title: string) => screen.getByText(title).closest('tr') as HTMLElement; -/** Stage a new Estimate on the row titled `title`, the way a user types it. */ -async function editEstimate(title: string, from: string, to: string) { +/** + * Type a new Estimate on the row titled `title` and commit it with Enter, the + * select-first way (a click selects, a double-click edits): the commit is the + * cell's save. + */ +async function commitEstimate(title: string, from: string, to: string) { const td = await waitFor(() => { const cell = Array.from(rowOf(title).querySelectorAll('td')).find((c) => c.textContent?.trim() === from); if (!cell) throw new Error(`no ${from} cell on ${title}`); return cell as HTMLElement; }); fireEvent.click(td); - const input = await waitFor(() => { - const el = td.querySelector('input') as HTMLInputElement | null; - if (!el) throw new Error('editor not open'); - return el; - }); + fireEvent.doubleClick(td); + // The editor mounts on the cell's overlay layer (objectstack#35688). + await waitFor(() => expect(td.querySelector('[data-slot="cell-editor-overlay"] input')).toBeTruthy()); + await act(async () => {}); + const input = td.querySelector('[data-slot="cell-editor-overlay"] input') as HTMLInputElement; fireEvent.change(input, { target: { value: to } }); fireEvent.keyDown(input, { key: 'Enter' }); - await waitFor(() => expect(within(rowOf(title)).getByText(to)).toBeInTheDocument()); + await act(async () => {}); } -const clickSaveAll = () => fireEvent.click(screen.getByRole('button', { name: /Save All/ })); - describe('ObjectGrid inline-edit saves carry the hook notice (objectstack-ai/objectstack#28252)', () => { - it('the per-row save: one success toast, the notice under "1 row saved"; the channel shows nothing', async () => { + it('a cell save: one success toast, the notice under "1 row saved"; the channel shows nothing', async () => { const channelToast = vi.fn(); const ds = makeDataSource(channelToast); await loaded(ds); - await editEstimate('Ingest pipeline', '60', '61'); - fireEvent.click(within(rowOf('Ingest pipeline')).getByTitle('Save row')); + await commitEstimate('Ingest pipeline', '60', '61'); await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(1)); - expect(toasts.success).toHaveBeenCalledWith('1 row saved', { description: NOTICE }); + expect(toasts.success).toHaveBeenCalledWith('1 row saved', expect.objectContaining({ description: NOTICE })); expect(toasts.warning).not.toHaveBeenCalled(); expect(channelToast).not.toHaveBeenCalled(); }); - it('"Save All" over two rows: one toast, the shared notice once, the warning lines under it', async () => { + it('a cell save with a warning: one toast, the notice, the warning line under it', async () => { const channelToast = vi.fn(); const ds = makeDataSource(channelToast, new Set(['t2'])); await loaded(ds); - await editEstimate('Ingest pipeline', '60', '61'); - await editEstimate('Warehouse schema', '33', '31'); - clickSaveAll(); + await commitEstimate('Warehouse schema', '33', '31'); await waitFor(() => expect(toasts.warning).toHaveBeenCalledTimes(1)); - expect(toasts.warning).toHaveBeenCalledWith('2 rows saved', { description: `${NOTICE}\nEstimate is high on t2` }); + expect(toasts.warning).toHaveBeenCalledWith( + '1 row saved', + expect.objectContaining({ description: `${NOTICE}\nEstimate is high on t2` }), + ); expect(toasts.success).not.toHaveBeenCalled(); expect(channelToast).not.toHaveBeenCalled(); }); @@ -186,8 +188,7 @@ describe('ObjectGrid inline-edit saves carry the hook notice (objectstack-ai/obj const channelToast = vi.fn(); const ds = makeDataSource(channelToast); await loaded(ds); - await editEstimate('Ingest pipeline', '60', '61'); - fireEvent.click(within(rowOf('Ingest pipeline')).getByTitle('Save row')); + await commitEstimate('Ingest pipeline', '60', '61'); await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(1)); await ds.update(OBJECT, 't1', { estimate_hours: 62 }); diff --git a/ui/packages/plugin-grid/src/__tests__/lookupPickerKeys-7154.test.tsx b/ui/packages/plugin-grid/src/__tests__/lookupPickerKeys-7154.test.tsx index 3aa30b17ffc..d4cde48536a 100644 --- a/ui/packages/plugin-grid/src/__tests__/lookupPickerKeys-7154.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/lookupPickerKeys-7154.test.tsx @@ -178,7 +178,7 @@ function renderGrid(ds: any, rows: any[], columns: any[]) { return render( - + , ); @@ -199,6 +199,7 @@ function cellAt(container: HTMLElement, index: number): HTMLElement { */ async function openEditor(cell: HTMLElement): Promise { fireEvent.click(cell); + fireEvent.doubleClick(cell); // select-first: a click selects, a double-click edits (objectstack#35827) return await waitFor(() => { const panel = cell.querySelector('[data-testid="lookup-in-cell"]'); expect(panel).toBeTruthy(); diff --git a/ui/packages/plugin-grid/src/__tests__/maskedColumnSurfaces-10583.test.tsx b/ui/packages/plugin-grid/src/__tests__/maskedColumnSurfaces-10583.test.tsx index aa06fb1594a..063928ebb2a 100644 --- a/ui/packages/plugin-grid/src/__tests__/maskedColumnSurfaces-10583.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/maskedColumnSurfaces-10583.test.tsx @@ -93,7 +93,7 @@ function makeDataSource(rows: Record[], fields: Record, ds?: any) { - const grid = ; + const grid = ; return render( {ds ? {grid} : grid} @@ -143,15 +143,20 @@ describe('ObjectGrid — a masked column opens no inline editor (objectui#10583) ]; for (const c of cases) { - it(`view \`type: 'password'\` ${c.name} — click and Enter open no editor; the text control edits`, async () => { + it(`view \`type: 'password'\` ${c.name} — double-click and Enter open no editor; the text control edits`, async () => { c.render(); await waitFor(() => expect(screen.queryByText(CONTROL_VALUE)).not.toBeNull()); + // Select-first (objectstack#35827): a click selects, and a double-click + // or Enter on the selected cell is what would open an editor. const masked = cellUnder('PIN'); expect(masked.textContent, 'CONTROL: the authored password type drew the mask').toContain(MASK); fireEvent.click(masked); - fireEvent.keyDown(masked, { key: 'Enter' }); - expect(masked.querySelector('input, textarea'), 'no editor in the masked cell').toBeNull(); + fireEvent.doubleClick(masked); + const catcher = document.querySelector('[data-slot="cell-type-catcher"]'); + if (catcher) fireEvent.keyDown(catcher, { key: 'Enter' }); + expect(masked.hasAttribute('data-editing-cell'), 'no editor in the masked cell').toBe(false); + expect(masked.querySelector('textarea, input:not([data-slot="cell-type-catcher"])'), 'no editor in the masked cell').toBeNull(); expect(rawInAnEditor(RAW.pin), 'no editor holds the raw value').toBe(false); expect(document.body.innerHTML, 'the raw value is nowhere in the DOM').not.toContain(RAW.pin); @@ -159,8 +164,9 @@ describe('ObjectGrid — a masked column opens no inline editor (objectui#10583) // Held by reference: once it edits, its text lives in an input value. const control = cellUnder('Name'); fireEvent.click(control); + fireEvent.doubleClick(control); await waitFor(() => - expect(control.querySelector('input, textarea'), 'CONTROL: the text cell edits').not.toBeNull(), + expect(control.querySelector('textarea, input:not([data-slot="cell-type-catcher"])'), 'CONTROL: the text cell edits').not.toBeNull(), ); }); } diff --git a/ui/packages/plugin-grid/src/__tests__/relationalMetaCopySet-7166.test.tsx b/ui/packages/plugin-grid/src/__tests__/relationalMetaCopySet-7166.test.tsx index 21c894aead4..9f9b6f4f2f1 100644 --- a/ui/packages/plugin-grid/src/__tests__/relationalMetaCopySet-7166.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/relationalMetaCopySet-7166.test.tsx @@ -145,7 +145,7 @@ function renderGrid(ds: any, rows: any[], columns: any[]) { return render( - + , ); @@ -166,6 +166,7 @@ function cellAt(container: HTMLElement, index: number): HTMLElement { */ async function openEditor(cell: HTMLElement): Promise { fireEvent.click(cell); + fireEvent.doubleClick(cell); // select-first: a click selects, a double-click edits (objectstack#35827) return await waitFor(() => { const panel = cell.querySelector('[data-testid="lookup-in-cell"]'); expect(panel).toBeTruthy(); diff --git a/ui/packages/plugin-grid/src/objectGridRowVersion.ts b/ui/packages/plugin-grid/src/objectGridRowVersion.ts index 371f78527d1..80e240ce324 100644 --- a/ui/packages/plugin-grid/src/objectGridRowVersion.ts +++ b/ui/packages/plugin-grid/src/objectGridRowVersion.ts @@ -1,12 +1,9 @@ /** * The optimistic-concurrency helpers of `ObjectGrid` (`./ObjectGrid.tsx`): the - * row's version token, the version a row save sends, and the conflict and - * batch-save outcome types, moved out of that file verbatim - * (objectstack#25994, slice 1). + * row's version token, the version a row save sends, and the conflict outcome + * type, moved out of that file verbatim (objectstack#25994, slice 1). */ -import type { DataTableSchema } from '@object-ui/types'; - /** * The row key that carries a record's optimistic-concurrency token * (objectui#12292): `updated_at`, the key the record surfaces send as @@ -55,11 +52,3 @@ export function rowVersionToSend( /** The three ways out of `ConcurrentUpdateDialog`, by its own button names. */ export type RowConflictChoice = 'reload' | 'overwrite' | 'cancel'; -/** - * The per-row outcome the table's `onBatchSave` slot reads, derived from the - * slot's declared return rather than restated here. - */ -export type BatchSaveOutcome = Exclude< - Awaited>>, - void ->; diff --git a/ui/packages/plugin-grid/src/objectGridTranslations.ts b/ui/packages/plugin-grid/src/objectGridTranslations.ts index 5c6d4b565c9..052306e2b08 100644 --- a/ui/packages/plugin-grid/src/objectGridTranslations.ts +++ b/ui/packages/plugin-grid/src/objectGridTranslations.ts @@ -57,8 +57,7 @@ const GRID_DEFAULT_TRANSLATIONS: Record = { 'table.nextPage': 'Next page', 'table.lastPage': 'Last page', // The default inline-edit saves' success toast (objectui#12303), counted in - // the rows the server accepted — the `table.modified` unit the table's - // "Save All" bar counts in. + // the rows the server accepted. 'table.saved': '{{count}} row saved', 'table.saved_one': '{{count}} row saved', 'table.saved_other': '{{count}} rows saved', diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 36e5278a329..835a189d327 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -2900,7 +2900,7 @@ export const ListView = React.forwardRef(({ // --- P2: Auto-subscribe to DataSource mutation events --- // Refetch whenever the bound object is mutated through the DataSource. This - // is the ONLY refresh signal for inline-edit "Save All": ObjectGrid persists + // is the ONLY refresh signal for inline-edit cell saves: ObjectGrid persists // those edits by calling dataSource.update() directly, with no form-success // handler to bump an external refreshTrigger — so subscribing even when // `refreshTrigger` is provided is required, not redundant. Form/delete flows diff --git a/ui/packages/types/src/__tests__/handler-keys-json-refusal-6124.test.ts b/ui/packages/types/src/__tests__/handler-keys-json-refusal-6124.test.ts index 7198ecf8c99..47799b52186 100644 --- a/ui/packages/types/src/__tests__/handler-keys-json-refusal-6124.test.ts +++ b/ui/packages/types/src/__tests__/handler-keys-json-refusal-6124.test.ts @@ -304,11 +304,12 @@ const RUNTIME_SLOT: readonly Site[] = [ // // Each channel measured on its own, and they do NOT all share one — which is // why six siblings are not evidence for the seventh: - // - `onAddRecord` / `onBatchSave` / `onCellChange` / `onRowSave` are React - // props on `ObjectGridComponentProps`; `ObjectGrid` puts them on the - // `data-table` node it builds (`onRowSave ?? defaultRowSave` and - // `onBatchSave ?? defaultBatchSave` install a dataSource-backed default - // only when the host wired none); + // - `onAddRecord` / `onCellChange` / `onRowSave` are React props on + // `ObjectGridComponentProps`; `ObjectGrid` puts them on the `data-table` + // node it builds (`onRowSave ?? defaultRowSave` installs a + // dataSource-backed default only when the host wired none); + // - `onBatchSave`, the seventh, LEFT this half for `RETIRED` below + // (objectstack#35827 retired the staged editing model that called it); // - `onRowActionDef` is `RelatedList`'s own `onRowAction` React prop, // forwarded onto the node it builds; // - `onRowClick` has THREE suppliers — `ObjectGrid`'s `navigation.handleClick`, @@ -322,7 +323,6 @@ const RUNTIME_SLOT: readonly Site[] = [ // `'retired'` would have published "no renderer reads this key" for a read // objectui#6175 wired on purpose. ['data-display.zod.ts', 'DataTableSchema', 'onAddRecord', DataTableZod], - ['data-display.zod.ts', 'DataTableSchema', 'onBatchSave', DataTableZod], ['data-display.zod.ts', 'DataTableSchema', 'onCellChange', DataTableZod], ['data-display.zod.ts', 'DataTableSchema', 'onColumnResize', DataTableZod], ['data-display.zod.ts', 'DataTableSchema', 'onRowActionDef', DataTableZod], @@ -492,6 +492,11 @@ const RETIRED: readonly Site[] = [ ['objectql.zod.ts', 'ObjectKanbanSchema', 'onQuickAdd', ObjectKanbanZod], ['overlay.zod.ts', 'AlertDialogSchema', 'onConfirm', AlertDialogZod], ['overlay.zod.ts', 'AlertDialogSchema', 'onCancel', AlertDialogZod], + // ⭐ objectstack#35827 — `DataTableSchema.onBatchSave`, MOVED here from + // `RUNTIME_SLOT` above. "Save All" of the staged editing model called it; that + // model is retired, so the table saves each committed cell through + // `onRowSave` and no renderer reads this key. + ['data-display.zod.ts', 'DataTableSchema', 'onBatchSave', DataTableZod], ]; const ALL_SITES: readonly Site[] = [...RUNTIME_SLOT, ...RETIRED]; @@ -626,8 +631,12 @@ describe('census: no on* key in the eight mirrors is declared z.function() (obje // ⭐ 60 + 22 → 61 + 22: objectstack#35955 declared // `DataTableSchema.onColumnHide`, a runtime slot the `data-table` renderer // calls from its column menu. - expect(RUNTIME_SLOT).toHaveLength(61); - expect(RETIRED).toHaveLength(22); + // + // ⭐ 61 + 22 → 60 + 23, total unchanged: objectstack#35827 MOVED + // `DataTableSchema.onBatchSave` to the retired half with the staged editing + // model it served. + expect(RUNTIME_SLOT).toHaveLength(60); + expect(RETIRED).toHaveLength(23); const ids = ALL_SITES.map(([file, schema, key]) => `${file}#${schema}.${key}`); expect(new Set(ids).size).toBe(83); }); @@ -775,6 +784,8 @@ export type assertionRetiredKeysAreTombstoned = [ Expect>, // objectui#11234 — moved here from the runtime-slot block below. Expect>, + // objectstack#35827 — moved here from the runtime-slot block below. + Expect>, ]; export type assertionRuntimeSlotsKeepTheirFunctionType = [ @@ -797,7 +808,6 @@ export type assertionRuntimeSlotsKeepTheirFunctionType = [ // objectui#7804 — the `DataTableSchema` slice. Each TS twin stays callable // because the function value REACHES the renderer; the mirror refuses by name. Expect>, - Expect>, Expect>, Expect>, Expect>, diff --git a/ui/packages/types/src/__tests__/unmirrored-declared-round5-6152.test.ts b/ui/packages/types/src/__tests__/unmirrored-declared-round5-6152.test.ts index dd859ae6f30..15c34babb88 100644 --- a/ui/packages/types/src/__tests__/unmirrored-declared-round5-6152.test.ts +++ b/ui/packages/types/src/__tests__/unmirrored-declared-round5-6152.test.ts @@ -129,12 +129,13 @@ describe('objectui#6152 round 5 — the `chatbot-floating` face keeps its own `f * B): the declarations did NOT move. Read off the member, so a deletion — which read * as `any` through `BaseSchema`'s index signature until objectui#8347, and does not * compile now — or a tombstone — which would read as `undefined` — is red here. + * `singleClickEdit` left with the staged editing model (objectstack#35827): it + * chose how the retired click-to-edit opened a cell, and nothing reads it now. */ type Equal = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; type Expect = T; export type assertionInlineEditFlagsKeepTheirDeclarations = [ Expect>, - Expect>, Expect>, ]; diff --git a/ui/packages/types/src/__tests__/zod-mirror-parity.test.ts b/ui/packages/types/src/__tests__/zod-mirror-parity.test.ts index 300d91e3f1b..11c18f68dca 100644 --- a/ui/packages/types/src/__tests__/zod-mirror-parity.test.ts +++ b/ui/packages/types/src/__tests__/zod-mirror-parity.test.ts @@ -154,8 +154,12 @@ * a delta to this number; count the registry. Nothing asserts it against a written * one, so this line is prose and can rot; the pin that cannot is the one * comparing the two halves to each other. - * - **51 entries** in `KnownDrift`, **92 keys** across them — 51 / 91 until - * objectstack#35955 declared `DataTableSchema.onColumnHide`, the host's + * - **51 entries** in `KnownDrift`, **91 keys** across them — 51 / 92 until + * objectstack#35827 retired `DataTableSchema.onBatchSave` with the staged + * edit model: its TS face is `never` now and its mirror arm refuses it as + * retired, so it LEFT the `data-display.zod.ts#DataTableSchema` entry: the + * key total fell by one and the entry count did not move. It was 51 / 91 + * until objectstack#35955 declared `DataTableSchema.onColumnHide`, the host's * handler for the column menu's "Hide column", as a runtime slot refused * by name on the mirror, so it JOINED the same * `data-display.zod.ts#DataTableSchema` entry. It was 51 / 90 until @@ -568,7 +572,11 @@ * seeded long after the 121). It is ⛔ not replaced with a fresh digit, for the * reason above. The full statement is on that ledger, which owns it — read it * there, and ⛔ do not copy it back. - * - **5 entries** in `RuntimeOnlyDeclared`, **31 keys** across them — 5 / 30 + * - **5 entries** in `RuntimeOnlyDeclared`, **30 keys** across them — 5 / 31 + * until objectstack#35827 retired `DataTableSchema.singleClickEdit`, read + * only by the staged edit model it retired with: the key left the + * `DataTableSchema` entry and `RuntimeOnlyNamedAllowList`, and the entry + * count held. It was 5 / 30 * until objectui#11068's `keyboardNavigation` build filed `DataTableSchema`'s * `keyboardNavigation` here, on the entry that already existed, BY NAME with its * reason on `RuntimeOnlyNamedAllowList`: the flag `ObjectGrid` resolves from the @@ -2489,7 +2497,7 @@ interface KnownDrift { * `resolveSelectionMode` in `renderers/complex/data-table.tsx` implements * `'single'` as a real mode.) * - * The eleven callbacks — RUNTIME SLOT (objectui#6124) ×11: `renderers/complex/data-table.tsx` + * The ten callbacks — RUNTIME SLOT (objectui#6124) ×10: `renderers/complex/data-table.tsx` * CALLS every one of them off `schema.*` (`schema.onRowEdit?.(r)`, * `schema.onSelectionChange(selectedData)`, …), so the TS side keeps them callable * and the mirror refuses them by name. @@ -2509,10 +2517,14 @@ interface KnownDrift { * face, so still a runtime slot; had it been read as `'retired'` off its * siblings, the arm would publish "no renderer reads this key" to every author * who trips it, and objectui#6175 wired that read on purpose. + * + * ⭐ ELEVEN → ten: objectstack#35827 retired `onBatchSave` with the staged + * editing model that called it. It is a tombstone on BOTH faces now (`never` on + * the interface, `'retired'` on the mirror), which is no drift. */ 'data-display.zod.ts#DataTableSchema': | 'onRowEdit' | 'onRowDelete' | 'onSelectionChange' | 'onColumnsReorder' - | 'onAddRecord' | 'onBatchSave' | 'onCellChange' | 'onColumnResize' + | 'onAddRecord' | 'onCellChange' | 'onColumnResize' | 'onRowActionDef' | 'onRowClick' | 'onRowSave' // objectui#7759 group E — `renderCellEditor` is a RUNTIME SLOT in the // objectui#6124 shape (`data-table` reads `schema.renderCellEditor` and calls @@ -3670,6 +3682,10 @@ interface RuntimeOnlyDeclared { * node it builds, beside `editable`, whose value its default follows. Filed BY * NAME with its reason on `RuntimeOnlyNamedAllowList` below; ⛔ not mirrored, * since no document authors it on a `data-table` node. + * + * ⭐ SHRANK by one with objectstack#35827: `singleClickEdit` chose how the staged + * model's click-to-edit opened a cell, and that model is retired, so the member + * left the interface and this entry with it. */ 'data-display.zod.ts#DataTableSchema': | 'onColumnReorder' @@ -3677,7 +3693,7 @@ interface RuntimeOnlyDeclared { | 'onSearchChange' | 'onSortChange' | 'disableInnerScroll' | 'editable' | 'keyboardNavigation' | 'manualPagination' | 'manualSearch' | 'manualSorting' | 'page' | 'rowActionDefs' | 'rowClassName' | 'rowCount' | 'rowStyle' - | 'search' | 'selectionResetKey' | 'showAddRow' | 'showSelectionCount' | 'singleClickEdit' | 'sort'; + | 'search' | 'selectionResetKey' | 'showAddRow' | 'showSelectionCount' | 'sort'; /** * 1 of `FormSchema`'s former 9. OVERSIGHT group — `onSubmit`, `onChange` and * `onCancel` are mirrored beside it. Read at `renderers/form/form.tsx:997`, by @@ -3898,7 +3914,7 @@ interface RuntimeOnlyNamedAllowList { */ 'data-display.zod.ts#DataTableSchema': { disableInnerScroll: 'host-composition flag: set in code by ObjectGrid on the one grouped table so it overflows into the grid scroll container; authored in no document'; - editable: 'host-paired flag: set in code by ObjectGrid beside the onRowSave / onBatchSave save path it supplies; an authored value stages edits that nothing persists, and no document authors it'; + editable: 'host-paired flag: set in code by ObjectGrid beside the select-first model and the onRowSave save path it supplies; without both the table refuses it and draws read-only, and no document authors it'; keyboardNavigation: 'host-resolved flag: set in code by ObjectGrid from the keyboardNavigation key of the object-grid node, defaulting to the editable it hands down beside it; authored in no document'; manualPagination: 'host-driven server paging: set in code by ObjectGrid with rowCount, page and the onPageChange slot; authored in no document'; manualSearch: 'host-driven server search: set in code by ObjectGrid with search and the onSearchChange slot; authored in no document'; @@ -3912,7 +3928,6 @@ interface RuntimeOnlyNamedAllowList { selectionResetKey: 'imperative reset token: ObjectGrid bumps it in code to clear the checkboxes after a bulk action; authored in no document'; showAddRow: 'host-paired flag: set in code by ObjectGrid from create permission, beside the onAddRecord slot the row calls; authored in no document'; showSelectionCount: 'host-composition flag: set false in code by ObjectGrid, whose BulkActionBar shows the selection instead; authored in no document'; - singleClickEdit: 'host-paired flag: set in code by ObjectGrid with editable, choosing how a cell enters inline edit; authored in no document'; sort: 'controlled sort for manualSorting: set in code by ObjectGrid and RelatedList from their own sort state; authored in no document'; }; /** diff --git a/ui/packages/types/src/data-display.ts b/ui/packages/types/src/data-display.ts index 26ae50aef3f..7c66c0739be 100644 --- a/ui/packages/types/src/data-display.ts +++ b/ui/packages/types/src/data-display.ts @@ -1551,27 +1551,21 @@ export interface DataTableSchema extends BaseSchema { onColumnHide?: (columnKey: string) => void; /** * Enable inline cell editing - * When true, cells become editable on double-click or Enter key - * - * HOST-PAIRED, not an authored flag (objectui#6152 round 5): the table only - * STAGES an edit; persisting it is the job of the `onRowSave` / `onCellChange` - * / `onBatchSave` slots, which a host supplies in code — `ObjectGrid` sets this - * key on the `data-table` node it builds, together with that save path. A JSON - * document can supply no function, so an authored `editable: true` stages edits - * that nothing saves. To edit records inline from a document, author an - * `object-grid`, which carries the save path itself. + * When true, a selected cell opens its editor on double-click, Enter, F2 or + * typing, and each committed cell saves at once through {@link onRowSave}. + * + * HOST-PAIRED, not an authored flag (objectui#6152 round 5): the table edits + * only under the select-first cell model a host mounts (`GridCellSelection` + * from `@object-ui/components`) AND with an `onRowSave` slot to save each + * commit through (objectstack#35827: there is no staged model any more). + * `ObjectGrid` supplies both for every grid it renders editable. Without + * them `editable: true` is refused: the table draws read-only and says why + * once on the console. A JSON document can supply no function, so to edit + * records inline from a document, author an `object-grid`, which carries + * the save path itself. * @default false */ editable?: boolean; - /** - * Enable single-click editing mode - * When true with editable, clicking a cell enters edit mode (instead of double-click) - * - * HOST-PAIRED with {@link DataTableSchema.editable} (objectui#6152 round 5): - * `ObjectGrid` sets it in code; no document authors it. - * @default false - */ - singleClickEdit?: boolean; /** * Arrow-key cell navigation on the WAI-ARIA grid pattern (objectui#11068). * @@ -1758,8 +1752,8 @@ export interface DataTableSchema extends BaseSchema { * function, NOT authorable metadata: JSON has no function value, so the zod * twin refuses this key by name and points at the node-type spelling. Kept * callable here because it is called by `renderers/complex/data-table.tsx` - * when an inline edit is staged, with the staged value and the edited record's - * row. Supplied by `ObjectGrid` (`@object-ui/plugin-grid`), which forwards the + * when an inline edit is committed, with the committed value and the edited + * record's row. Supplied by `ObjectGrid` (`@object-ui/plugin-grid`), which forwards the * React prop of the same name off `ObjectGridComponentProps`. * * `rowIndex` is computed when the call is made (objectui#12310): the row's @@ -1773,56 +1767,35 @@ export interface DataTableSchema extends BaseSchema { onCellChange?: (rowIndex: number, columnKey: string, newValue: any, row: any) => void; /** * Row save handler - * Called when saving changes for a single row + * Called with one record's committed changes, once per commit * * RUNTIME SLOT (objectui#6124, declared by `75fca9669`) — a host-supplied * function, NOT authorable metadata: JSON has no function value, so the zod * twin refuses this key by name and points at the node-type spelling. Kept * callable here because it is called by `renderers/complex/data-table.tsx` - * from a row's own save button, with that record's staged changes and its - * row. Supplied by `ObjectGrid` as `onRowSave ?? defaultRowSave` — the left - * limb is the React prop of the same name on `ObjectGridComponentProps`, the - * right a dataSource-backed default installed only when no host wired one. + * each time a cell is committed (objectstack#35685), with every edit that + * record still holds and its row: the table's only save path + * (objectstack#35827), and the one {@link editable} needs. Supplied by + * `ObjectGrid` as `onRowSave ?? defaultRowSave` — the left limb is the React + * prop of the same name on `ObjectGridComponentProps`, the right a + * dataSource-backed default installed only when no host wired one. * * `rowIndex` is the row's global index when the call is made - * (objectui#12310). The button is drawn only on a row the table holds, so it - * is never negative here. + * (objectui#12310), or `-1` when the rows the table holds no longer include + * the record. */ onRowSave?: (rowIndex: number, changes: Record, row: any) => void | Promise; /** - * Batch save handler - * Called when saving changes for multiple rows - * - * RUNTIME SLOT (objectui#6124, declared by `75fca9669`) — a host-supplied - * function, NOT authorable metadata: JSON has no function value, so the zod - * twin refuses this key by name and points at the node-type spelling. Kept - * callable here because it is called by `renderers/complex/data-table.tsx` - * (`await schema.onBatchSave(changesToSave)`). Supplied by `ObjectGrid` as - * `onBatchSave ?? defaultBatchSave`, the same two-limb shape as - * {@link onRowSave}. - * - * The outcome is read PER ROW (objectui#12292). A batch is several - * independent writes, so some can land while others are refused, and the - * server does not take the landed ones back. A handler that knows which rows - * did not persist resolves with `{ failed }`, each entry naming a row by the - * `rowIndex` it was handed: the table keeps and flags exactly those rows and - * clears the rest. Resolving with nothing means every row persisted. - * Rejecting means the handler cannot say which rows landed, so the table - * keeps and flags every row, as it always has. - * - * Each entry is one record's pending edit, resolved by the record, never by - * a position (objectui#12310). While the table holds the record, `row` is - * its current row and `rowIndex` its global index when Save All is pressed. - * A record the table no longer holds (a re-read or a client-side search - * dropped it, or it sits on another server page) is still handed over: - * `row` is the row the edit was staged against, and `rowIndex` is negative - * (`-1`, `-2`, …, distinct within one batch), since no position in the held - * rows is that record's. A `{ failed }` entry names its row by the - * `rowIndex` it was handed, negatives included. - */ - onBatchSave?: ( - changes: Array<{ rowIndex: number; changes: Record; row: any }>, - ) => void | Promise }>; + * RETIRED (objectstack#35827, ADR-0049; the zod twin refuses it by name) — + * the batch save handler of the staged editing model, which "Save All" + * called with every pending row. The staged model is gone: the table saves + * each committed cell on its own, through {@link onRowSave} (one call per + * record), and no renderer calls this key. Migrate a batch handler to a + * per-record `onRowSave`, or let `ObjectGrid` write through its own + * `dataSource.update`. + * @deprecated Retired with the staged editing model — nothing calls it. + */ + onBatchSave?: never; /** * Row click handler * Called when a row is clicked @@ -1970,7 +1943,7 @@ export interface DataTableSchema extends BaseSchema { * `packages/plugin-chatbot/src/renderer.tsx` is the kind of prefix hit grep * scores. Every read is filed under the TYPE of the object it is read from; * this declaration carries none. What the renderer DOES read off this node: - * `emptyAction`, `isRowEditable`, `onAddRecord`, `onBatchSave`, `onCellChange`, + * `emptyAction`, `isRowEditable`, `onAddRecord`, `onCellChange`, * `onColumnResize`, `onColumnsReorder`, `onRowActionDef`, `onRowClick`, * `onRowDelete`, `onRowEdit`, `onRowSave`, `onSelectionChange`, * `renderCellEditor`, `renderRowContextMenu`, `rowActionDefs`, @@ -2001,7 +1974,7 @@ export interface DataTableSchema extends BaseSchema { * `packages/plugin-chatbot/src/renderer.tsx` is the kind of prefix hit grep * scores. Every read is filed under the TYPE of the object it is read from; * this declaration carries none. What the renderer DOES read off this node: - * `emptyAction`, `isRowEditable`, `onAddRecord`, `onBatchSave`, `onCellChange`, + * `emptyAction`, `isRowEditable`, `onAddRecord`, `onCellChange`, * `onColumnResize`, `onColumnsReorder`, `onRowActionDef`, `onRowClick`, * `onRowDelete`, `onRowEdit`, `onRowSave`, `onSelectionChange`, * `renderCellEditor`, `renderRowContextMenu`, `rowActionDefs`, diff --git a/ui/packages/types/src/objectql.ts b/ui/packages/types/src/objectql.ts index 2d0e14d04f9..42e4e07dd09 100644 --- a/ui/packages/types/src/objectql.ts +++ b/ui/packages/types/src/objectql.ts @@ -1337,7 +1337,8 @@ export interface ObjectGridSchema extends BaseSchema { * `?: never`, not a deletion — this package's tombstone convention (see * `resizableColumns` above). Lockstep with the Zod twin * (`zod/objectql.zod.ts`, `retirementTombstone()`). `DataTableSchema`'s own - * `singleClickEdit`, a flag a host sets in code, is unchanged. + * `singleClickEdit`, a flag a host set in code, left with the staged model + * (objectstack#35827). * * @deprecated RETIRED (objectstack#36270) — delete the key; `editable` decides * whether the grid edits. @@ -1386,10 +1387,10 @@ export interface ObjectGridSchema extends BaseSchema { * `inlineEditable` is the authored `editable` AND the viewer's write verdict on * the object — the one value the grid's inline editing itself obeys. A grid * that renders read-only keeps its Tab behaviour unless this is `true`. A grid - * that renders editable is select-first by default (objectstack#36270), and - * the select-first model always keeps navigation on, so `false` has no effect - * there. Only a host that keeps the staged model (`cellSelection={false}` on - * `ObjectGrid`) lets `false` turn it off on an editable grid. + * that renders editable is select-first (objectstack#36270, and with no + * staged model left to opt back into since objectstack#35827), and the + * select-first model always keeps navigation on, so `false` has no effect + * there. * @default true when the grid renders editable */ keyboardNavigation?: boolean; @@ -1442,11 +1443,11 @@ export interface ObjectGridSchema extends BaseSchema { * key. Writing it into a stored document does nothing at all. * * Programmatic callers should prefer `ObjectGridComponentProps` - * (`@object-ui/plugin-grid`), which declares ten callbacks: this one, as a + * (`@object-ui/plugin-grid`), which declares nine callbacks: this one, as a * prop since objectui#9547 — and the prop wins when both are supplied — and - * the nine siblings `onRowClick`, `onRowSelect`, `onCellChange`, - * `onRowSave`, `onBatchSave`, `onEdit`, `onDelete`, `onBulkDelete`, - * `onAddRecord`, which live and only live there, for exactly this reason. + * the eight siblings `onRowClick`, `onRowSelect`, `onCellChange`, + * `onRowSave`, `onEdit`, `onDelete`, `onBulkDelete`, `onAddRecord`, which + * live and only live there, for exactly this reason. * * The declaration is kept rather than removed: with the key explicitly * published, removing it is a breaking public type change plus a deprecation diff --git a/ui/packages/types/src/zod/data-display.zod.ts b/ui/packages/types/src/zod/data-display.zod.ts index d8f28045d84..85f5ba27f90 100644 --- a/ui/packages/types/src/zod/data-display.zod.ts +++ b/ui/packages/types/src/zod/data-display.zod.ts @@ -519,8 +519,9 @@ export const DataTableSchema = BaseSchema.extend({ // - `onAddRecord` `ObjectGrid` puts its own `onAddRecord` React prop on // the `data-table` node it builds; `ObjectManager` and // `FieldDesigner` are the hosts that supply it. - // - `onBatchSave` `ObjectGrid`'s `onBatchSave ?? defaultBatchSave` — - // the left limb is `ObjectGridComponentProps.onBatchSave`. + // - `onBatchSave` was one of the seven until objectstack#35827 RETIRED + // the staged editing model it served: no renderer reads + // it any more, so it is refused as `'retired'` below. // - `onCellChange` `ObjectGrid` forwards `ObjectGridComponentProps.onCellChange`. // - `onColumnResize` ⚠️ a DIFFERENT channel from its six siblings, and the // reason "six of them were" is not evidence: no host prop @@ -540,7 +541,7 @@ export const DataTableSchema = BaseSchema.extend({ // - `onRowSave` `ObjectGrid`'s `onRowSave ?? defaultRowSave` — the left // limb is `ObjectGridComponentProps.onRowSave`. onAddRecord: handlerKeyRefusal('onAddRecord', 'runtime-slot', 'Add record handler'), - onBatchSave: handlerKeyRefusal('onBatchSave', 'runtime-slot', 'Batch save handler'), + onBatchSave: handlerKeyRefusal('onBatchSave', 'retired', 'Batch save handler'), onCellChange: handlerKeyRefusal('onCellChange', 'runtime-slot', 'Cell value change handler'), onColumnResize: handlerKeyRefusal('onColumnResize', 'runtime-slot', 'Column resize handler'), onRowActionDef: handlerKeyRefusal('onRowActionDef', 'runtime-slot', 'Row action handler'), @@ -589,7 +590,7 @@ export const DataTableSchema = BaseSchema.extend({ + 'TypeScript type checker across all 24 registering packages, no renderer read consumes `body` or ' + '`children` for this node, and `SchemaRenderer` strips both out of the props bag it spreads. An ' + 'authored value therefore rendered NOTHING — no render-time error or warning and no element; only the parser tier\'s `not-a-container` warning (objectui#9910) noticed it. ' - + 'What it renders instead: `emptyAction`, `isRowEditable`, `onAddRecord`, `onBatchSave`, `onCellChange`, ' + + 'What it renders instead: `emptyAction`, `isRowEditable`, `onAddRecord`, `onCellChange`, ' + '`onColumnResize`, `onColumnsReorder`, `onRowActionDef`, `onRowClick`, `onRowDelete`, ' + '`onRowEdit`, `onRowSave`, `onSelectionChange`, `renderCellEditor`, `renderRowContextMenu`, `rowActionDefs`, ' + '`rowDeletePredicates`, `rowEditPredicates`.', @@ -599,7 +600,7 @@ export const DataTableSchema = BaseSchema.extend({ + 'TypeScript type checker across all 24 registering packages, no renderer read consumes `body` or ' + '`children` for this node, and `SchemaRenderer` strips both out of the props bag it spreads. An ' + 'authored value therefore rendered NOTHING — no render-time error or warning and no element; only the parser tier\'s `not-a-container` warning (objectui#9910) noticed it. ' - + 'What it renders instead: `emptyAction`, `isRowEditable`, `onAddRecord`, `onBatchSave`, `onCellChange`, ' + + 'What it renders instead: `emptyAction`, `isRowEditable`, `onAddRecord`, `onCellChange`, ' + '`onColumnResize`, `onColumnsReorder`, `onRowActionDef`, `onRowClick`, `onRowDelete`, ' + '`onRowEdit`, `onRowSave`, `onSelectionChange`, `renderCellEditor`, `renderRowContextMenu`, `rowActionDefs`, ' + '`rowDeletePredicates`, `rowEditPredicates`.',