Skip to content

Commit baf2678

Browse files
fix(plugin-form): a placed row editor is not nested in a form, and a save refused on placed lines marks their tab (#36088)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuVwX4pUdM1qvNLSqRZNSvv3)_ Fixes #36019 Clause-②: no Metadata-protocol: none Skills-docs: none — no authorable key and no behaviour a skill teaches moves repo:objectstack#1 · os-sales · session_01L6bhgW85kwjGaz7HqsmEuv ## 维护者速读 - 用户能看到什么变化:在“表头加明细”的录入表单里,明细表放在某个字段分组处时,展开一行明细编辑不再在开发控制台报“表单嵌套表单”的警告;分页签的表单里,保存被服务器以某一行明细为由拒绝时,明细所在的页签会像表头字段出错时一样标红点。 - 为什么做:这是“明细表放在字段分组处”那项工作(主从表单布局)评审时留下的两条收尾意见,补上明细出错时用户找不到原因的缺口。 - 出错会怎样:最坏情况是明细页签该标红没标、或多标了一个页签,保存本身照旧被拒、数据不会写错;整个改动可直接撤回。 - 要你做什么:无 ## What changes 1. **Row editor in a placed slot (N2 of the L2 record on #36009).** `FormSlotPlacement` takes `ownsForm`: when its children already are a form of their own, it portals them into the slot with no wrapper form. The expanded row editor (an `ObjectForm`, its only other control a `type="button"`) is placed with `ownsForm`, so its form is no longer a React child of the slot's wrapper form, and React's DOM-nesting check stops logging "form cannot be a descendant of form". This is the measured S2 patch, re-applied on main (`git apply --check` clean, offsets +24/+78). 2. **Tab marker for a refused line (N3 of the L2 record, L1-c's nit).** A batch refusal is attributed to the placed collections it was refused on, using the same evidence the record page's `attributeRecordEditRefusal` reads: the operation the server names in `details.failedOperation.index` when it names one (a line's operation, never operation 0, the parent), else each field in `fields[]` that only line operations write. A field the parent operation carries stays the header form's to mark. `FormSlotStore` records those collection ids (`refuse(ids)`, cleared when the next save gets past validation, as the renderer clears its own markers). `TabbedForm` subscribes to the store and rebuilds its slot rows, each carrying `slotRefused` when its collection was refused. The form renderer's `erroredFieldTabs` marks the tab of a refused slot row with the treatment a refused header field gets (`data-error`, destructive text, the dot). No export, prop or i18n key is added. `FormSlotHost` and `FormSlotRow` live in `formSlots.ts`, which `@object-ui/plugin-form` does not export. The renderer reads `slotRefused` off a `form-slot` row the same way it reads `slotRef`: a key only a host can produce. ## Tests - `MasterDetailForm.groupPlacement-35889.test.tsx`, existing describe: an expanded row editor opens in the slot beside its collection, its inputs are owned by its own form, and no nesting warning is logged. - Same file, new top-level describe (a refused save marks the tab of the placed lines it was refused on): a field only a line writes marks the lines tab and not the header tab; a server-named failed line operation marks the lines tab; control: a refusal on the header's own field marks its tab and leaves the lines tab unmarked. - `formSlots.test.ts`: `refuse` marks the slot row until retired, de-duplicates, and an equal refusal emits nothing. All readings at head `9ac514e3`. <details><summary>Suites and type-check</summary> - `pnpm exec vitest run --maxWorkers=2 packages/plugin-form/ packages/components/src/renderers/form/` (from `ui/`, under the verify lock): `Test Files 332 passed (332)`, `Tests 3359 passed | 18 skipped (3377)`, `VERDICT command-exit 0`. - `pnpm --filter @object-ui/plugin-form --filter @object-ui/components run type-check` (both run `tsc --noEmit && tsc -p tsconfig.test.json`): `VERDICT command-exit 0`. - `eslint` over the six changed source and test files: 0 errors (106 warnings, all on lines this diff does not touch). </details> <details><summary>Ablations (one per fix, through `scripts/ablation-replace.mjs`, restore proven)</summary> - Fix 1: `ownsForm` removed from the row editor's placement (anchor 1 to 0, blob `632b58a14b7d` to `f73ce79e3a8b`). The nesting pin goes red with React's own message, "In HTML, a FORM cannot be a descendant of a FORM" (its DOM-nesting check); `Tests 1 failed | 10 passed (11)`. Restored: blob equals HEAD (`632b58a14b7d`), `git diff HEAD` empty. This mutation is the code on `main`, so the pin fails on `main` and passes with the fix. - Fix 2: the `slotStore.refuse(...)` call in `sendBatch`'s catch deleted (anchor 1 to 0, blob to `2e2969a6db0b`). Both tab pins go red, and the control (a header-field refusal) stays green; `Tests 2 failed | 9 passed (11)`. Restored: blob equals HEAD, `git diff HEAD` empty. </details> <details><summary>Derived gate families</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 38 commands. Every one exited 0. `--ran` reconciliation: "38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED (a DERIVED zero — all 38 recorded an exit code and none of them is 3)". The type-check lanes, artifact rosters and wide-population families are CI's. </details> <details><summary>Overlap</summary> `node scripts/pm/overlap-check.mjs --branch=HEAD --pr=36039,36054`: origin/main, #36039 and #36054 each merge cleanly, `VERDICT clean exit 0`. </details> ## Acceptance notes - The marker is the whole of the header-field treatment that applies here. A refused header field also activates its tab and focuses the field; a refused line does not switch tabs, because the renderer's catch runs before the host's refusal reaches the tab rows, and the lines show no per-row reason today (the master-detail form shows the refusal as the form's banner, as before). The acceptance names the marker only. - A refusal that names neither a failed operation nor a field (a lock, a permission denial) is on no collection, and marks nothing, as before. - File surface beyond the claim's wording: the tab marker is drawn by the form renderer (`ui/packages/components/src/renderers/form/form.tsx`), not by `TabbedForm`, and the refusal travels through `formSlots.ts`. Both are named here. - The editor's form still sits inside the header's form in the DOM (the slot element is inside it), as the lines' wrapper form already did; ownership is answered by the innermost form, which the pin asserts. ## Verification Two-minute check: `pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-form/src/MasterDetailForm.groupPlacement-35889.test.tsx`: expect 11 tests passed. Read first: (1) `MasterDetailForm.tsx` `refusedChildObjects` and its call in `sendBatch` (which refusals count as a line's); (2) `form.tsx` `erroredFieldTabs` (the renderer's new read); (3) `TabbedForm.tsx` the `useSyncExternalStore` on the slot host. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgW85kwjGaz7HqsmEuv --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c59ee99 commit baf2678

7 files changed

Lines changed: 230 additions & 14 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: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,43 @@ describe('MasterDetailForm — a group-placed collection sits at its group (obje
150150
expect(submitted).not.toHaveBeenCalled();
151151
});
152152

