Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/36019-placed-lines-form.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 9 additions & 1 deletion ui/packages/components/src/renderers/form/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<MasterDetailForm schema={{ objectName: 'po', mode: 'edit', recordId: 'po1', details: withEditor } as any} dataSource={ds} />,
);
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 });
Expand Down Expand Up @@ -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(<MasterDetailForm schema={tabbed as any} dataSource={ds} />);
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);
});
});
61 changes: 51 additions & 10 deletions ui/packages/plugin-form/src/MasterDetailForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string> {
const out = new Set<string>();
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(
<form noValidate onSubmit={preventSubmit} data-form-slot-owner="">
<button type="submit" disabled hidden aria-hidden="true" tabIndex={-1} />
Expand Down Expand Up @@ -2136,7 +2167,15 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
childSchema: childSchemasRef.current[e.config.childObject],
})),
);
const res = await runBatchTransaction(dataSource, ops);
let res: Awaited<ReturnType<typeof runBatchTransaction>>;
try {
res = await runBatchTransaction(dataSource, ops);
} catch (err) {
// A refusal on a placed collection marks the tab that holds it.
const refused = refusedChildObjects(err, ops);
slotStore.refuse(entries.filter((e) => refused.has(e.config.childObject)).map((e) => e.id));
throw err;
}
// The batch COMMITTED: advance the child rows' baseline from it, so a
// form that stays mounted diffs its next save against what this one
// wrote (objectui#10564). The parent's baseline advances in the header
Expand Down Expand Up @@ -2178,7 +2217,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
// create → parent is op 0; edit → echo the parent values back.
return res?.results?.[0] ?? { ...parentData, id: schema.recordId };
},
[dataSource, entries, schema.objectName, schema.recordId, isEdit],
[dataSource, entries, schema.objectName, schema.recordId, isEdit, slotStore],
);

