Skip to content

Commit 8500ee7

Browse files
feat(list): confirm a state-machine move before a list cell saves it; the drawer says when the record changed (#35972)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuKUos5dktPsiz4z1ihWMgNS)_ repo:objectstack#1 · os-sales · session_01L6bhgVhAK4uNYvjNY3H7XU Fixes #35685 (slice S3, the last of three: the state-machine confirm and the drawer sync. S1 #35864 and S2 #35898 are merged. Retiring `onBatchSave` stays with #35827.) Clause-②: yes (widening) — `GridCellSelection` in `@object-ui/components` takes an optional `confirmCommit(row, columnKey, value)` member; nothing removed or renamed Metadata-protocol: none Skills-docs: `content/docs/frontend/plugins/plugin-grid.mdx` — the "On an object's list page" section gains two bullets (a state-machine field asks first; the record drawer follows a list save and keeps a draft). No skill under `skills/` teaches the list's save, so nothing there moves. Follow-up: #35928 (the confirm names the automation that would run; the ruling asked for a card, not this slice) Flow: dev-thread rule (maintainer 2026-11-20 09:22:50Z): the card thread builds itself; L1 by L1-a, the declaration L2 by the seat on the green head. ## 维护者速读 - 列表页里改「状态」这类受状态机规则管的字段时,选好新值后会先弹出确认框:「更改状态?状态从 已暂停 改为 进行中,保存后可能触发相关自动化。」点「取消」什么都不保存,格子保持原值;点「确认更改」才保存。粘贴到这种格子也一样会先问。其他字段不弹框,照旧改完即存。 - 属于「列表行内编辑重做」专题,是逐格自动保存这张卡的最后一片;合并后 #35685 关闭。确认框里列出具体会触发哪些自动化,按裁定另开了卡 #35928。 - 记录抽屉开着时,列表里改了同一条记录,抽屉会跟着刷新显示新值;如果抽屉里正有没保存的修改,修改原样保留,并提示「此记录已在别处被修改……保存时以你的修改为准」,点保存不会报冲突,写在最新版本上。 - 无。 ## What changes **A state-machine move asks first** (`@object-ui/plugin-grid`, `ObjectGrid`; only a grid with `cellSelection`, i.e. every grid `ListView` draws). - A field is a state-machine field when an active `state_machine` validation rule of the object names it and its `events` cover `update` (the spec default `['insert','update']` when absent). Severity does not matter: a move along the machine is what related automation listens for, blocking or not. Which moves are legal stays the server's call. (`objectGridStateConfirm.ts`) - A new value committed into such a cell (picked in its editor, or pasted) opens an in-app confirm: title `Change {{field}}?`, body `{{field}} changes from {{from}} to {{to}}. Saving may trigger related automation.` (ruling 7039615827), buttons Cancel / Change. The values are shown as their option labels as the host translates them, the stored code when no option declares it, and the grid's `Empty` word for no value. - Cancel writes nothing: nothing is staged, nothing is sent, the cell keeps what it showed. Change saves the value as any S1 commit is saved (one guarded update). Focus goes back to the selected cell either way. A second ask while one is open answers the first one No; unmounting the grid answers No. - A commit that changes nothing, and any cell the host does not ask about, is written at once, as before. **The generic seam** (`@object-ui/components`): `GridCellSelection.confirmCommit` is asked at the table's commit point, before a value that changes what the cell shows is staged or saved, for the editor's commit (`saveEdit`) and for `commitCellValue` (paste, toggle). A promise holds the write until it settles: `true` writes, `false` or a rejection writes nothing; `null` / `undefined` means no question. Only an autosaving select-first table asks; a table outside a provider is byte-for-byte what it was. `exitEdit`'s snapshot revert is factored out as `revertEditSession` so the held commit closes the editor the way Esc does. **The record drawer follows a list save** (`@object-ui/plugin-detail`, `InlineEditSaveBar`). The drawer already re-reads the record when the list saves it (the data-invalidation bus from S1), so the new value shows. What is new: while an inline edit session is open and the record is read again at another version, the save bar says so (`detail.inlineEditRecordChanged`, a `role="status"` note). The draft stays as typed and Save writes it with `If-Match` the version now read, as before (the drawer's draft wins, as the brief asked); only the note is new. Strings: `grid.stateChange.{title,description,confirm,cancel}` and `detail.inlineEditRecordChanged` in all eleven locale packs (zh-Hant regenerated by `gen:zh-hant`), with English fallbacks in `objectGridTranslations.ts` and `useDetailTranslation.ts`, byte-identical to `en`. ## Acceptance notes - The card's parts this slice owns, as the seat's S3 brief words them: (1) a new state picked in a list cell for a state-machine field is confirmed first, Cancel saves nothing; (2) the drawer follows a list save, and when it holds unsaved edits the drawer wins and says so. Both measured in the browser below. - Reading I chose: the confirm does not list the flows that would run; the ruling's words are "may trigger related automation", and naming the flows is #35928. - Reading I chose: at 375 px the list draws cards, not table cells, so there is no list cell to commit into and no confirm there. The phone list's own edit path is not this card. - Platform checklist: no clause moves. `ux-conventions.write-feedback` variants[1] edits a Priority cell (no state machine), and its steps[4] already says the grid editor offers only legal moves. ## Tests - `ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx`, new block "a commit the host asks to confirm first": No writes nothing, the editor closes, focus returns to the cell; Yes gives exactly one update of that cell; a paste is asked as an editor commit is; an unchanged commit and a cell the host does not ask about are not held. - `ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx`, new block: the dialog names the field and both labels and says automation may run, Cancel sends nothing; Change sends one guarded update; a field with no machine, and an inactive machine, is not asked; a machine bound to `insert` alone is not asked; a warning-severity machine is asked (round 1). - `ui/packages/plugin-detail/src/__tests__/InlineEditSaveBar.test.tsx`, new block: the note appears when the record is read again at another version during the session, the draft is kept and Save sends `ifMatch` the new version; no note while the version is the one the edit began on, nor in the next session. Ablation (committed first, mutated through `scripts/ablation-replace.mjs`, restored to the HEAD blob with `git diff HEAD` empty): - `commitConfirmationOf` returns `null` unconditionally → 6 failed / 27 passed across the two confirm files; restored → green. - the save bar's note never rendered → 2 failed / 9 passed in `InlineEditSaveBar.test.tsx`; restored → green. - round 1: `isStateMachineField` returns `true` instead of reading `events` → "a machine bound to insert alone" fails (1 failed / 17 passed); it refuses a `severity: 'warning'` rule → "an advisory (warning-severity) machine still asks" fails (1 / 17); each restored → 18/18. Migrated or voided: none. ## Review round 1 (head `c904bd92`, after `1ef49fae`) - L2 7055688534 F2 should-fix: two cases added to the `ObjectGrid` block (insert-only machine not asked; warning-severity machine asked), so the `events.includes('update')` branch and the ignored severity are both measured; ablated as above. F3 nit: the `confirmCommit` JSDoc now says only a table wired with `onRowSave` asks, and one on `onBatchSave` alone never does. F4 nit left, as the seat ruled. - L2 F1 should-fix, traced in the browser (log `f1-trace.log` beside the other evidence; every `fetch` to the object wrapped to print its call stack): with the list alone, a confirmed list cell save sends exactly one request, the `PATCH`, and no read. With the record drawer open on the same row, the `PATCH` is followed by three requests, all for that one record: `GET /api/v1/data/showcase_project?populate=…&top=1&filter=["id","=","<the record id>"]` (the adapter's `findOne` with `$expand`, `readOne` → `rawFindWithPopulate`, which reads one record through the collection route), `POST …/<id>/page` and `GET …/<id>/field-access`. That is the drawer re-reading its own record, which is the drawer sync this slice delivers; it is not S2's related-grid re-read (7042779557) and not a reload of the list's other rows. S1's acceptance holds; nothing to file. - Local on `c904bd92`: `ObjectGrid.autosave-35685` 18/18; eslint on the two changed files 0 errors; `check:nul-bytes` exit 0; overlap-check VERDICT clean. ## Verification <details><summary>Local runs</summary> - `vitest` from `ui/`, one package at a time under `os-verify-lock.sh` on head `44ec496a` (before the main merge): `plugin-grid` 294 files / 2562 tests passed; `plugin-detail` 393 / 3601 passed (1 file skipped); `components` 493 / 4747 passed (1 file skipped); `plugin-list` 182 / 1971 passed; `i18n` 104 / 1956 passed with one red, the zh-Hant generated-catalogue pin, fixed by running `gen:zh-hant` and re-run green (11/11). - After merging main (`1ef49fae`; conflicts only in the locale packs and `useDetailTranslation.ts`, all adjacent additions, both sides kept, zh-Hant regenerated): `app-shell` whole package 2356 files: the first run read a stale `@objectstack/spec` dist (83 files red on exports main had just added, e.g. `readFieldGroupMembership`); after rebuilding `@objectstack/spec` those 83 files re-ran 83/83 passed (627 tests). The confirm and drawer tests plus `i18n` and every `data-table` / `ObjectGrid` / `InlineEditSaveBar` test file re-ran on the merged head: 184 files / 2496 tests passed. - `type-check` (`tsc --noEmit`) for `@object-ui/components`, `@object-ui/plugin-grid`, `@object-ui/plugin-detail`, `@object-ui/i18n`: clean on the merged head (after rebuilding the packages' dependency dists). `eslint` on every changed source and test file: 0 errors. - `node scripts/pm/dispatch-gates.mjs --commands`: 73 families, each run with its exit captured before any pipe. 71 ran on `8620e49e` (before the zh-Hant regeneration and the main merge, which touch no gate input beyond the locale packs) and 2 on the merged head (`check:type-check-debt` under the verify lock, `vitest run scripts/` under `ui/` with one worker), all exit 0. `--ran` on the merged head: 73 derived, 73 run, 0 NOT-MEASURED, 0 UNRUN. - `node scripts/pm/overlap-check.mjs`: VERDICT clean (main and #35968, #35918, #35910 merge cleanly). - Changed lines about 640 vs the 3000 threshold: under. </details> <details><summary>Browser</summary> `examples/app-showcase` (`objectstack dev --fresh --seed-admin`, own port and temp DB) with the `ui/apps/console` Vite dev server over it, headless Chromium, zh-CN, light and dark, desktop 1600×1000 and 375×812. Project list, `status` (governed by `project_status_flow`): - Pick 「进行中」 for a 「已暂停」 project: the confirm reads 「更改状态? 状态从 已暂停 改为 进行中,保存后可能触发相关自动化。」; 0 writes while it is open. - Cancel: 0 writes, the cell still reads 「已暂停」, focus is back on the cell. - Again, Change: one `PATCH {"status":"active"}` with `If-Match`; the cell reads 「进行中」. - Dark theme: the same, the dialog in dark tokens. - 375 px: the list draws cards; no table cells, no confirm (see Acceptance notes). - Drawer open on the record, list cell saved: the drawer re-reads and shows the new status. - Drawer with an unsaved owner draft, list cell saved: the draft is kept, the note shows, the drawer's status follows the list; drawer Save sends `PATCH {"owner":…}` with the latest `If-Match`, no 409. - Not measured: Safari / WebKit (no WebKit build in the container). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (eslint on the changed files: 0 errors) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. (The branch is the platform-assigned `claude/project-thread-f8vhdm`, named in the claim.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (the 维护者速读 block and the maintainer's quotes are Chinese by the maintainer's standing rule) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgVhAK4uNYvjNY3H7XU <!-- signed: repo:objectstack#1 · os-sales · session_01L6bhgVhAK4uNYvjNY3H7XU --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e72f2aa commit 8500ee7

23 files changed

Lines changed: 644 additions & 16 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@object-ui/components': patch
3+
'@object-ui/plugin-grid': patch
4+
'@object-ui/plugin-detail': patch
5+
'@object-ui/i18n': patch
6+
---
7+
8+
feat(list): confirm a state-machine move before a list cell saves it; the drawer's save bar says when the record changed elsewhere
9+
10+
Clause-②: yes (widening) — `GridCellSelection` in `@object-ui/components` takes an optional `confirmCommit(row, columnKey, value)` member; nothing removed or renamed
11+
Metadata-protocol: none
12+
13+
In a grid that mounts `GridCellSelection` (the select-first grid every `ListView` draws):
14+
15+
- **A move of a state-machine field asks first.** When an active `state_machine` validation rule of the object governs the field on update, a new value committed into its cell (picked in the editor, or pasted) opens a confirm naming the field and both values and saying saving may trigger related automation. Cancel writes nothing and the cell keeps what it showed; Change saves the value as any commit is saved. Focus goes back to the cell either way.
16+
- **The generic seam:** `GridCellSelection.confirmCommit` is asked before a value that changes what a cell shows is staged or saved. A promise holds the write until it settles (`true` writes, `false` or a rejection writes nothing); `null` or `undefined` means no question, as before.
17+
18+
On a record page or in a record drawer, `InlineEditSaveBar` now says so when the record is read again at another version while an inline edit session is open (a list cell beside the drawer saved it, say). The draft stays as typed, and Save writes it over the version now read, as it did before; only the note is new.

‎content/docs/frontend/plugins/plugin-grid.mdx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,18 @@ row whose new value would sort it elsewhere stays in place until the next load
427427
takes back that toast's save, while Ctrl+Z always goes newest first. Inside
428428
an open editor Ctrl+Z stays the editor's own text undo. A save of a field the
429429
row did not read offers no Undo.
430+
- **A state-machine field asks first.** When the object's `state_machine`
431+
validation rule governs the field (an active rule whose events cover an
432+
update), picking a new value — in the cell's editor, or by pasting — opens a
433+
confirm that names the field and both values and says saving may trigger
434+
related automation ("Status changes from On Hold to Active. Saving may
435+
trigger related automation."). Cancel writes nothing and the cell keeps the
436+
value it had; Change saves it as any commit is saved. The confirm does not
437+
list the flows. A host asks this through `GridCellSelection.confirmCommit`.
438+
- **The record drawer follows.** A record open in the list's drawer is read
439+
again when a list cell saves it. If the drawer holds unsaved edits of its own,
440+
those stay as typed, the drawer's save bar says the record was changed
441+
elsewhere, and Save writes the drawer's edits over the latest version.
430442

431443
### Footer calculations
432444

‎ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
* 5. A refusal naming a field the list cannot edit offers to open the record.
2222
* 6. A client-sorted row a save updated stays where it is until the rows load.
2323
* 7. Control: without the provider the save bar model is unchanged.
24+
* 8. A commit the host asks to confirm (`confirmCommit`, slice S3) is held
25+
* with nothing staged: No leaves the cell as it was, Yes writes it; a
26+
* paste is asked too, an unchanged value is not.
2427
*/
2528
import React from 'react';
2629
import { describe, it, expect, afterEach, vi } from 'vitest';
@@ -310,3 +313,93 @@ describe('data-table autosave — Esc in the editor while the row is saving', ()
310313
expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Alpha 2' });
311314
});
312315
});
316+
317+
describe('data-table autosave — a commit the host asks to confirm first (objectstack#35685)', () => {
318+
/** A table whose host asks about every commit into `Stage`, each answer settled by hand. */
319+
function renderConfirming(onRowSave: Save) {
320+
const asks: Array<{ row: any; columnKey: string; value: unknown; answer: (yes: boolean) => void }> = [];
321+
const confirmCommit = vi.fn((row: any, columnKey: string, value: unknown) => {
322+
if (columnKey !== 'stage') return null;
323+
return new Promise<boolean>((resolve) => { asks.push({ row, columnKey, value, answer: resolve }); });
324+
});
325+
const DataTable = ComponentRegistry.get('data-table')!;
326+
const utils = render(
327+
<GridCellSelectionProvider value={{ confirmCommit }}>
328+
<DataTable schema={schemaOf(onRowSave)} />
329+
</GridCellSelectionProvider>,
330+
);
331+
const cell = (row: number, col: number) =>
332+
utils.container.querySelectorAll('tbody tr')[row].querySelectorAll('td[data-grid-cell]')[col] as HTMLElement;
333+
const editor = () => utils.container.querySelector<HTMLInputElement>('td[data-editing-cell] input');
334+
const catcher = () => utils.container.querySelector<HTMLInputElement>('[data-slot="cell-type-catcher"]');
335+
const typeAndEnter = (row: number, col: number, value: string) => {
336+
fireEvent.click(cell(row, col));
337+
fireEvent.change(catcher()!, { target: { value: value.slice(0, 1) } });
338+
fireEvent.change(editor()!, { target: { value } });
339+
fireEvent.keyDown(editor()!, { key: 'Enter' });
340+
};
341+
return { ...utils, cell, editor, catcher, typeAndEnter, asks, confirmCommit };
342+
}
343+
344+
it('No writes nothing: the editor closes, nothing is staged or sent, the cell shows what it had', async () => {
345+
const { onRowSave } = deferredSave();
346+
const t = renderConfirming(onRowSave);
347+
t.typeAndEnter(0, 1, 'won');
348+
await act(async () => {});
349+
expect(t.confirmCommit).toHaveBeenCalledTimes(1);
350+
expect(t.asks[0].row).toBe(ROWS[0]);
351+
expect(t.asks[0].value).toBe('won');
352+
// While the host asks: the editor is closed, the cell shows the stored
353+
// value with no save state, and nothing went out.
354+
expect(t.editor()).toBeNull();
355+
expect(t.cell(0, 1).textContent).toContain('open');
356+
expect(t.cell(0, 1).querySelector('[data-slot="cell-save-state"]')).toBeNull();
357+
expect(onRowSave).not.toHaveBeenCalled();
358+
await act(async () => { t.asks[0].answer(false); });
359+
expect(onRowSave).not.toHaveBeenCalled();
360+
expect(t.cell(0, 1).textContent).toContain('open');
361+
expect(t.cell(0, 1).textContent).not.toContain('won');
362+
// Focus is back on the selected cell, so the keys carry on.
363+
expect(document.activeElement).toBe(t.catcher());
364+
});
365+
366+
it('Yes writes the value as any commit is written: one update of that cell', async () => {
367+
const { onRowSave } = deferredSave();
368+
const t = renderConfirming(onRowSave);
369+
t.typeAndEnter(0, 1, 'won');
370+
await act(async () => {});
371+
expect(onRowSave).not.toHaveBeenCalled();
372+
await act(async () => { t.asks[0].answer(true); });
373+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1));
374+
expect(onRowSave.mock.calls[0][1]).toEqual({ stage: 'won' });
375+
expect(t.cell(0, 1).querySelector('[data-slot="cell-save-state"]')).toHaveAttribute('data-state', 'saving');
376+
});
377+
378+
it('a paste is asked about as an editor commit is', async () => {
379+
const { onRowSave } = deferredSave();
380+
const t = renderConfirming(onRowSave);
381+
fireEvent.click(t.cell(0, 1));
382+
fireEvent.paste(t.catcher()!, { clipboardData: { getData: () => 'won' } });
383+
await act(async () => {});
384+
expect(t.confirmCommit).toHaveBeenCalledTimes(1);
385+
expect(onRowSave).not.toHaveBeenCalled();
386+
await act(async () => { t.asks[0].answer(false); });
387+
expect(onRowSave).not.toHaveBeenCalled();
388+
expect(t.cell(0, 1).textContent).toContain('open');
389+
});
390+
391+
it('a commit that changes nothing, and a cell the host does not ask about, are not held', async () => {
392+
const { onRowSave } = deferredSave();
393+
const t = renderConfirming(onRowSave);
394+
// The stored value again: nothing to ask, nothing to send.
395+
t.typeAndEnter(0, 1, 'open');
396+
await act(async () => {});
397+
expect(t.confirmCommit).not.toHaveBeenCalled();
398+
expect(onRowSave).not.toHaveBeenCalled();
399+
// Another column: the host answers no question, and it saves at once.
400+
t.typeAndEnter(0, 0, 'Alpha 2');
401+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1));
402+
expect(t.confirmCommit).toHaveBeenCalledTimes(1);
403+
expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Alpha 2' });
404+
});
405+
});

