Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/35685-list-state-confirm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@object-ui/components': patch
'@object-ui/plugin-grid': patch
'@object-ui/plugin-detail': patch
'@object-ui/i18n': patch
---

feat(list): confirm a state-machine move before a list cell saves it; the drawer's save bar says when the record changed elsewhere

Clause-②: yes (widening) — `GridCellSelection` in `@object-ui/components` takes an optional `confirmCommit(row, columnKey, value)` member; nothing removed or renamed
Metadata-protocol: none

In a grid that mounts `GridCellSelection` (the select-first grid every `ListView` draws):

- **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.
- **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.

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

### Footer calculations

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
* 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.
* 8. A commit the host asks to confirm (`confirmCommit`, slice S3) is held
* with nothing staged: No leaves the cell as it was, Yes writes it; a
* paste is asked too, an unchanged value is not.
*/
import React from 'react';
import { describe, it, expect, afterEach, vi } from 'vitest';
Expand Down Expand Up @@ -310,3 +313,93 @@ describe('data-table autosave — Esc in the editor while the row is saving', ()
expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Alpha 2' });
});
});

describe('data-table autosave — a commit the host asks to confirm first (objectstack#35685)', () => {
/** A table whose host asks about every commit into `Stage`, each answer settled by hand. */
function renderConfirming(onRowSave: Save) {
const asks: Array<{ row: any; columnKey: string; value: unknown; answer: (yes: boolean) => void }> = [];
const confirmCommit = vi.fn((row: any, columnKey: string, value: unknown) => {
if (columnKey !== 'stage') return null;
return new Promise<boolean>((resolve) => { asks.push({ row, columnKey, value, answer: resolve }); });
});
const DataTable = ComponentRegistry.get('data-table')!;
const utils = render(
<GridCellSelectionProvider value={{ confirmCommit }}>
<DataTable schema={schemaOf(onRowSave)} />
</GridCellSelectionProvider>,
);
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<HTMLInputElement>('td[data-editing-cell] input');
const catcher = () => utils.container.querySelector<HTMLInputElement>('[data-slot="cell-type-catcher"]');
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' });
};
return { ...utils, cell, editor, catcher, typeAndEnter, asks, confirmCommit };
}

it('No writes nothing: the editor closes, nothing is staged or sent, the cell shows what it had', async () => {
const { onRowSave } = deferredSave();
const t = renderConfirming(onRowSave);
t.typeAndEnter(0, 1, 'won');
await act(async () => {});
expect(t.confirmCommit).toHaveBeenCalledTimes(1);
expect(t.asks[0].row).toBe(ROWS[0]);
expect(t.asks[0].value).toBe('won');
// While the host asks: the editor is closed, the cell shows the stored
// value with no save state, and nothing went out.
expect(t.editor()).toBeNull();
expect(t.cell(0, 1).textContent).toContain('open');
expect(t.cell(0, 1).querySelector('[data-slot="cell-save-state"]')).toBeNull();
expect(onRowSave).not.toHaveBeenCalled();
await act(async () => { t.asks[0].answer(false); });
expect(onRowSave).not.toHaveBeenCalled();
expect(t.cell(0, 1).textContent).toContain('open');
expect(t.cell(0, 1).textContent).not.toContain('won');
// Focus is back on the selected cell, so the keys carry on.
expect(document.activeElement).toBe(t.catcher());
});

it('Yes writes the value as any commit is written: one update of that cell', async () => {
const { onRowSave } = deferredSave();
const t = renderConfirming(onRowSave);
t.typeAndEnter(0, 1, 'won');
await act(async () => {});
expect(onRowSave).not.toHaveBeenCalled();
await act(async () => { t.asks[0].answer(true); });
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1));
expect(onRowSave.mock.calls[0][1]).toEqual({ stage: 'won' });
expect(t.cell(0, 1).querySelector('[data-slot="cell-save-state"]')).toHaveAttribute('data-state', 'saving');
});

it('a paste is asked about as an editor commit is', async () => {
const { onRowSave } = deferredSave();
const t = renderConfirming(onRowSave);
fireEvent.click(t.cell(0, 1));
fireEvent.paste(t.catcher()!, { clipboardData: { getData: () => 'won' } });
await act(async () => {});
expect(t.confirmCommit).toHaveBeenCalledTimes(1);
expect(onRowSave).not.toHaveBeenCalled();
await act(async () => { t.asks[0].answer(false); });
expect(onRowSave).not.toHaveBeenCalled();
expect(t.cell(0, 1).textContent).toContain('open');
});

