diff --git a/.changeset/35685-list-cell-autosave.md b/.changeset/35685-list-cell-autosave.md new file mode 100644 index 00000000000..17e800a0d7b --- /dev/null +++ b/.changeset/35685-list-cell-autosave.md @@ -0,0 +1,26 @@ +--- +'@object-ui/components': patch +'@object-ui/plugin-grid': patch +'@object-ui/i18n': patch +'@object-ui/react': patch +'@object-ui/plugin-list': patch +--- + +feat(list): a list cell saves the moment it is committed, and Space types into the selected cell + +Clause-②: yes (widening) — new members on the `@object-ui/react` package entry: `createOwnWrites`, `OwnWritesContext`, `useOwnWrites` and the `OwnWrites` type, and an optional third parameter on `useDataInvalidation`; three new `table.*` keys in every `@object-ui/i18n` locale (`cellSaving`, `cellSaved`, `openRecordToFinish`); nothing removed or renamed +Metadata-protocol: none + +In a grid that mounts `GridCellSelection` (the select-first grid every `ListView` draws), a committed cell edit is now saved at once, as one update for that record: + +- **No save bar, no row Save/Cancel column, no amber row.** The cell shows a small spinner while the save runs and a check mark once it landed. +- **Only that row is redrawn**, from the record the write answered with, so a value a server hook rewrote shows as stored. The list is not read again, though the write is still announced to every other reader (the record's detail pane, related lists, counts): the grid holds the record in the list's `OwnWritesContext` registry for the length of its write, and `ListView` lets that one write go by. So a row whose new value would sort it elsewhere stays where it is until the next load (refresh, sort, filter or page change). The counts on group headers, read with the rows, follow on the next load too; the footer's whole-set summary is its own reader and still refreshes on the write. +- **A refused save keeps the typed value** and shows the server's reason on the cell. Esc puts the stored value back. Later edits on the same row are sent together with the refused one as one update. When the reason names a field the list does not show (a rule that needs another field), the notice offers to open the record. +- **The 409 conflict dialog is unchanged.** The next save on a row sends the version the previous save answered. +- **Space** on a selected cell now types a space and opens its editor, as any other key does. A two-state (boolean) cell still flips. The record opens from the title link or a touch tap; the "Space opens the record" key added in #35747 is gone, so a master-detail page opens its pane only that way too. + +`@object-ui/react` adds that registry: `createOwnWrites()`, `OwnWritesContext` / `useOwnWrites()`, and `useDataInvalidation(objectName, recordId, ownWrites)`, which skips a change naming a held record. + +Grids without `GridCellSelection` keep the staged save bar and its batch save unchanged. + +New `table.*` strings in every locale: `cellSaving`, `cellSaved`, `openRecordToFinish`. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 40d537767d3..31d1c45621c 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -370,17 +370,31 @@ object and the view does not declare `userActions.editInline: false`, and move right / left, and Escape cancels and keeps the cell selected. In a multi-line editor Enter is a new line and Ctrl/Cmd+Enter commits. A click elsewhere commits. -- **Selected cell keys:** the arrows and Tab move the selection; Space opens the - record (a checkbox cell flips instead, as does a second click on it); - Ctrl/Cmd+C copies; Ctrl/Cmd+V converts the text to the field's type and - commits it; Escape clears the selection. +- **Selected cell keys:** the arrows and Tab move the selection; Space is typed + like any other key and opens the editor (a checkbox cell flips instead, as + does a second click on it); Ctrl/Cmd+C copies; Ctrl/Cmd+V converts the text + to the field's type and commits it; Escape clears the selection. The record + opens from the name link, or a tap on a touch screen. - **A cell that opens no editor says why** on the cell: the field is read-only, calculated or not editable in a list, the reader may not edit the field, the object or the record, the view turned editing off, or the record is locked by an approval. -Commits are the grid's own staged edits: the row's Save / Cancel and the Save -All bar save them, as before. +**Each commit is saved at once** (objectstack#35685), as one update for that +record; there is no Save All bar, no row Save / Cancel and no amber row. The +cell shows a small spinner while its save runs and a check mark once it +landed. Only that row is redrawn, from the record the server answered with (a +value a server hook rewrote shows as stored); the list is not read again, so a +row whose new value would sort it elsewhere stays in place until the next load +(a refresh, a sort, a filter or a page change). + +- **A refused save** keeps the typed value and shows the server's reason on the + cell. Escape puts the stored value back. A later edit on the same row is sent + together with the refused one, as one update. When the reason names a field + the list cannot edit, the notice offers to open the record. +- **A newer version** (409) still opens the conflict dialog: "Reload latest" + re-reads the list, "Overwrite anyway" writes over it and keeps the row in + place. ### Keyboard navigation @@ -419,8 +433,11 @@ WAI-ARIA grid pattern (objectui#11068): ### Batch Editing & Multi-Row Save Edit multiple cells across multiple rows and save them individually or all at -once. The schema half is just `editable` — the save/cancel affordances appear on -their own once a row has pending changes: +once. This is the model of a grid without the select-first cell model (a +related list, a dashboard table, an `object-grid` outside a list page); a list +page saves each cell as it is committed (above). The schema half is just +`editable` — the save/cancel affordances appear on their own once a row has +pending changes: ```json { diff --git a/docs/qa/platform-checklist/areas/ux-conventions.json b/docs/qa/platform-checklist/areas/ux-conventions.json index e1fea4d9173..54b8f86f10c 100644 --- a/docs/qa/platform-checklist/areas/ux-conventions.json +++ b/docs/qa/platform-checklist/areas/ux-conventions.json @@ -9,7 +9,7 @@ "title": "Every user-initiated write answers visibly — success names what changed, a refusal says why, and a no-op claims nothing", "since": "v17.7", "status": "active", - "revision": 14, + "revision": 15, "priority": "P1", "surface": "browser", "personas": [ @@ -25,14 +25,14 @@ ], "knownGaps": [ "FIXED, regression row, expected PASS (objectui#11817): Setup → Users → Invite User toasts the copy of the delivery outcome the server answers (#27843): on a deployment that does not deliver mail the declared outcomeMessages.link_only, 'Invitation created for EMAIL. Mail is not configured on this server, so no email went out. Use Copy Invite Link on the invitation to share it.' (QA run #29890 read it verbatim), and 'Invitation sent to EMAIL' (outcomeMessages.sent) only where mail is delivered (packages/platform-objects/src/identity/invite-outcome-messages.ts#INVITE_USER_OUTCOME_MESSAGES on packages/platform-objects/src/identity/sys-user.object.ts#invite_user, whose successMessage `Invitation sent to {{ result.email }}` is the fallback for an answer without an outcome), interpolating the invitee from the action result — while the sys_invitation and sys_email rows are written (QA run #23163 at objectui 1fb1ced36243; pin ObjectView.inviteFeedback-11817.test.tsx)", - "FIXED, regression rows, expected PASS (QA run #23953 at objectui daeb77fc84dd): Studio Publish gives a success confirmation (objectui#11807); the task grid's 'Save All' toasts '1 row saved' (objectui#12303 fixed for this row); the approval decision's Approve toasted the framework-declared successMessage, read in the approvals drawer that route no longer has (variants[6]) `Approved \"{{ result.request.record_title }}\"` (packages/plugins/plugin-approvals/src/sys-approval-request.object.ts), e.g. Approved \"EXP-2001\" (#23157, closed). Studio's 'Discard draft' toast and its confirm now name the item by its LABEL — QA run #24570 at objectui 4016370a read 'Draft discarded: QA Widget' — a regression row, expected PASS (objectstack-ai/objectui#12690, closed by objectui PR #12830, 0f42aaf8, in the console pin 4016370a and on objectui main; ResourceEditPage.tsx falls back to type/name only for an item with no label)", + "FIXED, regression rows, expected PASS (QA run #23953 at objectui daeb77fc84dd): Studio Publish gives a success confirmation (objectui#11807); the task grid's row save toasts '1 row saved' (objectui#12303 fixed for this row; since #35685 it is the save each committed cell makes, with no Save All); the approval decision's Approve toasted the framework-declared successMessage, read in the approvals drawer that route no longer has (variants[6]) `Approved \"{{ result.request.record_title }}\"` (packages/plugins/plugin-approvals/src/sys-approval-request.object.ts), e.g. Approved \"EXP-2001\" (#23157, closed). Studio's 'Discard draft' toast and its confirm now name the item by its LABEL — QA run #24570 at objectui 4016370a read 'Draft discarded: QA Widget' — a regression row, expected PASS (objectstack-ai/objectui#12690, closed by objectui PR #12830, 0f42aaf8, in the console pin 4016370a and on objectui main; ResourceEditPage.tsx falls back to type/name only for an item with no label)", "FIXED, regression row, expected PASS (objectui#11816): leaving an inline editor with no value change no longer reads '1 row modified · Save All (1)' (QA run #23163 at objectui 1fb1ced36243; pin data-table-noop-edit-11816.test.tsx) — negative[1]", "Undo is scored only where a surface offers it, and on stock ONE surface does: the import. An import run as a job (the wizard's 'runs as an undoable job' option) is listed in the import history with 'Undo import', which deletes the records it created and restores the records it updated to their previous values; QA run #25817 at 6679644a read it working in both create and update modes. Elsewhere no stock surface offers Undo: only an action declaring `undoable` pushes an Undo op (inline and form edits push none), and the showcase declares no undoable action (records-forms.record-edit-undo, blocked(fixture)). So acceptance[5] is scored on the import variant. Undo's absence elsewhere is recorded in the evidence and is never a FAIL of this item: which writes should offer Undo is a product decision, not this item's oracle" ] }, "variants": [ "record create — New form save on showcase_task", - "record inline edit — on any task list (since #35684 a list is editable in place wherever its reader may edit and its view declares no userActions.editInline: false; there is no 'Edit inline' toggle), double-click a Priority cell (a single click only selects it), change it, then Save row or Save All", + "record inline edit — on any task list (since #35684 a list is editable in place wherever its reader may edit and its view declares no userActions.editInline: false; there is no 'Edit inline' toggle), double-click a Priority cell (a single click only selects it), change it and commit it (Enter, Tab or a click elsewhere): since #35685 the cell saves at once, as one update — a spinner on the cell while it runs, then a check mark and the '1 row saved' toast; there is no Save row and no Save All", "bulk delete — select two rows → Delete in the selection bar → confirm", "kanban move — drag a card Backlog → To Do (direct manipulation: the card in its new column IS the success feedback; a move the transition rule blocks never leaves the client — its lane is dimmed, data-kanban-drop-blocked, and the drop sends nothing, #25933)", "declared record action — Mark Done on a task record (declared successMessage `{{ record.title | default:'Task' }} marked done.`, which names the task, examples/app-showcase/src/ui/actions/index.ts#MarkDoneAction). The action patches only done and progress, so the record's Status still reads its old value (e.g. 'To Do') beside the toast: that is the declaration, not a failed write (QA run #33861)", @@ -189,6 +189,12 @@ "date": "2026-11-20", "change": "variants[1] follows #35684: every task list is editable in place, not only the Grid view that declares inlineEdit: true, and a single click selects a cell while a double-click edits it. The clauses are unchanged. Read at base 238661f4", "ref": "#35684" + }, + { + "revision": 15, + "date": "2026-11-20", + "change": "variants[1] and knownGaps[1] follow #35685: a list cell saves the moment it is committed, with a saving and a saved mark on the cell and the '1 row saved' toast, and there is no Save row or Save All to press. The clauses are unchanged. Read at base 2ad42b5d", + "ref": "#35864" } ] }, diff --git a/ui/packages/app-shell/src/views/ObjectView.listOnlyRecordPage-33219.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listOnlyRecordPage-33219.test.tsx index e015b30aa9c..ace0fb7b983 100644 --- a/ui/packages/app-shell/src/views/ObjectView.listOnlyRecordPage-33219.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.listOnlyRecordPage-33219.test.tsx @@ -234,7 +234,7 @@ describe('objectstack#33219 — a list-only object\'s rows open no record page', it('a row click opens nothing: no `?recordId=`, no drawer, the list stays', async () => { await mountList(LIST_ONLY_OPERATIONS); fireEvent.click(screen.getByText('okta-staging')); - openWithSpace('scim_ab12'); + openWithTap('scim_ab12'); await settle(); expect(search()).toBe(''); expect(pathname()).toBe(LIST_PATH); @@ -290,12 +290,14 @@ describe('objectstack#33219 — a list-only object\'s rows open no record page', /** * objectstack#35684 — the list's other way to open a row: a click on a data - * cell selects it (and opens nothing), and Space on the selected cell opens - * its record, as the row's click used to. + * cell selects it (and opens nothing), and a touch tap on a cell opens its + * record, as the row's click used to. (It was Space on the selected cell until + * objectstack#35685 made Space type into the cell, per the maintainer.) */ -function openWithSpace(text: string): void { - fireEvent.click(screen.getByText(text).closest('td') as HTMLElement); - fireEvent.keyDown(document.activeElement as HTMLElement, { key: ' ' }); +function openWithTap(text: string): void { + const cell = screen.getByText(text).closest('td') as HTMLElement; + fireEvent.pointerDown(cell.closest('tr') as HTMLElement, { pointerType: 'touch' }); + fireEvent.click(cell); } async function mountDataPage(apiOperations: string[] | undefined, search = '') { @@ -333,7 +335,7 @@ describe('objectstack#33219 — the bare data page opens no record of a list-onl await mountDataPage(LIST_ONLY_OPERATIONS); fireEvent.click(screen.getByText('scim_ab12')); fireEvent.click(screen.getByText('scim_ab12'), { metaKey: true }); - openWithSpace('scim_ab12'); + openWithTap('scim_ab12'); await settle(); expect(search()).toBe(''); expect(openSpy).not.toHaveBeenCalled(); @@ -348,9 +350,9 @@ describe('objectstack#33219 — the bare data page opens no record of a list-onl expect(findOne).not.toHaveBeenCalled(); }); - it('CONTROL — the same object served with no restriction: Space on a selected cell opens the drawer', async () => { + it('CONTROL — the same object served with no restriction: a touch tap on a cell opens the drawer', async () => { await mountDataPage(undefined); - openWithSpace('scim_ab12'); + openWithTap('scim_ab12'); await waitFor(() => expect(search()).toBe('?recordId=c1')); expect(await screen.findByRole('dialog', undefined, { timeout: 5000 })).toBeTruthy(); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.rowOpensNothing-33317.test.tsx b/ui/packages/app-shell/src/views/ObjectView.rowOpensNothing-33317.test.tsx index 0faed25f564..fe7699f5dd7 100644 --- a/ui/packages/app-shell/src/views/ObjectView.rowOpensNothing-33317.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.rowOpensNothing-33317.test.tsx @@ -287,12 +287,14 @@ const OPEN_ITEMS = ['row-context-open', 'row-context-open-new-tab']; /** * objectstack#35684 — the list's other way to open a row: a click on a data - * cell selects it (and opens nothing), and Space on the selected cell opens - * its record, as the row's click used to. + * cell selects it (and opens nothing), and a touch tap on a cell opens its + * record, as the row's click used to. (It was Space on the selected cell until + * objectstack#35685 made Space type into the cell, per the maintainer.) */ -function openWithSpace(text: string): void { - fireEvent.click(screen.getByText(text).closest('td') as HTMLElement); - fireEvent.keyDown(document.activeElement as HTMLElement, { key: ' ' }); +function openWithTap(text: string): void { + const cell = screen.getByText(text).closest('td') as HTMLElement; + fireEvent.pointerDown(cell.closest('tr') as HTMLElement, { pointerType: 'touch' }); + fireEvent.click(cell); } describe('objectstack#33317 — the console object list: a row that opens nothing does not look clickable', () => { @@ -313,7 +315,7 @@ describe('objectstack#33317 — the console object list: a row that opens nothin fireEvent.click(screen.getByText('scim_ab12'), { button: 1 }); // The name cell, no longer a link of its own, hands its click to the row too. fireEvent.click(screen.getByText('okta-staging'), { metaKey: true }); - openWithSpace('scim_ab12'); + openWithTap('scim_ab12'); expect(openSpy).not.toHaveBeenCalled(); expect(screen.queryByTestId('left-the-list')).toBeNull(); }); @@ -385,7 +387,7 @@ describe('objectstack#33549 — the console object list: `navigation.preventNavi await mountList({ navigation: PREVENTED_DRAWER }); fireEvent.click(screen.getByText('scim_ab12')); fireEvent.click(screen.getByText('okta-staging')); - openWithSpace('scim_ab12'); + openWithTap('scim_ab12'); expect(drawerRecordId()).toBeNull(); expect(screen.queryByTestId('left-the-list')).toBeNull(); expect(openSpy).not.toHaveBeenCalled(); @@ -412,14 +414,14 @@ describe('objectstack#33549 — the console object list: `navigation.preventNavi it('a `page` view with `preventNavigation: true` draws no link face either', async () => { await mountList({ navigation: { mode: 'page', preventNavigation: true } }); expect(looksLikeALink('okta-staging')).toBe(false); - openWithSpace('scim_ab12'); + openWithTap('scim_ab12'); expect(screen.queryByTestId('left-the-list')).toBeNull(); }); - it('CONTROL — the same `drawer` view with `preventNavigation: false`: Space on a selected cell writes `?recordId=`, and the name cell is the record link', async () => { + it('CONTROL — the same `drawer` view with `preventNavigation: false`: a touch tap on a cell writes `?recordId=`, and the name cell is the record link', async () => { await mountList({ navigation: { mode: 'drawer', preventNavigation: false } }); expect(looksLikeALink('okta-staging')).toBe(true); - openWithSpace('scim_ab12'); + openWithTap('scim_ab12'); await waitFor(() => expect(drawerRecordId()).toBe('c1')); }); 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 new file mode 100644 index 00000000000..36b4510b61d --- /dev/null +++ b/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx @@ -0,0 +1,312 @@ +/** + * 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. + */ + +/** + * `data-table`'s per-cell save in the select-first model (objectstack#35685), + * behind the `GridCellSelection` a host mounts. + * + * 1. A committed cell sends its record's update at once: one call, that + * cell only; no save bar, no row Save/Cancel column, no amber row; the + * cell says saving, then saved. A boolean flipped on Space saves too. + * 2. A refused update keeps the typed value and says the server's reason on + * the cell; Esc, selected or editing, goes back to the stored value. + * 3. A row holding a refused cell sends its next commit together with it, + * as one update (a rule that needs two fields changed together). + * 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. + */ +import React from 'react'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { render, fireEvent, cleanup, screen, waitFor, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { ComponentRegistry } from '@object-ui/core'; +// Registers `data-table` at module scope, not in a hook (objectui#3010). +import '../renderers'; +// `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'; +import { GridCellSelectionProvider } from '../context/gridCellSelection'; + +afterEach(cleanup); + +const ROWS = [ + { id: '1', name: 'Alpha', stage: 'open', lost_reason: '', done: false }, + { id: '2', name: 'Beta', stage: 'open', lost_reason: '', done: true }, +]; + +/** 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' })) }, + }); +} + +type Save = (rowIndex: number, changes: Record, row: any) => Promise; + +function schemaOf(onRowSave: Save, extra: Record = {}) { + return { + type: 'data-table', + columns: [ + { header: 'Name', accessorKey: 'name' }, + { header: 'Stage', accessorKey: 'stage' }, + { header: 'Lost reason', accessorKey: 'lost_reason' }, + { header: 'Done', accessorKey: 'done', type: 'boolean' }, + ], + data: ROWS, + editable: true, + searchable: false, + pagination: false, + rowActions: true, + onRowSave, + ...extra, + }; +} + +function renderTable(onRowSave: Save, extra: Record = {}, withProvider = true) { + const DataTable = ComponentRegistry.get('data-table')!; + const tree = (schema: any) => (withProvider + ? + : ); + const utils = render(tree(schemaOf(onRowSave, extra))); + const cell = (row: number, col: number) => + utils.container.querySelectorAll('tbody tr')[row].querySelectorAll('td[data-grid-cell]')[col] as HTMLElement; + const editor = () => utils.container.querySelector('td[data-editing-cell] input'); + const catcher = () => utils.container.querySelector('[data-slot="cell-type-catcher"]'); + /** Select a cell, type `value` over it, and commit with Enter. */ + const typeAndEnter = (row: number, col: number, value: string) => { + fireEvent.click(cell(row, col)); + fireEvent.change(catcher()!, { target: { value: value.slice(0, 1) } }); + fireEvent.change(editor()!, { target: { value } }); + fireEvent.keyDown(editor()!, { key: 'Enter' }); + }; + const rerenderWith = (extraNext: Record) => utils.rerender(tree(schemaOf(onRowSave, { ...extra, ...extraNext }))); + return { ...utils, cell, editor, catcher, typeAndEnter, rerenderWith }; +} + +/** A save the test settles by hand. */ +function deferredSave() { + const calls: Array<{ changes: Record; resolve: () => void; reject: (e: unknown) => void }> = []; + const onRowSave = vi.fn((_i: number, changes: Record, _row?: unknown) => new Promise((resolve, reject) => { + calls.push({ changes, resolve, reject }); + })); + return { onRowSave, calls }; +} + +describe('data-table autosave — a committed cell saves at once (objectstack#35685)', () => { + it('sends one update with that cell only, draws no save bar, no edit column and no amber row', async () => { + const { onRowSave, calls } = deferredSave(); + const t = renderTable(onRowSave); + t.typeAndEnter(0, 0, 'Alpha 2'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Alpha 2' }); + expect(onRowSave.mock.calls[0][2]).toBe(ROWS[0]); + // The cell says it is saving, over its own edge. + expect(t.cell(0, 0).querySelector('[data-slot="cell-save-state"]')).toHaveAttribute('data-state', 'saving'); + expect(screen.queryByText(/Save All/)).toBeNull(); + expect(screen.queryByText(/row modified/)).toBeNull(); + expect(t.container.querySelector('button[title="Save row"]')).toBeNull(); + expect(t.container.querySelector('[data-testid="data-table-edit-column-header"]')).toBeNull(); + const firstRow = t.container.querySelectorAll('tbody tr')[0] as HTMLElement; + expect(firstRow.className).not.toContain('bg-amber-50'); + expect(t.cell(0, 0).className).not.toContain('text-amber-700'); + await act(async () => { calls[0].resolve(); }); + expect(t.cell(0, 0).querySelector('[data-slot="cell-save-state"]')).toHaveAttribute('data-state', 'saved'); + expect(onRowSave).toHaveBeenCalledTimes(1); + }); + + it('an unchanged commit sends nothing', async () => { + const onRowSave = vi.fn(async () => {}); + const t = renderTable(onRowSave); + fireEvent.click(t.cell(0, 0)); + fireEvent.keyDown(t.catcher()!, { key: 'Enter' }); + fireEvent.keyDown(t.editor()!, { key: 'Enter' }); + await act(async () => {}); + expect(onRowSave).not.toHaveBeenCalled(); + }); + + it('a boolean flipped on Space saves at once', async () => { + const onRowSave = vi.fn(async (_i: number, _changes: Record) => {}); + const t = renderTable(onRowSave); + fireEvent.click(t.cell(0, 3)); + fireEvent.keyDown(t.catcher()!, { key: ' ' }); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + expect(onRowSave.mock.calls[0][1]).toEqual({ done: true }); + }); +}); + +describe('data-table autosave — a refusal keeps the edit and says why', () => { + it('keeps the typed value, marks the cell with the server reason, and Esc goes back to the stored value', async () => { + const onRowSave = vi.fn(async () => { throw fieldRefusal([{ field: 'name', message: 'Name is required' }]); }); + const t = renderTable(onRowSave); + t.typeAndEnter(0, 0, 'Alp'); + await waitFor(() => expect(t.cell(0, 0)).toHaveAttribute('aria-invalid', 'true')); + expect(t.cell(0, 0)).toHaveTextContent('Alp'); + expect(screen.getByTestId('cell-save-failure')).toHaveTextContent('Name is required'); + // Back on the cell: editing again starts from what was typed. + fireEvent.click(t.cell(0, 0)); + fireEvent.keyDown(t.catcher()!, { key: 'Enter' }); + expect(t.editor()).toHaveValue('Alp'); + // Esc in the editor drops the kept edit. + fireEvent.keyDown(t.editor()!, { key: 'Escape' }); + expect(t.editor()).toBeNull(); + expect(t.cell(0, 0)).toHaveTextContent('Alpha'); + expect(t.cell(0, 0)).not.toHaveAttribute('aria-invalid'); + expect(screen.queryByTestId('cell-save-failure')).toBeNull(); + }); + + it('Esc on the selected refused cell drops the edit too', async () => { + const onRowSave = vi.fn(async () => { throw new Error('Server unavailable'); }); + const t = renderTable(onRowSave); + t.typeAndEnter(1, 0, 'Bet'); + await waitFor(() => expect(t.cell(1, 0)).toHaveAttribute('aria-invalid', 'true')); + // A reason the refusal names on no field is said on the edited cell. + expect(screen.getByTestId('cell-save-failure')).toHaveTextContent('Server unavailable'); + fireEvent.click(t.cell(1, 0)); + fireEvent.keyDown(t.catcher()!, { key: 'Escape' }); + expect(t.cell(1, 0)).toHaveTextContent('Beta'); + expect(t.cell(1, 0)).not.toHaveAttribute('aria-invalid'); + }); +}); + +describe('data-table autosave — a refused row sends its next commit together with the kept cell', () => { + it('stage refused for a missing lost reason; filling the reason sends both in one update', async () => { + const onRowSave = vi.fn(async (_i: number, changes: Record) => { + if (changes.stage === 'lost' && !changes.lost_reason) { + throw fieldRefusal([{ field: 'lost_reason', message: 'A lost deal needs a reason' }]); + } + }); + const t = renderTable(onRowSave); + t.typeAndEnter(0, 1, 'lost'); + await waitFor(() => expect(t.cell(0, 2)).toHaveAttribute('aria-invalid', 'true')); + // The named cell carries its reason; the edited one keeps its value. + expect(t.cell(0, 2)).toHaveAttribute('data-cell-error', 'A lost deal needs a reason'); + expect(t.cell(0, 1)).toHaveTextContent('lost'); + t.typeAndEnter(0, 2, 'Budget'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2)); + expect(onRowSave.mock.calls[1][1]).toEqual({ stage: 'lost', lost_reason: 'Budget' }); + await waitFor(() => expect(t.cell(0, 2)).not.toHaveAttribute('aria-invalid')); + expect(t.cell(0, 1)).not.toHaveAttribute('aria-invalid'); + }); +}); + +describe('data-table autosave — a commit during a running save waits for it', () => { + it('sends the second cell alone once the first save lands', async () => { + const { onRowSave, calls } = deferredSave(); + const t = renderTable(onRowSave); + t.typeAndEnter(0, 0, 'Alpha 2'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + t.typeAndEnter(0, 1, 'won'); + await act(async () => {}); + expect(onRowSave).toHaveBeenCalledTimes(1); + await act(async () => { calls[0].resolve(); }); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2)); + expect(onRowSave.mock.calls[1][1]).toEqual({ stage: 'won' }); + }); +}); + +describe('data-table autosave — a rule the list cannot complete', () => { + it('offers to open the record when the refusal names a field the list does not draw', async () => { + const onRowClick = vi.fn(); + const onRowSave = vi.fn(async () => { throw fieldRefusal([{ field: 'close_date', message: 'A closed deal needs a close date' }]); }); + const t = renderTable(onRowSave, { onRowClick }); + t.typeAndEnter(0, 1, 'won'); + const open = await screen.findByTestId('cell-save-open-record'); + expect(screen.getByTestId('cell-save-failure')).toHaveTextContent('A closed deal needs a close date'); + fireEvent.click(open); + expect(onRowClick).toHaveBeenCalledTimes(1); + expect(onRowClick.mock.calls[0][0]).toBe(ROWS[0]); + }); + + it('offers nothing when every named field is a cell the list edits', async () => { + const onRowSave = vi.fn(async () => { throw fieldRefusal([{ field: 'lost_reason', message: 'Needs a reason' }]); }); + const t = renderTable(onRowSave, { onRowClick: vi.fn() }); + t.typeAndEnter(0, 1, 'lost'); + await screen.findByTestId('cell-save-failure'); + expect(screen.queryByTestId('cell-save-open-record')).toBeNull(); + }); +}); + +describe('data-table autosave — a saved row keeps its place until the rows load', () => { + const names = (c: HTMLElement) => [...c.querySelectorAll('tbody tr')].map((tr) => tr.querySelectorAll('td[data-grid-cell]')[0].textContent); + + it('a client-sorted row updated in place stays put; a new load sorts it', async () => { + const onRowSave = vi.fn(async () => {}); + const t = renderTable(onRowSave); + // Sort by Name ascending: Alpha, Beta. + fireEvent.click(screen.getByText('Name')); + expect(names(t.container)).toEqual(['Alpha', 'Beta']); + t.typeAndEnter(0, 0, 'Zulu'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + // The host draws the saved row in place of the one it read, as `ObjectGrid` does. + t.rerenderWith({ data: [{ ...ROWS[0], name: 'Zulu' }, ROWS[1]] }); + await act(async () => {}); + expect(names(t.container)).toEqual(['Zulu', 'Beta']); + // A load: every row is a new object. + t.rerenderWith({ data: [{ ...ROWS[0], name: 'Zulu' }, { ...ROWS[1] }] }); + await waitFor(() => expect(names(t.container)).toEqual(['Beta', 'Zulu'])); + }); +}); + +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); + 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 () => {}); + expect(onRowSave).not.toHaveBeenCalled(); + expect(screen.getByText(/row modified/)).toBeInTheDocument(); + }); +}); + +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' }); + }); +}); + +describe('data-table autosave — Esc in the editor while the row is saving', () => { + it('takes back only that edit and leaves the sent value alone', async () => { + const { onRowSave, calls } = deferredSave(); + const t = renderTable(onRowSave); + t.typeAndEnter(0, 0, 'Alpha 2'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + // Reopen the cell whose value is on the wire, type, then Esc. + fireEvent.click(t.cell(0, 0)); + fireEvent.change(t.catcher()!, { target: { value: 'X' } }); + fireEvent.change(t.editor()!, { target: { value: 'Xyz' } }); + fireEvent.keyDown(t.editor()!, { key: 'Escape' }); + await act(async () => {}); + expect(t.cell(0, 0).textContent).toContain('Alpha 2'); + expect(t.editor()).toBeNull(); + // The typed-over text was never sent: the one save is the first commit. + await act(async () => { calls[0].resolve(); }); + expect(onRowSave).toHaveBeenCalledTimes(1); + expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Alpha 2' }); + }); +}); 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 302df864b15..b0de1635bd9 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 @@ -15,13 +15,16 @@ * 1. A click selects a cell: a ring, no editor, no record opened. Without * the provider the same click still edits (the control). * 2. Double-click, Enter or F2 edits; the value is kept. - * 3. Space opens the record; a two-state cell flips on Space or on a second - * click instead, and commits. + * 3. Space is typed like any key and opens the editor, never the record + * (the maintainer's correction on #35683); a two-state cell flips on + * Space or on a second click instead, and commits. * 4. A link the cell draws keeps its own click; a double-click on the cell * around it edits. * 5. A cell that opens no editor says why on the cell: the host's sentence, * else the table's own. * 6. A touch tap opens the record and edits nothing. + * 7. The edit-only row column is never drawn: each cell saves itself + * (objectstack#35685, `data-table-autosave-35685.test.tsx`). */ import React from 'react'; import { describe, it, expect, afterEach, vi } from 'vitest'; @@ -154,14 +157,16 @@ describe('data-table select-first — double-click, Enter and F2 edit', () => { }); }); -describe('data-table select-first — Space opens; a two-state cell flips', () => { - it('Space on the selected cell opens the record', () => { +describe('data-table select-first — Space types; a two-state cell flips', () => { + it('Space on the selected cell is typed into it: the editor opens on it and no record opens', () => { const t = renderTable(); fireEvent.click(t.cell(0, 0)); - fireEvent.keyDown(t.catcher()!, { key: ' ' }); - expect(t.onRowClick).toHaveBeenCalledTimes(1); - expect(t.onRowClick.mock.calls[0][0]).toBe(ROWS[0]); - expect(t.editor()).toBeNull(); + // The key is left to the catcher (not prevented), which reads it as typing. + expect(fireEvent.keyDown(t.catcher()!, { key: ' ' })).toBe(true); + expect(t.onRowClick).not.toHaveBeenCalled(); + fireEvent.change(t.catcher()!, { target: { value: ' ' } }); + expect(t.editor()).toHaveValue(' '); + expect(t.onRowClick).not.toHaveBeenCalled(); }); it('Space on a selected boolean flips it and commits, and opens nothing', () => { @@ -236,26 +241,24 @@ describe('data-table select-first — a cell that opens no editor says why', () }); }); -describe('data-table select-first — the edit-only column is drawn only while a row has changes (objectstack#35554)', () => { +describe('data-table select-first — no edit-only column, ever (objectstack#35554, objectstack#35685)', () => { const editHeader = (c: HTMLElement) => c.querySelector('[data-testid="data-table-edit-column-header"]'); const lastHeader = (c: HTMLElement) => [...c.querySelectorAll('thead th')].pop()!; // The shape `ObjectGrid` hands the list page: a save path and no row menu. const EDIT_ONLY = { rowActions: true, onRowSave: () => Promise.resolve() }; - it('none at rest; a commit draws it with that row\'s Cancel and Save; Cancel takes it away', () => { - const t = renderTable({ extra: EDIT_ONLY }); + it('none at rest and none after a commit: the commit saves itself', () => { + const onRowSave = vi.fn(() => Promise.resolve()); + const t = renderTable({ extra: { ...EDIT_ONLY, onRowSave } }); expect(editHeader(t.container)).toBeNull(); expect(lastHeader(t.container)).toHaveTextContent('Site'); fireEvent.click(t.cell(0, 0)); fireEvent.change(t.catcher()!, { target: { value: 'A' } }); fireEvent.keyDown(t.editor()!, { key: 'Enter' }); - expect(editHeader(t.container)).not.toBeNull(); - expect(lastHeader(t.container)).toBe(editHeader(t.container)); - const firstRow = t.container.querySelectorAll('tbody tr')[0] as HTMLElement; - expect(firstRow.querySelector('button[title="Save row"]')).not.toBeNull(); - fireEvent.click(firstRow.querySelector('button[title="Cancel changes"]')!); expect(editHeader(t.container)).toBeNull(); expect(lastHeader(t.container)).toHaveTextContent('Site'); + expect(t.container.querySelector('button[title="Save row"]')).toBeNull(); + expect(onRowSave).toHaveBeenCalledTimes(1); }); it('control: without the provider the column is drawn at rest, as before', () => { diff --git a/ui/packages/components/src/context/gridCellSelection.tsx b/ui/packages/components/src/context/gridCellSelection.tsx index 8302bd61347..3348d0e9a96 100644 --- a/ui/packages/components/src/context/gridCellSelection.tsx +++ b/ui/packages/components/src/context/gridCellSelection.tsx @@ -12,7 +12,8 @@ * * Inside a provider whose value is not `null`, a data cell is SELECTED by a * single click, never edited by it and never opening the record. An editor - * opens on double-click, Enter, F2 or typing; Space opens the record; Esc + * opens on double-click, Enter, F2 or typing (Space included; a two-state + * cell flips instead); the title link or a touch tap opens the record; Esc * cancels; Enter and Tab commit and move (in a multi-line editor Enter is a * newline and Ctrl/Cmd+Enter commits). A cell that opens no editor says why * in place. Outside a provider (`null`, the default) the table keeps its diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index c3621e2c0ea..a70ec14d359 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -64,6 +64,8 @@ import { Plus, MoreHorizontal, AlertCircle, + Check, + Loader2, } from 'lucide-react'; import { DropdownMenu, @@ -342,6 +344,11 @@ const TABLE_DEFAULT_TRANSLATIONS: Record = { // 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.', + // objectstack#35685 — a list cell's own save state, and the way out of a + // rule the list cannot complete. + 'table.cellSaving': 'Saving…', + 'table.cellSaved': 'Saved', + 'table.openRecordToFinish': 'Open the record to finish this change', 'common.actions': 'Actions', // objectui#10625 — the inline date editors' notice for a stored value // written on a day that does not exist. The SAME keys `DateField` / @@ -1386,6 +1393,70 @@ function CellNotice({ text, onDismiss }: { text: string; onDismiss: () => void } ); } +/** + * objectstack#35685 — why a list cell's save was refused, said on that cell: + * the server's reasons, one line each, and, when the refusal names a field the + * list cannot edit, the way to the record where it can be finished. + */ +function CellSaveFailure({ + lines, + title, + openRecordLabel, + onOpenRecord, + onDismiss, +}: { + lines: readonly string[]; + title: string; + openRecordLabel: string; + onOpenRecord?: (e: React.MouseEvent) => void; + onDismiss: () => void; +}) { + return ( + { if (!open) onDismiss(); }}> + + + e.preventDefault()} + onCloseAutoFocus={(e) => e.preventDefault()} + className="w-auto max-w-xs space-y-1 px-2.5 py-1.5 text-xs" + > +
+ + {lines.length === 1 ? ( + {title}: {lines[0]} + ) : ( +
+ {title}: +
    + {lines.map((line) =>
  • {line}
  • )} +
+
+ )} +
+ {onOpenRecord && ( + + )} +
+
+ ); +} + const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const { caption, @@ -1438,10 +1509,15 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // objectstack#35684 — the select-first cell model, when a host mounted one // (`GridCellSelection`): a click selects a cell, an editor opens on - // double-click, Enter, F2 or typing, Space opens the record. It needs the + // double-click, Enter, F2 or typing (Space too), and each committed cell + // saves at once (objectstack#35685). It needs the // arrow keys, so it turns the roving-cell navigation on. const cellSelection = useGridCellSelection(); 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. + const autosaves = selectFirst && typeof schema.onRowSave === 'function'; const keyboardNavigation = keyboardNavigationProp || selectFirst; // 'single' caps the selection at one row (replace-on-select) and drops the @@ -1946,6 +2022,33 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // 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 + // commit sends them again together with the new cell, as one update. + // + // The refusal of a row's last save: its lines, and whether it named a field + // the list cannot edit (the record is where that change can be finished). + const [rowRefusals, setRowRefusals] = useState>(new Map()); + // Each cell's save state while it shows: in flight, or just saved. + const [cellSaveStates, setCellSaveStates] = useState>>(new Map()); + // The refused cell whose reason opens on its own as the refusal lands. + const [failureNotice, setFailureNotice] = useState<{ rowKey: PendingRowKey; columnKey: string } | null>(null); + // The rows a save updated in place since the rows last loaded, each as it + // sorted and filtered before that save: a client-side sort or search keeps + // reading these, so a saved row stays where it is until the next load. + const [sortBasis, setSortBasis] = useState>(new Map()); + // The records whose save is running, those committed again meanwhile, and + // those whose commit is waiting for the render that holds it. + const runningSavesRef = useRef>(new Set()); + const saveAgainRef = useRef>(new Set()); + const autosaveDueRef = useRef>(new Set()); + const [autosaveTick, setAutosaveTick] = useState(0); + const savedTimersRef = useRef>>(new Set()); + useEffect(() => () => { + for (const timer of savedTimersRef.current) clearTimeout(timer); + savedTimersRef.current.clear(); + }, []); // Column header context menu state const [contextMenu, setContextMenu] = useState<{ x: number; y: number; columnKey: string } | null>(null); // objectstack#28434 — the row context menu: which row it is open on, where, @@ -2064,6 +2167,26 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // filter path, so leaving both active would not even be redundant: the client // pass would narrow the server's answer to whichever of its rows happen to // contain the term as rendered text. + // objectstack#35685 — a row a save updated in place is sorted and searched + // as it was before that save, until the rows load again (`sortBasis`). + const sortRowOf = (row: any): any => (sortBasis.size > 0 ? sortBasis.get(pendingRowKeyOf(row)) ?? row : row); + // A load is any held row that changed without a save of ours updating it: + // the basis then has nothing left to stand for. + const lastHeldRowsRef = useRef | null>(null); + useEffect(() => { + const held = new Map(); + for (const row of data) held.set(pendingRowKeyOf(row), row); + const before = lastHeldRowsRef.current; + lastHeldRowsRef.current = held; + if (sortBasis.size === 0 || before === null) return; + const loaded = held.size !== before.size + || Array.from(held).some(([key, row]) => before.get(key) !== row && !sortBasis.has(key)); + if (loaded) setSortBasis(new Map()); + }, [data]); + useEffect(() => { + setSortBasis((prev) => (prev.size === 0 ? prev : new Map())); + }, [sortColumn, sortDirection, searchQuery]); + const filteredData = useMemo(() => { if (manualSearch) return data; if (!searchQuery) return data; @@ -2074,11 +2197,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const searchedColumns = columns.filter((col) => !isMaskedColumnKey(rawColumns, col.accessorKey)); return data.filter((row) => searchedColumns.some((col) => { - const value = row[col.accessorKey]; + const value = sortRowOf(row)[col.accessorKey]; return value?.toString().toLowerCase().includes(searchQuery.toLowerCase()); }) ); - }, [data, searchQuery, columns, rawColumns, manualSearch]); + }, [data, searchQuery, columns, rawColumns, manualSearch, sortBasis]); // Sorting — client-side, over the rows this table was handed. // @@ -2104,14 +2227,14 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // the reader how it compares with every other row's. if (isMaskedColumnKey(rawColumns, sortColumn)) return filteredData; - const keyed = filteredData.map((row) => ({ row, key: getSortValue(row[sortColumn]) })); + const keyed = filteredData.map((row) => ({ row, key: getSortValue(sortRowOf(row)[sortColumn]) })); // Array#sort is stable, so rows with equal keys keep their incoming order. keyed.sort((a, b) => { const comparison = compareSortValues(a.key, b.key); return sortDirection === 'asc' ? comparison : -comparison; }); return keyed.map((entry) => entry.row); - }, [filteredData, sortColumn, sortDirection, manualSorting, rawColumns]); + }, [filteredData, sortColumn, sortDirection, manualSorting, rawColumns, sortBasis]); // objectui#12620 — a grouped table keeps every row in its own band. The // sorted rows are partitioned back into their groups, in group order; the @@ -2656,6 +2779,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const inFlight = inFlightRef.current.get(rowKey); setPendingChanges((prev) => stageCellChange(prev, rowKey, row, columnKey, valueToStage, inFlight)); clearCellError(rowKey, columnKey); + // objectstack#35685 — the select-first model saves the commit at once. + requestAutosave(rowKey); // Call the legacy onCellChange callback if provided if (schema.onCellChange) { @@ -2709,7 +2834,13 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const active = editingCellRef.current; const snap = editRevertRef.current; editRevertRef.current = null; - if (revert && active && snap) { + if (revert && active && autosaves && !runningSavesRef.current.has(active.rowKey)) { + // objectstack#35685 — Esc goes back to the stored value, a kept + // (refused) edit of this cell included. While the row's save is on the + // wire it only takes back this edit (below), as Esc on the selected cell + // leaves a sent value alone. + discardCellChange(active.rowKey, active.columnKey); + } else if (revert && active && snap) { const { rowKey, columnKey } = active; setPendingChanges((prev) => { const cur = prev.get(rowKey); @@ -2956,6 +3087,148 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { setSaveError(null); }; + // ── Per-cell autosave (objectstack#35685) ──────────────────────────────── + const setCellSaveState = (rowKey: PendingRowKey, columnKeys: readonly string[], state: 'saving' | 'saved' | null) => { + setCellSaveStates((prev) => { + const next = new Map(prev); + const cells = { ...(prev.get(rowKey) ?? {}) }; + for (const key of columnKeys) { + if (state) cells[key] = state; + else delete cells[key]; + } + if (Object.keys(cells).length > 0) next.set(rowKey, cells); + else next.delete(rowKey); + return next; + }); + }; + /** A just-saved cell says so for a moment, then goes quiet. */ + const flashSaved = (rowKey: PendingRowKey, columnKeys: readonly string[]) => { + setCellSaveState(rowKey, columnKeys, 'saved'); + const timer = setTimeout(() => { + savedTimersRef.current.delete(timer); + setCellSaveStates((prev) => { + const cells = prev.get(rowKey); + if (!cells || !columnKeys.some((key) => cells[key] === 'saved')) return prev; + const rest = { ...cells }; + for (const key of columnKeys) if (rest[key] === 'saved') delete rest[key]; + const next = new Map(prev); + if (Object.keys(rest).length > 0) next.set(rowKey, rest); + else next.delete(rowKey); + return next; + }); + }, 1500); + savedTimersRef.current.add(timer); + }; + + /** Ask for a record's autosave; it runs once the render holding the commit lands. */ + const requestAutosave = (rowKey: PendingRowKey) => { + if (!autosaves) return; + autosaveDueRef.current.add(rowKey); + setAutosaveTick((tick) => tick + 1); + }; + + /** + * Send one record's pending edits as one update. Every edit the record still + * holds goes, so a cell a refusal kept travels with the next commit on its + * row. A commit made while the record's save runs waits for it, and then + * sends what is left. + */ + const autosaveRow = async (rowKey: PendingRowKey, pending: PendingRow | undefined) => { + if (!pending || Object.keys(pending.changes).length === 0 || !schema.onRowSave) return; + if (runningSavesRef.current.has(rowKey)) { + saveAgainRef.current.add(rowKey); + return; + } + runningSavesRef.current.add(rowKey); + const sentChanges = pending.changes; + const sentKeys = Object.keys(sentChanges); + const sent = new Map([[rowKey, sentChanges]]); + const row = heldRowOf(rowKey) ?? pending.row; + // The row sorts as it does now until the next load, whatever the save writes. + setSortBasis((prev) => (prev.has(rowKey) ? prev : new Map(prev).set(rowKey, row))); + setCellSaveState(rowKey, sentKeys, 'saving'); + try { + await whileInFlight(sent, async () => { + await schema.onRowSave?.(rowIndexOf(rowKey), sentChanges, row); + }); + setPendingChanges((prev) => removeSentEdits(prev, sent)); + setRowCellErrors(rowKey, null); + setRowRefusals((prev) => { + if (!prev.has(rowKey)) return prev; + const next = new Map(prev); + next.delete(rowKey); + return next; + }); + setFailureNotice((prev) => (prev?.rowKey === rowKey ? null : prev)); + flashSaved(rowKey, sentKeys); + } catch (error) { + // The edits stay pending and the cells keep what was typed. Each cell the + // refusal names shows its own reason; a cell it does not name shows them + // all. A named field the list cannot edit sends the reader to the record. + console.error('Failed to save row:', error); + setCellSaveState(rowKey, sentKeys, null); + const lines = saveRefusalLines([error]); + const named = refusedCellsOf(error) ?? {}; + const editableHere = (field: string) => { + const col = columns.find((c) => c.accessorKey === field); + return !!col && col.editable !== false && !col.masked; + }; + const cells: Record = {}; + for (const [field, message] of Object.entries(named)) { + if (columns.some((c) => c.accessorKey === field)) cells[field] = message; + } + for (const key of sentKeys) if (!(key in cells)) cells[key] = lines.join(' '); + setRowCellErrors(rowKey, cells); + setRowRefusals((prev) => new Map(prev).set(rowKey, { + lines, + needsRecord: Object.keys(named).some((field) => !editableHere(field)), + })); + setFailureNotice({ rowKey, columnKey: sentKeys[0] }); + } finally { + runningSavesRef.current.delete(rowKey); + if (saveAgainRef.current.delete(rowKey)) requestAutosave(rowKey); + } + }; + + useEffect(() => { + if (!autosaves || autosaveDueRef.current.size === 0) return; + const due = Array.from(autosaveDueRef.current); + autosaveDueRef.current.clear(); + for (const rowKey of due) void autosaveRow(rowKey, pendingChanges.get(rowKey)); + }, [autosaveTick, pendingChanges]); + + /** + * Esc on a cell whose edit is kept: the edit is dropped and the cell shows + * the stored value again. The rest of the row's kept edits stay. + */ + const discardCellChange = (rowKey: PendingRowKey, columnKey: string) => { + setPendingChanges((prev) => { + const cur = prev.get(rowKey); + if (!cur || !(columnKey in cur.changes)) return prev; + const next = new Map(prev); + const rest = { ...cur.changes }; + delete rest[columnKey]; + if (Object.keys(rest).length > 0) next.set(rowKey, { row: cur.row, changes: rest }); + else next.delete(rowKey); + return next; + }); + const kept = pendingChanges.get(rowKey)?.changes; + if (!kept || Object.keys(kept).every((key) => key === columnKey)) { + // Nothing of the row is kept any more, so nothing of its refusal stands. + setRowCellErrors(rowKey, null); + setRowRefusals((prev) => { + if (!prev.has(rowKey)) return prev; + const next = new Map(prev); + next.delete(rowKey); + return next; + }); + setFailureNotice((prev) => (prev?.rowKey === rowKey ? null : prev)); + } else { + clearCellError(rowKey, columnKey); + setFailureNotice((prev) => (prev?.rowKey === rowKey && prev?.columnKey === columnKey ? null : prev)); + } + }; + // ── Keyboard navigation (objectui#11068) ────────────────────────────────── // // Arrow-key cell navigation on the WAI-ARIA grid pattern, behind @@ -3175,6 +3448,9 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const col = columns[colIndex]; if (row === undefined || col === undefined) return; setCellNotice(null); + // objectstack#35685 — a selected cell whose edit a refusal kept says why. + const rowKey = pendingRowKeyOf(row); + setFailureNotice(cellErrors.get(rowKey)?.[col.accessorKey] !== undefined ? { rowKey, columnKey: col.accessorKey } : null); rove(rowIndex, colIndex); if (selectedPos?.rowIndex === rowIndex && selectedPos.colIndex === colIndex) { // Selected already, so no render follows to move the focus: a click on @@ -3220,6 +3496,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { setPendingChanges((prev) => stageCellChange(prev, rowKey, held, columnKey, value, inFlight)); clearCellError(rowKey, columnKey); schema.onCellChange?.(rowIndexOf(rowKey), columnKey, value, held); + requestAutosave(rowKey); }; /** What a cell does with a value it is handed rather than edited: a toggle or a paste. */ @@ -3281,8 +3558,13 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { if (row === undefined || col === undefined) return; const bare = !e.ctrlKey && !e.metaKey && !e.altKey; if (e.key === 'Escape') { + const rowKey = pendingRowKeyOf(row); if (cellNotice) setCellNotice(null); - else if (selectedPos) { + else if (autosaves && pendingChanges.get(rowKey)?.changes && col.accessorKey in pendingChanges.get(rowKey)!.changes && !runningSavesRef.current.has(rowKey)) { + // objectstack#35685 — a kept (refused) edit: Esc drops it. + e.preventDefault(); + discardCellChange(rowKey, col.accessorKey); + } else if (selectedPos) { e.preventDefault(); focusGridCell(rowIndex, colIndex); setSelectedCell(null); @@ -3316,10 +3598,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { if ((e.key === 'Enter' || e.key === 'F2') && bare && !e.shiftKey) { e.preventDefault(); attemptEdit(rowIndex, colIndex); - } else if (e.key === ' ' && bare) { + } else if (e.key === ' ' && bare && togglesCell(row, col)) { + // A two-state cell flips; on any other cell Space is typed like any key + // and opens the editor (the catcher reads it). e.preventDefault(); - if (togglesCell(row, col)) toggleCell(rowIndex, colIndex); - else schema.onRowClick?.(row, e); + toggleCell(rowIndex, colIndex); } else if ((e.key === 'Backspace' || e.key === 'Delete') && bare) { // An empty editor; nothing is written until it commits. e.preventDefault(); @@ -3599,10 +3882,13 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { (Array.isArray(schema.rowActionDefs) && schema.rowActionDefs.length > 0 && schema.onRowActionDef) ); const rowActionsColumnIsEditOnly = editable && !!(schema.onRowSave || schema.onBatchSave) && !rowMenuDeclared; - // objectstack#35684, until objectstack#35685 retires it: in the select-first - // model the edit-only column shows only while a row has pending changes, so a - // list at rest ends on its last data column (objectstack#35554). - const drawRowActionsColumn = rowActions && !(selectFirst && rowActionsColumnIsEditOnly && !hasPendingChanges); + // 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); /** * objectstack#28434 — the items ONE row's context menu opens with, or `null` @@ -3727,7 +4013,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
- {hasPendingChanges && ( + {/* objectstack#35685 — the select-first model saves each cell, so it draws no save bar. */} + {hasPendingChanges && !autosaves && ( <>
{t('table.modified', { count: pendingChanges.size })} @@ -3775,7 +4062,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { {/* 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 && saveError && ( + {hasPendingChanges && !autosaves && saveError && (
{ "data-[active-record]:bg-primary/10 data-[active-record]:[--os-row-tint:color-mix(in_oklab,var(--color-primary)_10%,transparent)]", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-inset", !selectFirst && schema.onRowClick && "cursor-pointer", - rowHasChanges && !rowErrored && "bg-amber-50 dark:bg-amber-950/20", - rowErrored && "bg-destructive/10 dark:bg-destructive/15 ring-1 ring-inset ring-destructive/40", + // objectstack#35685 — the select-first model marks the cell, never the row. + !autosaves && rowHasChanges && !rowErrored && "bg-amber-50 dark:bg-amber-950/20", + !autosaves && rowErrored && "bg-destructive/10 dark:bg-destructive/15 ring-1 ring-inset ring-destructive/40", rowClassName && rowClassName(row, rowIndex) )} style={rowStyle ? rowStyle(row, rowIndex) : undefined} @@ -4457,7 +4745,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // A ring that moves no layout (outline, not border). isSelectedCell && "outline-2 -outline-offset-2 outline-primary", selectFirst && !isFrozen && "relative", - hasPendingChange && "font-semibold text-amber-700 dark:text-amber-400", + !autosaves && hasPendingChange && "font-semibold text-amber-700 dark:text-amber-400", cellError !== undefined && "ring-2 ring-inset ring-destructive", isFrozen && ['sticky z-10 bg-background', STICKY_ROW_TINT], isFrozen && colIndex === frozenColumns - 1 && scrolledX && FROZEN_EDGE_SHADOW, @@ -4582,6 +4870,40 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { {cellNotice?.rowIndex === rowIndex && cellNotice.colIndex === colIndex && ( setCellNotice(null)} /> )} + {selectFirst && !isEditing && cellError !== undefined + && failureNotice?.rowKey === rowKey && failureNotice?.columnKey === col.accessorKey + && !(cellNotice?.rowIndex === rowIndex && cellNotice.colIndex === colIndex) && (() => { + // objectstack#35685 — the refusal, on the cell it kept. + const refusal = rowRefusals.get(rowKey); + const lines = refusal && cellError === refusal.lines.join(' ') ? refusal.lines : [cellError]; + return ( + schema.onRowClick?.(row, e) : undefined} + onDismiss={() => setFailureNotice(null)} + /> + ); + })()} + {selectFirst && !isEditing && cellSaveStates.get(rowKey)?.[col.accessorKey] && (() => { + // objectstack#35685 — the cell's own save state, drawn over its + // edge so nothing moves. + const state = cellSaveStates.get(rowKey)?.[col.accessorKey]; + return ( + + {state === 'saving' + ? + ); + })()} {isEditing ? ( (() => { // Type-aware inline editor. `col.type` is forwarded @@ -4829,7 +5151,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { {drawRowActionsColumn && (
- {rowHasChanges && (schema.onRowSave || schema.onBatchSave) ? ( + {rowHasChanges && !autosaves && (schema.onRowSave || schema.onBatchSave) ? ( <>