‎ui/packages/components/src/context/gridCellSelection.tsx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,18 @@ export interface GridCellSelection {
5555
describeCell?: (row: any, columnKey: string) => GridCellFacts | null | undefined;
5656
/** Called when a cell becomes the selected one (a host may prefetch what an edit will need). */
5757
onCellSelect?: (row: any, columnKey: string) => void;
58+
/**
59+
* Asked when a value is committed into a cell (an editor's commit, a toggle
60+
* or a paste) that changes what the cell shows, before anything is staged
61+
* or saved. A promise holds the write until it settles: `true` writes the
62+
* value as any commit is written, `false` (or a rejection) writes nothing
63+
* and the cell keeps what it showed. `null` / `undefined` ⇒ no question;
64+
* the value is written at once. Only a table that saves each cell as it is
65+
* committed (one wired with `onRowSave`) asks; a table on `onBatchSave`
66+
* alone never does. A host asks, for example, before a move of a
67+
* state-machine field (objectstack#35685).
68+
*/
69+
confirmCommit?: (row: any, columnKey: string, value: unknown) => Promise<boolean> | null | undefined;
5870
}
5971

6072
const GridCellSelectionContext = React.createContext<GridCellSelection | null>(null);

‎ui/packages/components/src/renderers/complex/data-table.tsx‎