153+
it('an expanded row editor opens in the slot beside its collection, a form of its own, with no nesting warning', async () => {
154+
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
155+
const parent = parentWith([HEADER_GROUP, LINES_GROUP, TOTALS_GROUP]);
156+
const child = { name: 'po_line', fields: { qty: { type: 'number', label: 'Qty' }, note: { type: 'text', label: 'Note' }, po: { type: 'master_detail', label: 'PO', reference: 'po' } } };
157+
const ds = makeDataSource(parent, {
158+
getObjectSchema: vi.fn(async (object: string) => (object === 'po_line' ? child : parent)),
159+
findOne: vi.fn().mockResolvedValue({ id: 'po1', ref: 'PO-7', memo: 'm' }),
160+
find: vi.fn().mockImplementation((object: string) =>
161+
Promise.resolve({ data: object === 'po_line' ? [{ id: 'l1', po: 'po1', qty: 3, note: 'n' }] : [] }),
162+
),
163+
});
164+
const withEditor = [{ ...details[0], formFields: ['qty', 'note'] }];
165+
const { container } = render(
166+
<MasterDetailForm schema={{ objectName: 'po', mode: 'edit', recordId: 'po1', details: withEditor } as any} dataSource={ds} />,
167+
);
168+
const expand = await waitFor(() => {
169+
const el = container.querySelector('[data-form-slot] [data-testid="line-items-expand-0"]') as HTMLElement | null;
170+
if (!el) throw new Error('no expand in the placed collection');
171+
return el;
172+
});
173+
fireEvent.click(expand);
174+
const editor = await waitFor(() => {
175+
const el = container.querySelector('[data-testid="md-row-form"]') as HTMLElement | null;
176+
if (!el || !el.querySelector('input')) throw new Error('editor not open');
177+
return el;
178+
});
179+
const header = container.querySelector('[data-form-section="__section_header"]')!.closest('form')!;
180+
expect(editor.closest('[data-form-slot]')).toBe(container.querySelector('[data-form-slot]'));
181+
for (const input of editor.querySelectorAll('input')) {
182+
expect((input as HTMLInputElement).form).not.toBe(header);
183+
expect(editor.contains((input as HTMLInputElement).form)).toBe(true);
184+
}
185+
const nesting = errors.mock.calls.filter((call) => /cannot be a descendant of|cannot contain a nested|validateDOMNesting/i.test(call.map(String).join(' ')));
186+
expect(nesting).toEqual([]);
187+
errors.mockRestore();
188+
});
189+
153190
it('saves the record and its lines in one batch from the placed table', async () => {
154191
const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }] });
155192
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
196233
expect(label && document.getElementById(label)?.textContent?.trim()).toBe('Lines');
197234
});
198235
});
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: 51 additions & 10 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';
@@ -913,18 +913,49 @@ interface MasterDetailLinesProps {
913913
* never blocks Save with a browser bubble), a line button without a `type`
914914
* submits only the wrapper, which does nothing, and Enter in a cell finds the
915915
* wrapper's disabled default button and submits nothing.
916+
*
917+
* `ownsForm` says `children` already are a form of their own (an expanded row
918+
* editor is an `ObjectForm`, its only other control a `type="button"`), so no
919+
* wrapper is drawn: a form inside a form is a nesting React refuses.
916920
*/
917921
const preventSubmit = (event: React.FormEvent) => event.preventDefault();
918922

