diff --git a/.changeset/35889-master-detail-tab-by-default.md b/.changeset/35889-master-detail-tab-by-default.md new file mode 100644 index 00000000000..d3672ae5bc8 --- /dev/null +++ b/.changeset/35889-master-detail-tab-by-default.md @@ -0,0 +1,35 @@ +--- +'@objectstack/spec': minor +'@objectstack/lint': minor +'@object-ui/app-shell': minor +'@object-ui/plugin-detail': minor +'@objectstack/platform-objects': minor +--- + +feat(spec, ui): a master_detail child is a tab by default; a field group puts it in the overview and the form + +Clause-②: yes (widening: `@objectstack/spec/data` exports `isGroupPlaceableRelationship`, `fieldGroupsPlaceRelationship` and the `BodyTableContext` type, and `isBodyTableRelationship` takes an optional second argument) +Metadata-protocol: semantic + +A `master_detail` FK that declares no `relatedList` used to put its child list into the parent record's overview as a table (since #35597). Now it is a tab of the record page with its count, like any other related list, `inlineEdit` or not. It goes into the overview only where a field group of the PARENT names it (`fieldGroups[].relatedList`). + +- Placed by a group, the child's table is drawn at that group's position in the overview, the parent's create and edit forms inline it, and the record page's Edit saves the record fields and the rows in one save. Its tab stays on the tab row too, with its count. +- `relatedList: 'primary'` on the FK is unchanged on the record page: a body table with no group, and no tab of its own whether or not a group positions it. Its forms follow ruling B like every other child: a field group naming it inlines it in the parent's create and edit forms, `inlineEdit` or not, and with no group naming it the forms do not inline it, even with `inlineEdit`. `relatedList: true` keeps a tab that no group may place, and `false` hides the list. +- A field group may name exactly what it could name before: a plain `master_detail` child or a `'primary'` one. `isGroupPlaceableRelationship` is that test; `isBodyTableRelationship(field, { placedByGroup })` is still the one body-table judgement. +- `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. +- 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: + +```ts +fieldGroups: [ + { key: 'basic', label: 'Basic information' }, + { key: 'lines', label: 'Lines', relatedList: 'order_line' }, // or 'order_line.order' for one FK + { key: 'terms', label: 'Terms' }, +], +``` + +Such a group holds no fields. Or write `relatedList: 'primary'` on the child's FK to keep it in the overview with no group. A group may name only a list it can place: for an `inlineEdit` child on a `lookup` FK, or on a FK declaring `relatedList: true`, also write `relatedList: 'primary'` on the FK (a `master_detail` FK may instead drop `relatedList: true`). A form view that declares its own subforms still inlines what it declares. diff --git a/content/docs/data-modeling/field-types.mdx b/content/docs/data-modeling/field-types.mdx index c4780a103b6..15ff531eb1c 100644 --- a/content/docs/data-modeling/field-types.mdx +++ b/content/docs/data-modeling/field-types.mdx @@ -564,7 +564,7 @@ Parent-child relationship (cascading delete by default). | `reference` | `string` | **required** | Target (master) object name. A stored-metadata table is refused — see [below](#a-relationship-never-targets-a-stored-metadata-table) | | `referenceFilters` | `string[]` | — | **Removed** (#2377, ADR-0049) — no longer a recognized field property. `FieldSchema` is a strict object, so an unknown key is **rejected with guidance**, not silently stripped (ADR-0078): the error echoes the offending key and prescribes the replacement. Use structured `lookupFilters` + `dependsOn` instead; see [Relationships](/docs/data-modeling/relationships) | | `deleteBehavior` | `'restrict' \| 'cascade'` | `'cascade'` | Behavior when parent is deleted. `restrict` refuses the parent delete while children exist; `cascade` (and omitting the key) deletes the children with the parent. An explicit `set_null` is a **parse-time rejection** on this type (#9689) — a detail row cannot outlive its master; use a `lookup` if children must survive the parent | -| `inlineEdit` | `boolean \| 'grid' \| 'form'` | — | Edit child records inline on the parent create/edit form (`true` = auto-pick, `'grid'`, or `'form'`) | +| `inlineEdit` | `boolean \| 'grid' \| 'form'` | — | Form factor of the child rows on the parent create/edit form (`true` = auto-pick, `'grid'`, or `'form'`). The form inlines the child only where a field group of the parent names it; `inlineEdit` alone inlines nothing | | `inlineColumns` | `array` | — | Optional explicit inline grid columns | | `inlineAmountField` | `string` | — | Numeric child field used for the inline running total | @@ -579,6 +579,21 @@ Parent-child relationship (cascading delete by default). } ``` +**Where the child list shows.** A `master_detail` child is a tab of the parent's record page, with +its count, like any other related list. It goes into the record page's overview and the parent's +create and edit forms only where a field group of the PARENT names it, at that group's position: + +```typescript +// on the parent object +fieldGroups: [ + { key: 'basic', label: 'Basic information' }, + { key: 'lines', label: 'Lines', relatedList: 'order_line' }, // or 'order_line.order' for one FK +], +``` + +A placed table keeps its tab, and the record page's Edit saves the record and its rows in one +save. `relatedList: 'primary'` on the FK puts the table in the overview with no group. + **The inline grid in the Console.** With `inlineEdit: 'grid'` (or `true` resolving to the grid) the parent's form edits the children as rows of a table: @@ -835,7 +850,7 @@ options, required flags or translations, and nothing validates or addresses a si **A list that needs typed columns is a child object** with a [`master_detail`](#master_detail) field pointing back at the parent — the shape Salesforce, Dynamics, ServiceNow and Odoo use for line items. The child's own fields carry the types and validation, `inlineEdit: 'grid'` edits the rows as an -inline grid on the parent's form, and every row is a record a lookup, a roll-up or a flow can reach. +inline grid on the parent's form (where a field group of the parent names the child), and every row is a record a lookup, a roll-up or a flow can reach. ### `composite` @@ -854,7 +869,8 @@ child object (see above). ``` ```typescript -// A typed list: a child object, edited inline on the parent's form +// A typed list: a child object, edited inline on the parent's form once the +// invoice names it in a field group: { key: 'lines', relatedList: 'invoice_line' } { name: 'invoice_line', fields: { diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index ddcb5dce4d1..34e6bc16921 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -233,7 +233,8 @@ project: Field.masterDetail('project', { required: true, }), -// Inline line items on the parent form +// Inline line items on the parent form (the parent names the child in a +// field group: fieldGroups: [{ key: 'lines', relatedList: 'order_line' }]) order: Field.masterDetail('order', { label: 'Order', required: true, @@ -249,7 +250,7 @@ order: Field.masterDetail('order', { | `lookupFilters` | `{ field, operator, value, orEmpty? }[]` | Base filters restricting which records are selectable (structured, picker-honored). `value` is a literal or a `{ $record }` reference — see below | | `dependsOn` | `(string \| { field, param? })[]` | Sibling fields that scope the candidates by equality; the picker is gated until they are set | | `deleteBehavior` | `enum` | `'set_null'`, `'cascade'`, `'restrict'` | -| `inlineEdit` | `boolean \| 'grid' \| 'form'` | Render child records inline on the parent create/edit form (`true` = auto-pick, `'grid'`, or `'form'`) | +| `inlineEdit` | `boolean \| 'grid' \| 'form'` | Form factor of the child rows on the parent create/edit form (`true` = auto-pick, `'grid'`, or `'form'`). The form inlines the child only where a field group of the parent names it (`fieldGroups[].relatedList`); `inlineEdit` alone inlines nothing | | `inlineColumns` | `array` | Optional explicit columns for the inline grid | | `inlineAmountField` | `string` | Optional numeric child field for the inline running total | | `lookupAutofill` | `{ target, source, overwrite? }[]` | Fields of this object a pick fills from the picked record (single-value `lookup` / `master_detail` only) — see below | diff --git a/content/docs/getting-started/common-patterns.mdx b/content/docs/getting-started/common-patterns.mdx index 2fba827b96a..4b4022e70bb 100644 --- a/content/docs/getting-started/common-patterns.mdx +++ b/content/docs/getting-started/common-patterns.mdx @@ -103,6 +103,9 @@ Create a parent-child relationship between a master and its detail records. A `m name: 'order', label: 'Order', sharingModel: 'public_read', + // The group naming order_line puts the lines in the order's form and + // record page; without it they are a tab of the record page. + fieldGroups: [{ key: 'lines', label: 'Lines', relatedList: 'order_line' }], fields: { order_number: { label: 'Order #', type: 'autonumber', autonumberFormat: 'ORD-{0000}' }, customer: { label: 'Customer', type: 'lookup', reference: 'contact' }, diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index a26c824ac09..cd4a0964fae 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -81,11 +81,11 @@ const result = CurrencyConfigSchema.parse(data); | **referenceNameVisible** | `boolean` | optional | Declared name exposure (`lookup` and `user` fields only). TRUE declares that a principal who can read the record carrying this field may see the referenced record's display name (the target object's `nameField`, else its `displayNameField`, else the derived title field) and id even when that principal cannot read the referenced record. Served on `$expand`: a target the reader is refused (the object's read gate or its row scope) answers `{ id, name, readRefused: true }` (`ReferenceNameOnlyValueSchema`), per element on a multi-value field; an unexpanded read answers the stored id, as for every reader. Nothing else of the target: `$expand` on this field returns the same name and id only, the field's `displayField` does not widen it, and the name renders as text with no link to the target. A field-level rule on the name field still holds, and the name field is read only where nothing the security layer owns must be computed: the name is the `Record #` floor with the id when the reader may not read that field, it declares a `maskingRule`, it is a formula reading through another reference, an explicit `nameField` (or its `displayNameField` alias) points at a column that is neither title-typed nor autonumber, or no field-level answer can be had for the reader. A target with no resolvable or no non-empty name reads as the same floor. A principal who can read the target is served exactly what it is served without the key. Absent or false keeps the restricted-reference posture for a target the reader cannot read. Declared on the referencing field only; there is no target-object switch. Refused on any other type. | | **mailAssociation** | `boolean` | optional | Inbound mail association (`email` fields only): TRUE marks this field as identifying a correspondent. When a mailbox service ingests a message, it associates the message with every record of this object whose value in this field equals one of the message's participant addresses (From, Sender, Reply-To, To and Cc, plus those of a forwarded message it carries; ASCII case-insensitive; the receiving mailbox's own addresses excluded; only within the mailbox's organization). A message no record matches waits in the mailbox's unassociated pool. Refused on any other type. Takes effect only where a mailbox service is composed. | | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | -| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | Edit these child records inline within the parent's form (atomic master-detail). true = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | +| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | | **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | -| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = 'primary' (a body table) on a master_detail field, an auxiliary panel on a lookup field; false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | +| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | | **relatedListColumns** | `string[]` | optional | Explicit columns for the detail-page related list, as child field names (e.g. ['name', 'status']); derived from the child object (highlightFields → field walk) when omitted. Strings only — labels, cell types and formatting always derive from the child object's field definitions; column objects are refused at parse. | | **relatedListFilter** | `any` | optional | Declarative default filter for the detail-page related list: AND-composed with the parent-relationship condition `{ [referenceField]: parentId }` — an authored constraint, never a user-editable suggestion. The related-list tab badge count honors the same composed filter, so counts match the visible rows. Canonical Query-DSL FilterCondition (the same dialect as a query `where`), e.g. `{ status: { $ne: 'deleted' } }` to hide soft-deleted children. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index ad896cf2693..ebe750aef22 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -260,11 +260,11 @@ const result = ApiMethod.parse(data); | **referenceNameVisible** | `boolean` | optional | Declared name exposure (`lookup` and `user` fields only). TRUE declares that a principal who can read the record carrying this field may see the referenced record's display name (the target object's `nameField`, else its `displayNameField`, else the derived title field) and id even when that principal cannot read the referenced record. Served on `$expand`: a target the reader is refused (the object's read gate or its row scope) answers `{ id, name, readRefused: true }` (`ReferenceNameOnlyValueSchema`), per element on a multi-value field; an unexpanded read answers the stored id, as for every reader. Nothing else of the target: `$expand` on this field returns the same name and id only, the field's `displayField` does not widen it, and the name renders as text with no link to the target. A field-level rule on the name field still holds, and the name field is read only where nothing the security layer owns must be computed: the name is the `Record #` floor with the id when the reader may not read that field, it declares a `maskingRule`, it is a formula reading through another reference, an explicit `nameField` (or its `displayNameField` alias) points at a column that is neither title-typed nor autonumber, or no field-level answer can be had for the reader. A target with no resolvable or no non-empty name reads as the same floor. A principal who can read the target is served exactly what it is served without the key. Absent or false keeps the restricted-reference posture for a target the reader cannot read. Declared on the referencing field only; there is no target-object switch. Refused on any other type. | | **mailAssociation** | `boolean` | optional | Inbound mail association (`email` fields only): TRUE marks this field as identifying a correspondent. When a mailbox service ingests a message, it associates the message with every record of this object whose value in this field equals one of the message's participant addresses (From, Sender, Reply-To, To and Cc, plus those of a forwarded message it carries; ASCII case-insensitive; the receiving mailbox's own addresses excluded; only within the mailbox's organization). A message no record matches waits in the mailbox's unassociated pool. Refused on any other type. Takes effect only where a mailbox service is composed. | | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | -| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | Edit these child records inline within the parent's form (atomic master-detail). true = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | +| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | | **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | -| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = 'primary' (a body table) on a master_detail field, an auxiliary panel on a lookup field; false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | +| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | | **relatedListColumns** | `string[]` | optional | Explicit columns for the detail-page related list, as child field names (e.g. ['name', 'status']); derived from the child object (highlightFields → field walk) when omitted. Strings only — labels, cell types and formatting always derive from the child object's field definitions; column objects are refused at parse. | | **relatedListFilter** | `any` | optional | Declarative default filter for the detail-page related list: AND-composed with the parent-relationship condition `{ [referenceField]: parentId }` — an authored constraint, never a user-editable suggestion. The related-list tab badge count honors the same composed filter, so counts match the visible rows. Canonical Query-DSL FilterCondition (the same dialect as a query `where`), e.g. `{ status: { $ne: 'deleted' } }` to hide soft-deleted children. | @@ -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): 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 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). | | **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). | @@ -642,11 +642,11 @@ const result = ApiMethod.parse(data); | **referenceNameVisible** | `boolean` | optional | Declared name exposure (`lookup` and `user` fields only). TRUE declares that a principal who can read the record carrying this field may see the referenced record's display name (the target object's `nameField`, else its `displayNameField`, else the derived title field) and id even when that principal cannot read the referenced record. Served on `$expand`: a target the reader is refused (the object's read gate or its row scope) answers `{ id, name, readRefused: true }` (`ReferenceNameOnlyValueSchema`), per element on a multi-value field; an unexpanded read answers the stored id, as for every reader. Nothing else of the target: `$expand` on this field returns the same name and id only, the field's `displayField` does not widen it, and the name renders as text with no link to the target. A field-level rule on the name field still holds, and the name field is read only where nothing the security layer owns must be computed: the name is the `Record #` floor with the id when the reader may not read that field, it declares a `maskingRule`, it is a formula reading through another reference, an explicit `nameField` (or its `displayNameField` alias) points at a column that is neither title-typed nor autonumber, or no field-level answer can be had for the reader. A target with no resolvable or no non-empty name reads as the same floor. A principal who can read the target is served exactly what it is served without the key. Absent or false keeps the restricted-reference posture for a target the reader cannot read. Declared on the referencing field only; there is no target-object switch. Refused on any other type. | | **mailAssociation** | `boolean` | optional | Inbound mail association (`email` fields only): TRUE marks this field as identifying a correspondent. When a mailbox service ingests a message, it associates the message with every record of this object whose value in this field equals one of the message's participant addresses (From, Sender, Reply-To, To and Cc, plus those of a forwarded message it carries; ASCII case-insensitive; the receiving mailbox's own addresses excluded; only within the mailbox's organization). A message no record matches waits in the mailbox's unassociated pool. Refused on any other type. Takes effect only where a mailbox service is composed. | | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | -| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | Edit these child records inline within the parent's form (atomic master-detail). true = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | +| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | | **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | -| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = 'primary' (a body table) on a master_detail field, an auxiliary panel on a lookup field; false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | +| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | | **relatedListColumns** | `string[]` | optional | Explicit columns for the detail-page related list, as child field names (e.g. ['name', 'status']); derived from the child object (highlightFields → field walk) when omitted. Strings only — labels, cell types and formatting always derive from the child object's field definitions; column objects are refused at parse. | | **relatedListFilter** | `any` | optional | Declarative default filter for the detail-page related list: AND-composed with the parent-relationship condition `{ [referenceField]: parentId }` — an authored constraint, never a user-editable suggestion. The related-list tab badge count honors the same composed filter, so counts match the visible rows. Canonical Query-DSL FilterCondition (the same dialect as a query `where`), e.g. `{ status: { $ne: 'deleted' } }` to hide soft-deleted children. | @@ -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): 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 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). | | **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/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 095ac234857..3fbad58f15d 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -84,11 +84,11 @@ Add a new field to an existing object | **referenceNameVisible** | `boolean` | optional | Declared name exposure (`lookup` and `user` fields only). TRUE declares that a principal who can read the record carrying this field may see the referenced record's display name (the target object's `nameField`, else its `displayNameField`, else the derived title field) and id even when that principal cannot read the referenced record. Served on `$expand`: a target the reader is refused (the object's read gate or its row scope) answers `{ id, name, readRefused: true }` (`ReferenceNameOnlyValueSchema`), per element on a multi-value field; an unexpanded read answers the stored id, as for every reader. Nothing else of the target: `$expand` on this field returns the same name and id only, the field's `displayField` does not widen it, and the name renders as text with no link to the target. A field-level rule on the name field still holds, and the name field is read only where nothing the security layer owns must be computed: the name is the `Record #` floor with the id when the reader may not read that field, it declares a `maskingRule`, it is a formula reading through another reference, an explicit `nameField` (or its `displayNameField` alias) points at a column that is neither title-typed nor autonumber, or no field-level answer can be had for the reader. A target with no resolvable or no non-empty name reads as the same floor. A principal who can read the target is served exactly what it is served without the key. Absent or false keeps the restricted-reference posture for a target the reader cannot read. Declared on the referencing field only; there is no target-object switch. Refused on any other type. | | **mailAssociation** | `boolean` | optional | Inbound mail association (`email` fields only): TRUE marks this field as identifying a correspondent. When a mailbox service ingests a message, it associates the message with every record of this object whose value in this field equals one of the message's participant addresses (From, Sender, Reply-To, To and Cc, plus those of a forwarded message it carries; ASCII case-insensitive; the receiving mailbox's own addresses excluded; only within the mailbox's organization). A message no record matches waits in the mailbox's unassociated pool. Refused on any other type. Takes effect only where a mailbox service is composed. | | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | -| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | Edit these child records inline within the parent's form (atomic master-detail). true = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | +| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | | **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | -| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = 'primary' (a body table) on a master_detail field, an auxiliary panel on a lookup field; false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | +| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | | **relatedListColumns** | `string[]` | optional | Explicit columns for the detail-page related list, as child field names (e.g. ['name', 'status']); derived from the child object (highlightFields → field walk) when omitted. Strings only — labels, cell types and formatting always derive from the child object's field definitions; column objects are refused at parse. | | **relatedListFilter** | `any` | optional | Declarative default filter for the detail-page related list: AND-composed with the parent-relationship condition `{ [referenceField]: parentId }` — an authored constraint, never a user-editable suggestion. The related-list tab badge count honors the same composed filter, so counts match the visible rows. Canonical Query-DSL FilterCondition (the same dialect as a query `where`), e.g. `{ status: { $ne: 'deleted' } }` to hide soft-deleted children. | @@ -521,11 +521,11 @@ Add a new field to an existing object | **referenceNameVisible** | `boolean` | optional | Declared name exposure (`lookup` and `user` fields only). TRUE declares that a principal who can read the record carrying this field may see the referenced record's display name (the target object's `nameField`, else its `displayNameField`, else the derived title field) and id even when that principal cannot read the referenced record. Served on `$expand`: a target the reader is refused (the object's read gate or its row scope) answers `{ id, name, readRefused: true }` (`ReferenceNameOnlyValueSchema`), per element on a multi-value field; an unexpanded read answers the stored id, as for every reader. Nothing else of the target: `$expand` on this field returns the same name and id only, the field's `displayField` does not widen it, and the name renders as text with no link to the target. A field-level rule on the name field still holds, and the name field is read only where nothing the security layer owns must be computed: the name is the `Record #` floor with the id when the reader may not read that field, it declares a `maskingRule`, it is a formula reading through another reference, an explicit `nameField` (or its `displayNameField` alias) points at a column that is neither title-typed nor autonumber, or no field-level answer can be had for the reader. A target with no resolvable or no non-empty name reads as the same floor. A principal who can read the target is served exactly what it is served without the key. Absent or false keeps the restricted-reference posture for a target the reader cannot read. Declared on the referencing field only; there is no target-object switch. Refused on any other type. | | **mailAssociation** | `boolean` | optional | Inbound mail association (`email` fields only): TRUE marks this field as identifying a correspondent. When a mailbox service ingests a message, it associates the message with every record of this object whose value in this field equals one of the message's participant addresses (From, Sender, Reply-To, To and Cc, plus those of a forwarded message it carries; ASCII case-insensitive; the receiving mailbox's own addresses excluded; only within the mailbox's organization). A message no record matches waits in the mailbox's unassociated pool. Refused on any other type. Takes effect only where a mailbox service is composed. | | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | -| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | Edit these child records inline within the parent's form (atomic master-detail). true = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | +| **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | | **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | -| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = 'primary' (a body table) on a master_detail field, an auxiliary panel on a lookup field; false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | +| **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | | **relatedListColumns** | `string[]` | optional | Explicit columns for the detail-page related list, as child field names (e.g. ['name', 'status']); derived from the child object (highlightFields → field walk) when omitted. Strings only — labels, cell types and formatting always derive from the child object's field definitions; column objects are refused at parse. | | **relatedListFilter** | `any` | optional | Declarative default filter for the detail-page related list: AND-composed with the parent-relationship condition `{ [referenceField]: parentId }` — an authored constraint, never a user-editable suggestion. The related-list tab badge count honors the same composed filter, so counts match the visible rows. Canonical Query-DSL FilterCondition (the same dialect as a query `where`), e.g. `{ status: { $ne: 'deleted' } }` to hide soft-deleted children. | diff --git a/docs/adr/0035-config-driven-master-detail.md b/docs/adr/0035-config-driven-master-detail.md index f37b0d1fffe..b864a0bc762 100644 --- a/docs/adr/0035-config-driven-master-detail.md +++ b/docs/adr/0035-config-driven-master-detail.md @@ -1,6 +1,6 @@ # ADR-0035: Config-driven master-detail (declare on the relationship, forms derive) -**Status**: Accepted · **Amended** (2026-10-28, [#27069](https://github.com/objectstack-ai/objectstack/issues/27069), maintainer rulings on that card: 「A」, an ordered list on the parent, and 「明细行的子表放在右侧合适嘛?」 / 「他如果做到放在基本信息下面,而条款和备注在后面」, line items in the record body) — `relatedList: 'primary'` is a **placement** (the record body, as a full-width table), no longer a prominence hint that orders lists; the order is the parent object's `relatedLists`; and an omitted `relatedList` on a `master_detail` FK that sets `inlineEdit` is now `'primary'` by default. See the note under the read-side table. · **Amended** (2026-11-19, [#35597](https://github.com/objectstack-ai/objectstack/issues/35597), under the record-page epic [#35590](https://github.com/objectstack-ai/objectstack/issues/35590), maintainer's words on that card: 「就是master-detail表类型的子表」 / 「主从的子表是否应该默认出现在概览的左侧区域?关键字段下面。」) — an omitted `relatedList` on ANY `master_detail` FK is `'primary'` (a body table) by default, `inlineEdit` or not; its totals are server-owned. See the second note under the read-side table. +**Status**: Accepted · **Amended** (2026-10-28, [#27069](https://github.com/objectstack-ai/objectstack/issues/27069), maintainer rulings on that card: 「A」, an ordered list on the parent, and 「明细行的子表放在右侧合适嘛?」 / 「他如果做到放在基本信息下面,而条款和备注在后面」, line items in the record body) — `relatedList: 'primary'` is a **placement** (the record body, as a full-width table), no longer a prominence hint that orders lists; the order is the parent object's `relatedLists`; and an omitted `relatedList` on a `master_detail` FK that sets `inlineEdit` is now `'primary'` by default. See the note under the read-side table. · **Amended** (2026-11-19, [#35597](https://github.com/objectstack-ai/objectstack/issues/35597), under the record-page epic [#35590](https://github.com/objectstack-ai/objectstack/issues/35590), maintainer's words on that card: 「就是master-detail表类型的子表」 / 「主从的子表是否应该默认出现在概览的左侧区域?关键字段下面。」) — an omitted `relatedList` on ANY `master_detail` FK is `'primary'` (a body table) by default, `inlineEdit` or not; its totals are server-owned. See the second note under the read-side table. · **Amended** (2026-11-20, [#35889](https://github.com/objectstack-ai/objectstack/issues/35889), same epic, maintainer's words on that card: 「主从子表我认为不应该自动申明放在概览中,除非我通过 fieldGroup 强制指定」) — that default is withdrawn: an omitted `relatedList` on a `master_detail` FK is a tab, and the list is a body table (in the record page, the parent's forms and its edit state) only where a parent field group names it, and `inlineEdit` no longer inlines a child in the form by itself. See the third note under the read-side table. **Author**: surfaced while making master-detail (parent + child line-item) entry a first-class, low-config capability **Affects**: `@objectstack/spec` (field schema), `@object-ui/plugin-form`, `@object-ui/plugin-view`, `@object-ui/app-shell`; builds on ADR-0034 (atomic multi-write) and the cross-object batch endpoint (#1604) @@ -139,6 +139,36 @@ a self-referential FK surfaces a "children" list. > `inlineEdit` is a body table on the record page and stays out of the > parent's form. +> **Amended (2026-11-20, #35889; epic #35590).** The default of the note above +> is withdrawn; the rest of it stands. An omitted `relatedList` on a +> `master_detail` FK is a TAB of the parent's record page (with its count), as +> on a `lookup` FK, `inlineEdit` or not (the maintainer on #35889: +> 「主从子表我认为不应该自动申明放在概览中,除非我通过 fieldGroup 强制指定」, +> 「我们已经开发好的功能也没必要作废」). Such a list becomes a body table only +> where a field group of the PARENT names it (`fieldGroups[].relatedList`, a +> child object name or `object.field`): the record page draws it at that +> group's position, the parent's create and edit forms inline it, and the +> record page's Edit saves the record fields and its rows in one batch +> (#35599); its tab stays on the tab row. `relatedList: 'primary'` on the FK +> still makes a body table with no group (and no tab, positioned by a group or not), `true` keeps a tab that no group can +> place, and `false` hides it. The set a field group may name is unchanged +> (`isGroupPlaceableRelationship`, read by the refusal at `defineStack` and at +> the publish door); `isBodyTableRelationship` is still the one body-table +> judgement, now told whether a parent group places the list. The WRITE side +> follows the same group (maintainer ruling B on #35889, +> 「明细表应该改成指看分组的定义了」): "Only `inlineEdit` children are inlined" +> (Decision → Derivation rules) no longer holds. The parent's form, as derived +> from its relationships, inlines a child exactly where a parent field group +> names it (a form view that declares its own subforms still inlines what it +> declares); `inlineEdit` on the FK no longer inlines a child by itself and +> only picks the form factor of a placed one (`'grid'`, `'form'`, or the +> shape-picked default), placed in the form below the record's fields until +> the form places it at the group. A group may name only a list it can place, +> so an `inlineEdit` child on a `lookup` FK, or on a FK declaring +> `relatedList: true`, needs `relatedList: 'primary'` on its FK as well as the +> group (a `master_detail` FK may instead drop `relatedList: true`); a group +> naming a list its FK hides (`false`) is refused. + 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/examples/app-crm/src/flows/convert-lead.flow.ts b/examples/app-crm/src/flows/convert-lead.flow.ts index 283bf1f9057..5dbb2944b46 100644 --- a/examples/app-crm/src/flows/convert-lead.flow.ts +++ b/examples/app-crm/src/flows/convert-lead.flow.ts @@ -120,7 +120,8 @@ export const ConvertLeadScreenFlow = defineFlow({ }, // ── 5. Step 2 — full Opportunity form WITH product line items ────────── - // crm_opportunity_line_item.opportunity declares inlineEdit: 'grid', so the + // crm_opportunity's `lines` field group names crm_opportunity_line_item + // (objectstack#35889) and its FK declares inlineEdit: 'grid', so the // standard Opportunity form (and therefore this step) renders an editable // product line-item grid below the header — the master-detail entry the // user asked for. The account FK is prefilled with Step 1's new id. diff --git a/examples/app-crm/src/objects/opportunity-line-item.object.ts b/examples/app-crm/src/objects/opportunity-line-item.object.ts index b807ec26e22..03fb329d58d 100644 --- a/examples/app-crm/src/objects/opportunity-line-item.object.ts +++ b/examples/app-crm/src/objects/opportunity-line-item.object.ts @@ -8,8 +8,9 @@ import { cel } from '@objectstack/spec'; * * This is the canonical master-detail "header + line items" shape (mirrors the * showcase Invoice ↔ InvoiceLine pair): an opportunity is quoted together with - * the products on it, entered in ONE atomic transaction. So the back-pointer - * `opportunity` field declares `inlineEdit: 'grid'` — every standard New/Edit + * the products on it, entered in ONE atomic transaction. So the opportunity's + * `lines` field group names this object (and the back-pointer `opportunity` + * picks the grid form factor with `inlineEdit: 'grid'`) — every standard New/Edit * Opportunity form (and the lead-conversion wizard's Opportunity step) renders * an editable line-item grid, and the parent `Opportunity.line_total` rolls the * line amounts up server-side. diff --git a/examples/app-crm/src/objects/opportunity.object.ts b/examples/app-crm/src/objects/opportunity.object.ts index 398e39b81f4..2e6e825ebd4 100644 --- a/examples/app-crm/src/objects/opportunity.object.ts +++ b/examples/app-crm/src/objects/opportunity.object.ts @@ -23,18 +23,31 @@ export const Opportunity = ObjectSchema.create({ // record page show it. enable: { trackHistory: true }, + // [#35889] The product lines are part of the opportunity: this group puts the + // `crm_opportunity_line_item` table in the record page after its fields, + // inlines it in the New / Edit Opportunity form (and the lead-conversion + // wizard's Opportunity step), and lets Edit on the record page save both + // together. A master-detail child no group names is only a tab. + fieldGroups: [ + { key: 'opportunity', label: 'Opportunity' }, + { key: 'lines', label: 'Products', relatedList: 'crm_opportunity_line_item' }, + ], + fields: { name: Field.text({ + group: 'opportunity', label: 'Opportunity Name', required: true, searchable: true, maxLength: 200, }), account: Field.lookup('crm_account', { + group: 'opportunity', label: 'Account', required: true, }), stage: Field.select({ + group: 'opportunity', label: 'Stage', required: true, options: [ @@ -46,10 +59,12 @@ export const Opportunity = ObjectSchema.create({ ], }), amount: Field.currency({ + group: 'opportunity', label: 'Amount', min: 0, }), probability: Field.percent({ + group: 'opportunity', label: 'Probability', defaultValue: 50, min: 0, @@ -59,20 +74,24 @@ export const Opportunity = ObjectSchema.create({ // console reads `returnType` and never infers money from the expression, // and an undeclared formula draws the plain number face beside `amount`. expected_revenue: Field.formula({ + group: 'opportunity', label: 'Expected Revenue', returnType: 'currency', expression: cel`(record.amount == null ? 0 : record.amount) * (record.probability == null ? 0 : record.probability) / 100`, }), close_date: Field.date({ + group: 'opportunity', label: 'Close Date', }), // Exercises the newly-registered `daysBetween` stdlib function — the canonical // "days remaining" formula (negative once the close date has passed). days_to_close: Field.formula({ + group: 'opportunity', label: 'Days to Close', expression: cel`record.close_date == null ? 0 : daysBetween(today(), record.close_date)`, }), discount_percent: Field.percent({ + group: 'opportunity', label: 'Discount %', defaultValue: 0, min: 0, @@ -85,6 +104,7 @@ export const Opportunity = ObjectSchema.create({ // flows are examples/app-showcase/src/automation/flows/, and the // `approvalStatusField` wiring is shown in skills/objectstack-automation/SKILL.md. approval_status: Field.select({ + group: 'opportunity', label: 'Approval Status', readonly: true, options: [ @@ -95,6 +115,7 @@ export const Opportunity = ObjectSchema.create({ ], }), renewal_of: Field.lookup('crm_opportunity', { + group: 'opportunity', label: 'Renewal Of', }), // Roll-up of the opportunity's product line items — recomputed server-side @@ -102,6 +123,7 @@ export const Opportunity = ObjectSchema.create({ // crm_opportunity_line_item.opportunity). The line-item grid also shows a // live running total during entry (inlineAmountField: 'amount'). line_total: Field.summary({ + group: 'opportunity', label: 'Products Total', summaryOperations: { object: 'crm_opportunity_line_item', field: 'amount', function: 'sum' }, }), diff --git a/examples/app-crm/src/security/sales-positions.ts b/examples/app-crm/src/security/sales-positions.ts index c9ca897376a..3e2a4c8963d 100644 --- a/examples/app-crm/src/security/sales-positions.ts +++ b/examples/app-crm/src/security/sales-positions.ts @@ -53,7 +53,7 @@ export const SalesUserPermissionSet = definePermissionSet({ // scope always follows the parent (ADR-0055), but object-level CRUD is a // SEPARATE gate that is never derived (security-master-detail-ungranted). // Grant shape matches the master exactly: same set, same bits, so the - // line-item grid on the Opportunity form (inlineEdit: 'grid') opens for + // line-item grid on the Opportunity form (its `lines` field group) opens for // the same users who can already work the parent record. crm_opportunity_line_item: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, crm_lead: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, diff --git a/examples/app-showcase/src/data/objects/expense-report.object.ts b/examples/app-showcase/src/data/objects/expense-report.object.ts index 5d748d9cf45..074999aa13b 100644 --- a/examples/app-showcase/src/data/objects/expense-report.object.ts +++ b/examples/app-showcase/src/data/objects/expense-report.object.ts @@ -141,8 +141,11 @@ export const ExpenseReport = ObjectSchema.create({ // ADR-0085 §5: the form, detail and drawer layout is derived from these // groups, so each field is placed in a named section rather than left to the // untitled fallback, which the field-no-consumers rule credits to no one (#32168). + // [#35889] `lines` places the expense lines' table between the report and + // its totals on the record page, and inlines it in the New / Edit form. fieldGroups: [ { key: 'report', label: 'Report' }, + { key: 'lines', label: 'Expense Lines', relatedList: 'showcase_expense_line' }, { key: 'totals', label: 'Totals' }, ], }); diff --git a/examples/app-showcase/src/data/objects/invoice.object.ts b/examples/app-showcase/src/data/objects/invoice.object.ts index e221318ff34..a4be540802b 100644 --- a/examples/app-showcase/src/data/objects/invoice.object.ts +++ b/examples/app-showcase/src/data/objects/invoice.object.ts @@ -40,10 +40,11 @@ export const Product = ObjectSchema.create({ * Invoice + Invoice Line — the canonical master-detail "header + line items" * shape. Unlike project↔task (a task is added to a project over time), an * invoice is meaningless without its lines: you enter the header AND its lines - * together, in one atomic transaction. So `invoice_line.invoice` declares - * `inlineEdit: 'grid'` — every standard New/Edit Invoice form renders an - * editable line-item grid, and the invoice `total` rolls the line amounts up - * server-side. This is where inline master-detail entry belongs. + * together, in one atomic transaction. So the invoice's `lines` field group + * names `showcase_invoice_line` — every standard New/Edit Invoice form renders + * an editable line-item grid (`invoice_line.invoice` picks the grid form + * factor with `inlineEdit: 'grid'`), and the invoice `total` rolls the line + * amounts up server-side. This is where inline master-detail entry belongs. */ export const Invoice = ObjectSchema.create({ name: 'showcase_invoice', @@ -72,13 +73,24 @@ export const Invoice = ObjectSchema.create({ delete: { visibleWhen: P`record.status != 'paid'` }, }, + // [#35889] The lines are part of the invoice: this group puts the + // `showcase_invoice_line` table in the invoice's record page after its + // fields, inlines it in the New / Edit Invoice form, and lets Edit on the + // record page save the invoice and its lines together. A master-detail + // child no group names is only a tab of the record page. + fieldGroups: [ + { key: 'invoice', label: 'Invoice' }, + { key: 'lines', label: 'Lines', relatedList: 'showcase_invoice_line' }, + ], + fields: { - name: Field.text({ label: 'Invoice Number', required: true, searchable: true, maxLength: 60 }), + name: Field.text({ label: 'Invoice Number', required: true, searchable: true, maxLength: 60, group: 'invoice' }), // Forward record-picker config (spec lookup* props). The renderer // auto-derives columns from the Account schema, but here we curate them and // — crucially — SCOPE the picker so a rep can't invoice a churned account. // `lookupFilters` is the structured, picker-honoured form of referenceFilters. account: Field.lookup('showcase_account', { + group: 'invoice', label: 'Account', required: true, descriptionField: 'industry', @@ -103,6 +115,7 @@ export const Invoice = ObjectSchema.create({ // chosen the picker has nothing to scope by; after switching accounts the // candidate list changes with it. contact: Field.lookup('showcase_contact', { + group: 'invoice', label: 'Contact', descriptionField: 'email', dependsOn: ['account'], @@ -113,11 +126,12 @@ export const Invoice = ObjectSchema.create({ // invoices; because `showcase_invoice_line` is `controlled_by_parent`, the // lines follow automatically (ADR-0055). Mirror of `project.owner`, and // labelled apart from the platform-injected `owner_id` lookup ("Owner"). - owner: Field.text({ label: 'Owner Email', maxLength: 200 }), + owner: Field.text({ label: 'Owner Email', maxLength: 200, group: 'invoice' }), // Region the sale was booked in — the invoice-side target of the Revenue // Pulse dashboard's shared "region" filter (framework#2501): accounts map // the same filter to their own `sales_region` via `filterBindings`. region: Field.select({ + group: 'invoice', label: 'Region', options: [ { label: 'AMER', value: 'amer', default: true }, @@ -126,6 +140,7 @@ export const Invoice = ObjectSchema.create({ ], }), status: Field.select({ + group: 'invoice', label: 'Status', required: true, options: [ @@ -140,6 +155,7 @@ export const Invoice = ObjectSchema.create({ // required marker + blocks submit, and the server's rule-validator enforces // the same predicate over the merged record — one rule, both ends agree. issued_on: Field.date({ + group: 'invoice', label: 'Issued On', requiredWhen: P`record.status in ['sent', 'paid']`, }), @@ -150,6 +166,7 @@ export const Invoice = ObjectSchema.create({ // Header tax rate (percent). The line-item entry form reads it live to show // a Subtotal / Tax / Total stack under the grid as lines are entered. tax_rate: Field.number({ + group: 'invoice', label: 'Tax Rate (%)', min: 0, max: 100, @@ -161,6 +178,7 @@ export const Invoice = ObjectSchema.create({ // pure client UX concern (the server has no visibility notion); the // `requiredWhen` half is enforced on both ends. paid_on: Field.date({ + group: 'invoice', label: 'Paid On', visibleWhen: P`record.status == 'paid'`, requiredWhen: P`record.status == 'paid'`, @@ -169,6 +187,7 @@ export const Invoice = ObjectSchema.create({ // (child FK auto-detected: showcase_invoice_line.invoice). This is the line // subtotal; the tax-inclusive grand total is shown live during entry. total: Field.summary({ + group: 'invoice', label: 'Subtotal', summaryOperations: { object: 'showcase_invoice_line', field: 'amount', function: 'sum' }, }), @@ -206,6 +225,7 @@ export const Invoice = ObjectSchema.create({ // so a write can store only a real code. Optional: an invoice without a // currency has no `amount` yet (see below). currency_code: Field.text({ + group: 'invoice', label: 'Currency', maxLength: 3, valueDomain: 'iso_4217_currency', @@ -214,6 +234,7 @@ export const Invoice = ObjectSchema.create({ // foreign amount needs a date to pick its rate, so a draft dated today is // convertible from its first save. invoice_date: Field.date({ + group: 'invoice', label: 'Invoice Date', required: true, defaultValue: 'NOW()', @@ -226,6 +247,7 @@ export const Invoice = ObjectSchema.create({ // the one the invoice states (the seeded yen lines are whole yen, so a yen // total stays whole). amount: Field.currency({ + group: 'invoice', label: 'Total incl. Tax', expression: cel`record.currency_code == null || record.currency_code == '' ? null : double(round((record.total == null ? 0 : record.total) * (1 + (record.tax_rate == null ? 0 : record.tax_rate) / 100) * 100)) / 100`, currencyConfig: { @@ -237,12 +259,14 @@ export const Invoice = ObjectSchema.create({ // Written by the engine only (`readonly`), in `dynamic` mode: it displays // in the home currency, so this metadata never names that currency. amount_home: Field.currency({ + group: 'invoice', label: 'Total incl. Tax (Home Currency)', readonly: true, }), // The rate the conversion used, kept with every digit it was stored with // (no `scale`, so nothing rounds the rate a reader is shown). amount_rate: Field.number({ + group: 'invoice', label: 'Exchange Rate', readonly: true, }), diff --git a/packages/cli/test/data-model-rules.test.ts b/packages/cli/test/data-model-rules.test.ts index b0960499238..a77f6567e59 100644 --- a/packages/cli/test/data-model-rules.test.ts +++ b/packages/cli/test/data-model-rules.test.ts @@ -50,16 +50,21 @@ describe('lintDataModel — relationships', () => { expect(db?.message).toContain('(cascade/restrict'); }); - it('suggests inlineEdit on master_detail line-item children', () => { - const issues = lintDataModel([ - { name: 'order_line', fields: { order: { type: 'master_detail', reference: 'order', required: true, deleteBehavior: 'cascade' } } }, - ]); - expect(has(issues, 'relationship/line-items-inline-edit')).toBe(true); + // objectstack#35889: the parent's field group, not the FK's inlineEdit, inlines a child. + it('suggests a parent field group for master_detail line-item children, inlineEdit or not', () => { + for (const inlineEdit of [undefined, true]) { + const issues = lintDataModel([ + { name: 'order', fields: { name: { type: 'text' } } }, + { name: 'order_line', fields: { order: { type: 'master_detail', reference: 'order', required: true, deleteBehavior: 'cascade', ...(inlineEdit ? { inlineEdit } : {}) } } }, + ]); + expect(has(issues, 'relationship/line-items-inline-edit')).toBe(true); + } }); - it('does NOT suggest inlineEdit when already set', () => { + it('does NOT suggest a group when the parent already places the line items', () => { const issues = lintDataModel([ - { name: 'order_line', fields: { order: { type: 'master_detail', reference: 'order', required: true, deleteBehavior: 'cascade', inlineEdit: true } } }, + { name: 'order', fields: { name: { type: 'text' } }, fieldGroups: [{ key: 'lines', relatedList: 'order_line' }] }, + { name: 'order_line', fields: { order: { type: 'master_detail', reference: 'order', required: true, deleteBehavior: 'cascade' } } }, ]); expect(has(issues, 'relationship/line-items-inline-edit')).toBe(false); }); @@ -71,9 +76,10 @@ describe('lintDataModel — relationships', () => { expect(has(issues, 'relationship/line-item-should-be-master-detail')).toBe(true); }); - it('warns when an association child is inlineEdit', () => { + it('warns when a parent field group places an association child', () => { const issues = lintDataModel([ - { name: 'ticket_comment', fields: { ticket: { type: 'master_detail', reference: 'ticket', required: true, deleteBehavior: 'cascade', inlineEdit: true } } }, + { name: 'ticket', fields: { name: { type: 'text' } }, fieldGroups: [{ key: 'comments', relatedList: 'ticket_comment' }] }, + { name: 'ticket_comment', fields: { ticket: { type: 'master_detail', reference: 'ticket', required: true, deleteBehavior: 'cascade' } } }, ]); const assoc = issues.find((i) => i.rule === 'relationship/association-inline-edit'); expect(assoc?.severity).toBe('warning'); @@ -81,7 +87,8 @@ describe('lintDataModel — relationships', () => { it('does NOT treat a line-item child as an association', () => { const issues = lintDataModel([ - { name: 'invoice_line', fields: { invoice: { type: 'master_detail', reference: 'invoice', required: true, deleteBehavior: 'cascade', inlineEdit: true } } }, + { name: 'invoice', fields: { name: { type: 'text' } }, fieldGroups: [{ key: 'lines', relatedList: 'invoice_line' }] }, + { name: 'invoice_line', fields: { invoice: { type: 'master_detail', reference: 'invoice', required: true, deleteBehavior: 'cascade' } } }, ]); expect(has(issues, 'relationship/association-inline-edit')).toBe(false); }); @@ -95,7 +102,13 @@ describe('lintDataModel — relationships', () => { describe('lintInlineEditBulk — relationship/inline-edit-needs-bulk', () => { const RULE = 'relationship/inline-edit-needs-bulk'; const OPEN = ['get', 'list', 'create', 'update', 'delete']; - const budget = (enable?: unknown) => ({ name: 'project_budget', ...(enable ? { enable } : {}), fields: { title: { type: 'text' } } }); + // objectstack#35889: the parent's field group naming the lines is what inlines them in its form. + const budget = (enable?: unknown, placed = true) => ({ + name: 'project_budget', + ...(enable ? { enable } : {}), + ...(placed ? { fieldGroups: [{ key: 'lines', relatedList: 'project_budget_line' }, { key: 'items', relatedList: 'project_budget_item' }] } : {}), + fields: { title: { type: 'text' } }, + }); const line = (inlineEdit: unknown, enable?: unknown) => ({ name: 'project_budget_line', ...(enable ? { enable } : {}), @@ -106,7 +119,7 @@ describe('lintInlineEditBulk — relationship/inline-edit-needs-bulk', () => { }); const hits = (objects: any[]) => lintInlineEditBulk(objects).filter((i) => i.rule === RULE); - it.each([true, 'grid', 'form'])('warns on the parent when inlineEdit is %s and its apiMethods omit bulk', (inlineEdit) => { + it.each([undefined, true, 'grid', 'form'])('warns on the parent when a group places the lines (inlineEdit %s) and its apiMethods omit bulk', (inlineEdit) => { const [issue, ...rest] = hits([budget({ apiMethods: OPEN }), line(inlineEdit)]); expect(rest).toEqual([]); expect(issue?.severity).toBe('warning'); @@ -132,11 +145,11 @@ describe('lintInlineEditBulk — relationship/inline-edit-needs-bulk', () => { expect(hits([budget({ apiMethods: OPEN }), line('grid'), second])).toHaveLength(1); }); - it('is silent when apiMethods include bulk, are undeclared, or nothing is inline-edited', () => { + it('is silent when apiMethods include bulk, are undeclared, or no group places the lines', () => { expect(hits([budget({ apiMethods: [...OPEN, 'bulk'] }), line('grid', { apiMethods: [...OPEN, 'bulk'] })])).toEqual([]); expect(hits([budget(), line('grid')])).toEqual([]); - expect(hits([budget({ apiMethods: OPEN }), line(undefined)])).toEqual([]); - expect(hits([budget({ apiMethods: OPEN }), line(false)])).toEqual([]); + expect(hits([budget({ apiMethods: OPEN }, false), line('grid')])).toEqual([]); + expect(hits([budget({ apiMethods: OPEN }, false), line(true)])).toEqual([]); }); it('reaches os lint, os validate and os build through the registry, as a warning, once', () => { diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 324c34f2313..8b4169dd4b2 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -2569,7 +2569,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ hint: f.fix ?? '', })), }, - // An inline-edited relationship whose parent or child declares + // A relationship a parent field group places in the parent's form, whose parent or child declares // `enable.apiMethods` without `bulk` (`relationship/inline-edit-needs-bulk`). // The parent's form saves the rows in one cross-object `/api/v1/batch`, which // asks every object in it for `bulk`, so the form fills and then 405s on save. diff --git a/packages/lint/src/data-model-rules.inline-edit-advisories.test.ts b/packages/lint/src/data-model-rules.inline-edit-advisories.test.ts index d6eb0409025..ce0a1bba037 100644 --- a/packages/lint/src/data-model-rules.inline-edit-advisories.test.ts +++ b/packages/lint/src/data-model-rules.inline-edit-advisories.test.ts @@ -3,29 +3,35 @@ /** * R5 `relationship/line-items-inline-edit` and R6 * `relationship/association-inline-edit` ask one question of a relationship: - * is it edited inline within the parent's form at all? + * does the parent's form inline it at all? * - * `FieldSchema.inlineEdit` accepts `true`, `'grid'` and `'form'`, and every - * reader treats all three as inline-edited (the console's inline subforms, the - * spec's body-table predicate, the sibling `relationship/inline-edit-needs-bulk` - * rule). So R5 stays silent on any of the three — telling an author who chose - * `'grid'` to "consider inlineEdit: true" would replace the mode they picked — - * and R6 warns on any of the three, because a `'grid'` or `'form'` association - * clutters the parent's entry form exactly as `true` does. Absent (and `false`) - * is the control on both sides: R5 suggests, R6 is silent. + * Since objectstack#35889 (maintainer ruling B, 「明细表应该改成指看分组的定义了」) + * the answer is the PARENT's field groups: a group whose `relatedList` names the + * child (a plain `master_detail`, or a `relatedList: 'primary'` FK) inlines it, + * and the FK's `inlineEdit` only picks the form factor. So R5 stays silent on a + * placed line-item child and suggests a group otherwise, whatever `inlineEdit` + * says; R6 warns on a placed association and is silent otherwise. */ import { describe, expect, it } from 'vitest'; +import { ObjectFieldGroupSchema } from '@objectstack/spec/data'; import { lintDataModel } from './data-model-rules.js'; const R5 = 'relationship/line-items-inline-edit'; const R6 = 'relationship/association-inline-edit'; -const INLINE_VALUES = [true, 'grid', 'form'] as const; +const INLINE_VALUES = [undefined, true, 'grid', 'form'] as const; -/** A parent plus one child whose `master_detail` back to it carries `inlineEdit` (omitted when `undefined`). */ -const stack = (child: string, inlineEdit: unknown): any[] => [ - { name: 'order', fields: { name: { type: 'text' } } }, +/** + * A parent plus one child whose `master_detail` back to it carries `inlineEdit` + * (omitted when `undefined`); `placed` adds a parent field group naming the child. + */ +const stack = (child: string, inlineEdit: unknown, placed: boolean): any[] => [ + { + name: 'order', + fields: { name: { type: 'text' } }, + ...(placed ? { fieldGroups: [{ key: 'lines', relatedList: child }] } : {}), + }, { name: child, fields: { @@ -42,28 +48,44 @@ const stack = (child: string, inlineEdit: unknown): any[] => [ const hits = (objects: any[], rule: string) => lintDataModel(objects).filter((i) => i.rule === rule); -describe('R5 relationship/line-items-inline-edit — silent on every inline-edit mode', () => { - it.each(INLINE_VALUES)('is silent when the line-item relationship declares inlineEdit: %s', (inlineEdit) => { - expect(hits(stack('order_line', inlineEdit), R5)).toEqual([]); +describe('R5 relationship/line-items-inline-edit — reads the parent field group', () => { + it.each(INLINE_VALUES)('is silent when a parent group places the line items (inlineEdit: %s)', (inlineEdit) => { + expect(hits(stack('order_line', inlineEdit, true), R5)).toEqual([]); }); - it.each([undefined, false])('suggests inline editing when inlineEdit is %s', (inlineEdit) => { - const [issue, ...rest] = hits(stack('order_line', inlineEdit), R5); + it.each(INLINE_VALUES)('suggests a parent field group when none places them (inlineEdit: %s)', (inlineEdit) => { + const [issue, ...rest] = hits(stack('order_line', inlineEdit, false), R5); expect(rest).toEqual([]); expect(issue?.severity).toBe('suggestion'); - expect(issue?.path).toBe('objects[1].fields.order.inlineEdit'); + expect(issue?.path).toBe('objects[1].fields.order'); + expect(issue?.fix).toBe("add { key: 'order_line', label: 'order_line', relatedList: 'order_line' } to order.fieldGroups"); + }); + + it('the printed group parses: a parent carrying it is placed and R5 goes silent', () => { + const [parent, child] = stack('order_line', undefined, false); + const printed = { key: 'order_line', label: 'order_line', relatedList: 'order_line' }; + expect(ObjectFieldGroupSchema.safeParse(printed).success).toBe(true); + // CONTROL: the snippet R5 printed before, with no label, does not parse. + expect(ObjectFieldGroupSchema.safeParse({ key: 'order_line', relatedList: 'order_line' }).success).toBe(false); + expect(hits([{ ...parent, fieldGroups: [printed] }, child], R5)).toEqual([]); + }); + + it.each([true, false])('is silent on a FK declaring relatedList: %s, which no group may place', (relatedList) => { + const [parent, child] = stack('order_line', undefined, false); + const fk = { ...child.fields.order, relatedList }; + expect(hits([parent, { ...child, fields: { order: fk } }], R5)).toEqual([]); }); }); -describe('R6 relationship/association-inline-edit — warns on every inline-edit mode', () => { - it.each(INLINE_VALUES)('warns when an association relationship declares inlineEdit: %s', (inlineEdit) => { - const [issue, ...rest] = hits(stack('order_comment', inlineEdit), R6); +describe('R6 relationship/association-inline-edit — warns on a placed association', () => { + it.each(INLINE_VALUES)('warns when a parent group places an association (inlineEdit: %s)', (inlineEdit) => { + const [issue, ...rest] = hits(stack('order_comment', inlineEdit, true), R6); expect(rest).toEqual([]); expect(issue?.severity).toBe('warning'); - expect(issue?.path).toBe('objects[1].fields.order.inlineEdit'); + expect(issue?.path).toBe('objects[1].fields.order'); }); - it.each([undefined, false])('is silent when inlineEdit is %s', (inlineEdit) => { - expect(hits(stack('order_comment', inlineEdit), R6)).toEqual([]); + it.each(INLINE_VALUES)('is silent when no group places it (inlineEdit: %s)', (inlineEdit) => { + expect(hits(stack('order_comment', inlineEdit, false), R6)).toEqual([]); }); }); diff --git a/packages/lint/src/data-model-rules.ts b/packages/lint/src/data-model-rules.ts index aa405bb974e..b6d9fe6cbec 100644 --- a/packages/lint/src/data-model-rules.ts +++ b/packages/lint/src/data-model-rules.ts @@ -22,6 +22,8 @@ import { NUMERIC_VALUE_TYPES, isAggregateCompatibleWithFieldType, isApiOperationAllowed, + fieldGroupsPlaceRelationship, + isGroupPlaceableRelationship, masterDetailRequiredOmitted, referenceCarrierOf, resolveEffectiveApiMethods, @@ -216,19 +218,6 @@ function isAssociationName(name: string): boolean { return ASSOCIATION_TOKENS.some((t) => lc === t || lc.endsWith(`_${t}`) || lc.endsWith(`_${t}s`)); } -/** - * Is this relationship edited inline within its parent's form at all? - * `FieldSchema.inlineEdit` accepts `true` (auto-pick by child shape), `'grid'` - * and `'form'`, and every reader — the console's inline subforms, the spec's - * `isBodyTableRelationship` — treats all three as inline-edited; `false` and - * absent are not. The one copy of that question in this file, so no rule can - * read a single literal of the three. - */ -function isInlineEdited(def: { inlineEdit?: unknown } | null | undefined): boolean { - const inlineEdit = def?.inlineEdit; - return inlineEdit === true || inlineEdit === 'grid' || inlineEdit === 'form'; -} - interface FieldEntry { name: string; def: any; @@ -296,9 +285,11 @@ const VALUE_DOMAIN_BY_FIELD_NAME: ReadonlyMap = new Map( export const RELATIONSHIP_INLINE_EDIT_NEEDS_BULK = 'relationship/inline-edit-needs-bulk'; /** - * An inline-edited relationship whose parent or child withholds `bulk`. + * A form-inlined relationship whose parent or child withholds `bulk`. * - * The parent's form saves an `inlineEdit` child's rows together with the parent + * The parent's form saves the rows of a child one of its field groups places + * (`fieldGroups[].relatedList`, objectstack#35889: the group, not the FK's + * `inlineEdit`, decides that the form inlines it) together with the parent * in ONE cross-object `/api/v1/batch` (ADR-0035), and that route gates EVERY op * as `bulk` plus its own write on the op's own object * (`packages/rest/src/batch-routes.ts`). So a parent or child whose DECLARED @@ -310,7 +301,9 @@ export const RELATIONSHIP_INLINE_EDIT_NEEDS_BULK = 'relationship/inline-edit-nee * A registry rule (`AUTHORING_RULES`), not a `lintDataModel` member: it * forecasts a refusal at run time rather than nudging a style, so `os lint`, * `os validate` and `os build` all report it. Advisory: a warning that refuses - * nothing. One finding per object, however many inline children name it. + * nothing. One finding per object, however many inline children name it. The + * rule id keeps its name (`inline-edit-needs-bulk`), which every suppression + * and explanation already cites. */ export function lintInlineEditBulk(objects: any[]): LocatedLintIssue[] { const issues: LocatedLintIssue[] = []; @@ -324,9 +317,12 @@ export function lintInlineEditBulk(objects: any[]): LocatedLintIssue[] { if (!child?.name) continue; for (const { name: fieldName, def } of fieldEntries(child.fields)) { if (!RELATIONSHIP_TYPES.has(def?.type)) continue; - if (!isInlineEdited(def)) continue; + if (!isGroupPlaceableRelationship(def)) continue; const parent = refOf(def); if (!parent) continue; + const parentIndex = indexByName.get(parent); + if (parentIndex === undefined) continue; + if (!fieldGroupsPlaceRelationship(objects[parentIndex]?.fieldGroups, child.name, fieldName)) continue; for (const target of [parent, child.name]) { const j = indexByName.get(target); if (j === undefined || reported.has(target)) continue; @@ -337,7 +333,8 @@ export function lintInlineEditBulk(objects: any[]): LocatedLintIssue[] { rule: RELATIONSHIP_INLINE_EDIT_NEEDS_BULK, where: objectWhere(objects[j]), message: - `inlineEdit on "${child.name}.${fieldName}" saves ${parent} and its ${child.name} rows in one ` + + `the field group of ${parent} that places "${child.name}.${fieldName}" puts its rows in ${parent}'s form, ` + + `which saves ${parent} and its ${child.name} rows in one ` + `/api/v1/batch, which needs 'bulk' on every object in it; "${target}" declares ` + `enable.apiMethods without 'bulk', so that save is refused 405 OBJECT_API_METHOD_NOT_ALLOWED`, path: `objects[${j}].enable.apiMethods`, @@ -1011,6 +1008,15 @@ export function lintDataModel(objects: any[]): LintIssue[] { (childrenByParent[parent] ||= []).push({ child, fieldName, def }); } } + // objectstack#35889 — a child is inlined in its parent's entry form only when + // one of the PARENT's field groups places it (`fieldGroups[].relatedList`), + // not by its FK's `inlineEdit`; R5 and R6 read that. + const fieldGroupsByObject = new Map(); + for (const o of objects) { + if (typeof o?.name === 'string' && !fieldGroupsByObject.has(o.name)) fieldGroupsByObject.set(o.name, o.fieldGroups); + } + const formInlines = (childName: string, fieldName: string, def: any, parent: string): boolean => + isGroupPlaceableRelationship(def) && fieldGroupsPlaceRelationship(fieldGroupsByObject.get(parent), childName, fieldName); for (let i = 0; i < objects.length; i++) { const obj = objects[i]; @@ -1194,15 +1200,20 @@ export function lintDataModel(objects: any[]): LintIssue[] { }); } // R5 — line-item children are usually entered inline with the parent. - // Any inline-edit mode the author already chose (`true`, 'grid' or - // 'form') satisfies it; only an absent or `false` inlineEdit is nudged. - if (isLineItemName(obj.name) && !isInlineEdited(def)) { + // A field group of the parent that places them satisfies it + // (objectstack#35889: that, not the FK's `inlineEdit`, inlines a child + // in the parent's form and its record page's body). Only a FK a group + // MAY place is asked: one declaring `relatedList: true` / `false` would + // have its group refused (`related-list-group-not-body`), so the + // author chose a tab, or no list, on purpose. + if (isLineItemName(obj.name) && isGroupPlaceableRelationship(def) && !formInlines(obj.name, fieldName, def, parent)) { + const groupLabel = String(typeof obj.label === 'string' && obj.label ? obj.label : obj.name).replace(/\\/g, '\\\\').replace(/'/g, "\\'"); issues.push({ severity: 'suggestion', rule: 'relationship/line-items-inline-edit', - message: `"${obj.name}" looks like line items of ${parent}; consider inlineEdit: true on "${fieldName}" so it is entered inline within the ${parent} form`, - path: `${fieldPath}.inlineEdit`, - fix: 'inlineEdit: true', + message: `"${obj.name}" looks like line items of ${parent}; consider a field group on ${parent} with relatedList: '${obj.name}' so its rows are entered inline within the ${parent} form and drawn in its record page`, + path: `${fieldPath}`, + fix: `add { key: '${obj.name}', label: '${groupLabel}', relatedList: '${obj.name}' } to ${parent}.fieldGroups`, }); } } @@ -1219,14 +1230,14 @@ export function lintDataModel(objects: any[]): LintIssue[] { } // R6 — associations should NOT be inlined into the parent's entry form, - // in any inline-edit mode ('grid' and 'form' clutter it as `true` does). - if (isInlineEdited(def) && isAssociationName(obj.name)) { + // which a parent field group placing them does (objectstack#35889). + if (isAssociationName(obj.name) && formInlines(obj.name, fieldName, def, parent)) { issues.push({ severity: 'warning', rule: 'relationship/association-inline-edit', - message: `"${obj.name}" is an association (comments/audit/activity), not line items — inlineEdit clutters the ${parent} entry form; surface it as a detail-page related list instead`, - path: `${fieldPath}.inlineEdit`, - fix: 'remove inlineEdit (use relatedList on the detail page)', + message: `"${obj.name}" is an association (comments/audit/activity), not line items — a field group of ${parent} placing it clutters the ${parent} entry form and record body; leave it a tab of the record page instead`, + path: `${fieldPath}`, + fix: `remove the ${parent} field group whose relatedList names ${obj.name}`, }); } } diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index c56f12e9ce2..7581faeffce 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -73,7 +73,7 @@ const FIELD_NO_CONSUMERS_EXPLANATION: RuleExplanation = { 'A CARRIER names a field without reading it, so it does not count: a translation label, a seed ' + 'value, an import-mapping target, a field-level permission grant (the `.` key of a ' + 'permission set\'s `fields`), a flow that only WRITES it, an ' + - '`inlineColumns` entry on a relationship field that does not set `inlineEdit` (no grid is ' + + '`inlineColumns` entry on a relationship field no field group of its parent places (no grid is ' + 'drawn), or a dataset or cube member path the analytics door refuses (a hop or column that does ' + 'not resolve, or a join the dataset\'s `include` does not declare).', 'The verdict on the warning is `inert` when no site of any kind names the field, and ' + @@ -3815,8 +3815,8 @@ const FIELD_EMBEDDED_SUB_FIELDS_EXPLANATION: RuleExplanation = { 'or `columns` on one promises a typed list the platform does not build.', 'A list that needs typed columns is a child object: its own fields carry the types, labels, ' + 'options and validation, and a `master_detail` field on it points back at the parent. The ' + - 'parent\'s record page lists the children as a related list, and `inlineEdit: \'grid\'` on that ' + - 'field edits them as an inline grid on the parent\'s form. Each row then has a record identity ' + + 'parent\'s record page lists the children as a related list, and a field group on the parent whose ' + + '`relatedList` names the child edits them as an inline grid on the parent\'s form. Each row then has a record identity ' + 'that a lookup, a roll-up or a flow can reach. Keep a `composite` / `repeater` only for JSON ' + 'whose shape the platform does not need to know.', 'Not judged: a form view\'s `fields` sub-rows and the metadata forms Studio renders — those are ' + @@ -4729,11 +4729,11 @@ const RELATED_LIST_GROUP_NOT_BODY_EXPLANATION: RuleExplanation = { covers: 'which related list a field group may place', paragraphs: [ 'A field group\'s `relatedList` places one related list\'s table among the field sections of the ' + - 'record\'s details column. It only POSITIONS a list that is already a body table; it does not make ' + - 'one. Whether a list is a body table is decided once, by the relationship\'s own FK field on the ' + - 'child: `relatedList: \'primary\'`, or a `master_detail` FK that sets `inlineEdit` and declares no ' + - '`relatedList`. Every other list is a side card in the related column (`relatedList: true` or ' + - 'absent), or hidden (`relatedList: false`).', + 'record\'s details column. It may place a list whose FK declares `relatedList: \'primary\'` (a body ' + + 'table with or without a group), or a `master_detail` FK that declares no `relatedList`, which is a ' + + 'tab of the record page until a group names it and then a body table at the group, inlined in the ' + + 'parent\'s entry form too. Every other list is a tab (`relatedList: true`, or a `lookup` with no ' + + '`relatedList`), or hidden (`relatedList: false`), and a group cannot place it.', 'A group naming a side card or a hidden list draws nothing at the group, silently, so it is an ' + 'error, the verdict `defineStack` gives on `os validate` and `os build` and the runtime publish ' + 'gate gives too. A bare child name names every FK of that child, so it is refused when any of ' + diff --git a/packages/lint/src/validate-field-consumers.test.ts b/packages/lint/src/validate-field-consumers.test.ts index 810276df0e3..433cc56a7f7 100644 --- a/packages/lint/src/validate-field-consumers.test.ts +++ b/packages/lint/src/validate-field-consumers.test.ts @@ -27,6 +27,48 @@ const validateFieldConsumers: typeof validateFieldConsumersUnrecorded = (...args type AnyRec = Record; +/** + * objectstack#35889 (maintainer ruling B): a parent's form inlines a child's + * grid only where one of the PARENT's field groups names the child; the FK's + * `inlineEdit` only picks the form factor. The inline-grid fixtures below were + * written as "a relationship that sets `inlineEdit`", so this spells that the + * new way: every relationship whose `inlineEdit` is set (not `false`) gets a + * parent field group naming `child.field`, and a `lookup` one also declares + * `relatedList: 'primary'` (a group may place a lookup list only then). The + * fixtures that set no `inlineEdit` (or `false`) are the no-group controls. + */ +function placeInlineEdited(stack: AnyRec): AnyRec { + const objects = Array.isArray(stack.objects) ? (stack.objects as AnyRec[]) : []; + const groups = new Map(); + const next = objects.map((obj) => { + const fields = (obj.fields ?? {}) as Record; + let changed = false; + const out: Record = {}; + for (const [name, def] of Object.entries(fields)) { + const relationship = def && (def.type === 'lookup' || def.type === 'master_detail') && typeof def.reference === 'string'; + if (relationship && def.inlineEdit !== undefined && def.inlineEdit !== false) { + const list = groups.get(def.reference as string) ?? []; + list.push({ key: `lines_${String(obj.name)}_${name}`, relatedList: `${String(obj.name)}.${name}` }); + groups.set(def.reference as string, list); + if (def.type === 'lookup' && def.relatedList === undefined) { + out[name] = { ...def, relatedList: 'primary' }; + changed = true; + continue; + } + } + out[name] = def; + } + return changed ? { ...obj, fields: out } : obj; + }); + return { + ...stack, + objects: next.map((obj) => { + const placed = groups.get(String(obj.name)); + return placed ? { ...obj, fieldGroups: [...((obj.fieldGroups as AnyRec[]) ?? []), ...placed] } : obj; + }), + }; +} + /** * The HotCRM shape, reduced: two objects sharing a field NAME (`tax_rate`), * consumed on one and merely carried on the other, plus one field of every @@ -678,7 +720,7 @@ describe('[#20929] validateFieldConsumers — an inline grid column names a fiel const data = { provider: 'object', object: 'inv' }; const columns = [{ name: 'qty' }]; - const stack = (relationship: AnyRec, view: AnyRec = {}, extra: AnyRec = {}): AnyRec => ({ + const stack = (relationship: AnyRec, view: AnyRec = {}, extra: AnyRec = {}): AnyRec => placeInlineEdited({ objects: [ { name: 'inv', fields: { name: { type: 'text' }, qty: { type: 'number' } } }, { @@ -720,6 +762,28 @@ describe('[#20929] validateFieldConsumers — an inline grid column names a fiel expect(verdicts(stack({}, { formViews: { edit } }))).toEqual(CREDITED); }); + it('[#35889] `inlineEdit` with no parent field group naming the child draws no grid: its columns are a carrier', () => { + const unplaced: AnyRec = { + objects: [ + { name: 'inv', fields: { name: { type: 'text' }, qty: { type: 'number' } } }, + { + name: 'line', + fields: { + name: { type: 'text' }, + invoice: { type: 'master_detail', reference: 'inv', inlineEdit: 'grid', inlineColumns: columns }, + qty: { type: 'number' }, + memo: { type: 'text' }, + }, + }, + ], + views: [{ list: { type: 'grid', data, columns: [{ field: 'name' }] } }], + }; + expect(verdicts(unplaced)).toEqual({ 'inv.qty': 'inert', 'line.qty': 'carrier-only', 'line.memo': 'inert' }); + // Control: the parent's group naming the child draws the grid. + const placed = { ...unplaced, objects: [{ ...(unplaced.objects as AnyRec[])[0], fieldGroups: [{ key: 'lines', relatedList: 'line' }] }, (unplaced.objects as AnyRec[])[1]] }; + expect(verdicts(placed)).toEqual(CREDITED); + }); + it('`inlineColumns` on a field that does not set `inlineEdit` draws no grid: a carrier, listed for removal', () => { const findings = validateFieldConsumers(stack({ inlineColumns: columns })); expect(Object.fromEntries(findings.map((f) => [`${f.object}.${f.field}`, f.verdict]))).toEqual({ @@ -764,7 +828,7 @@ describe('[#20951] validateFieldConsumers — a child collection credits its chi const data = { provider: 'object', object: 'inv' }; const MASTER_DETAIL = { type: 'master_detail', reference: 'inv' }; - const stack = (lineFields: AnyRec, view: AnyRec = {}, invoice: AnyRec = MASTER_DETAIL): AnyRec => ({ + const stack = (lineFields: AnyRec, view: AnyRec = {}, invoice: AnyRec = MASTER_DETAIL): AnyRec => placeInlineEdited({ objects: [ { name: 'inv', fields: { name: { type: 'text' }, total: { type: 'number' }, line_total: { type: 'number' } } }, { name: 'line', fields: { name: { type: 'text' }, invoice, ...lineFields } }, @@ -1034,7 +1098,7 @@ describe('[#21091] validateFieldConsumers — an inline collection reads its joi secret: { type: 'text', hidden: true }, }; - const stack = (relationship: AnyRec, extra: { form?: AnyRec; details?: unknown[] } = {}): AnyRec => ({ + const stack = (relationship: AnyRec, extra: { form?: AnyRec; details?: unknown[] } = {}): AnyRec => placeInlineEdited({ objects: [ { name: 'ord', fields: { name: { type: 'text' }, notes: { type: 'textarea' } } }, { name: 'itm', fields: { ...ITEM_FIELDS, ord: relationship } }, @@ -1630,7 +1694,7 @@ describe('[#32256] validateFieldConsumers — an inline grid reads its line-posi sort_order: { type: 'number' }, }; - const stack = (relationship: AnyRec, extra: AnyRec = {}, lineFields: AnyRec = LINE_FIELDS): AnyRec => ({ + const stack = (relationship: AnyRec, extra: AnyRec = {}, lineFields: AnyRec = LINE_FIELDS): AnyRec => placeInlineEdited({ objects: [ { name: 'ord', fields: { name: { type: 'text' } } }, { name: 'lin', fields: { ...lineFields, ord: relationship } }, diff --git a/packages/lint/src/validate-field-consumers.ts b/packages/lint/src/validate-field-consumers.ts index 2d4321b1991..2e7865d8b1c 100644 --- a/packages/lint/src/validate-field-consumers.ts +++ b/packages/lint/src/validate-field-consumers.ts @@ -102,7 +102,7 @@ * names the field the entry grants on, is not a read: it is a carrier * ({@link fieldPermissionGrantOf}). * - **A derived inline grid** ({@link creditDerivedInlineGrid}, - * `deriveInlineGridColumns`). A relationship field that sets `inlineEdit` + * `deriveInlineGridColumns`). A relationship field a parent field group places (objectstack#35889) * with no `inlineColumns`, and a `subforms` entry with no `columns`, both * draw a grid of the child object whose columns are derived from the * child's fields. The derivation is the spec's, and it is the renderer's @@ -129,7 +129,7 @@ * not decided by this rule. * * One consumer is the relationship itself: a `lookup` or `master_detail` - * field that sets `inlineEdit` is the inline grid's join key — the renderer + * field a parent field group places is the inline grid's join key — the renderer * loads the child rows filtered on it and stamps it on every row it saves — * so it is read whatever columns the grid draws. * @@ -138,7 +138,7 @@ * position into on drag-reorder and loads the child rows ordered by. No * column draws it — both derivations above skip it — so no column credits * it, but every inline grid resolves one, with authored columns or derived - * ones: a relationship field that sets `inlineEdit` and every `subforms` / + * ones: a relationship field a parent field group places and every `subforms` / * `details` entry. The field is the spec's derivation, never a copy of its * name list; the child's other sort-named fields, and a `record:line_items` * panel (which draws no grid of its own), stay uncredited. @@ -219,7 +219,7 @@ import { resolveDisplayField, } from '@objectstack/spec/data'; import type { DisplayNameObjectMeta, ServiceObject } from '@objectstack/spec/data'; -import { referenceTargetOf } from '@objectstack/spec/data'; +import { fieldGroupsPlaceRelationship, isGroupPlaceableRelationship, referenceTargetOf } from '@objectstack/spec/data'; import type { DefaultRowScope, FieldPermission, @@ -694,6 +694,11 @@ class ConsumerLedger { readonly datasetObject = new Map(); /** object → its declared field map, the shape the spec's derivations read */ readonly fieldMapByObject = new Map>(); + /** + * object → its declared `fieldGroups`: a parent's group naming a child list + * is what inlines that child's grid in the parent's form (objectstack#35889). + */ + readonly fieldGroupsByObject = new Map(); /** `object.field` → sites */ readonly sites = new Map(); /** @@ -1234,45 +1239,43 @@ function walkObject(ledger: ConsumerLedger, obj: AnyRec, objectName: string, obj ledger.record(reference, displayField, { root: 'objects', path: `${fieldPath}.displayField`, kind: 'display' }); } // [#20929] The grid's columns name fields of THIS object, the child. The - // grid exists only where the field sets `inlineEdit`: the spec's help text - // says `inlineColumns` is "used only when this field sets inlineEdit", and - // objectui's `attachInlineSubforms` skips the field otherwise. Without it - // the columns name the field and draw nothing, so they are a carrier a - // removal must clean, not a consumer. + // grid exists only where a field group of the PARENT places this + // relationship (objectstack#35889: `fieldGroups[].relatedList`, no longer + // the FK's own `inlineEdit`), which is what objectui's + // `attachInlineSubforms` reads. Without it the columns name the field and + // draw nothing, so they are a carrier a removal must clean, not a consumer. + const fieldName = strName(field.name); + const formInlined = + fieldName !== undefined && + (field.type === 'master_detail' || field.type === 'lookup') && + !!reference && + isGroupPlaceableRelationship(field) && + fieldGroupsPlaceRelationship(ledger.fieldGroupsByObject.get(reference), objectName, fieldName); creditInlineGridColumns( ledger, field.inlineColumns, objectName, - field.inlineEdit ? 'display' : 'carrier', + formInlined ? 'display' : 'carrier', 'objects', `${fieldPath}.inlineColumns`, ); - // [#20951] With `inlineEdit` and no authored `inlineColumns`, the parent's - // form still draws a grid of THIS object: the derived columns. The grid - // exists for a relationship to a parent, which is what objectui's - // `attachInlineSubforms` requires before it builds one: a `master_detail` - // or `lookup` field whose target resolves. - const fieldName = strName(field.name); - if ( - fieldName !== undefined && - field.inlineEdit && - (field.type === 'master_detail' || field.type === 'lookup') && - !!reference - ) { + // [#20951] With no authored `inlineColumns`, the parent's form still draws + // a grid of THIS object: the derived columns. + if (formInlined) { // [#21091] The relationship itself is the grid's join key: the renderer // loads the child rows filtered on it and stamps it on every row it // saves. That holds whether the columns are authored or derived, and // for a `lookup` as for a `master_detail` — which is exempt anyway. - ledger.record(objectName, fieldName, { root: 'objects', path: `${fieldPath}.inlineEdit`, kind: 'behaviour' }); + ledger.record(objectName, fieldName, { root: 'objects', path: fieldPath, kind: 'behaviour' }); // [#32256] So is the grid's line-position field on THIS object, authored // columns or derived. - creditInlineGridSortField(ledger, objectName, 'objects', `${fieldPath}.inlineEdit`); + creditInlineGridSortField(ledger, objectName, 'objects', fieldPath); if (!hasAuthoredColumns(field.inlineColumns)) { // [#21091] The derived grid's per-row expand form draws more of THIS - // object. An explicit `grid` / `form` is the form factor; `true` is - // the renderer's smart default, which this rule does not resolve. + // object. An explicit `grid` / `form` is the form factor; anything + // else is the renderer's smart default, which this rule does not resolve. const rowForm = { inlineMode: formFactorOf(field.inlineEdit) }; - creditDerivedInlineGrid(ledger, objectName, fieldName, rowForm, 'objects', `${fieldPath}.inlineEdit`); + creditDerivedInlineGrid(ledger, objectName, fieldName, rowForm, 'objects', fieldPath); } } for (const [key, value] of Object.entries(field)) { @@ -1496,6 +1499,7 @@ export function validateFieldConsumers(stack: AnyRec): FieldConsumerFinding[] { const injected = injectedColumnsFor(obj); const titleField = resolveDisplayField(displayMetaOf(obj, fields)); creditFieldGroupLayout(ledger, obj, objectName, fields); + if (!ledger.fieldGroupsByObject.has(objectName)) ledger.fieldGroupsByObject.set(objectName, obj.fieldGroups); for (const { rec: field, path: fieldPath } of fields) { const fieldName = strName(field.name); if (!fieldName) continue; diff --git a/packages/lint/src/validate-related-list-refs.test.ts b/packages/lint/src/validate-related-list-refs.test.ts index 6c8d2a4a125..5f472b9ba19 100644 --- a/packages/lint/src/validate-related-list-refs.test.ts +++ b/packages/lint/src/validate-related-list-refs.test.ts @@ -100,7 +100,7 @@ describe('validateRelatedListRefs', () => { expect(finding.message).toContain("'rlo_task.lead_id' is a side card"); // Controls: the same group naming a body table, and the side card once marked primary. expect(rules(stack('rlo_line'))).toEqual([]); - // #35597: a master_detail with no relatedList is a body table without inlineEdit too. + // #35597 / #35889: a group may name a master_detail with no relatedList, inlineEdit or not. const plainLine = { ...line, name: 'rlo_step', fields: { lead_id: { type: 'master_detail', label: 'Lead', reference: 'rlo_lead' } } }; expect(rules(stack('rlo_step', plainLine))).toEqual([]); const primaryTask = { ...task, fields: { lead_id: { ...task.fields.lead_id, relatedList: 'primary' } } }; diff --git a/packages/lint/src/validate-related-list-refs.ts b/packages/lint/src/validate-related-list-refs.ts index de7043f30f5..876c0755bcd 100644 --- a/packages/lint/src/validate-related-list-refs.ts +++ b/packages/lint/src/validate-related-list-refs.ts @@ -51,9 +51,10 @@ * * ## A field group names body tables only (#27478) * - * A field group's `relatedList` positions a BODY TABLE; it never promotes a - * side card (ruling B on #27055: body-ness is the FK's own keys, - * `isBodyTableRelationship` in `@objectstack/spec/data`). So a group whose + * A field group's `relatedList` places a BODY TABLE: it positions a `'primary'` + * list, or makes a plain `master_detail` list one (#35889); it never promotes a + * side card (ruling B on #27055, `isGroupPlaceableRelationship` in + * `@objectstack/spec/data`). So a group whose * entry names a relationship that is not one — a side card, or a list hidden by * `relatedList: false` — is `related-list-group-not-body` at `error`: the * record page would draw nothing at the group. Judged on the same children as diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index acd2781e39e..58a84702277 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -106,7 +106,7 @@ export const enMetadataForms: NonNullable = { }, "fieldGroups.relatedList": { label: "Related List", - helpText: "Makes this entry a related list's table instead of a section of fields: name the child object (or object.field) whose list is drawn at this position in the record's details column. Such a group holds no fields; a field that names it as its group is refused, and so is a name that matches no relationship pointing at this object. The record page does not draw this placement yet." + helpText: "Makes this entry a related list's table instead of a section of fields: name the child object (or object.field) whose list is drawn at this position in the record's details column. Such a group holds no fields; a field that names it as its group is refused, and so is a name that matches no relationship pointing at this object. The parent's create and edit forms inline the table too, and the record page's Edit saves the record and its rows together." }, "fieldGroups.collapse": { label: "Collapse", @@ -791,7 +791,7 @@ export const enMetadataForms: NonNullable = { }, inlineColumns: { label: "Inline Columns", - helpText: "Columns of the inline grid on the parent's form, in display order; used only when this field sets inlineEdit, which is written in source. Unset: derived from this object's editable fields, and past six the rest start in the grid's column chooser. An entry that names only a field takes its type, options and rules from that field; the other column keys, type first, are written in source." + helpText: "Columns of the inline grid on the parent's form, in display order; used only when a field group of the parent names this child (fieldGroups[].relatedList). Unset: derived from this object's editable fields, and past six the rest start in the grid's column chooser. An entry that names only a field takes its type, options and rules from that field; the other column keys, type first, are written in source." }, "inlineColumns.name": { label: "Name", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 84cc7bf239a..f368949d5de 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -106,7 +106,7 @@ export const zhCNMetadataForms: NonNullable = }, "fieldGroups.relatedList": { label: "相关列表", - helpText: "让该条目代表一个相关列表的表格,而不是一组字段:填写子对象(或 object.field),其列表就显示在记录详情栏的这个位置。这样的分组不包含字段;把它填为自身分组的字段会被拒绝,不对应任何指向本对象的关系的名称也会被拒绝。记录页目前还不会绘制这种位置。" + helpText: "让该条目代表一个相关列表的表格,而不是一组字段:填写子对象(或 object.field),其列表就显示在记录详情栏的这个位置。这样的分组不包含字段;把它填为自身分组的字段会被拒绝,不对应任何指向本对象的关系的名称也会被拒绝。父记录的新建和编辑表单也会内嵌这张表,在记录页点「编辑」时主记录和这些行一起保存。" }, "fieldGroups.collapse": { label: "折叠", @@ -791,7 +791,7 @@ export const zhCNMetadataForms: NonNullable = }, inlineColumns: { label: "内嵌表格列", - helpText: "父记录表单上内嵌表格的列,按显示顺序排列;仅当本字段设置了 inlineEdit(在源码中编写)时才使用。未设置:从本对象的可编辑字段推导,超过六列时其余列起初收在表格的列选择器中。只写字段名的条目会从该字段获取类型、选项和规则;其他列设置(首先是 type)在源码中编写。" + helpText: "父记录表单上内嵌表格的列,按显示顺序排列;仅当父对象的某个字段分组指向这张子表(fieldGroups[].relatedList)时才使用。未设置:从本对象的可编辑字段推导,超过六列时其余列起初收在表格的列选择器中。只写字段名的条目会从该字段获取类型、选项和规则;其他列设置(首先是 type)在源码中编写。" }, "inlineColumns.name": { label: "名称", diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 79f5403adef..8994ef54081 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -83,6 +83,7 @@ "BodyDoorRecordRefSchema (const)", "BodyMailSendInput (type)", "BodyMailSendInputSchema (const)", + "BodyTableContext (interface)", "BooleanComparandDoorCase (type)", "BooleanComparandDoorDeferredCase (interface)", "BooleanComparandDoorFieldMeta (interface)", @@ -1020,6 +1021,7 @@ "externalColumnMapTargets (function)", "fieldForm (const)", "fieldGroupBodyTableRefusal (function)", + "fieldGroupsPlaceRelationship (function)", "filterOperatorFieldTypeFit (function)", "filterSubtreeProvenanceOf (function)", "fixedInnerReadOf (function)", @@ -1075,6 +1077,7 @@ "isFilterAST (function)", "isFixedReadLeaf (function)", "isGlobalUnique (function)", + "isGroupPlaceableRelationship (function)", "isIncoherentAggregate (function)", "isInjectedColumnDefinition (function)", "isInlineRowFormOffered (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 682f418df6d..805daa39943 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -80,6 +80,7 @@ "BodyDoorRecordRefSchema": "src/data/hook-body-doors.zod.ts#BodyDoorRecordRefSchema (const)", "BodyMailSendInput": "src/data/hook-body-doors.zod.ts#BodyMailSendInput (type)", "BodyMailSendInputSchema": "src/data/hook-body-doors.zod.ts#BodyMailSendInputSchema (const)", + "BodyTableContext": "src/data/related-list-body-table.ts#BodyTableContext (interface)", "BooleanComparandDoorCase": "src/data/filter-boolean-comparand-declared-type.ts#BooleanComparandDoorCase (type)", "BooleanComparandDoorDeferredCase": "src/data/filter-boolean-comparand-declared-type.ts#BooleanComparandDoorDeferredCase (interface)", "BooleanComparandDoorFieldMeta": "src/data/filter-boolean-comparand-declared-type.ts#BooleanComparandDoorFieldMeta (interface)", @@ -1005,6 +1006,7 @@ "externalColumnMapTargets": "src/data/injected-system-column-provenance.ts#externalColumnMapTargets (function)", "fieldForm": "src/data/field.form.ts#fieldForm (const)", "fieldGroupBodyTableRefusal": "src/data/related-list-body-table.ts#fieldGroupBodyTableRefusal (function)", + "fieldGroupsPlaceRelationship": "src/data/related-list-body-table.ts#fieldGroupsPlaceRelationship (function)", "filterOperatorFieldTypeFit": "src/data/filter-operator-field-type-fit.ts#filterOperatorFieldTypeFit (function)", "filterSubtreeProvenanceOf": "src/data/filter-subtree-provenance.ts#filterSubtreeProvenanceOf (function)", "fixedInnerReadOf": "src/data/fixed-read-leaf.ts#fixedInnerReadOf (function)", @@ -1060,6 +1062,7 @@ "isFilterAST": "src/data/filter.zod.ts#isFilterAST (function)", "isFixedReadLeaf": "src/data/fixed-read-leaf.ts#isFixedReadLeaf (function)", "isGlobalUnique": "src/data/field.zod.ts#isGlobalUnique (function)", + "isGroupPlaceableRelationship": "src/data/related-list-body-table.ts#isGroupPlaceableRelationship (function)", "isIncoherentAggregate": "src/data/aggregation-policy.ts#isIncoherentAggregate (function)", "isInjectedColumnDefinition": "src/data/injected-system-column-provenance.ts#isInjectedColumnDefinition (function)", "isInlineRowFormOffered": "src/data/inline-grid-columns.ts#isInlineRowFormOffered (function)", diff --git a/packages/spec/src/data/authoring-key-lint.ts b/packages/spec/src/data/authoring-key-lint.ts index ebad5a51e87..a6522383093 100644 --- a/packages/spec/src/data/authoring-key-lint.ts +++ b/packages/spec/src/data/authoring-key-lint.ts @@ -79,8 +79,8 @@ export interface UnknownAuthoringKeyFinding { const EMBEDDED_JSON_TYPED_LIST = 'An object-level `composite` / `repeater` stores untyped JSON — no per-column labels, types, ' + 'options or required flags. A list that needs typed columns is a child object whose ' - + '`master_detail` field points back at this object; `inlineEdit: \'grid\'` on that field edits ' - + 'its rows as an inline grid on this object\'s form.'; + + '`master_detail` field points back at this object; a field group on this object whose ' + + '`relatedList` names that child edits its rows as an inline grid on this object\'s form.'; /** * Semantic near-misses on `FieldSchema` — a different **word** for the same diff --git a/packages/spec/src/data/field.form.ts b/packages/spec/src/data/field.form.ts index d1a84a47967..231d90cc9ba 100644 --- a/packages/spec/src/data/field.form.ts +++ b/packages/spec/src/data/field.form.ts @@ -353,7 +353,7 @@ export const fieldForm = defineForm({ field: 'inlineColumns', type: 'repeater', visibleWhen: "data.type == 'master_detail'", - helpText: 'Columns of the inline grid on the parent\'s form, in display order; used only when this field sets inlineEdit, which is written in source. Unset: derived from this object\'s editable fields, and past six the rest start in the grid\'s column chooser. An entry that names only a field takes its type, options and rules from that field; the other column keys, type first, are written in source.', + helpText: 'Columns of the inline grid on the parent\'s form, in display order; used only when a field group of the parent names this child (fieldGroups[].relatedList). Unset: derived from this object\'s editable fields, and past six the rest start in the grid\'s column chooser. An entry that names only a field takes its type, options and rules from that field; the other column keys, type first, are written in source.', fields: [ { field: 'name', label: 'Name', type: 'text', required: true, helpText: 'Field of this (the child) object that the column shows and edits (e.g. quantity). Nothing checks it when you save or publish: a name that is not a field of this object renders a plain text column.' }, { field: 'label', label: 'Label', type: 'text', helpText: 'Column header. Unset: the field\'s own label.' }, diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 7c0b55a46f9..4cfda2c2b55 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -98,7 +98,7 @@ export const FieldType = z.enum([ // (≈ Strapi component / ACF group / ACF repeater): `FieldSchema` declares no sub-field // member, so nothing types, labels, validates or addresses the inner keys or rows. // A list that needs typed columns is a CHILD OBJECT whose `master_detail` field points - // back at the parent; `inlineEdit: 'grid'` edits its rows inline on the parent's form + // back at the parent; a parent field group naming it edits its rows inline on the parent's form // (ruling 6386744473). // A form view's `fields` sub-rows (`ui/view.zod.ts`) are a different surface. 'composite', // Single embedded JSON object, untyped — no declared sub-fields @@ -2294,25 +2294,27 @@ export const FieldSchema = lazySchema(() => { default: 'set_null', }), /** - * Master-detail INLINE EDITING. On a child's `master_detail`/`lookup` field - * (whose `reference` is the parent object), declare that "this child is - * entered/edited inline within the parent's form". The parent's standard - * create/edit form then renders the children and saves parent + children in - * ONE atomic transaction — no form view config and no bespoke page. The intent - * lives here in the data model; forms derive the UI. + * Master-detail INLINE EDITING — the FORM FACTOR of the child's rows in the + * parent's form. WHETHER the parent's form inlines this child is no longer + * this key's to say (#35889, maintainer ruling B: 「明细表应该改成指看分组的定义了」): + * the parent's create/edit form inlines a child exactly where one of the + * PARENT's field groups names it (`ObjectFieldGroupSchema.relatedList`), the + * same test that draws its table in the record page's body, and saves parent + * + children in ONE atomic transaction. A child no group names is a tab of + * the record page and stays out of the form, whatever this key says. * - * The value also selects the EDITING FORM FACTOR: - * - `true` → auto: the UI picks `grid` or `form` from the child's shape - * (rich types / many fields → `form`, else `grid`). + * The value selects the EDITING FORM FACTOR of a placed child: + * - `true` / absent → auto: the UI picks `grid` or `form` from the + * child's shape (rich types / many fields → `form`, else `grid`). * - `'grid'` → an editable line-item grid (fast bulk entry; thin children * like invoice lines / order items). * - `'form'` → a compact read-only list; "Add" / per-row edit opens the * child's FULL form (fat children with rich types, e.g. long * text, attachments, many fields). - * Use for true line-item/composition children; leave off for associations - * (comments, attachments) — surface those as detail-page related lists. + * Place true line-item/composition children with a group; leave + * associations (comments, attachments) as tabs. */ - inlineEdit: z.union([z.boolean(), z.enum(['grid', 'form'])]).optional().describe('Edit these child records inline within the parent\'s form (atomic master-detail). true = auto-pick grid/form by child shape; \'grid\' = editable line-item grid; \'form\' = list + per-row full form.'), + inlineEdit: z.union([z.boolean(), z.enum(['grid', 'form'])]).optional().describe('How the parent\'s form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; \'grid\' = editable line-item grid; \'form\' = list + per-row full form.'), /** Optional section title for the inline grid (defaults to the child object label). */ inlineTitle: z.string().optional().describe('Title for the inline master-detail grid'), /** @@ -2333,9 +2335,11 @@ export const FieldSchema = lazySchema(() => { * the parent's record DETAIL page. Owned children (`master_detail`) and * `lookup` children are shown by default (derived from the relationship); * set `relatedList: false` to suppress a child from the detail page (e.g. - * noisy audit/association links you don't want surfaced). Where `inlineEdit` - * pulls a child INTO the parent's entry form (write side), `relatedList` - * controls its appearance on the parent's detail page (read side). The intent + * noisy audit/association links you don't want surfaced). `relatedList` + * controls the child's appearance on the parent's detail page (read side); + * whether the parent's entry form inlines it is the parent's field group's + * to say (#35889, ruling B), and `inlineEdit` only picks the form factor of + * a child a group places. The intent * lives here in the data model; the detail page derives the UI. * * Tri-state (ADR-0085 semantic-role style — a statement about the @@ -2356,12 +2360,16 @@ export const FieldSchema = lazySchema(() => { * How the record page lays these out is ADR-0085's to define; this key states * the relationship's role, not the page's chrome. * - * Absent on a `master_detail` field, the list is `'primary'` by default - * (#35597, amending #27069 which also required `inlineEdit`): rows the parent - * owns are part of its main content (a quote's lines belong under the quote, - * not beside it), whether or not the parent's form edits them inline. Write - * `relatedList: true` to keep such a list an auxiliary panel, or `false` to - * hide it. Absent on a `lookup` field, the list stays an auxiliary panel. + * Absent on a `master_detail` field, the list is an auxiliary panel (a tab + * of the record page) by default, like a `lookup` (#35889, superseding + * #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). + * 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. * * SORT INHERITANCE (#13294, following #11345's browser-verified acceptance * run): a derived related list (`relatedList: 'primary'`) inherits its row @@ -2374,7 +2382,7 @@ export const FieldSchema = lazySchema(() => { * A child object with no list-view sort emits no ordering parameter at all, * and rows fall back to record-id order. */ - relatedList: z.union([z.boolean(), z.literal('primary')]).optional().describe('Show this child collection as a related list on the parent\'s detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = \'primary\' (a body table) on a master_detail field, an auxiliary panel on a lookup field; false = hidden: the child object is not shown on the parent record page; \'primary\' = a body table: part of the record\'s main content, shown as a full-width table in the record\'s detail body. Write true on a master_detail field to keep it an auxiliary panel. \'primary\' places a list and does not order it: the parent object\'s relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: \'primary\') inherits its row order from the child object\'s DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort= / sort=-, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order.'), + relatedList: z.union([z.boolean(), z.literal('primary')]).optional().describe('Show this child collection as a related list on the parent\'s detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; \'primary\' = a body table: part of the record\'s main content, shown as a full-width table in the record\'s detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. \'primary\' places a list and does not order it: the parent object\'s relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: \'primary\') inherits its row order from the child object\'s DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort= / sort=-, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order.'), /** Optional section title for the detail-page related list (defaults to the child object label). */ relatedListTitle: z.string().optional().describe('Title for the detail-page related list'), /** diff --git a/packages/spec/src/data/object.form.ts b/packages/spec/src/data/object.form.ts index 1e25ba41ca6..285bec3edb8 100644 --- a/packages/spec/src/data/object.form.ts +++ b/packages/spec/src/data/object.form.ts @@ -112,7 +112,7 @@ export const objectForm = defineForm({ { field: 'fields', label: 'Fields', type: 'tags', helpText: 'The fields this group shows, in display order (field names). Written, it sets the order inside the group without moving any field. A field this list names may not name another group in its own group setting, and a field may be listed by one group only. Not allowed with Related List.' }, { field: 'icon', label: 'Icon', type: 'text', helpText: 'Lucide icon name shown beside the header on the record detail page (e.g. "banknote"). The entry form does not show it.' }, { field: 'description', label: 'Description', type: 'textarea', helpText: 'Text shown under the header, on the entry form and the record detail page.' }, - { field: 'relatedList', label: 'Related List', type: 'text', helpText: 'Makes this entry a related list\'s table instead of a section of fields: name the child object (or object.field) whose list is drawn at this position in the record\'s details column. Such a group holds no fields; a field that names it as its group is refused, and so is a name that matches no relationship pointing at this object. The record page does not draw this placement yet.' }, + { field: 'relatedList', label: 'Related List', type: 'text', helpText: 'Makes this entry a related list\'s table instead of a section of fields: name the child object (or object.field) whose list is drawn at this position in the record\'s details column. Such a group holds no fields; a field that names it as its group is refused, and so is a name that matches no relationship pointing at this object. The parent\'s create and edit forms inline the table too, and the record page\'s Edit saves the record and its rows together.' }, { field: 'collapse', label: 'Collapse', type: 'select', helpText: 'Whether the section can be collapsed, on the entry form and the record detail page. Unset: none.', options: [ { label: 'None — always open, no toggle', value: 'none' }, { label: 'Expanded — collapsible, starts open', value: 'expanded' }, diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 11a9f6036e5..33628f876e0 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1409,20 +1409,24 @@ export const ObjectFieldGroupSchema = lazySchema(() => strictObject({ * everywhere; a child that exists nowhere is refused at `defineStack` (save a * platform-prefixed name, left to the runtime) and by a metadata write that * names no package, and a write into a package stores it, placing nothing. - * It names a BODY TABLE only (`isBodyTableRelationship`, #27478, as amended - * by #35597): an inbound FK declaring `relatedList: 'primary'`, or a - * `master_detail` FK that declares no `relatedList`. Body-ness is the FK's to - * decide; the group only positions it. 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 (`related-list-group-not-body`), naming - * each FK and the remedy (mark it `relatedList: 'primary'`, name only the - * body table as `object.field`, or remove the group's `relatedList`). + * It names a list a group may place only (`isGroupPlaceableRelationship`, + * #27478, as amended by #35597 and #35889): an inbound FK declaring + * `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 + * 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 + * (`related-list-group-not-body`), naming each FK and the remedy (mark it + * `relatedList: 'primary'`, name only the body table as `object.field`, or + * remove the group's `relatedList`). * Body tables no group places keep the record page's default position. */ 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): 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 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' }), /** * [ADR-0085 §5] Section visibility predicate — CEL, the ADR-0089 canonical diff --git a/packages/spec/src/data/record-page-describes.test.ts b/packages/spec/src/data/record-page-describes.test.ts index b09d910b8e5..0e4c7ecf55e 100644 --- a/packages/spec/src/data/record-page-describes.test.ts +++ b/packages/spec/src/data/record-page-describes.test.ts @@ -105,7 +105,10 @@ describe('[#27312] relatedList: \'primary\' describes the v3 body table', () => it('states each value\'s role on the record page and cites ADR-0085 for the layout', () => { expect(text).toContain('false = hidden: the child object is not shown on the parent record page'); expect(text).toContain('true = an auxiliary panel on the record page'); - expect(text).toContain('absent = \'primary\' (a body table) on a master_detail field, an auxiliary panel on a lookup field'); + // #35889: an absent key is an auxiliary panel on both relationship types; + // a master_detail one becomes a body table only when a parent field group names it. + expect(text).toContain('absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList)'); + expect(text).not.toContain('absent = \'primary\' (a body table) on a master_detail field'); expect(text).not.toContain('true/absent'); expect(text).toContain('shown as a full-width table in the record\'s detail body'); expect(text).toContain('The page layout is defined by ADR-0085'); 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 4a97a70c7ef..483aa566b26 100644 --- a/packages/spec/src/data/related-list-body-table.test.ts +++ b/packages/spec/src/data/related-list-body-table.test.ts @@ -15,6 +15,12 @@ * no `relatedList` is a body table whatever `inlineEdit` says (absent or * `false` used to be a side card). Every `lookup` cell, every explicit * `relatedList` cell and every inline-edited cell keeps its verdict. + * + * #35889 moved those cells again: a `master_detail` FK with no `relatedList` + * is a TAB by default, inline-edited or not, and a body table only when a + * parent field group places it. The set a group may place + * (`isGroupPlaceableRelationship`) is #35597's body-table set, unchanged, so + * the refusal still answers the same names. */ import { describe, it, expect } from 'vitest'; import { z } from 'zod'; @@ -22,38 +28,43 @@ import { ObjectFieldGroupSchema } from './object.zod'; import { fieldGroupBodyTableRefusal, isBodyTableRelationship, + isGroupPlaceableRelationship, type NamedInboundRelationship, } from './related-list-body-table'; describe('isBodyTableRelationship — the verdict table', () => { it.each([ - // type, relatedList, inlineEdit → body? - ['lookup', undefined, undefined, false], - ['lookup', true, undefined, false], - ['lookup', false, undefined, false], - ['lookup', 'primary', undefined, true], - ['lookup', undefined, 'grid', false], - ['master_detail', undefined, undefined, true], - ['master_detail', undefined, false, true], - ['master_detail', undefined, true, true], - ['master_detail', undefined, 'grid', true], - ['master_detail', undefined, 'form', true], - ['master_detail', 'primary', undefined, true], - ['master_detail', true, undefined, false], - ['master_detail', false, undefined, false], - ['master_detail', true, 'grid', false], - ['master_detail', false, 'grid', false], - ['text', 'primary', undefined, false], - ] as const)('%s · relatedList %s · inlineEdit %s → %s', (type, relatedList, inlineEdit, body) => { + // type, relatedList, inlineEdit → group may place? · body with no group? · body when a group places it? + ['lookup', undefined, undefined, false, false, false], + ['lookup', true, undefined, false, false, false], + ['lookup', false, undefined, false, false, false], + ['lookup', 'primary', undefined, true, true, true], + ['lookup', undefined, 'grid', false, false, false], + ['master_detail', undefined, undefined, true, false, true], + ['master_detail', undefined, false, true, false, true], + ['master_detail', undefined, true, true, false, true], + ['master_detail', undefined, 'grid', true, false, true], + ['master_detail', undefined, 'form', true, false, true], + ['master_detail', 'primary', undefined, true, true, true], + ['master_detail', true, undefined, false, false, false], + ['master_detail', false, undefined, false, false, false], + ['master_detail', true, 'grid', false, false, false], + ['master_detail', false, 'grid', false, false, false], + ['text', 'primary', undefined, false, false, false], + ] as const)('%s · relatedList %s · inlineEdit %s → placeable %s · body %s · body when placed %s', (type, relatedList, inlineEdit, placeable, body, placedBody) => { const field: Record = { type }; if (relatedList !== undefined) field.relatedList = relatedList; if (inlineEdit !== undefined) field.inlineEdit = inlineEdit; + expect(isGroupPlaceableRelationship(field)).toBe(placeable); expect(isBodyTableRelationship(field)).toBe(body); + expect(isBodyTableRelationship(field, { placedByGroup: false })).toBe(body); + expect(isBodyTableRelationship(field, { placedByGroup: true })).toBe(placedBody); }); it('answers false for a missing field', () => { expect(isBodyTableRelationship(undefined)).toBe(false); - expect(isBodyTableRelationship(null)).toBe(false); + expect(isBodyTableRelationship(null, { placedByGroup: true })).toBe(false); + expect(isGroupPlaceableRelationship(undefined)).toBe(false); }); }); @@ -61,10 +72,10 @@ describe('fieldGroupBodyTableRefusal — the sentence both surfaces write', () = const side: NamedInboundRelationship = { child: 'task', field: 'lead_id', def: { type: 'lookup' } }; const hidden: NamedInboundRelationship = { child: 'note', field: 'lead_id', def: { type: 'lookup', relatedList: false } }; const body: NamedInboundRelationship = { child: 'line', field: 'lead_id', def: { type: 'master_detail', inlineEdit: 'grid' } }; - // #35597: a plain master_detail (no inlineEdit, no relatedList) is a body table too. + // #35597 / #35889: a group may place a plain master_detail (no inlineEdit, no relatedList). const plainOwned: NamedInboundRelationship = { child: 'step', field: 'lead_id', def: { type: 'master_detail' } }; - it('is undefined when every named relationship is a body table, or none is named', () => { + it('is undefined when a group may place every named relationship, or none is named', () => { expect(fieldGroupBodyTableRefusal('lead', 0, 'line', [body])).toBeUndefined(); expect(fieldGroupBodyTableRefusal('lead', 0, 'step', [plainOwned])).toBeUndefined(); expect(fieldGroupBodyTableRefusal('lead', 0, 'nope', [])).toBeUndefined(); @@ -73,8 +84,8 @@ describe('fieldGroupBodyTableRefusal — the sentence both surfaces write', () = it('names the position, the entry, each FK that is not a body table, and the remedy', () => { expect(fieldGroupBodyTableRefusal('lead', 2, 'task', [side])).toBe( "Object 'lead' fieldGroups[2].relatedList 'task' names a related list that is not a body table: " + - "'task.lead_id' is a side card. A field group's relatedList only positions a body table (a FK declaring " + - "relatedList: 'primary', or a master_detail FK that declares no relatedList), so the " + + "'task.lead_id' is a side card. A field group's relatedList only places a body table (a FK declaring " + + "relatedList: 'primary', or a master_detail FK that declares no relatedList, which the group makes one), so the " + "record page draws nothing at the group for any other list. Set relatedList: 'primary' on that FK, or " + "remove the group's relatedList.", ); @@ -99,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)"); + 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('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 1be462b071f..23462ffcb89 100644 --- a/packages/spec/src/data/related-list-body-table.ts +++ b/packages/spec/src/data/related-list-body-table.ts @@ -1,42 +1,49 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#27478 · ruling B on #27055, as amended by #35597] The ONE predicate behind - * "is this inbound relationship a BODY TABLE of its parent's record page", and - * the one refusal a field group's `relatedList` earns when it names a - * relationship that is not. + * [#27478 · ruling B on #27055, as amended by #35597 and #35889] The ONE + * predicate behind "is this inbound relationship a BODY TABLE of its parent's + * record page", the one behind "may a field group place it", and the one + * refusal a field group's `relatedList` earns when it names a relationship it + * cannot place. * - * Body-ness is decided once, by the relationship's own keys on the child's FK - * field (`FieldSchema.relatedList`), and by the relationship's TYPE: + * A body table is decided by the relationship's own keys on the child's FK + * field (`FieldSchema.relatedList`) and by the parent's field groups: * * - `relatedList: 'primary'` — the author marks the list part of the - * record's main content; - * - a `master_detail` FK that declares NO `relatedList` — the parent owns - * these rows, so they are drawn in its body by default (#35597, the - * maintainer's 「就是master-detail表类型的子表」). `inlineEdit` no longer - * takes part: it is the WRITE side (the parent's form, ADR-0035 §3), and a - * master-detail child is a body table whether or not the form edits it; - * - anything else is a side card (`true`, or a `lookup` with no - * `relatedList`), or hidden (`false`). `relatedList: true` on a - * `master_detail` keeps it a side card, as the key's own description says. - * A `lookup` child never becomes a body table by default. + * record's main content, with or without a group; + * - a `master_detail` FK that declares NO `relatedList` is a TAB by default + * (#35889, the maintainer's 「主从子表我认为不应该自动申明放在概览中, + * 除非我通过 fieldGroup 强制指定」, superseding #35597's "body table by + * 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); + * - 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 + * `'primary'`. * - * A field group's `relatedList` (`ObjectFieldGroupSchema.relatedList`) only - * POSITIONS a body table among the field sections; it never promotes a side - * card. Giving body-ness a second source on the group would let the two - * disagree (the FK saying side card, the group saying body), so a group that - * names a relationship this predicate does not count is refused, with + * So a field group places either a `'primary'` list (positioning it) or a + * plain `master_detail` list (making it a body table there); every other + * relationship a group names is refused, with * {@link fieldGroupBodyTableRefusal}'s sentence, where the child's fields are * known: `defineStack` (`os validate`, `os build`) and the runtime object - * publish door (`@objectstack/lint` `validate-related-list-refs`). + * publish door (`@objectstack/lint` `validate-related-list-refs`). The set a + * group may name is the set #35597 accepted, unchanged. * * Readers, one judgement (no second copy anywhere): - * - the record page: objectui `deriveRelatedLists` (`isPrimary`) and - * `RecordDetailView` (`isBody`), which decide which lists the synthesized - * page draws as body tables (`bodyTablePlacement`) and which as side cards; - * - Studio: the field-group inspector offers only body tables - * (`RelatedTablePlacement`), and the relationship field inspector reads an - * absent `relatedList` through it; + * - the record page: objectui `deriveRelatedLists` (`isPrimary`, which hands + * {@link isBodyTableRelationship} whether a parent group names the list) + * and `RecordDetailView` (`isBody`), which decide which lists the + * synthesized page draws as body tables (`bodyTablePlacement`) and which as + * tabs; the parent's entry form, which inlines the lists a group places; + * - Studio: the field-group inspector offers only what a group may place + * ({@link isGroupPlaceableRelationship}), and the relationship field + * inspector reads an absent `relatedList` through it; * - the refusal at `defineStack` and at the publish door. * * Read on either the PARSED field or a stored body: `relatedList` carries no @@ -54,16 +61,64 @@ export interface RelatedListRelationshipFields { readonly inlineEdit?: unknown; } +/** What else decides a body table besides the FK's own keys. */ +export interface BodyTableContext { + /** + * True when one of the PARENT object's field groups names this relationship + * (`fieldGroups[].relatedList`, a child object name or `object.field`). + */ + readonly placedByGroup?: boolean; +} + /** - * Is the related list this FK field produces a BODY TABLE on its parent's - * record page? See the module header for the rule. A field that is not a - * `lookup` / `master_detail` produces no related list at all, so it is `false`. + * May a field group of the parent place the related list this FK produces? + * `'primary'` lists (the group positions them) and plain `master_detail` lists + * with no `relatedList` (the group makes them body tables, #35889). Every other + * relationship, and a field that is not a `lookup` / `master_detail`, is + * `false`. */ -export function isBodyTableRelationship(field: RelatedListRelationshipFields | null | undefined): boolean { +export function isGroupPlaceableRelationship(field: RelatedListRelationshipFields | null | undefined): boolean { if (!field || (field.type !== 'lookup' && field.type !== 'master_detail')) return false; if (field.relatedList === 'primary') return true; - if (field.relatedList !== undefined) return false; - return field.type === 'master_detail'; + return field.relatedList === undefined && field.type === 'master_detail'; +} + +/** + * Is the related list this FK field produces a BODY TABLE on its parent's + * record page? `'primary'` always is; a plain `master_detail` is only when a + * parent field group places it (`context.placedByGroup`, #35889); anything + * else never is. See the module header for the rule. A field that is not a + * `lookup` / `master_detail` produces no related list at all, so it is `false`. + */ +export function isBodyTableRelationship( + field: RelatedListRelationshipFields | null | undefined, + context?: BodyTableContext, +): boolean { + if (!isGroupPlaceableRelationship(field)) return false; + return field!.relatedList === 'primary' || context?.placedByGroup === true; +} + +/** + * Does one of a PARENT object's field groups name the related list `child.field` + * (`fieldGroups[].relatedList`: a bare child object name names every FK of that + * child, `object.field` names one)? The `placedByGroup` answer + * {@link isBodyTableRelationship} takes, for every reader that holds the parent + * (objectui's record page and entry form, `@objectstack/lint`). Tolerant of a + * stored or unparsed body: a group that is not a record, or whose `relatedList` + * is not a non-empty string, names nothing. + */ +export function fieldGroupsPlaceRelationship( + fieldGroups: unknown, + child: string, + field: string, +): boolean { + if (!Array.isArray(fieldGroups)) return false; + return fieldGroups.some((group) => { + const entry = group && typeof group === 'object' ? (group as { relatedList?: unknown }).relatedList : undefined; + if (typeof entry !== 'string' || entry.length === 0) return false; + const dot = entry.indexOf('.'); + return dot === -1 ? entry === child : entry.slice(0, dot) === child && entry.slice(dot + 1) === field; + }); } /** One inbound relationship a field group's `relatedList` names: the child, its FK, and the FK's keys. */ @@ -76,12 +131,12 @@ export interface NamedInboundRelationship { /** * The refusal for `fieldGroups[index].relatedList` (`entry`) on `objectName`, * given the inbound relationships the entry names (`named`, non-empty: an entry - * naming none is the unknown-name refusal's case). `undefined` when every one - * of them is a body table. `defineStack` and `@objectstack/lint` both write + * naming none is the unknown-name refusal's case). `undefined` when a group may + * place every one of them ({@link isGroupPlaceableRelationship}). `defineStack` and `@objectstack/lint` both write * this sentence, so the two surfaces cannot word it apart. * * A bare child name names every FK of that child, so it is refused when ANY of - * them is not a body table; when one of them is, the prescription points at + * them cannot be placed; when one of them can, the prescription points at * `object.field` for it. */ export function fieldGroupBodyTableRefusal( @@ -90,20 +145,20 @@ export function fieldGroupBodyTableRefusal( entry: string, named: readonly NamedInboundRelationship[], ): string | undefined { - const notBody = named.filter((r) => !isBodyTableRelationship(r.def)); + const notBody = named.filter((r) => !isGroupPlaceableRelationship(r.def)); if (named.length === 0 || notBody.length === 0) return undefined; const what = notBody .map((r) => `'${r.child}.${r.field}' is ${r.def.relatedList === false ? 'hidden (relatedList: false)' : 'a side card'}`) .join(', '); - const bodies = named.filter((r) => isBodyTableRelationship(r.def)); + const bodies = named.filter((r) => isGroupPlaceableRelationship(r.def)); const fk = notBody.length === 1 ? 'that FK' : 'those FKs'; const pick = bodies.length > 0 ? `, name only the body table as object.field (${bodies.map((r) => `'${r.child}.${r.field}'`).join(', ')})` : ''; return ( `Object '${objectName}' fieldGroups[${index}].relatedList '${entry}' names a related list that is not a body table: ` + - `${what}. A field group's relatedList only positions a body table (a FK declaring relatedList: 'primary', ` + - `or a master_detail FK that declares no relatedList), so the record page draws nothing ` + + `${what}. A field group's relatedList only places a body table (a FK declaring relatedList: 'primary', ` + + `or a master_detail FK that declares no relatedList, which the group makes one), so the record page draws nothing ` + `at the group for any other list. Set relatedList: 'primary' on ${fk}${pick}, or remove the group's relatedList.` ); } 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 new file mode 100644 index 00000000000..1e20bbcab5f --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts @@ -0,0 +1,77 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #35889 (epic #35590, superseding #35597's default) — a `master_detail` FK +// that declares no `relatedList` is a TAB of the parent's record page by +// default, like a `lookup`, not a body table in the overview. It is a body +// table only where a field group of the parent names it +// (`fieldGroups[].relatedList`): then the record page draws it at the group, +// the parent's entry form inlines it, and the record page's edit state saves +// its rows with the record (#35599). `relatedList: 'primary'` is unchanged. +// Maintainer ruling B on #35889 (「明细表应该改成指看分组的定义了」): the FK's +// `inlineEdit` no longer inlines a child in the parent's form by itself either; +// only the group does, and `inlineEdit` picks the form factor of a placed one. +// What a field group may name is unchanged (`isGroupPlaceableRelationship` +// accepts exactly what #35597 accepted), so no write that was accepted is +// refused. Semantic only, with no D2 conversion: whether an author wants the +// table back in the overview is theirs to say, by a group. The printed guidance +// below names no tracker id (the os migrate meta guidance pin); the previous +// default it names is #35597's, and the approval lock is #35599's ruling A. +export const entry: SemanticMigration = { + id: 'master-detail-related-list-tab-by-default', + surface: + 'objects[].fields. (data.FieldSchema.relatedList) left absent on a master_detail field, and ' + + 'objects[].fields..inlineEdit on a lookup or master_detail field, where the parent declares no ' + + 'fieldGroups[].relatedList naming that child (by its object name or object.field); and a lookup or ' + + 'master_detail FK declaring relatedList \'primary\' that such a parent field group DOES name, which ' + + 'the parent\'s create and edit forms now inline (inlineEdit or not; its record page is unchanged)', + replacement: + 'Nothing to replace for the new default: the child list is a tab of the parent\'s record page, with its ' + + 'count, as every other related list is. To keep it a table in the record\'s overview, at a chosen place ' + + 'among the field sections, add a field group to the PARENT object whose `relatedList` names it — ' + + '`{ key: \'lines\', label: \'Lines\', relatedList: \'\' }` (or `\'.\'` when the child ' + + 'points at the parent more than once) — in the `fieldGroups` order where the table should sit; such a ' + + 'group holds no fields. The table is then also inlined in the parent\'s create and edit forms, and the ' + + 'record page\'s Edit saves the record and its rows together. The same group is what keeps a child that ' + + 'sets `inlineEdit` inlined in the parent\'s form derived from its relationships: `inlineEdit` alone no ' + + 'longer does, and now only picks the form factor (`\'grid\'`, `\'form\'`, or `true` / absent for the ' + + 'shape-picked default) of a child a group places. A group may name only a list it can place, so for an ' + + '`inlineEdit` child that is not a plain master_detail the FK changes too: on a lookup FK, or a FK declaring ' + + '`relatedList: true`, write `relatedList: \'primary\'` and add the group (a master_detail FK may instead ' + + 'drop `relatedList: true`); a FK declaring `relatedList: false` hides the list, and a group naming it is ' + + 'refused (`related-list-group-not-body`). A form view that declares its own subforms still inlines what it ' + + 'declares. To keep a table in the overview with no group, write `relatedList: \'primary\'` on the ' + + 'child\'s FK instead (that does not inline it in the form).', + reason: + 'The maintainer ruled that a master-detail child should not be put into the overview by its relationship ' + + 'type alone: 「主从子表我认为不应该自动申明放在概览中,除非我通过 fieldGroup 强制指定」, while keeping ' + + 'what was built: 「大部分场景不需要,但是我们已经开发好的功能也没必要作废」. Before this change every ' + + 'master_detail FK with no relatedList was a body table. Now body-ness comes from `relatedList: \'primary\'` ' + + 'on the FK, or from a parent field group that places the list. Nothing is refused that was accepted: a ' + + 'field group may still name a plain master_detail child, and that is now what makes it a body table. ' + + 'There is no D2 conversion, since adding a group to every parent would put back the default the ' + + 'maintainer removed. A STORED object row is not rewritten and loads unchanged; its record page draws ' + + 'the child as a tab. The child\'s rows, their approval lock and the parent\'s summary ' + + 'fields are unchanged. In-repo census before the change: no example, platform object or HotCRM object ' + + 'declared a field group relatedList. Moving to a tab: the showcase task (project), field zoo ' + + '(f_master_detail), project membership (team, project), invoice line and expense line children, the CRM ' + + 'opportunity line item, and every plain master_detail child in HotCRM (for example sales order lines, ' + + 'project budget lines, and the contacts, contracts, quotes, orders, invoices and payments of an ' + + 'account). The inline-edited ones (showcase invoice and expense lines, CRM opportunity line item) get a ' + + 'field group on their parent in this change, so their forms and record pages keep the table; HotCRM\'s ' + + 'project budget lines need the same group in HotCRM. HotCRM\'s quote and opportunity line items declare ' + + 'relatedList \'primary\' and stay in the overview. Deployed metadata was NOT ' + + 'measured. ADR-0035 as amended, ADR-0085 / ADR-0087', + acceptanceCriteria: + 'On the record page of a parent with a master_detail child and no field group naming it, the overview ' + + '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 ' + + '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 ' + + 'a parent field group names such a child, the parent\'s create and edit forms inline it (inlineEdit or ' + + 'not); where none does, they do not, inlineEdit or not. `os validate` reports no new issue.', +}; diff --git a/packages/spec/src/stack-related-lists-order.test.ts b/packages/spec/src/stack-related-lists-order.test.ts index 4f19310dcfb..22ab1b74f23 100644 --- a/packages/spec/src/stack-related-lists-order.test.ts +++ b/packages/spec/src/stack-related-lists-order.test.ts @@ -188,11 +188,11 @@ describe('defineStack — a field group relatedList names body tables only', () fields: { lead_id: { ...line.fields.lead_id, ...keys } }, }); - it('accepts a group naming a body table: relatedList primary, or a master_detail with no relatedList (controls)', () => { + it('accepts a group naming what it may place: relatedList primary, or a master_detail with no relatedList (controls)', () => { expect(() => defineStack(withChild(taskFk({ relatedList: 'primary' }), 'rlo_task'))).not.toThrow(); expect(() => defineStack(withChild(line, 'rlo_line'))).not.toThrow(); expect(() => defineStack(withChild(lineFk({ inlineEdit: true }), 'rlo_line.lead_id'))).not.toThrow(); - // #35597: a plain master_detail (no inlineEdit) is a body table too. + // #35597 / #35889: a group may name a plain master_detail (no inlineEdit); the group makes it a body table. expect(() => defineStack(withChild(lineFk({ inlineEdit: undefined }), 'rlo_line'))).not.toThrow(); }); diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index 0d32524b0d8..5fcb37a76ae 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -4510,9 +4510,11 @@ const RELATED_LIST_AUDIT_FKS: ReadonlySet = new Set(['created_by', 'upda * spelled the way an entry may name it. * * [#27478] A field group's `relatedList` that DOES name inbound relationships - * must name body tables only (`isBodyTableRelationship`, ruling B on #27055): - * the group positions a body table and never promotes a side card, so one that - * names a side card or a hidden list would draw nothing at the group. Judged + * must name lists a group may place only (`isGroupPlaceableRelationship`, + * ruling B on #27055 as amended by #35889): the group positions a `'primary'` + * body table or makes a plain `master_detail` one, and never promotes a side + * card, so one that names a side card or a hidden list would draw nothing at + * the group. Judged * here for the same reason — the FK's keys live on the child — and on the same * children: a child left unjudged above is left unjudged here. The sentence is * `fieldGroupBodyTableRefusal`'s, which `@objectstack/lint` writes too. diff --git a/ui/packages/app-shell/src/providers/MetadataProvider.merge.test.ts b/ui/packages/app-shell/src/providers/MetadataProvider.merge.test.ts index 138164892b6..5eed73a617c 100644 --- a/ui/packages/app-shell/src/providers/MetadataProvider.merge.test.ts +++ b/ui/packages/app-shell/src/providers/MetadataProvider.merge.test.ts @@ -284,41 +284,68 @@ describe('mergeViewsIntoObjects — `.form` is the served default form only (obj import { attachInlineSubforms } from './MetadataProvider'; -describe('attachInlineSubforms — relationship-level inlineEdit', () => { +describe('attachInlineSubforms — a parent field group places the child (objectstack#35889)', () => { + // Maintainer ruling B on objectstack#35889 (「明细表应该改成指看分组的定义了」): + // the parent's form inlines a child exactly where one of the PARENT's field + // groups names it; the FK's `inlineEdit` only picks the form factor. const objects = [ - { name: 'invoice', fields: { number: { type: 'text' } } }, + { + name: 'invoice', + fields: { number: { type: 'text' } }, + fieldGroups: [{ key: 'main', label: 'Main' }, { key: 'lines', relatedList: 'invoice_line' }, { key: 'parts', relatedList: 'invoice_part.invoice' }], + }, { name: 'invoice_line', fields: { amount: { type: 'number' }, - invoice: { type: 'master_detail', reference: 'invoice', inlineEdit: true, inlineTitle: 'Lines' }, + invoice: { type: 'master_detail', reference: 'invoice', inlineEdit: 'grid', inlineTitle: 'Lines' }, }, }, + { + name: 'invoice_part', + // placed by a group, no inlineEdit → inlined, the form factor picked by shape + fields: { qty: { type: 'number' }, invoice: { type: 'master_detail', reference: 'invoice' } }, + }, + { + name: 'invoice_note', + // inlineEdit but NO group names it → must NOT be inlined + fields: { body: { type: 'text' }, invoice: { type: 'master_detail', reference: 'invoice', inlineEdit: true } }, + }, { name: 'comment', - // master_detail but NOT inlineEdit → must NOT be inlined + // master_detail, no group, no inlineEdit → must NOT be inlined fields: { body: { type: 'text' }, invoice: { type: 'master_detail', reference: 'invoice' } }, }, ]; - it('merges inlineEdit children into the parent form as subforms', () => { + it('merges the children a parent group names into the parent form as subforms, inlineEdit picking the form factor', () => { const out = attachInlineSubforms(objects); const invoice = out.find((o) => o.name === 'invoice')!; - expect(invoice.form?.subforms).toHaveLength(1); + expect(invoice.form?.subforms).toHaveLength(2); expect(invoice.form?.subforms?.[0]).toMatchObject({ childObject: 'invoice_line', relationshipField: 'invoice', title: 'Lines', + inlineMode: 'grid', }); - // The resolved inline-edit mode is attached too. - expect(['grid', 'form']).toContain(invoice.form?.subforms?.[0]?.inlineMode); + expect(invoice.form?.subforms?.[1]).toMatchObject({ childObject: 'invoice_part', relationshipField: 'invoice' }); + expect(['grid', 'form']).toContain(invoice.form?.subforms?.[1]?.inlineMode); }); - it('does not inline master_detail children without inlineEdit', () => { + it('does not inline a child no parent group names, inlineEdit or not', () => { const out = attachInlineSubforms(objects); const invoice = out.find((o) => o.name === 'invoice')!; const children = (invoice.form?.subforms ?? []).map((s: any) => s.childObject); expect(children).not.toContain('comment'); + expect(children).not.toContain('invoice_note'); + }); + + it('does not inline a child whose FK keeps it a tab (relatedList: true), even when a group names it', () => { + const out = attachInlineSubforms([ + { name: 'order', fields: { number: { type: 'text' } }, fieldGroups: [{ key: 'lines', relatedList: 'order_line' }] }, + { name: 'order_line', fields: { order: { type: 'master_detail', reference: 'order', relatedList: true } } }, + ]); + expect(out.find((o) => o.name === 'order')!.form).toBeUndefined(); }); it('lets an explicit form.subforms entry override the derived one', () => { @@ -335,7 +362,7 @@ describe('attachInlineSubforms — relationship-level inlineEdit', () => { expect(lineSubforms[0].columns).toBeTruthy(); }); - it('returns objects unchanged when no inlineEdit relationships exist', () => { + it('returns objects unchanged when no field group places a child', () => { const plain = [{ name: 'a', fields: { x: { type: 'text' } } }]; expect(attachInlineSubforms(plain)).toBe(plain); }); @@ -347,7 +374,7 @@ describe('attachInlineSubforms — relationship-level inlineEdit', () => { // `reference_to`-only def (the second child here) is one no served object // can be, and it resolves no parent. const out = attachInlineSubforms([ - { name: 'order', fields: { number: { type: 'text' } } }, + { name: 'order', fields: { number: { type: 'text' } }, fieldGroups: [{ key: 'lines', relatedList: 'order_line' }, { key: 'notes', relatedList: 'order_note' }] }, { name: 'order_line', fields: { diff --git a/ui/packages/app-shell/src/providers/MetadataProvider.tsx b/ui/packages/app-shell/src/providers/MetadataProvider.tsx index 74386095634..5e64e9b6840 100644 --- a/ui/packages/app-shell/src/providers/MetadataProvider.tsx +++ b/ui/packages/app-shell/src/providers/MetadataProvider.tsx @@ -19,6 +19,7 @@ import { import { isActionSwitchedOff, markSwitchedOffActions, markSwitchedOffActionsByObject, normalizeSchemaReferenceKeys } from '@object-ui/core'; import { errorCodeIs } from '@object-ui/types'; import { resolveInlineMode } from '@object-ui/plugin-form/core'; +import { fieldGroupsPlaceRelationship, isGroupPlaceableRelationship } from '@objectstack/spec/data'; import { MetadataCtx, answeredLoadFailure, @@ -705,19 +706,35 @@ export function mergeViewsIntoObjects(objects: any[], views: any[]): any[] { } /** - * Relationship-driven master-detail: a child object's `master_detail`/`lookup` - * field can carry `inlineEdit: true` to declare "edit me inline within my - * parent's form". This pass scans every object for such fields and merges the + * Relationship-driven master-detail: a parent object's field group can name a + * child list (`fieldGroups[].relatedList`) to declare "these rows are part of + * me". This pass scans every object for such children and merges the * resulting child collections into each parent object's form view as * `subforms` — so the parent's standard create/edit form renders an atomic * master-detail form with NO view config and NO bespoke page. The intent lives * in the data model (where it's defined once, e.g. by an AI modelling the * schema); forms just follow. An explicit `form.subforms` entry for the same * child overrides the model-derived one. + * + * objectstack#35889 (maintainer ruling B, 「明细表应该改成指看分组的定义了」) — + * a child is inlined in its parent's form ONLY when a field group of the + * PARENT names it (`fieldGroups[].relatedList`) and a group may place it + * (`@objectstack/spec`'s `isGroupPlaceableRelationship`: a plain + * `master_detail` FK, or a `relatedList: 'primary'` one). That is the same + * test that puts its table into the record page's body, so the record page, + * its forms and the record page's edit state carry the same tables. + * `inlineEdit` on the FK no longer pulls a child in by itself: it only picks + * the form factor (`'grid'` / `'form'`; anything else lets the child's shape + * decide). */ export function attachInlineSubforms(objects: any[]): any[] { if (!objects?.length) return objects; const inlineByParent: Record = {}; + // objectstack#35889 — each parent's field groups, by name. + const groupsByParent = new Map(); + for (const obj of objects) { + if (obj?.name && Array.isArray(obj.fieldGroups)) groupsByParent.set(obj.name, obj.fieldGroups); + } for (const child of objects) { const fields = child?.fields; if (!fields) continue; @@ -726,19 +743,22 @@ export function attachInlineSubforms(objects: any[]): any[] { : Object.entries(fields); for (const [fname, fdef] of entries) { const d: any = fdef; - if (!fname || !d?.inlineEdit) continue; + if (!fname || !d) continue; if (d.type !== 'master_detail' && d.type !== 'lookup') continue; // `reference` is the only target spelling read (objectui#11070 round 4); // a legacy def was folded onto it at ingestion (`ensureType` runs // `normalizeSchemaReferenceKeys` over every `object` item it stores). const parent = d.reference; if (!parent) continue; + const placedByGroup = isGroupPlaceableRelationship(d) + && fieldGroupsPlaceRelationship(groupsByParent.get(parent), child.name, fname); + if (!placedByGroup) continue; (inlineByParent[parent] ||= []).push({ childObject: child.name, relationshipField: fname, // Resolve the inline-edit form factor (grid vs per-row form) from the // declared value, falling back to the smart default by child shape. - inlineMode: resolveInlineMode(child, d.inlineEdit, { relationshipField: fname }), + inlineMode: resolveInlineMode(child, d.inlineEdit === 'grid' || d.inlineEdit === 'form' ? d.inlineEdit : undefined, { relationshipField: fname }), ...(d.inlineTitle ? { title: d.inlineTitle } : {}), ...(Array.isArray(d.inlineColumns) ? { columns: d.inlineColumns } : {}), ...(typeof d.inlineAmountField === 'string' ? { amountField: d.inlineAmountField } : {}), diff --git a/ui/packages/app-shell/src/providers/__tests__/MetadataProvider.composedObjectsIdentity-11699.test.tsx b/ui/packages/app-shell/src/providers/__tests__/MetadataProvider.composedObjectsIdentity-11699.test.tsx index c25d2b37476..1f3730b8e2c 100644 --- a/ui/packages/app-shell/src/providers/__tests__/MetadataProvider.composedObjectsIdentity-11699.test.tsx +++ b/ui/packages/app-shell/src/providers/__tests__/MetadataProvider.composedObjectsIdentity-11699.test.tsx @@ -45,8 +45,9 @@ * objectui#11699 and not changed here. * * The fixture makes both helpers wrap: `task` has a list view (merged into its - * `listViews`), and its `project` field declares `inlineEdit`, so `project` - * gets a derived form `subforms` entry. + * `listViews`), and `project`'s field group names `task` (objectstack#35889: + * the group, not the FK's `inlineEdit`, inlines a child), so `project` gets a + * derived form `subforms` entry. */ import { describe, it, expect, vi, afterEach } from 'vitest'; @@ -85,7 +86,7 @@ const OBJECTS = [ project: { type: 'master_detail', reference: 'project', inlineEdit: true }, }, }, - { name: 'project', label: 'Project', fields: { name: { type: 'text' } } }, + { name: 'project', label: 'Project', fields: { name: { type: 'text' } }, fieldGroups: [{ key: 'tasks', relatedList: 'task' }] }, ]; const VIEWS = [ { name: 'task.all', object: 'task', viewKind: 'list', label: 'All', isDefault: true, config: { type: 'grid', columns: ['title'] } }, diff --git a/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.relatedListsOrder-27069.test.ts b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.relatedListsOrder-27069.test.ts index bd61bb3c42d..5a004659562 100644 --- a/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.relatedListsOrder-27069.test.ts +++ b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.relatedListsOrder-27069.test.ts @@ -86,11 +86,11 @@ describe('relatedLists — the declared business order (objectstack#27069)', () fields: { lead_id: { type: 'lookup', reference: 'lead', relatedList: 'primary' } }, }; const out = deriveRelatedLists({ ...lead, relatedLists: ['task'] }, [lead, note, task, primaryCampaign]); - // `note` is an owned child with no relatedList: a body table by default - // since objectstack#35597, and still in its derived position. + // `note` is an owned child with no relatedList: a tab since + // objectstack#35889 (no group of the lead places it), in its derived position. expect(out.map((r) => [r.childObject, r.isPrimary])).toEqual([ ['task', false], - ['note', true], + ['note', false], ['campaign_member', true], ]); }); @@ -116,24 +116,36 @@ describe("relatedList: 'primary' as body placement (objectstack#27069)", () => { const primaryOf = (fk: Record) => deriveRelatedLists(quote, [quote, lineOf(fk)])[0].isPrimary; - it('a master_detail FK that sets inlineEdit is primary by default, on every inlineEdit arm', () => { - expect(primaryOf({ inlineEdit: true })).toBe(true); - expect(primaryOf({ inlineEdit: 'grid' })).toBe(true); - expect(primaryOf({ inlineEdit: 'form' })).toBe(true); + // objectstack#35889 — a master_detail FK with no relatedList is a tab by + // default, inlineEdit or not; a field group of the PARENT naming it makes it + // a body table. + const placedQuote = (entry: string) => ({ ...quote, fieldGroups: [{ key: 'main' }, { key: 'lines', relatedList: entry }] }); + const placedPrimaryOf = (fk: Record, entry = 'quote_line_item') => + deriveRelatedLists(placedQuote(entry), [placedQuote(entry), lineOf(fk)])[0].isPrimary; + + it('a master_detail FK with no relatedList is not primary by default, on every inlineEdit arm (objectstack#35889)', () => { + for (const inlineEdit of [undefined, false, true, 'grid', 'form']) { + expect(primaryOf(inlineEdit === undefined ? {} : { inlineEdit }), String(inlineEdit)).toBe(false); + } }); - it('an explicit relatedList: true keeps an inline-edited child a side card', () => { - expect(primaryOf({ inlineEdit: true, relatedList: true })).toBe(false); + it('a parent field group naming it makes it primary, by child name or object.field, on every inlineEdit arm', () => { + for (const inlineEdit of [undefined, false, true, 'grid', 'form']) { + const fk = inlineEdit === undefined ? {} : { inlineEdit }; + expect(placedPrimaryOf(fk), String(inlineEdit)).toBe(true); + expect(placedPrimaryOf(fk, 'quote_line_item.quote'), String(inlineEdit)).toBe(true); + expect(placedPrimaryOf(fk, 'quote_line_item.other'), String(inlineEdit)).toBe(false); + } }); - it('no inlineEdit, or inlineEdit: false, is primary by default too (objectstack#35597: the relation type decides)', () => { - expect(primaryOf({})).toBe(true); - expect(primaryOf({ inlineEdit: false })).toBe(true); + it('an explicit relatedList: true keeps it a tab even when a group names it', () => { + expect(primaryOf({ inlineEdit: true, relatedList: true })).toBe(false); + expect(placedPrimaryOf({ relatedList: true })).toBe(false); }); - it("relatedList: true keeps a plain master_detail a side card; 'primary' is unchanged (objectstack#35597)", () => { - expect(primaryOf({ relatedList: true })).toBe(false); + it("'primary' is primary with or without a group (objectstack#27069)", () => { expect(primaryOf({ relatedList: 'primary' })).toBe(true); + expect(placedPrimaryOf({ relatedList: 'primary' })).toBe(true); }); it('relatedList: false hides a plain master_detail: no list at all (objectstack#35597)', () => { diff --git a/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.test.ts b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.test.ts index 221b295fe4e..251b43fd4c8 100644 --- a/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.test.ts +++ b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.test.ts @@ -11,7 +11,7 @@ describe('deriveRelatedLists', () => { expect(deriveRelatedLists(project, null as any)).toEqual([]); }); - it('derives a related list from a master_detail child (owned) — a body table by default (objectstack#35597)', () => { + it('derives a related list from a master_detail child (owned) — a tab by default, placeable by a field group (objectstack#35889)', () => { const task = { name: 'task', label: 'Task', @@ -24,11 +24,38 @@ describe('deriveRelatedLists', () => { childLabel: 'Task', referenceField: 'project', isOwned: true, - isPrimary: true, + isPrimary: false, + isPlaceable: true, }, ]); }); + it('a parent field group naming the master_detail child makes it a body table (objectstack#35889)', () => { + const task = { + name: 'task', + label: 'Task', + fields: { project: { type: 'master_detail', reference: 'project' } }, + }; + const placing = { ...project, fieldGroups: [{ key: 'tasks', relatedList: 'task' }] }; + expect(deriveRelatedLists(placing, [placing, task])[0]).toMatchObject({ isPrimary: true, isPlaceable: true, keepsTab: true }); + const byField = { ...project, fieldGroups: [{ key: 'tasks', relatedList: 'task.project' }] }; + expect(deriveRelatedLists(byField, [byField, task])[0]).toMatchObject({ isPrimary: true, keepsTab: true }); + }); + + it("a 'primary' FK is a body table with or without a group, and keeps no tab (objectstack#35889 item 4)", () => { + const task = { + name: 'task', + label: 'Task', + fields: { project: { type: 'master_detail', reference: 'project', relatedList: 'primary' } }, + }; + const placing = { ...project, fieldGroups: [{ key: 'tasks', relatedList: 'task' }] }; + for (const parent of [project, placing]) { + const [list] = deriveRelatedLists(parent, [parent, task]); + expect(list).toMatchObject({ isPrimary: true, isPlaceable: true }); + expect(list.keepsTab).toBeUndefined(); + } + }); + it('derives a related list from a lookup child', () => { const note = { name: 'note', @@ -299,7 +326,14 @@ describe('deriveRelatedLists — a child the data API does not expose', () => { * body table (the derived list's `isPrimary`). */ describe('authoredBodyTableIds (objectstack#35597)', () => { - const quote = { name: 'quote', label: 'Quote', fields: { name: { type: 'text' } } }; + // objectstack#35889: a master-detail child is a body table only where a field + // group of the parent names it, so the quote's group places its lines. + const quote = { + name: 'quote', + label: 'Quote', + fields: { name: { type: 'text' } }, + fieldGroups: [{ key: 'lines', relatedList: 'quote_line' }], + }; const line = { name: 'quote_line', label: 'Line', fields: { quote: { type: 'master_detail', reference: 'quote' } } }; const note = { name: 'note', label: 'Note', fields: { quote: { type: 'lookup', reference: 'quote' } } }; const sideLine = { name: 'quote_term', label: 'Term', fields: { quote: { type: 'master_detail', reference: 'quote', relatedList: true } } }; diff --git a/ui/packages/app-shell/src/utils/deriveRelatedLists.ts b/ui/packages/app-shell/src/utils/deriveRelatedLists.ts index 70d13af4878..970860683d9 100644 --- a/ui/packages/app-shell/src/utils/deriveRelatedLists.ts +++ b/ui/packages/app-shell/src/utils/deriveRelatedLists.ts @@ -75,7 +75,7 @@ * server-side; this closes the UI/DX gap. */ -import { isBodyTableRelationship } from '@objectstack/spec/data'; +import { fieldGroupsPlaceRelationship, isBodyTableRelationship, isGroupPlaceableRelationship } from '@objectstack/spec/data'; import { convertSortToQueryParams } from '@object-ui/core'; import { relatedListEntryNames } from '@object-ui/plugin-detail'; @@ -121,16 +121,31 @@ export interface DerivedRelatedList { /** * True when the list is part of the record's MAIN CONTENT — a body table: the * FK declares `relatedList: 'primary'`, or it is a `master_detail` FK that - * declares no `relatedList` at all (objectstack#27069, objectstack#35597 — - * the rows the parent owns are drawn under it, not beside it, whether or - * not its form edits them inline). The verdict is `@objectstack/spec`'s `isBodyTableRelationship` - * (objectstack#27478), the one predicate the spec's refusal of a field group - * naming a side card reads too. + * declares no `relatedList` AND one of the parent's field groups names it + * (`fieldGroups[].relatedList`, objectstack#35889: a master-detail child is a + * tab by default, superseding objectstack#35597's "body table by default"). + * The verdict is `@objectstack/spec`'s `isBodyTableRelationship` + * (objectstack#27478), handed whether a parent group places the list. * A placement, not an order: the body draws primary lists as full-width - * tables, the tabbed page gives each its OWN tab, and non-primary lists are - * the side cards (a single "Related" tab on the tabbed page). + * tables, and every other list is a tab of its own. */ isPrimary: boolean; + /** + * True when a field group of the parent MAY place this list + * (`@objectstack/spec`'s `isGroupPlaceableRelationship`): a `'primary'` FK, + * or a `master_detail` FK that declares no `relatedList` (objectstack#35889). + * What Studio's field-group inspector offers; the spec refuses a group naming + * any other list. + */ + isPlaceable: boolean; + /** + * Present (true) on a body table that a parent field group MAKES one: a + * `master_detail` FK declaring no `relatedList` that a group names. Such a + * table keeps its tab on the record page too (objectstack#35889 item 4). A + * `'primary'` table is a body table without a group and keeps no tab, as + * before, whether or not a group positions it. + */ + keepsTab?: true; /** * Default row order, INHERITED from the child object's default list view * `sort` (objectui#5795; ruled on objectstack#11345, maintainer 2026-08-23: @@ -189,6 +204,11 @@ interface MergedObjectLike { * a child object name or `object.field`; see {@link resolveRelatedListOrder}. */ relatedLists?: string[]; + /** + * The spec's optional `fieldGroups`, read when this object is the parent: a + * group's `relatedList` names the related list it places (objectstack#35889). + */ + fieldGroups?: Array<{ relatedList?: unknown } | null | undefined>; /** The spec's optional `pluralLabel`, read by a caller's `listLabel` only. */ pluralLabel?: string; fields?: Record | any[]; @@ -393,12 +413,21 @@ export function deriveRelatedLists( const hidden = fieldDef.relatedList === false || apiDisabled; if (hidden && !options?.includeHidden) continue; + const isBody = isBodyTableRelationship(fieldDef, { + placedByGroup: fieldGroupsPlaceRelationship(objectDef.fieldGroups, child.name, fieldName), + }); const entry: Working = { childObject: child.name, childLabel, referenceField: fieldName, isOwned: type === 'master_detail', - isPrimary: isBodyTableRelationship(fieldDef), + // objectstack#35889 — a plain master-detail child is a body table + // only where one of the parent's field groups names it. + isPrimary: isBody, + isPlaceable: isGroupPlaceableRelationship(fieldDef), + // Item 4: a table the group MAKES a body table keeps its tab; a + // `'primary'` one keeps none, as before. + ...(isBody && fieldDef.relatedList !== 'primary' ? { keepsTab: true as const } : {}), ...(inheritedSort ? { sort: inheritedSort } : {}), ...(hidden ? { isHidden: true as const } : {}), _fkLabel: (typeof fieldDef.label === 'string' && fieldDef.label) || fieldName, @@ -446,9 +475,11 @@ export function deriveRelatedLists( * page draws (objectstack#35597): every `record:related_list` placed anywhere * in the page's tree whose relationship the record page counts as a body table * (`isPrimary` on its derived list — `@objectstack/spec`'s - * `isBodyTableRelationship`, the one predicate). A master-detail list an author - * places gets the body-table treatment the synthesized page gives it: drawn - * when empty, a server totals row, the row cap and 「显示全部」. + * `isBodyTableRelationship`, the one predicate: a `'primary'` list, or a + * master-detail list a field group of the parent places, objectstack#35889). + * Such a list an author places gets the body-table treatment the synthesized + * page gives it: drawn when empty, a server totals row, the row cap and + * 「显示全部」. * * The synthesized page reads its body tables off its Details tab instead * (`bodyTableIdsOf` in `@object-ui/plugin-detail`): there the placement IS diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index 30c5e306c32..5da24155770 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -1957,12 +1957,11 @@ describe('RecordDetailView.relatedListsOrder-27241', () => { * record page draws as BODY TABLES is `@objectstack/spec`'s * `isBodyTableRelationship`, the predicate the spec's refusal of a field group * naming a side card reads too: `relatedList: 'primary'`, or a `master_detail` - * FK that sets `inlineEdit` and declares no `relatedList`. + * FK declaring no `relatedList` that a field group of the parent names + * (objectstack#35889: unnamed, it is a tab; `inlineEdit` plays no part). * - * Behaviour change pinned here: an inline-edited `master_detail` FK that - * declares `relatedList: true` is a SIDE CARD, as the key's description says - * ("write true to keep it a side card"). The page used to draw it as a body - * table, because its own copy of the rule ignored `relatedList`. + * objectstack#35889 item 4: a body table a group places keeps its tab, with + * its count. `relatedList: true` keeps a list a tab even when a group names it. * * Measured from a real `RecordDetailView` mount at 1440 px, details beside * the right column (the `relatedListsOrder-27241` harness). @@ -1975,7 +1974,7 @@ describe('RecordDetailView.bodyTablePredicate-27478', () => { const RECORD_ID = 'q-1'; const BASE_FIELDS = { id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' } }; - const objectsWith = (taskFk: Record) => [ + const objectsWith = (taskFk: Record, { placeTask = false }: { placeTask?: boolean } = {}) => [ { name: PARENT, label: 'Quote', @@ -1985,6 +1984,7 @@ describe('RecordDetailView.bodyTablePredicate-27478', () => { fieldGroups: [ { key: 'basic', label: 'Basic' }, { key: 'lines', label: 'Lines', relatedList: 'showcase_line' }, + ...(placeTask ? [{ key: 'tasks', label: 'Tasks', relatedList: 'showcase_task' }] : []), ], }, { @@ -2075,46 +2075,67 @@ describe('RecordDetailView.bodyTablePredicate-27478', () => { const detailsText = (container: HTMLElement) => container.querySelector('[data-record-column="details"]')?.textContent ?? ''; - describe('RecordDetailView — body tables are the spec predicate\'s verdict (objectstack#27478)', () => { - it('an inline-edited master_detail with no relatedList is a body table; one with relatedList: true is a side card', async () => { - const { container } = renderPage(objectsWith({ relatedList: true })); - await waitFor(() => expect(cardOrder(container)).toHaveLength(2), { timeout: 5000 }); - expect(cardOrder(container)).toEqual(['showcase_task.quote', 'showcase_note.quote']); + describe('RecordDetailView — body tables are the spec predicate\'s verdict (objectstack#27478, objectstack#35889)', () => { + it('a group-placed master_detail is a body table that keeps its tab; one with relatedList: true is a tab only, even named by a group', async () => { + const { container } = renderPage(objectsWith({ relatedList: true }, { placeTask: true })); + await waitFor(() => expect(cardOrder(container)).toHaveLength(3), { timeout: 5000 }); + expect(cardOrder(container)).toEqual(['showcase_line.quote', 'showcase_task.quote', 'showcase_note.quote']); expect(detailsText(container)).toContain('Lines'); expect(detailsText(container)).not.toContain('Tasks'); }); - it('control: the same FK with no relatedList is a body table, not a card', async () => { - const { container } = renderPage(objectsWith({})); - await waitFor(() => expect(cardOrder(container)).toHaveLength(1), { timeout: 5000 }); - expect(cardOrder(container)).toEqual(['showcase_note.quote']); + it('control: the same FK with no relatedList, named by a group, is a body table and keeps its tab', async () => { + const { container } = renderPage(objectsWith({}, { placeTask: true })); + await waitFor(() => expect(cardOrder(container)).toHaveLength(3), { timeout: 5000 }); + expect(cardOrder(container)).toEqual(['showcase_line.quote', 'showcase_task.quote', 'showcase_note.quote']); await waitFor(() => expect(detailsText(container)).toContain('Tasks'), { timeout: 5000 }); expect(detailsText(container)).toContain('Lines'); }); }); - describe('RecordDetailView — the relation type decides, not inlineEdit (objectstack#35597)', () => { - it('a master_detail with NO inlineEdit and no relatedList is a body table: drawn in the details, no card', async () => { - const { container } = renderPage(objectsWith({ inlineEdit: undefined })); - await waitFor(() => expect(cardOrder(container)).toHaveLength(1), { timeout: 5000 }); - expect(cardOrder(container)).toEqual(['showcase_note.quote']); - // Drawn even with no rows (the data source answers every list empty). + describe('RecordDetailView — the parent field group decides, not the relation type or inlineEdit (objectstack#35889)', () => { + it('a master_detail no group names is a tab with its count, not a body table — inlineEdit or not', async () => { + for (const taskFk of [{ inlineEdit: undefined }, {}]) { + cleanup(); + RelatedCountStore._reset(); + const { container } = renderPage(objectsWith(taskFk)); + await waitFor(() => expect(cardOrder(container)).toHaveLength(3), { timeout: 5000 }); + expect(cardOrder(container)).toEqual(['showcase_line.quote', 'showcase_task.quote', 'showcase_note.quote']); + await waitFor(() => expect(detailsText(container)).toContain('Lines'), { timeout: 5000 }); + expect(detailsText(container)).not.toContain('Tasks'); + } + }); + + it('CONTROL — the same FK with NO inlineEdit, named by a group, is drawn in the details even with no rows', async () => { + const { container } = renderPage(objectsWith({ inlineEdit: undefined }, { placeTask: true })); + await waitFor(() => expect(cardOrder(container)).toHaveLength(3), { timeout: 5000 }); await waitFor(() => expect(detailsText(container)).toContain('Tasks'), { timeout: 5000 }); - expect(container.querySelector('[data-record-column="details"] [data-body-table-empty]')).not.toBeNull(); + expect(container.querySelectorAll('[data-record-column="details"] [data-body-table-empty]').length).toBe(2); }); - it('relatedList: false hides it: neither a body table nor a card', async () => { - const { container } = renderPage(objectsWith({ inlineEdit: undefined, relatedList: false })); - await waitFor(() => expect(cardOrder(container)).toHaveLength(1), { timeout: 5000 }); - expect(cardOrder(container)).toEqual(['showcase_note.quote']); + it('relatedList: false hides it: neither a body table nor a tab, even named by a group', async () => { + const { container } = renderPage(objectsWith({ inlineEdit: undefined, relatedList: false }, { placeTask: true })); + await waitFor(() => expect(cardOrder(container)).toHaveLength(2), { timeout: 5000 }); + expect(cardOrder(container)).toEqual(['showcase_line.quote', 'showcase_note.quote']); await waitFor(() => expect(detailsText(container)).toContain('Lines'), { timeout: 5000 }); expect(detailsText(container)).not.toContain('Tasks'); }); - it('relatedList: true keeps it a side card', async () => { + it("CONTROL — relatedList: 'primary' is a body table with no tab, as before, whether or not a group positions it", async () => { + for (const placeTask of [false, true]) { + cleanup(); + RelatedCountStore._reset(); + const { container } = renderPage(objectsWith({ inlineEdit: undefined, relatedList: 'primary' }, { placeTask })); + await waitFor(() => expect(cardOrder(container)).toHaveLength(2), { timeout: 5000 }); + expect(cardOrder(container)).toEqual(['showcase_line.quote', 'showcase_note.quote']); + await waitFor(() => expect(detailsText(container)).toContain('Tasks'), { timeout: 5000 }); + } + }); + + it('relatedList: true keeps it a tab', async () => { const { container } = renderPage(objectsWith({ inlineEdit: undefined, relatedList: true })); - await waitFor(() => expect(cardOrder(container)).toHaveLength(2), { timeout: 5000 }); - expect(cardOrder(container)).toEqual(['showcase_task.quote', 'showcase_note.quote']); + await waitFor(() => expect(cardOrder(container)).toHaveLength(3), { timeout: 5000 }); + expect(cardOrder(container)).toEqual(['showcase_line.quote', 'showcase_task.quote', 'showcase_note.quote']); expect(detailsText(container)).not.toContain('Tasks'); }); }); @@ -2878,7 +2899,18 @@ describe('RecordDetailView.recordEditState-35599', () => { name: PARENT, label: 'Quote', pluralLabel: 'Quotes', - fields: { id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' }, summary: { type: 'text', label: 'Summary' } }, + fields: { + id: { type: 'text', label: 'Id', group: 'basic' }, + name: { type: 'text', label: 'Name', group: 'basic' }, + summary: { type: 'text', label: 'Summary', group: 'basic' }, + }, + // objectstack#35889: a master-detail child is a body table only where a + // field group of the parent names it. + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'lines', label: 'Lines', relatedList: 'showcase_line' }, + { key: 'tasks', label: 'Tasks', relatedList: 'showcase_task' }, + ], }, { name: 'showcase_line', diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 1ca911ec66b..e9d444c97d6 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -4251,7 +4251,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri sections?: Array>; highlightFields?: string[]; headerActions?: ActionDef[]; - related?: Array<{ title?: string; objectName: string; relationshipField: string; columns?: any[]; icon?: string; isPrimary?: boolean; isBody?: boolean }>; + related?: Array<{ title?: string; objectName: string; relationshipField: string; columns?: any[]; icon?: string; isPrimary?: boolean; isBody?: boolean; keepsTab?: boolean }>; approvals?: { count?: number; node?: Record }; }; } @@ -4339,12 +4339,12 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri ...childRelations.filter((relation) => relation.isPrimary), ...childRelations.filter((relation) => !relation.isPrimary), ]; - const related = orderedRelations.map(({ childObject, childLabel, referenceField, title: titleOverride, columns: columnsOverride, isPrimary, sort: inheritedSort, filter: declaredFilter }) => { + const related = orderedRelations.map(({ childObject, childLabel, referenceField, title: titleOverride, columns: columnsOverride, isPrimary, keepsTab, sort: inheritedSort, filter: declaredFilter }) => { const childObjectDef = objects.find((o: any) => o.name === childObject); // objectstack#27055, Target 8 — the record's own BODY: a list the author - // marks `relatedList: 'primary'`, or a `master_detail` FK declaring - // `inlineEdit` (the child is edited as part of the parent) and no - // `relatedList` — `relatedList: true` keeps it a side card. That is + // marks `relatedList: 'primary'`, or a `master_detail` FK declaring no + // `relatedList` that one of this object's field groups places + // (objectstack#35889; unplaced, it is a tab). That is // `isPrimary`: `deriveRelatedLists` sets it from `@objectstack/spec`'s // `isBodyTableRelationship` (objectstack#27478), the one predicate the // spec's refusal of a field group naming a side card reads too, so no @@ -4393,6 +4393,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // verdict above: a body list is a table in the Details tab. ...(isPrimary ? { isPrimary: true } : {}), ...(isBody ? { isBody: true } : {}), + // objectstack#35889 item 4 — a body table a field group makes one + // keeps its tab as well; a `'primary'` one does not. + ...(keepsTab ? { keepsTab: true } : {}), }; }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.relatedList-27054.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.relatedList-27054.test.tsx index ffb42239030..f14abb2604e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.relatedList-27054.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.relatedList-27054.test.tsx @@ -159,35 +159,28 @@ describe('ObjectFieldInspector — the related list on the parent (relatedList / expect(ObjectSchema.safeParse(drafts.at(-1)!).success).toBe(true); }); - it('a plain master_detail with no relatedList reads as primary, and 「显示」 writes an explicit true (objectstack#35597)', () => { - // The record page's default since objectstack#35597: a `master_detail` FK - // that declares no `relatedList` is a body table, `inlineEdit` or not. + it.each([ + ['a plain master_detail', {}], + ['an inline-edited master_detail', { inlineEdit: true }], + ])('%s with no relatedList reads as shown, and 「主要」 writes primary, 「显示」 clears it (objectstack#35889)', (_name, keys) => { + // The record page's default since objectstack#35889: a `master_detail` FK + // that declares no `relatedList` is a tab, `inlineEdit` or not; only a + // field group of the parent (or `'primary'`) makes it a body table. const drafts: Row[] = []; - render(); - expect(radio('primary').getAttribute('aria-checked')).toBe('true'); - fireEvent.click(radio('shown')); - expect(leadFkOf(drafts.at(-1)!).relatedList).toBe(true); - expect(deriveRelatedLists(LEAD as any, [drafts.at(-1)! as any])[0].isPrimary).toBe(false); - expect(ObjectSchema.safeParse(drafts.at(-1)!).success).toBe(true); - }); - - it('an inline-edited master_detail with no relatedList reads as primary, and 「显示」 writes an explicit true (objectstack#27069)', () => { - // The record page's default: a `master_detail` FK that sets `inlineEdit` - // and declares no `relatedList` is primary. The control reads that default - // rather than "absent = shown", so "Show" must write `true` to mean it. - const drafts: Row[] = []; - render(); - expect(radio('primary').getAttribute('aria-checked')).toBe('true'); + render(); + expect(radio('shown').getAttribute('aria-checked')).toBe('true'); + expect(deriveRelatedLists(LEAD as any, [taskWith({ type: 'master_detail', label: 'Lead', reference: 'lead', ...keys }) as any])[0].isPrimary).toBe(false); - fireEvent.click(radio('shown')); - expect(leadFkOf(drafts.at(-1)!).relatedList).toBe(true); - expect(deriveRelatedLists(LEAD as any, [drafts.at(-1)! as any])[0].isPrimary).toBe(false); + fireEvent.click(radio('primary')); + expect(leadFkOf(drafts.at(-1)!).relatedList).toBe('primary'); + expect(deriveRelatedLists(LEAD as any, [drafts.at(-1)! as any])[0].isPrimary).toBe(true); expect(ObjectSchema.safeParse(drafts.at(-1)!).success).toBe(true); - // Picking the default again clears the key rather than writing `'primary'`. - fireEvent.click(radio('primary')); + // Picking the default again clears the key rather than writing `true`, so + // a parent field group can still place the list. + fireEvent.click(radio('shown')); expect('relatedList' in leadFkOf(drafts.at(-1)!)).toBe(false); - expect(deriveRelatedLists(LEAD as any, [drafts.at(-1)! as any])[0].isPrimary).toBe(true); + expect(deriveRelatedLists(LEAD as any, [drafts.at(-1)! as any])[0].isPlaceable).toBe(true); }); it('reads a stored `true` as shown, and re-picking the current state writes nothing', () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx index a470a52a04f..2c290403557 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx @@ -53,7 +53,6 @@ import { COMPUTED_VALUE_TYPES, FieldSchema, isAggregateCompatibleWithFieldType, - isBodyTableRelationship, MULTI_OPTION_TYPES, NUMERIC_VALUE_TYPES, SelectOptionSchema, @@ -3056,21 +3055,15 @@ function DeleteBehaviorField({ type RelatedListMode = 'shown' | 'hidden' | 'primary'; /** - * The stored `relatedList` as one of the control's three states. `true` reads - * as `shown`. ABSENT reads as the relationship's default, which the record - * page's own predicate decides (`@objectstack/spec`'s `isBodyTableRelationship`, - * objectstack#27069 / objectstack#27478): a - * `master_detail` FK that sets `inlineEdit` is primary by default, every other - * FK is shown. Without `field` an absent value reads as `shown`. + * The stored `relatedList` as one of the control's three states. `true` and + * ABSENT read as `shown`: since objectstack#35889 every FK with no + * `relatedList` is a tab by default, a `master_detail` one included (a field + * group of the parent may still make that one a body table; the field + * inspector does not see the parent's groups). */ -export function readRelatedListMode( - value: unknown, - field?: { type?: unknown; inlineEdit?: unknown }, -): RelatedListMode { +export function readRelatedListMode(value: unknown): RelatedListMode { if (value === false) return 'hidden'; if (value === 'primary') return 'primary'; - if (value === undefined && field && typeof field.type === 'string' - && isBodyTableRelationship({ type: field.type, inlineEdit: field.inlineEdit })) return 'primary'; return 'shown'; } @@ -3086,8 +3079,8 @@ const RELATED_LIST_MODES: ReadonlyArray<{ mode: RelatedListMode; labelKey: strin * * - The three-state `relatedList` control: shown, hidden (`false`), and * primary (`'primary'`), a core relationship. The relationship's default - * state leaves the key ABSENT: shown, or primary on a `master_detail` FK - * that sets `inlineEdit` (objectstack#27069); the other states write it. The primary state's wording, + * state leaves the key ABSENT: shown (objectstack#35889, every FK type); + * the other states write it. The primary state's wording, * "Primary (in body)", follows the record-page v3 ruling that a primary * related list is drawn in the record body as a full-width table (the * rendering half is the record-page card objectstack#27069). @@ -3112,11 +3105,11 @@ function RelatedListFields({ locale?: string; }) { const tr = (key: string) => t(key, locale); - const mode = readRelatedListMode(def.relatedList, def); + const mode = readRelatedListMode(def.relatedList); // The state an absent key already means here. Picking it clears the key; - // picking another writes it, so "Show" on an inline-edited `master_detail` - // (primary by default) is an explicit `true`. - const defaultMode = readRelatedListMode(undefined, def); + // picking another writes it. "Show" leaves a `master_detail` FK's key absent, + // so a field group of the parent can still place it (objectstack#35889). + const defaultMode = readRelatedListMode(undefined); const reference = typeof def.reference === 'string' && def.reference ? (def.reference as string) : ''; const setMode = (next: RelatedListMode) => { if (next === mode) return; diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectGroupInspector.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectGroupInspector.tsx index cd50a51b38b..a91d2fcf899 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectGroupInspector.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectGroupInspector.tsx @@ -153,12 +153,13 @@ export function ObjectGroupInspector({ * draws that table at the group's position in the details column. * * What the picker can write is held to what the spec accepts: - * - only inbound relationships that are BODY TABLES are offered - * (objectstack#27478): a group positions a body table and never promotes a - * side card, so a relationship whose FK keeps it a side card, or hides it, - * is not offered. Body-ness is the record page's own verdict (`isPrimary`, - * `@objectstack/spec`'s `isBodyTableRelationship`), the predicate the spec's - * refusal reads too. A pick is checked against them before it is written (a + * - only inbound relationships a group may place are offered + * (objectstack#27478, objectstack#35889): a `'primary'` list (the group + * positions it) or a plain master-detail list (the group makes it a body + * table); a group never promotes a side card, so a relationship whose FK + * keeps it a side card, or hides it, is not offered. The verdict is + * `isPlaceable` (`@objectstack/spec`'s `isGroupPlaceableRelationship`), the + * predicate the spec's refusal reads too. A pick is checked against them before it is written (a * name matching none, or naming a list that is not a body table, is refused * at `defineStack` and by the publish door's lint); * - a stored value naming a list that is not a body table stays visible, with @@ -200,10 +201,10 @@ function RelatedTablePlacement({ // names all of that child's FKs); the spec refuses the entry otherwise. const namesBodyTablesOnly = (entry: string) => { const named = relationshipsNamedBy(entry, relationships); - return named.length > 0 && named.every((r) => r.isPrimary); + return named.length > 0 && named.every((r) => r.isPlaceable); }; const options = relationships - .filter((r) => r.isPrimary) + .filter((r) => r.isPlaceable) .filter((r) => !placedElsewhere.has(r) || relationshipsNamedBy(current, relationships).includes(r)) .map((r) => { const entry = relationshipEntry(r, relationships); diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts index 0e03f88bb02..80e71715dc9 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts @@ -21,7 +21,8 @@ * list is a tab of its own (objectstack#35595, which retired the one `Related` * tab). A field group whose `relatedList` names a body table's * relationship places that table at the group's position instead - * (objectstack#27069, objectstack#27241). + * (objectstack#27069, objectstack#27241), and the table keeps its tab too + * (objectstack#35889 item 4). */ import { describe, expect, it } from 'vitest'; @@ -173,6 +174,28 @@ describe('a field group places a body table at its position (objectstack#27069, expect(tabOf(tabs, 'related:task.quote').children.map((n: any) => n.properties.objectName)).toEqual(['task']); }); + it('a table a group MAKES a body table keeps its tab, with its count (objectstack#35889 item 4)', () => { + const tabs = buildDefaultTabs(placed('quote_line_item'), { related: [{ ...LINES, keepsTab: true }, SCHEDULE, TASKS] }); + expect(items(tabs).map((i: any) => i.value)).toEqual([ + 'details', + 'related:quote_line_item.quote', + 'related:task.quote', + 'timeline', + ]); + expect(tabOf(tabs, 'related:quote_line_item.quote').children.map((n: any) => n.properties.objectName)).toEqual(['quote_line_item']); + // The Overview still draws it at the group, and the page still counts it a body table. + expect(shape(items(tabs)[0].children)).toContain('table(quote_line_item)'); + const page = buildDefaultPageSchema(placed('quote_line_item'), { related: [{ ...LINES, keepsTab: true }, TASKS] }); + expect([...bodyTableIdsOf(page)]).toEqual(['quote_line_item.quote']); + }); + + it("CONTROL — a `'primary'` body table a group only positions keeps no tab, as before (objectstack#35889)", () => { + const primaryLines = { ...LINES, isBody: undefined, isPrimary: true }; + const tabs = buildDefaultTabs(placed('quote_line_item'), { related: [primaryLines, TASKS] }); + expect(items(tabs).map((i: any) => i.value)).toEqual(['details', 'related:task.quote', 'timeline']); + expect(shape(items(tabs)[0].children)).toEqual(['details(basic,terms)', 'table(quote_line_item)', 'details(notes)']); + }); + it('the host-passed sections place the same way (the `{ group }` sections RecordDetailView passes)', () => { const def = placed('quote_line_item'); // The `{ group }` reference form, as the host writes it (the options type diff --git a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts index c08c513d752..459b4bfa6aa 100644 --- a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts +++ b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts @@ -243,14 +243,22 @@ export interface BuildPageOptions { /** * The list is the record's own body (objectstack#27055, Target 8): * `relatedList: 'primary'`, or a `master_detail` FK declaring no - * `relatedList` (objectstack#35597; `inlineEdit` no longer required). Drawn - * as a full-width table section in the Details tab, before the field - * sections, instead of in the Related tab / related column. Absent: `isPrimary` decides. The host computes it from - * the FK with `@objectstack/spec`'s `isBodyTableRelationship` + * `relatedList` that a field group of the parent places (objectstack#35889; + * unplaced, it is a tab). Drawn as a full-width table section in the + * Details tab instead of a tab of its own. Absent: `isPrimary` decides. The + * host computes it from the FK and the parent's field groups with + * `@objectstack/spec`'s `isBodyTableRelationship` * (objectstack#27478) — the one predicate, which the spec's refusal of a * field group naming a side card reads too (no spec key of its own). */ isBody?: boolean; + /** + * objectstack#35889 item 4 — a body table that keeps its tab as well: a + * plain `master_detail` list a field group of this object makes a body + * table (the host sets it). Absent: a body table takes no tab, as a + * `relatedList: 'primary'` one never did. + */ + keepsTab?: boolean; }>; // objectstack#27055 (Target 3): `showActivity` and `history` are gone too. // The timeline is ONE stream — discussion, activity (`sys_activity`) and @@ -828,11 +836,15 @@ export const BODY_TABLE_PAGE_SIZE = 10; * no fields (the spec refuses one that does), so it is a position, never a * section of its own. A group only POSITIONS a body table: only the * lists in `bodies` are placed, and a side card is never among them (objectstack#27478: - * the spec refuses a group naming a side card or a hidden list, by the same - * `isBodyTableRelationship` the host computes `isBody` with); - * - every other body table goes AFTER the field sections the record page + * the spec refuses a group naming a side card or a hidden list; a plain + * master-detail list a group names is a body table because the group names + * it, objectstack#35889, by the same `isBodyTableRelationship` the host + * computes `isBody` with); + * - every other body table (a `relatedList: 'primary'` list no group places; + * since objectstack#35889 a master-detail list is a body table only where a + * group places it) goes AFTER the field sections the record page * draws open (objectstack#35742: the record's own fields first, then its - * master-detail tables — 「主记录的字段分组 → 主从子表」; the header strip's + * body tables — 「主记录的字段分组 → 主从子表」; the header strip's * stage bar and key fields sit above both, objectstack#35597's * 「关键字段下面」), stacked in the order given — the parent's * `relatedLists`, then the derived order. The sections drawn CLOSED that @@ -1017,7 +1029,12 @@ function synthTabs( const related = Array.isArray(options.related) ? options.related : []; const isBody = (rel: (typeof related)[number]) => rel.isBody ?? rel.isPrimary === true; const bodies = related.filter(isBody).map((rel) => relatedNode(rel, BODY_TABLE_PAGE_SIZE)); - const sides = related.filter((rel) => !isBody(rel)); + // objectstack#35889 (item 4) — a body table a field group of this object + // MAKES one (`keepsTab`, set by the host for a plain master_detail list a + // group names) keeps its tab too, with its count: the group adds it to the + // overview, it does not take it off the tab row. A `relatedList: 'primary'` + // body table stays body-only, as before, whether or not a group positions it. + const sides = related.filter((rel) => !isBody(rel) || rel.keepsTab === true); // objectstack#35595 — the first tab is 「概览」 (the token the tab strip // localizes as `detail.recordTabOverview`); its value stays `details`, the // URL token a `?tab=` link already names.