Skip to content

Commit 9ac514e

Browse files
committed
fix(plugin-form): a save refused on placed lines marks the tab that holds them
In a tabbed master-detail form a group-placed line table lives in a tab of its own. A batch the server refuses on a line (the failed operation is a line's, or the refused field is one only the lines write) now marks that tab the way a refused header field marks its own: the slot store records the refused collections, the tabbed form rebuilds its slot rows from it, and the form renderer marks the tab of a refused slot row. The mark retires when the next save gets past validation. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L6bhgW85kwjGaz7HqsmEuv
1 parent 67f8e56 commit 9ac514e

7 files changed

Lines changed: 181 additions & 8 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/plugin-form': patch
3+
'@object-ui/components': patch
4+
---
5+
6+
fix(ui): a placed line table's row editor is a form of its own, and a refused line marks its tab
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
Two fixes to a master-detail entry form whose field group places the line table:
12+
13+
- 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.
14+
- 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.

‎ui/packages/components/src/renderers/form/form.tsx‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2757,8 +2757,16 @@ ComponentRegistry.register('form',
27572757
const key = tabKeyByFieldName.get(name);
27582758
if (key) out.add(key);
27592759
}
2760+
// A host slot whose collection the last save was refused on
2761+
// (objectstack#35889's placed lines): the host owns that refusal, since
2762+
// no field of THIS form carries it, and says so on the slot row.
2763+
for (const f of fields as FormFieldConfig[]) {
2764+
if (f?.type !== 'form-slot' || !(f as { slotRefused?: boolean }).slotRefused) continue;
2765+
const key = tabKeyByFieldName.get(f.name);
2766+
if (key) out.add(key);
2767+
}
27602768
return out;
2761-
}, [fieldTabs, tabKeyByFieldName, rejectedFieldNames]);
2769+
}, [fieldTabs, tabKeyByFieldName, rejectedFieldNames, fields]);
27622770

27632771
// objectstack#34615 — below `sm` a horizontal tab strip that does not fit
27642772
// scrolls sideways inside its own box (see the strip's classes) instead of

‎ui/packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,3 +233,64 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje
233233
expect(label && document.getElementById(label)?.textContent?.trim()).toBe('Lines');
234234
});
235235
});
236+
237+
describe('MasterDetailForm — a refused save marks the tab of the placed lines it was refused on', () => {
238+
const tabbed = {
239+
objectName: 'po',
240+
mode: 'edit',
241+
recordId: 'po1',
242+
formType: 'tabbed',
243+
sections: [
244+
{ name: 'header', label: 'Header', fields: ['ref'] },
245+
{ name: 'totals', label: 'Totals', fields: ['memo'] },
246+
],
247+
details,
248+
};
249+
const refusal = (field: string, failedOperation?: { index: number; object: string }) =>
250+
Object.assign(new Error(`${field} is not valid`), {
251+
details: { code: 'VALIDATION_FAILED', fields: [{ field, message: `${field} is not valid` }], ...(failedOperation ? { failedOperation } : {}) },
252+
});
253+
254+
async function saveRefusedWith(err: Error) {
255+
const parent = parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP]);
256+
const child = { name: 'po_line', fields: { qty: { type: 'number', label: 'Qty' }, po: { type: 'master_detail', label: 'PO', reference: 'po' } } };
257+
const batchTransaction = vi.fn().mockRejectedValue(err);
258+
const ds = makeDataSource(parent, {
259+
batchTransaction,
260+
getObjectSchema: vi.fn(async (object: string) => (object === 'po_line' ? child : parent)),
261+
findOne: vi.fn().mockResolvedValue({ id: 'po1', ref: 'PO-7', memo: 'm' }),
262+
find: vi.fn().mockImplementation((object: string) =>
263+
Promise.resolve({ data: object === 'po_line' ? [{ id: 'l1', po: 'po1', qty: 3 }] : [] }),
264+
),
265+
});
266+
const { container } = render(<MasterDetailForm schema={tabbed as any} dataSource={ds} />);
267+
const qty = await waitFor(() => {
268+
const el = [...container.querySelectorAll('[data-form-slot] [data-testid="md-collection"] input')]
269+
.find((input) => (input as HTMLInputElement).value === '3') as HTMLInputElement | undefined;
270+
if (!el) throw new Error('lines not placed');
271+
return el;
272+
});
273+
fireEvent.change(qty, { target: { value: '4' } });
274+
fireEvent.change(container.querySelector('input[name="ref"]') as HTMLInputElement, { target: { value: 'PO-8' } });
275+
fireEvent.click(screen.getByTestId('md-form-submit'));
276+
await waitFor(() => expect(batchTransaction).toHaveBeenCalledTimes(1));
277+
return container;
278+
}
279+
280+
it('a field only a line writes: the lines tab is marked, the header tab is not', async () => {
281+
await saveRefusedWith(refusal('qty'));
282+
await waitFor(() => expect(screen.getByTestId('form-tab:lines').getAttribute('data-error')).toBe('true'));
283+
expect(screen.getByTestId('form-tab:header').hasAttribute('data-error')).toBe(false);
284+
});
285+
286+
it('the operation the server names as failed: a line op marks the lines tab', async () => {
287+
await saveRefusedWith(refusal('anything', { index: 1, object: 'po_line' }));
288+
await waitFor(() => expect(screen.getByTestId('form-tab:lines').getAttribute('data-error')).toBe('true'));
289+
});
290+
291+
it('control: a refusal on the header\'s own field marks its tab and leaves the lines tab unmarked', async () => {
292+
await saveRefusedWith(refusal('ref'));
293+
await waitFor(() => expect(screen.getByTestId('form-tab:header').getAttribute('data-error')).toBe('true'));
294+
expect(screen.getByTestId('form-tab:lines').hasAttribute('data-error')).toBe(false);
295+
});
296+
});

