diff --git a/.changeset/35956-required-fill-in-in-place.md b/.changeset/35956-required-fill-in-in-place.md new file mode 100644 index 00000000000..a826a78a13b --- /dev/null +++ b/.changeset/35956-required-fill-in-in-place.md @@ -0,0 +1,22 @@ +--- +'@object-ui/fields': patch +'@object-ui/plugin-kanban': patch +'@object-ui/plugin-grid': patch +'@object-ui/plugin-detail': patch +'@object-ui/i18n': patch +--- + +feat(list,detail): a change that makes other fields required asks for them in place — the kanban drop's fill-in, now shared by the list cell and the record page + +Clause-②: yes (widening) — `@object-ui/fields` exports `collectRequiredWhenPromptFields`, `RequiredFieldsDialog` and their types (moved from `@object-ui/plugin-kanban`, which never exported them) and the new `requiredWhenPromptReads`; nothing removed or renamed +Metadata-protocol: none + +When a value about to be written makes another field's `requiredWhen` true while that field is still empty, the write is held and one dialog asks for the missing values: + +- **Where:** a list cell in the select-first grid every `ListView` draws, the record page's inline Save, and the kanban drop (as before). +- **What it shows:** the record's name, the change that set it off (read-only), and one row per field to fill, with the editors the record form uses. A value typed there that makes one more field required adds that field; Save waits for it. +- **Save** writes the change and the typed values as ONE update. **Cancel** writes nothing: the list cell keeps its value; on the record page the edit session and its draft stay. +- **A refusal of that update stays in the dialog:** under the field it names, as a new row for another field the reader can fill, or at the dialog's foot. +- **Not asked for**, and written and refused as before: a field that already has a value, is hidden or read-only, that the reader may not write, or that has no in-place editor (a file, rich text, a formula). The record drawer's per-field save does not ask either. + +The pre-evaluation is the one the kanban drop already used (`resolveFieldRuleState`, the evaluator the form and the server share, judged as the engine's transition gate), generalised from one key to any set of changed keys. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 26a95d8bc1d..6e68c838161 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -447,6 +447,19 @@ row whose new value would sort it elsewhere stays in place until the next load trigger related automation."). Cancel writes nothing and the cell keeps the value it had; Change saves it as any commit is saved. The confirm does not list the flows. A host asks this through `GridCellSelection.confirmCommit`. +- **A change that makes other fields required asks for them** (objectstack#35956). + When the new value makes a field's `requiredWhen` true while that field is + still empty (a win reason on "Won", say), nothing is written yet: a dialog + names the record and the change and asks for those fields, with the editors + the record form uses, whether or not the view draws them as columns. A value + typed there that makes one more field required adds it. Save writes the cell + and the typed values as one update; Cancel writes nothing and the cell keeps + its value. A refusal of that update stays in the dialog, under the field it + names. That dialog is the confirmation, so a state-machine field does not ask + twice. A field that has a value, is hidden or read-only, the reader may not + write, or has no in-place editor (a file, rich text) is not asked for: the + change is saved and refused as before. The kanban drop and the record page's + inline Save open the same dialog (`RequiredFieldsDialog` in `@object-ui/fields`). - **The record drawer follows.** A record open in the list's drawer is read again when a list cell saves it. If the drawer holds unsaved edits of its own, those stay as typed, the drawer's save bar says the record was changed diff --git a/ui/packages/fields/src/RequiredFieldsDialog.tsx b/ui/packages/fields/src/RequiredFieldsDialog.tsx new file mode 100644 index 00000000000..a10ce9f7c95 --- /dev/null +++ b/ui/packages/fields/src/RequiredFieldsDialog.tsx @@ -0,0 +1,328 @@ +/** + * 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. + */ + +/** + * The small collect-then-save dialog an in-place change opens when it makes + * other fields required — objectui#4254 (the kanban drop), made shared by + * objectstack#35956 so a list cell and the record page's inline edit open the + * same one. The host decides WHEN to open it (`collectRequiredWhenPromptFields` + * returned fields) and owns the write; this dialog collects the values. + * + * ## What it shows + * + * The record's name, then the change that set this off as read-only rows + * (`changes`, e.g. 「销售阶段:赢单」), then one row per field to fill. Save + * hands the host the typed values, and the host writes them together with the + * change in ONE write; Cancel writes nothing. + * + * ## Chained requirements + * + * A value typed here can make one more field required (`moreFields`): it joins + * the dialog at once, nothing is saved half-way, and Save waits for it too. + * + * ## A refusal stays in the dialog + * + * When the host's `onSubmit` rejects (someone else changed the record, a rule + * the prompt could not foresee), the dialog stays open and says why: a reason + * naming a field shown here is drawn under that field; one naming another + * field the reader can fill adds that field (`refusalField`); every other + * reason is listed at the foot. A host whose `onSubmit` settles its own + * failures (the kanban board's toast and rollback) simply never rejects. + * + * ## Not a mini-form + * + * Every control here is {@link FieldEditWidget}, i.e. the SAME widget the + * record form renders for that field type (its own header: "the SAME dedicated + * widgets the form renders"), which is also what the data grid's inline editor + * and the detail page's inline edit compose. So a select edits as a select, a + * date as a date picker, a boolean as a checkbox — without a second set of + * field-rendering decisions that could drift from the form's. + * + * The validation is the same one definition too: `isMissingForRequired` from + * `@object-ui/core`, the presence contract the form and the server share, so + * this dialog cannot decide a value is "empty" in a way the server would + * disagree with (a `false` boolean and a `0` are values, not absences). + * + * ## Copy + * + * Through `useSafeTranslate` — the per-call `tt(key, fallback)` channel — so a + * host with no `I18nProvider` mounted (a standalone board, a package's tests, + * the preview gallery) reads English instead of a raw key. The host may pass + * its own `title`, `description` and `submitLabel` (the board keeps its + * 「移动卡片」). + */ + +import React from 'react'; +import { + Button, + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@object-ui/components'; +import { + useSafeTranslate, + declaredUserMessage, + extractFieldErrors, + extractWriteErrorMessage, +} from '@object-ui/react'; +import { isMissingForRequired } from '@object-ui/core'; +import { FieldEditWidget } from './FieldEditWidget.js'; +import type { RequiredWhenPromptField } from './requiredWhenPrompt.js'; + +/** A prompt field with its display label already resolved by the host. */ +export interface RequiredFieldsDialogField extends RequiredWhenPromptField { + label: string; +} + +/** One read-only row naming a value of the change that opened the dialog. */ +export interface RequiredFieldsDialogChange { + name: string; + label: string; + /** The value as the reader reads it (an option's label, not its code). */ + value: string; +} + +export interface RequiredFieldsDialogProps { + open: boolean; + /** The required-and-empty fields, in the object's declared order. */ + fields: RequiredFieldsDialogField[]; + /** Disables the controls while the host's write is in flight. */ + submitting?: boolean; + onCancel: () => void; + /** + * Called with the typed values once every field shown has one. The host + * writes them with its change; a rejection keeps the dialog open and shows + * the reason (see the file header). + */ + onSubmit: (values: Record) => void | Promise; + /** The record's display name, drawn first. */ + recordName?: string; + /** The change that set this off, drawn read-only above the fields. */ + changes?: RequiredFieldsDialogChange[]; + /** + * The fields the typed values make required in turn (chained requirements), + * asked on every change of the values; shown after `fields`, de-duplicated. + */ + moreFields?: (values: Record) => RequiredFieldsDialogField[]; + /** + * A field a refusal names that is not shown yet: the row to add for it, or + * `null` when the reader cannot fill it here (its reason is then listed at + * the foot). + */ + refusalField?: (name: string) => RequiredFieldsDialogField | null; + /** The label of a field a foot line names; `undefined` reads the reason alone. */ + labelOf?: (name: string) => string | undefined; + title?: string; + description?: string; + submitLabel?: string; +} + +/** The reasons a rejected submit carries: per field, and the rest. */ +function refusalOf(err: unknown): { entries: Array<{ field: string; message: string }>; fallback: string | null } { + const entries = (extractFieldErrors(err) ?? []) + .filter((e) => typeof e.message === 'string' && e.message.length > 0) + .map((e) => ({ field: e.field, message: e.message as string })); + return { entries, fallback: entries.length > 0 ? null : declaredUserMessage(err) ?? extractWriteErrorMessage(err) ?? null }; +} + +export function RequiredFieldsDialog({ + open, + fields, + submitting, + onCancel, + onSubmit, + recordName, + changes, + moreFields, + refusalField, + labelOf, + title, + description, + submitLabel, +}: RequiredFieldsDialogProps): React.ReactElement { + const tt = useSafeTranslate(); + // Each change is its own collection, and that is enforced by MOUNTING rather + // than by a reset effect: hosts render this component only while a change is + // pending, so cancelling or saving unmounts it and the next change starts + // from empty state. A `useEffect` re-seed would be both redundant and a + // cascading-render hazard the lint rule correctly flags. + const [values, setValues] = React.useState>({}); + // True only after a submit attempt, so the dialog opens clean rather than + // shouting "Required" at fields the user has not reached yet. + const [showErrors, setShowErrors] = React.useState(false); + // The last refusal: per-field reasons, the fields it added, the foot lines. + const [serverErrors, setServerErrors] = React.useState>({}); + const [addedFields, setAddedFields] = React.useState([]); + const [footLines, setFootLines] = React.useState([]); + const [sending, setSending] = React.useState(false); + const busy = !!submitting || sending; + + const shown: RequiredFieldsDialogField[] = []; + const seen = new Set(); + for (const f of [...fields, ...(moreFields?.(values) ?? []), ...addedFields]) { + if (seen.has(f.name)) continue; + seen.add(f.name); + shown.push(f); + } + const missing = shown.filter((f) => isMissingForRequired(values[f.name])); + + const presentRefusal = (err: unknown) => { + const { entries, fallback } = refusalOf(err); + const byField: Record = {}; + const added: RequiredFieldsDialogField[] = []; + const lines: string[] = []; + for (const { field, message } of entries) { + if (seen.has(field) || added.some((f) => f.name === field)) { + if (!(field in byField)) byField[field] = message; + continue; + } + const row = refusalField?.(field) ?? null; + if (row) { + added.push(row); + byField[field] = message; + continue; + } + const label = labelOf?.(field); + const line = label ? `${label}: ${message}` : message; + if (!lines.includes(line)) lines.push(line); + } + if (fallback) lines.push(fallback); + if (entries.length === 0 && !fallback) lines.push(tt('table.saveFailed', 'Save failed')); + setServerErrors(byField); + setAddedFields((prev) => [...prev, ...added.filter((f) => !prev.some((p) => p.name === f.name))]); + setFootLines(lines); + }; + + const handleSubmit = async () => { + if (busy) return; + if (missing.length > 0) { + setShowErrors(true); + return; + } + // Only the fields shown are sent: a value typed for a chained field that + // a later edit made unnecessary again stays out of the write. + const sent = Object.fromEntries(shown.map((f) => [f.name, values[f.name]])); + setFootLines([]); + setSending(true); + try { + await onSubmit(sent); + } catch (err) { + presentRefusal(err); + } finally { + setSending(false); + } + }; + + return ( + { if (!next && !busy) onCancel(); }}> + + + + {title ?? tt('fields.requiredPromptTitle', 'Complete required fields')} + + + {description ?? tt( + 'fields.requiredPromptDescription', + 'This change makes the fields below required. Fill them in to save it.', + )} + + + + {(recordName || (changes && changes.length > 0)) && ( +
+ {recordName && ( +

{recordName}

+ )} + {changes && changes.length > 0 && ( +
+ {changes.map((c) => ( +
+
{c.label}:
+
{c.value}
+
+ ))} +
+ )} +
+ )} + +
+ {shown.map((f) => { + const isMissing = isMissingForRequired(values[f.name]); + const message = serverErrors[f.name] + ?? (showErrors && isMissing ? tt('common.required', 'Required') : undefined); + return ( + // A wrapping `label` gives the control its accessible name + // implicitly. `FieldEditWidget` does take an `id` (objectui#7009 + // put it in `DOM_PASS_THROUGH_KEYS`), but this dialog renders + // whatever field types the change made required, and several of + // them resolve to COMPOSITE controls with no single labelable + // element for a `htmlFor` to point at — `RadioField` renders + // `
`, `CheckboxesField` `
`, `AddressField` a set of sibling inputs. One + // wrapping `label` covers every type uniformly and mints no ids. + + ); + })} +
+ + {footLines.length > 0 && ( +
+ {footLines.map((line) =>

{line}

)} +
+ )} + + + + + + +
+ ); +} diff --git a/ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.ariaInvalid-7008.test.tsx b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.ariaInvalid-7008.test.tsx similarity index 98% rename from ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.ariaInvalid-7008.test.tsx rename to ui/packages/fields/src/__tests__/RequiredFieldsDialog.ariaInvalid-7008.test.tsx index 704f82f6c2f..6d86c579c7f 100644 --- a/ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.ariaInvalid-7008.test.tsx +++ b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.ariaInvalid-7008.test.tsx @@ -84,7 +84,7 @@ describe('RequiredFieldsDialog tells assistive tech about a failed required fiel // after the click would prove nothing. expect(screen.getByTestId('select-trigger-stage')).toHaveAttribute('aria-invalid', 'false'); - fireEvent.click(screen.getByText('Move card')); + fireEvent.click(screen.getByText('Save')); // The submit is refused (that half already worked) … expect(onSubmit).not.toHaveBeenCalled(); @@ -117,7 +117,7 @@ describe('RequiredFieldsDialog tells assistive tech about a failed required fiel const notes = screen.getByRole('textbox'); fireEvent.change(notes, { target: { value: 'ready to move' } }); - fireEvent.click(screen.getByText('Move card')); + fireEvent.click(screen.getByText('Save')); // Still refused, because the select is still empty. expect(onSubmit).not.toHaveBeenCalled(); diff --git a/ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.ariaInvalidText-7126.test.tsx b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.ariaInvalidText-7126.test.tsx similarity index 99% rename from ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.ariaInvalidText-7126.test.tsx rename to ui/packages/fields/src/__tests__/RequiredFieldsDialog.ariaInvalidText-7126.test.tsx index 329d0f55b88..e5dc1e1a3fa 100644 --- a/ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.ariaInvalidText-7126.test.tsx +++ b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.ariaInvalidText-7126.test.tsx @@ -53,7 +53,7 @@ function textControl(name = 'title'): Element { return el; } -const moveCard = () => fireEvent.click(screen.getByText('Move card')); +const moveCard = () => fireEvent.click(screen.getByText('Save')); describe('RequiredFieldsDialog marks a failed required TEXT field (objectui#7126)', () => { it('a required text field reports aria-invalid once a submit attempt finds it empty', () => { diff --git a/ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.datePicker-12664.test.tsx b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.datePicker-12664.test.tsx similarity index 94% rename from ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.datePicker-12664.test.tsx rename to ui/packages/fields/src/__tests__/RequiredFieldsDialog.datePicker-12664.test.tsx index 324faa9199c..f1418d66a0d 100644 --- a/ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.datePicker-12664.test.tsx +++ b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.datePicker-12664.test.tsx @@ -11,7 +11,7 @@ * picker for a `date` / `datetime` field, through `FieldEditWidget`, and the * typed value reaches the submit. * - * The dialog is a form-shaped host: the user types, then presses "Move card", + * The dialog is a form-shaped host: the user types, then presses "Save", * which takes focus — and that blur is where the picker reads its text, as on * the action-param and bulk dialogs. Nothing in the dialog changed; this pins * that the inline factory's new face rides the dialog's existing seam. @@ -33,12 +33,12 @@ async function pickerBox(): Promise { }); } -/** Type into the box, then press "Move card" the way a pointer does: focus leaves the box first. */ +/** Type into the box, then press "Save" the way a pointer does: focus leaves the box first. */ function typeThenMove(input: HTMLInputElement, text: string) { input.focus(); fireEvent.change(input, { target: { value: text } }); fireEvent.blur(input); - fireEvent.click(screen.getByText('Move card')); + fireEvent.click(screen.getByText('Save')); } describe('RequiredFieldsDialog — date / datetime draw the platform picker (objectui#12664)', () => { diff --git a/ui/packages/fields/src/__tests__/RequiredFieldsDialog.inPlace-35956.test.tsx b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.inPlace-35956.test.tsx new file mode 100644 index 00000000000..c04ef0ac827 --- /dev/null +++ b/ui/packages/fields/src/__tests__/RequiredFieldsDialog.inPlace-35956.test.tsx @@ -0,0 +1,140 @@ +/** + * 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#35956 — the shared fill-in dialog: it names the record and the + * change that opened it, adds a field a typed value makes required, and keeps + * a refusal inside the dialog (under the field it names, as a new row for a + * field the reader can fill, or at the foot). + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { RequiredFieldsDialog, type RequiredFieldsDialogField } from '../RequiredFieldsDialog'; +import { collectRequiredWhenPromptFields } from '../requiredWhenPrompt'; + +afterEach(() => cleanup()); + +const OBJECT_FIELDS = { + stage: { type: 'select', label: 'Stage', options: [{ value: 'won', label: 'Won' }] }, + win_reason: { type: 'text', label: 'Win Reason', requiredWhen: 'record.stage == "won"' }, + competitor: { type: 'text', label: 'Competitor', requiredWhen: 'record.win_reason == "price"' }, + notes: { type: 'textarea', label: 'Notes' }, +}; +const RECORD = { id: 'o1', name: 'Acme deal', stage: 'open', win_reason: null, competitor: null }; +const CHANGE = { stage: 'won' }; + +const labelled = (fields: ReturnType): RequiredFieldsDialogField[] => + fields.map((f) => ({ ...f, label: String((f.def as { label?: unknown }).label ?? f.name) })); + +function renderDialog(onSubmit: (values: Record) => void | Promise, onCancel = vi.fn()) { + render( + labelled(collectRequiredWhenPromptFields( + OBJECT_FIELDS, + RECORD, + { ...CHANGE, ...values }, + { exclude: Object.keys(CHANGE) }, + ))} + refusalField={(name) => (name === 'notes' + ? { name, label: 'Notes', def: { name, ...OBJECT_FIELDS.notes } } + : null)} + labelOf={(name) => (name in OBJECT_FIELDS ? (OBJECT_FIELDS as Record)[name].label : undefined)} + onCancel={onCancel} + onSubmit={onSubmit} + />, + ); + return screen.getByTestId('required-fields-dialog'); +} + +const textboxOf = (dialog: HTMLElement, name: string) => + within(dialog.querySelector(`[data-required-fields-field="${name}"]`) as HTMLElement).getByRole('textbox'); + +describe('RequiredFieldsDialog in place (objectstack#35956)', () => { + it('names the record and the change that opened it, read-only, above the fields', () => { + const dialog = renderDialog(vi.fn()); + expect(within(dialog).getByText('Acme deal')).toBeInTheDocument(); + const row = dialog.querySelector('[data-required-fields-change-row="stage"]') as HTMLElement; + expect(row).toHaveTextContent('Stage:'); + expect(row).toHaveTextContent('Won'); + // The change is not an input. + expect(within(row).queryByRole('textbox')).toBeNull(); + expect(dialog.querySelector('[data-required-fields-field="win_reason"]')).not.toBeNull(); + }); + + it('adds the field a typed value makes required, and waits for it before saving', () => { + const onSubmit = vi.fn(); + const dialog = renderDialog(onSubmit); + // CONTROL: no Competitor row before the value that requires it. + expect(dialog.querySelector('[data-required-fields-field="competitor"]')).toBeNull(); + fireEvent.change(textboxOf(dialog, 'win_reason'), { target: { value: 'price' } }); + expect(dialog.querySelector('[data-required-fields-field="competitor"]')).not.toBeNull(); + + fireEvent.click(within(dialog).getByRole('button', { name: 'Save' })); + expect(onSubmit).not.toHaveBeenCalled(); + expect(within(dialog).getByText('Required')).toBeInTheDocument(); + + fireEvent.change(textboxOf(dialog, 'competitor'), { target: { value: 'Globex' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Save' })); + expect(onSubmit).toHaveBeenCalledTimes(1); + expect(onSubmit).toHaveBeenCalledWith({ win_reason: 'price', competitor: 'Globex' }); + }); + + it('keeps a refusal in the dialog: under its field, as a new row, or at the foot', async () => { + const refusal = Object.assign(new Error('Validation failed'), { + code: 'VALIDATION_FAILED', + details: { + fields: [ + { field: 'win_reason', message: 'Too short' }, + { field: 'notes', message: 'Notes are required' }, + { field: 'stage', message: 'Stage cannot move back' }, + ], + }, + }); + const onSubmit = vi.fn().mockRejectedValueOnce(refusal); + const onCancel = vi.fn(); + const dialog = renderDialog(onSubmit, onCancel); + fireEvent.change(textboxOf(dialog, 'win_reason'), { target: { value: 'x' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Save' })); + + await waitFor(() => + expect(dialog.querySelector('[data-required-fields-error="win_reason"]')).toHaveTextContent('Too short')); + // A field the reader can fill joins the dialog with its reason … + expect(dialog.querySelector('[data-required-fields-field="notes"]')).not.toBeNull(); + expect(dialog.querySelector('[data-required-fields-error="notes"]')).toHaveTextContent('Notes are required'); + // … and a reason about a field it cannot offer reads at the foot, named. + expect(dialog.querySelector('[data-required-fields-refusal]')).toHaveTextContent('Stage: Stage cannot move back'); + // The dialog did not close. + expect(onCancel).not.toHaveBeenCalled(); + expect(screen.getByTestId('required-fields-dialog')).toBeInTheDocument(); + }); + + it('a refusal naming no field reads at the foot', async () => { + const onSubmit = vi.fn().mockRejectedValueOnce(new Error('The record was changed by someone else')); + const dialog = renderDialog(onSubmit); + fireEvent.change(textboxOf(dialog, 'win_reason'), { target: { value: 'better fit' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Save' })); + await waitFor(() => + expect(dialog.querySelector('[data-required-fields-refusal]')).toHaveTextContent('The record was changed by someone else')); + }); + + it('Cancel hands back to the host and submits nothing', () => { + const onSubmit = vi.fn(); + const onCancel = vi.fn(); + const dialog = renderDialog(onSubmit, onCancel); + fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); + expect(onCancel).toHaveBeenCalledTimes(1); + expect(onSubmit).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index a5a0cbc06b1..e2fda6f7823 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -5355,6 +5355,21 @@ export { } from './widgets/file-value.js'; export type { FileValueView, UploadResultLike } from './widgets/file-value.js'; export * from './FieldEditWidget.js'; +// objectstack#35956 — the in-place fill-in a change opens when it makes other +// fields required: the pre-evaluation and the dialog, shared by the kanban +// drop, the list cell and the record page's inline edit. +export { + collectRequiredWhenPromptFields, + requiredWhenPromptReads, + type RequiredWhenPromptField, + type RequiredWhenPromptOptions, +} from './requiredWhenPrompt.js'; +export { + RequiredFieldsDialog, + type RequiredFieldsDialogField, + type RequiredFieldsDialogChange, + type RequiredFieldsDialogProps, +} from './RequiredFieldsDialog.js'; export * from './widgets/TextField.js'; export * from './widgets/NumberField.js'; export * from './widgets/BooleanField.js'; diff --git a/ui/packages/plugin-kanban/src/requiredWhenPrompt.test.ts b/ui/packages/fields/src/requiredWhenPrompt.test.ts similarity index 61% rename from ui/packages/plugin-kanban/src/requiredWhenPrompt.test.ts rename to ui/packages/fields/src/requiredWhenPrompt.test.ts index 4f751bf5c41..5906680c6a1 100644 --- a/ui/packages/plugin-kanban/src/requiredWhenPrompt.test.ts +++ b/ui/packages/fields/src/requiredWhenPrompt.test.ts @@ -7,7 +7,9 @@ */ /** - * The pre-evaluation half of objectui#4254, pinned directly. + * The pre-evaluation half of objectui#4254, pinned directly (moved here from + * `@object-ui/plugin-kanban` by objectstack#35956, when the list cell and the + * record page started asking too). * * The board-level test (`ObjectKanban.requiredWhenPrompt.test.tsx`) drives the * whole flow through a real drop; this file pins the SET the flow is built on, @@ -21,7 +23,7 @@ */ import { describe, it, expect } from 'vitest'; -import { collectRequiredWhenPromptFields } from './requiredWhenPrompt'; +import { collectRequiredWhenPromptFields, requiredWhenPromptReads } from './requiredWhenPrompt'; /** The card's own predicate: `has()` + `==` + `&&`. */ const WHEN_WON = 'has(record.stage) && record.stage == "closed_won"'; @@ -40,8 +42,7 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { const out = collectRequiredWhenPromptFields( fields({ requiredWhen: WHEN_WON }), record, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ); expect(out.map((f) => f.name)).toEqual(['win_reason']); // The definition travels with it so the dialog can render the right widget. @@ -53,8 +54,7 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { collectRequiredWhenPromptFields( fields({ requiredWhen: WHEN_WON }), { ...record, stage: 'closed_won' }, - 'stage', - 'negotiation', + { stage: 'negotiation' }, ), ).toEqual([]); }); @@ -64,8 +64,7 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { collectRequiredWhenPromptFields( fields({ requiredWhen: WHEN_WON }), { ...record, win_reason: 'Better price' }, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ), ).toEqual([]); }); @@ -78,8 +77,7 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { collectRequiredWhenPromptFields( { stage: {}, flag: { type: 'boolean', requiredWhen: WHEN_WON } }, { stage: 'negotiation', flag: value }, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ), ).toEqual([]); } @@ -90,8 +88,7 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { collectRequiredWhenPromptFields( fields({ requiredWhen: WHEN_WON, visibleWhen: 'false' }), record, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ), ).toEqual([]); }); @@ -101,8 +98,7 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { collectRequiredWhenPromptFields( fields({ requiredWhen: WHEN_WON, readonlyWhen: 'true' }), record, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ), ).toEqual([]); }); @@ -112,19 +108,17 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { collectRequiredWhenPromptFields( fields({ type: 'file', requiredWhen: WHEN_WON }), record, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ), ).toEqual([]); }); - it('never prompts for the groupBy field itself — the drop IS its value', () => { + it('never prompts for a field the change itself writes — the change IS its value', () => { expect( collectRequiredWhenPromptFields( { stage: { type: 'picklist', requiredWhen: WHEN_WON } }, { stage: null }, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ), ).toEqual([]); }); @@ -134,15 +128,14 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { collectRequiredWhenPromptFields( { stage: {}, note: { type: 'text', required: true } }, { stage: 'negotiation', note: null }, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ), ).toEqual([]); }); it('returns [] rather than throwing on absent metadata or record', () => { - expect(collectRequiredWhenPromptFields(undefined, record, 'stage', 'x')).toEqual([]); - expect(collectRequiredWhenPromptFields(fields({}), undefined, 'stage', 'x')).toEqual([]); + expect(collectRequiredWhenPromptFields(undefined, record, { stage: 'x' })).toEqual([]); + expect(collectRequiredWhenPromptFields(fields({}), undefined, { stage: 'x' })).toEqual([]); }); it('keeps the object’s declared field order', () => { @@ -153,8 +146,7 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { a_field: { type: 'text', requiredWhen: WHEN_WON }, }, { stage: 'negotiation', a_field: null, b_field: null }, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ); expect(out.map((f) => f.name)).toEqual(['b_field', 'a_field']); }); @@ -166,8 +158,7 @@ describe('collectRequiredWhenPromptFields (#4254)', () => { collectRequiredWhenPromptFields( fields({ requiredWhen: 'this is not ( valid CEL' }), record, - 'stage', - 'closed_won', + { stage: 'closed_won' }, ), ).toEqual([]); }); @@ -197,8 +188,7 @@ describe('collectRequiredWhenPromptFields judges the transition gate (objectstac collectRequiredWhenPromptFields( contractFields, { id: 'c1', priority: 'low', status: 'activated', signed_copy: null }, - 'priority', - 'high', + { priority: 'high' }, ), ).toEqual([]); }); @@ -209,9 +199,90 @@ describe('collectRequiredWhenPromptFields judges the transition gate (objectstac const out = collectRequiredWhenPromptFields( contractFields, { id: 'c2', priority: 'low', status: 'draft', signed_copy: null }, - 'status', - 'activated', + { status: 'activated' }, ); expect(out.map((f) => f.name)).toEqual(['signed_copy']); }); }); + +/** + * objectstack#35956 — the generalised shape: a change of any keys, an + * `exclude` set that lets a dialog re-ask with what was typed into it, and the + * host's own `fillable` question. + */ +describe('collectRequiredWhenPromptFields over a change of several keys (objectstack#35956)', () => { + it('judges every key of the change, and skips each of them', () => { + const out = collectRequiredWhenPromptFields( + { + stage: { type: 'picklist', requiredWhen: 'record.amount > 10' }, + amount: { type: 'number' }, + win_reason: { type: 'text', requiredWhen: WHEN_WON }, + }, + { stage: 'negotiation', amount: 1, win_reason: null }, + { stage: 'closed_won', amount: 50 }, + ); + expect(out.map((f) => f.name)).toEqual(['win_reason']); + }); + + it('chains: a value typed into the dialog can make one more field required', () => { + const objectFields = { + stage: { type: 'picklist' }, + win_reason: { type: 'text', requiredWhen: WHEN_WON }, + competitor: { type: 'text', requiredWhen: 'record.win_reason == "price"' }, + }; + const stored = { stage: 'negotiation', win_reason: null, competitor: null }; + const change = { stage: 'closed_won' }; + // CONTROL: before anything is typed, only the first field is asked. + expect( + collectRequiredWhenPromptFields(objectFields, stored, { ...change }, { exclude: Object.keys(change) }) + .map((f) => f.name), + ).toEqual(['win_reason']); + // The typed value keeps its row (the stored record still lacks it) and + // brings the field it makes required. + expect( + collectRequiredWhenPromptFields( + objectFields, + stored, + { ...change, win_reason: 'price' }, + { exclude: Object.keys(change) }, + ).map((f) => f.name), + ).toEqual(['win_reason', 'competitor']); + }); + + it('asks the host whether each field is fillable', () => { + const out = collectRequiredWhenPromptFields( + fields({ requiredWhen: WHEN_WON }), + record, + { stage: 'closed_won' }, + { fillable: (name) => name !== 'win_reason' }, + ); + expect(out).toEqual([]); + }); +}); + +describe('requiredWhenPromptReads — the keys the judgment reads (objectstack#35956, L1 M1)', () => { + const fields = { + name: { type: 'text' }, + stage: { type: 'select' }, + segment: { type: 'text' }, + owner: { type: 'text' }, + win_reason: { + type: 'text', + requiredWhen: 'record.segment == "enterprise" && record.stage == "won"', + visibleWhen: 'previous.owner != ""', + }, + memo: { type: 'richtext', requiredWhen: 'record.name == "x"' }, + locked: { type: 'text', requiredWhen: 'record.stage == "won"' }, + typo: { type: 'text', requiredWhen: 'record.no_such_field == 1' }, + }; + + it('names each askable field and the declared fields its predicates read, record. and previous. alike', () => { + expect(requiredWhenPromptReads(fields, { fillable: (name) => name !== 'locked' })) + .toEqual(['win_reason', 'segment', 'stage', 'owner', 'typo']); + }); + + it('reads nothing for an object with nothing to ask', () => { + expect(requiredWhenPromptReads({ name: { type: 'text' } })).toEqual([]); + expect(requiredWhenPromptReads(undefined)).toEqual([]); + }); +}); diff --git a/ui/packages/fields/src/requiredWhenPrompt.ts b/ui/packages/fields/src/requiredWhenPrompt.ts new file mode 100644 index 00000000000..71a1fe365ca --- /dev/null +++ b/ui/packages/fields/src/requiredWhenPrompt.ts @@ -0,0 +1,209 @@ +/** + * 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. + */ + +/** + * Which fields a change is about to make REQUIRED while they are still empty — + * the pre-evaluation half of the in-place fill-in (objectui#4254 for the kanban + * drop, objectstack#35956 for every other in-place write: a list cell, the + * record page's inline edit, the header's stage change). + * + * A change writes a few values, and that write can flip another field's + * `requiredWhen` predicate to TRUE. Sent alone, the engine refuses the whole + * update (`Win Reason 不能为空`), and the surface the change was made on often + * has no place to type the missing value (a column the view does not draw, a + * collapsed section). This module answers the question that makes the change + * completable instead: *given the record and the values about to be written, + * which fields become required while still being empty?* + * + * ## One evaluator, not two + * + * The verdict comes from `@object-ui/core`'s {@link resolveFieldRuleState} — + * the SAME function the record form (`components/renderers/form/form.tsx`), + * the wizard (`plugin-form/WizardForm.tsx`) and the line-item grid + * (`fields/widgets/GridField.tsx`) resolve `visibleWhen`/`readonlyWhen`/ + * `requiredWhen` with, which in turn delegates to `@objectstack/formula`'s + * `ExpressionEngine`. That is deliberate and load-bearing: the prompt and the + * server's enforcement must reach the identical verdict, and a second + * hand-rolled predicate evaluator is exactly how the two ends drift. The + * card's own predicate shape — `has(record.stage) && record.stage == + * "closed_won"` — was measured against that engine before this was written. + * + * ## Why "required" alone is not the filter + * + * A field is only offered when the dialog can honestly render a control for + * it, so further conditions narrow the set. Each exclusion is a case where + * prompting would be worse than not prompting: + * + * - **already has a value** — the change is not what is missing. `required` is + * a PRESENCE contract, so the emptiness test is core's `isMissingForRequired` + * (the one the form and the server agree on: `false` and `0` are values, + * an empty array is not) rather than a truthiness check that would re-ask + * for every unchecked box. It is read off the record as STORED, so a value + * typed into the dialog keeps its row. + * - **not visible** (`visibleWhen` FALSE) — the record form would not show it, + * so neither does this. + * - **readonly** — there is nothing the user could author. + * - **no edit widget** (`file`, `richtext`, `formula`, … — the types + * `@object-ui/fields` deliberately excludes from in-place editing) — a + * dialog row with no control is a worse dead end than the one being fixed. + * - **not fillable by this reader** — the host's own field-write question + * (`options.fillable`), so the dialog never offers a field the reader's + * grant would refuse. + * + * These fall through to the unchanged write, where the server's refusal is + * legible (objectstack#7525 is closed) — a legible refusal beats a dialog that + * cannot collect anything. + * + * The fields the change itself writes are skipped (`options.exclude`, by + * default every key of `changes`): the change IS their value. + */ +import { resolveFieldRuleState, isMissingForRequired, collectPredicateFieldRefs } from '@object-ui/core'; +import { hasFieldEditWidget } from './FieldEditWidget.js'; + +/** A field the change makes required, paired with the definition to render it. */ +export interface RequiredWhenPromptField { + /** Field name — the key the combined write will carry. */ + name: string; + /** The field definition, with `name` guaranteed present for the widget. */ + def: Record & { type?: string }; +} + +/** How {@link collectRequiredWhenPromptFields} narrows its set. */ +export interface RequiredWhenPromptOptions { + /** + * Fields never offered. Defaults to every key of `changes` — the values the + * change writes. A dialog re-asking with the values typed into it passes the + * keys of the ORIGINAL change only, so a field it collected keeps its row. + */ + exclude?: Iterable; + /** + * The host's own question of whether this reader may write `name` here (its + * field grant, a system column). Absent: every field is fillable. + */ + fillable?: (name: string, def: Record) => boolean; +} + +/** + * The fields writing `changes` over `record` would make required and that are + * still empty, in the object's declared field order. + * + * Returns `[]` whenever the change needs no prompt — the caller's signal to + * keep its write exactly as it was. + * + * @param objectFields `objectDef.fields`, as the surface fetched them. + * @param record The record as it stands BEFORE the change. + * @param changes The values the change is about to write. + * @param options See {@link RequiredWhenPromptOptions}. + */ +export function collectRequiredWhenPromptFields( + objectFields: Record | null | undefined, + record: Record | null | undefined, + changes: Record, + options: RequiredWhenPromptOptions = {}, +): RequiredWhenPromptField[] { + if (!objectFields || !record) return []; + + // The record as the server would see it after the write — this is what the + // predicates are judged against, and the whole reason the prompt can happen + // BEFORE the write rather than in reaction to a refusal. + const next = { ...record, ...changes }; + const exclude = new Set(options.exclude ?? Object.keys(changes)); + + const prompts: RequiredWhenPromptField[] = []; + for (const [name, raw] of Object.entries(objectFields)) { + if (exclude.has(name)) continue; + if (!raw || typeof raw !== 'object') continue; + const def = raw as Record; + + // Scoped to conditional requirements on purpose. A statically-required + // empty field means the record was already invalid before anyone touched + // it; turning an in-place edit into a general-purpose validation form is a + // different feature from the one that was approved. + if (def.requiredWhen == null) continue; + if (!isMissingForRequired(record[name])) continue; + + const state = resolveFieldRuleState( + { + visibleWhen: def.visibleWhen as never, + readonlyWhen: def.readonlyWhen as never, + requiredWhen: def.requiredWhen as never, + }, + next, + // `name` says which column of the stored record is this field's value, + // so the change is judged as the engine judges the write: a transition + // gate (objectstack#30220). A record already inside the gate without + // the value rests there, the engine lets the write through, and nothing + // is asked. + { required: def.required === true, readonly: def.readonly === true, name }, + // The stored record, so a predicate reading `previous.*` sees what the + // form would show it. + record, + undefined, + `field '${name}'`, + ); + + if (!state.required || !state.visible || state.readonly) continue; + if (!hasFieldEditWidget(def.type as string | undefined)) continue; + if (options.fillable && !options.fillable(name, def)) continue; + + prompts.push({ name, def: { name, ...def } }); + } + return prompts; +} + +/** A predicate's `previous.x` spelled as `record.x`, so one harvester reads both. */ +function asRecordScoped(pred: unknown): unknown { + const swap = (src: string) => src.replace(/\bprevious\.(\??)/g, 'record.$1'); + if (typeof pred === 'string') return swap(pred); + if (pred && typeof pred === 'object' && typeof (pred as { source?: unknown }).source === 'string') { + return { ...(pred as object), source: swap((pred as { source: string }).source) }; + } + return pred; +} + +/** + * The record keys {@link collectRequiredWhenPromptFields} reads to judge a + * change: every field it could ask for, and every declared field its + * `requiredWhen` / `visibleWhen` / `readonlyWhen` predicates name (as + * `record.x`, `data.x` or `previous.x`). + * + * A surface whose row is a PROJECTION (a list fetches the columns it draws) + * must not judge a key it never read: an absent key reads as empty, so a stored + * value would be asked for again and overwritten, and a predicate would be + * judged on a missing operand (objectstack#35956, L1 7057894230 M1). The host + * compares this list with the keys its row carries and reads the rest first. + * + * The same static narrowing as the collector (a `requiredWhen`, an in-place + * editor, the host's `fillable`), so an object with nothing to ask reads + * nothing more. Declared order, de-duplicated. + */ +export function requiredWhenPromptReads( + objectFields: Record | null | undefined, + options: Pick = {}, +): string[] { + if (!objectFields) return []; + const out: string[] = []; + const seen = new Set(); + const add = (name: string) => { + if (seen.has(name) || !(name in objectFields)) return; + seen.add(name); + out.push(name); + }; + for (const [name, raw] of Object.entries(objectFields)) { + if (!raw || typeof raw !== 'object') continue; + const def = raw as Record; + if (def.requiredWhen == null) continue; + if (!hasFieldEditWidget(def.type as string | undefined)) continue; + if (options.fillable && !options.fillable(name, def)) continue; + add(name); + for (const ref of collectPredicateFieldRefs( + [def.requiredWhen, def.visibleWhen, def.readonlyWhen].map(asRecordScoped), + )) add(ref); + } + return out; +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 70af4a16288..06398590469 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -271,6 +271,10 @@ const ar = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: 'أكمل الحقول المطلوبة', + requiredPromptDescription: 'هذا التغيير يجعل الحقول أدناه مطلوبة. املأها لحفظه.', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: 'فتح {{name}}', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 7e99247e5ca..4b7e7933968 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -257,6 +257,10 @@ const de = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: 'Pflichtfelder ausfüllen', + requiredPromptDescription: 'Durch diese Änderung werden die folgenden Felder zu Pflichtfeldern. Füllen Sie sie aus, um die Änderung zu speichern.', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: '{{name}} öffnen', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 13266e90f2a..1381eec0697 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -404,6 +404,10 @@ const en = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: 'Complete required fields', + requiredPromptDescription: 'This change makes the fields below required. Fill them in to save it.', // ADR-0144 D2 — the record-currency code select (`CurrencyCodeField`). currencyCode: { placeholder: 'Select currency', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f06b1b1529d..9ad5e91e4bc 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -264,6 +264,10 @@ const es = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: 'Completa los campos obligatorios', + requiredPromptDescription: 'Este cambio hace obligatorios los campos de abajo. Rellénalos para guardarlo.', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: 'Abrir {{name}}', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 749a7bfda0e..a2bb4a90936 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -259,6 +259,10 @@ const fr = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: 'Compléter les champs obligatoires', + requiredPromptDescription: 'Cette modification rend les champs ci-dessous obligatoires. Remplissez-les pour l’enregistrer.', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: 'Ouvrir {{name}}', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 9ff01af1738..c765604c5b6 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -257,6 +257,10 @@ const ja = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: '必須項目を入力', + requiredPromptDescription: 'この変更により、以下の項目が必須になります。入力すると変更と一緒に保存されます。', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: '{{name}} を開く', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 7136511d607..83b84b7544f 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -257,6 +257,10 @@ const ko = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: '필수 필드 입력', + requiredPromptDescription: '이 변경으로 아래 필드가 필수가 됩니다. 입력하면 변경 내용과 함께 저장됩니다.', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: '{{name}} 열기', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0d1c9c34747..f2cd35fd666 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -259,6 +259,10 @@ const pt = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: 'Preencha os campos obrigatórios', + requiredPromptDescription: 'Esta alteração torna obrigatórios os campos abaixo. Preencha-os para salvá-la.', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: 'Abrir {{name}}', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ef52983f948..b57e95ec93b 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -264,6 +264,10 @@ const ru = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: 'Заполните обязательные поля', + requiredPromptDescription: 'Это изменение делает поля ниже обязательными. Заполните их, чтобы сохранить его.', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: 'Открыть {{name}}', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 7288c069e0d..9fe934726b9 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -267,6 +267,10 @@ const zh = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: '补填必填字段', + requiredPromptDescription: '这次改动让下面的字段变成必填,填好后和改动一起保存。', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: '打开 {{name}}', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 33893d18585..33398be7fbb 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -267,6 +267,10 @@ const zhHant = { }, }, fields: { + // objectstack#35956 — the in-place fill-in a change opens when it makes + // other fields required (`RequiredFieldsDialog`). + requiredPromptTitle: '補填必填欄位', + requiredPromptDescription: '這次改動讓下面的欄位變成必填,填好後和改動一起儲存。', // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { view: '開啟 {{name}}', diff --git a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx index 390900cfb2d..19ca56bf6f9 100644 --- a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx +++ b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx @@ -71,11 +71,24 @@ import { Button, cn } from '@object-ui/components'; import { Check, X, Loader2 } from 'lucide-react'; import { useInlineEdit, + useRecordContext, + useSafeFieldLabel, extractFieldErrors, extractWriteErrorMessage, isExternalWriteRefusal, type WriteFieldError, } from '@object-ui/react'; +import { getRecordDisplayName, resolveFieldAffordance } from '@object-ui/core'; +import { usePermissions } from '@object-ui/permissions'; +import { + collectRequiredWhenPromptFields, + hasFieldEditWidget, + RequiredFieldsDialog, + type RequiredFieldsDialogField, + type RequiredWhenPromptField, +} from '@object-ui/fields'; +import { isComputedDetailField } from './fieldEnrichment'; +import { NON_EDITABLE_SYSTEM_FIELDS } from './systemFields'; import { useDetailTranslation } from './useDetailTranslation'; import { ConcurrentUpdateDialog, @@ -302,6 +315,37 @@ export const InlineEditSaveBar: React.FC = ({ const canAtomic = !!dataSource && !!objectName && recordId != null; + // 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. + 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); + // 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 + // conflict of the plain Save, whose write is the draft. + const conflictWriteRef = React.useRef | null>(null); + /** A field this reader may fill on this page: the question the inline editors ask. */ + const fillable = React.useCallback( + (name: string, def: Record) => + def.readonly !== true + && !isComputedDetailField(undefined, def as never) + && !NON_EDITABLE_SYSTEM_FIELDS.has(name) + && !!objectName + && resolveFieldAffordance('recordEdit', perms, objectName, name), + [objectName, perms], + ); + /** * Record-level lines of the last refusal, held beside the banner text they * were rendered into (objectui#13292). Shown only while the session's @@ -436,6 +480,15 @@ export const InlineEditSaveBar: React.FC = ({ inline.reset(); return; } + if (!onFieldSave && 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 }); + return; + } + } inline.setSaving(true); inline.setError(null); inline.setFieldErrors(null); @@ -474,9 +527,10 @@ export const InlineEditSaveBar: React.FC = ({ } finally { inline.setSaving(false); } - }, [inline, onFieldSave, canAtomic, data, dataSource, objectName, recordId, refresh, buildConflict, presentRefusal]); + }, [inline, onFieldSave, canAtomic, data, dataSource, objectName, recordId, refresh, buildConflict, presentRefusal, objectFields, fillable]); const closeConflict = React.useCallback(() => { + conflictWriteRef.current = null; setConflict(null); setConflictBusy(false); }, []); @@ -487,6 +541,7 @@ export const InlineEditSaveBar: React.FC = ({ await refresh?.(); } finally { // Discard the pending draft — the user chose the server's version. + setRequiredAsk(null); inline?.reset(); closeConflict(); } @@ -501,14 +556,17 @@ export const InlineEditSaveBar: React.FC = ({ try { // Re-key the write against the version the server reported in the 409 — // "I've seen the newer record, apply my whole draft on top of it." - const draft = inline?.draft ?? {}; + const draft = conflictWriteRef.current ?? inline?.draft ?? {}; const opts = conflict.currentVersion ? { ifMatch: conflict.currentVersion } : undefined; await updateVia(dataSource, objectName!, recordId!, draft, opts); + setRequiredAsk(null); await refresh?.(); inline?.reset(); } catch (err) { // Same presentation contract as the first save — an overwrite the server // refuses on validation grounds gets per-field reasons, not a raw string. + // They are drawn by the save bar, so a fill-in dialog above it closes. + setRequiredAsk(null); presentRefusal(err); } finally { closeConflict(); @@ -570,6 +628,83 @@ export const InlineEditSaveBar: React.FC = ({ 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 objectKey = objectName ?? ''; + const labelOf = (name: string): string => { + const declared = (objectFields?.[name] as { label?: unknown } | undefined)?.label; + const fallback = typeof declared === 'string' && declared.length > 0 ? declared : name; + return fieldLabelFor?.(name) || (objectKey ? fieldLabel(objectKey, name, fallback) : fallback); + }; + const label = (f: RequiredWhenPromptField): RequiredFieldsDialogField => { + const options = f.def.options; + const localized = objectKey && Array.isArray(options) ? translateOptions(objectKey, f.name, options) : options; + return { ...f, def: { ...f.def, ...(localized ? { options: localized } : {}) }, label: labelOf(f.name) }; + }; + const shownValue = (name: string, value: unknown): string => { + if (value === undefined || value === null || value === '') return '—'; + const options = (objectFields?.[name] as { options?: unknown } | undefined)?.options; + const one = (v: unknown): string => { + const code = String(v); + const option = Array.isArray(options) + ? (options as Array<{ value?: unknown; label?: unknown }>).find((o) => o && String(o.value) === code) + : undefined; + const declared = typeof option?.label === 'string' && option.label ? option.label : code; + return objectKey && option ? fieldOptionLabel(objectKey, name, code, declared) : declared; + }; + return Array.isArray(value) ? value.map(one).join(', ') : one(value); + }; + const exclude = Object.keys(ask.draft); + return ( + ({ name, label: labelOf(name), value: shownValue(name, ask.draft[name]) }))} + moreFields={(values) => collectRequiredWhenPromptFields( + objectFields, + data, + { ...ask.draft, ...values }, + { exclude, fillable }, + ).map(label)} + refusalField={(name) => { + const def = objectFields?.[name] as Record | undefined; + if (!def || typeof def !== 'object' || exclude.includes(name)) return null; + if (!hasFieldEditWidget(def.type as string | undefined) || !fillable(name, def)) return null; + return label({ name, def: { name, ...def } }); + }} + labelOf={(name) => (objectFields?.[name] ? labelOf(name) : undefined)} + // Cancel writes nothing and leaves the edit session as it was: the + // 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; + inline?.setSaving(true); + const write = { ...ask.draft, ...values }; + try { + await updateVia(dataSource, objectName!, recordId!, write, ifMatch ? { ifMatch } : undefined); + } catch (err) { + // Someone else saved the record meanwhile: the same conflict + // dialog a plain Save opens (L1 7057894230 S1), over this one. + // Its overwrite sends the draft and the typed values; its Cancel + // comes back here with them still typed; Reload drops the edit. + if (isConcurrentUpdateError(err)) { + conflictWriteRef.current = write; + setConflict(buildConflict(write, err)); + return; + } + throw err; + } finally { + inline?.setSaving(false); + } + setRequiredAsk(null); + await refresh?.(); + inline?.reset(); + }} + /> + ); + }; + // Render nothing unless a provider is present and the record is being edited. if (!inline || !inline.editing) return null; @@ -662,6 +797,7 @@ export const InlineEditSaveBar: React.FC = ({ {inline.saving ? t('detail.saving') : t('detail.save')} + {requiredAsk && renderRequiredAsk(requiredAsk)} cleanup()); + +const OBJECT_SCHEMA = { + name: 'deal', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'select', label: 'Stage', options: [{ value: 'new', label: 'New' }, { value: 'won', label: 'Won' }] }, + priority: { type: 'select', label: 'Priority', options: [{ value: 'low', label: 'Low' }, { value: 'high', label: 'High' }] }, + win_reason: { type: 'text', label: 'Win Reason', requiredWhen: 'record.stage == "won"' }, + }, +}; +const DATA = { id: 'd1', name: 'Acme deal', stage: 'new', priority: 'low', win_reason: null, updated_at: 'v1' }; + +function Harness() { + const inline = useInlineEdit()!; + return ( + <> + + + + {inline.editing ? 'editing' : 'idle'} + {JSON.stringify(inline.draft)} + + ); +} + +function renderBar(update: ReturnType, extra: Partial> = {}) { + const refresh = vi.fn().mockResolvedValue(undefined); + render( + + + + + + , + ); + return { refresh }; +} + +const winReasonInput = (dialog: HTMLElement) => + dialog.querySelector('[data-required-fields-field="win_reason"] input')!; + +function stageWon() { + fireEvent.click(screen.getByText('edit-enter')); + fireEvent.click(screen.getByText('edit-stage-won')); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); +} + +describe('InlineEditSaveBar asks for the fields a draft makes required (objectstack#35956)', () => { + it('opens the dialog naming the record and the change, and writes nothing yet', async () => { + const update = vi.fn().mockResolvedValue({}); + renderBar(update); + stageWon(); + const dialog = await screen.findByTestId('required-fields-dialog'); + expect(dialog).toHaveTextContent('Acme deal'); + expect(dialog.querySelector('[data-required-fields-change-row="stage"]')).toHaveTextContent('Stage:Won'); + expect(winReasonInput(dialog)).toBeTruthy(); + expect(update).not.toHaveBeenCalled(); + }); + + it('Save writes the draft and the typed value in one guarded update, then leaves edit mode', async () => { + const update = vi.fn().mockResolvedValue({}); + const { refresh } = renderBar(update); + 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(update).toHaveBeenCalledTimes(1)); + expect(update).toHaveBeenCalledWith('deal', 'd1', { stage: 'won', win_reason: 'Better price' }, { ifMatch: 'v1' }); + await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(screen.getByTestId('editing')).toHaveTextContent('idle')); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('Cancel writes nothing and keeps the edit session and its draft', async () => { + const update = vi.fn().mockResolvedValue({}); + renderBar(update); + 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(screen.getByTestId('editing')).toHaveTextContent('editing'); + expect(screen.getByTestId('draft')).toHaveTextContent('"stage":"won"'); + }); + + it('a refusal of the combined write stays in the dialog', async () => { + const update = vi.fn().mockRejectedValueOnce(new Error('Someone else changed this record')); + renderBar(update); + 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(dialog.querySelector('[data-required-fields-refusal]')).toHaveTextContent('Someone else changed this record')); + expect(screen.getByTestId('editing')).toHaveTextContent('editing'); + }); + + it('control: a draft that makes nothing required saves at once', async () => { + const update = vi.fn().mockResolvedValue({}); + renderBar(update); + fireEvent.click(screen.getByText('edit-enter')); + fireEvent.click(screen.getByText('edit-priority')); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(update).toHaveBeenCalledTimes(1)); + expect(update).toHaveBeenCalledWith('deal', 'd1', { priority: 'high' }, { ifMatch: 'v1' }); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('control: the per-field callback mode (drawer) never asks', 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(); + }); + + describe('a 409 of the combined write opens the conflict dialog, as a plain Save does', () => { + const conflict = { + code: 'CONCURRENT_UPDATE', + currentVersion: 'v2', + currentRecord: { ...DATA, priority: 'high', updated_at: 'v2' }, + }; + + it('Overwrite sends the draft and the typed value at the version the server reported', async () => { + const update = vi.fn().mockRejectedValueOnce(conflict).mockResolvedValueOnce({}); + const { refresh } = renderBar(update); + 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()); + // Nothing is re-read under the reader: the choice is theirs. + expect(refresh).not.toHaveBeenCalled(); + 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' }); + await waitFor(() => expect(screen.getByTestId('editing')).toHaveTextContent('idle')); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('the conflict dialog\'s Cancel comes back to the fill-in dialog with the value still typed', async () => { + const update = vi.fn().mockRejectedValueOnce(conflict); + renderBar(update); + 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()); + fireEvent.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: /cancel/i })); + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); + const still = screen.getByTestId('required-fields-dialog'); + expect(winReasonInput(still).value).toBe('Better price'); + expect(update).toHaveBeenCalledTimes(1); + expect(screen.getByTestId('editing')).toHaveTextContent('editing'); + }); + }); +}); diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 7bd85d57cfa..e59b2397fef 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -48,6 +48,7 @@ import { useLocalization, useDisplayLocale } from '@object-ui/i18n'; import { resolveI18nLabel as resolveInlineI18nLabel } from '@objectstack/spec/ui'; import { stateMachineNextValues } from './inline-edit-options'; import { isStateMachineField, stateLabelOf, type StateChangeConfirm } from './objectGridStateConfirm'; +import { useCellRequiredPrompt } from './objectGridRequiredPrompt'; import { cellReadOnlyKind, readOnlyReasonText, inlineTyping, choiceFromText } from './objectGridCellFacts'; import { Badge, Button, NavigationOverlay, EmptyValue, @@ -1271,6 +1272,41 @@ export const ObjectGrid: React.FC = ({ // does there and what pasted text stands for. `null` without the host's // ask, so every other grid keeps the table it had. const approvalLocks = useRowApprovalLocks(hostCellSelection ? objectName : undefined); + // objectstack#35956 — a cell change that makes other fields required asks + // for them first, and saves them with it (`./objectGridRequiredPrompt`). + const fieldLabelOf = (field: string): string => { + const declared = objectFields?.[field]?.label; + const fallback = typeof declared === 'string' && declared.length > 0 ? declared : field; + return columnHeaderOf(field) ?? (objectName ? resolveFieldLabel(objectName, field, fallback) : fallback); + }; + const requiredPrompt = useCellRequiredPrompt({ + objectName, + objectSchema, + objectFields, + perms, + labelOf: fieldLabelOf, + translateOptions, + optionLabel: (field, code, fallback) => (objectName ? resolveFieldOptionLabel(objectName, field, code, fallback) : fallback), + emptyText: t('grid.empty'), + save: async (row, changes) => { + const rows = loadedRowsRef.current.data; + const id = resolveRecordId(row); + const index = rows.findIndex((r: any) => r === row || (id != null && String(resolveRecordId(r)) === String(id))); + // A row no longer loaded (the list re-read under the open dialog) has + // no index to hand a host's `onRowSave`; the dialog says the save failed + // rather than guessing one. + if (index < 0) throw new Error(t('table.saveFailed')); + await (onRowSave ?? defaultRowSave)(index, changes, row); + }, + // The row is the view's projection; the prompt reads the keys it lacks. + read: dataSource && objectName && typeof dataSource.findOne === 'function' + ? async (row, keys) => { + const id = resolveRecordId(row); + if (id == null) return null; + return dataSource.findOne(objectName, String(id), { $select: keys }); + } + : undefined, + }); const gridCellSelection: GridCellSelection | null = hostCellSelection ? { describeCell: (row, columnKey) => { @@ -1299,26 +1335,32 @@ export const ObjectGrid: React.FC = ({ 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), - }); - }, + // before anything is written (`./objectGridStateConfirm`). A move that + // needs fields filled asks for them first; that dialog is the + // confirmation, so a state-machine move does not ask twice. + confirmCommit: (row, columnKey, value) => + requiredPrompt.ask(row, columnKey, value, () => askStateMove(row, columnKey, value)), } : null; + // objectstack#35685 — the state-machine confirm, the grid's next question + // when the required-fields prompt has nothing to ask. + function askStateMove(row: any, columnKey: string, value: unknown): Promise | null { + 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), + }); + } // The projection keys and the filter, sort, search and server-paging state, // read here in hook order (`./objectGridQueryInputs`). @@ -4770,6 +4812,7 @@ export const ObjectGrid: React.FC = ({ {bulkDialog} {rowConflictDialog} {stateChangeDialog} + {requiredPrompt.renderDialog()} ); }; diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.requiredPrompt-35956.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.requiredPrompt-35956.test.tsx new file mode 100644 index 00000000000..845a89a62bd --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.requiredPrompt-35956.test.tsx @@ -0,0 +1,340 @@ +/** + * 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#35956 — a list cell's change that makes other fields required + * asks for them in place (the shared `RequiredFieldsDialog`) before anything + * is written: + * + * 1. Changing 「Stage」 to 「Won」 when 「Win Reason」 is required on Won opens + * the dialog, names the record and the change, and writes nothing yet — + * whether or not the view draws a Win Reason column. + * 2. Save sends the cell's value and the typed value in ONE guarded update, + * and the row shows the new stage. + * 3. Cancel writes nothing, and the cell keeps the stage it showed. + * 4. A refusal of that write stays in the dialog, under the field it names. + * 5. A field that already has a value asks nothing: the change saves at once. + * 6. A field with no in-place editor (rich text) asks nothing: the change is + * written and refused as before. + * 7. The row is the view's PROJECTION (this file's server honours `$select`, + * as a real one does): a key the judgment reads that the row lacks is read + * from the record first, so a stored value not drawn as a column is not + * asked for again (L1 7057894230 M1), a predicate operand outside the + * columns is judged on its stored value, and a read that fails asks + * nothing. + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +// The grid's toast, to read the save toast's Undo button (the components +// entry is the module the grid imports `toast` from). +const toasts = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() })); +vi.mock('@object-ui/components', async (importOriginal) => { + const actual = await importOriginal>(); + return { ...actual, toast: Object.assign(vi.fn(), toasts) }; +}); + +import { ObjectGrid } from '../ObjectGrid'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, notifyDataChanged } from '@object-ui/react'; +import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; +import { __resetApprovalsServiceLatch } from '../hooks/useRowApprovalLocks'; +import { installExplainDouble } from './explainDouble'; + +beforeEach(() => { + __clearRecordCrudVerdictCache(); + __resetApprovalsServiceLatch(); + installExplainDouble(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + for (const fn of Object.values(toasts)) fn.mockClear(); +}); + +registerAllFields(); + +beforeAll(() => { + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn() as any; + } +}); + +const OBJECT = 'deal'; + +/** + * A fake server whose update hook rewrites the name it is sent to upper case, + * and whose writes are announced on the data-invalidation bus. + */ +function makeDataSource() { + const store: Record = { + d1: { id: 'd1', name: 'alpha', amount: 10, updated_at: '2026-11-20T10:00:00.000Z' }, + d2: { id: 'd2', name: 'beta', amount: 20, updated_at: '2026-11-20T10:00:00.000Z' }, + }; + let clock = 0; + const find = vi.fn(async () => { + const data = Object.values(store).map((r) => ({ ...r })); + return { data, total: data.length, hasMore: false, pageSize: 50 }; + }); + const update = vi.fn(async (_object: string, id: string, changes: Record) => { + const next = { ...store[id], ...changes }; + if (typeof changes.name === 'string') next.name = changes.name.toUpperCase(); + next.updated_at = `2026-11-20T11:00:0${++clock}.000Z`; + store[id] = next; + // Announced on the bus inside the write, as the console's mutation bridge + // does, so a grid that re-read on its own write would read again here. + notifyDataChanged({ objectName: OBJECT, recordId: id }); + return { ...next }; + }); + return { + store, + find, + update, + getObjectSchema: async (name: string) => ({ + name, + fields: { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + amount: { type: 'number', label: 'Amount' }, + updated_at: { type: 'datetime' }, + }, + }), + } as any; +} + + +const WON_RULE = 'record.stage == "won"'; + +/** Only the keys a `$select` names, as a real server answers a projection. */ +const project = (record: Record, select: unknown) => + Array.isArray(select) + ? Object.fromEntries(select.filter((k) => k in record).map((k) => [k, record[k]])) + : { ...record }; + +function makePromptDataSource( + winReason: Record = { type: 'text' }, + stored: unknown = null, + extraFields: Record = {}, +) { + const ds = makeDataSource(); + ds.store.d1.stage = 'new'; + ds.store.d1.win_reason = stored; + ds.find = vi.fn(async (_object: string, params: any = {}) => { + const data = Object.values(ds.store).map((r: any) => project(r, params.$select)); + return { data, total: data.length, hasMore: false, pageSize: 50 }; + }); + ds.findOne = vi.fn(async (_object: string, id: string, params: any = {}) => + (ds.store[id] ? project(ds.store[id], params.$select) : null)); + ds.getObjectSchema = async (name: string) => ({ + name, + fields: { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + stage: { + type: 'select', + label: 'Stage', + options: [{ value: 'new', label: 'New' }, { value: 'won', label: 'Won' }], + }, + win_reason: { label: 'Win Reason', requiredWhen: WON_RULE, ...winReason }, + ...extraFields, + updated_at: { type: 'datetime' }, + }, + }); + return ds; +} + +function renderPromptGrid(ds: any, withWinReasonColumn = false) { + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + editable: true, + columns: [ + { field: 'name', label: 'Name' }, + { field: 'stage', label: 'Stage' }, + ...(withWinReasonColumn ? [{ field: 'win_reason', label: 'Win Reason' }] : []), + ], + pagination: { pageSize: 50 }, + }; + return render( + + + , + ); +} + +const dataCell = (container: HTMLElement, row: number, text: string) => + Array.from(container.querySelectorAll('tbody tr')[row].querySelectorAll('td')) + .find((td) => td.textContent === text)!; + +/** Select a cell and paste `text` into it (a commit made without an editor). */ +function pasteInto(container: HTMLElement, cell: HTMLElement, text: string) { + fireEvent.click(cell); + const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; + fireEvent.paste(catcher, { clipboardData: { getData: () => text } }); +} + +const winReasonInput = (dialog: HTMLElement) => + dialog.querySelector('[data-required-fields-field="win_reason"] input')!; + +describe('ObjectGrid — a cell change that makes fields required asks for them in place (objectstack#35956)', () => { + it('opens the dialog naming the record and the change, with no column for the field, and writes nothing yet', async () => { + const ds = makePromptDataSource(); + const { container } = renderPromptGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + const dialog = await screen.findByTestId('required-fields-dialog'); + expect(dialog).toHaveTextContent('Complete required fields'); + expect(dialog).toHaveTextContent('alpha'); + expect(dialog.querySelector('[data-required-fields-change-row="stage"]')).toHaveTextContent('Stage:Won'); + expect(winReasonInput(dialog)).toBeTruthy(); + // The fill-in is the confirmation: no second (state) dialog, nothing sent. + expect(screen.queryByRole('alertdialog')).toBeNull(); + expect(ds.update).not.toHaveBeenCalled(); + }); + + it('Save sends the change and the typed value in one guarded update', async () => { + const ds = makePromptDataSource(); + const { container } = renderPromptGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + const dialog = await screen.findByTestId('required-fields-dialog'); + fireEvent.change(winReasonInput(dialog), { target: { value: 'Better price' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update).toHaveBeenCalledWith( + OBJECT, + 'd1', + { stage: 'won', win_reason: 'Better price' }, + { ifMatch: '2026-11-20T10:00:00.000Z' }, + ); + await waitFor(() => expect(screen.queryByTestId('required-fields-dialog')).toBeNull()); + await waitFor(() => expect(dataCell(container, 0, 'Won')).toBeTruthy()); + await act(async () => {}); + expect(ds.update).toHaveBeenCalledTimes(1); + }); + + it('Cancel writes nothing and the cell keeps its stage', async () => { + const ds = makePromptDataSource(); + const { container } = renderPromptGrid(ds, true); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await screen.findByTestId('required-fields-dialog'); + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + await waitFor(() => expect(screen.queryByTestId('required-fields-dialog')).toBeNull()); + await act(async () => {}); + expect(ds.update).not.toHaveBeenCalled(); + expect(dataCell(container, 0, 'New')).toBeTruthy(); + }); + + it('a refusal of the combined write stays in the dialog, under the field it names', async () => { + const ds = makePromptDataSource(); + ds.update.mockRejectedValueOnce(Object.assign(new Error('Validation failed'), { + code: 'VALIDATION_FAILED', + details: { fields: [{ field: 'win_reason', message: 'Win Reason is too short' }] }, + })); + const { container } = renderPromptGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + const dialog = await screen.findByTestId('required-fields-dialog'); + fireEvent.change(winReasonInput(dialog), { target: { value: 'x' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => + expect(dialog.querySelector('[data-required-fields-error="win_reason"]')).toHaveTextContent('Win Reason is too short')); + expect(screen.getByTestId('required-fields-dialog')).toBeInTheDocument(); + }); + + it('control: a field that already has a value asks nothing, and the change saves at once', async () => { + const ds = makePromptDataSource({ type: 'text' }, 'Known reason'); + const { container } = renderPromptGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('control: a field with no in-place editor asks nothing, and the change is written as before', async () => { + const ds = makePromptDataSource({ type: 'richtext' }); + const { container } = renderPromptGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + describe('the row is a projection: what it lacks is read from the record first', () => { + it('a stored value that is not a column is read, not asked for again, and not overwritten', async () => { + const ds = makePromptDataSource({ type: 'text' }, 'Known reason'); + const { container } = renderPromptGrid(ds); + await screen.findByText('beta'); + // The row really lacks the field: the grid fetched its columns only. + expect(ds.find.mock.calls[0][1].$select).not.toContain('win_reason'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.findOne).toHaveBeenCalledWith(OBJECT, 'd1', { $select: ['win_reason'] }); + expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); + expect(ds.store.d1.win_reason).toBe('Known reason'); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('an empty stored value read the same way still opens the dialog', async () => { + const ds = makePromptDataSource(); + const { container } = renderPromptGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await screen.findByTestId('required-fields-dialog'); + expect(ds.findOne).toHaveBeenCalledTimes(1); + expect(ds.update).not.toHaveBeenCalled(); + }); + + it('a predicate operand outside the columns is judged on its stored value', async () => { + const rule = { type: 'text', requiredWhen: 'record.segment == "enterprise" && record.stage == "won"' }; + const segment = { segment: { type: 'text', label: 'Segment' } }; + const enterprise = makePromptDataSource(rule, null, segment); + enterprise.store.d1.segment = 'enterprise'; + const first = renderPromptGrid(enterprise); + await screen.findByText('beta'); + pasteInto(first.container, dataCell(first.container, 0, 'New'), 'Won'); + await screen.findByTestId('required-fields-dialog'); + expect(enterprise.findOne.mock.calls[0][2].$select).toEqual(['win_reason', 'segment']); + first.unmount(); + + const smb = makePromptDataSource(rule, null, segment); + smb.store.d1.segment = 'smb'; + const second = renderPromptGrid(smb); + await screen.findByText('beta'); + pasteInto(second.container, dataCell(second.container, 0, 'New'), 'Won'); + await waitFor(() => expect(smb.update).toHaveBeenCalledTimes(1)); + expect(smb.update.mock.calls[0][2]).toEqual({ stage: 'won' }); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('a read that fails asks nothing: the change is written and the server judges it', async () => { + const ds = makePromptDataSource({ type: 'text' }, 'Known reason'); + ds.findOne.mockRejectedValueOnce(new Error('offline')); + const { container } = renderPromptGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); + expect(screen.queryByTestId('required-fields-dialog')).toBeNull(); + }); + + it('a row that carries every key it needs reads nothing more', async () => { + const ds = makePromptDataSource({ type: 'text' }, 'Known reason'); + const { container } = renderPromptGrid(ds, true); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.findOne).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridRequiredPrompt.tsx b/ui/packages/plugin-grid/src/objectGridRequiredPrompt.tsx new file mode 100644 index 00000000000..20fc540cf94 --- /dev/null +++ b/ui/packages/plugin-grid/src/objectGridRequiredPrompt.tsx @@ -0,0 +1,226 @@ +/** + * 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#35956 — a list cell's change that makes other fields required + * asks for them in place, before anything is written. + * + * Changing 「阶段」 to 「赢单」 when 「赢单原因」 is required on 赢单 used to be + * written alone, refused by the engine, and left the reader with a red cell and + * often no place to type the reason (a column the view does not draw). Now the + * select-first grid's `confirmCommit` asks first: when the new value makes + * fields required that are still empty (`collectRequiredWhenPromptFields`, the + * one pre-evaluation the kanban drop and the record page use), the shared + * `RequiredFieldsDialog` opens. Save writes the cell's value and the typed + * values in ONE update through the grid's own row save (`save`, the same + * guarded write a cell commit makes, so the row redraws in place and the save + * toast offers Undo); a refusal stays in the dialog. Cancel writes nothing and + * the cell shows what it showed before. + * + * Either way the table is told "no" (`confirmCommit` resolves `false`): the + * write, when there is one, was the grid's, not the table's. + * + * ## Judged on what the record holds, not on what the list fetched + * + * A list row is a PROJECTION: the grid asks the server for the columns it + * draws. A `requiredWhen` field that is not a column, or an operand its + * predicate reads, is simply absent from the row, and an absent key reads as + * empty. Judged on the row alone, a stored 「赢单原因」 would be asked for again + * and overwritten by what the reader types (L1 7057894230 M1). So when the + * row lacks a key the judgment reads (`requiredWhenPromptReads`), the record's + * missing keys are read first (`read`, one `findOne` with `$select` those + * keys), and the change is judged on the row with them filled in. A read that + * fails asks nothing: the write goes ahead and the server judges it, as before + * this card. + */ + +import React from 'react'; +import { getRecordDisplayName, resolveFieldAffordance } from '@object-ui/core'; +import { + collectRequiredWhenPromptFields, + requiredWhenPromptReads, + hasFieldEditWidget, + RequiredFieldsDialog, + type RequiredFieldsDialogField, + type RequiredFieldsDialogChange, + type RequiredWhenPromptField, +} from '@object-ui/fields'; +import { stateLabelOf } from './objectGridStateConfirm'; + +type FieldDefs = Record | undefined; + +export interface CellRequiredPromptInputs { + objectName: string | undefined; + objectSchema: unknown; + objectFields: FieldDefs; + perms: Parameters[1]; + /** The grid's field label (the column header when it draws one). */ + labelOf: (field: string) => string; + /** The grid's option localisation. */ + translateOptions: (objectName: string, field: string, options: any[]) => any[]; + /** The grid's option label for one stored code. */ + optionLabel: (field: string, code: string, fallback: string) => string; + /** The grid's word for no value. */ + emptyText: string; + /** The grid's row save: one guarded update of `changes` over `row`. */ + save: (row: any, changes: Record) => Promise; + /** + * Reads `keys` of the record `row` stands for (the keys the row lacks). + * Absent: the row is judged as it is (a host whose rows are whole records). + */ + read?: (row: any, keys: string[]) => Promise | null | undefined>; +} + +interface PendingPrompt { + /** The grid's row, as the table handed it (what the save is keyed on). */ + row: any; + /** The record the change is judged on: the row with the keys it lacked read in. */ + record: any; + columnKey: string; + value: unknown; + fields: RequiredWhenPromptField[]; + resolve: (written: boolean) => void; +} + +/** + * The ask `confirmCommit` makes, and the dialog the grid renders once. + * `renderDialog` is called from the grid's JSX, after every helper `inputs` + * reads is in scope (the labels read the grid's columns). + */ +export function useCellRequiredPrompt(inputs: CellRequiredPromptInputs): { + /** + * `otherwise` is the grid's next question (the state-machine confirm), asked + * when this one has nothing to ask; `null` from it means "write". + */ + ask: ( + row: any, + columnKey: string, + value: unknown, + otherwise: () => Promise | null, + ) => Promise | null; + renderDialog: () => React.ReactNode; +} { + const [pending, setPending] = React.useState(null); + const pendingRef = React.useRef(null); + const { objectName, objectSchema, objectFields, perms } = inputs; + + // A field this reader may write from the list: the field grant the cell + // editors ask (`listInlineEdit`). + const fillable = (name: string, def: Record): boolean => + def.readonly !== true + && (!objectName || resolveFieldAffordance('listInlineEdit', perms, objectName, name)); + + const label = (f: RequiredWhenPromptField): RequiredFieldsDialogField => { + const options = f.def.options; + const localized = objectName && Array.isArray(options) + ? inputs.translateOptions(objectName, f.name, options) + : options; + return { ...f, def: { ...f.def, ...(localized ? { options: localized } : {}) }, label: inputs.labelOf(f.name) }; + }; + + const settle = (written: boolean) => { + const current = pendingRef.current; + pendingRef.current = null; + setPending(null); + current?.resolve(written); + }; + + // Unmounting the grid answers an open ask "no", as the state confirm does. + React.useEffect(() => () => { pendingRef.current?.resolve(false); pendingRef.current = null; }, []); + + const open = (row: any, record: any, columnKey: string, value: unknown, fields: RequiredWhenPromptField[]) => + // The table writes nothing either way: the grid's own save did, or the + // reader cancelled. A second ask while one is open answers the first no. + new Promise((resolve) => { + pendingRef.current?.resolve(false); + const next: PendingPrompt = { row, record, columnKey, value, fields, resolve: () => resolve(false) }; + pendingRef.current = next; + setPending(next); + }); + + const ask = ( + row: any, + columnKey: string, + value: unknown, + otherwise: () => Promise | null, + ): Promise | null => { + if (!row || typeof row !== 'object') return otherwise(); + const judge = (record: any) => + collectRequiredWhenPromptFields(objectFields, record, { [columnKey]: value }, { fillable }); + const lacking = requiredWhenPromptReads(objectFields, { fillable }) + .filter((key) => key !== columnKey && !(key in row)); + if (lacking.length === 0 || !inputs.read) { + const fields = judge(row); + return fields.length > 0 ? open(row, row, columnKey, value, fields) : otherwise(); + } + const read = inputs.read; + return (async () => { + let record: any; + try { + const fresh = await read(row, lacking); + if (!fresh || typeof fresh !== 'object') return (await otherwise()) ?? true; + // Only the keys the row lacked: the rest of the row is what the reader + // sees and what the write is guarded on. A key the read did not answer + // (no value, or not readable) stays absent and reads as empty. + record = { ...row }; + for (const key of lacking) record[key] = (fresh as Record)[key]; + } catch { + // Not knowing the record, ask nothing: the write goes ahead and the + // server judges it, as it did before this card. + return (await otherwise()) ?? true; + } + const fields = judge(record); + return fields.length > 0 ? open(row, record, columnKey, value, fields) : ((await otherwise()) ?? true); + })(); + }; + + const renderDialog = (): React.ReactNode => { + if (!pending) return null; + const { row, record, columnKey, value } = pending; + const changes: RequiredFieldsDialogChange[] = [{ + name: columnKey, + label: inputs.labelOf(columnKey), + value: stateLabelOf( + objectFields?.[columnKey]?.options, + value, + (code, fallback) => inputs.optionLabel(columnKey, code, fallback), + inputs.emptyText, + ), + }]; + const refusalField = (name: string): RequiredFieldsDialogField | null => { + const def = objectFields?.[name]; + if (!def || typeof def !== 'object' || name === columnKey) return null; + // A field a refusal names joins the dialog when it could have been asked + // for: it has an edit widget and this reader may write it. + if (!hasFieldEditWidget(def.type) || !fillable(name, def)) return null; + return label({ name, def: { name, ...def } }); + }; + return ( + collectRequiredWhenPromptFields( + objectFields, + record, + { [columnKey]: value, ...values }, + { exclude: [columnKey], fillable }, + ).map(label)} + refusalField={refusalField} + labelOf={(name) => (objectFields?.[name] ? inputs.labelOf(name) : undefined)} + onCancel={() => settle(false)} + onSubmit={async (values) => { + await inputs.save(row, { [columnKey]: value, ...values }); + settle(true); + }} + /> + ); + }; + return { ask, renderDialog }; +} diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.requiredWhenPrompt.test.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.requiredWhenPrompt.test.tsx index 4d16e83595b..3db22a95009 100644 --- a/ui/packages/plugin-kanban/src/ObjectKanban.requiredWhenPrompt.test.tsx +++ b/ui/packages/plugin-kanban/src/ObjectKanban.requiredWhenPrompt.test.tsx @@ -195,6 +195,12 @@ describe('ObjectKanban — a drop that makes fields required collects them (#425 const dialog = await screen.findByRole('dialog'); expect(within(dialog).getByText('Complete required fields')).toBeInTheDocument(); expect(within(dialog).getByText('Win Reason')).toBeInTheDocument(); + // objectstack#35956 — the shared dialog names the record and the move, + // read-only, above the field. + expect(within(dialog).getByText(DEAL)).toBeInTheDocument(); + const moveRow = dialog.querySelector('[data-required-fields-change-row="stage"]'); + expect(moveRow).toHaveTextContent('Stage:'); + expect(moveRow).toHaveTextContent('Closed Won'); // Only the field the move made required — `name` is empty of a predicate, // `stage` is the thing being set. expect(within(dialog).queryByText('Name')).not.toBeInTheDocument(); diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.tsx index 9965fee9064..980d724fa95 100644 --- a/ui/packages/plugin-kanban/src/ObjectKanban.tsx +++ b/ui/packages/plugin-kanban/src/ObjectKanban.tsx @@ -47,16 +47,22 @@ import { stateMachineNextValues, type SchemaLike, } from '@object-ui/core'; -import { getBadgeColorClasses, getBadgeHexAppearance, getCellRenderer, resolveCellRendererType } from '@object-ui/fields'; +import { + getBadgeColorClasses, + getBadgeHexAppearance, + getCellRenderer, + resolveCellRendererType, + // objectstack#35956 — the in-place fill-in, shared with the list cell and + // the record page (it used to live in this package). + collectRequiredWhenPromptFields, + RequiredFieldsDialog, + type RequiredFieldsDialogField, + type RequiredWhenPromptField, +} from '@object-ui/fields'; import { usePermissions } from '@object-ui/permissions'; import { KANBAN_UNCOLUMNED_ID } from './index'; import { KanbanBoardCore } from './KanbanBoardCore'; import type { KanbanBoardProps, KanbanLaneRows } from './KanbanImpl'; -import { - collectRequiredWhenPromptFields, - type RequiredWhenPromptField, -} from './requiredWhenPrompt'; -import { RequiredFieldsDialog } from './RequiredFieldsDialog'; import { KanbanRecordsSettledContext } from './KanbanRecordsSettled'; import { KanbanColumnSummaryContext, type KanbanColumnSummary } from './KanbanColumnSummary'; import { @@ -1821,6 +1827,8 @@ export const ObjectKanban: React.FC = ({ fromColumnId: string; toColumnId: string; fields: RequiredWhenPromptField[]; + /** The record as stored when the card was dropped. */ + record: Record; } | null>(null); const [pendingSubmitting, setPendingSubmitting] = useState(false); @@ -1913,14 +1921,13 @@ export const ObjectKanban: React.FC = ({ const fields = collectRequiredWhenPromptFields( objectDef?.fields, record, - groupBy, - toColumnId, + { [groupBy]: toColumnId }, ); if (fields.length > 0) { // No optimistic write and no PATCH: the card sits in its source column // behind the modal until the user commits, so Cancel needs no rollback // and a refusal that never happens cannot need one either. - setPendingMove({ cardId, fromColumnId, toColumnId, fields }); + setPendingMove({ cardId, fromColumnId, toColumnId, fields, record: record ?? {} }); // Nothing was written yet: the board announces nothing at settle. The // dialog, and the toast of the write it submits, speak for this move. return { kind: 'deferred' }; @@ -1933,23 +1940,46 @@ export const ObjectKanban: React.FC = ({ // Label + localized options for each prompted field, resolved with the same // helpers the cards use so the dialog names a field exactly as the board does. - const pendingFields = useMemo(() => { - if (!pendingMove) return []; + const labelPromptField = (f: RequiredWhenPromptField): RequiredFieldsDialogField => { const objectKey = objectDef?.name || schema.objectName || ''; - return pendingMove.fields.map((f) => { - const options = f.def.options; - const localized = - objectKey && Array.isArray(options) - ? translateOptions(objectKey, f.name, options) - : options; - const declaredLabel = typeof f.def.label === 'string' ? f.def.label : ''; - return { - ...f, - def: { ...f.def, ...(localized ? { options: localized } : {}) }, - label: fieldLabel(objectKey, f.name, declaredLabel || f.name), - }; - }); - }, [pendingMove, objectDef, schema.objectName, translateOptions, fieldLabel]); + const options = f.def.options; + const localized = + objectKey && Array.isArray(options) + ? translateOptions(objectKey, f.name, options) + : options; + const declaredLabel = typeof f.def.label === 'string' ? f.def.label : ''; + return { + ...f, + def: { ...f.def, ...(localized ? { options: localized } : {}) }, + label: fieldLabel(objectKey, f.name, declaredLabel || f.name), + }; + }; + const pendingFields = pendingMove ? pendingMove.fields.map(labelPromptField) : []; + // objectstack#35956 — the dialog names the record and the move that set it + // off, and a value typed into it can make one more field required. + const pendingChange = (() => { + if (!pendingMove || !schema.groupBy) return null; + const objectKey = objectDef?.name || schema.objectName || ''; + const declared = objectDef?.fields?.[schema.groupBy]?.label; + const column = (effectiveColumns as Array<{ id: unknown; title?: unknown }>) + .find((c) => String(c.id) === String(pendingMove.toColumnId)); + const record = pendingMove.record; + const name = getRecordDisplayName(objectDef, record); + return { + recordName: typeof name === 'string' && name.length > 0 ? name : undefined, + changes: [{ + name: schema.groupBy, + label: fieldLabel(objectKey, schema.groupBy, typeof declared === 'string' && declared ? declared : schema.groupBy), + value: typeof column?.title === 'string' && column.title ? column.title : String(pendingMove.toColumnId), + }], + moreFields: (values: Record) => collectRequiredWhenPromptFields( + objectDef?.fields, + record, + { [schema.groupBy!]: pendingMove.toColumnId, ...values }, + { exclude: [schema.groupBy!] }, + ).map(labelPromptField), + }; + })(); // Error branch renders only after every hook above has run, so hook order // stays stable across renders (no early return before the hooks). @@ -2123,6 +2153,15 @@ export const ObjectKanban: React.FC = ({ setPendingMove(null)} onSubmit={async (values) => { diff --git a/ui/packages/plugin-kanban/src/RequiredFieldsDialog.tsx b/ui/packages/plugin-kanban/src/RequiredFieldsDialog.tsx deleted file mode 100644 index 5d62cb749cb..00000000000 --- a/ui/packages/plugin-kanban/src/RequiredFieldsDialog.tsx +++ /dev/null @@ -1,179 +0,0 @@ -/** - * 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. - */ - -/** - * The small collect-then-move dialog a kanban drop opens when the target - * column makes fields required — objectui#4254. - * - * ## Not a mini-form - * - * Every control here is `@object-ui/fields`' {@link FieldEditWidget}, i.e. the - * SAME widget the record form renders for that field type (its own header: - * "the SAME dedicated widgets the form renders"), which is also what the data - * grid's inline editor and the detail page's inline edit compose. So a select - * edits as a select, a date as a date picker, a boolean as a checkbox — - * without this package owning a single input implementation, and without a - * second set of field-rendering decisions that could drift from the form's. - * - * The validation is the same one definition too: `isMissingForRequired` from - * `@object-ui/core`, the presence contract the form and the server share, so - * this dialog cannot decide a value is "empty" in a way the server would - * disagree with (a `false` boolean and a `0` are values, not absences). - * - * ## Copy - * - * Through `useSafeTranslate` — the per-call `tt(key, fallback)` channel this - * package already uses — so a host with no `I18nProvider` mounted (a - * standalone board, this package's tests, the preview gallery) reads English - * instead of a raw key. The two new keys live in the `kanban` namespace of all - * ten locale packs; `common.cancel` and `kanban.moveCard` are reused rather - * than minted again, since one control's label should not get several - * translations that can drift apart. - */ - -import React from 'react'; -import { - Button, - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from '@object-ui/components'; -import { useSafeTranslate } from '@object-ui/react'; -import { isMissingForRequired } from '@object-ui/core'; -import { FieldEditWidget } from '@object-ui/fields'; -import type { RequiredWhenPromptField } from './requiredWhenPrompt'; - -/** A prompt field with its display label already resolved by the board. */ -export interface RequiredFieldsDialogField extends RequiredWhenPromptField { - label: string; -} - -export interface RequiredFieldsDialogProps { - open: boolean; - /** The required-and-empty fields, in the object's declared order. */ - fields: RequiredFieldsDialogField[]; - /** Disables the controls while the combined PATCH is in flight. */ - submitting?: boolean; - onCancel: () => void; - onSubmit: (values: Record) => void; -} - -export function RequiredFieldsDialog({ - open, - fields, - submitting, - onCancel, - onSubmit, -}: RequiredFieldsDialogProps): React.ReactElement { - const tt = useSafeTranslate(); - // Each drop is its own collection, and that is enforced by MOUNTING rather - // than by a reset effect: the board renders this component only while a move - // is pending, so cancelling or submitting unmounts it and the next drop - // starts from empty state. A `useEffect` re-seed would be both redundant and - // a cascading-render hazard the lint rule correctly flags. - const [values, setValues] = React.useState>({}); - // True only after a submit attempt, so the dialog opens clean rather than - // shouting "Required" at fields the user has not reached yet. - const [showErrors, setShowErrors] = React.useState(false); - - const missing = fields.filter((f) => isMissingForRequired(values[f.name])); - - const handleSubmit = () => { - if (missing.length > 0) { - setShowErrors(true); - return; - } - onSubmit(values); - }; - - return ( - { if (!next) onCancel(); }}> - - - - {tt('kanban.requiredFieldsTitle', 'Complete required fields')} - - - {tt( - 'kanban.requiredFieldsDescription', - 'This move makes the fields below required. Fill them in to continue.', - )} - - - -
- {fields.map((f) => { - const isMissing = isMissingForRequired(values[f.name]); - return ( - // A wrapping `label` gives the control its accessible name - // implicitly. This used to be justified with "`FieldEditWidget` - // renders the widget itself and takes no `id` to associate with, - // and widening its contract belongs to `@object-ui/fields`" — - // FALSE since objectui#7009 put `id` in `DOM_PASS_THROUGH_KEYS`: - // the factory takes an `id` and lands it on the real control. - // The reason is corrected rather than the markup changed - // (`f08bcd9af`), because a dead constraint left in a comment is - // how the next reader concludes it still binds. - // - // The wrapping form is still the right choice here, for a reason - // that IS still true: this dialog renders whatever field types the - // target column made required, and several of them resolve to - // COMPOSITE controls with no single labelable element for a - // `htmlFor` to point at — `RadioField` renders `
`, `CheckboxesField` `
`, - // `AddressField` a set of sibling inputs. One wrapping `label` - // covers every type uniformly and mints no ids. - - ); - })} -
- - - - - - -
- ); -} diff --git a/ui/packages/plugin-kanban/src/requiredWhenPrompt.ts b/ui/packages/plugin-kanban/src/requiredWhenPrompt.ts deleted file mode 100644 index c09359b5499..00000000000 --- a/ui/packages/plugin-kanban/src/requiredWhenPrompt.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * 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. - */ - -/** - * Which fields a kanban drop is about to make REQUIRED and empty — the - * pre-evaluation half of objectui#4254. - * - * Dropping a card into a column writes one value (`groupBy` := the column id), - * and that write can flip a field's `requiredWhen` predicate to TRUE. The board - * used to PATCH the column value alone, the engine refused the whole update - * (`Win Reason 不能为空`), and there was no way to finish the move from the - * board at all. This module answers the question that makes the move - * completable instead: *given the record and the value the drop is about to - * write, which fields become required while still being empty?* - * - * ## One evaluator, not two - * - * The verdict comes from `@object-ui/core`'s {@link resolveFieldRuleState} — - * the SAME function the record form (`components/renderers/form/form.tsx`), - * the wizard (`plugin-form/WizardForm.tsx`) and the line-item grid - * (`fields/widgets/GridField.tsx`) resolve `visibleWhen`/`readonlyWhen`/ - * `requiredWhen` with, which in turn delegates to `@objectstack/formula`'s - * `ExpressionEngine`. That is deliberate and load-bearing: the board's prompt - * and the server's enforcement must reach the identical verdict, and a second - * hand-rolled predicate evaluator is exactly how the two ends drift. The - * card's own predicate shape — `has(record.stage) && record.stage == - * "closed_won"` — was measured against that engine before this was written. - * - * ## Why "required" alone is not the filter - * - * A field is only offered when the dialog can honestly render a control for - * it, so four further conditions narrow the set. Each exclusion is a case - * where prompting would be worse than not prompting: - * - * - **already has a value** — the move is not what is missing. `required` is a - * PRESENCE contract, so the emptiness test is core's `isMissingForRequired` - * (the one the form and the server agree on: `false` and `0` are values, - * an empty array is not) rather than a truthiness check that would re-ask - * for every unchecked box. - * - **not visible** (`visibleWhen` FALSE) — the record form would not show it, - * so neither does this. - * - **readonly** — there is nothing the user could author. - * - **no edit widget** (`file`, `richtext`, `formula`, … — the types - * `@object-ui/fields` deliberately excludes from in-place editing) — a - * dialog row with no control is a worse dead end than the one being fixed. - * - * The last three fall through to the unchanged PATCH, where the server's - * refusal is now legible (objectstack#7525 is closed) — a legible refusal - * beats a dialog that cannot collect anything. - * - * The `groupBy` field itself is skipped: the drop IS its value. - */ -import { resolveFieldRuleState, isMissingForRequired } from '@object-ui/core'; -import { hasFieldEditWidget } from '@object-ui/fields'; - -/** A field the drop makes required, paired with the definition to render it. */ -export interface RequiredWhenPromptField { - /** Field name — the key the combined PATCH will carry. */ - name: string; - /** The field definition, with `name` guaranteed present for the widget. */ - def: Record & { type?: string }; -} - -/** - * The fields a move to `toColumnId` would make required and that are still - * empty, in the object's declared field order. - * - * Returns `[]` whenever the drop needs no prompt — the caller's signal to keep - * today's single-key PATCH exactly as it was. - * - * @param objectFields `objectDef.fields`, as fetched by the board. - * @param record The record as it stands BEFORE the drop. - * @param groupBy The field the board groups by (the one the drop writes). - * @param toColumnId The value the drop is about to write. - */ -export function collectRequiredWhenPromptFields( - objectFields: Record | null | undefined, - record: Record | null | undefined, - groupBy: string, - toColumnId: unknown, -): RequiredWhenPromptField[] { - if (!objectFields || !record) return []; - - // The record as the server would see it after the drop — this is what the - // predicates are judged against, and the whole reason the prompt can happen - // BEFORE the write rather than in reaction to a refusal. - const next = { ...record, [groupBy]: toColumnId }; - - const prompts: RequiredWhenPromptField[] = []; - for (const [name, raw] of Object.entries(objectFields)) { - if (name === groupBy) continue; - if (!raw || typeof raw !== 'object') continue; - const def = raw as Record; - - // Scoped to conditional requirements on purpose. A statically-required - // empty field means the record was already invalid before anyone touched - // the board; turning a drag into a general-purpose validation form is a - // different feature from the one that was approved. - if (def.requiredWhen == null) continue; - if (!isMissingForRequired(record[name])) continue; - - const state = resolveFieldRuleState( - { - visibleWhen: def.visibleWhen as never, - readonlyWhen: def.readonlyWhen as never, - requiredWhen: def.requiredWhen as never, - }, - next, - // `name` says which column of the pre-drop record is this field's stored - // value, so the drop is judged as the engine judges the write: a - // transition gate (objectstack#30220). A record already inside the gate - // without the value rests there, the engine lets the drop through, and - // the board asks for nothing. - { required: def.required === true, readonly: def.readonly === true, name }, - // The pre-drop record, so a predicate reading `previous.*` sees what the - // form would show it. - record, - undefined, - `field '${name}'`, - ); - - if (!state.required || !state.visible || state.readonly) continue; - if (!hasFieldEditWidget(def.type as string | undefined)) continue; - - prompts.push({ name, def: { name, ...def } }); - } - return prompts; -}