From bf197a6923b1ba9ac48c56ba29a268d75d10f639 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:21:36 +0000 Subject: [PATCH 1/8] wip(ui): form slots place a master-detail collection at its field group Claude-Session: https://claude.ai/code/session_01L6bhgXUMw7b8gUmNsyoXHR Co-authored-by: Claude --- .../components/src/renderers/form/form.tsx | 11 +- .../plugin-form/src/MasterDetailForm.tsx | 67 +++++- ui/packages/plugin-form/src/ObjectForm.tsx | 32 ++- ui/packages/plugin-form/src/TabbedForm.tsx | 66 +++++- ui/packages/plugin-form/src/formSlots.ts | 198 ++++++++++++++++++ 5 files changed, 364 insertions(+), 10 deletions(-) create mode 100644 ui/packages/plugin-form/src/formSlots.ts diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index ae0c4c76ad5..9b848dc0097 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -2634,7 +2634,7 @@ ComponentRegistry.register('form', const drawn = new Set(); const changeable = new Set(); for (const f of fields as FormFieldConfig[]) { - if (!f?.name || f.type === 'section-divider') continue; + if (!f?.name || f.type === 'section-divider' || f.type === 'form-slot') continue; drawn.add(f.name); if (f.hidden || (f as any).readonly === true || f.disabled === true) continue; changeable.add(f.name); @@ -3711,6 +3711,15 @@ ComponentRegistry.register('form', // Skip hidden fields if (hidden) return null; + // A host slot (objectstack#35889): an empty full-width element the form's + // host fills through a portal (`@object-ui/plugin-form` `formSlots.ts`, + // a master-detail form's collection at its field group). It holds no + // value and registers no control; `slotRef` is the host's callback. + if (type === 'form-slot') { + const { slotRef } = fieldProps as { slotRef?: React.Ref }; + return
; + } + // A field claimed by a HIDDEN section is not drawn (#6236) — the same // `return null` a field's own false predicate takes, so the ruled // semantics ride the existing mechanism: the value stays in the form diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 292f17ff7a3..14efb55be34 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -30,7 +30,8 @@ * `lookup`) FK on the child object. */ -import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; +import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; +import { createPortal } from 'react-dom'; import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types'; import { resolveAffordance, runBatchTransaction } from '@object-ui/core'; import { LineItemsField, lookupAutofillByField, useBooleanValueLabel, type BooleanValueLabel, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; @@ -51,6 +52,7 @@ import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploa import { FormDirtyReportContext } from './formDirtyReport'; import { MasterDetailFrameContext } from './masterDetailFrame'; import { useFormChromeTranslation } from './formChrome'; +import { FormSlotStore, type FormSlotHandoff, type FormSlotRequest } from './formSlots'; import { buildMasterDetailBatch, buildMasterDetailEditBatch, @@ -776,6 +778,9 @@ function scrapeHeaderRecord(host: HTMLElement | null): Record { els.forEach((el) => { const name = el.getAttribute('name'); if (!name) return; + // A collection the header form places at its field group is drawn inside + // the header's element (objectstack#35889): its cells are not header fields. + if (el.closest('[data-form-slot]')) return; if (el.tagName === 'INPUT') { const input = el as HTMLInputElement; if (input.type === 'checkbox') { out[name] = input.checked; return; } @@ -859,8 +864,27 @@ interface MasterDetailLinesProps { * Remove asks the child's delete grant: a create form's lines are drafts. */ formMode: 'create' | 'edit'; + /** Where the header form placed each collection (objectstack#35889, `formSlots.ts`). */ + slotStore: FormSlotStore; } +/** + * Draws `children` where the header form placed collection `id`: in its slot + * element through a portal, in place when no drawn layout claims it, and + * nowhere while a claimed slot's element is not mounted (objectstack#35889). + * Its own component, so a slot landing re-renders only what it moves. + */ +const FormSlotPlacement: React.FC<{ store: FormSlotStore; id: string; children: React.ReactNode }> = ({ + store, + id, + children, +}) => { + useSyncExternalStore(store.subscribe, store.getVersion, store.getVersion); + const at = store.placement(id); + if (at === 'inline') return <>{children}; + return at ? createPortal(children, at) : null; +}; + /** * The line-item grids + document totals, isolated from the header form. * @@ -888,6 +912,7 @@ const MasterDetailLines: React.FC = ({ onAddViaForm, parentObjectName, formMode, + slotStore, }) => { // The subtotal / tax / grand-total stack formats in the display locale; it // used to pass `toLocaleString` an explicit `undefined`, i.e. the MACHINE's @@ -1030,7 +1055,8 @@ const MasterDetailLines: React.FC = ({ // ahead of the index, which left such a section with no identity beyond // its position, so a sibling moving above it re-associated the section // and its rows with a different collection (objectui#6371). -
+ +

{d.title || t('form.lineItems.title')}