it('a commit that changes nothing, and a cell the host does not ask about, are not held', async () => {
const { onRowSave } = deferredSave();
const t = renderConfirming(onRowSave);
// The stored value again: nothing to ask, nothing to send.
t.typeAndEnter(0, 1, 'open');
await act(async () => {});
expect(t.confirmCommit).not.toHaveBeenCalled();
expect(onRowSave).not.toHaveBeenCalled();
// Another column: the host answers no question, and it saves at once.
t.typeAndEnter(0, 0, 'Alpha 2');
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1));
expect(t.confirmCommit).toHaveBeenCalledTimes(1);
expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Alpha 2' });
});
});
12 changes: 12 additions & 0 deletions ui/packages/components/src/context/gridCellSelection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ export interface GridCellSelection {
describeCell?: (row: any, columnKey: string) => GridCellFacts | null | undefined;
/** Called when a cell becomes the selected one (a host may prefetch what an edit will need). */
onCellSelect?: (row: any, columnKey: string) => void;
/**
* Asked when a value is committed into a cell (an editor's commit, a toggle
* or a paste) that changes what the cell shows, before anything is staged
* or saved. A promise holds the write until it settles: `true` writes the
* value as any commit is written, `false` (or a rejection) writes nothing
* and the cell keeps what it showed. `null` / `undefined` ⇒ no question;
* the value is written at once. Only a table that saves each cell as it is
* committed (one wired with `onRowSave`) asks; a table on `onBatchSave`
* alone never does. A host asks, for example, before a move of a
* state-machine field (objectstack#35685).
*/
confirmCommit?: (row: any, columnKey: string, value: unknown) => Promise<boolean> | null | undefined;
}

const GridCellSelectionContext = React.createContext<GridCellSelection | null>(null);
Expand Down
97 changes: 82 additions & 15 deletions ui/packages/components/src/renderers/complex/data-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2049,6 +2049,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
const autosaveDueRef = useRef<Set<PendingRowKey>>(new Set());
const [autosaveTick, setAutosaveTick] = useState(0);
const savedTimersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());
// A commit the host confirmed is written by the newest `commitCellValue`,
// and its answer re-renders so focus goes back to the selected cell.
const commitCellValueRef = useRef<(row: any, columnKey: string, value: unknown, confirmed?: boolean) => void>(() => {});
const [, bumpConfirmSettled] = React.useReducer((n: number) => n + 1, 0);
useEffect(() => () => {
for (const timer of savedTimersRef.current) clearTimeout(timer);
savedTimersRef.current.clear();
Expand Down Expand Up @@ -2817,6 +2821,20 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
// (objectui#12664) has not reached state yet either.
const valueToStage = explicitValue !== undefined ? explicitValue : editValueRef.current;

// objectstack#35685 — a value the host asks to confirm first: the editor
// closes with nothing of this session staged, and the value is written
// only once the host says yes (a no leaves the cell as it was).
const asked = commitConfirmationOf(rowKey, row, columnKey, valueToStage);
if (asked) {
revertEditSession(editingCell, editRevertRef.current);
editRevertRef.current = null;
editingCellRef.current = null;
setEditingCell(null);
setEditValue('');
settleCommitConfirmation(asked, row, columnKey, valueToStage);
return;
}

// Update pending changes — or drop this cell's entry when the committed
// value is the one the row loaded with (objectui#11816). An updater, so a
// save that settled since this render is not undone (objectui#12322).
Expand Down Expand Up @@ -2844,6 +2862,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
const saveEditRef = useRef(saveEdit);
useEffect(() => {
saveEditRef.current = saveEdit;
commitCellValueRef.current = commitCellValue;
});

// The injected-editor commit contract (objectui#12664): before the table
Expand Down Expand Up @@ -2874,6 +2893,60 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
// is what makes Escape/cancel discard an injected widget's staged changes. For
// built-in editors (which don't stage until commit) the snapshot equals the
// live pending value, so the revert is a no-op.
/** Roll the edit session's cell back to its snapshot (see `editRevertRef`). */
const revertEditSession = (active: EditingCell, snap: { had: boolean; value: any } | null) => {
if (!snap) return;
const { rowKey, columnKey } = active;
setPendingChanges((prev) => {
const cur = prev.get(rowKey);
const staged = !!cur && columnKey in cur.changes;
if (!staged && !snap.had) return prev; // nothing changed for this cell
const next = new Map(prev);
const rc = { ...(cur?.changes || {}) };
if (snap.had) rc[columnKey] = snap.value;
else delete rc[columnKey];
if (Object.keys(rc).length > 0) next.set(rowKey, { row: cur?.row ?? active.row, changes: rc });
else next.delete(rowKey);
return next;
});
};

/**
* objectstack#35685 — the host's confirmation of a value committed into a
* select-first cell (`GridCellSelection.confirmCommit`), or `null` when it
* asks none. Only a value that changes what the cell shows is asked about.
*/
const commitConfirmationOf = (
rowKey: PendingRowKey,
row: any,
columnKey: string,
value: unknown,
): Promise<boolean> | null => {
if (!autosaves || typeof cellSelection?.confirmCommit !== 'function') return null;
const staged = pendingChanges.get(rowKey)?.changes;
const shown = staged && columnKey in staged ? staged[columnKey] : row?.[columnKey];
if (isUnchangedCellValue(value, shown)) return null;
return cellSelection.confirmCommit(row, columnKey, value) ?? null;
};

/**
* Write a confirmed value once the host's answer comes, and hand focus back
* to the selected cell either way (the host's dialog had it meanwhile).
*/
const settleCommitConfirmation = (asked: Promise<boolean>, row: any, columnKey: string, value: unknown) => {
void asked.then(
(confirmed) => {
if (confirmed) commitCellValueRef.current(row, columnKey, value, true);
focusSelectionRef.current = true;
bumpConfirmSettled();
},
() => {
focusSelectionRef.current = true;
bumpConfirmSettled();
},
);
};

const exitEdit = (revert: boolean) => {
const active = editingCellRef.current;
const snap = editRevertRef.current;
Expand All @@ -2884,20 +2957,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
// 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);
const staged = !!cur && columnKey in cur.changes;
if (!staged && !snap.had) return prev; // nothing changed for this cell
const next = new Map(prev);
const rc = { ...(cur?.changes || {}) };
if (snap.had) rc[columnKey] = snap.value;
else delete rc[columnKey];
if (Object.keys(rc).length > 0) next.set(rowKey, { row: cur?.row ?? active.row, changes: rc });
else next.delete(rowKey);
return next;
});
} else if (revert && active) {
revertEditSession(active, snap);
}
editingCellRef.current = null;
setEditingCell(null);
Expand Down Expand Up @@ -3533,9 +3594,15 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
};