‎ui/packages/plugin-form/src/MasterDetailForm.tsx‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ import {
4545
useObjectTranslation,
4646
} from '@object-ui/i18n';
4747
import { usePermissions } from '@object-ui/permissions';
48-
import { dataChangeMatches, subscribeDataChanges } from '@object-ui/react';
48+
import { dataChangeMatches, extractFieldErrors, subscribeDataChanges } from '@object-ui/react';
4949
import { ObjectForm } from './ObjectForm';
5050
import { applyColumnPermissions } from './fieldWriteGate';
5151
import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate';
@@ -920,6 +920,31 @@ interface MasterDetailLinesProps {
920920
*/
921921
const preventSubmit = (event: React.FormEvent) => event.preventDefault();
922922

923+
/**
924+
* The child objects a refused batch was refused on, presented from the
925+
* refusal and never re-derived (the record page's `attributeRecordEditRefusal`
926+
* reads the same evidence): the operation the server names as the failed one,
927+
* else each field it names that only line operations write (a field the
928+
* parent's own operation carries is the header form's to mark). The parent is
929+
* operation 0 in both batch builders. A refusal that names neither, a lock or
930+
* a permission denial, is on no collection.
931+
*/
932+
function refusedChildObjects(err: unknown, ops: readonly BatchTransactionOperation[]): Set<string> {
933+
const out = new Set<string>();
934+
const failed = (err as { details?: { failedOperation?: { index?: unknown } } } | null)?.details?.failedOperation?.index;
935+
if (typeof failed === 'number') {
936+
if (failed > 0 && ops[failed]?.object) out.add(ops[failed].object);
937+
return out;
938+
}
939+
const carries = (op: BatchTransactionOperation | undefined, field: string) =>
940+
!!op && op.action !== 'delete' && !!op.data && Object.prototype.hasOwnProperty.call(op.data, field);
941+
for (const { field } of extractFieldErrors(err) ?? []) {
942+
if (carries(ops[0], field)) continue;
943+
for (const op of ops.slice(1)) if (carries(op, field)) out.add(op.object);
944+
}
945+
return out;
946+
}
947+
923948
const FormSlotPlacement: React.FC<{
924949
store: FormSlotStore;
925950
id: string;
@@ -2142,7 +2167,15 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
21422167
childSchema: childSchemasRef.current[e.config.childObject],
21432168
})),
21442169
);
2145-
const res = await runBatchTransaction(dataSource, ops);
2170+
let res: Awaited<ReturnType<typeof runBatchTransaction>>;
2171+
try {
2172+
res = await runBatchTransaction(dataSource, ops);
2173+
} catch (err) {
2174+
// A refusal on a placed collection marks the tab that holds it.
2175+
const refused = refusedChildObjects(err, ops);
2176+
slotStore.refuse(entries.filter((e) => refused.has(e.config.childObject)).map((e) => e.id));
2177+
throw err;
2178+
}
21462179
// The batch COMMITTED: advance the child rows' baseline from it, so a
21472180
// form that stays mounted diffs its next save against what this one
21482181
// wrote (objectui#10564). The parent's baseline advances in the header
@@ -2184,7 +2217,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
21842217
// create → parent is op 0; edit → echo the parent values back.
21852218
return res?.results?.[0] ?? { ...parentData, id: schema.recordId };
21862219
},
2187-
[dataSource, entries, schema.objectName, schema.recordId, isEdit],
2220+
[dataSource, entries, schema.objectName, schema.recordId, isEdit, slotStore],
21882221
);
21892222