/**
Expand All @@ -2200,6 +2239,8 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
}
batchInFlightRef.current = true;
setSaveTried(true);
// Past validation: the last refusal's marks retire, as the form's own do.
slotStore.refuse([]);
holdSaveForBatch();
try {
return await sendBatch(parentValues);
Expand All @@ -2209,7 +2250,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
batchInFlightRef.current = false;
}
},
[sendBatch, holdSaveForBatch],
[sendBatch, holdSaveForBatch, slotStore],
);

// The parent form renders WITHOUT its own submit button — the master-detail
Expand Down Expand Up @@ -2384,7 +2425,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
everything on the parent Save. */}
{expanded && expandedDetail && (
// Beside its collection: where the header placed that collection, there.
<FormSlotPlacement store={slotStore} id={expanded.entryId}>
<FormSlotPlacement store={slotStore} id={expanded.entryId} ownsForm>
<Card className="border-primary/40 shadow-none ring-1 ring-primary/10" data-testid="md-row-form">
<CardHeader className="pb-2 flex flex-row items-center justify-between gap-2 space-y-0">
<CardTitle className="text-sm font-medium">
Expand Down
14 changes: 13 additions & 1 deletion ui/packages/plugin-form/src/TabbedForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* Aligns with @objectstack/spec FormView type: 'tabbed'
*/

import React, { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import React, { useState, useCallback, useRef, useEffect, useMemo, useSyncExternalStore } 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';
Expand Down Expand Up @@ -271,6 +271,10 @@ export interface TabbedFormProps {
className?: string;
}

/** The refusal snapshot of a form no host places collections in. */
const noSlotHostSubscribe = (): (() => void) => () => {};
const noSlotRefusal = (): string => '';

/**
* TabbedForm Component
*
Expand Down Expand Up @@ -608,6 +612,14 @@ export const TabbedForm: React.FC<TabbedFormProps> = ({
if (slotClaim === null || !slotHost) return;
slotHost.claim(slotClaim ? slotClaim.split('\n') : []);
}, [slotClaim, slotHost]);
// A save refused on a placed collection marks the tab that holds it, as a
// refused field marks its own tab: the slot rows are rebuilt when the
// host's refusal moves.
useSyncExternalStore(
slotHost ? slotHost.subscribe : noSlotHostSubscribe,
slotHost ? slotHost.refusedKey : noSlotRefusal,
slotHost ? slotHost.refusedKey : noSlotRefusal,
);

// Generate tab value
const getTabValue = (section: FormSectionConfig, index: number): string => {
Expand Down
17 changes: 16 additions & 1 deletion ui/packages/plugin-form/src/formSlots.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
import { FormSlotStore, formSlotGroupIndex, placeFormSlots, type FormSlotRequest } from './formSlots';
import { FormSlotStore, formSlotGroupIndex, formSlotRow, 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`).
Expand Down Expand Up @@ -82,4 +82,19 @@ describe('FormSlotStore (objectstack#35889)', () => {
store.claim(['d0']);
expect(store.getVersion()).toBe(v);
});

it('a refusal on a collection marks its slot row until it is retired, and an equal refusal changes nothing', () => {
const store = new FormSlotStore();
const request = { id: 'd0', childObject: 'po_line' };
expect(formSlotRow(request, store).slotRefused).toBeUndefined();
store.refuse(['d0', 'd0']);
expect(formSlotRow(request, store).slotRefused).toBe(true);
expect(formSlotRow({ id: 'd1', childObject: 'po_line' }, store).slotRefused).toBeUndefined();
const v = store.getVersion();
store.refuse(['d0']);
expect(store.getVersion()).toBe(v);
store.refuse([]);
expect(formSlotRow(request, store).slotRefused).toBeUndefined();
expect(store.getVersion()).toBe(v + 1);
});
});
30 changes: 29 additions & 1 deletion ui/packages/plugin-form/src/formSlots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,17 @@ export interface FormSlotRequest {
* 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.
*
* `refusedKey()` names the collections the last refused save was refused on
* (one id per line, `''` for none), and `subscribe` tells a layout that it
* moved: a tabbed form marks the tab that holds such a collection, as it
* marks the tab of a refused field.
*/
export interface FormSlotHost {
refFor(id: string): (el: HTMLElement | null) => void;
claim(ids: readonly string[]): void;
refusedKey(): string;
subscribe(listener: () => void): () => void;
}

/** The hand-off key a host sets on the header form's schema. */
Expand Down Expand Up @@ -137,19 +144,25 @@ export function placeFormSlots<S>(
* 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 };
export type FormSlotRow = FormField & {
slotRef: (el: HTMLElement | null) => void;
/** The last save was refused on this collection: its tab is marked. */
slotRefused?: true;
};

/**
* 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 {
const refused = host.refusedKey().split('\n').includes(request.id);
return {
name: `__form_slot__${request.id}`,
label,
type: FORM_SLOT_ROW_TYPE,
slotRef: host.refFor(request.id),
...(refused ? { slotRefused: true } : {}),
} as FormSlotRow;
}

Expand All @@ -163,6 +176,7 @@ export class FormSlotStore implements FormSlotHost {
private readonly elements = new Map<string, HTMLElement>();
private readonly refs = new Map<string, (el: HTMLElement | null) => void>();
private claimed: ReadonlySet<string> | null = null;
private refused = '';
private readonly listeners = new Set<() => void>();
private version = 0;

Expand All @@ -187,6 +201,20 @@ export class FormSlotStore implements FormSlotHost {
this.emit();
}

/**
* The collections the last refused save was refused on; `[]` when a save
* gets past validation, so a mark lasts exactly as long as a refused
* field's.
*/
refuse(ids: readonly string[]): void {
const key = [...new Set(ids)].sort().join('\n');
if (key === this.refused) return;
this.refused = key;
this.emit();
}

refusedKey = (): string => this.refused;

/**
* 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
Expand Down
Loading