/** Write a value into a cell without an editor: the commit `saveEdit` makes. */
const commitCellValue = (row: any, columnKey: string, value: unknown) => {
const commitCellValue = (row: any, columnKey: string, value: unknown, confirmed = false) => {
const rowKey = pendingRowKeyOf(row);
const held = heldRowOf(rowKey) ?? row;
// objectstack#35685 — a toggle or a paste is asked about as an editor's commit is.
const asked = confirmed ? null : commitConfirmationOf(rowKey, held, columnKey, value);
if (asked) {
settleCommitConfirmation(asked, held, columnKey, value);
return;
}
const inFlight = inFlightRef.current.get(rowKey);
setPendingChanges((prev) => stageCellChange(prev, rowKey, held, columnKey, value, inFlight));
clearCellError(rowKey, columnKey);
Expand Down
7 changes: 7 additions & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,12 @@ const ar = {
approvalLocked: "هذا السجل مقفل أثناء الموافقة عليه.",
noRecordPermission: "ليس لديك إذن بتحرير هذا السجل.",
},
stateChange: {
title: "تغيير {{field}}؟",
description: "يتغير {{field}} من {{from}} إلى {{to}}. قد يؤدي الحفظ إلى تشغيل عمليات أتمتة ذات صلة.",
confirm: "تغيير",
cancel: "إلغاء",
},
bulkSelected: "تم تحديد {{count}}",
bulkSelected_zero: "تم تحديد {{count}}",
bulkSelected_one: "تم تحديد {{count}}",
Expand Down Expand Up @@ -1646,6 +1652,7 @@ const ar = {
pathStageChangeConflict: 'قام شخص آخر بتغيير هذا السجل، ويتم الآن عرض أحدث إصدار. اضغط على المرحلة مرة أخرى إذا كان النقل لا يزال مطلوبًا.',
pathStageChangeDenied: 'ليس لديك إذن لتغيير مرحلة هذا السجل.',
pathStageChangeFailed: 'تعذر تغيير المرحلة.',
inlineEditRecordChanged: "تم تغيير هذا السجل في مكان آخر أثناء التحرير. يتم الاحتفاظ بتغييراتك غير المحفوظة، ويكتبها الحفظ فوق أحدث إصدار.",
stageMenuTrigger: 'المرحلة: {{stage}}. تغيير المرحلة',
stageMenuCurrent: 'المرحلة الحالية',
stageMenuNotReachable: 'لا يمكن الانتقال إلى هنا من {{stage}}',
Expand Down
7 changes: 7 additions & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,12 @@ const de = {
approvalLocked: "Dieser Datensatz ist während der Genehmigung gesperrt.",
noRecordPermission: "Sie haben keine Berechtigung, diesen Datensatz zu bearbeiten.",
},
stateChange: {
title: "{{field}} ändern?",
description: "{{field}} wechselt von {{from}} zu {{to}}. Beim Speichern können zugehörige Automatisierungen ausgelöst werden.",
confirm: "Ändern",
cancel: "Abbrechen",
},
bulkSelected: "{{count}} ausgewählt",
bulkSelected_one: "{{count}} ausgewählt",
bulkSelected_other: "{{count}} ausgewählt",
Expand Down Expand Up @@ -1472,6 +1478,7 @@ const de = {
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.',
pathStageChangeDenied: 'Sie sind nicht berechtigt, die Phase dieses Datensatzes zu ändern.',
pathStageChangeFailed: 'Die Phase konnte nicht geändert werden.',
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.",
stageMenuTrigger: 'Phase: {{stage}}. Phase ändern',
stageMenuCurrent: 'aktuelle Phase',
stageMenuNotReachable: 'Von {{stage}} nicht hierher verschiebbar',
Expand Down
Loading
Loading