diff --git a/.changeset/36019-placed-lines-form.md b/.changeset/36019-placed-lines-form.md new file mode 100644 index 00000000000..1a9670e562f --- /dev/null +++ b/.changeset/36019-placed-lines-form.md @@ -0,0 +1,14 @@ +--- +'@object-ui/plugin-form': patch +'@object-ui/components': patch +--- + +fix(ui): a placed line table's row editor is a form of its own, and a refused line marks its tab + +Clause-②: no +Metadata-protocol: none + +Two fixes to a master-detail entry form whose field group places the line table: + +- Opening a line's row editor no longer draws the editor's form inside the placed table's wrapper form. The markup is valid again, and React no longer logs "form cannot be a descendant of form" in development. The editor's inputs still belong to the editor's own form. +- In a tabbed form, a save the server refuses on a line marks the tab that holds the lines, the way a refused header field marks its own tab. A refusal is on the lines when the server names a line's operation as the failed one, or names a field that only the lines write. The mark clears when the next save gets past validation. diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index e070436565a..a641d4b6791 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -2757,8 +2757,16 @@ ComponentRegistry.register('form', const key = tabKeyByFieldName.get(name); if (key) out.add(key); } + // A host slot whose collection the last save was refused on + // (objectstack#35889's placed lines): the host owns that refusal, since + // no field of THIS form carries it, and says so on the slot row. + for (const f of fields as FormFieldConfig[]) { + if (f?.type !== 'form-slot' || !(f as { slotRefused?: boolean }).slotRefused) continue; + const key = tabKeyByFieldName.get(f.name); + if (key) out.add(key); + } return out; - }, [fieldTabs, tabKeyByFieldName, rejectedFieldNames]); + }, [fieldTabs, tabKeyByFieldName, rejectedFieldNames, fields]); // objectstack#34615 — below `sm` a horizontal tab strip that does not fit // scrolls sideways inside its own box (see the strip's classes) instead of 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 d3187bf3cbb..e3915f9388d 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx @@ -150,6 +150,43 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje expect(submitted).not.toHaveBeenCalled(); }); + it('an expanded row editor opens in the slot beside its collection, a form of its own, with no nesting warning', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}); + const parent = parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP]); + const child = { name: 'po_line', fields: { qty: { type: 'number', label: 'Qty' }, note: { type: 'text', label: 'Note' }, 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, note: 'n' }] : [] }), + ), + }); + const withEditor = [{ ...details[0], formFields: ['qty', 'note'] }]; + const { container } = render( + , + ); + const expand = await waitFor(() => { + const el = container.querySelector('[data-form-slot] [data-testid="line-items-expand-0"]') as HTMLElement | null; + if (!el) throw new Error('no expand in the placed collection'); + return el; + }); + fireEvent.click(expand); + const editor = await waitFor(() => { + const el = container.querySelector('[data-testid="md-row-form"]') as HTMLElement | null; + if (!el || !el.querySelector('input')) throw new Error('editor not open'); + return el; + }); + const header = container.querySelector('[data-form-section="__section_header"]')!.closest('form')!; + expect(editor.closest('[data-form-slot]')).toBe(container.querySelector('[data-form-slot]')); + for (const input of editor.querySelectorAll('input')) { + expect((input as HTMLInputElement).form).not.toBe(header); + expect(editor.contains((input as HTMLInputElement).form)).toBe(true); + } + const nesting = errors.mock.calls.filter((call) => /cannot be a descendant of|cannot contain a nested|validateDOMNesting/i.test(call.map(String).join(' '))); + expect(nesting).toEqual([]); + errors.mockRestore(); + }); + 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 }); @@ -196,3 +233,64 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje expect(label && document.getElementById(label)?.textContent?.trim()).toBe('Lines'); }); }); + +describe('MasterDetailForm — a refused save marks the tab of the placed lines it was refused on', () => { + const tabbed = { + objectName: 'po', + mode: 'edit', + recordId: 'po1', + formType: 'tabbed', + sections: [ + { name: 'header', label: 'Header', fields: ['ref'] }, + { name: 'totals', label: 'Totals', fields: ['memo'] }, + ], + details, + }; + const refusal = (field: string, failedOperation?: { index: number; object: string }) => + Object.assign(new Error(`${field} is not valid`), { + details: { code: 'VALIDATION_FAILED', fields: [{ field, message: `${field} is not valid` }], ...(failedOperation ? { failedOperation } : {}) }, + }); + + async function saveRefusedWith(err: Error) { + 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 batchTransaction = vi.fn().mockRejectedValue(err); + const ds = makeDataSource(parent, { + batchTransaction, + 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(); + const qty = await waitFor(() => { + const el = [...container.querySelectorAll('[data-form-slot] [data-testid="md-collection"] input')] + .find((input) => (input as HTMLInputElement).value === '3') as HTMLInputElement | undefined; + if (!el) throw new Error('lines not placed'); + return el; + }); + fireEvent.change(qty, { target: { value: '4' } }); + fireEvent.change(container.querySelector('input[name="ref"]') as HTMLInputElement, { target: { value: 'PO-8' } }); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(batchTransaction).toHaveBeenCalledTimes(1)); + return container; + } + + it('a field only a line writes: the lines tab is marked, the header tab is not', async () => { + await saveRefusedWith(refusal('qty')); + await waitFor(() => expect(screen.getByTestId('form-tab:lines').getAttribute('data-error')).toBe('true')); + expect(screen.getByTestId('form-tab:header').hasAttribute('data-error')).toBe(false); + }); + + it('the operation the server names as failed: a line op marks the lines tab', async () => { + await saveRefusedWith(refusal('anything', { index: 1, object: 'po_line' })); + await waitFor(() => expect(screen.getByTestId('form-tab:lines').getAttribute('data-error')).toBe('true')); + }); + + it('control: a refusal on the header\'s own field marks its tab and leaves the lines tab unmarked', async () => { + await saveRefusedWith(refusal('ref')); + await waitFor(() => expect(screen.getByTestId('form-tab:header').getAttribute('data-error')).toBe('true')); + expect(screen.getByTestId('form-tab:lines').hasAttribute('data-error')).toBe(false); + }); +}); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index b892cd7097f..632b58a14b7 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -45,7 +45,7 @@ import { useObjectTranslation, } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; -import { dataChangeMatches, subscribeDataChanges } from '@object-ui/react'; +import { dataChangeMatches, extractFieldErrors, subscribeDataChanges } from '@object-ui/react'; import { ObjectForm } from './ObjectForm'; import { applyColumnPermissions } from './fieldWriteGate'; import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate'; @@ -913,18 +913,49 @@ interface MasterDetailLinesProps { * 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. + * + * `ownsForm` says `children` already are a form of their own (an expanded row + * editor is an `ObjectForm`, its only other control a `type="button"`), so no + * wrapper is drawn: a form inside a form is a nesting React refuses. */ const preventSubmit = (event: React.FormEvent) => event.preventDefault(); -const FormSlotPlacement: React.FC<{ store: FormSlotStore; id: string; children: React.ReactNode }> = ({ - store, - id, - children, -}) => { +/** + * The child objects a refused batch was refused on, presented from the + * refusal and never re-derived (the record page's `attributeRecordEditRefusal` + * reads the same evidence): the operation the server names as the failed one, + * else each field it names that only line operations write (a field the + * parent's own operation carries is the header form's to mark). The parent is + * operation 0 in both batch builders. A refusal that names neither, a lock or + * a permission denial, is on no collection. + */ +function refusedChildObjects(err: unknown, ops: readonly BatchTransactionOperation[]): Set { + const out = new Set(); + const failed = (err as { details?: { failedOperation?: { index?: unknown } } } | null)?.details?.failedOperation?.index; + if (typeof failed === 'number') { + if (failed > 0 && ops[failed]?.object) out.add(ops[failed].object); + return out; + } + const carries = (op: BatchTransactionOperation | undefined, field: string) => + !!op && op.action !== 'delete' && !!op.data && Object.prototype.hasOwnProperty.call(op.data, field); + for (const { field } of extractFieldErrors(err) ?? []) { + if (carries(ops[0], field)) continue; + for (const op of ops.slice(1)) if (carries(op, field)) out.add(op.object); + } + return out; +} + +const FormSlotPlacement: React.FC<{ + store: FormSlotStore; + id: string; + ownsForm?: boolean; + children: React.ReactNode; +}> = ({ store, id, ownsForm = false, children }) => { useSyncExternalStore(store.subscribe, store.getVersion, store.getVersion); const at = store.placement(id); if (at === 'inline') return <>{children}; if (!at) return null; + if (ownsForm) return createPortal(children, at); return createPortal(