From 5e61f1e99f94c0dbb25fdc256c16836a4487f8da Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:34:39 +0000 Subject: [PATCH 1/2] feat(detail): the record header's stage menu asks through the shared fill-in dialog The stage menu beside the record's name now judges which fields a stage makes required with `collectRequiredWhenPromptFields` and collects them in `RequiredFieldsDialog` from `@object-ui/fields`, the pair the list cell, the record page's inline Save and the kanban drop use. Its own pre-check (`fieldsNeededAt`), field form and `confirmWithFields` in `recordPathStageChange.tsx` are deleted. A stage that needs nothing opens the same dialog as the move's confirmation; the dialog focuses its submit button when it shows no field, so Enter still confirms. `record:path` keeps its plain confirmation. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgWV6ouxRg2fByapa6F --- .changeset/35956-stage-menu-shared-fill-in.md | 18 + .../fields/src/RequiredFieldsDialog.tsx | 19 +- .../plugin-detail/src/RecordStageMenu.tsx | 7 +- .../__tests__/RecordStageMenu-35891.test.tsx | 191 ++++++++-- .../src/renderers/recordPathStageChange.tsx | 334 ++++++++---------- 5 files changed, 352 insertions(+), 217 deletions(-) create mode 100644 .changeset/35956-stage-menu-shared-fill-in.md diff --git a/.changeset/35956-stage-menu-shared-fill-in.md b/.changeset/35956-stage-menu-shared-fill-in.md new file mode 100644 index 00000000000..7becd77239a --- /dev/null +++ b/.changeset/35956-stage-menu-shared-fill-in.md @@ -0,0 +1,18 @@ +--- +'@object-ui/fields': patch +'@object-ui/plugin-detail': patch +--- + +feat(detail): the record header's stage menu asks for the fields a stage needs through the shared fill-in dialog + +Clause-②: no +Metadata-protocol: none + +The stage menu beside the record's name now opens the same dialog the list cell, the record page's inline Save and the kanban drop open (`RequiredFieldsDialog`, with `collectRequiredWhenPromptFields` judging which fields to ask for), and its own copy of the pre-check and field form is gone: + +- **What it shows:** the record's name and the move (「阶段:赢单」, read-only), then the fields the stage makes required while they are still empty. A stage that needs nothing opens the same dialog as the move's confirmation, with Move focused so Enter confirms. +- **Move** writes the stage and the typed values as ONE update; **Cancel** writes nothing. A value typed there that makes one more field required adds that field, and Move waits for it. +- **A refusal stays in the dialog** and the stage does not move: under the field it names, as a new row for another field the reader can fill, or at the foot (someone else changed the record, which is then re-read; a permission or other refusal as the stage line it was before). +- **Now not asked for, and refused as before:** a field with no in-place editor (rich text, a file, a formula). The menu's old form did not ask whether a field has one; the shared pre-check never offers such a field. + +`record:path`'s stage press keeps its plain confirmation. diff --git a/ui/packages/fields/src/RequiredFieldsDialog.tsx b/ui/packages/fields/src/RequiredFieldsDialog.tsx index a10ce9f7c95..1b94e5ed952 100644 --- a/ui/packages/fields/src/RequiredFieldsDialog.tsx +++ b/ui/packages/fields/src/RequiredFieldsDialog.tsx @@ -55,6 +55,13 @@ * the preview gallery) reads English instead of a raw key. The host may pass * its own `title`, `description` and `submitLabel` (the board keeps its * 「移动卡片」). + * + * ## Nothing to fill + * + * A host may open it with no fields (the record header's stage menu, whose + * every move goes through this dialog): it is then the change's confirmation, + * the record and the change above Cancel and Save, and Save takes the focus. + * A refusal naming a field the reader can fill still adds that field. */ import React from 'react'; @@ -164,6 +171,7 @@ export function RequiredFieldsDialog({ const [footLines, setFootLines] = React.useState([]); const [sending, setSending] = React.useState(false); const busy = !!submitting || sending; + const submitRef = React.useRef(null); const shown: RequiredFieldsDialogField[] = []; const seen = new Set(); @@ -226,6 +234,15 @@ export function RequiredFieldsDialog({ { + // With fields to fill the first one takes focus (the default). With + // none — a host using the dialog as the change's confirmation, the + // record header's stage menu — Save does, so Enter confirms the + // change the reader just picked rather than Cancel (objectstack#35891). + if (shown.length > 0 || !submitRef.current) return; + event.preventDefault(); + submitRef.current.focus(); + }} > @@ -318,7 +335,7 @@ export function RequiredFieldsDialog({ - diff --git a/ui/packages/plugin-detail/src/RecordStageMenu.tsx b/ui/packages/plugin-detail/src/RecordStageMenu.tsx index 4d36ab0d8d3..558d58213db 100644 --- a/ui/packages/plugin-detail/src/RecordStageMenu.tsx +++ b/ui/packages/plugin-detail/src/RecordStageMenu.tsx @@ -20,9 +20,10 @@ * `record:path`'s press asks (`useStageChange`). * - A stage the field's blocking `state_machine` cannot reach from the stored * value is drawn disabled, with the reason under its name. - * - Picking a stage opens the stage confirmation. A stage that needs other - * fields filled first asks for exactly those fields in the same dialog and - * writes them with the move; a refusal is shown in the dialog and the stage + * - Picking a stage opens the shared in-place fill-in dialog + * (`RequiredFieldsDialog`, objectstack#35956): the record's name, the move, + * and the fields the stage makes required, if any. The move and those + * values go in one write; a refusal is shown in the dialog and the stage * does not move (`collectFields`, see `recordPathStageChange.tsx`). * - The menu is Radix's: Enter or Space on the focused tag opens it, the arrow * keys move, Enter picks, Esc closes without a change. diff --git a/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx index 4d0be9ed54f..c023b071e35 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx @@ -102,6 +102,7 @@ interface MountOptions { dataSource?: ReturnType; refresh?: () => Promise; stage?: string; + schema?: typeof OPPORTUNITY; } function mount(opts: MountOptions = {}) { @@ -115,7 +116,7 @@ function mount(opts: MountOptions = {}) { objectName="crm_opportunity" recordId="o1" data={{ id: 'o1', name: 'Wayne deal', stage, loss_reason: null, updated_at: VERSION }} - objectSchema={OPPORTUNITY} + objectSchema={opts.schema ?? OPPORTUNITY} dataSource={dataSource as any} refresh={refresh} > @@ -168,21 +169,21 @@ describe('#35891 the stage tag opens a menu of every stage', () => { it('picking a reachable stage confirms, then writes the stage with the record version and re-reads', async () => { const { dataSource, refresh } = mount(); fireEvent.click(item(openMenu(), 'Negotiation')); - const dialog = await screen.findByRole('alertdialog'); + const dialog = await screen.findByRole('dialog'); expect(within(dialog).getByText('Move this record to Negotiation?')).toBeInTheDocument(); fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); expect(dataSource.update).toHaveBeenCalledWith('crm_opportunity', 'o1', { stage: 'negotiation' }, { ifMatch: VERSION }); await waitFor(() => expect(refresh).toHaveBeenCalled()); - await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); }); it('cancelling writes nothing', async () => { const { dataSource } = mount(); fireEvent.click(item(openMenu(), 'Negotiation')); - const dialog = await screen.findByRole('alertdialog'); + const dialog = await screen.findByRole('dialog'); fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); - await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); expect(dataSource.update).not.toHaveBeenCalled(); }); }); @@ -196,9 +197,9 @@ describe('#35891 a stage that needs more fields asks for them', () => { it('Closed Lost asks for the loss reason only, and writes it with the move', async () => { const { dataSource } = mount(); fireEvent.click(item(openMenu(), 'Closed Lost')); - const dialog = await screen.findByRole('alertdialog'); + const dialog = await screen.findByRole('dialog'); expect(within(dialog).getByText('To move this record to Closed Lost, fill in:')).toBeInTheDocument(); - const fields = Array.from(dialog.querySelectorAll('[data-stage-change-field]')).map((el) => el.getAttribute('data-stage-change-field')); + const fields = Array.from(dialog.querySelectorAll('[data-required-fields-field]')).map((el) => el.getAttribute('data-required-fields-field')); expect(fields).toEqual(['loss_reason']); fireEvent.change(within(dialog).getByRole('textbox'), { target: { value: 'Price' } }); fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); @@ -206,20 +207,27 @@ describe('#35891 a stage that needs more fields asks for them', () => { expect(dataSource.update).toHaveBeenCalledWith( 'crm_opportunity', 'o1', { stage: 'closed_lost', loss_reason: 'Price' }, { ifMatch: VERSION }, ); - await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); }); - it('left empty, the server refusal names the field in the dialog and the stage does not move', async () => { + it('left empty, Move says the field is required and writes nothing; a server refusal of the value reads under the field', async () => { const dataSource = makeDataSource(async () => { throw lossRefusal(); }); const { refresh } = mount({ dataSource }); fireEvent.click(item(openMenu(), 'Closed Lost')); - const dialog = await screen.findByRole('alertdialog'); + const dialog = await screen.findByRole('dialog'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + // The shared dialog's own presence check (objectstack#35956): no write. + await waitFor(() => expect(dialog.querySelector('[data-required-fields-error="loss_reason"]')).not.toBeNull()); + expect(within(dialog).getByText('Required')).toBeInTheDocument(); + expect(dataSource.update).not.toHaveBeenCalled(); + // Filled, the server still refuses: still open, its reason beside the + // field, nothing re-read, the stage not moved. + fireEvent.change(within(dialog).getByRole('textbox'), { target: { value: 'x' } }); fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); - // Still open, the reason beside the field, nothing re-read. - const open = await screen.findByRole('alertdialog'); - expect(within(open).getByText('Loss Reason is required to close as lost')).toBeInTheDocument(); - expect(open.querySelector('[data-stage-change-field-error="loss_reason"]')).not.toBeNull(); + const open = await screen.findByRole('dialog'); + await waitFor(() => expect(within(open).getByText('Loss Reason is required to close as lost')).toBeInTheDocument()); + expect(open.querySelector('[data-required-fields-error="loss_reason"]')).not.toBeNull(); expect(refresh).not.toHaveBeenCalled(); }); @@ -231,12 +239,12 @@ describe('#35891 a stage that needs more fields asks for them', () => { const dataSource = makeDataSource(async () => { throw amountRefusal; }); mount({ dataSource }); fireEvent.click(item(openMenu(), 'Negotiation')); - let dialog = await screen.findByRole('alertdialog'); - expect(dialog.querySelector('[data-stage-change-field]')).toBeNull(); + let dialog = await screen.findByRole('dialog'); + expect(dialog.querySelector('[data-required-fields-field]')).toBeNull(); fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); - dialog = await screen.findByRole('alertdialog'); - await waitFor(() => expect(dialog.querySelector('[data-stage-change-field="name"]')).not.toBeNull()); + dialog = await screen.findByRole('dialog'); + await waitFor(() => expect(dialog.querySelector('[data-required-fields-field="name"]')).not.toBeNull()); expect(within(dialog).getByText('Name is required to negotiate')).toBeInTheDocument(); }); @@ -248,14 +256,153 @@ describe('#35891 a stage that needs more fields asks for them', () => { const dataSource = makeDataSource(async () => { throw machineRefusal; }); mount({ dataSource }); fireEvent.click(item(openMenu(), 'Negotiation')); - const dialog = await screen.findByRole('alertdialog'); + const dialog = await screen.findByRole('dialog'); fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); - const open = await screen.findByRole('alertdialog'); + const open = await screen.findByRole('dialog'); await waitFor(() => expect(within(open).getByText('A deal cannot skip negotiation.')).toBeInTheDocument()); }); }); +describe('#35956 the stage menu opens the shared fill-in dialog', () => { + // Two more conditional fields: one a typed loss reason makes required in + // turn, and one rich-text field the dialog has no in-place editor for. + const CHAINED = { + ...OPPORTUNITY, + fields: { + ...OPPORTUNITY.fields, + loss_detail: { + type: 'text', + label: 'Loss Detail', + requiredWhen: 'has(record.loss_reason) && record.loss_reason == "other"', + }, + negotiation_memo: { + type: 'richtext', + label: 'Negotiation Memo', + requiredWhen: 'has(record.stage) && record.stage == "negotiation"', + }, + }, + } as unknown as typeof OPPORTUNITY; + + const footOf = (dialog: HTMLElement) => waitFor(() => { + const el = dialog.querySelector('[data-required-fields-refusal]') as HTMLElement | null; + expect(el).not.toBeNull(); + return el as HTMLElement; + }); + + const fieldsShown = (dialog: HTMLElement) => + Array.from(dialog.querySelectorAll('[data-required-fields-field]')).map((el) => el.getAttribute('data-required-fields-field')); + + it('is the one shared dialog: the record name and the move, read-only, above the field', async () => { + mount(); + fireEvent.click(item(openMenu(), 'Closed Lost')); + const dialog = await screen.findByRole('dialog'); + expect(dialog).toHaveAttribute('data-testid', 'required-fields-dialog'); + const change = dialog.querySelector('[data-required-fields-change]') as HTMLElement; + expect(within(change).getByText('Wayne deal')).toBeInTheDocument(); + const row = change.querySelector('[data-required-fields-change-row="stage"]') as HTMLElement; + expect(row).toHaveTextContent('Stage:Closed Lost'); + expect(within(row).queryByRole('textbox')).toBeNull(); + // The surface's own copy of the old form is gone. + expect(dialog.querySelector('[data-stage-change-fields]')).toBeNull(); + }); + + it('a stage that needs nothing opens the same dialog as the move confirmation, no fields', async () => { + mount(); + fireEvent.click(item(openMenu(), 'Negotiation')); + const dialog = await screen.findByRole('dialog'); + expect(dialog).toHaveAttribute('data-testid', 'required-fields-dialog'); + expect(fieldsShown(dialog)).toEqual([]); + expect(within(dialog).getByText('Change stage?')).toBeInTheDocument(); + expect(dialog.querySelector('[data-required-fields-change-row="stage"]')).toHaveTextContent('Stage:Negotiation'); + }); + + it('a value typed in the dialog that makes one more field required adds it, and Move waits for it', async () => { + const { dataSource } = mount({ schema: CHAINED }); + fireEvent.click(item(openMenu(), 'Closed Lost')); + const dialog = await screen.findByRole('dialog'); + expect(fieldsShown(dialog)).toEqual(['loss_reason']); + fireEvent.change(within(dialog).getByRole('textbox'), { target: { value: 'other' } }); + await waitFor(() => expect(fieldsShown(dialog)).toEqual(['loss_reason', 'loss_detail'])); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + // Empty, the chained field says so and nothing is written. + await waitFor(() => expect(dialog.querySelector('[data-required-fields-error="loss_detail"]')).not.toBeNull()); + expect(dataSource.update).not.toHaveBeenCalled(); + const detail = dialog.querySelector('[data-required-fields-field="loss_detail"]') as HTMLElement; + fireEvent.change(within(detail).getByRole('textbox'), { target: { value: 'Went with a competitor' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); + expect(dataSource.update).toHaveBeenCalledWith( + 'crm_opportunity', 'o1', + { stage: 'closed_lost', loss_reason: 'other', loss_detail: 'Went with a competitor' }, + { ifMatch: VERSION }, + ); + }); + + it('control: a required field with no in-place editor (rich text) is not asked; the server judges the move', async () => { + const richRefusal = Object.assign(new Error('VALIDATION_FAILED'), { + code: 'VALIDATION_FAILED', + fields: [{ field: 'negotiation_memo', code: 'required', message: 'Negotiation Memo is required' }], + }); + const dataSource = makeDataSource(async () => { throw richRefusal; }); + mount({ schema: CHAINED, dataSource }); + fireEvent.click(item(openMenu(), 'Negotiation')); + const dialog = await screen.findByRole('dialog'); + expect(fieldsShown(dialog)).toEqual([]); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + await waitFor(() => expect(dataSource.update).toHaveBeenCalledWith( + 'crm_opportunity', 'o1', { stage: 'negotiation' }, { ifMatch: VERSION }, + )); + // Not added as a row (nothing to type it into): its reason reads at the foot. + const foot = await footOf(dialog); + expect(foot).toHaveTextContent('Negotiation Memo: Negotiation Memo is required'); + expect(fieldsShown(dialog)).toEqual([]); + }); + + it('someone else changed the record: the dialog stays, says so at its foot, and the record is re-read', async () => { + const conflict = Object.assign(new Error('CONCURRENT_UPDATE'), { code: 'CONCURRENT_UPDATE', status: 409 }); + const dataSource = makeDataSource(async () => { throw conflict; }); + const { refresh } = mount({ dataSource }); + fireEvent.click(item(openMenu(), 'Closed Lost')); + const dialog = await screen.findByRole('dialog'); + fireEvent.change(within(dialog).getByRole('textbox'), { target: { value: 'Price' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1)); + const foot = await footOf(dialog); + expect(foot).toHaveTextContent('Someone else changed this record'); + // The typed value is still there for the next press. + expect(within(dialog).getByRole('textbox')).toHaveValue('Price'); + }); + + it('a permission refusal reads as the stage line at the foot, never the raw 403', async () => { + const denied = Object.assign(new Error('403 Forbidden {"error":"permission denied: crm_opportunity.update"}'), { + code: 'PERMISSION_DENIED', + status: 403, + }); + const dataSource = makeDataSource(async () => { throw denied; }); + mount({ dataSource }); + fireEvent.click(item(openMenu(), 'Negotiation')); + const dialog = await screen.findByRole('dialog'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + const foot = await footOf(dialog); + expect(foot).toHaveTextContent("You don't have permission to change this record's stage."); + expect(foot).not.toHaveTextContent('permission denied'); + }); + + it('Cancel writes nothing and the next pick starts empty', async () => { + const { dataSource } = mount(); + fireEvent.click(item(openMenu(), 'Closed Lost')); + let dialog = await screen.findByRole('dialog'); + fireEvent.change(within(dialog).getByRole('textbox'), { target: { value: 'Price' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + expect(dataSource.update).not.toHaveBeenCalled(); + fireEvent.click(item(openMenu(), 'Closed Lost')); + dialog = await screen.findByRole('dialog'); + expect(within(dialog).getByRole('textbox')).toHaveValue(''); + }); +}); + describe('#35891 who sees the plain tag', () => { it('a reader the page may not let edit (an approval lock included) sees the tag, no arrow', () => { mount({ canEdit: false }); @@ -292,14 +439,14 @@ describe('#35891 the keyboard', () => { it('the confirm dialog opens on Move, so Enter confirms the stage it names', async () => { mount(); fireEvent.click(item(openMenu(), 'Negotiation')); - const dialog = await screen.findByRole('alertdialog'); + const dialog = await screen.findByRole('dialog'); await waitFor(() => expect(within(dialog).getByRole('button', { name: 'Move' })).toHaveFocus()); }); it('a stage that needs a field opens with that field focused', async () => { mount(); fireEvent.click(item(openMenu(), 'Closed Lost')); - const dialog = await screen.findByRole('alertdialog'); + const dialog = await screen.findByRole('dialog'); await waitFor(() => expect(within(dialog).getByRole('textbox')).toHaveFocus()); }); diff --git a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx index a5c7d351e0f..5d599d0d453 100644 --- a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx +++ b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx @@ -38,18 +38,23 @@ * every app with a machine on its stage field. A field without such a rule * offers every stage, and the server still judges each write. * - * ## The fields a stage needs (`collectFields`, objectstack#35891) + * ## The fields a stage needs (`collectFields`, objectstack#35891, #35956) * * The header's stage menu (`RecordStageMenu`) asks for more than a yes: a * stage that makes other fields required — a field whose `requiredWhen` holds * once the record stands on it and is empty now, such as a loss reason on - * 「失败」 — opens the confirmation with just those fields, and the move and - * their values go in ONE write. Which fields to ask for is presentation; the - * server still judges the write (objectui#6868: it is the only validation - * authority on this surface). A refusal that names fields the reader may fill - * keeps the form open with those fields added and each one's reason beside - * it, and the stage does not move. `record:path` leaves the option off and - * keeps its plain confirmation. + * 「失败」 — asks for just those fields, and the move and their values go in + * ONE write. Both halves are the shared in-place fill-in of `@object-ui/fields` + * (objectstack#35956): `collectRequiredWhenPromptFields` picks the fields and + * `RequiredFieldsDialog` collects them, the same pair the list cell, the + * record page's inline Save and the board use, so this surface keeps no copy + * of its own. Which fields to ask for is presentation; the server still judges + * the write (objectui#6868: it is the only validation authority on this + * surface). A refusal stays in the dialog and the stage does not move: a + * reason that names a field shown is drawn under it, one that names a field + * the reader may fill adds that field, any other reads at the dialog's foot. + * A stage that needs nothing opens the same dialog as the move's confirmation. + * `record:path` leaves the option off and keeps its plain confirmation. */ import React from 'react'; @@ -62,14 +67,19 @@ import { AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, - Button, } from '@object-ui/components'; import { - isMissingForRequired, + getRecordDisplayName, resolveFieldAffordance, - resolveFieldRuleState, stateMachineNextValues, } from '@object-ui/core'; +import { + collectRequiredWhenPromptFields, + hasFieldEditWidget, + RequiredFieldsDialog, + type RequiredFieldsDialogField, + type RequiredWhenPromptField, +} from '@object-ui/fields'; import { usePermissions } from '@object-ui/permissions'; import { declaredUserMessage, @@ -86,8 +96,6 @@ import { pickLocalized, useObjectTranslation } from '@object-ui/i18n'; import { isComputedDetailField } from '../fieldEnrichment'; import { NON_EDITABLE_SYSTEM_FIELDS } from '../systemFields'; import { updateVia } from '../InlineEditSaveBar'; -import { InlineFieldInput } from '../InlineFieldInput'; -import { enrichDetailField } from '../fieldEnrichment'; import { isConcurrentUpdateError } from '../ConcurrentUpdateDialog'; import { useDetailTranslation } from '../useDetailTranslation'; @@ -180,8 +188,8 @@ export interface StageChangeOptions { collectFields?: boolean; } -/** A pending move: the stage, and the fields its confirmation asks for. */ -type StageTarget = { value: unknown; label: string; fields: string[] }; +/** A pending move: the stage, and the fields its dialog asks for. */ +type StageTarget = { value: unknown; label: string; fields: RequiredWhenPromptField[] }; export function useStageChange( allowStageChange: boolean, @@ -193,21 +201,18 @@ export function useStageChange( const inline = useInlineEdit(); const perms = usePermissions(); const { t } = useDetailTranslation(); - const { fieldLabel } = useSafeFieldLabel(); + const { fieldLabel, translateOptions } = useSafeFieldLabel(); const { language } = useObjectTranslation(); const [target, setTarget] = React.useState(null); const [busy, setBusy] = React.useState(false); const [refusal, setRefusal] = React.useState(null); - // The confirmation's own fields (`collectFields`): their values, and the - // server's reason for each one it refused on the last try. - const [values, setValues] = React.useState>({}); - const [fieldErrors, setFieldErrors] = React.useState>({}); - const [formLines, setFormLines] = React.useState(null); const objectName = ctx?.objectName; const recordId = ctx?.recordId; const dataSource = ctx?.dataSource; - const fieldDef = statusField ? fieldDefOf(ctx?.objectSchema, statusField) : undefined; + const objectSchema = ctx?.objectSchema; + const objectFields = (objectSchema as { fields?: Record } | null | undefined)?.fields; + const fieldDef = statusField ? fieldDefOf(objectSchema, statusField) : undefined; const pressable = allowStageChange && !!statusField @@ -222,72 +227,54 @@ export function useStageChange( && !NON_EDITABLE_SYSTEM_FIELDS.has(statusField) && resolveFieldAffordance('recordEdit', perms, objectName, statusField); - const stored = statusField ? (ctx?.data as Record | undefined)?.[statusField] : undefined; - const reachable = statusField ? stateMachineNextValues(ctx?.objectSchema, statusField, stored) : null; + const record = (ctx?.data ?? {}) as Record; + const stored = statusField ? record[statusField] : undefined; + const reachable = statusField ? stateMachineNextValues(objectSchema, statusField, stored) : null; const admits = (value: unknown): boolean => reachable === null || reachable.has(String(value)); - // A field this reader may fill in the confirmation: the same question the - // record page's other in-place editors ask of a field. - const fillable = (field: string): boolean => { - const def = fieldDefOf(ctx?.objectSchema, field); - return !!def - && field !== statusField - && def.readonly !== true - && !isComputedDetailField(undefined, def) - && !NON_EDITABLE_SYSTEM_FIELDS.has(field) - && !!objectName - && resolveFieldAffordance('recordEdit', perms, objectName, field); - }; + // A field this reader may fill in the stage dialog: the question the record + // page's other in-place editors ask of a field (`InlineEditSaveBar`'s + // fill-in asks the same one). + const fillable = (name: string, def: Record): boolean => + name !== statusField + && def.readonly !== true + && !isComputedDetailField(undefined, def as FieldDef) + && !NON_EDITABLE_SYSTEM_FIELDS.has(name) + && !!objectName + && resolveFieldAffordance('recordEdit', perms, objectName, name); - // The empty fields whose `requiredWhen` holds once the record stands on - // `value`, judged as the engine's transition gate judges them (the stored - // row is `previous`), and that are shown and writable there. - const fieldsNeededAt = (value: unknown): string[] => { - if (!collectFields || !statusField) return []; - const fields = (ctx?.objectSchema as { fields?: Record } | undefined)?.fields ?? {}; - const record = (ctx?.data ?? {}) as Record; - const moved = { ...record, [statusField]: value }; - const out: string[] = []; - for (const [name, def] of Object.entries(fields)) { - if (!def || def.requiredWhen == null || !fillable(name)) continue; - if (!isMissingForRequired(record[name])) continue; - const state = resolveFieldRuleState( - { visibleWhen: def.visibleWhen, readonlyWhen: def.readonlyWhen, requiredWhen: def.requiredWhen }, - moved, - { required: def.required === true, readonly: def.readonly === true, name }, - record, - undefined, - `field '${name}'`, - ); - if (state.visible && !state.readonly && state.required) out.push(name); - } - return out; - }; + // The empty fields the move makes required, judged by the shared prompt + // (`@object-ui/fields`, objectstack#35956): the evaluator the form and the + // server share, as the engine's transition gate judges the write. + const fieldsNeededAt = (value: unknown): RequiredWhenPromptField[] => + collectFields && statusField + ? collectRequiredWhenPromptFields(objectFields, record, { [statusField]: value }, { fillable }) + : []; const request = (stage: { value: unknown; label: string }) => { setRefusal(null); - setValues({}); - setFieldErrors({}); - setFormLines(null); setTarget({ value: stage.value, label: stage.label, fields: fieldsNeededAt(stage.value) }); }; const labelOf = (field: string): string => { - const declared = fieldDefOf(ctx?.objectSchema, field)?.label; + const declared = fieldDefOf(objectSchema, field)?.label; const fallback = declared == null ? field : String(pickLocalized(declared as Parameters[0], language) ?? field); return objectName ? fieldLabel(objectName, field, fallback) : fallback; }; + const ifMatchOf = (): { ifMatch: string } | undefined => { + const updatedAt = record.updated_at; + return typeof updatedAt === 'string' ? { ifMatch: updatedAt } : undefined; + }; + + // `record:path`: a yes, then the move alone; a refusal reads under the rail. const confirm = async () => { const stage = target; - if (collectFields) return confirmWithFields(stage); setTarget(null); if (!stage || !pressable || !admits(stage.value)) return; setBusy(true); - const updatedAt = (ctx?.data as Record | undefined)?.updated_at; - const ifMatch = typeof updatedAt === 'string' ? updatedAt : undefined; try { - await updateVia(dataSource, objectName!, recordId!, { [statusField!]: stage.value }, ifMatch ? { ifMatch } : undefined); + await updateVia(dataSource, objectName!, recordId!, { [statusField!]: stage.value }, ifMatchOf()); await ctx?.refresh?.(); } catch (err) { setRefusal(stageRefusalLines(err, statusField!, labelOf, t)); @@ -299,140 +286,105 @@ export function useStageChange( } }; - // `collectFields`: the move and the asked-for fields in one write. The - // confirmation stays open until the write lands; a refusal is shown in it, - // never only after it closed, and the stage does not move. - const confirmWithFields = async (stage: StageTarget | null) => { - if (!stage || !pressable || !admits(stage.value) || busy) return; - setBusy(true); - setFieldErrors({}); - setFormLines(null); - const updatedAt = (ctx?.data as Record | undefined)?.updated_at; - const ifMatch = typeof updatedAt === 'string' ? updatedAt : undefined; - const payload: Record = { [statusField!]: stage.value }; - for (const field of stage.fields) { - if (Object.prototype.hasOwnProperty.call(values, field)) payload[field] = values[field]; + // `collectFields`: the move and the typed values in ONE write, from the + // shared dialog. A rejection keeps the dialog open: a refusal that names + // fields goes to the dialog as it came (each reason under its field, a + // fillable field it names joins the dialog); every other refusal reads as + // this surface's own line at the dialog's foot. The stage does not move. + const submitWithFields = async (stage: StageTarget, values: Record) => { + if (!pressable || !admits(stage.value)) { + setTarget(null); + return; } + setBusy(true); try { - await updateVia(dataSource, objectName!, recordId!, payload, ifMatch ? { ifMatch } : undefined); - setTarget(null); - await ctx?.refresh?.(); + await updateVia(dataSource, objectName!, recordId!, { ...values, [statusField!]: stage.value }, ifMatchOf()); } catch (err) { - // The fields the refusal names that this reader may fill join the - // form, each with its reason; every other line reads under the form. - const named = isConcurrentUpdateError(err) ? [] : (extractFieldErrors(err) ?? []); - const byField: Record = {}; - for (const e of named) { - if (e.message && fillable(e.field)) byField[e.field] = e.message; - } - const asked = Object.keys(byField); - if (asked.length > 0) { - setTarget({ ...stage, fields: [...stage.fields, ...asked.filter((f) => !stage.fields.includes(f))] }); - setFieldErrors(byField); - } - const rest = asked.length > 0 - ? named.filter((e) => e.message && !(e.field in byField)).map((e) => - e.field === statusField || e.field === RECORD_LEVEL_FIELD ? e.message : `${labelOf(e.field)}: ${e.message}`) - : stageRefusalLines(err, statusField!, labelOf, t); - setFormLines(rest.length > 0 ? rest : null); - if (isConcurrentUpdateError(err)) await ctx?.refresh?.(); + const concurrent = isConcurrentUpdateError(err); + if (concurrent) await ctx?.refresh?.(); + const named = concurrent ? [] : (extractFieldErrors(err) ?? []).filter((e) => !!e.message); + if (named.length > 0 && !declaredUserMessage(err)) throw err; + const line = stageRefusalLines(err, statusField!, labelOf, t).join(' '); + throw Object.assign(new Error(line), { userMessage: line }); } finally { setBusy(false); } + setTarget(null); + await ctx?.refresh?.(); }; - const record = (ctx?.data ?? {}) as Record; - const staged = { ...record, ...values, ...(target && statusField ? { [statusField]: target.value } : {}) }; - const fieldsBody = collectFields && target && target.fields.length > 0 ? ( -
- {target.fields.map((field) => { - const def = fieldDefOf(ctx?.objectSchema, field) as Record | undefined; - const enriched = enrichDetailField({ name: field, label: labelOf(field), type: def?.type ?? 'text' }, def); - const error = fieldErrors[field]; - const id = `stage-change-field-${field}`; - return ( -
- -
- setValues((prev) => ({ ...prev, [field]: v }))} - dataSource={dataSource} - autoFocus={field === target.fields[0]} - error={error} - dependentValues={staged} - /> -
- {error && ( -

- {error} -

- )} -
- ); - })} -
- ) : null; - - const dialog = ( - { if (!open && !(collectFields && busy)) setTarget(null); }} - > - { - // An alert dialog focuses Cancel on open. The stage menu's dialog is - // one the reader opened by picking a stage, so Enter confirms the - // move (objectstack#35891): focus the first field it asks for, or - // the confirm button when it asks for none. - const content = event.currentTarget as HTMLElement | null; - const first = content?.querySelector( - '[data-stage-change-fields] input, [data-stage-change-fields] textarea, [data-stage-change-fields] button, [data-stage-change-fields] [role="combobox"]', - ) ?? content?.querySelector('[data-stage-change-confirm]'); - if (first) { - event.preventDefault(); - first.focus(); - } - } : undefined} - > - - {t('detail.pathStageChangeTitle')} - - {fieldsBody - ? t('detail.stageMenuFieldsDescription', { stage: target?.label ?? '' }) - : t('detail.pathStageChangeDescription', { stage: target?.label ?? '' })} - - - {fieldsBody} - {collectFields && formLines && ( -
- {formLines.map((line, i) =>

{line}

)} -
- )} - - {t('detail.cancel')} - {collectFields ? ( - - ) : ( + const dialog = collectFields + ? renderFieldsDialog() + : ( + { if (!open) setTarget(null); }}> + + + {t('detail.pathStageChangeTitle')} + + {t('detail.pathStageChangeDescription', { stage: target?.label ?? '' })} + + + + {t('detail.cancel')} { void confirm(); }}> {t('detail.pathStageChangeConfirm')} - )} - - - - ); + +
+
+ ); + + /** + * The header menu's dialog: the shared `RequiredFieldsDialog` the list cell, + * the record page's inline Save and the board open (objectstack#35956). It + * names the record and the move, then the fields the move needs — none for + * most stages, when it is the move's confirmation and opens on its button, + * so Enter confirms (objectstack#35891). + */ + function renderFieldsDialog(): React.ReactNode { + if (!target || !statusField) return null; + const stage = target; + const objectKey = objectName ?? ''; + const label = (f: RequiredWhenPromptField): RequiredFieldsDialogField => { + const opts = f.def.options; + const localized = objectKey && Array.isArray(opts) ? translateOptions(objectKey, f.name, opts) : opts; + return { ...f, def: { ...f.def, ...(localized ? { options: localized } : {}) }, label: labelOf(f.name) }; + }; + const exclude = [statusField]; + return ( + collectRequiredWhenPromptFields( + objectFields, + record, + { ...values, [statusField]: stage.value }, + { exclude, fillable }, + ).map(label)} + refusalField={(name) => { + const def = objectFields?.[name] as Record | undefined; + if (!def || typeof def !== 'object' || name === statusField) return null; + if (!hasFieldEditWidget(def.type as string | undefined) || !fillable(name, def)) return null; + return label({ name, def: { name, ...def } }); + }} + // The stage field and an object-level (`_record`) reason read alone, + // as `stageRefusalLines` reads them; another field by its label. + labelOf={(name) => (name !== statusField && objectFields?.[name] ? labelOf(name) : undefined)} + title={t('detail.pathStageChangeTitle')} + description={stage.fields.length > 0 + ? t('detail.stageMenuFieldsDescription', { stage: stage.label }) + : t('detail.pathStageChangeDescription', { stage: stage.label })} + submitLabel={t('detail.pathStageChangeConfirm')} + onCancel={() => setTarget(null)} + onSubmit={(values) => submitWithFields(stage, values)} + /> + ); + } return { pressable, admits, busy, refusal, request, dialog }; } From 0477e86e3dcc3c481c4e917440d92788359dbc49 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:53:34 +0000 Subject: [PATCH 2/2] test(fields): the fill-in dialog with nothing to fill focuses its submit button Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgWV6ouxRg2fByapa6F --- ...equiredFieldsDialog.inPlace-35956.test.tsx | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/ui/packages/fields/src/__tests__/RequiredFieldsDialog.inPlace-35956.test.tsx b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.inPlace-35956.test.tsx index c04ef0ac827..5de14f0c879 100644 --- a/ui/packages/fields/src/__tests__/RequiredFieldsDialog.inPlace-35956.test.tsx +++ b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.inPlace-35956.test.tsx @@ -138,3 +138,30 @@ describe('RequiredFieldsDialog in place (objectstack#35956)', () => { expect(onSubmit).not.toHaveBeenCalled(); }); }); + +describe('RequiredFieldsDialog with nothing to fill (objectstack#35956 PR 2, the stage menu)', () => { + it('is the change confirmation: Save takes the focus, and Save submits at once', async () => { + const onSubmit = vi.fn(); + render( + , + ); + const dialog = screen.getByTestId('required-fields-dialog'); + expect(dialog.querySelector('[data-required-fields-field]')).toBeNull(); + await waitFor(() => expect(within(dialog).getByRole('button', { name: 'Move' })).toHaveFocus()); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + await waitFor(() => expect(onSubmit).toHaveBeenCalledWith({})); + }); + + it('control: with a field to fill, that field takes the focus, not Save', async () => { + const dialog = renderDialog(vi.fn()); + await waitFor(() => expect(textboxOf(dialog, 'win_reason')).toHaveFocus()); + }); +});