{/* A detail whose child object never resolved gets its OWN branch, ahead of the columns/loading one (objectui#6360) — the render half @@ -1165,6 +1191,7 @@ const MasterDetailLines: React.FC = ({ /> )}
+
); })} @@ -1249,6 +1276,32 @@ export const MasterDetailForm: React.FC = ({ [schema.details], ); + /** + * objectstack#35889 — the collections the header form may place at the + * field group that names them (`formSlots.ts`), from the AUTHORED entries so + * the header's schema does not change when the child schemas resolve. A + * derived entry already carries its FK (`attachInlineSubforms`); one with no + * FK is placed only by a group naming its bare child object. + */ + const slotRequests = useMemo( + () => + rawDetails.flatMap((d, i) => + typeof d?.childObject === 'string' && d.childObject + ? [{ + id: detailIds[i], + childObject: d.childObject, + ...(typeof d.relationshipField === 'string' ? { relationshipField: d.relationshipField } : {}), + }] + : [], + ), + // eslint-disable-next-line react-hooks/exhaustive-deps + [schema.details, detailIds], + ); + // One store per form instance, in a ref (never a memo, AGENTS.md #10). + const slotStoreRef = useRef(null); + if (!slotStoreRef.current) slotStoreRef.current = new FormSlotStore(); + const slotStore = slotStoreRef.current; + /** The unresolved entries — what renders until (or unless) the fetch lands. */ const baseEntries = useMemo( () => @@ -2084,8 +2137,10 @@ export const MasterDetailForm: React.FC = ({ submitHandler: submitViaBatch, onSuccess: handleSaved, onError: handleError, - }), - [schema, titleText, submitViaBatch, handleSaved, handleError], + // objectstack#35889 — each collection at its field group in the header. + formSlots: { requests: slotRequests, host: slotStore }, + } satisfies FormSlotHandoff & Record), + [schema, titleText, submitViaBatch, handleSaved, handleError, slotRequests, slotStore], ); const formHostRef = useRef(null); @@ -2209,6 +2264,7 @@ export const MasterDetailForm: React.FC = ({ onAddViaForm={addRowViaForm} parentObjectName={schema.objectName} formMode={isEdit ? 'edit' : 'create'} + slotStore={slotStore} /> {/* Per-row "expand to full form": an inline editor panel for the selected @@ -2220,6 +2276,8 @@ export const MasterDetailForm: React.FC = ({ the values back into the in-memory row; the atomic batch persists everything on the parent Save. */} {expanded && expandedDetail && ( + // Beside its collection: where the header placed that collection, there. + @@ -2272,6 +2330,7 @@ export const MasterDetailForm: React.FC = ({ + )} ); diff --git a/ui/packages/plugin-form/src/ObjectForm.tsx b/ui/packages/plugin-form/src/ObjectForm.tsx index c81879780be..27164709809 100644 --- a/ui/packages/plugin-form/src/ObjectForm.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.tsx @@ -49,6 +49,7 @@ import { sectionedGridLayout, } from './autoLayout'; import { deriveFieldGroupSections, projectSectionDivider, resolveSectionCollapse, type FormFieldWithGroup } from './fieldGroups'; +import { formSlotRow, placeFormSlots, type FormSlotHandoff } from './formSlots'; import { FormSectionNav, useFormSectionNav } from './FormSectionNav'; import { mergeCustomFields } from './customFieldsMerge'; import { hasSectionGroupReference, resolveSectionGroupReferences } from './sectionGroups'; @@ -1556,6 +1557,29 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource // (so a group declared `collapsed: true` starts closed without pre-seeding). const [collapsedSections, setCollapsedSections] = useState>({}); + // objectstack#35889 — the host's collections a field group of this object + // places (`formSlots.ts`): laid out among the sections by the record page's + // rule, drawn as `form-slot` rows by the sectioned arm below. The claim names + // what the drawn layout places, `[]` for any other layout, and is never made + // while the form is still loading. + const formSlots = (schema as FormSlotHandoff).formSlots; + const drawsSections = !!effectiveSections?.length && (!schema.formType || schema.formType === 'simple'); + const slotPlacement = React.useMemo( + () => placeFormSlots( + drawsSections ? effectiveSections! : [], + (section) => (typeof section?.name === 'string' ? section.name : undefined), + objectSchema?.fieldGroups, + formSlots?.requests, + ), + [drawsSections, effectiveSections, objectSchema, formSlots?.requests], + ); + const slotClaim = loading ? null : (drawsSections && !error && !submitted ? slotPlacement.placed : []).join('\n'); + const slotHost = formSlots?.host; + useEffect(() => { + if (slotClaim === null || !slotHost) return; + slotHost.claim(slotClaim ? slotClaim.split('\n') : []); + }, [slotClaim, slotHost]); + // Render error state if (error instanceof RecordNotFoundError) { return ; @@ -1667,7 +1691,13 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource customFields: schema.customFields, pool: sourceFields, }; - effectiveSections.forEach((section, index) => { + slotPlacement.sequence.forEach((item) => { + if ('slot' in item) { + if (slotHost) groupedFields.push(formSlotRow(item.slot, slotHost)); + return; + } + const { section } = item; + const index = effectiveSections.indexOf(section); // ⚠️ `?? []`, not a bare `.map` — the second containment layer for // objectui#7051. The group-reference resolution above this component // means a `{ group }` section never arrives here carrying no `fields`, diff --git a/ui/packages/plugin-form/src/TabbedForm.tsx b/ui/packages/plugin-form/src/TabbedForm.tsx index 81b68dfe167..777d61b7014 100644 --- a/ui/packages/plugin-form/src/TabbedForm.tsx +++ b/ui/packages/plugin-form/src/TabbedForm.tsx @@ -13,7 +13,7 @@ * Aligns with @objectstack/spec FormView type: 'tabbed' */ -import React, { useState, useCallback, useRef } from 'react'; +import React, { useState, useCallback, useRef, useEffect, useMemo } from 'react'; import type { FormField, FormSchema, DataSource, ObjectFormSchema, ObjectFormSection } from '@object-ui/types'; import { cn, toast } from '@object-ui/components'; import { useLocalization } from '@object-ui/i18n'; @@ -42,6 +42,7 @@ import { useRecordInvalidation } from './recordInvalidation'; import { useReportedDirtyChange } from './formDirtyReport'; import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate'; import { useFormChromeTranslation } from './formChrome'; +import { formSlotGroupIndex, formSlotRow, placeFormSlots, type FormSlotHandoff } from './formSlots'; export interface FormSectionConfig { /** @@ -297,7 +298,7 @@ export const TabbedForm: React.FC = ({ dataSource, className, }) => { - const { fieldLabel } = useSafeFieldLabel(); + const { fieldLabel, sectionLabel } = useSafeFieldLabel(); // The loading line, the load-failure heading and the default submit label, // in the session locale (objectui#11039). See `formChrome.ts`. const { t } = useFormChromeTranslation(); @@ -587,6 +588,27 @@ export const TabbedForm: React.FC = ({ } }, [schema]); + // objectstack#35889 — a collection a field group places is a tab of its + // own at that group's position among the tabs (`formSlots.ts`, the record + // page's rule), labelled with the group's label. The claim names what the + // drawn tabs place, and is never made while the form is still loading. + const formSlots = (schema as FormSlotHandoff).formSlots; + const slotPlacement = useMemo( + () => placeFormSlots( + schema.sections, + (section) => (typeof section?.name === 'string' ? section.name : undefined), + objectSchema?.fieldGroups, + formSlots?.requests, + ), + [schema.sections, objectSchema, formSlots?.requests], + ); + const slotClaim = loading ? null : (error ? [] : slotPlacement.placed).join('\n'); + const slotHost = formSlots?.host; + useEffect(() => { + if (slotClaim === null || !slotHost) return; + slotHost.claim(slotClaim ? slotClaim.split('\n') : []); + }, [slotClaim, slotHost]); + // Generate tab value const getTabValue = (section: FormSectionConfig, index: number): string => { return section.name || section.label || `tab-${index}`; @@ -634,7 +656,43 @@ export const TabbedForm: React.FC = ({ const formColumns = sectionGrid.columns; const containerFieldClass = sectionGrid.fieldContainerClass; - const tabGroups = schema.sections.map((section, index) => { + type TabGroup = { + key: string; + label: string; + description?: string; + containerClass?: string; + visibleWhen?: FormSectionConfig['visibleWhen']; + visibleWhenFault?: FormSectionConfig['visibleWhenFault']; + fields: FormField[]; + }; + const tabGroups: TabGroup[] = []; + let slotTab: { at: number; group: TabGroup } | null = null; + slotPlacement.sequence.forEach((item) => { + if ('section' in item) { + slotTab = null; + const index = schema.sections.indexOf(item.section); + tabGroups.push(sectionTabGroup(item.section, index)); + return; + } + if (!slotHost) return; + const at = formSlotGroupIndex(objectSchema?.fieldGroups, item.slot) ?? -1; + const row = formSlotRow(item.slot, slotHost) as FormField; + // Two collections one group places share its tab. + if (slotTab && slotTab.at === at) { + slotTab.group.fields.push(row); + return; + } + const group = (objectSchema?.fieldGroups as Array<{ key?: string; label?: string }> | undefined)?.[at]; + const key = typeof group?.key === 'string' ? group.key : `__form_slot_tab__${item.slot.id}`; + const label = typeof group?.key === 'string' + ? sectionLabel(schema.objectName, group.key, group.label || group.key) + : item.slot.childObject; + const tab: TabGroup = { key, label, fields: [row] }; + slotTab = { at, group: tab }; + tabGroups.push(tab); + }); + + function sectionTabGroup(section: FormSectionConfig, index: number): TabGroup { const body = buildSectionFields(section); return { key: getTabValue(section, index), @@ -648,7 +706,7 @@ export const TabbedForm: React.FC = ({ visibleWhenFault: section.visibleWhenFault, fields: sectionGrid.layOut(body, section.columns), }; - }); + } // ── "Collapse below two tabs", the ruling's third binding semantic ───────── // Two different situations wear that name, and only one of them was answered diff --git a/ui/packages/plugin-form/src/formSlots.ts b/ui/packages/plugin-form/src/formSlots.ts new file mode 100644 index 00000000000..bb20443b42d --- /dev/null +++ b/ui/packages/plugin-form/src/formSlots.ts @@ -0,0 +1,198 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Form slots: a place in a header form's layout where its HOST draws something + * the form does not own (objectstack#35889). + * + * The one producer is `MasterDetailForm`: a child collection a field group of + * the parent places (`fieldGroups[].relatedList`, the spec's + * `fieldGroupsPlaceRelationship` reading) is drawn at that group's position in + * the parent's form, as the record page draws the same table at the same + * group (`bodyTablePlacement` in `@object-ui/plugin-detail`). The header form + * draws an empty `form-slot` row there; the host renders the collection into + * that row's element through a portal, so the collection stays out of the + * header's React tree (a header keystroke never re-renders the lines, and the + * lines never re-render the header, #1581). + * + * Both halves are runtime-only hand-off state, typed here where producer and + * consumer live and never on the `ObjectFormSchema` authoring face (ui + * AGENTS.md #0.1). + */ + +import { fieldGroupsPlaceRelationship } from '@objectstack/spec/data'; +import type { FormField } from '@object-ui/types'; + +/** The row type the form renderer draws as an empty slot element. */ +export const FORM_SLOT_ROW_TYPE = 'form-slot'; + +/** One collection the host asks the form to place. */ +export interface FormSlotRequest { + /** The host's stable identity of the collection (a detail entry id). */ + id: string; + /** The child object the collection lists. */ + childObject: string; + /** The child's FK to the parent; absent, only a bare child-name group places it. */ + relationshipField?: string; +} + +/** + * Where the form reports what it placed. `refFor(id)` is the element callback + * of one slot row; `claim(ids)` names every slot the drawn layout carries, and + * is called once per drawn layout (`[]` when it places none), never while the + * form is still loading — so a remounting header keeps the previous claim and + * the collections do not jump below the form and back. + */ +export interface FormSlotHost { + refFor(id: string): (el: HTMLElement | null) => void; + claim(ids: readonly string[]): void; +} + +/** The hand-off key a host sets on the header form's schema. */ +export interface FormSlotHandoff { + formSlots?: { requests: readonly FormSlotRequest[]; host: FormSlotHost }; +} + +/** + * The index, among the object's declared `fieldGroups`, of the first group + * whose `relatedList` names this collection; `null` when none does. + */ +export function formSlotGroupIndex(fieldGroups: unknown, request: FormSlotRequest): number | null { + if (!Array.isArray(fieldGroups)) return null; + const index = fieldGroups.findIndex((group) => + fieldGroupsPlaceRelationship([group], request.childObject, request.relationshipField ?? ''), + ); + return index === -1 ? null : index; +} + +export type FormSlotSequenceItem = { section: S } | { slot: FormSlotRequest }; + +/** + * Lay a form's sections and the placed collections out in one sequence, by + * the record page's rule (`bodyTablePlacement`): a collection a group places + * comes after the sections of the groups declared before that group and + * before those declared after it; a section that names no declared group (the + * ungrouped bucket, an authored section of its own) counts as after every + * group. Sections keep their order; collections at one position keep the + * request order. + * + * A layout none of whose sections names a declared group has no position to + * give, so it places nothing and every collection stays where the host draws + * it. `placed` lists the ids placed. + */ +export function placeFormSlots( + sections: readonly S[], + sectionGroupKey: (section: S) => string | undefined, + fieldGroups: unknown, + requests: readonly FormSlotRequest[] | undefined, +): { sequence: FormSlotSequenceItem[]; placed: string[] } { + const plain = { sequence: sections.map((section) => ({ section })), placed: [] as string[] }; + if (!requests?.length || !Array.isArray(fieldGroups)) return plain; + const groupIndex = new Map(); + fieldGroups.forEach((group, index) => { + const key = group && typeof group === 'object' ? (group as { key?: unknown }).key : undefined; + if (typeof key === 'string' && !groupIndex.has(key)) groupIndex.set(key, index); + }); + const indexOf = (section: S): number => { + const key = sectionGroupKey(section); + return (key !== undefined ? groupIndex.get(key) : undefined) ?? Number.POSITIVE_INFINITY; + }; + if (!sections.some((section) => Number.isFinite(indexOf(section)))) return plain; + + const slots = requests + .map((slot, order) => ({ slot, order, at: formSlotGroupIndex(fieldGroups, slot) })) + .filter((s): s is { slot: FormSlotRequest; order: number; at: number } => s.at !== null) + .sort((a, b) => a.at - b.at || a.order - b.order); + if (slots.length === 0) return plain; + + const sequence: FormSlotSequenceItem[] = []; + let next = 0; + for (const section of sections) { + const at = indexOf(section); + while (next < slots.length && slots[next].at < at) sequence.push({ slot: slots[next++].slot }); + sequence.push({ section }); + } + while (next < slots.length) sequence.push({ slot: slots[next++].slot }); + return { sequence, placed: slots.map((s) => s.slot.id) }; +} + +/** + * The form row of one slot. `slotRef` is the host's element callback, read + * by the form renderer's `form-slot` branch; like a divider row's `onToggle` + * it is written by the host and never authored, so it stays off `FormField`. + */ +export type FormSlotRow = FormField & { slotRef: (el: HTMLElement | null) => void }; + +/** The row a placed collection takes in the header form's field list. */ +export function formSlotRow(request: FormSlotRequest, host: FormSlotHost): FormSlotRow { + return { + name: `__form_slot__${request.id}`, + label: '', + type: FORM_SLOT_ROW_TYPE, + slotRef: host.refFor(request.id), + } as FormSlotRow; +} + +/** + * The host half: the slot elements the header form has mounted and the ids + * its drawn layout claims, for `useSyncExternalStore`. One instance per host, + * held in a ref, so `refFor` hands out one callback per id for the store's + * lifetime. + */ +export class FormSlotStore implements FormSlotHost { + private readonly elements = new Map(); + private readonly refs = new Map void>(); + private claimed: ReadonlySet | null = null; + private readonly listeners = new Set<() => void>(); + private version = 0; + + refFor(id: string): (el: HTMLElement | null) => void { + let ref = this.refs.get(id); + if (!ref) { + ref = (el) => { + if (el ? this.elements.get(id) === el : !this.elements.has(id)) return; + if (el) this.elements.set(id, el); + else this.elements.delete(id); + this.emit(); + }; + this.refs.set(id, ref); + } + return ref; + } + + claim(ids: readonly string[]): void { + const prev = this.claimed; + if (prev && prev.size === ids.length && ids.every((id) => prev.has(id))) return; + this.claimed = new Set(ids); + this.emit(); + } + + /** + * Where the host draws collection `id`: `'inline'` (no layout has claimed + * it: in the host's own place), the slot element, or `null` (claimed, its + * element not mounted this moment: drawn nowhere until it is). + */ + placement(id: string): 'inline' | HTMLElement | null { + if (!this.claimed?.has(id)) return 'inline'; + return this.elements.get(id) ?? null; + } + + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + }; + + getVersion = (): number => this.version; + + private emit(): void { + this.version += 1; + for (const listener of this.listeners) listener(); + } +} From 3c21300fbb7547fb86377d83a485056932164ff8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:23:32 +0000 Subject: [PATCH 2/8] wip: texts and tests for group-placed detail in the entry form Claude-Session: https://claude.ai/code/session_01L6bhgXUMw7b8gUmNsyoXHR Co-authored-by: Claude --- .../35889-form-places-detail-at-group.md | 18 +++ .../35889-master-detail-tab-by-default.md | 2 +- docs/adr/0035-config-driven-master-detail.md | 13 ++ packages/spec/src/data/field.zod.ts | 4 +- packages/spec/src/data/object.zod.ts | 7 +- .../src/data/related-list-body-table.test.ts | 2 +- .../spec/src/data/related-list-body-table.ts | 8 +- ...ster-detail-related-list-tab-by-default.ts | 3 +- ...erDetailForm.groupPlacement-35889.test.tsx | 150 ++++++++++++++++++ ui/packages/plugin-form/src/formSlots.test.ts | 85 ++++++++++ 10 files changed, 280 insertions(+), 12 deletions(-) create mode 100644 .changeset/35889-form-places-detail-at-group.md create mode 100644 ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx create mode 100644 ui/packages/plugin-form/src/formSlots.test.ts diff --git a/.changeset/35889-form-places-detail-at-group.md b/.changeset/35889-form-places-detail-at-group.md new file mode 100644 index 00000000000..127ffe05b09 --- /dev/null +++ b/.changeset/35889-form-places-detail-at-group.md @@ -0,0 +1,18 @@ +--- +'@object-ui/plugin-form': patch +'@object-ui/components': patch +'@objectstack/spec': patch +--- + +fix(ui): the entry form draws a group-placed master-detail table at its field group + +Clause-②: no +Metadata-protocol: none + +A master-detail child that a field group of the parent places (`fieldGroups[].relatedList`) is now drawn at that group in the parent's create and edit forms, where the record page draws it, instead of below all of the record's fields: + +- A form laid out from the parent's field groups draws the table after the sections of the groups declared before the placing group and before the ones declared after it. +- A tabbed form gives it a tab of its own at that position, labelled with the group's label. A wizard master-detail form is drawn as the simple form, as before, and places it the same way. +- A form whose sections name no field group, and a child no group places (a form view's own `subforms`), keep the table below the record's fields, as before. + +The table is the same one: its rows still save with the record in one batch, an expanded row's editor opens beside it, and the document totals stay at the foot of the form. No metadata changes. diff --git a/.changeset/35889-master-detail-tab-by-default.md b/.changeset/35889-master-detail-tab-by-default.md index d3672ae5bc8..b69c182ec46 100644 --- a/.changeset/35889-master-detail-tab-by-default.md +++ b/.changeset/35889-master-detail-tab-by-default.md @@ -19,7 +19,7 @@ A `master_detail` FK that declares no `relatedList` used to put its child list i - `inlineEdit` on the FK no longer inlines a child in the parent's form by itself (maintainer ruling B: only the field group decides). It now only picks the form factor of a child a group places: `'grid'`, `'form'`, or `true` / absent for the shape-picked default. A child with `inlineEdit` that no group names is a tab and is not in the form. - `os lint`: `relationship/line-items-inline-edit` now suggests a field group on the parent (with its required `label`) instead of `inlineEdit: true`, and only for a FK a group may place; `relationship/association-inline-edit` and `relationship/inline-edit-needs-bulk` judge the children a parent group places; the field-consumer rule credits a child's inline grid columns only when a parent group places it. - The showcase invoice and expense report, and the CRM opportunity, gain a field group naming their lines, so their forms and record pages keep the line table. -- In the entry form a placed table still sits below the record's fields, where `inlineEdit` tables sit today. Moving it to its group's place in the form is a follow-up. +- In the entry form a placed table sits at its group's place too: between the sections of the groups around it, or in a tab of its own (labelled with the group) in a tabbed form. A form whose sections name no field group keeps it below the record's fields. - Studio's field-group picker offers the same children as before. The relationship field inspector reads a plain `master_detail` FK as "Show", and "Show" leaves the key absent so a group can still place it. To keep a master-detail child's table in the overview and its rows in the form (including a child that set `inlineEdit`), add a field group to the parent that names it, in the place the table should sit: diff --git a/docs/adr/0035-config-driven-master-detail.md b/docs/adr/0035-config-driven-master-detail.md index b864a0bc762..c6f65f22780 100644 --- a/docs/adr/0035-config-driven-master-detail.md +++ b/docs/adr/0035-config-driven-master-detail.md @@ -169,6 +169,19 @@ a self-referential FK surfaces a "children" list. > group (a `master_detail` FK may instead drop `relatedList: true`); a group > naming a list its FK hides (`false`) is refused. +> **Note (2026-11-21, #35889, second slice).** The entry form now draws a +> placed child where the record page does, so "placed in the form below the +> record's fields until the form places it at the group" above is superseded. +> A form laid out from the parent's field groups draws the child's table +> after the sections of the groups declared before the placing group and +> before those declared after it; a tabbed form gives it a tab of its own at +> that position, labelled with the group's label (a wizard master-detail form +> is drawn as the simple form, as before). A form whose sections name no +> declared field group, and a child no group places (a form view's own +> subforms), keep the table below the record's fields. The table is the same +> one: it still saves with the record in one batch, and the document totals +> stay at the foot of the form. + The derivation is a pure function — `deriveRelatedLists(objectDef, objects)` in `@object-ui/app-shell` (`utils/deriveRelatedLists.ts`) — the read-side analogue of `attachInlineSubforms`. `RecordDetailView` feeds its output into the diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 4cfda2c2b55..ef388203f56 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2365,8 +2365,8 @@ export const FieldSchema = lazySchema(() => { * #35597's `'primary'` default): it joins the record's main content only * when a field group of the PARENT names it (`ObjectFieldGroupSchema.relatedList`), * which draws its table at the group's position in the record page and its - * edit state, and inlines it in the parent's entry form (below the record's - * fields until the form places it at the group too). + * edit state, and inlines it in the parent's entry form at the same place + * (a form whose sections name no field group keeps it below its fields). * Write `relatedList: true` to keep it a tab even from a group (a group * naming it is refused), `'primary'` to make it a body table with no group, * or `false` to hide it. diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 33628f876e0..89441beea90 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1414,8 +1414,9 @@ export const ObjectFieldGroupSchema = lazySchema(() => strictObject({ * `relatedList: 'primary'` (the group positions that body table), or a * `master_detail` FK that declares no `relatedList` (a tab by default; the * group makes it a body table at this position in the record page and its - * edit state, and the parent's entry form inlines it, below the record's - * fields until the form places it at the group too, #35889). A group + * edit state, and the parent's entry form inlines it at the same position; + * a form whose sections name no field group keeps it below its fields, + * #35889). A group * naming a side card, or a list its FK hides with `relatedList: false`, * draws nothing at the group, so it is refused wherever the child's fields * are known: at `defineStack` and at the runtime metadata write door @@ -1426,7 +1427,7 @@ export const ObjectFieldGroupSchema = lazySchema(() => strictObject({ */ relatedList: z.string().regex(RELATED_LIST_ENTRY_PATTERN, { message: 'A field group\'s relatedList is a child object name (e.g. "task") or object.field (e.g. "event.related_to"), in snake_case', - }).optional().describe('Places a related list\'s body table at this position in the record\'s details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: \'primary\', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent\'s entry form inlines it below the record\'s fields until the form places it at the group as well): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child\'s fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: \'primary\' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group\'s relatedList).').meta({ title: 'Related List' }), + }).optional().describe('Places a related list\'s body table at this position in the record\'s details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: \'primary\', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent\'s entry form inlines it here too, or below its fields when the form\'s sections name no field group): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child\'s fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: \'primary\' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group\'s relatedList).').meta({ title: 'Related List' }), /** * [ADR-0085 §5] Section visibility predicate — CEL, the ADR-0089 canonical diff --git a/packages/spec/src/data/related-list-body-table.test.ts b/packages/spec/src/data/related-list-body-table.test.ts index 483aa566b26..6305719445d 100644 --- a/packages/spec/src/data/related-list-body-table.test.ts +++ b/packages/spec/src/data/related-list-body-table.test.ts @@ -110,7 +110,7 @@ describe('fieldGroups[i].relatedList describes the body-table rule it enforces', const text = root.properties?.relatedList?.description ?? ''; it('says it names a body table only, and that any other list is refused with the remedy', () => { - expect(text).toContain("It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it below the record's fields until the form places it at the group as well)"); + expect(text).toContain("It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it here too, or below its fields when the form's sections name no field group)"); expect(text).toContain('a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused'); expect(text).toContain("set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList"); }); diff --git a/packages/spec/src/data/related-list-body-table.ts b/packages/spec/src/data/related-list-body-table.ts index 23462ffcb89..2d406bf55ce 100644 --- a/packages/spec/src/data/related-list-body-table.ts +++ b/packages/spec/src/data/related-list-body-table.ts @@ -18,10 +18,10 @@ * default"). It becomes a body table only when one of the PARENT's field * groups names it (`ObjectFieldGroupSchema.relatedList`): then it is drawn * at that group's position, the record page's edit state carries it, and - * the parent's entry form inlines it (below the record's fields until the - * form places it at the group). `inlineEdit` takes no part in placement: - * since ruling B on #35889 it only picks the form factor of a child a group - * places (ADR-0035 as amended); + * the parent's entry form inlines it at the same place (below its fields + * when the form's sections name no field group). `inlineEdit` takes no + * part in placement: since ruling B on #35889 it only picks the form + * factor of a child a group places (ADR-0035 as amended); * - anything else is a tab (`true`, or a `lookup` with no `relatedList`), or * hidden (`false`). `relatedList: true` on a `master_detail` keeps it a tab, * which a group cannot override. A `lookup` child is a body table only by diff --git a/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts b/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts index 1e20bbcab5f..21ee63d321f 100644 --- a/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts +++ b/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts @@ -68,7 +68,8 @@ export const entry: SemanticMigration = { + 'draws no table for the child and the tab row carries the child\'s tab with its count; the create and ' + 'edit forms do not inline it. After adding a field group that names the ' + 'child, second in fieldGroups: the overview draws the child\'s table in the second group\'s place, the ' - + 'tab is still there, the create and edit forms inline the table, and the record page\'s Edit saves the ' + + 'tab is still there, the create and edit forms inline the table at the same place (a tab of its own in a ' + + 'tabbed form), and the record page\'s Edit saves the ' + 'record fields and the rows in one save. A child whose FK sets inlineEdit and that no group names is not ' + 'inlined in the parent\'s forms. A child whose FK declares relatedList \'primary\' is drawn on the ' + 'record page as before: a body table with no tab of its own, whether or not a group positions it. Where ' diff --git a/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx new file mode 100644 index 00000000000..724256278da --- /dev/null +++ b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx @@ -0,0 +1,150 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen, waitFor, fireEvent } from '@testing-library/react'; +import React from 'react'; +import { registerAllFields } from '@object-ui/fields'; +import { MasterDetailForm } from './MasterDetailForm'; + +// objectstack#35889 — a master-detail collection a field group of the parent +// places (`fieldGroups[].relatedList`) is drawn at that group in the entry +// form, as the record page draws it: after the groups declared before it, +// before the groups declared after it. A collection no group places stays +// below the record's fields. + +registerAllFields(); + +const LINES_GROUP = { key: 'lines', label: 'Lines', relatedList: 'po_line' }; +function parentWith(fieldGroups: unknown[]) { + return { + name: 'po', + fieldGroups, + fields: { + ref: { type: 'text', label: 'Ref', group: 'header' }, + memo: { type: 'text', label: 'Memo', group: 'totals' }, + }, + }; +} +const HEADER_GROUP = { key: 'header', label: 'Header', fields: ['ref'] }; +const TOTALS_GROUP = { key: 'totals', label: 'Totals', fields: ['memo'] }; + +function makeDataSource(parent: unknown, overrides: Record = {}) { + return { + getObjectSchema: vi.fn().mockResolvedValue(parent), + find: vi.fn().mockResolvedValue({ data: [] }), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + bulk: vi.fn(), + ...overrides, + } as any; +} + +const details = [ + { childObject: 'po_line', relationshipField: 'po', title: 'Order lines', columns: [{ key: 'qty', label: 'Qty', type: 'number' } as any] }, +]; + +/** Whether `a` comes before `b` in document order. */ +function before(a: Node, b: Node): boolean { + return (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0; +} + +async function collection(container: HTMLElement): Promise { + return waitFor(() => { + const el = container.querySelector('[data-testid="md-collection"]') as HTMLElement | null; + if (!el) throw new Error('collection not drawn'); + return el; + }); +} + +describe('MasterDetailForm — a group-placed collection sits at its group (objectstack#35889)', () => { + it('simple form: between the sections of the groups around its group, inside the header form', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + const el = container.querySelector('[data-form-slot] [data-testid="md-collection"]'); + if (!el) throw new Error('collection not placed'); + }); + const placed = await collection(container); + const header = container.querySelector('[data-form-section="header"]')!; + const totals = container.querySelector('[data-form-section="totals"]')!; + expect(header).toBeTruthy(); + expect(totals).toBeTruthy(); + expect(placed.closest('form')).toBe(header.closest('form')); + expect(before(header, placed)).toBe(true); + expect(before(placed, totals)).toBe(true); + expect(placed.textContent).toContain('Order lines'); + }); + + it('simple form: a collection no group places stays below the record fields', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, TOTALS_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-section="totals"]')) throw new Error('header not ready'); + }); + const below = await collection(container); + expect(below.closest('form')).toBeNull(); + expect(container.querySelector('[data-form-slot]')).toBeNull(); + expect(before(container.querySelector('[data-form-section="totals"]')!, below)).toBe(true); + }); + + it('a group placed last: after every declared group', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, TOTALS_GROUP, LINES_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-slot] [data-testid="md-collection"]')) throw new Error('not placed'); + }); + const placed = await collection(container); + expect(before(container.querySelector('[data-form-section="totals"]')!, placed)).toBe(true); + }); + + it('saves the record and its lines in one batch from the placed table', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }] }); + const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP]), { batchTransaction }); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-slot] [data-testid="md-collection"]')) throw new Error('not placed'); + }); + const ref = container.querySelector('input[name="ref"]') as HTMLInputElement; + fireEvent.change(ref, { target: { value: 'PO-1' } }); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(batchTransaction).toHaveBeenCalledTimes(1)); + const ops = batchTransaction.mock.calls[0][0] as Array<{ object?: string; objectName?: string; data?: any }>; + expect(JSON.stringify(ops)).toContain('PO-1'); + }); + + it('tabbed form: a tab of its own at its group, labelled with the group', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-slot] [data-testid="md-collection"]')) throw new Error('not placed'); + }); + const tabs = screen.getAllByRole('tab').map((tab) => tab.textContent?.trim()); + expect(tabs).toEqual(['Header', 'Lines', 'Totals']); + const placed = await collection(container); + const panel = placed.closest('[role="tabpanel"]') as HTMLElement; + expect(panel).toBeTruthy(); + const label = panel.getAttribute('aria-labelledby'); + expect(label && document.getElementById(label)?.textContent?.trim()).toBe('Lines'); + }); +}); diff --git a/ui/packages/plugin-form/src/formSlots.test.ts b/ui/packages/plugin-form/src/formSlots.test.ts new file mode 100644 index 00000000000..336ce3659f2 --- /dev/null +++ b/ui/packages/plugin-form/src/formSlots.test.ts @@ -0,0 +1,85 @@ +import { describe, it, expect, vi } from 'vitest'; +import { FormSlotStore, formSlotGroupIndex, placeFormSlots, type FormSlotRequest } from './formSlots'; + +// objectstack#35889 — a collection a field group places sits at that group in +// the header form, by the record page's rule (`bodyTablePlacement`). + +const groups = [ + { key: 'header', label: 'Header', fields: ['ref'] }, + { key: 'lines', label: 'Lines', relatedList: 'po_line' }, + { key: 'totals', label: 'Totals', fields: ['memo'] }, +]; +const lines: FormSlotRequest = { id: 'd0', childObject: 'po_line', relationshipField: 'po' }; +const named = (s: { name?: string }) => s.name; +const order = (sequence: Array<{ section: { name?: string } } | { slot: FormSlotRequest }>) => + sequence.map((item) => ('slot' in item ? `slot:${item.slot.id}` : item.section.name ?? '(ungrouped)')); + +describe('placeFormSlots (objectstack#35889)', () => { + it('puts a placed collection after the groups declared before its group and before those after it', () => { + const { sequence, placed } = placeFormSlots( + [{ name: 'header' }, { name: 'totals' }, {}], + named, + groups, + [lines], + ); + expect(order(sequence)).toEqual(['header', 'slot:d0', 'totals', '(ungrouped)']); + expect(placed).toEqual(['d0']); + }); + + it('a group declared last puts it after the declared groups and before the ungrouped bucket', () => { + const last = [groups[0], groups[2], groups[1]]; + const { sequence } = placeFormSlots([{ name: 'header' }, { name: 'totals' }, {}], named, last, [lines]); + expect(order(sequence)).toEqual(['header', 'totals', 'slot:d0', '(ungrouped)']); + }); + + it('reads the group entry as the record page does: a bare child, or object.field', () => { + expect(formSlotGroupIndex(groups, lines)).toBe(1); + expect(formSlotGroupIndex([{ key: 'l', relatedList: 'po_line.po' }], lines)).toBe(0); + expect(formSlotGroupIndex([{ key: 'l', relatedList: 'po_line.other' }], lines)).toBeNull(); + // No FK on the request: only a bare child-name group places it. + expect(formSlotGroupIndex([{ key: 'l', relatedList: 'po_line.po' }], { id: 'x', childObject: 'po_line' })).toBeNull(); + expect(formSlotGroupIndex(groups, { id: 'x', childObject: 'po_line' })).toBe(1); + }); + + it('places nothing a group does not name, and nothing when no section names a declared group', () => { + const other: FormSlotRequest = { id: 'd1', childObject: 'note', relationshipField: 'po' }; + const a = placeFormSlots([{ name: 'header' }], named, groups, [other]); + expect(order(a.sequence)).toEqual(['header']); + expect(a.placed).toEqual([]); + // Authored sections of their own: no position to give, the host keeps it. + const b = placeFormSlots([{ name: 'main' }, { name: 'more' }], named, groups, [lines]); + expect(order(b.sequence)).toEqual(['main', 'more']); + expect(b.placed).toEqual([]); + expect(placeFormSlots([{ name: 'header' }], named, undefined, [lines]).placed).toEqual([]); + }); +}); + +describe('FormSlotStore (objectstack#35889)', () => { + it('draws a collection in place until a layout claims it, then in its slot, and nowhere while the slot is unmounted', () => { + const store = new FormSlotStore(); + const listener = vi.fn(); + store.subscribe(listener); + expect(store.placement('d0')).toBe('inline'); + + const el = document.createElement('div'); + store.refFor('d0')(el); + // Mounted but not claimed: still in place. + expect(store.placement('d0')).toBe('inline'); + store.claim(['d0']); + expect(store.placement('d0')).toBe(el); + store.refFor('d0')(null); + expect(store.placement('d0')).toBeNull(); + store.claim([]); + expect(store.placement('d0')).toBe('inline'); + expect(listener).toHaveBeenCalledTimes(4); + }); + + it('hands out one element callback per id, and an equal claim changes nothing', () => { + const store = new FormSlotStore(); + expect(store.refFor('d0')).toBe(store.refFor('d0')); + store.claim(['d0']); + const v = store.getVersion(); + store.claim(['d0']); + expect(store.getVersion()).toBe(v); + }); +}); From 850405ca6f90c38e91a95f2b75ec67857abb583b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:29:13 +0000 Subject: [PATCH 3/8] test(ui): pin group placement of a master-detail collection in the entry form Claude-Session: https://claude.ai/code/session_01L6bhgXUMw7b8gUmNsyoXHR Co-authored-by: Claude --- .../src/MasterDetailForm.groupPlacement-35889.test.tsx | 10 +++++----- ui/packages/plugin-form/src/formSlots.test.ts | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx index 724256278da..0799d92d93d 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx @@ -66,8 +66,8 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje if (!el) throw new Error('collection not placed'); }); const placed = await collection(container); - const header = container.querySelector('[data-form-section="header"]')!; - const totals = container.querySelector('[data-form-section="totals"]')!; + const header = container.querySelector('[data-form-section="__section_header"]')!; + const totals = container.querySelector('[data-form-section="__section_totals"]')!; expect(header).toBeTruthy(); expect(totals).toBeTruthy(); expect(placed.closest('form')).toBe(header.closest('form')); @@ -82,12 +82,12 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje , ); await waitFor(() => { - if (!container.querySelector('[data-form-section="totals"]')) throw new Error('header not ready'); + if (!container.querySelector('[data-form-section="__section_totals"]')) throw new Error('header not ready'); }); const below = await collection(container); expect(below.closest('form')).toBeNull(); expect(container.querySelector('[data-form-slot]')).toBeNull(); - expect(before(container.querySelector('[data-form-section="totals"]')!, below)).toBe(true); + expect(before(container.querySelector('[data-form-section="__section_totals"]')!, below)).toBe(true); }); it('a group placed last: after every declared group', async () => { @@ -99,7 +99,7 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje if (!container.querySelector('[data-form-slot] [data-testid="md-collection"]')) throw new Error('not placed'); }); const placed = await collection(container); - expect(before(container.querySelector('[data-form-section="totals"]')!, placed)).toBe(true); + expect(before(container.querySelector('[data-form-section="__section_totals"]')!, placed)).toBe(true); }); it('saves the record and its lines in one batch from the placed table', async () => { diff --git a/ui/packages/plugin-form/src/formSlots.test.ts b/ui/packages/plugin-form/src/formSlots.test.ts index 336ce3659f2..19e075ea195 100644 --- a/ui/packages/plugin-form/src/formSlots.test.ts +++ b/ui/packages/plugin-form/src/formSlots.test.ts @@ -61,7 +61,7 @@ describe('FormSlotStore (objectstack#35889)', () => { store.subscribe(listener); expect(store.placement('d0')).toBe('inline'); - const el = document.createElement('div'); + const el = { tagName: 'DIV' } as unknown as HTMLElement; store.refFor('d0')(el); // Mounted but not claimed: still in place. expect(store.placement('d0')).toBe('inline'); From e7816f5a80b8a68e76652c17efade9d497505a1b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:33:09 +0000 Subject: [PATCH 4/8] docs(spec): regenerate the object reference for the field-group relatedList text Claude-Session: https://claude.ai/code/session_01L6bhgXUMw7b8gUmNsyoXHR Co-authored-by: Claude --- content/docs/references/data/object.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index d251a875826..c2eb110ee1d 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -331,7 +331,7 @@ const result = ApiMethod.parse(data); | **fields** | `string[]` | optional | The group's members in display order (field names of this object). Written, it decides which fields the group shows and their order on the record page and the forms, without changing the order of the object's fields. Absent, members are the fields whose `group` names this group, in field declaration order (the older spelling, still read). A field whose `group` names this group but that the list does not name follows the listed ones. Refused: a listed field whose own `group` names another group, a field two groups list, a repeated name, and `fields` on a group with `relatedList`. A name the object does not declare is skipped. | | **icon** | `string` | optional | Icon name (Lucide/Material) for the group header | | **description** | `string` | optional | Optional description shown under the group header | -| **relatedList** | `string` | optional | Places a related list's body table at this position in the record's details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it below the record's fields until the form places it at the group as well): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child's fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList). | +| **relatedList** | `string` | optional | Places a related list's body table at this position in the record's details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it here too, or below its fields when the form's sections name no field group): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child's fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList). | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Section visibility predicate (CEL) — the whole group (header included) is shown only when TRUE, else hidden (fail-closed). e.g. P`record.type == 'invoice'` | | **requiresFeature** | `Enum<'twoFactor' \| 'organization' \| 'multiOrgEnabled' \| 'degradedTenancy' \| …>` | optional | Deployment feature flag gating this group, from the same set an action's `requiresFeature` names (e.g. 'multiOrgEnabled'). Lowered at parse time into the group's `visibleWhen` (AND-composed after an authored `visibleWhen`) and stripped from the output; the whole group is hidden where the flag is off. Presentation only: the fields stay readable through the API. | | **collapse** | `Enum<'none' \| 'expanded' \| 'collapsed'>` | optional (default: `"none"`) | [ADR-0085] Section collapse behaviour: 'none' (always open, no toggle), 'expanded' (collapsible, starts open), 'collapsed' (collapsible, starts closed). | @@ -746,7 +746,7 @@ External datasource binding (ADR-0015) | **fields** | `string[]` | optional | The group's members in display order (field names of this object). Written, it decides which fields the group shows and their order on the record page and the forms, without changing the order of the object's fields. Absent, members are the fields whose `group` names this group, in field declaration order (the older spelling, still read). A field whose `group` names this group but that the list does not name follows the listed ones. Refused: a listed field whose own `group` names another group, a field two groups list, a repeated name, and `fields` on a group with `relatedList`. A name the object does not declare is skipped. | | **icon** | `string` | optional | Icon name (Lucide/Material) for the group header | | **description** | `string` | optional | Optional description shown under the group header | -| **relatedList** | `string` | optional | Places a related list's body table at this position in the record's details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it below the record's fields until the form places it at the group as well): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child's fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList). | +| **relatedList** | `string` | optional | Places a related list's body table at this position in the record's details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it here too, or below its fields when the form's sections name no field group): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child's fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList). | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Section visibility predicate (CEL) — the whole group (header included) is shown only when TRUE, else hidden (fail-closed). e.g. P`record.type == 'invoice'` | | **requiresFeature** | `Enum<'twoFactor' \| 'organization' \| 'multiOrgEnabled' \| 'degradedTenancy' \| 'oidcProvider' \| 'sso' \| 'ssoEnforced' \| 'directSignIn' \| 'deviceAuthorization' \| 'admin' \| … +5 more>` | optional | Deployment feature flag gating this group, from the same set an action's `requiresFeature` names (e.g. 'multiOrgEnabled'). Lowered at parse time into the group's `visibleWhen` (AND-composed after an authored `visibleWhen`) and stripped from the output; the whole group is hidden where the flag is off. Presentation only: the fields stay readable through the API. | | **collapse** | `Enum<'none' \| 'expanded' \| 'collapsed'>` | optional (default: `"none"`) | [ADR-0085] Section collapse behaviour: 'none' (always open, no toggle), 'expanded' (collapsible, starts open), 'collapsed' (collapsible, starts closed). | From d19ebd0258934e92f3fcef22f6227e50b6d52e01 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 06:06:32 +0000 Subject: [PATCH 5/8] feat(ui): the form's section bar stops at a group-placed master-detail table A slot row carries its field group's label, once per group, and the form renderer reports a labelled slot to the section navigation between the headings around it. Adds an edit-mode pin for the placed collection. Claude-Session: https://claude.ai/code/session_01L6bhgXUMw7b8gUmNsyoXHR Co-authored-by: Claude --- .../35889-form-places-detail-at-group.md | 1 + .../__tests__/form-section-nav-34605.test.tsx | 21 ++++++++++++++ .../components/src/renderers/form/form.tsx | 15 ++++++++-- ...erDetailForm.groupPlacement-35889.test.tsx | 28 ++++++++++++++++++- ui/packages/plugin-form/src/ObjectForm.tsx | 13 +++++++-- ui/packages/plugin-form/src/TabbedForm.tsx | 8 +++--- ui/packages/plugin-form/src/formSlots.ts | 21 ++++++++++++-- 7 files changed, 94 insertions(+), 13 deletions(-) diff --git a/.changeset/35889-form-places-detail-at-group.md b/.changeset/35889-form-places-detail-at-group.md index 127ffe05b09..712c40ffc8a 100644 --- a/.changeset/35889-form-places-detail-at-group.md +++ b/.changeset/35889-form-places-detail-at-group.md @@ -12,6 +12,7 @@ Metadata-protocol: none A master-detail child that a field group of the parent places (`fieldGroups[].relatedList`) is now drawn at that group in the parent's create and edit forms, where the record page draws it, instead of below all of the record's fields: - A form laid out from the parent's field groups draws the table after the sections of the groups declared before the placing group and before the ones declared after it. +- The form's section bar stops at the table too, between the sections around it. - A tabbed form gives it a tab of its own at that position, labelled with the group's label. A wizard master-detail form is drawn as the simple form, as before, and places it the same way. - A form whose sections name no field group, and a child no group places (a form view's own `subforms`), keep the table below the record's fields, as before. diff --git a/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx b/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx index 53c69bff6e7..412c4c24336 100644 --- a/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx +++ b/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx @@ -66,6 +66,27 @@ function renderWithSink(schema: Record) { } describe('form section list for the host navigation (objectstack#34605)', () => { + it('stops at a labelled host slot between the headings around it, and skips an unlabelled one (objectstack#35889)', async () => { + const { last } = renderWithSink({ + fields: [ + divider('s_header', 'Header', ['name']), + { name: 'name', label: 'Name', type: 'input' }, + { name: '__form_slot__d0', label: 'Lines', type: 'form-slot' }, + { name: '__form_slot__d1', label: '', type: 'form-slot' }, + divider('s_totals', 'Totals', ['memo']), + { name: 'memo', label: 'Memo', type: 'input' }, + ], + }); + await waitFor(() => expect(last()).toBeTruthy()); + const items = last()!; + expect(items.map((i) => [i.key, i.label])).toEqual([ + ['s_header', 'Header'], + ['__form_slot__d0', 'Lines'], + ['s_totals', 'Totals'], + ]); + expect(document.getElementById(items[1].anchorId)?.getAttribute('data-form-slot')).toBe('__form_slot__d0'); + }); + it('reports the drawn headings in order, each with the DOM id of its row', async () => { const { last } = renderWithSink({ fields: SECTIONED }); await waitFor(() => expect(last()).toBeTruthy()); diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index 9b848dc0097..4a855c3884b 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -3714,10 +3714,19 @@ ComponentRegistry.register('form', // A host slot (objectstack#35889): an empty full-width element the form's // host fills through a portal (`@object-ui/plugin-form` `formSlots.ts`, // a master-detail form's collection at its field group). It holds no - // value and registers no control; `slotRef` is the host's callback. + // value and registers no control; `slotRef` is the host's callback. A + // labelled slot is a stop of the section navigation, like a heading. if (type === 'form-slot') { const { slotRef } = fieldProps as { slotRef?: React.Ref }; - return
; + return ( +
+ ); } // A field claimed by a HIDDEN section is not drawn (#6236) — the same @@ -4485,7 +4494,7 @@ ComponentRegistry.register('form', // the section navigation lists exactly these, so a section a predicate // hides is absent from it by the same verdict that hid its row. block.forEach((f, j) => { - if (f?.type === 'section-divider' && nodes[j] != null && f.label && typeof f.name === 'string') { + if ((f?.type === 'section-divider' || f?.type === 'form-slot') && nodes[j] != null && f.label && typeof f.name === 'string') { drawnHeadings?.push({ key: f.name, label: String(f.label) }); } }); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx index 0799d92d93d..76425ea2866 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx @@ -39,7 +39,7 @@ function makeDataSource(parent: unknown, overrides: Record = {} } const details = [ - { childObject: 'po_line', relationshipField: 'po', title: 'Order lines', columns: [{ key: 'qty', label: 'Qty', type: 'number' } as any] }, + { childObject: 'po_line', relationshipField: 'po', title: 'Order lines', columns: [{ name: 'qty', label: 'Qty', type: 'number' } as any] }, ]; /** Whether `a` comes before `b` in document order. */ @@ -102,6 +102,32 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje expect(before(container.querySelector('[data-form-section="__section_totals"]')!, placed)).toBe(true); }); + it('edit form: the loaded record\'s lines are drawn at the group, and only there', async () => { + const parent = parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP]); + const child = { name: 'po_line', fields: { qty: { type: 'number', label: 'Qty' }, po: { type: 'master_detail', label: 'PO', reference: 'po' } } }; + const ds = makeDataSource(parent, { + getObjectSchema: vi.fn(async (object: string) => (object === 'po_line' ? child : parent)), + findOne: vi.fn().mockResolvedValue({ id: 'po1', ref: 'PO-7', memo: 'm' }), + find: vi.fn().mockImplementation((object: string) => + Promise.resolve({ data: object === 'po_line' ? [{ id: 'l1', po: 'po1', qty: 3 }] : [] }), + ), + }); + const { container } = render( + , + ); + await waitFor(() => { + const el = container.querySelector('[data-form-slot] [data-testid="md-collection"]'); + const values = el ? [...el.querySelectorAll('input')].map((input) => (input as HTMLInputElement).value) : []; + if (!values.includes('3')) throw new Error('lines not placed'); + }); + const header = container.querySelector('[data-form-section="__section_header"]')!; + const totals = container.querySelector('[data-form-section="__section_totals"]')!; + const placed = container.querySelector('[data-form-slot] [data-testid="md-collection"]')!; + expect(before(header, placed)).toBe(true); + expect(before(placed, totals)).toBe(true); + expect(container.querySelectorAll('[data-testid="md-collection"]')).toHaveLength(1); + }); + it('saves the record and its lines in one batch from the placed table', async () => { const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }] }); const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP]), { batchTransaction }); diff --git a/ui/packages/plugin-form/src/ObjectForm.tsx b/ui/packages/plugin-form/src/ObjectForm.tsx index 27164709809..b91b5b76872 100644 --- a/ui/packages/plugin-form/src/ObjectForm.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.tsx @@ -49,7 +49,7 @@ import { sectionedGridLayout, } from './autoLayout'; import { deriveFieldGroupSections, projectSectionDivider, resolveSectionCollapse, type FormFieldWithGroup } from './fieldGroups'; -import { formSlotRow, placeFormSlots, type FormSlotHandoff } from './formSlots'; +import { formSlotGroup, formSlotRow, placeFormSlots, type FormSlotHandoff } from './formSlots'; import { FormSectionNav, useFormSectionNav } from './FormSectionNav'; import { mergeCustomFields } from './customFieldsMerge'; import { hasSectionGroupReference, resolveSectionGroupReferences } from './sectionGroups'; @@ -1691,9 +1691,18 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource customFields: schema.customFields, pool: sourceFields, }; + // A placed collection's row is named by its group, once per group, so the + // section navigation stops at it between the headings around it. + const namedSlotGroups = new Set(); slotPlacement.sequence.forEach((item) => { if ('slot' in item) { - if (slotHost) groupedFields.push(formSlotRow(item.slot, slotHost)); + if (!slotHost) return; + const group = formSlotGroup(objectSchema?.fieldGroups, item.slot); + const label = group && !namedSlotGroups.has(group.key) + ? sectionLabel(schema.objectName, group.key, group.label || group.key) + : ''; + if (group) namedSlotGroups.add(group.key); + groupedFields.push(formSlotRow(item.slot, slotHost, label)); return; } const { section } = item; diff --git a/ui/packages/plugin-form/src/TabbedForm.tsx b/ui/packages/plugin-form/src/TabbedForm.tsx index 777d61b7014..40e832b6617 100644 --- a/ui/packages/plugin-form/src/TabbedForm.tsx +++ b/ui/packages/plugin-form/src/TabbedForm.tsx @@ -42,7 +42,7 @@ import { useRecordInvalidation } from './recordInvalidation'; import { useReportedDirtyChange } from './formDirtyReport'; import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate'; import { useFormChromeTranslation } from './formChrome'; -import { formSlotGroupIndex, formSlotRow, placeFormSlots, type FormSlotHandoff } from './formSlots'; +import { formSlotGroup, formSlotGroupIndex, formSlotRow, placeFormSlots, type FormSlotHandoff } from './formSlots'; export interface FormSectionConfig { /** @@ -682,9 +682,9 @@ export const TabbedForm: React.FC = ({ slotTab.group.fields.push(row); return; } - const group = (objectSchema?.fieldGroups as Array<{ key?: string; label?: string }> | undefined)?.[at]; - const key = typeof group?.key === 'string' ? group.key : `__form_slot_tab__${item.slot.id}`; - const label = typeof group?.key === 'string' + const group = formSlotGroup(objectSchema?.fieldGroups, item.slot); + const key = group ? group.key : `__form_slot_tab__${item.slot.id}`; + const label = group ? sectionLabel(schema.objectName, group.key, group.label || group.key) : item.slot.childObject; const tab: TabGroup = { key, label, fields: [row] }; diff --git a/ui/packages/plugin-form/src/formSlots.ts b/ui/packages/plugin-form/src/formSlots.ts index bb20443b42d..8bee0e0339c 100644 --- a/ui/packages/plugin-form/src/formSlots.ts +++ b/ui/packages/plugin-form/src/formSlots.ts @@ -70,6 +70,17 @@ export function formSlotGroupIndex(fieldGroups: unknown, request: FormSlotReques return index === -1 ? null : index; } +/** + * The declared group that places this collection (its key and authored + * label), the name a form gives the collection's place; `null` when none does. + */ +export function formSlotGroup(fieldGroups: unknown, request: FormSlotRequest): { key: string; label?: string } | null { + const index = formSlotGroupIndex(fieldGroups, request); + const group = index === null ? undefined : (fieldGroups as Array<{ key?: unknown; label?: unknown }>)[index]; + if (typeof group?.key !== 'string') return null; + return { key: group.key, label: typeof group.label === 'string' ? group.label : undefined }; +} + export type FormSlotSequenceItem = { section: S } | { slot: FormSlotRequest }; /** @@ -128,11 +139,15 @@ export function placeFormSlots( */ export type FormSlotRow = FormField & { slotRef: (el: HTMLElement | null) => void }; -/** The row a placed collection takes in the header form's field list. */ -export function formSlotRow(request: FormSlotRequest, host: FormSlotHost): FormSlotRow { +/** + * The row a placed collection takes in the header form's field list. A + * `label` (its group's) makes the row a stop of the form's section + * navigation, between the headings it sits between. + */ +export function formSlotRow(request: FormSlotRequest, host: FormSlotHost, label = ''): FormSlotRow { return { name: `__form_slot__${request.id}`, - label: '', + label, type: FORM_SLOT_ROW_TYPE, slotRef: host.refFor(request.id), } as FormSlotRow; From 25b2e82fdf2533ba231c202e3b7593fac4db5e05 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 06:29:57 +0000 Subject: [PATCH 6/8] fix(ui): a placed master-detail collection's controls stay out of the header form The slot sits inside the header's
, so the portaled collection is wrapped in a form of its own (noValidate, a disabled default button, submit prevented): the header's requestSubmit validates only its own fields, a line button without a type no longer submits the header, and Enter in a line cell submits nothing. The renderer's reveal of an errored field skips what a host drew into its slot rows. Claude-Session: https://claude.ai/code/session_01L6bhgXUMw7b8gUmNsyoXHR Co-authored-by: Claude --- .../__tests__/form-invalid-scroll.test.tsx | 23 ++++++++++++++++++ .../components/src/renderers/form/form.tsx | 10 +++++++- ...erDetailForm.groupPlacement-35889.test.tsx | 24 ++++++++++++++++++- .../plugin-form/src/MasterDetailForm.tsx | 19 ++++++++++++++- 4 files changed, 73 insertions(+), 3 deletions(-) diff --git a/ui/packages/components/src/renderers/form/__tests__/form-invalid-scroll.test.tsx b/ui/packages/components/src/renderers/form/__tests__/form-invalid-scroll.test.tsx index 29543054d3a..a64fe05e243 100644 --- a/ui/packages/components/src/renderers/form/__tests__/form-invalid-scroll.test.tsx +++ b/ui/packages/components/src/renderers/form/__tests__/form-invalid-scroll.test.tsx @@ -63,6 +63,29 @@ function renderForm(fields: any[], defaultValues?: Record) { const submit = () => fireEvent.click(screen.getByRole('button', { name: /create/i })); describe('form renderer — invalid-submit feedback (#2793)', () => { + it('reveals its own field, not a same-named field a host drew into a form-slot row (objectstack#35889)', async () => { + // What a host draws there (an expanded line editor) is a form of its own. + const slotRef = (el: HTMLElement | null) => { + if (el && !el.firstChild) el.innerHTML = '
'; + }; + const { container } = renderForm([ + { name: '__form_slot__d0', label: '', type: 'form-slot', slotRef }, + { name: 'title', label: 'Title', type: 'input', required: true }, + ]); + const own = [...container.querySelectorAll('[data-field="title"]')].find((el) => !el.closest('[data-form-slot]'))!; + const ownScroll = vi.fn(); + own.scrollIntoView = ownScroll; + const slotted = container.querySelector('[data-form-slot] [data-field="title"]')!; + const slottedScroll = vi.fn(); + slotted.scrollIntoView = slottedScroll; + + submit(); + + await waitFor(() => expect(ownScroll).toHaveBeenCalled()); + expect(slottedScroll).not.toHaveBeenCalled(); + expect(document.activeElement).not.toBe(screen.getByTestId('line-title')); + }); + it('scrolls+focuses the first errored field on a missing required field, with no toast', async () => { const { container } = renderForm([ { name: 'title', label: 'Title', type: 'input', required: true }, diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index 92a86435651..e070436565a 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -3317,7 +3317,15 @@ ComponentRegistry.register('form', typeof CSS !== 'undefined' && typeof CSS.escape === 'function' ? CSS.escape(name) : name.replace(/["\\]/g, '\\$&'); - return root.querySelector(`[data-field="${escaped}"]`); + // Not a field a host drew into one of THIS form's `form-slot` rows (an + // expanded line editor there is a form of its own, objectstack#35889); + // that editor, inside a slot, still finds its own fields. + return ( + [...root.querySelectorAll(`[data-field="${escaped}"]`)].find((el) => { + const slot = el.closest('[data-form-slot]'); + return !slot || !(root as Node).contains(slot); + }) ?? null + ); }; const revealField = (name: string) => { const target = fieldWrapper(name); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx index 76425ea2866..d3187bf3cbb 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx @@ -70,7 +70,7 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje const totals = container.querySelector('[data-form-section="__section_totals"]')!; expect(header).toBeTruthy(); expect(totals).toBeTruthy(); - expect(placed.closest('form')).toBe(header.closest('form')); + expect(placed.closest('[data-form-slot]')!.closest('form')).toBe(header.closest('form')); expect(before(header, placed)).toBe(true); expect(before(placed, totals)).toBe(true); expect(placed.textContent).toContain('Order lines'); @@ -128,6 +128,28 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje expect(container.querySelectorAll('[data-testid="md-collection"]')).toHaveLength(1); }); + it('a placed collection\'s controls are not the header form\'s: no native validation, no submit from a line button', async () => { + const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP])); + const { container } = render( + , + ); + await waitFor(() => { + if (!container.querySelector('[data-form-slot] [data-testid="md-collection"] button')) throw new Error('not placed'); + }); + const header = container.querySelector('[data-form-section="__section_header"]')!.closest('form')!; + const slot = container.querySelector('[data-form-slot]')!; + const controls = [...slot.querySelectorAll('input, select, textarea, button')] as HTMLInputElement[]; + expect(controls.length).toBeGreaterThan(0); + // `requestSubmit()` validates, and a submit button submits, only the + // controls the form owns. + for (const control of controls) expect(control.form).not.toBe(header); + + const submitted = vi.fn(); + header.addEventListener('submit', submitted); + for (const button of slot.querySelectorAll('button')) fireEvent.click(button); + expect(submitted).not.toHaveBeenCalled(); + }); + it('saves the record and its lines in one batch from the placed table', async () => { const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }] }); const ds = makeDataSource(parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP]), { batchTransaction }); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 14efb55be34..9f2f520b80d 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -873,7 +873,17 @@ interface MasterDetailLinesProps { * element through a portal, in place when no drawn layout claims it, and * nowhere while a claimed slot's element is not mounted (objectstack#35889). * Its own component, so a slot landing re-renders only what it moves. + * + * The slot element sits inside the header's ``, so a portaled collection + * is wrapped in a form of its own: its controls then belong to that form, not + * the header's, exactly as they belonged to none below the form. The header's + * `requestSubmit()` validates only its own fields (a line cell's bad input + * never blocks Save with a browser bubble), a line button without a `type` + * submits only the wrapper, which does nothing, and Enter in a cell finds the + * wrapper's disabled default button and submits nothing. */ +const preventSubmit = (event: React.FormEvent) => event.preventDefault(); + const FormSlotPlacement: React.FC<{ store: FormSlotStore; id: string; children: React.ReactNode }> = ({ store, id, @@ -882,7 +892,14 @@ const FormSlotPlacement: React.FC<{ store: FormSlotStore; id: string; children: useSyncExternalStore(store.subscribe, store.getVersion, store.getVersion); const at = store.placement(id); if (at === 'inline') return <>{children}; - return at ? createPortal(children, at) : null; + if (!at) return null; + return createPortal( + +