diff --git a/.changeset/35889-form-places-detail-at-group.md b/.changeset/35889-form-places-detail-at-group.md new file mode 100644 index 00000000000..712c40ffc8a --- /dev/null +++ b/.changeset/35889-form-places-detail-at-group.md @@ -0,0 +1,19 @@ +--- +'@object-ui/plugin-form': patch +'@object-ui/components': patch +'@objectstack/spec': patch +--- + +fix(ui): the entry form draws a group-placed master-detail table at its field group + +Clause-②: no +Metadata-protocol: none + +A master-detail child that a field group of the parent places (`fieldGroups[].relatedList`) is now drawn at that group in the parent's create and edit forms, where the record page draws it, instead of below all of the record's fields: + +- A form laid out from the parent's field groups draws the table after the sections of the groups declared before the placing group and before the ones declared after it. +- The form's section bar stops at the table too, between the sections around it. +- A tabbed form gives it a tab of its own at that position, labelled with the group's label. A wizard master-detail form is drawn as the simple form, as before, and places it the same way. +- A form whose sections name no field group, and a child no group places (a form view's own `subforms`), keep the table below the record's fields, as before. + +The table is the same one: its rows still save with the record in one batch, an expanded row's editor opens beside it, and the document totals stay at the foot of the form. No metadata changes. diff --git a/.changeset/35889-master-detail-tab-by-default.md b/.changeset/35889-master-detail-tab-by-default.md index d3672ae5bc8..b69c182ec46 100644 --- a/.changeset/35889-master-detail-tab-by-default.md +++ b/.changeset/35889-master-detail-tab-by-default.md @@ -19,7 +19,7 @@ A `master_detail` FK that declares no `relatedList` used to put its child list i - `inlineEdit` on the FK no longer inlines a child in the parent's form by itself (maintainer ruling B: only the field group decides). It now only picks the form factor of a child a group places: `'grid'`, `'form'`, or `true` / absent for the shape-picked default. A child with `inlineEdit` that no group names is a tab and is not in the form. - `os lint`: `relationship/line-items-inline-edit` now suggests a field group on the parent (with its required `label`) instead of `inlineEdit: true`, and only for a FK a group may place; `relationship/association-inline-edit` and `relationship/inline-edit-needs-bulk` judge the children a parent group places; the field-consumer rule credits a child's inline grid columns only when a parent group places it. - The showcase invoice and expense report, and the CRM opportunity, gain a field group naming their lines, so their forms and record pages keep the line table. -- In the entry form a placed table still sits below the record's fields, where `inlineEdit` tables sit today. Moving it to its group's place in the form is a follow-up. +- In the entry form a placed table sits at its group's place too: between the sections of the groups around it, or in a tab of its own (labelled with the group) in a tabbed form. A form whose sections name no field group keeps it below the record's fields. - Studio's field-group picker offers the same children as before. The relationship field inspector reads a plain `master_detail` FK as "Show", and "Show" leaves the key absent so a group can still place it. To keep a master-detail child's table in the overview and its rows in the form (including a child that set `inlineEdit`), add a field group to the parent that names it, in the place the table should sit: diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 2039c7c6511..7b724f54255 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -331,7 +331,7 @@ const result = ApiMethod.parse(data); | **fields** | `string[]` | optional | The group's members in display order (field names of this object). Written, it decides which fields the group shows and their order on the record page and the forms, without changing the order of the object's fields. Absent, members are the fields whose `group` names this group, in field declaration order (the older spelling, still read). A field whose `group` names this group but that the list does not name follows the listed ones. Refused: a listed field whose own `group` names another group, a field two groups list, a repeated name, and `fields` on a group with `relatedList`. A name the object does not declare is skipped. | | **icon** | `string` | optional | Icon name (Lucide/Material) for the group header | | **description** | `string` | optional | Optional description shown under the group header | -| **relatedList** | `string` | optional | Places a related list's body table at this position in the record's details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it below the record's fields until the form places it at the group as well): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child's fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList). | +| **relatedList** | `string` | optional | Places a related list's body table at this position in the record's details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it here too, or below its fields when the form's sections name no field group): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child's fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList). | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Section visibility predicate (CEL) — the whole group (header included) is shown only when TRUE, else hidden (fail-closed). e.g. P`record.type == 'invoice'` | | **requiresFeature** | `Enum<'twoFactor' \| 'organization' \| 'multiOrgEnabled' \| 'degradedTenancy' \| …>` | optional | Deployment feature flag gating this group, from the same set an action's `requiresFeature` names (e.g. 'multiOrgEnabled'). Lowered at parse time into the group's `visibleWhen` (AND-composed after an authored `visibleWhen`) and stripped from the output; the whole group is hidden where the flag is off. Presentation only: the fields stay readable through the API. | | **collapse** | `Enum<'none' \| 'expanded' \| 'collapsed'>` | optional (default: `"none"`) | [ADR-0085] Section collapse behaviour: 'none' (always open, no toggle), 'expanded' (collapsible, starts open), 'collapsed' (collapsible, starts closed). | @@ -746,7 +746,7 @@ External datasource binding (ADR-0015) | **fields** | `string[]` | optional | The group's members in display order (field names of this object). Written, it decides which fields the group shows and their order on the record page and the forms, without changing the order of the object's fields. Absent, members are the fields whose `group` names this group, in field declaration order (the older spelling, still read). A field whose `group` names this group but that the list does not name follows the listed ones. Refused: a listed field whose own `group` names another group, a field two groups list, a repeated name, and `fields` on a group with `relatedList`. A name the object does not declare is skipped. | | **icon** | `string` | optional | Icon name (Lucide/Material) for the group header | | **description** | `string` | optional | Optional description shown under the group header | -| **relatedList** | `string` | optional | Places a related list's body table at this position in the record's details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it below the record's fields until the form places it at the group as well): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child's fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList). | +| **relatedList** | `string` | optional | Places a related list's body table at this position in the record's details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it here too, or below its fields when the form's sections name no field group): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child's fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList). | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Section visibility predicate (CEL) — the whole group (header included) is shown only when TRUE, else hidden (fail-closed). e.g. P`record.type == 'invoice'` | | **requiresFeature** | `Enum<'twoFactor' \| 'organization' \| 'multiOrgEnabled' \| 'degradedTenancy' \| 'oidcProvider' \| 'sso' \| 'ssoEnforced' \| 'directSignIn' \| 'deviceAuthorization' \| 'admin' \| … +5 more>` | optional | Deployment feature flag gating this group, from the same set an action's `requiresFeature` names (e.g. 'multiOrgEnabled'). Lowered at parse time into the group's `visibleWhen` (AND-composed after an authored `visibleWhen`) and stripped from the output; the whole group is hidden where the flag is off. Presentation only: the fields stay readable through the API. | | **collapse** | `Enum<'none' \| 'expanded' \| 'collapsed'>` | optional (default: `"none"`) | [ADR-0085] Section collapse behaviour: 'none' (always open, no toggle), 'expanded' (collapsible, starts open), 'collapsed' (collapsible, starts closed). | diff --git a/docs/adr/0035-config-driven-master-detail.md b/docs/adr/0035-config-driven-master-detail.md index b864a0bc762..c6f65f22780 100644 --- a/docs/adr/0035-config-driven-master-detail.md +++ b/docs/adr/0035-config-driven-master-detail.md @@ -169,6 +169,19 @@ a self-referential FK surfaces a "children" list. > group (a `master_detail` FK may instead drop `relatedList: true`); a group > naming a list its FK hides (`false`) is refused. +> **Note (2026-11-21, #35889, second slice).** The entry form now draws a +> placed child where the record page does, so "placed in the form below the +> record's fields until the form places it at the group" above is superseded. +> A form laid out from the parent's field groups draws the child's table +> after the sections of the groups declared before the placing group and +> before those declared after it; a tabbed form gives it a tab of its own at +> that position, labelled with the group's label (a wizard master-detail form +> is drawn as the simple form, as before). A form whose sections name no +> declared field group, and a child no group places (a form view's own +> subforms), keep the table below the record's fields. The table is the same +> one: it still saves with the record in one batch, and the document totals +> stay at the foot of the form. + The derivation is a pure function — `deriveRelatedLists(objectDef, objects)` in `@object-ui/app-shell` (`utils/deriveRelatedLists.ts`) — the read-side analogue of `attachInlineSubforms`. `RecordDetailView` feeds its output into the diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 4cfda2c2b55..ef388203f56 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2365,8 +2365,8 @@ export const FieldSchema = lazySchema(() => { * #35597's `'primary'` default): it joins the record's main content only * when a field group of the PARENT names it (`ObjectFieldGroupSchema.relatedList`), * which draws its table at the group's position in the record page and its - * edit state, and inlines it in the parent's entry form (below the record's - * fields until the form places it at the group too). + * edit state, and inlines it in the parent's entry form at the same place + * (a form whose sections name no field group keeps it below its fields). * Write `relatedList: true` to keep it a tab even from a group (a group * naming it is refused), `'primary'` to make it a body table with no group, * or `false` to hide it. diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 05ac2fa70f4..ea1b12ca81e 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1414,8 +1414,9 @@ export const ObjectFieldGroupSchema = lazySchema(() => strictObject({ * `relatedList: 'primary'` (the group positions that body table), or a * `master_detail` FK that declares no `relatedList` (a tab by default; the * group makes it a body table at this position in the record page and its - * edit state, and the parent's entry form inlines it, below the record's - * fields until the form places it at the group too, #35889). A group + * edit state, and the parent's entry form inlines it at the same position; + * a form whose sections name no field group keeps it below its fields, + * #35889). A group * naming a side card, or a list its FK hides with `relatedList: false`, * draws nothing at the group, so it is refused wherever the child's fields * are known: at `defineStack` and at the runtime metadata write door @@ -1426,7 +1427,7 @@ export const ObjectFieldGroupSchema = lazySchema(() => strictObject({ */ relatedList: z.string().regex(RELATED_LIST_ENTRY_PATTERN, { message: 'A field group\'s relatedList is a child object name (e.g. "task") or object.field (e.g. "event.related_to"), in snake_case', - }).optional().describe('Places a related list\'s body table at this position in the record\'s details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: \'primary\', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent\'s entry form inlines it below the record\'s fields until the form places it at the group as well): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child\'s fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: \'primary\' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group\'s relatedList).').meta({ title: 'Related List' }), + }).optional().describe('Places a related list\'s body table at this position in the record\'s details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: \'primary\', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent\'s entry form inlines it here too, or below its fields when the form\'s sections name no field group): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child\'s fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: \'primary\' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group\'s relatedList).').meta({ title: 'Related List' }), /** * [ADR-0085 §5] Section visibility predicate — CEL, the ADR-0089 canonical diff --git a/packages/spec/src/data/related-list-body-table.test.ts b/packages/spec/src/data/related-list-body-table.test.ts index 483aa566b26..6305719445d 100644 --- a/packages/spec/src/data/related-list-body-table.test.ts +++ b/packages/spec/src/data/related-list-body-table.test.ts @@ -110,7 +110,7 @@ describe('fieldGroups[i].relatedList describes the body-table rule it enforces', const text = root.properties?.relatedList?.description ?? ''; it('says it names a body table only, and that any other list is refused with the remedy', () => { - expect(text).toContain("It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it below the record's fields until the form places it at the group as well)"); + expect(text).toContain("It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it here too, or below its fields when the form's sections name no field group)"); expect(text).toContain('a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused'); expect(text).toContain("set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList"); }); diff --git a/packages/spec/src/data/related-list-body-table.ts b/packages/spec/src/data/related-list-body-table.ts index 23462ffcb89..2d406bf55ce 100644 --- a/packages/spec/src/data/related-list-body-table.ts +++ b/packages/spec/src/data/related-list-body-table.ts @@ -18,10 +18,10 @@ * default"). It becomes a body table only when one of the PARENT's field * groups names it (`ObjectFieldGroupSchema.relatedList`): then it is drawn * at that group's position, the record page's edit state carries it, and - * the parent's entry form inlines it (below the record's fields until the - * form places it at the group). `inlineEdit` takes no part in placement: - * since ruling B on #35889 it only picks the form factor of a child a group - * places (ADR-0035 as amended); + * the parent's entry form inlines it at the same place (below its fields + * when the form's sections name no field group). `inlineEdit` takes no + * part in placement: since ruling B on #35889 it only picks the form + * factor of a child a group places (ADR-0035 as amended); * - anything else is a tab (`true`, or a `lookup` with no `relatedList`), or * hidden (`false`). `relatedList: true` on a `master_detail` keeps it a tab, * which a group cannot override. A `lookup` child is a body table only by diff --git a/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts b/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts index 1e20bbcab5f..21ee63d321f 100644 --- a/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts +++ b/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts @@ -68,7 +68,8 @@ export const entry: SemanticMigration = { + 'draws no table for the child and the tab row carries the child\'s tab with its count; the create and ' + 'edit forms do not inline it. After adding a field group that names the ' + 'child, second in fieldGroups: the overview draws the child\'s table in the second group\'s place, the ' - + 'tab is still there, the create and edit forms inline the table, and the record page\'s Edit saves the ' + + 'tab is still there, the create and edit forms inline the table at the same place (a tab of its own in a ' + + 'tabbed form), and the record page\'s Edit saves the ' + 'record fields and the rows in one save. A child whose FK sets inlineEdit and that no group names is not ' + 'inlined in the parent\'s forms. A child whose FK declares relatedList \'primary\' is drawn on the ' + 'record page as before: a body table with no tab of its own, whether or not a group positions it. Where ' diff --git a/ui/packages/components/src/renderers/form/__tests__/form-invalid-scroll.test.tsx b/ui/packages/components/src/renderers/form/__tests__/form-invalid-scroll.test.tsx index 29543054d3a..5789e7e51f5 100644 --- a/ui/packages/components/src/renderers/form/__tests__/form-invalid-scroll.test.tsx +++ b/ui/packages/components/src/renderers/form/__tests__/form-invalid-scroll.test.tsx @@ -27,6 +27,8 @@ import { toast } from '../../../ui/sonner'; // cold transform is billed to `hookTimeout`, which is why this carried a raised // timeout. See object-ui/no-dynamic-import-in-test-hook (objectui#3010/#3021). import '../../../renderers'; +// The renderers reach `react-runtime` through a dynamic import: pay its load at collection. +import '@object-ui/react-runtime'; let toastErrorSpy: ReturnType; @@ -63,6 +65,29 @@ function renderForm(fields: any[], defaultValues?: Record) { const submit = () => fireEvent.click(screen.getByRole('button', { name: /create/i })); describe('form renderer — invalid-submit feedback (#2793)', () => { + it('reveals its own field, not a same-named field a host drew into a form-slot row (objectstack#35889)', async () => { + // What a host draws there (an expanded line editor) is a form of its own. + const slotRef = (el: HTMLElement | null) => { + if (el && !el.firstChild) el.innerHTML = '
'; + }; + const { container } = renderForm([ + { name: '__form_slot__d0', label: '', type: 'form-slot', slotRef }, + { name: 'title', label: 'Title', type: 'input', required: true }, + ]); + const own = [...container.querySelectorAll('[data-field="title"]')].find((el) => !el.closest('[data-form-slot]'))!; + const ownScroll = vi.fn(); + own.scrollIntoView = ownScroll; + const slotted = container.querySelector('[data-form-slot] [data-field="title"]')!; + const slottedScroll = vi.fn(); + slotted.scrollIntoView = slottedScroll; + + submit(); + + await waitFor(() => expect(ownScroll).toHaveBeenCalled()); + expect(slottedScroll).not.toHaveBeenCalled(); + expect(document.activeElement).not.toBe(screen.getByTestId('line-title')); + }); + it('scrolls+focuses the first errored field on a missing required field, with no toast', async () => { const { container } = renderForm([ { name: 'title', label: 'Title', type: 'input', required: true }, diff --git a/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx b/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx index 53c69bff6e7..412c4c24336 100644 --- a/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx +++ b/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx @@ -66,6 +66,27 @@ function renderWithSink(schema: Record) { } describe('form section list for the host navigation (objectstack#34605)', () => { + it('stops at a labelled host slot between the headings around it, and skips an unlabelled one (objectstack#35889)', async () => { + const { last } = renderWithSink({ + fields: [ + divider('s_header', 'Header', ['name']), + { name: 'name', label: 'Name', type: 'input' }, + { name: '__form_slot__d0', label: 'Lines', type: 'form-slot' }, + { name: '__form_slot__d1', label: '', type: 'form-slot' }, + divider('s_totals', 'Totals', ['memo']), + { name: 'memo', label: 'Memo', type: 'input' }, + ], + }); + await waitFor(() => expect(last()).toBeTruthy()); + const items = last()!; + expect(items.map((i) => [i.key, i.label])).toEqual([ + ['s_header', 'Header'], + ['__form_slot__d0', 'Lines'], + ['s_totals', 'Totals'], + ]); + expect(document.getElementById(items[1].anchorId)?.getAttribute('data-form-slot')).toBe('__form_slot__d0'); + }); + it('reports the drawn headings in order, each with the DOM id of its row', async () => { const { last } = renderWithSink({ fields: SECTIONED }); await waitFor(() => expect(last()).toBeTruthy()); diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index 01a65c2994b..e070436565a 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -2636,7 +2636,7 @@ ComponentRegistry.register('form', const drawn = new Set(); const changeable = new Set(); for (const f of fields as FormFieldConfig[]) { - if (!f?.name || f.type === 'section-divider') continue; + if (!f?.name || f.type === 'section-divider' || f.type === 'form-slot') continue; drawn.add(f.name); if (f.hidden || (f as any).readonly === true || f.disabled === true) continue; changeable.add(f.name); @@ -3317,7 +3317,15 @@ ComponentRegistry.register('form', typeof CSS !== 'undefined' && typeof CSS.escape === 'function' ? CSS.escape(name) : name.replace(/["\\]/g, '\\$&'); - return root.querySelector(`[data-field="${escaped}"]`); + // Not a field a host drew into one of THIS form's `form-slot` rows (an + // expanded line editor there is a form of its own, objectstack#35889); + // that editor, inside a slot, still finds its own fields. + return ( + [...root.querySelectorAll(`[data-field="${escaped}"]`)].find((el) => { + const slot = el.closest('[data-form-slot]'); + return !slot || !(root as Node).contains(slot); + }) ?? null + ); }; const revealField = (name: string) => { const target = fieldWrapper(name); @@ -3713,6 +3721,24 @@ ComponentRegistry.register('form', // Skip hidden fields if (hidden) return null; + // A host slot (objectstack#35889): an empty full-width element the form's + // host fills through a portal (`@object-ui/plugin-form` `formSlots.ts`, + // a master-detail form's collection at its field group). It holds no + // value and registers no control; `slotRef` is the host's callback. A + // labelled slot is a stop of the section navigation, like a heading. + if (type === 'form-slot') { + const { slotRef } = fieldProps as { slotRef?: React.Ref }; + return ( +
+ ); + } + // A field claimed by a HIDDEN section is not drawn (#6236) — the same // `return null` a field's own false predicate takes, so the ruled // semantics ride the existing mechanism: the value stays in the form @@ -4478,7 +4504,7 @@ ComponentRegistry.register('form', // the section navigation lists exactly these, so a section a predicate // hides is absent from it by the same verdict that hid its row. block.forEach((f, j) => { - if (f?.type === 'section-divider' && nodes[j] != null && f.label && typeof f.name === 'string') { + if ((f?.type === 'section-divider' || f?.type === 'form-slot') && nodes[j] != null && f.label && typeof f.name === 'string') { drawnHeadings?.push({ key: f.name, label: String(f.label) }); } }); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx new file mode 100644 index 00000000000..d3187bf3cbb --- /dev/null +++ b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx @@ -0,0 +1,198 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen, waitFor, fireEvent } from '@testing-library/react'; +import React from 'react'; +import { registerAllFields } from '@object-ui/fields'; +import { MasterDetailForm } from './MasterDetailForm'; + +// objectstack#35889 — a master-detail collection a field group of the parent +// places (`fieldGroups[].relatedList`) is drawn at that group in the entry +// form, as the record page draws it: after the groups declared before it, +// before the groups declared after it. A collection no group places stays +// below the record's fields. + +registerAllFields(); + +const LINES_GROUP = { key: 'lines', label: 'Lines', relatedList: 'po_line' }; +function parentWith(fieldGroups: unknown[]) { + return { + name: 'po', + fieldGroups, + fields: { + ref: { type: 'text', label: 'Ref', group: 'header' }, + memo: { type: 'text', label: 'Memo', group: 'totals' }, + }, + }; +} +const HEADER_GROUP = { key: 'header', label: 'Header', fields: ['ref'] }; +const TOTALS_GROUP = { key: 'totals', label: 'Totals', fields: ['memo'] }; + +function makeDataSource(parent: unknown, overrides: Record = {}) { + return { + getObjectSchema: vi.fn().mockResolvedValue(parent), + find: vi.fn().mockResolvedValue({ data: [] }), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + bulk: vi.fn(), + ...overrides, + } as any; +} + +const details = [ + { childObject: 'po_line', relationshipField: 'po', title: 'Order lines', columns: [{ name: 'qty', label: 'Qty', type: 'number' } as any] }, +]; + +/** Whether `a` comes before `b` in document order. */ +function before(a: Node, b: Node): boolean { + return (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0; +} + +async function collection(container: HTMLElement): Promise { + return waitFor(() => { + const el = container.querySelector('[data-testid="md-collection"]') as HTMLElement | null; + if (!el) throw new Error('collection not drawn'); + return el; + }); +} + +describe('MasterDetailForm — a group-placed collection sits at its group (objectstack#35889)', () => { + it('simple form: between the sections of the groups around its group, inside the header form', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + const el = container.querySelector('[data-form-slot] [data-testid="md-collection"]'); + if (!el) throw new Error('collection not placed'); + }); + const placed = await collection(container); + const header = container.querySelector('[data-form-section="__section_header"]')!; + const totals = container.querySelector('[data-form-section="__section_totals"]')!; + expect(header).toBeTruthy(); + expect(totals).toBeTruthy(); + expect(placed.closest('[data-form-slot]')!.closest('form')).toBe(header.closest('form')); + expect(before(header, placed)).toBe(true); + expect(before(placed, totals)).toBe(true); + expect(placed.textContent).toContain('Order lines'); + }); + + it('simple form: a collection no group places stays below the record fields', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, TOTALS_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-section="__section_totals"]')) throw new Error('header not ready'); + }); + const below = await collection(container); + expect(below.closest('form')).toBeNull(); + expect(container.querySelector('[data-form-slot]')).toBeNull(); + expect(before(container.querySelector('[data-form-section="__section_totals"]')!, below)).toBe(true); + }); + + it('a group placed last: after every declared group', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, TOTALS_GROUP, LINES_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-slot] [data-testid="md-collection"]')) throw new Error('not placed'); + }); + const placed = await collection(container); + expect(before(container.querySelector('[data-form-section="__section_totals"]')!, placed)).toBe(true); + }); + + it('edit form: the loaded record\'s lines are drawn at the group, and only there', async () => { + const parent = parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP]); + const child = { name: 'po_line', fields: { qty: { type: 'number', label: 'Qty' }, po: { type: 'master_detail', label: 'PO', reference: 'po' } } }; + const ds = makeDataSource(parent, { + getObjectSchema: vi.fn(async (object: string) => (object === 'po_line' ? child : parent)), + findOne: vi.fn().mockResolvedValue({ id: 'po1', ref: 'PO-7', memo: 'm' }), + find: vi.fn().mockImplementation((object: string) => + Promise.resolve({ data: object === 'po_line' ? [{ id: 'l1', po: 'po1', qty: 3 }] : [] }), + ), + }); + const { container } = render( + , + ); + await waitFor(() => { + const el = container.querySelector('[data-form-slot] [data-testid="md-collection"]'); + const values = el ? [...el.querySelectorAll('input')].map((input) => (input as HTMLInputElement).value) : []; + if (!values.includes('3')) throw new Error('lines not placed'); + }); + const header = container.querySelector('[data-form-section="__section_header"]')!; + const totals = container.querySelector('[data-form-section="__section_totals"]')!; + const placed = container.querySelector('[data-form-slot] [data-testid="md-collection"]')!; + expect(before(header, placed)).toBe(true); + expect(before(placed, totals)).toBe(true); + expect(container.querySelectorAll('[data-testid="md-collection"]')).toHaveLength(1); + }); + + it('a placed collection\'s controls are not the header form\'s: no native validation, no submit from a line button', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-slot] [data-testid="md-collection"] button')) throw new Error('not placed'); + }); + const header = container.querySelector('[data-form-section="__section_header"]')!.closest('form')!; + const slot = container.querySelector('[data-form-slot]')!; + const controls = [...slot.querySelectorAll('input, select, textarea, button')] as HTMLInputElement[]; + expect(controls.length).toBeGreaterThan(0); + // `requestSubmit()` validates, and a submit button submits, only the + // controls the form owns. + for (const control of controls) expect(control.form).not.toBe(header); + + const submitted = vi.fn(); + header.addEventListener('submit', submitted); + for (const button of slot.querySelectorAll('button')) fireEvent.click(button); + expect(submitted).not.toHaveBeenCalled(); + }); + + it('saves the record and its lines in one batch from the placed table', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }] }); + const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP]), { batchTransaction }); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-slot] [data-testid="md-collection"]')) throw new Error('not placed'); + }); + const ref = container.querySelector('input[name="ref"]') as HTMLInputElement; + fireEvent.change(ref, { target: { value: 'PO-1' } }); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(batchTransaction).toHaveBeenCalledTimes(1)); + const ops = batchTransaction.mock.calls[0][0] as Array<{ object?: string; objectName?: string; data?: any }>; + expect(JSON.stringify(ops)).toContain('PO-1'); + }); + + it('tabbed form: a tab of its own at its group, labelled with the group', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-slot] [data-testid="md-collection"]')) throw new Error('not placed'); + }); + const tabs = screen.getAllByRole('tab').map((tab) => tab.textContent?.trim()); + expect(tabs).toEqual(['Header', 'Lines', 'Totals']); + const placed = await collection(container); + const panel = placed.closest('[role="tabpanel"]') as HTMLElement; + expect(panel).toBeTruthy(); + const label = panel.getAttribute('aria-labelledby'); + expect(label && document.getElementById(label)?.textContent?.trim()).toBe('Lines'); + }); +}); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index e48202c8b4f..b892cd7097f 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -30,7 +30,8 @@ * `lookup`) FK on the child object. */ -import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; +import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; +import { createPortal } from 'react-dom'; import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types'; import { resolveAffordance, runBatchTransaction } from '@object-ui/core'; import { isUntouchedNewRow, LineItemsField, lookupAutofillByField, columnHelpByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type ColumnHelp, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; @@ -51,6 +52,7 @@ import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploa import { FormDirtyReportContext } from './formDirtyReport'; import { MasterDetailFrameContext } from './masterDetailFrame'; import { useFormChromeTranslation } from './formChrome'; +import { FormSlotStore, type FormSlotHandoff, type FormSlotRequest } from './formSlots'; import { buildMasterDetailBatch, buildMasterDetailEditBatch, @@ -785,6 +787,9 @@ function scrapeHeaderRecord(host: HTMLElement | null): Record { els.forEach((el) => { const name = el.getAttribute('name'); if (!name) return; + // A collection the header form places at its field group is drawn inside + // the header's element (objectstack#35889): its cells are not header fields. + if (el.closest('[data-form-slot]')) return; if (el.tagName === 'INPUT') { const input = el as HTMLInputElement; if (input.type === 'checkbox') { out[name] = input.checked; return; } @@ -878,6 +883,8 @@ interface MasterDetailLinesProps { * Remove asks the child's delete grant: a create form's lines are drafts. */ formMode: 'create' | 'edit'; + /** Where the header form placed each collection (objectstack#35889, `formSlots.ts`). */ + slotStore: FormSlotStore; /** * The values a new line starts with, by CHILD object name (objectstack#35940): * the child's static defaults, seeded as a create form seeds them. A child @@ -893,6 +900,40 @@ interface MasterDetailLinesProps { newRowRequiredShown: boolean; } +/** + * Draws `children` where the header form placed collection `id`: in its slot + * element through a portal, in place when no drawn layout claims it, and + * nowhere while a claimed slot's element is not mounted (objectstack#35889). + * Its own component, so a slot landing re-renders only what it moves. + * + * The slot element sits inside the header's `
`, so a portaled collection + * is wrapped in a form of its own: its controls then belong to that form, not + * the header's, exactly as they belonged to none below the form. The header's + * `requestSubmit()` validates only its own fields (a line cell's bad input + * never blocks Save with a browser bubble), a line button without a `type` + * submits only the wrapper, which does nothing, and Enter in a cell finds the + * wrapper's disabled default button and submits nothing. + */ +const preventSubmit = (event: React.FormEvent) => event.preventDefault(); + +const FormSlotPlacement: React.FC<{ store: FormSlotStore; id: string; children: React.ReactNode }> = ({ + store, + id, + children, +}) => { + useSyncExternalStore(store.subscribe, store.getVersion, store.getVersion); + const at = store.placement(id); + if (at === 'inline') return <>{children}; + if (!at) return null; + return createPortal( + +