From 12cfc3b82672086ac07cd38ee8ca2b0f1e3517fa Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:24:39 +0000 Subject: [PATCH 1/5] wip(list): confirm a state-machine move before a list cell saves it Claude-Session: https://claude.ai/code/session_01L6bhgVhAK4uNYvjNY3H7XU Co-authored-by: Claude --- .../src/context/gridCellSelection.tsx | 10 ++ .../src/renderers/complex/data-table.tsx | 97 ++++++++++++++++--- ui/packages/i18n/src/locales/ar.ts | 6 ++ ui/packages/i18n/src/locales/de.ts | 6 ++ ui/packages/i18n/src/locales/en.ts | 7 ++ ui/packages/i18n/src/locales/es.ts | 6 ++ ui/packages/i18n/src/locales/fr.ts | 6 ++ ui/packages/i18n/src/locales/ja.ts | 6 ++ ui/packages/i18n/src/locales/ko.ts | 6 ++ ui/packages/i18n/src/locales/pt-BR.ts | 6 ++ ui/packages/i18n/src/locales/ru.ts | 6 ++ ui/packages/i18n/src/locales/zh-Hans.ts | 6 ++ ui/packages/i18n/src/locales/zh-Hant.ts | 6 ++ ui/packages/plugin-grid/src/ObjectGrid.tsx | 76 +++++++++++++++ .../plugin-grid/src/objectGridStateConfirm.ts | 68 +++++++++++++ .../plugin-grid/src/objectGridTranslations.ts | 6 ++ 16 files changed, 309 insertions(+), 15 deletions(-) create mode 100644 ui/packages/plugin-grid/src/objectGridStateConfirm.ts diff --git a/ui/packages/components/src/context/gridCellSelection.tsx b/ui/packages/components/src/context/gridCellSelection.tsx index 3348d0e9a96..dd108d78223 100644 --- a/ui/packages/components/src/context/gridCellSelection.tsx +++ b/ui/packages/components/src/context/gridCellSelection.tsx @@ -55,6 +55,16 @@ 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. A host asks, for example, before a move of + * a state-machine field (objectstack#35685). + */ + confirmCommit?: (row: any, columnKey: string, value: unknown) => Promise | null | undefined; } const GridCellSelectionContext = React.createContext(null); diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index a70ec14d359..9515e1ab3b4 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -2045,6 +2045,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const autosaveDueRef = useRef>(new Set()); const [autosaveTick, setAutosaveTick] = useState(0); const savedTimersRef = useRef>>(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(); @@ -2773,6 +2777,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). @@ -2800,6 +2818,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 @@ -2830,6 +2849,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 | 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, 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; @@ -2840,20 +2913,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); @@ -3489,9 +3550,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); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 14b652d847d..f1b88a5267a 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -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}}", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 58e70f7edbe..fbb398ffcb0 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -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", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index dff9e7910d5..7485d156d74 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -794,6 +794,13 @@ const en = { approvalLocked: 'This record is locked while it\'s in approval.', noRecordPermission: 'You don\'t have permission to edit this record.', }, + // objectstack#35685 — the confirm before a list cell moves a state-machine field. + stateChange: { + title: 'Change {{field}}?', + description: '{{field}} changes from {{from}} to {{to}}. Saving may trigger related automation.', + confirm: 'Change', + cancel: 'Cancel', + }, actions: 'Actions', edit: 'Edit', delete: 'Delete', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index e0c7e224bfd..67363a15c27 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -542,6 +542,12 @@ const es = { approvalLocked: "Este registro está bloqueado mientras está en aprobación.", noRecordPermission: "No tiene permiso para editar este registro.", }, + stateChange: { + title: "¿Cambiar {{field}}?", + description: "{{field}} cambia de {{from}} a {{to}}. Al guardar se pueden activar automatizaciones relacionadas.", + confirm: "Cambiar", + cancel: "Cancelar", + }, bulkSelected: "{{count}} seleccionados", bulkSelected_one: "{{count}} seleccionado", bulkSelected_many: "{{count}} seleccionados", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 82acd914de1..fd4b5f0b95b 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -537,6 +537,12 @@ const fr = { approvalLocked: "Cet enregistrement est verrouillé pendant son approbation.", noRecordPermission: "Vous n'avez pas l'autorisation de modifier cet enregistrement.", }, + stateChange: { + title: "Modifier {{field}} ?", + description: "{{field}} passe de {{from}} à {{to}}. L'enregistrement peut déclencher des automatisations associées.", + confirm: "Modifier", + cancel: "Annuler", + }, bulkSelected: "{{count}} sélectionné(s)", bulkSelected_one: "{{count}} sélectionné", bulkSelected_many: "{{count}} sélectionnés", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 6991ebb6490..d09bd48c9a1 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -531,6 +531,12 @@ const ja = { approvalLocked: "このレコードは承認中のためロックされています。", noRecordPermission: "このレコードを編集する権限がありません。", }, + stateChange: { + title: "{{field}}を変更しますか?", + description: "{{field}}を {{from}} から {{to}} に変更します。保存すると関連する自動化が実行される場合があります。", + confirm: "変更", + cancel: "キャンセル", + }, bulkSelected: "{{count}} 件を選択中", bulkSelected_one: "{{count}} 件を選択中", bulkSelected_other: "{{count}} 件を選択中", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 13f7a980535..dce34bdd8cd 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -531,6 +531,12 @@ const ko = { approvalLocked: "이 레코드는 승인 중이라 잠겨 있습니다.", noRecordPermission: "이 레코드를 편집할 권한이 없습니다.", }, + stateChange: { + title: "{{field}}을(를) 변경할까요?", + description: "{{field}}이(가) {{from}}에서 {{to}}(으)로 변경됩니다. 저장하면 관련 자동화가 실행될 수 있습니다.", + confirm: "변경", + cancel: "취소", + }, bulkSelected: "{{count}}건 선택됨", bulkSelected_one: "{{count}}건 선택됨", bulkSelected_other: "{{count}}건 선택됨", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 171f9615455..79686dd24df 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -537,6 +537,12 @@ const pt = { approvalLocked: "Este registro está bloqueado enquanto está em aprovação.", noRecordPermission: "Você não tem permissão para editar este registro.", }, + stateChange: { + title: "Alterar {{field}}?", + description: "{{field}} muda de {{from}} para {{to}}. Salvar pode acionar automações relacionadas.", + confirm: "Alterar", + cancel: "Cancelar", + }, bulkSelected: "{{count}} selecionados", bulkSelected_one: "{{count}} selecionado", bulkSelected_many: "{{count}} selecionados", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 0629e208996..6e20db66f59 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -546,6 +546,12 @@ const ru = { approvalLocked: "Эта запись заблокирована, пока находится на согласовании.", noRecordPermission: "У вас нет прав на изменение этой записи.", }, + stateChange: { + title: "Изменить {{field}}?", + description: "{{field}}: {{from}} → {{to}}. При сохранении могут запуститься связанные автоматизации.", + confirm: "Изменить", + cancel: "Отмена", + }, bulkSelected: "Выбрано: {{count}}", bulkSelected_one: "Выбрано: {{count}}", bulkSelected_few: "Выбрано: {{count}}", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 3812641e6a2..b07759e0433 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -544,6 +544,12 @@ const zh = { approvalLocked: '此记录正在审批中,已锁定。', noRecordPermission: '您没有编辑此记录的权限。', }, + stateChange: { + title: '更改{{field}}?', + description: '{{field}}从 {{from}} 改为 {{to}},保存后可能触发相关自动化。', + confirm: '确认更改', + cancel: '取消', + }, actions: '操作', edit: '编辑', delete: '删除', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 3ff3be4e69d..0ac82c60b63 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -544,6 +544,12 @@ const zhHant = { approvalLocked: '此記錄正在審批中,已鎖定。', noRecordPermission: '您沒有編輯此記錄的權限。', }, + stateChange: { + title: '變更{{field}}?', + description: '{{field}}從 {{from}} 改為 {{to}},儲存後可能觸發相關自動化。', + confirm: '確認變更', + cancel: '取消', + }, actions: '操作', edit: '編輯', delete: '刪除', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 782fcd9b3c4..97500a4bffb 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -47,6 +47,7 @@ import { useLocalization, useDisplayLocale } from '@object-ui/i18n'; // to reach them as an object and the compiler could not say so. import { resolveI18nLabel as resolveInlineI18nLabel } from '@objectstack/spec/ui'; import { stateMachineNextValues } from './inline-edit-options'; +import { isStateMachineField, stateLabelOf, type StateChangeConfirm } from './objectGridStateConfirm'; import { cellReadOnlyKind, readOnlyReasonText, inlineTyping, choiceFromText } from './objectGridCellFacts'; import { Badge, Button, NavigationOverlay, EmptyValue, @@ -60,6 +61,14 @@ import { cn, GridCellSelectionProvider, type GridCellSelection, + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, } from '@object-ui/components'; import { captureUpdateUndoData, resolveConditionalFormatting, declaredNameField, buildExportFileName, resolveAffordance, resolveAffordanceGrant, resolveFieldAffordance, type SchemaLike, isExpandableFieldType, isUnmaterializedFieldType, readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, filterRefusalSubject, FilterOperatorError, resolveRecordSourceConfig, resolveRecordSourceObjectName, partitionRowsByPredicate, csvBlob, readActionPayload } from '@object-ui/core'; import { usePermissions } from '@object-ui/permissions'; @@ -787,6 +796,12 @@ export const ObjectGrid: React.FC = ({ // A grid torn down mid-conflict settles it as Cancel, so the awaiting save // never hangs. useEffect(() => () => rowConflictDecisionRef.current?.('cancel'), []); + // objectstack#35685 — the move of a state-machine field a list cell asks to + // confirm first, and the answer the cell's commit is waiting on. A grid torn + // down meanwhile answers no, so nothing is written. + const [stateChange, setStateChange] = useState(null); + const stateChangeDecisionRef = React.useRef<((confirmed: boolean) => void) | null>(null); + useEffect(() => () => stateChangeDecisionRef.current?.(false), []); // objectstack#35685 — the rows a select-first save redrew in place, per // record id. Each applies while the grid still holds the row object it was // saved from (`RowPatch.base`); the next load's rows replace them. @@ -1198,6 +1213,25 @@ export const ObjectGrid: React.FC = ({ recordVerdict.requestVerdicts(); approvalLocks.probe(rowRecordId(row)); }, + // objectstack#35685 — a move of a state-machine field is confirmed + // before anything is written (`./objectGridStateConfirm`). + confirmCommit: (row, columnKey, value) => { + if (!isStateMachineField(objectSchema, columnKey)) return null; + const options = objectFields?.[columnKey]?.options; + const labelOf = (v: unknown) => stateLabelOf( + options, + v, + (code, fallback) => (objectName ? resolveFieldOptionLabel(objectName, columnKey, code, fallback) : fallback), + t('grid.empty'), + ); + const declared = objectFields?.[columnKey]?.label; + const fallback = typeof declared === 'string' && declared.length > 0 ? declared : columnKey; + return askStateChange({ + field: columnHeaderOf(columnKey) ?? (objectName ? resolveFieldLabel(objectName, columnKey, fallback) : fallback), + from: labelOf(row?.[columnKey]), + to: labelOf(value), + }); + }, } : null; @@ -2476,6 +2510,24 @@ export const ObjectGrid: React.FC = ({ * waiting on an earlier dialog is settled as Cancel first, so no save is * left waiting on a dialog that is no longer shown. */ + /** + * objectstack#35685 — open the state-change confirm and wait for the + * answer. A move still waiting on an earlier confirm is answered no first, + * so no commit is left waiting on a dialog that is no longer shown. + */ + const askStateChange = (change: StateChangeConfirm): Promise => + new Promise((resolve) => { + stateChangeDecisionRef.current?.(false); + stateChangeDecisionRef.current = resolve; + setStateChange(change); + }); + const settleStateChange = (confirmed: boolean) => { + const resolve = stateChangeDecisionRef.current; + stateChangeDecisionRef.current = null; + setStateChange(null); + resolve?.(confirmed); + }; + const askRowConflict = (conflict: ConcurrentUpdateConflict): Promise => new Promise((resolve) => { rowConflictDecisionRef.current?.('cancel'); @@ -4475,6 +4527,29 @@ export const ObjectGrid: React.FC = ({ /> ); + // objectstack#35685 — the confirm before a list cell moves a state-machine + // field. Focus goes back to the cell, which the table hands it. + const stateChangeDialog = ( + { if (!open) settleStateChange(false); }}> + e.preventDefault()}> + + {t('grid.stateChange.title', { field: stateChange?.field ?? '' })} + + {t('grid.stateChange.description', { + field: stateChange?.field ?? '', + from: stateChange?.from ?? '', + to: stateChange?.to ?? '', + })} + + + + {t('grid.stateChange.cancel')} + settleStateChange(true)}>{t('grid.stateChange.confirm')} + + + + ); + return (
{/* Re-fetch indicator while existing rows remain visible (filter/sort @@ -4542,6 +4617,7 @@ export const ObjectGrid: React.FC = ({ )} {bulkDialog} {rowConflictDialog} + {stateChangeDialog}
); }; diff --git a/ui/packages/plugin-grid/src/objectGridStateConfirm.ts b/ui/packages/plugin-grid/src/objectGridStateConfirm.ts new file mode 100644 index 00000000000..ae23a348c95 --- /dev/null +++ b/ui/packages/plugin-grid/src/objectGridStateConfirm.ts @@ -0,0 +1,68 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * objectstack#35685 — the confirm step before a list cell moves a + * state-machine field. + * + * A state-machine field is a field the object's `state_machine` validation + * rule governs (ADR-0020), read the way the board, the record form and the + * grid's own editor read it: an active rule naming the field whose events + * cover an update. Its severity does not matter here: a move along a machine + * is the change that related automation listens for, whether or not the rule + * blocks a bad one. Which moves are legal stays the server's call. + * + * The confirm names the field and its old and new value and says saving may + * trigger related automation, as the maintainer ruled (ruling record + * 7039615827 on objectstack#35685); it does not list the flows. + */ + +/** The spec's `events` default for a validation rule. */ +const DEFAULT_EVENTS: readonly string[] = ['insert', 'update']; + +/** Whether an active `state_machine` rule of `objectSchema` governs `field` on update. */ +export function isStateMachineField(objectSchema: unknown, field: string): boolean { + const rules = (objectSchema as { validations?: unknown } | null | undefined)?.validations; + if (!Array.isArray(rules)) return false; + return rules.some((rule) => { + if (!rule || typeof rule !== 'object') return false; + const r = rule as { type?: unknown; field?: unknown; active?: unknown; events?: unknown }; + if (r.type !== 'state_machine' || r.field !== field || r.active === false) return false; + const events = Array.isArray(r.events) && r.events.length > 0 ? r.events : DEFAULT_EVENTS; + return events.includes('update'); + }); +} + +/** What the confirm says about one move: the field, and the value it leaves and takes. */ +export interface StateChangeConfirm { + field: string; + from: string; + to: string; +} + +type OptionLike = { value?: unknown; label?: unknown } | string | number; + +/** + * The words a stored state is shown in: the option's label (as the host + * translates it), the stored code when no option declares it, and `empty` + * for no value. + */ +export function stateLabelOf( + options: unknown, + value: unknown, + translate: (optionValue: string, fallback: string) => string, + empty: string, +): string { + if (value === undefined || value === null || value === '') return empty; + const code = String(value); + const option = Array.isArray(options) + ? (options as OptionLike[]).find((o) => String(typeof o === 'object' && o !== null ? o.value : o) === code) + : undefined; + const declared = typeof option === 'object' && option !== null && typeof option.label === 'string' && option.label.length > 0 + ? option.label + : code; + return translate(code, declared); +} diff --git a/ui/packages/plugin-grid/src/objectGridTranslations.ts b/ui/packages/plugin-grid/src/objectGridTranslations.ts index 0227c227dbb..45be44a4d42 100644 --- a/ui/packages/plugin-grid/src/objectGridTranslations.ts +++ b/ui/packages/plugin-grid/src/objectGridTranslations.ts @@ -119,6 +119,12 @@ const GRID_DEFAULT_TRANSLATIONS: Record = { 'grid.readOnlyReason.noPermission': 'You don\'t have permission to edit these records.', 'grid.readOnlyReason.approvalLocked': 'This record is locked while it\'s in approval.', 'grid.readOnlyReason.noRecordPermission': 'You don\'t have permission to edit this record.', + // objectstack#35685 — the confirm before a list cell moves a state-machine + // field (`objectGridStateConfirm`). Byte-identical to the `en` pack. + 'grid.stateChange.title': 'Change {{field}}?', + 'grid.stateChange.description': '{{field}} changes from {{from}} to {{to}}. Saving may trigger related automation.', + 'grid.stateChange.confirm': 'Change', + 'grid.stateChange.cancel': 'Cancel', }; /** From 3d5646838092f57e31b3d0002d94d80518bf8e91 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:37:34 +0000 Subject: [PATCH 2/5] feat(list): drawer save bar says when the record changed during the edit; tests for the S3 confirm Claude-Session: https://claude.ai/code/session_01L6bhgVhAK4uNYvjNY3H7XU Co-authored-by: Claude --- .../data-table-autosave-35685.test.tsx | 93 +++++++++++++++ ui/packages/i18n/src/locales/ar.ts | 1 + ui/packages/i18n/src/locales/de.ts | 1 + ui/packages/i18n/src/locales/en.ts | 1 + ui/packages/i18n/src/locales/es.ts | 1 + ui/packages/i18n/src/locales/fr.ts | 1 + ui/packages/i18n/src/locales/ja.ts | 1 + ui/packages/i18n/src/locales/ko.ts | 1 + ui/packages/i18n/src/locales/pt-BR.ts | 1 + ui/packages/i18n/src/locales/ru.ts | 1 + ui/packages/i18n/src/locales/zh-Hans.ts | 1 + ui/packages/i18n/src/locales/zh-Hant.ts | 1 + .../plugin-detail/src/InlineEditSaveBar.tsx | 25 ++++ .../src/__tests__/InlineEditSaveBar.test.tsx | 45 ++++++++ .../plugin-detail/src/useDetailTranslation.ts | 3 + .../ObjectGrid.autosave-35685.test.tsx | 107 +++++++++++++++++- 16 files changed, 283 insertions(+), 1 deletion(-) diff --git a/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx b/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx index 36b4510b61d..bf088cc00ef 100644 --- a/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx @@ -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'; @@ -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((resolve) => { asks.push({ row, columnKey, value, answer: resolve }); }); + }); + const DataTable = ComponentRegistry.get('data-table')!; + const utils = render( + + + , + ); + 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"]'); + 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' }); + }); +}); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index f1b88a5267a..a4f663485bb 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1641,6 +1641,7 @@ const ar = { pathStageChangeConflict: 'قام شخص آخر بتغيير هذا السجل، ويتم الآن عرض أحدث إصدار. اضغط على المرحلة مرة أخرى إذا كان النقل لا يزال مطلوبًا.', pathStageChangeDenied: 'ليس لديك إذن لتغيير مرحلة هذا السجل.', pathStageChangeFailed: 'تعذر تغيير المرحلة.', + inlineEditRecordChanged: "تم تغيير هذا السجل في مكان آخر أثناء التحرير. يتم الاحتفاظ بتغييراتك غير المحفوظة، ويكتبها الحفظ فوق أحدث إصدار.", linkCopied: "تم نسخ الرابط إلى الحافظة", commentFailed: "لم يُنشر تعليقك. لم يُحفظ أي شيء — يُرجى المحاولة مرة أخرى.", reactionFailed: "لم يُحفظ تفاعلك. يُرجى المحاولة مرة أخرى.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index fbb398ffcb0..e28c96fa29f 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1467,6 +1467,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.", linkCopied: "Link in die Zwischenablage kopiert", commentFailed: "Ihr Kommentar wurde nicht veröffentlicht. Es wurde nichts gespeichert – bitte versuchen Sie es erneut.", reactionFailed: "Ihre Reaktion wurde nicht gespeichert. Bitte versuchen Sie es erneut.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 7485d156d74..a00510509b1 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1607,6 +1607,7 @@ const en = { pathStageChangeConflict: 'Someone else changed this record, and the latest version is now shown. Press the stage again if the move still applies.', pathStageChangeDenied: "You don't have permission to change this record's stage.", pathStageChangeFailed: 'The stage could not be changed.', + inlineEditRecordChanged: 'This record was changed elsewhere while you were editing. Your unsaved changes are kept, and Save writes them over the latest version.', linkCopied: 'Link copied to clipboard', commentFailed: 'Your comment was not posted. Nothing was saved — please try again.', reactionFailed: 'Your reaction was not saved. Please try again.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 67363a15c27..c6faa67abe5 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1512,6 +1512,7 @@ const es = { pathStageChangeConflict: 'Otra persona ha modificado este registro y ahora se muestra la versión más reciente. Vuelve a pulsar la etapa si el cambio sigue siendo válido.', pathStageChangeDenied: 'No tienes permiso para cambiar la etapa de este registro.', pathStageChangeFailed: 'No se ha podido cambiar la etapa.', + inlineEditRecordChanged: "Este registro se modificó en otro lugar mientras lo editaba. Sus cambios sin guardar se conservan, y Guardar los escribe sobre la versión más reciente.", linkCopied: "Enlace copiado al portapapeles", commentFailed: "Tu comentario no se ha publicado. No se ha guardado nada; inténtalo de nuevo.", reactionFailed: "Tu reacción no se ha guardado. Inténtalo de nuevo.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index fd4b5f0b95b..640aff76d36 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1509,6 +1509,7 @@ const fr = { pathStageChangeConflict: "Quelqu'un d'autre a modifié cet enregistrement ; la dernière version est maintenant affichée. Cliquez à nouveau sur l'étape si le changement s'applique toujours.", pathStageChangeDenied: "Vous n'avez pas l'autorisation de modifier l'étape de cet enregistrement.", pathStageChangeFailed: "L'étape n'a pas pu être modifiée.", + inlineEditRecordChanged: "Cet enregistrement a été modifié ailleurs pendant votre modification. Vos modifications non enregistrées sont conservées, et Enregistrer les écrit sur la dernière version.", linkCopied: "Lien copié dans le presse-papiers", commentFailed: "Votre commentaire n'a pas été publié. Rien n'a été enregistré — veuillez réessayer.", reactionFailed: "Votre réaction n'a pas été enregistrée. Veuillez réessayer.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index d09bd48c9a1..9f7f228e7f8 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1548,6 +1548,7 @@ const ja = { pathStageChangeConflict: '他のユーザーがこのレコードを変更したため、最新の内容を表示しています。移動が必要な場合は、もう一度ステージを押してください。', pathStageChangeDenied: 'このレコードのステージを変更する権限がありません。', pathStageChangeFailed: 'ステージを変更できませんでした。', + inlineEditRecordChanged: "編集中にこのレコードが別の場所で変更されました。未保存の変更はそのまま残り、保存すると最新版に上書きされます。", linkCopied: "リンクをクリップボードにコピーしました", commentFailed: "コメントを投稿できませんでした。何も保存されていません。もう一度お試しください。", reactionFailed: "リアクションが保存されませんでした。もう一度お試しください。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index dce34bdd8cd..9fbfc963cb1 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1467,6 +1467,7 @@ const ko = { pathStageChangeConflict: '다른 사용자가 이 레코드를 변경하여 최신 버전을 표시합니다. 이동이 여전히 필요하면 단계를 다시 누르세요.', pathStageChangeDenied: '이 레코드의 단계를 변경할 권한이 없습니다.', pathStageChangeFailed: '단계를 변경할 수 없습니다.', + inlineEditRecordChanged: "편집하는 동안 이 레코드가 다른 곳에서 변경되었습니다. 저장하지 않은 변경 사항은 유지되며, 저장하면 최신 버전에 덮어씁니다.", linkCopied: "링크가 클립보드에 복사됨", commentFailed: "댓글이 게시되지 않았습니다. 아무것도 저장되지 않았습니다. 다시 시도해 주세요.", reactionFailed: "반응이 저장되지 않았습니다. 다시 시도해 주세요.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 79686dd24df..fd696fff801 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1509,6 +1509,7 @@ const pt = { pathStageChangeConflict: 'Outra pessoa alterou este registro, e a versão mais recente está sendo exibida. Pressione a etapa novamente se a mudança ainda se aplicar.', pathStageChangeDenied: 'Você não tem permissão para alterar a etapa deste registro.', pathStageChangeFailed: 'Não foi possível alterar a etapa.', + inlineEditRecordChanged: "Este registro foi alterado em outro lugar enquanto você editava. Suas alterações não salvas são mantidas, e Salvar as grava sobre a versão mais recente.", linkCopied: "Link copiado para a área de transferência", commentFailed: "Seu comentário não foi publicado. Nada foi salvo — tente novamente.", reactionFailed: "Sua reação não foi salva. Tente novamente.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 6e20db66f59..6a94b00d08f 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1653,6 +1653,7 @@ const ru = { pathStageChangeConflict: 'Запись изменил другой пользователь, теперь показана последняя версия. Нажмите на этап ещё раз, если перевод всё ещё нужен.', pathStageChangeDenied: 'У вас нет прав на смену этапа этой записи.', pathStageChangeFailed: 'Не удалось сменить этап.', + inlineEditRecordChanged: "Пока вы редактировали, эту запись изменили в другом месте. Несохранённые изменения сохранены, и при сохранении они будут записаны поверх последней версии.", linkCopied: "Ссылка скопирована в буфер обмена", commentFailed: "Комментарий не опубликован. Ничего не сохранено — попробуйте ещё раз.", reactionFailed: "Реакция не сохранена. Попробуйте ещё раз.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index b07759e0433..e620d442439 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1333,6 +1333,7 @@ const zh = { pathStageChangeConflict: '其他人已修改此记录,现已显示最新版本。如仍需移动,请再次点击该阶段。', pathStageChangeDenied: '你没有更改此记录阶段的权限。', pathStageChangeFailed: '无法更改阶段。', + inlineEditRecordChanged: '编辑期间,此记录已在别处被修改。你未保存的修改会保留,保存时以你的修改为准,写到最新版本上。', linkCopied: '链接已复制到剪贴板', commentFailed: '评论未发布,内容没有保存,请重试。', reactionFailed: '表情回应未保存,请重试。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 0ac82c60b63..479b900aa65 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1333,6 +1333,7 @@ const zhHant = { pathStageChangeConflict: '其他人已修改此記錄,現已顯示最新版本。如仍需移動,請再次點選該階段。', pathStageChangeDenied: '你沒有更改此記錄階段的權限。', pathStageChangeFailed: '無法更改階段。', + inlineEditRecordChanged: '編輯期間,此記錄已在別處被修改。你未儲存的修改會保留,儲存時以你的修改為準,寫到最新版本上。', linkCopied: '連結已複製到剪貼簿', commentFailed: '評論未釋出,內容沒有儲存,請重試。', reactionFailed: '表情回應未儲存,請重試。', diff --git a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx index af5fa0dab05..390900cfb2d 100644 --- a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx +++ b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx @@ -554,6 +554,22 @@ export const InlineEditSaveBar: React.FC = ({ return () => window.removeEventListener('keydown', onKeyDown); }, [editing, saving, locked, conflictOpen, handleSave, cancel]); + // objectstack#35685 — the record's version when this edit session began. A + // record read again meanwhile at another version was changed elsewhere (a + // list cell beside the drawer, another tab): the draft stays as typed and + // Save writes it over the record as it is now, so the bar says so. + const dataVersion = typeof data?.updated_at === 'string' ? (data.updated_at as string) : undefined; + const [editBase, setEditBase] = React.useState<{ version: string | undefined } | null>(null); + React.useEffect(() => { + if (!editing) { + setEditBase(null); + return; + } + setEditBase((prev) => prev ?? { version: dataVersion }); + }, [editing, dataVersion]); + const changedWhileEditing = + !saving && editBase !== null && editBase.version !== undefined && dataVersion !== undefined && dataVersion !== editBase.version; + // Render nothing unless a provider is present and the record is being edited. if (!inline || !inline.editing) return null; @@ -609,6 +625,15 @@ export const InlineEditSaveBar: React.FC = ({ )} )} + {changedWhileEditing && ( +
+ {t('detail.inlineEditRecordChanged')} +
+ )} {/* The lock REASON is surfaced by DetailView's approval-lock band; here we only disable Save so a locked record can't be written. */}