21902223
/**
@@ -2206,6 +2239,8 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
22062239
}
22072240
batchInFlightRef.current = true;
22082241
setSaveTried(true);
2242+
// Past validation: the last refusal's marks retire, as the form's own do.
2243+
slotStore.refuse([]);
22092244
holdSaveForBatch();
22102245
try {
22112246
return await sendBatch(parentValues);
@@ -2215,7 +2250,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
22152250
batchInFlightRef.current = false;
22162251
}
22172252
},
2218-
[sendBatch, holdSaveForBatch],
2253+
[sendBatch, holdSaveForBatch, slotStore],
22192254
);
22202255

22212256
// The parent form renders WITHOUT its own submit button — the master-detail

‎ui/packages/plugin-form/src/TabbedForm.tsx‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
* Aligns with @objectstack/spec FormView type: 'tabbed'
1414
*/
1515

16-
import React, { useState, useCallback, useRef, useEffect, useMemo } from 'react';
16+
import React, { useState, useCallback, useRef, useEffect, useMemo, useSyncExternalStore } from 'react';
1717
import type { FormField, FormSchema, DataSource, ObjectFormSchema, ObjectFormSection } from '@object-ui/types';
1818
import { cn, toast } from '@object-ui/components';
1919
import { useLocalization } from '@object-ui/i18n';
@@ -271,6 +271,10 @@ export interface TabbedFormProps {
271271
className?: string;
272272
}
273273

