diff --git a/.changeset/35995-drawer-required-prompt.md b/.changeset/35995-drawer-required-prompt.md new file mode 100644 index 00000000000..12b227a5912 --- /dev/null +++ b/.changeset/35995-drawer-required-prompt.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-detail': patch +--- + +fix(plugin-detail): the record drawer's per-field save asks for the fields a change makes required + +Clause-②: no +Metadata-protocol: none + +In the record overlay (`RecordDetailPanel`, and `RecordDetailDrawer` around it), a change that made another field required (`requiredWhen`) while that field was empty went straight to the host's `onFieldSave` and came back refused by the server. The overlay now asks first, in the same fill-in dialog the record page, the list cell and the kanban open: Save writes the change and the typed values in one update guarded with `If-Match` at the version the edit began on, Cancel writes nothing and keeps the edit. A change that makes nothing required still saves at once through `onFieldSave`. + +The ask needs one write to put the values in, so `InlineEditSaveBar` asks in its callback mode only when it is also given `dataSource`, `objectName`, `recordId` and `data`; `RecordDetailPanel` now passes them, with a record context naming the object's fields. That one write goes through the data source, not through `onFieldSave`; a host that patches its own list in `onFieldSave` sees it through the data source's mutation event. Without a data source the overlay saves field by field as before. diff --git a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx index 19ca56bf6f9..ac0eb2b67b3 100644 --- a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx +++ b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx @@ -19,6 +19,8 @@ * - **Callback mode** (standalone drawer): loops a caller-supplied * `onFieldSave(field, value)` over the draft, preserving the drawer's * existing per-field persistence contract with plugin-gantt/calendar/kanban. + * The one exception is a draft that makes other fields required + * (objectstack#35995): see `handleSave`. * * While the session is active the bar also owns the record-level keyboard * shortcuts (objectui#2572): **Esc** cancels (when no popover/dialog is open) @@ -112,7 +114,10 @@ export interface InlineEditSaveBarProps { /** * Callback-persistence mode (drawer): when provided, the save loops this * per-field callback over the draft instead of issuing a DataSource update. - * Takes precedence over the DataSource path. + * Takes precedence over the DataSource path — except for a draft that makes + * other fields required (objectstack#35995): when the DataSource props are + * given too, that draft asks for the fields and writes the draft and the + * typed values in ONE guarded DataSource update, as the record page does. */ onFieldSave?: (field: string, value: any) => void | Promise; /** When true, disables Save and shows a lock hint (e.g. approval-locked). */ @@ -141,6 +146,18 @@ export interface InlineEditSaveBarProps { * `currentRecord` / `currentVersion` is a red build here rather than a fresh * `any`. */ +/** + * A draft waiting on the fill-in dialog (objectstack#35956). `ifMatch` is + * present only for the callback mode (objectstack#35995): the version its edit + * session began on, which guards the combined write. The atomic mode reads the + * record's version when Save is pressed, as its plain Save does. + */ +interface RequiredAsk { + draft: Record; + fields: RequiredWhenPromptField[]; + ifMatch?: string | undefined; +} + type NarrowedBy = F extends (arg: unknown) => arg is infer N ? N : never; type ConcurrentUpdateErrorShape = NarrowedBy; @@ -317,19 +334,18 @@ export const InlineEditSaveBar: React.FC = ({ // objectstack#35956 — a draft that makes other fields required asks for // them before the write, in the dialog the list cell and the kanban drop - // open, and Save writes the draft and those values in ONE update. Only on - // the atomic path: the drawer's per-field callback has no one write to put - // them in. The fields come from the page's record context, which describes - // this record only when it names the same object. + // open, and Save writes the draft and those values in ONE update. That + // update is the DataSource one, so the ask needs the DataSource props in + // both modes: the drawer's per-field callback has no one write to put them + // in, and objectstack#35995 has the drawer hand those props over too. The + // fields come from the record context, which describes this record only + // when it names the same object. const recordCtx = useRecordContext(); const perms = usePermissions(); const { fieldLabel, translateOptions, fieldOptionLabel } = useSafeFieldLabel(); const objectSchema = recordCtx?.objectName === objectName ? recordCtx?.objectSchema : undefined; const objectFields = (objectSchema as { fields?: Record } | undefined)?.fields; - const [requiredAsk, setRequiredAsk] = React.useState<{ - draft: Record; - fields: RequiredWhenPromptField[]; - } | null>(null); + const [requiredAsk, setRequiredAsk] = React.useState(null); // The write a conflict raised from that dialog was making (the draft AND the // typed values), so the conflict dialog's overwrite sends all of it rather // than the draft alone, which the server would refuse again. `null` for a @@ -471,6 +487,21 @@ export const InlineEditSaveBar: React.FC = ({ [fieldLabelFor, t], ); + // 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 editing = !!inline?.editing; + 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 handleSave = React.useCallback(async () => { if (!inline) return; const draft = inline.draft; @@ -480,12 +511,16 @@ export const InlineEditSaveBar: React.FC = ({ inline.reset(); return; } - if (!onFieldSave && canAtomic && data && typeof data === 'object') { + // Asked in both modes before anything is written (objectstack#35995): + // the callback mode's first `onFieldSave` would otherwise land the change + // alone, and the server refuses it for the empty field. The callback mode + // guards the combined write with the version the edit session began on. + if (canAtomic && data && typeof data === 'object') { const fields = collectRequiredWhenPromptFields(objectFields, data, draft, { fillable }); if (fields.length > 0) { inline.setError(null); inline.setFieldErrors(null); - setRequiredAsk({ draft, fields }); + setRequiredAsk(onFieldSave ? { draft, fields, ifMatch: editBase?.version ?? dataVersion } : { draft, fields }); return; } } @@ -516,7 +551,10 @@ export const InlineEditSaveBar: React.FC = ({ } inline.reset(); } catch (err) { - if (isConcurrentUpdateError(err) && canAtomic) { + // The callback mode's writes are the host's, so its conflict is + // presented like any other refusal: the dialog's overwrite writes + // through the DataSource, which is not the path that refused. + if (isConcurrentUpdateError(err) && canAtomic && !onFieldSave) { // Stay in edit mode; the dialog drives reload / overwrite. setConflict(buildConflict(draft, err)); } else { @@ -527,7 +565,7 @@ export const InlineEditSaveBar: React.FC = ({ } finally { inline.setSaving(false); } - }, [inline, onFieldSave, canAtomic, data, dataSource, objectName, recordId, refresh, buildConflict, presentRefusal, objectFields, fillable]); + }, [inline, onFieldSave, canAtomic, data, dataSource, objectName, recordId, refresh, buildConflict, presentRefusal, objectFields, fillable, editBase, dataVersion]); const closeConflict = React.useCallback(() => { conflictWriteRef.current = null; @@ -580,7 +618,6 @@ export const InlineEditSaveBar: React.FC = ({ // layer", so the session only cancels when nothing is stacked on top. // Both respect the in-flight `saving` state; save also respects `locked` // and stands down while the conflict dialog drives the session. - const editing = !!inline?.editing; const saving = !!inline?.saving; const cancel = inline?.cancel; const conflictOpen = !!conflict; @@ -612,24 +649,11 @@ 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; /** The fill-in dialog for a draft that needs fields filled (objectstack#35956). */ - const renderRequiredAsk = (ask: { draft: Record; fields: RequiredWhenPromptField[] }) => { + const renderRequiredAsk = (ask: RequiredAsk) => { const objectKey = objectName ?? ''; const labelOf = (name: string): string => { const declared = (objectFields?.[name] as { label?: unknown } | undefined)?.label; @@ -678,7 +702,9 @@ export const InlineEditSaveBar: React.FC = ({ // draft is still the reader's to change or cancel. onCancel={() => setRequiredAsk(null)} onSubmit={async (values) => { - const ifMatch = typeof data?.updated_at === 'string' ? (data.updated_at as string) : undefined; + const ifMatch = 'ifMatch' in ask + ? ask.ifMatch + : typeof data?.updated_at === 'string' ? (data.updated_at as string) : undefined; inline?.setSaving(true); const write = { ...ask.draft, ...values }; try { diff --git a/ui/packages/plugin-detail/src/RecordDetailPanel.tsx b/ui/packages/plugin-detail/src/RecordDetailPanel.tsx index d093454094f..0ba2726f9ea 100644 --- a/ui/packages/plugin-detail/src/RecordDetailPanel.tsx +++ b/ui/packages/plugin-detail/src/RecordDetailPanel.tsx @@ -53,7 +53,7 @@ import React from 'react'; import { isExpandableFieldType, resolveAffordance, type SchemaLike } from '@object-ui/core'; import type { DataSource } from '@object-ui/types'; import { SYSTEM_MANAGED_FIELD_NAMES } from '@object-ui/types'; -import { InlineEditProvider } from '@object-ui/react'; +import { InlineEditProvider, RecordContextProvider } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import { DetailView } from './DetailView'; import { InlineEditSaveBar } from './InlineEditSaveBar'; @@ -347,19 +347,37 @@ export function RecordDetailPanel({ /> {/* Record-level Save/Cancel bar. Callback mode: loops the caller's per-field onFieldSave over the draft, preserving the overlay's - existing persistence contract (plugin-gantt/kanban/calendar). */} - { - try { - await fieldSave(field, value); - } catch (err) { - console.error('[RecordDetailPanel] inline field save failed:', err); - // Rethrow so the save bar surfaces the failure inline and keeps - // the draft — swallowing made a rejected save look successful. - throw err; - } - } : undefined} - /> + existing persistence contract (plugin-gantt/kanban/calendar). + objectstack#35995 — the record, its object and the data source go + along too, so a draft that makes other fields required asks for + them first and writes everything in one guarded update, as the + record page does. The record context names this record for the + bar alone (the object's fields), not for the panel's body. */} + + { + try { + await fieldSave(field, value); + } catch (err) { + console.error('[RecordDetailPanel] inline field save failed:', err); + // Rethrow so the save bar surfaces the failure inline and keeps + // the draft — swallowing made a rejected save look successful. + throw err; + } + } : undefined} + /> + ); } diff --git a/ui/packages/plugin-detail/src/__tests__/InlineEditSaveBar.requiredPrompt-35956.test.tsx b/ui/packages/plugin-detail/src/__tests__/InlineEditSaveBar.requiredPrompt-35956.test.tsx index 3213267cf93..dab41927621 100644 --- a/ui/packages/plugin-detail/src/__tests__/InlineEditSaveBar.requiredPrompt-35956.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/InlineEditSaveBar.requiredPrompt-35956.test.tsx @@ -19,8 +19,15 @@ * conflict dialog over it, as a plain Save's 409 does (L1 7057894230 * S1): its Overwrite sends the draft AND the typed values at the version * the server reported, its Cancel comes back to the typed values. - * 5. Control: a draft that makes nothing required saves at once, as before; - * and the drawer's per-field callback mode never asks. + * 5. Control: a draft that makes nothing required saves at once, as before. + * + * objectstack#35995 — the drawer's per-field callback mode asks too, when its + * host hands the bar the record and the data source (`RecordDetailPanel` + * does): Save writes the change and the typed values in ONE guarded update at + * the version the edit began on, never through the per-field callback; Cancel + * writes nothing; a change that makes nothing required still goes through the + * callback at once; a 409 keeps the fill-in dialog open under the conflict + * dialog. */ import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, fireEvent, waitFor, cleanup, within } from '@testing-library/react'; @@ -29,6 +36,7 @@ import React from 'react'; import { InlineEditProvider, RecordContextProvider, useInlineEdit } from '@object-ui/react'; import { registerAllFields } from '@object-ui/fields'; import { InlineEditSaveBar } from '../InlineEditSaveBar'; +import { RecordDetailPanel } from '../RecordDetailPanel'; registerAllFields(); afterEach(() => cleanup()); @@ -59,22 +67,23 @@ function Harness() { function renderBar(update: ReturnType, extra: Partial> = {}) { const refresh = vi.fn().mockResolvedValue(undefined); - render( - + const tree = (data: typeof DATA) => ( + - , + ); - return { refresh }; + const { rerender } = render(tree(DATA)); + return { refresh, rereadAs: (data: typeof DATA) => rerender(tree(data)) }; } const winReasonInput = (dialog: HTMLElement) => @@ -147,13 +156,15 @@ describe('InlineEditSaveBar asks for the fields a draft makes required (objectst expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); }); - it('control: the per-field callback mode (drawer) never asks', async () => { + it('the per-field callback mode (drawer) asks too, and writes nothing yet (objectstack#35995)', async () => { const update = vi.fn().mockResolvedValue({}); const onFieldSave = vi.fn().mockResolvedValue(undefined); renderBar(update, { onFieldSave }); stageWon(); - await waitFor(() => expect(onFieldSave).toHaveBeenCalledWith('stage', 'won')); - expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + const dialog = await screen.findByTestId('required-fields-dialog'); + expect(winReasonInput(dialog)).toBeTruthy(); + expect(onFieldSave).not.toHaveBeenCalled(); + expect(update).not.toHaveBeenCalled(); }); describe('a 409 of the combined write opens the conflict dialog, as a plain Save does', () => { @@ -197,3 +208,135 @@ describe('InlineEditSaveBar asks for the fields a draft makes required (objectst }); }); }); + +describe('the drawer\'s per-field callback mode asks for the fields a change makes required (objectstack#35995)', () => { + it('Save writes the change and the typed value in ONE guarded update, never through the callback', async () => { + const update = vi.fn().mockResolvedValue({}); + const onFieldSave = vi.fn().mockResolvedValue(undefined); + renderBar(update, { onFieldSave }); + stageWon(); + const dialog = await screen.findByTestId('required-fields-dialog'); + fireEvent.change(winReasonInput(dialog), { target: { value: 'Better price' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Save' })); + await waitFor(() => expect(screen.getByTestId('editing')).toHaveTextContent('idle')); + expect(update).toHaveBeenCalledTimes(1); + expect(update).toHaveBeenCalledWith('deal', 'd1', { stage: 'won', win_reason: 'Better price' }, { ifMatch: 'v1' }); + expect(onFieldSave).not.toHaveBeenCalled(); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('the guard is the version the edit began on, not one read again meanwhile', async () => { + const update = vi.fn().mockResolvedValue({}); + const onFieldSave = vi.fn().mockResolvedValue(undefined); + const { rereadAs } = renderBar(update, { onFieldSave }); + fireEvent.click(screen.getByText('edit-enter')); + fireEvent.click(screen.getByText('edit-stage-won')); + // The host reads the record again mid-edit (a write elsewhere). + rereadAs({ ...DATA, priority: 'high', updated_at: 'v2' }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + const dialog = await screen.findByTestId('required-fields-dialog'); + fireEvent.change(winReasonInput(dialog), { target: { value: 'Better price' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Save' })); + await waitFor(() => expect(update).toHaveBeenCalledTimes(1)); + expect(update).toHaveBeenCalledWith('deal', 'd1', { stage: 'won', win_reason: 'Better price' }, { ifMatch: 'v1' }); + }); + + it('Cancel writes nothing and keeps the field\'s edit', async () => { + const update = vi.fn().mockResolvedValue({}); + const onFieldSave = vi.fn().mockResolvedValue(undefined); + renderBar(update, { onFieldSave }); + stageWon(); + const dialog = await screen.findByTestId('required-fields-dialog'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); + await waitFor(() => expect(screen.queryByTestId('required-fields-dialog')).toBeNull()); + expect(update).not.toHaveBeenCalled(); + expect(onFieldSave).not.toHaveBeenCalled(); + expect(screen.getByTestId('editing')).toHaveTextContent('editing'); + expect(screen.getByTestId('draft')).toHaveTextContent('"stage":"won"'); + }); + + it('control: a change that makes nothing required saves at once through the callback, as before', async () => { + const update = vi.fn().mockResolvedValue({}); + const onFieldSave = vi.fn().mockResolvedValue(undefined); + renderBar(update, { onFieldSave }); + fireEvent.click(screen.getByText('edit-enter')); + fireEvent.click(screen.getByText('edit-priority')); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(onFieldSave).toHaveBeenCalledWith('priority', 'high')); + expect(onFieldSave).toHaveBeenCalledTimes(1); + expect(update).not.toHaveBeenCalled(); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('a 409 keeps the fill-in dialog open under the conflict dialog, with the value still typed', async () => { + const conflict = { + code: 'CONCURRENT_UPDATE', + currentVersion: 'v2', + currentRecord: { ...DATA, priority: 'high', updated_at: 'v2' }, + }; + const update = vi.fn().mockRejectedValueOnce(conflict).mockResolvedValueOnce({}); + const onFieldSave = vi.fn().mockResolvedValue(undefined); + renderBar(update, { onFieldSave }); + stageWon(); + const dialog = await screen.findByTestId('required-fields-dialog'); + fireEvent.change(winReasonInput(dialog), { target: { value: 'Better price' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Save' })); + await waitFor(() => expect(screen.getByRole('alertdialog')).toBeInTheDocument()); + expect(winReasonInput(screen.getByTestId('required-fields-dialog')).value).toBe('Better price'); + fireEvent.click(screen.getByRole('button', { name: /overwrite/i })); + await waitFor(() => expect(update).toHaveBeenCalledTimes(2)); + expect(update).toHaveBeenLastCalledWith('deal', 'd1', { stage: 'won', win_reason: 'Better price' }, { ifMatch: 'v2' }); + expect(onFieldSave).not.toHaveBeenCalled(); + }); + + it('control: with no data source handed over there is no one write to make, so it never asks', async () => { + const update = vi.fn().mockResolvedValue({}); + const onFieldSave = vi.fn().mockResolvedValue(undefined); + renderBar(update, { onFieldSave, dataSource: undefined }); + stageWon(); + await waitFor(() => expect(onFieldSave).toHaveBeenCalledWith('stage', 'won')); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('RecordDetailPanel hands the bar what it needs: the drawer asks before its per-field save', async () => { + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 }); + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ record: { visible: true } }) }))); + try { + const schema = { + name: 'task', + fields: { + subject: { type: 'text', label: 'Subject' }, + status: { type: 'text', label: 'Status' }, + outcome: { type: 'text', label: 'Outcome', requiredWhen: 'record.status == "done"' }, + }, + }; + const record = { id: 't1', subject: 'Call Acme', status: 'open', outcome: null, updated_at: 'v1' }; + const update = vi.fn().mockResolvedValue({}); + const onFieldSave = vi.fn().mockResolvedValue(undefined); + render( + , + ); + // The status reads in more than one place (the header's highlights, the + // body); the body's value is the one a double-click edits. + for (const el of screen.getAllByText('open')) fireEvent.doubleClick(el); + fireEvent.change(screen.getAllByDisplayValue('open')[0], { target: { value: 'done' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + const dialog = await screen.findByTestId('required-fields-dialog'); + const outcome = dialog.querySelector('[data-required-fields-field="outcome"] input')!; + fireEvent.change(outcome, { target: { value: 'Signed' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Save' })); + await waitFor(() => expect(update).toHaveBeenCalledTimes(1)); + expect(update).toHaveBeenCalledWith('task', 't1', { status: 'done', outcome: 'Signed' }, { ifMatch: 'v1' }); + expect(onFieldSave).not.toHaveBeenCalled(); + } finally { + vi.unstubAllGlobals(); + } + }); +});