Lines changed: 82 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2049,6 +2049,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
20492049
const autosaveDueRef = useRef<Set<PendingRowKey>>(new Set());
20502050
const [autosaveTick, setAutosaveTick] = useState(0);
20512051
const savedTimersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());
2052+
// A commit the host confirmed is written by the newest `commitCellValue`,
2053+
// and its answer re-renders so focus goes back to the selected cell.
2054+
const commitCellValueRef = useRef<(row: any, columnKey: string, value: unknown, confirmed?: boolean) => void>(() => {});
2055+
const [, bumpConfirmSettled] = React.useReducer((n: number) => n + 1, 0);
20522056
useEffect(() => () => {
20532057
for (const timer of savedTimersRef.current) clearTimeout(timer);
20542058
savedTimersRef.current.clear();
@@ -2817,6 +2821,20 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
28172821
// (objectui#12664) has not reached state yet either.
28182822
const valueToStage = explicitValue !== undefined ? explicitValue : editValueRef.current;
28192823

2824+
// objectstack#35685 — a value the host asks to confirm first: the editor
2825+
// closes with nothing of this session staged, and the value is written
2826+
// only once the host says yes (a no leaves the cell as it was).
2827+
const asked = commitConfirmationOf(rowKey, row, columnKey, valueToStage);
2828+
if (asked) {
2829+
revertEditSession(editingCell, editRevertRef.current);
2830+
editRevertRef.current = null;
2831+
editingCellRef.current = null;
2832+
setEditingCell(null);
2833+
setEditValue('');
2834+
settleCommitConfirmation(asked, row, columnKey, valueToStage);
2835+
return;
2836+
}
2837+
28202838
// Update pending changes — or drop this cell's entry when the committed
28212839
// value is the one the row loaded with (objectui#11816). An updater, so a
28222840
// save that settled since this render is not undone (objectui#12322).
@@ -2844,6 +2862,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
28442862
const saveEditRef = useRef(saveEdit);
28452863
useEffect(() => {
28462864
saveEditRef.current = saveEdit;
2865+
commitCellValueRef.current = commitCellValue;
28472866
});
28482867

28492868
// The injected-editor commit contract (objectui#12664): before the table
@@ -2874,6 +2893,60 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
28742893
// is what makes Escape/cancel discard an injected widget's staged changes. For
28752894
// built-in editors (which don't stage until commit) the snapshot equals the
28762895
// live pending value, so the revert is a no-op.
2896+
/** Roll the edit session's cell back to its snapshot (see `editRevertRef`). */
2897+
const revertEditSession = (active: EditingCell, snap: { had: boolean; value: any } | null) => {
2898+
if (!snap) return;
2899+
const { rowKey, columnKey } = active;
2900+
setPendingChanges((prev) => {
2901+
const cur = prev.get(rowKey);
2902+
const staged = !!cur && columnKey in cur.changes;
2903+
if (!staged && !snap.had) return prev; // nothing changed for this cell
2904+
const next = new Map(prev);
2905+
const rc = { ...(cur?.changes || {}) };
2906+
if (snap.had) rc[columnKey] = snap.value;
2907+
else delete rc[columnKey];
2908+
if (Object.keys(rc).length > 0) next.set(rowKey, { row: cur?.row ?? active.row, changes: rc });
2909+
else next.delete(rowKey);
2910+
return next;
2911+
});
2912+
};
2913+
2914+
/**
2915+
* objectstack#35685 — the host's confirmation of a value committed into a
2916+
* select-first cell (`GridCellSelection.confirmCommit`), or `null` when it
2917+
* asks none. Only a value that changes what the cell shows is asked about.
2918+
*/
2919+
const commitConfirmationOf = (
2920+
rowKey: PendingRowKey,
2921+
row: any,
2922+
columnKey: string,
2923+
value: unknown,
2924+
): Promise<boolean> | null => {
2925+
if (!autosaves || typeof cellSelection?.confirmCommit !== 'function') return null;
2926+
const staged = pendingChanges.get(rowKey)?.changes;
2927+
const shown = staged && columnKey in staged ? staged[columnKey] : row?.[columnKey];
2928+
if (isUnchangedCellValue(value, shown)) return null;
2929+
return cellSelection.confirmCommit(row, columnKey, value) ?? null;
2930+
};
2931+
2932+
/**
2933+
* Write a confirmed value once the host's answer comes, and hand focus back
2934+
* to the selected cell either way (the host's dialog had it meanwhile).
2935+
*/
2936+
const settleCommitConfirmation = (asked: Promise<boolean>, row: any, columnKey: string, value: unknown) => {
2937+
void asked.then(
2938+
(confirmed) => {
2939+
if (confirmed) commitCellValueRef.current(row, columnKey, value, true);
2940+
focusSelectionRef.current = true;
2941+
bumpConfirmSettled();
2942+
},
2943+
() => {
2944+
focusSelectionRef.current = true;
2945+
bumpConfirmSettled();
2946+
},
2947+
);
2948+
};
2949+
28772950
const exitEdit = (revert: boolean) => {
28782951
const active = editingCellRef.current;
28792952
const snap = editRevertRef.current;
@@ -2884,20 +2957,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
28842957
// wire it only takes back this edit (below), as Esc on the selected cell
28852958
// leaves a sent value alone.
28862959
discardCellChange(active.rowKey, active.columnKey);
2887-
} else if (revert && active && snap) {
2888-
const { rowKey, columnKey } = active;
2889-
setPendingChanges((prev) => {
2890-
const cur = prev.get(rowKey);
2891-
const staged = !!cur && columnKey in cur.changes;
2892-
if (!staged && !snap.had) return prev; // nothing changed for this cell
2893-
const next = new Map(prev);
2894-
const rc = { ...(cur?.changes || {}) };
2895-
if (snap.had) rc[columnKey] = snap.value;
2896-
else delete rc[columnKey];
2897-
if (Object.keys(rc).length > 0) next.set(rowKey, { row: cur?.row ?? active.row, changes: rc });
2898-
else next.delete(rowKey);
2899-
return next;
2900-
});
2960+
} else if (revert && active) {
2961+
revertEditSession(active, snap);
29012962
}
29022963
editingCellRef.current = null;
29032964
setEditingCell(null);
@@ -3533,9 +3594,15 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
35333594
};
35343595

35353596
/** Write a value into a cell without an editor: the commit `saveEdit` makes. */
3536-
const commitCellValue = (row: any, columnKey: string, value: unknown) => {
3597+
const commitCellValue = (row: any, columnKey: string, value: unknown, confirmed = false) => {
35373598
const rowKey = pendingRowKeyOf(row);
35383599
const held = heldRowOf(rowKey) ?? row;
3600+
// objectstack#35685 — a toggle or a paste is asked about as an editor's commit is.
3601+
const asked = confirmed ? null : commitConfirmationOf(rowKey, held, columnKey, value);
3602+
if (asked) {
3603+
settleCommitConfirmation(asked, held, columnKey, value);
3604+
return;
3605+
}
35393606
const inFlight = inFlightRef.current.get(rowKey);
35403607
setPendingChanges((prev) => stageCellChange(prev, rowKey, held, columnKey, value, inFlight));
35413608
clearCellError(rowKey, columnKey);

‎ui/packages/i18n/src/locales/ar.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,12 @@ const ar = {
561561
approvalLocked: "هذا السجل مقفل أثناء الموافقة عليه.",
562562
noRecordPermission: "ليس لديك إذن بتحرير هذا السجل.",
563563
},
564+
stateChange: {
565+
title: "تغيير {{field}}؟",
566+
description: "يتغير {{field}} من {{from}} إلى {{to}}. قد يؤدي الحفظ إلى تشغيل عمليات أتمتة ذات صلة.",
567+
confirm: "تغيير",
568+
cancel: "إلغاء",
569+
},
564570
bulkSelected: "تم تحديد {{count}}",
565571
bulkSelected_zero: "تم تحديد {{count}}",
566572
bulkSelected_one: "تم تحديد {{count}}",
@@ -1646,6 +1652,7 @@ const ar = {
16461652
pathStageChangeConflict: 'قام شخص آخر بتغيير هذا السجل، ويتم الآن عرض أحدث إصدار. اضغط على المرحلة مرة أخرى إذا كان النقل لا يزال مطلوبًا.',
16471653
pathStageChangeDenied: 'ليس لديك إذن لتغيير مرحلة هذا السجل.',
16481654
pathStageChangeFailed: 'تعذر تغيير المرحلة.',
1655+
inlineEditRecordChanged: "تم تغيير هذا السجل في مكان آخر أثناء التحرير. يتم الاحتفاظ بتغييراتك غير المحفوظة، ويكتبها الحفظ فوق أحدث إصدار.",
16491656
stageMenuTrigger: 'المرحلة: {{stage}}. تغيير المرحلة',
16501657
stageMenuCurrent: 'المرحلة الحالية',
16511658
stageMenuNotReachable: 'لا يمكن الانتقال إلى هنا من {{stage}}',

‎ui/packages/i18n/src/locales/de.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,12 @@ const de = {
531531
approvalLocked: "Dieser Datensatz ist während der Genehmigung gesperrt.",
532532
noRecordPermission: "Sie haben keine Berechtigung, diesen Datensatz zu bearbeiten.",
533533
},
534+
stateChange: {
535+
title: "{{field}} ändern?",
536+
description: "{{field}} wechselt von {{from}} zu {{to}}. Beim Speichern können zugehörige Automatisierungen ausgelöst werden.",
537+
confirm: "Ändern",
538+
cancel: "Abbrechen",
539+
},
534540
bulkSelected: "{{count}} ausgewählt",
535541
bulkSelected_one: "{{count}} ausgewählt",
536542
bulkSelected_other: "{{count}} ausgewählt",
@@ -1472,6 +1478,7 @@ const de = {
14721478
pathStageChangeConflict: 'Jemand anderes hat diesen Datensatz geändert; die aktuelle Version wird jetzt angezeigt. Klicken Sie erneut auf die Phase, wenn die Verschiebung weiterhin gilt.',
14731479
pathStageChangeDenied: 'Sie sind nicht berechtigt, die Phase dieses Datensatzes zu ändern.',
14741480
pathStageChangeFailed: 'Die Phase konnte nicht geändert werden.',
1481+
inlineEditRecordChanged: "Dieser Datensatz wurde während Ihrer Bearbeitung an anderer Stelle geändert. Ihre ungespeicherten Änderungen bleiben erhalten, und Speichern schreibt sie über die neueste Version.",
14751482
stageMenuTrigger: 'Phase: {{stage}}. Phase ändern',
14761483
stageMenuCurrent: 'aktuelle Phase',
14771484
stageMenuNotReachable: 'Von {{stage}} nicht hierher verschiebbar',

0 commit comments

Comments
 (0)