Skip to content

Commit 9a98a46

Browse files
feat(list,detail): a change that makes other fields required asks for them in place (#35994)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu5gFHCZrvoE2E7co6REx5Fq)_ repo:objectstack#1 · os-sales · session_01L6bhgWZ6R6aogVL9TTxNG8 Part of #35956 (PR 1 of 2, claim 7056727903: the shared prompt, the list cell, the record page's inline Save, the kanban on the shared copy. PR 2 moves the record header's stage menu onto it and deletes its own copy; it does not wait for #35853. The record drawer's per-field save is not this card; the seat files it.) 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 Skills-docs: `content/docs/frontend/plugins/plugin-grid.mdx` — the "On an object's list page" section gains one bullet (a change that makes other fields required asks for them). No skill under `skills/` teaches the in-place save, so nothing there moves. Follow-up: #35995 (the record drawer's per-field save asks too; Blocked-by this PR) Flow: dev-thread rule (maintainer 2026-11-20 09:22:50Z): the card thread builds itself; L1 by L1-a, the declaration L2 by the seat on the green head. ## 维护者速读 - 在列表单元格或记录页上改一个值(例如把项目状态改成「已完成」),如果这会让另一个还空着的字段变成必填,现在不再直接保存然后被服务端拒绝,而是先弹出「补填必填字段」框:先写记录名,再写这次改动(只读,如「状态:已完成」),下面列出要补的字段,用表单同款控件。 - 填好点「保存」,原改动和补填的值一次写入;点「取消」什么都不写,列表格子保持原值,记录页的编辑状态和草稿原样保留。不填就点保存,字段下面显示「必填」,框不关。补填的值又让别的字段变必填时,框里马上追加那个字段。 - 保存时服务端仍然拒绝,框不关,原因显示在对应字段下面,说不上字段的显示在框底部。如果是别人刚改过这条记录,会弹出和平常保存一样的冲突对比框,选「仍然覆盖」时补填的值一起写入。看板拖动用的是同一个框,行为不变。 - 第一轮审查后的修正:列表只取了显示的那几列,补填判断现在会先把缺的字段从记录里读回来再判断,所以已经填过但没显示成列的字段不会被要求重填、也不会被覆盖。 - 不弹框、照旧走拒绝提示的:字段已有值、不可见、只读、当前用户没有写权限、或者这种类型不能就地编辑(文件、富文本、公式)。记录抽屉里的逐字段保存这次也不弹,另开卡。 - 需要你决定的:无。 ## What changes **One prompt, shared** (`@object-ui/fields`). `requiredWhenPrompt.ts` and `RequiredFieldsDialog.tsx` move here from `@object-ui/plugin-kanban` (`git mv`, so the history follows); the kanban imports them from `@object-ui/fields`. Nothing else in the repository had a copy except the record header's stage menu, which PR 2 moves. - `collectRequiredWhenPromptFields(objectFields, record, changes, options?)` takes the change as a set of keys (`{ stage: 'won' }`, or a whole record-page draft) instead of one key. It judges `requiredWhen` on `{ ...record, ...changes }` with `resolveFieldRuleState`, the evaluator the form and the server share, as the engine's transition gate (objectstack#30220), exactly as the kanban did. It skips the same fields as before (already has a stored value, hidden, read-only, no in-place editor) and, new, any field the host's `fillable(name, def)` refuses. `exclude` defaults to the changed keys. - `RequiredFieldsDialog` now shows the record's name and the change rows (read-only, the option's label) above the fields, as the card's item 3 describes. A value typed in the dialog that makes one more field required adds that field at once (`moreFields`), and Save waits for it. When the host's `onSubmit` rejects, the dialog stays open: a reason that names a field shown is drawn under that field; a reason that names another field the reader can fill adds that field (`refusalField`); every other reason goes to the foot (`role="alert"`). Only the shown fields' values are sent. The defaults read `fields.requiredPromptTitle` / `fields.requiredPromptDescription` and Save; the kanban keeps its own title, description and 「移动卡片」 button. **The list cell** (`@object-ui/plugin-grid`, `ObjectGrid`; a grid with `cellSelection`, i.e. every grid `ListView` draws). `useCellRequiredPrompt` (`objectGridRequiredPrompt.tsx`) answers the S3 seam `GridCellSelection.confirmCommit` before the state-machine confirm: when the committed value makes fields required, it opens the dialog and nothing is staged or sent. The row is the view's projection (the grid fetches the columns it draws), so before judging, the prompt compares the keys the judgment reads (`requiredWhenPromptReads`: every field it could ask for, and the declared fields its `requiredWhen` / `visibleWhen` / `readonlyWhen` predicates name) with the keys the row carries, and reads the missing ones from the record (one `findOne` with `$select` those keys). A row that carries them all reads nothing more; a read that fails asks nothing and the write goes ahead for the server to judge. Save writes the cell's value and the typed values in one `onRowSave ?? defaultRowSave` call, so the existing in-place write applies (one guarded update, redraw in place, undo notice, the 409 conflict dialog); the seam is then answered `false` so the table does not write a second time. Cancel answers `false` and the cell keeps what it showed. `fillable` is the list's own inline-edit test (`resolveFieldAffordance('listInlineEdit', …)` plus field permissions). When this dialog opens it replaces the state-machine confirm for that commit, so the reader is asked once. **The record page's inline Save** (`@object-ui/plugin-detail`, `InlineEditSaveBar`). In the atomic mode (no `onFieldSave`), Save first collects against the record context's object schema and the draft. When fields come back, nothing is written and the dialog opens; its Save sends `{ ...draft, ...values }` in one `update` with `If-Match` the record's current `updated_at`, then re-reads and leaves edit mode, as a plain Save does. A 409 opens the page's own conflict dialog over it, as a plain Save's 409 does: Overwrite sends the draft and the typed values at the version the server reported, Reload drops the edit, Cancel comes back to the fill-in dialog with the values still typed. Cancel closes the dialog only: the edit session and its draft stay. `fillable` is the page's record-edit test (`resolveFieldAffordance('recordEdit', …)`, permissions, computed and system fields). The per-field callback mode the drawer uses is not asked. Strings: `fields.requiredPromptTitle` / `fields.requiredPromptDescription` in all eleven locale packs (zh-Hant regenerated by `gen:zh-hant`), with English fallbacks through `useSafeTranslate`. ## Acceptance notes The card's items, as this PR covers them: 1. The prompt and dialog are lifted into `@object-ui/fields`; the kanban uses them with its behaviour unchanged (its 8 prompt tests pass, two assertions added for the record name and change row). 2. The list cell, the record page's inline Save and the kanban drop ask. The record header's stage menu is PR 2. 3. Dialog content as described; Save writes one update; Cancel writes nothing. 4. Chained requirements: measured in tests and the browser. 5. A refusal stays in the dialog: under the field, as an added field, or at the foot. 6. What cannot be foreseen is written and refused as before (measured with a rich-text field below). 7. The 「打开记录」 link in the list's refusal notice was already delivered by S1 (#35864): `data-table`'s `needsRecord`, and the browser reads 「保存失败: Cancel Memo不能为空 打开记录完成修改」 below. No code change here. Readings I chose: - In the list, the fill-in dialog replaces the state-machine confirm for that commit, so the reader is asked once, not twice. Its change row names the move. - On the record page, Cancel keeps the edit session and its draft (the card says the change is not written and the screen returns to before the change; on the record page the draft is what the reader typed, so it is kept for them to change or cancel). - A conflicting write by someone else while a fill-in dialog is open: on both surfaces the surface's own conflict dialog comes up over it, the one a plain save opens there. The list's (`askRowConflict`) overwrite writes and its Cancel rethrows, so the fill-in dialog shows the reason; the record page's is measured in its tests (below). The browser run saw the list's conflict dialog open but did not click either choice. - When the list must read the record first, the commit waits for that read before the dialog opens or the write goes. Only an object with a `requiredWhen` field the row lacks pays it. - 375 px: the list draws cards, not table cells (S3's reading), so the phone check is the record page's dialog. Platform checklist: no clause moves. ## Tests Migrated (moved from `@object-ui/plugin-kanban` with `git mv`, assertions kept): - `ui/packages/fields/src/requiredWhenPrompt.test.ts`: the 13 single-key calls now pass `{ key: value }`; new block for a multi-key change, a chained field and `fillable`. - `ui/packages/fields/src/__tests__/RequiredFieldsDialog.ariaInvalid-7008.test.tsx`, `…ariaInvalidText-7126.test.tsx`, `…datePicker-12664.test.tsx`: the submit button's name is the generic default `Save` instead of `Move card` (the kanban passes its own); nothing else changed. New: - `ui/packages/fields/src/__tests__/RequiredFieldsDialog.inPlace-35956.test.tsx` (5): record name and change rows; a chained field joins and Save waits for it; a refusal naming a shown field draws under it, one naming a fillable field adds it; an unattributed refusal is listed at the foot; Cancel sends nothing. - `ui/packages/plugin-grid/src/__tests__/ObjectGrid.requiredPrompt-35956.test.tsx` (11; its server honours `$select`, as a real one does): the dialog opens for a field with no column and writes nothing; Save sends one guarded update `{ stage: 'won', win_reason: … }` with `ifMatch`; Cancel writes nothing and the cell keeps its value; a refusal is drawn under the field; controls: a field that already has a value, and a rich-text field, are not asked. Round 1: a stored value that is not a column is read (`findOne` `$select: ['win_reason']`), not asked for, not overwritten; an empty one read the same way still asks; a predicate operand outside the columns is judged on its stored value (asks for `enterprise`, not for `smb`); a failed read asks nothing; a row that carries every key reads nothing more. - `ui/packages/plugin-detail/src/__tests__/InlineEditSaveBar.requiredPrompt-35956.test.tsx` (8): the dialog names the record and change and writes nothing; Save sends one guarded update and leaves edit mode; Cancel keeps the session and the draft; a refusal stays in the dialog; controls: a draft that makes nothing required saves at once, and the drawer's callback mode never asks. Round 1: a 409 opens the conflict dialog with nothing re-read, and Overwrite sends `{ stage, win_reason }` with `ifMatch` the reported version; the conflict dialog's Cancel comes back to the fill-in dialog with the value still typed. - `ui/packages/fields/src/requiredWhenPrompt.test.ts`, round 1: `requiredWhenPromptReads` names the askable fields and their declared operands (`record.` and `previous.`), skips a field with no editor, an unfillable one and an undeclared operand, and reads nothing for an object with nothing to ask. - `ui/packages/plugin-kanban/src/ObjectKanban.requiredWhenPrompt.test.tsx`: two assertions added (record name, change row). Ablation (committed first, mutated through `scripts/ablation-replace.mjs`, restored to the HEAD blob with `git diff HEAD` empty): - the grid's `requiredPrompt.ask` replaced by `null` → 4 failed / 6 in `ObjectGrid.requiredPrompt-35956`; restored → green. - the save bar's `fields.length > 0` turned to `< 0` → 4 failed / 6 in `InlineEditSaveBar.requiredPrompt-35956`; restored → green. - the dialog's `moreFields` ignored → 1 failed / 5 in `RequiredFieldsDialog.inPlace-35956`; restored → green. - `presentRefusal` emptied → 4 failed across three files; restored → green. - the kanban's change row dropped → 1 failed / 8 in `ObjectKanban.requiredWhenPrompt`; restored → green. - round 1 (on `1462c319`): the list prompt never reads (`if (true || …)`) → 5 failed / 11 in `ObjectGrid.requiredPrompt-35956`, the old control "a field that already has a value" among them now that the server honours `$select`; the dialog's 409 not routed to the conflict dialog → 2 failed / 8 in `InlineEditSaveBar.requiredPrompt-35956`; the overwrite sends the draft alone → 1 failed / 8; each restored → green. ## Review round 1 (L1-a 7057894230 REWORK on `59fb5217`; the seat's declaration L2 on the same head, not posted) - **M1 must-fix (list judged a projected row):** fixed as described under *What changes*: the keys the judgment reads and the row lacks are read from the record first. I chose the re-read over widening the two projections (`objectGridRowLoad.ts#getSelectFields`, `ListView.tsx#selectFields`): it costs nothing on an object without `requiredWhen`, and it judges the stored values at the moment of the change rather than at the list's last fetch. Pinned with a `find` and `findOne` that honour `$select`; the existing control now passes only through the read (ablation above). - **S1 should-fix / L2 F1 (409 in the record page's dialog):** fixed: the page's conflict dialog, with the typed values carried into its overwrite (`conflictWriteRef`), and nothing re-read under the reader. - **N1 / L2 F2 (`Math.max(index, 0)`):** a row no longer among the loaded rows now fails the save with `table.saveFailed` in the dialog rather than handing a host index `0`. - **N2 / L2 F3 (wording):** the body now says the record page guards on the record's current `updated_at`, as the plain Save does; the code is unchanged there. - Follow-up named: #35995. - Round-1 runs, on `9a473a0c` (main merged after #35990, which the seat landed first; no conflict): `vitest` from `ui/`, one package at a time: `fields` 314 files / 4731 tests passed (1 file skipped); `plugin-grid` 296 / 2602; `plugin-detail` 395 / 3636 (1 skipped); `plugin-list` 181 / 1965; `plugin-kanban` 81 / 533; `i18n` 105 / 1957. `tsc --noEmit` clean for `fields`, `plugin-grid`, `plugin-detail`, `plugin-kanban`; eslint on the changed files 0 errors. `dispatch-gates --commands` re-derived on this head, 74 families, all exit 0 (`vitest run scripts/` with one worker); `--ran` 74 derived, 74 run, 0 NOT-MEASURED, 0 UNRUN. `overlap-check` VERDICT clean (main `a6607c79` and 4 PR heads). The built `dist/index.d.ts` of `@object-ui/fields` exports `requiredWhenPromptReads`. - Round-1 browser, against the real server (it answers a projection): `Website Relaunch` with `completion_note = 'Already noted'` stored and no Completion Note column on the list; pick 「已完成」 → no fill-in dialog, one `GET` of the record, the state confirm, then `PATCH {"status":"completed"}` → 200; stored afterwards `completion_note = "Already noted"`. On `59fb5217` the same row would have opened the dialog (the empty-note case still opens it, run 1 of the same script). Log `r1-m1-journey.log` beside the other evidence. ## Verification <details><summary>Local runs</summary> - `vitest` from `ui/`, one package at a time, on the tree of `59fb5217` (the commit was reworded for the trailer check only, no file changed): `fields` 313 files / 4719 tests passed (1 file skipped); `plugin-kanban` 81 / 533; `i18n` 105 / 1957; `plugin-detail` 395 / 3632 (1 skipped); `plugin-grid` 296 / 2597; `plugin-list` 183 / 1979 with one red, `ListView.relationalSort` "CONTROL: a sort on a plain field" timing out at 15 s while the gate loop ran beside it, re-run alone 9/9 passed. - `type-check` (`tsc --noEmit`) for `@object-ui/fields`, `@object-ui/plugin-grid`, `@object-ui/plugin-detail`, `@object-ui/plugin-kanban`: clean (after building their dependency dists). `eslint` on every changed source and test file: 0 errors. - Clause-② measured on the built declarations: `dist/index.d.ts` of `@object-ui/fields` now exports `collectRequiredWhenPromptFields`, `RequiredFieldsDialog` and the five types; `@object-ui/plugin-kanban`'s built index never exported either file. - `node scripts/pm/dispatch-gates.mjs --commands`: 74 families, each run with its exit captured before any pipe. 72 exit 0 on the first pass; two re-run alone: `vitest run scripts/` under `ui/` was SIGKILLed while a package suite ran beside it, re-run with one worker 172 files / 5111 tests passed; `check:skill-examples` refused with exit 3 on a stale `@objectstack/client-react` dist, re-run after building it, exit 0. `--ran`: 74 derived, 74 run, 0 NOT-MEASURED, 0 UNRUN. - `node scripts/pm/overlap-check.mjs`: VERDICT clean (against main `f9f45d34` and 4 open PR heads). - Changed lines about 1,960 (including the four moved files' rewrites) vs the 3000 threshold: under. </details> <details><summary>Browser</summary> `examples/app-showcase` (`objectstack dev --fresh --seed-admin`, own port and temp DB) with the `ui/apps/console` Vite dev server over it, headless Chromium, zh-CN, light and dark, desktop 1600×1000 and 375×812. No shipped object declares `requiredWhen`, so for the run only (not committed) `showcase_project` gained three probe fields: `completion_note` (text, required when `status == 'completed'`), `follow_up` (required when `completion_note == 'partial'`) and `cancel_memo` (rich text, required when `status == 'cancelled'`). Before (the two host wirings ablated, i.e. main's behaviour): - List: pick 「已完成」 for 「Website Relaunch」 → the state-machine confirm only, then `PATCH {"status":"completed"}` → 400 「Completion Note不能为空」; the notice reads 「保存失败: Completion Note不能为空 打开记录完成修改」 and there is nowhere to fill the field. - Record page: inline Save → `PATCH` → 400; the save bar lists 「Completion Note: Completion Note不能为空」. After, list: - Pick 「已完成」 → the dialog 「补填必填字段」 with 「Website Relaunch」, 「状态: 已完成」 and 「Completion Note *」; 0 writes while it is open. `completion_note` is not a column of the view. - Save empty → 「必填」 under the field, the dialog stays, 0 writes. - Type `partial` → 「Follow-up Owner *」 joins. - Cancel → 0 writes, the cell still reads 「进行中」. - Again, fill and Save → one `PATCH {"status":"completed","completion_note":"Shipped on time"}` with `If-Match` → 200, the cell reads 「已完成」. - 「已取消」 (the required field is rich text) → no dialog; the state confirm, then `PATCH {"status":"cancelled"}` → 400 and the notice 「保存失败: Cancel Memo不能为空 打开记录完成修改」, as before. - Another user writes the record while the dialog is open, then Save → 409; the grid's conflict dialog opens over the fill-in dialog. - Dark theme: the same through Cancel. After, record page (light, dark, 375): - Inline edit 「状态」 to 「已完成」, Save → the dialog; 0 writes. - Cancel → the save bar and the draft are still there. - Chain, then Save → one `PATCH {"status":"completed","completion_note":"partial","follow_up":"ops@example.com"}` → 200, edit mode left. - 375 px: the dialog fits the screen, the controls work. Evidence (screenshots and journey logs) is with the seat. Not measured: Safari / WebKit (no WebKit build in the container), the kanban drag in the browser (its tests cover it, and its code path changed only in what it passes to the dialog). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (eslint on the changed files: 0 errors) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. (The branch is the platform-assigned `claude/project-thread-4on43b`, named in the claim.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (the 维护者速读 block and the quoted UI strings are Chinese by the maintainer's standing rule) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgWZ6R6aogVL9TTxNG8 <!-- signed: repo:objectstack#1 · os-sales · session_01L6bhgWZ6R6aogVL9TTxNG8 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent eb53d63 commit 9a98a46

30 files changed

Lines changed: 1913 additions & 394 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@object-ui/fields': patch
3+
'@object-ui/plugin-kanban': patch
4+
'@object-ui/plugin-grid': patch
5+
'@object-ui/plugin-detail': patch
6+
'@object-ui/i18n': patch
7+
---
8+
9+
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
10+
11+
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
12+
Metadata-protocol: none
13+
14+
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:
15+
16+
- **Where:** a list cell in the select-first grid every `ListView` draws, the record page's inline Save, and the kanban drop (as before).
17+
- **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.
18+
- **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.
19+
- **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.
20+
- **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.
21+
22+
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.

‎content/docs/frontend/plugins/plugin-grid.mdx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,19 @@ row whose new value would sort it elsewhere stays in place until the next load
447447
trigger related automation."). Cancel writes nothing and the cell keeps the
448448
value it had; Change saves it as any commit is saved. The confirm does not
449449
list the flows. A host asks this through `GridCellSelection.confirmCommit`.
450+
- **A change that makes other fields required asks for them** (objectstack#35956).
451+
When the new value makes a field's `requiredWhen` true while that field is
452+
still empty (a win reason on "Won", say), nothing is written yet: a dialog
453+
names the record and the change and asks for those fields, with the editors
454+
the record form uses, whether or not the view draws them as columns. A value
455+
typed there that makes one more field required adds it. Save writes the cell
456+
and the typed values as one update; Cancel writes nothing and the cell keeps
457+
its value. A refusal of that update stays in the dialog, under the field it
458+
names. That dialog is the confirmation, so a state-machine field does not ask
459+
twice. A field that has a value, is hidden or read-only, the reader may not
460+
write, or has no in-place editor (a file, rich text) is not asked for: the
461+
change is saved and refused as before. The kanban drop and the record page's
462+
inline Save open the same dialog (`RequiredFieldsDialog` in `@object-ui/fields`).
450463
- **The record drawer follows.** A record open in the list's drawer is read
451464
again when a list cell saves it. If the drawer holds unsaved edits of its own,
452465
those stay as typed, the drawer's save bar says the record was changed
Lines changed: 328 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* The small collect-then-save dialog an in-place change opens when it makes
11+
* other fields required — objectui#4254 (the kanban drop), made shared by
12+
* objectstack#35956 so a list cell and the record page's inline edit open the
13+
* same one. The host decides WHEN to open it (`collectRequiredWhenPromptFields`
14+
* returned fields) and owns the write; this dialog collects the values.
15+
*
16+
* ## What it shows
17+
*
18+
* The record's name, then the change that set this off as read-only rows
19+
* (`changes`, e.g. 「销售阶段:赢单」), then one row per field to fill. Save
20+
* hands the host the typed values, and the host writes them together with the
21+
* change in ONE write; Cancel writes nothing.
22+
*
23+
* ## Chained requirements
24+
*
25+
* A value typed here can make one more field required (`moreFields`): it joins
26+
* the dialog at once, nothing is saved half-way, and Save waits for it too.
27+
*
28+
* ## A refusal stays in the dialog
29+
*
30+
* When the host's `onSubmit` rejects (someone else changed the record, a rule
31+
* the prompt could not foresee), the dialog stays open and says why: a reason
32+
* naming a field shown here is drawn under that field; one naming another
33+
* field the reader can fill adds that field (`refusalField`); every other
34+
* reason is listed at the foot. A host whose `onSubmit` settles its own
35+
* failures (the kanban board's toast and rollback) simply never rejects.
36+
*
37+
* ## Not a mini-form
38+
*
39+
* Every control here is {@link FieldEditWidget}, i.e. the SAME widget the
40+
* record form renders for that field type (its own header: "the SAME dedicated
41+
* widgets the form renders"), which is also what the data grid's inline editor
42+
* and the detail page's inline edit compose. So a select edits as a select, a
43+
* date as a date picker, a boolean as a checkbox — without a second set of
44+
* field-rendering decisions that could drift from the form's.
45+
*
46+
* The validation is the same one definition too: `isMissingForRequired` from
47+
* `@object-ui/core`, the presence contract the form and the server share, so
48+
* this dialog cannot decide a value is "empty" in a way the server would
49+
* disagree with (a `false` boolean and a `0` are values, not absences).
50+
*
51+
* ## Copy
52+
*
53+
* Through `useSafeTranslate` — the per-call `tt(key, fallback)` channel — so a
54+
* host with no `I18nProvider` mounted (a standalone board, a package's tests,
55+
* the preview gallery) reads English instead of a raw key. The host may pass
56+
* its own `title`, `description` and `submitLabel` (the board keeps its
57+
* 「移动卡片」).
58+
*/
59+
60+
import React from 'react';
61+
import {
62+
Button,
63+
Dialog,
64+
DialogContent,
65+
DialogDescription,
66+
DialogFooter,
67+
DialogHeader,
68+
DialogTitle,
69+
} from '@object-ui/components';
70+
import {
71+
useSafeTranslate,
72+
declaredUserMessage,
73+
extractFieldErrors,
74+
extractWriteErrorMessage,
75+
} from '@object-ui/react';
76+
import { isMissingForRequired } from '@object-ui/core';
77+
import { FieldEditWidget } from './FieldEditWidget.js';
78+
import type { RequiredWhenPromptField } from './requiredWhenPrompt.js';
79+
80+
/** A prompt field with its display label already resolved by the host. */
81+
export interface RequiredFieldsDialogField extends RequiredWhenPromptField {
82+
label: string;
83+
}
84+
85+
/** One read-only row naming a value of the change that opened the dialog. */
86+
export interface RequiredFieldsDialogChange {
87+
name: string;
88+
label: string;
89+
/** The value as the reader reads it (an option's label, not its code). */
90+
value: string;
91+
}
92+
93+
export interface RequiredFieldsDialogProps {
94+
open: boolean;
95+
/** The required-and-empty fields, in the object's declared order. */
96+
fields: RequiredFieldsDialogField[];
97+
/** Disables the controls while the host's write is in flight. */
98+
submitting?: boolean;
99+
onCancel: () => void;
100+
/**
101+
* Called with the typed values once every field shown has one. The host
102+
* writes them with its change; a rejection keeps the dialog open and shows
103+
* the reason (see the file header).
104+
*/
105+
onSubmit: (values: Record<string, unknown>) => void | Promise<void>;
106+
/** The record's display name, drawn first. */
107+
recordName?: string;
108+
/** The change that set this off, drawn read-only above the fields. */
109+
changes?: RequiredFieldsDialogChange[];
110+
/**
111+
* The fields the typed values make required in turn (chained requirements),
112+
* asked on every change of the values; shown after `fields`, de-duplicated.
113+
*/
114+
moreFields?: (values: Record<string, unknown>) => RequiredFieldsDialogField[];
115+
/**
116+
* A field a refusal names that is not shown yet: the row to add for it, or
117+
* `null` when the reader cannot fill it here (its reason is then listed at
118+
* the foot).
119+
*/
120+
refusalField?: (name: string) => RequiredFieldsDialogField | null;
121+
/** The label of a field a foot line names; `undefined` reads the reason alone. */
122+
labelOf?: (name: string) => string | undefined;
123+
title?: string;
124+
description?: string;
125+
submitLabel?: string;
126+
}
127+
128+
/** The reasons a rejected submit carries: per field, and the rest. */
129+
function refusalOf(err: unknown): { entries: Array<{ field: string; message: string }>; fallback: string | null } {
130+
const entries = (extractFieldErrors(err) ?? [])
131+
.filter((e) => typeof e.message === 'string' && e.message.length > 0)
132+
.map((e) => ({ field: e.field, message: e.message as string }));
133+
return { entries, fallback: entries.length > 0 ? null : declaredUserMessage(err) ?? extractWriteErrorMessage(err) ?? null };
134+
}
135+
136+
export function RequiredFieldsDialog({
137+
open,
138+
fields,
139+
submitting,
140+
onCancel,
141+
onSubmit,
142+
recordName,
143+
changes,
144+
moreFields,
145+
refusalField,
146+
labelOf,
147+
title,
148+
description,
149+
submitLabel,
150+
}: RequiredFieldsDialogProps): React.ReactElement {
151+
const tt = useSafeTranslate();
152+
// Each change is its own collection, and that is enforced by MOUNTING rather
153+
// than by a reset effect: hosts render this component only while a change is
154+
// pending, so cancelling or saving unmounts it and the next change starts
155+
// from empty state. A `useEffect` re-seed would be both redundant and a
156+
// cascading-render hazard the lint rule correctly flags.
157+
const [values, setValues] = React.useState<Record<string, unknown>>({});
158+
// True only after a submit attempt, so the dialog opens clean rather than
159+
// shouting "Required" at fields the user has not reached yet.
160+
const [showErrors, setShowErrors] = React.useState(false);
161+
// The last refusal: per-field reasons, the fields it added, the foot lines.
162+
const [serverErrors, setServerErrors] = React.useState<Record<string, string>>({});
163+
const [addedFields, setAddedFields] = React.useState<RequiredFieldsDialogField[]>([]);
164+
const [footLines, setFootLines] = React.useState<string[]>([]);
165+
const [sending, setSending] = React.useState(false);
166+
const busy = !!submitting || sending;
167+
168+
const shown: RequiredFieldsDialogField[] = [];
169+
const seen = new Set<string>();
170+
for (const f of [...fields, ...(moreFields?.(values) ?? []), ...addedFields]) {
171+
if (seen.has(f.name)) continue;
172+
seen.add(f.name);
173+
shown.push(f);
174+
}
175+
const missing = shown.filter((f) => isMissingForRequired(values[f.name]));
176+
177+
const presentRefusal = (err: unknown) => {
178+
const { entries, fallback } = refusalOf(err);
179+
const byField: Record<string, string> = {};
180+
const added: RequiredFieldsDialogField[] = [];
181+
const lines: string[] = [];
182+
for (const { field, message } of entries) {
183+
if (seen.has(field) || added.some((f) => f.name === field)) {
184+
if (!(field in byField)) byField[field] = message;
185+
continue;
186+
}
187+
const row = refusalField?.(field) ?? null;
188+
if (row) {
189+
added.push(row);
190+
byField[field] = message;
191+
continue;
192+
}
193+
const label = labelOf?.(field);
194+
const line = label ? `${label}: ${message}` : message;
195+
if (!lines.includes(line)) lines.push(line);
196+
}
197+
if (fallback) lines.push(fallback);
198+
if (entries.length === 0 && !fallback) lines.push(tt('table.saveFailed', 'Save failed'));
199+
setServerErrors(byField);
200+
setAddedFields((prev) => [...prev, ...added.filter((f) => !prev.some((p) => p.name === f.name))]);
201+
setFootLines(lines);
202+
};
203+
204+
const handleSubmit = async () => {
205+
if (busy) return;
206+
if (missing.length > 0) {
207+
setShowErrors(true);
208+
return;
209+
}
210+
// Only the fields shown are sent: a value typed for a chained field that
211+
// a later edit made unnecessary again stays out of the write.
212+
const sent = Object.fromEntries(shown.map((f) => [f.name, values[f.name]]));
213+
setFootLines([]);
214+
setSending(true);
215+
try {
216+
await onSubmit(sent);
217+
} catch (err) {
218+
presentRefusal(err);
219+
} finally {
220+
setSending(false);
221+
}
222+
};
223+
224+
return (
225+
<Dialog open={open} onOpenChange={(next) => { if (!next && !busy) onCancel(); }}>
226+
<DialogContent
227+
className="sm:max-w-md max-h-[90dvh] overflow-y-auto"
228+
data-testid="required-fields-dialog"
229+
>
230+
<DialogHeader>
231+
<DialogTitle>
232+
{title ?? tt('fields.requiredPromptTitle', 'Complete required fields')}
233+
</DialogTitle>
234+
<DialogDescription>
235+
{description ?? tt(
236+
'fields.requiredPromptDescription',
237+
'This change makes the fields below required. Fill them in to save it.',
238+
)}
239+
</DialogDescription>
240+
</DialogHeader>
241+
242+
{(recordName || (changes && changes.length > 0)) && (
243+
<div className="flex flex-col gap-2 rounded-md border bg-muted/40 px-3 py-2" data-required-fields-change="">
244+
{recordName && (
245+
<p className="min-w-0 break-words text-sm font-semibold">{recordName}</p>
246+
)}
247+
{changes && changes.length > 0 && (
248+
<dl className="flex flex-col gap-1 text-sm">
249+
{changes.map((c) => (
250+
<div key={c.name} className="flex min-w-0 flex-wrap gap-x-1.5" data-required-fields-change-row={c.name}>
251+
<dt className="text-muted-foreground">{c.label}:</dt>
252+
<dd className="min-w-0 break-words font-medium">{c.value}</dd>
253+
</div>
254+
))}
255+
</dl>
256+
)}
257+
</div>
258+
)}
259+
260+
<div className="flex flex-col gap-4 py-2">
261+
{shown.map((f) => {
262+
const isMissing = isMissingForRequired(values[f.name]);
263+
const message = serverErrors[f.name]
264+
?? (showErrors && isMissing ? tt('common.required', 'Required') : undefined);
265+
return (
266+
// A wrapping `label` gives the control its accessible name
267+
// implicitly. `FieldEditWidget` does take an `id` (objectui#7009
268+
// put it in `DOM_PASS_THROUGH_KEYS`), but this dialog renders
269+
// whatever field types the change made required, and several of
270+
// them resolve to COMPOSITE controls with no single labelable
271+
// element for a `htmlFor` to point at — `RadioField` renders
272+
// `<div role="radiogroup">`, `CheckboxesField` `<div
273+
// role="group">`, `AddressField` a set of sibling inputs. One
274+
// wrapping `label` covers every type uniformly and mints no ids.
275+
<label key={f.name} className="flex flex-col gap-1.5" data-required-fields-field={f.name}>
276+
<span className="text-sm font-medium">
277+
{f.label}
278+
<span className="text-destructive ml-0.5" aria-hidden="true">*</span>
279+
</span>
280+
<FieldEditWidget
281+
field={f.def as never}
282+
value={values[f.name]}
283+
onChange={(v: unknown) => {
284+
setValues((prev) => ({ ...prev, [f.name]: v }));
285+
// A server reason is about the value it was given; a new
286+
// value retires it.
287+
setServerErrors((prev) => {
288+
if (!(f.name in prev)) return prev;
289+
const next = { ...prev };
290+
delete next[f.name];
291+
return next;
292+
});
293+
}}
294+
readonly={busy}
295+
// A widget reads `error` ONLY to drive `aria-invalid` (the
296+
// #3222 contract — the message TEXT stays with the host), so
297+
// the same string as the visible hint below cannot
298+
// double-display (objectui#7008).
299+
error={message}
300+
/>
301+
{message && (
302+
<span className="text-xs text-destructive" data-required-fields-error={f.name}>
303+
{message}
304+
</span>
305+
)}
306+
</label>
307+
);
308+
})}
309+
</div>
310+
311+
{footLines.length > 0 && (
312+
<div role="alert" className="flex flex-col gap-1 text-sm text-destructive" data-required-fields-refusal="">
313+
{footLines.map((line) => <p key={line} className="break-words">{line}</p>)}
314+
</div>
315+
)}
316+
317+
<DialogFooter>
318+
<Button variant="outline" onClick={onCancel} disabled={busy}>
319+
{tt('common.cancel', 'Cancel')}
320+
</Button>
321+
<Button onClick={() => { void handleSubmit(); }} disabled={busy}>
322+
{submitLabel ?? tt('common.save', 'Save')}
323+
</Button>
324+
</DialogFooter>
325+
</DialogContent>
326+
</Dialog>
327+
);
328+
}

ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.ariaInvalid-7008.test.tsx renamed to ui/packages/fields/src/__tests__/RequiredFieldsDialog.ariaInvalid-7008.test.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ describe('RequiredFieldsDialog tells assistive tech about a failed required fiel
8484
// after the click would prove nothing.
8585
expect(screen.getByTestId('select-trigger-stage')).toHaveAttribute('aria-invalid', 'false');
8686

87-
fireEvent.click(screen.getByText('Move card'));
87+
fireEvent.click(screen.getByText('Save'));
8888

8989
// The submit is refused (that half already worked) …
9090
expect(onSubmit).not.toHaveBeenCalled();
@@ -117,7 +117,7 @@ describe('RequiredFieldsDialog tells assistive tech about a failed required fiel
117117
const notes = screen.getByRole('textbox');
118118
fireEvent.change(notes, { target: { value: 'ready to move' } });
119119

120-
fireEvent.click(screen.getByText('Move card'));
120+
fireEvent.click(screen.getByText('Save'));
121121

122122
// Still refused, because the select is still empty.
123123
expect(onSubmit).not.toHaveBeenCalled();

ui/packages/plugin-kanban/src/__tests__/RequiredFieldsDialog.ariaInvalidText-7126.test.tsx renamed to ui/packages/fields/src/__tests__/RequiredFieldsDialog.ariaInvalidText-7126.test.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ function textControl(name = 'title'): Element {
5353
return el;
5454
}
5555

56-
const moveCard = () => fireEvent.click(screen.getByText('Move card'));
56+
const moveCard = () => fireEvent.click(screen.getByText('Save'));
5757

5858
describe('RequiredFieldsDialog marks a failed required TEXT field (objectui#7126)', () => {
5959
it('a required text field reports aria-invalid once a submit attempt finds it empty', () => {

0 commit comments

Comments
 (0)