919-
const FormSlotPlacement: React.FC<{ store: FormSlotStore; id: string; children: React.ReactNode }> = ({
920-
store,
921-
id,
922-
children,
923-
}) => {
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+
948+
const FormSlotPlacement: React.FC<{
949+
store: FormSlotStore;
950+
id: string;
951+
ownsForm?: boolean;
952+
children: React.ReactNode;
953+
}> = ({ store, id, ownsForm = false, children }) => {
924954
useSyncExternalStore(store.subscribe, store.getVersion, store.getVersion);
925955
const at = store.placement(id);
926956
if (at === 'inline') return <>{children}</>;
927957
if (!at) return null;
958+
if (ownsForm) return createPortal(children, at);
928959
return createPortal(
929960
<form noValidate onSubmit={preventSubmit} data-form-slot-owner="">
930961
<button type="submit" disabled hidden aria-hidden="true" tabIndex={-1} />
@@ -2136,7 +2167,15 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
21362167
childSchema: childSchemasRef.current[e.config.childObject],
21372168
})),
21382169
);
2139-
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+
}
21402179
// The batch COMMITTED: advance the child rows' baseline from it, so a
21412180
// form that stays mounted diffs its next save against what this one
21422181
// wrote (objectui#10564). The parent's baseline advances in the header
@@ -2178,7 +2217,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
21782217
// create → parent is op 0; edit → echo the parent values back.
21792218
return res?.results?.[0] ?? { ...parentData, id: schema.recordId };
21802219
},
2181-
[dataSource, entries, schema.objectName, schema.recordId, isEdit],
2220+
[dataSource, entries, schema.objectName, schema.recordId, isEdit, slotStore],
21822221
);
21832222

21842223
/**
@@ -2200,6 +2239,8 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
22002239
}
22012240
batchInFlightRef.current = true;
22022241
setSaveTried(true);
2242+
// Past validation: the last refusal's marks retire, as the form's own do.
2243+
slotStore.refuse([]);
22032244
holdSaveForBatch();
22042245
try {
22052246
return await sendBatch(parentValues);
@@ -2209,7 +2250,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
22092250
batchInFlightRef.current = false;
22102251
}
22112252
},
2212-
[sendBatch, holdSaveForBatch],
2253+
[sendBatch, holdSaveForBatch, slotStore],
22132254
);
22142255

22152256
// The parent form renders WITHOUT its own submit button — the master-detail
@@ -2384,7 +2425,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
23842425
everything on the parent Save. */}
23852426
{expanded && expandedDetail && (
23862427
// Beside its collection: where the header placed that collection, there.
2387-
<FormSlotPlacement store={slotStore} id={expanded.entryId}>
2428+
<FormSlotPlacement store={slotStore} id={expanded.entryId} ownsForm>
23882429
<Card className="border-primary/40 shadow-none ring-1 ring-primary/10" data-testid="md-row-form">
23892430
<CardHeader className="pb-2 flex flex-row items-center justify-between gap-2 space-y-0">
23902431
<CardTitle className="text-sm font-medium">

‎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)