274+
/** The refusal snapshot of a form no host places collections in. */
275+
const noSlotHostSubscribe = (): (() => void) => () => {};
276+
const noSlotRefusal = (): string => '';
277+
274278
/**
275279
* TabbedForm Component
276280
*
@@ -608,6 +612,14 @@ export const TabbedForm: React.FC<TabbedFormProps> = ({
608612
if (slotClaim === null || !slotHost) return;
609613
slotHost.claim(slotClaim ? slotClaim.split('\n') : []);
610614
}, [slotClaim, slotHost]);
615+
// A save refused on a placed collection marks the tab that holds it, as a
616+
// refused field marks its own tab: the slot rows are rebuilt when the
617+
// host's refusal moves.
618+
useSyncExternalStore(
619+
slotHost ? slotHost.subscribe : noSlotHostSubscribe,
620+
slotHost ? slotHost.refusedKey : noSlotRefusal,
621+
slotHost ? slotHost.refusedKey : noSlotRefusal,
622+
);
611623

612624
// Generate tab value
613625
const getTabValue = (section: FormSectionConfig, index: number): string => {

‎ui/packages/plugin-form/src/formSlots.test.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, it, expect, vi } from 'vitest';
2-
import { FormSlotStore, formSlotGroupIndex, placeFormSlots, type FormSlotRequest } from './formSlots';
2+
import { FormSlotStore, formSlotGroupIndex, formSlotRow, placeFormSlots, type FormSlotRequest } from './formSlots';
33

44
// objectstack#35889 — a collection a field group places sits at that group in
55
// the header form, by the record page's rule (`bodyTablePlacement`).
@@ -82,4 +82,19 @@ describe('FormSlotStore (objectstack#35889)', () => {
8282
store.claim(['d0']);
8383
expect(store.getVersion()).toBe(v);
8484
});
85+
86+
it('a refusal on a collection marks its slot row until it is retired, and an equal refusal changes nothing', () => {
87+
const store = new FormSlotStore();
88+
const request = { id: 'd0', childObject: 'po_line' };
89+
expect(formSlotRow(request, store).slotRefused).toBeUndefined();
90+
store.refuse(['d0', 'd0']);
91+
expect(formSlotRow(request, store).slotRefused).toBe(true);
92+
expect(formSlotRow({ id: 'd1', childObject: 'po_line' }, store).slotRefused).toBeUndefined();
93+
const v = store.getVersion();
94+
store.refuse(['d0']);
95+
expect(store.getVersion()).toBe(v);
96+
store.refuse([]);
97+
expect(formSlotRow(request, store).slotRefused).toBeUndefined();
98+
expect(store.getVersion()).toBe(v + 1);
99+
});
85100
});

‎ui/packages/plugin-form/src/formSlots.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,17 @@ export interface FormSlotRequest {
4747
* is called once per drawn layout (`[]` when it places none), never while the
4848
* form is still loading — so a remounting header keeps the previous claim and
4949
* the collections do not jump below the form and back.
50+
*
51+
* `refusedKey()` names the collections the last refused save was refused on
52+
* (one id per line, `''` for none), and `subscribe` tells a layout that it
53+
* moved: a tabbed form marks the tab that holds such a collection, as it
54+
* marks the tab of a refused field.
5055
*/
5156
export interface FormSlotHost {
5257
refFor(id: string): (el: HTMLElement | null) => void;
5358
claim(ids: readonly string[]): void;
59+
refusedKey(): string;
60+
subscribe(listener: () => void): () => void;
5461
}
5562

5663
/** The hand-off key a host sets on the header form's schema. */
@@ -137,19 +144,25 @@ export function placeFormSlots<S>(
137144
* by the form renderer's `form-slot` branch; like a divider row's `onToggle`
138145
* it is written by the host and never authored, so it stays off `FormField`.
139146
*/
140-
export type FormSlotRow = FormField & { slotRef: (el: HTMLElement | null) => void };
147+
export type FormSlotRow = FormField & {
148+
slotRef: (el: HTMLElement | null) => void;
149+
/** The last save was refused on this collection: its tab is marked. */
150+
slotRefused?: true;
151+
};
141152

142153
/**
143154
* The row a placed collection takes in the header form's field list. A
144155
* `label` (its group's) makes the row a stop of the form's section
145156
* navigation, between the headings it sits between.
146157
*/
147158
export function formSlotRow(request: FormSlotRequest, host: FormSlotHost, label = ''): FormSlotRow {
159+
const refused = host.refusedKey().split('\n').includes(request.id);
148160
return {
149161
name: `__form_slot__${request.id}`,
150162
label,
151163
type: FORM_SLOT_ROW_TYPE,
152164
slotRef: host.refFor(request.id),
165+
...(refused ? { slotRefused: true } : {}),
153166
} as FormSlotRow;
154167
}
155168

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

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

204+
/**
205+
* The collections the last refused save was refused on; `[]` when a save
206+
* gets past validation, so a mark lasts exactly as long as a refused
207+
* field's.
208+
*/
209+
refuse(ids: readonly string[]): void {
210+
const key = [...new Set(ids)].sort().join('\n');
211+
if (key === this.refused) return;
212+
this.refused = key;
213+
this.emit();
214+
}
215+
216+
refusedKey = (): string => this.refused;
217+
190218
/**
191219
* Where the host draws collection `id`: `'inline'` (no layout has claimed
192220
* it: in the host's own place), the slot element, or `null` (claimed, its

0 commit comments

Comments
 (0)