From ebb814e250bd9e36be6c72afaee30239e1a2a78d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 23:21:26 +0000 Subject: [PATCH 1/7] wip(ui): master-detail form new lines start on the child's defaults (#35940) Claude-Session: https://claude.ai/code/session_01L6bhgWYi6WWWnJAmc7Jtpu Co-authored-by: Claude --- ui/e2e/live/record-page-polish-35745.spec.ts | 7 +- ui/package.json | 2 +- .../plugin-form/src/MasterDetailForm.tsx | 78 ++++++++++++++++++- .../plugin-form/src/RecordBodyTableEditor.tsx | 14 +++- 4 files changed, 91 insertions(+), 10 deletions(-) diff --git a/ui/e2e/live/record-page-polish-35745.spec.ts b/ui/e2e/live/record-page-polish-35745.spec.ts index 5efa6c9fdde..cc6cd9591e2 100644 --- a/ui/e2e/live/record-page-polish-35745.spec.ts +++ b/ui/e2e/live/record-page-polish-35745.spec.ts @@ -113,10 +113,13 @@ test('record page polish (#35745, #35816) — showcase Expense Report', async ({ await save.click(); await expect(toolbar.getByRole('button', { name: 'Edit', exact: true })).toBeVisible({ timeout: 15_000 }); - const stored = await request.get(`${API}/api/v1/data/${LINE}?$top=500`); + // Asked of the server for this report's lines only: a filter the route + // ignored would answer other reports' lines, and fail the count. + const ofThisReport = encodeURIComponent(JSON.stringify([['expense_report', 'equals', id]])); + const stored = await request.get(`${API}/api/v1/data/${LINE}?$filter=${ofThisReport}`); expect(stored.ok(), await stored.text()).toBeTruthy(); const body = await stored.json(); - const rows: any[] = (body.records ?? body.data ?? []).filter((r: any) => r.expense_report === id); + const rows: any[] = body.records ?? body.data ?? []; expect(rows, 'an added line left on its defaults is not stored').toHaveLength(0); } finally { await request.delete(`${API}/api/v1/data/${OBJECT}/${encodeURIComponent(id)}`); diff --git a/ui/package.json b/ui/package.json index d322e082bc9..2d1369cf83f 100644 --- a/ui/package.json +++ b/ui/package.json @@ -110,7 +110,7 @@ "test:e2e": "playwright test", "test:e2e:ui": "playwright test --ui", "test:e2e:live": "playwright test --config=playwright.live.config.ts", - "test:e2e:live:ci": "playwright test --config=playwright.live.config.ts screen-flow.spec.ts action-modal.spec.ts master-detail.spec.ts saved-view-filter.spec.ts studio-object-designer.spec.ts studio-editor.spec.ts record-form-direct-url.spec.ts list-row-action-cel.spec.ts studio-customize-journey.spec.ts", + "test:e2e:live:ci": "playwright test --config=playwright.live.config.ts screen-flow.spec.ts action-modal.spec.ts master-detail.spec.ts saved-view-filter.spec.ts studio-object-designer.spec.ts studio-editor.spec.ts record-form-direct-url.spec.ts list-row-action-cel.spec.ts studio-customize-journey.spec.ts record-page-polish-35745.spec.ts", "test:e2e:live:nightly": "playwright test --config=playwright.live.config.ts cascading-options.spec.ts declared-sharing-rules-reach-13091.spec.ts field-conditional-rules.spec.ts form-view-subforms.spec.ts grid-conditional-rules.spec.ts grid-file-upload.spec.ts grid-parent-rules.spec.ts inline-edit-polish-2572.spec.ts read-only-member-record.spec.ts record-history-display.spec.ts required-when-submit.spec.ts summary-rollup.spec.ts user-filters.spec.ts phone-nav-drawer-back-29131.spec.ts", "test:e2e:import-console": "playwright test --config=playwright.import-console.config.ts" }, diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 292f17ff7a3..ae4406142a4 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -33,7 +33,7 @@ import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; 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'; +import { LineItemsField, lookupAutofillByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; import { Button, Card, CardContent, CardHeader, CardTitle, cn, toast } from '@object-ui/components'; import { formatDisplayNumber, @@ -64,6 +64,7 @@ import { isSameStoredValue } from './sanitize'; import { resolveInitialRecord } from './initialRecord'; import { sectionEntryName } from './sectionFields'; import { deriveDetail } from './deriveMasterDetail'; +import { schemaDefaultValues } from './schemaDefaults'; import { parentCurrencyFieldsOf, followedColumnCurrencies } from './parentCurrencyColumns'; // objectui#11428 — the per-row form's offer test is the spec's rule. import { isInlineRowFormOffered } from '@objectstack/spec/data'; @@ -818,6 +819,16 @@ function withCodeHoles(sentence: string, holes: Record): Record { + const { [UNTOUCHED_NEW_ROW]: _untouched, ...rest } = row as Record & { [UNTOUCHED_NEW_ROW]?: true }; + return rest; +} + interface MasterDetailLinesProps { entries: DetailEntry[]; /** Row state addressed by ENTRY ID, never by array position (objectui#6371). */ @@ -859,6 +870,19 @@ interface MasterDetailLinesProps { * Remove asks the child's delete grant: a create form's lines are drafts. */ formMode: 'create' | 'edit'; + /** + * The values a new line starts with, by CHILD object name (objectstack#35940): + * the child's static defaults, seeded as a create form seeds them. A child + * whose schema has not answered has no entry, and its new lines start blank. + */ + newRowValuesByChild: Readonly>>; + /** + * A save of this form was tried since the lines were last saved: from then + * on a new line's empty required cell reads red (objectstack#35940). Before + * it, a line the user just added is not flagged for a cell they have not + * reached yet. + */ + newRowRequiredShown: boolean; } /** @@ -888,6 +912,8 @@ const MasterDetailLines: React.FC = ({ onAddViaForm, parentObjectName, formMode, + newRowValuesByChild, + newRowRequiredShown, }) => { // The subtotal / tax / grand-total stack formats in the display locale; it // used to pass `toLocaleString` an explicit `undefined`, i.e. the MACHINE's @@ -1124,6 +1150,11 @@ const MasterDetailLines: React.FC = ({ // The columns whose amount follows this header's currency // (ADR-0144 D2 as amended), in the header's live code. columnCurrencies={followedColumnCurrencies(entry.parentCurrencyFields, parentRecord, tenantCurrency)} + // objectstack#35940 — a new line starts on the child's defaults, + // and its empty required cell reads red once a save was tried, + // as on the record page's edit state. + newRowValues={newRowValuesByChild[d.childObject]} + newRowRequiredShown={newRowRequiredShown} // Per-row "expand to full form" is offered when it adds something: // always in form mode (it IS the editor), and in grid mode only // when the full form has fields the grid omits. A thin grid whose @@ -1263,6 +1294,8 @@ export const MasterDetailForm: React.FC = ({ const [resolvedEntries, setResolvedEntries] = useState(null); const entries = resolvedEntries ?? baseEntries; // length always matches rawDetails + const entriesRef = useRef(entries); + entriesRef.current = entries; /** * What the line grids draw: `entries`, each derived entry's columns re-run * with the CURRENT session words (objectui#12924). A host that has not @@ -1473,6 +1506,10 @@ export const MasterDetailForm: React.FC = ({ // never resets — the header (see #1581). Reads happen at submit // time, long after the fetch resolves. const childSchemasRef = useRef }>>({}); + // objectstack#35940 — the same answer for the lines' new-line defaults, which + // are read at render. It lands once, in the render the lines' own load lands + // in, and the header 's props do not depend on it. + const [childSchemas, setChildSchemas] = useState }>>({}); useEffect(() => { const ds: any = dataSource; if (!ds || typeof ds.getObjectSchema !== 'function') return; @@ -1489,11 +1526,32 @@ export const MasterDetailForm: React.FC = ({ const next: Record }> = {}; for (const [obj, sch] of entries) if (sch) next[obj] = sch; childSchemasRef.current = next; + setChildSchemas(next); })(); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [dataSource, schema.objectName, schema.details]); + // objectstack#35940 — every new line is a child record to create, so it + // starts on the values a create form of the child seeds: its static + // defaults, with the same session facts `ObjectForm` threads (the acting + // user, the organization's currency and time zone). A default the server + // resolves per insert (`NOW()`, CEL) is left to the server. + const perms = usePermissions(); + const { currency: homeCurrency, timezone: homeTimeZone } = useLocalization(); + const newRowValuesByChild = useMemo(() => { + const out: Record> = {}; + for (const [childObject, childSchema] of Object.entries(childSchemas)) { + out[childObject] = schemaDefaultValues(childSchema, { currentUserId: perms.userId, homeCurrency, homeTimeZone }); + } + return out; + }, [childSchemas, perms.userId, homeCurrency, homeTimeZone]); + const newRowValuesRef = useRef(newRowValuesByChild); + newRowValuesRef.current = newRowValuesByChild; + // objectstack#35940 — set when a save is tried, cleared when one lands: a + // new line's empty required cell reads red from the try on. + const [saveTried, setSaveTried] = useState(false); + // Bumped after a successful CREATE to remount the parent (which // owns react-hook-form state) so its fields clear for the next entry. const [formKey, setFormKey] = useState(0); @@ -1821,18 +1879,25 @@ export const MasterDetailForm: React.FC = ({ const cur = prev[entryId] ?? { rows: [], original: [] }; return { ...prev, - [entryId]: { ...cur, rows: cur.rows.map((r, j) => (j === rowIdx ? { ...r, ...values } : r)) }, + // An applied editor is input, so the line loses the untouched mark + // an Add on its defaults gave it (objectstack#35940). + [entryId]: { ...cur, rows: cur.rows.map((r, j) => (j === rowIdx ? { ...withoutUntouchedMark(r), ...values } : r)) }, }; }); }, [], ); - /** List/form mode "Add": append a blank row and open it in the full form. */ + /** + * List/form mode "Add": append a row on the child's defaults + * (objectstack#35940) and open it in the full form. + */ const addRowViaForm = useCallback((entryId: string) => { + const childObject = entriesRef.current.find((e) => e.id === entryId)?.config.childObject; + const seed = childObject ? newRowValuesRef.current[childObject] : undefined; setRowState((prev) => { const cur = prev[entryId] ?? { rows: [], original: [] }; - const rows = [...cur.rows, {}]; + const rows = [...cur.rows, { ...seed }]; setExpanded({ entryId, rowIdx: rows.length - 1, isNew: true }); return { ...prev, [entryId]: { ...cur, rows } }; }); @@ -1867,6 +1932,7 @@ export const MasterDetailForm: React.FC = ({ async (parent: any) => { releaseSave(); setHeaderDirty(false); + setSaveTried(false); if (!schema.onSuccess) { toast.success( isEdit @@ -2043,6 +2109,7 @@ export const MasterDetailForm: React.FC = ({ throw new Error('This save was not sent: another save of this form was still in progress.'); } batchInFlightRef.current = true; + setSaveTried(true); holdSaveForBatch(); try { return await sendBatch(parentValues); @@ -2154,6 +2221,7 @@ export const MasterDetailForm: React.FC = ({ if (!form) return; savingRef.current = true; setSaving(true); + setSaveTried(true); // The previous attempt's outcome belongs to the previous attempt: retire it // the moment a new one starts, so no host can confirm a success while this // form's last refusal is still on screen (objectui#7345). @@ -2209,6 +2277,8 @@ export const MasterDetailForm: React.FC = ({ onAddViaForm={addRowViaForm} parentObjectName={schema.objectName} formMode={isEdit ? 'edit' : 'create'} + newRowValuesByChild={newRowValuesByChild} + newRowRequiredShown={saveTried} /> {/* Per-row "expand to full form": an inline editor panel for the selected diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index 64851f4000c..1ca9227bde1 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -39,6 +39,7 @@ import type { BatchTransactionOperation, GridFieldMetadata } from '@object-ui/ty import { resolveAffordance, type SchemaLike } from '@object-ui/core'; import { LineItemsField, lookupAutofillByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; import { cn } from '@object-ui/components'; +import { useLocalization } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; import { extractFieldErrors, @@ -213,6 +214,7 @@ export const RecordBodyTableEditor: React.FC = ({ ob const parentObject = record?.objectName; const parentId = record?.recordId; const perms = usePermissions(); + const { currency: homeCurrency, timezone: homeTimeZone } = useLocalization(); const { t } = useFormChromeTranslation(); const booleanLabel = useBooleanValueLabel(); const booleanTrue = booleanLabel(true); @@ -271,10 +273,16 @@ export const RecordBodyTableEditor: React.FC = ({ ob // defaults, the values a create form seeds (`schemaDefaultValues`), so a // required column with a default is filled instead of flagged empty. A // default the server resolves per insert (`NOW()`, a CEL expression) is not - // seeded; the server fills it as it fills an omitted field. + // seeded; the server fills it as it fills an omitted field. The session + // facts are the ones `ObjectForm` threads (objectstack#35940): the acting + // user, the organization's currency and time zone. Until the child schema + // answers there are no defaults, and a new line starts blank. const newRowValues = useMemo( - () => schemaDefaultValues(childSchema as Parameters[0]), - [childSchema], + () => + childSchema + ? schemaDefaultValues(childSchema, { currentUserId: perms.userId, homeCurrency, homeTimeZone }) + : undefined, + [childSchema, perms.userId, homeCurrency, homeTimeZone], ); const snapshotRef = useRef(null); From 2cbd9bc26426cc88b413d1db455b3af03b26e2d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 23:25:28 +0000 Subject: [PATCH 2/7] test(ui): pin the master-detail form's new-line defaults and the editor's seed context (#35940) Claude-Session: https://claude.ai/code/session_01L6bhgWYi6WWWnJAmc7Jtpu Co-authored-by: Claude --- .../plugin-form/src/MasterDetailForm.test.tsx | 137 +++++++++++++++++- ...BodyTableEditor.seedContext-35940.test.tsx | 94 ++++++++++++ 2 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 ui/packages/plugin-form/src/RecordBodyTableEditor.seedContext-35940.test.tsx diff --git a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx index 2e58ea8d86b..b1f98cfa225 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx @@ -1,7 +1,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, waitFor, fireEvent } from '@testing-library/react'; +import { act, render, screen, waitFor, fireEvent, within } from '@testing-library/react'; import React from 'react'; import { registerAllFields } from '@object-ui/fields'; +import { MePermissionsProvider } from '@object-ui/permissions'; import { MasterDetailForm } from './MasterDetailForm'; // Capture toast calls so we can assert the form is never a silent no-op. @@ -345,3 +346,137 @@ describe('MasterDetailForm — showSubmit gate (Studio screen preview)', () => { expect(cancelBtn).toHaveTextContent('取消'); }); }); + +describe('MasterDetailForm — a new line starts on the child\'s defaults and waits to read red (objectstack#35940)', () => { + const USER_ID = 'user-42'; + // `name` is required with no default; `note` is required with one; + // `applicant` defaults to the acting user, which only a known session can seed. + const lineSchema = { + name: 'po_line', + fields: { + name: { type: 'text', label: 'Name', required: true }, + note: { type: 'text', label: 'Note', required: true, defaultValue: 'Pending' }, + applicant: { type: 'user', label: 'Applicant', defaultValue: 'current_user' }, + po: { type: 'master_detail', label: 'PO', reference: 'po' }, + }, + }; + const ME_PERMISSIONS = { + authenticated: true, + userId: USER_ID, + tenantId: 't1', + roles: ['user'], + permissionSets: [], + objects: { '*': { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true } }, + fields: {}, + }; + const columns = [ + { name: 'name', label: 'Name', type: 'text', required: true }, + { name: 'note', label: 'Note', type: 'text', required: true }, + ]; + const lineDataSource = (overrides: any = {}) => + makeDataSource({ + getObjectSchema: vi.fn(async (name: string) => (name === 'po_line' ? lineSchema : parentSchema)), + ...overrides, + }); + const schemaWith = (detail: Record = {}, extra: Record = {}) => + ({ + objectName: 'po', + mode: 'create', + fields: ['ref'], + details: [{ childObject: 'po_line', relationshipField: 'po', columns, ...detail }], + ...extra, + }) as any; + const cell = (container: HTMLElement, row: number, col: number) => + container.querySelector(`[data-cell="${row}-${col}"]`) as HTMLInputElement | null; + /** Add a line once the child schema (and so its defaults) has answered. */ + const addSeededLine = async (container: HTMLElement) => { + await waitFor(() => expect(cell(container, 0, 1)?.value).toBe('Pending')); // the entry line + fireEvent.click(screen.getByTestId('line-items-add')); + await waitFor(() => expect(container.querySelectorAll('[data-testid="line-items"] tbody tr').length).toBe(2)); + }; + const createOps = (batch: ReturnType) => + (batch.mock.calls[0][0] as Array<{ object: string; action: string; data?: Record }>).filter( + (op) => op.object === 'po_line' && op.action === 'create', + ); + + it('an added line shows the defaults and no red cell; once a save is tried its empty required cell reads red', async () => { + const batchTransaction = vi.fn().mockRejectedValue(new Error('Name is required')); + const { container } = render(); + await addSeededLine(container); + expect(cell(container, 0, 1)!.value).toBe('Pending'); + // An edit to another cell: the line is the user's input, its Name still empty. + fireEvent.change(cell(container, 0, 1)!, { target: { value: 'Later' } }); + expect(container.querySelector('[data-testid^="line-items-invalid-"]')).toBeNull(); + + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(screen.getByTestId('line-items-invalid-0-name')).toBeInTheDocument()); + // The cell with a default is filled, so it is never flagged. + expect(screen.queryByTestId('line-items-invalid-0-note')).toBeNull(); + }); + + it('CONTROL: a stored line\'s empty required cell is flagged at once, as before', async () => { + const ds = lineDataSource({ + find: vi.fn().mockResolvedValue({ data: [{ id: 'l1', po: 'p1', name: null, note: 'x' }] }), + findOne: vi.fn().mockResolvedValue({ id: 'p1', ref: 'PO-1' }), + }); + render(); + await waitFor(() => expect(screen.getByTestId('line-items-invalid-0-name')).toBeInTheDocument()); + }); + + it('the line is written with its defaults, the acting user included (the context a create form seeds with)', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }, { id: 'l1' }] }); + const { container } = render( + + + , + ); + await addSeededLine(container); + fireEvent.change(cell(container, 0, 0)!, { target: { value: 'Bolts' } }); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(batchTransaction).toHaveBeenCalledTimes(1)); + expect(createOps(batchTransaction)).toEqual([ + expect.objectContaining({ data: expect.objectContaining({ name: 'Bolts', note: 'Pending', applicant: USER_ID }) }), + ]); + }); + + it('form mode: Add opens the row editor on the defaults', async () => { + const ds = lineDataSource(); + render(); + // The defaults come from the child schema: let its read answer first. + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalledWith('po_line')); + await act(async () => {}); + fireEvent.click(screen.getByTestId('line-items-add')); + const editor = await waitFor(() => screen.getByTestId('md-row-form')); + await waitFor(() => + expect((editor.querySelector('input[name="note"]') as HTMLInputElement | null)?.value).toBe('Pending'), + ); + }); + + it('a line Add started and the row editor then applied is input, and is written', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }, { id: 'l1' }] }); + const { container } = render( + , + ); + await addSeededLine(container); + fireEvent.click(screen.getByTestId('line-items-expand-0')); + const editor = await waitFor(() => screen.getByTestId('md-row-form')); + const name = await waitFor(() => { + const el = editor.querySelector('input[name="name"]') as HTMLInputElement | null; + if (!el) throw new Error('row editor not ready'); + return el; + }); + // Typed in the editor, not in the grid: only Apply carries it to the line, + // and a line still marked untouched would be skipped whatever it holds. + fireEvent.change(name, { target: { value: 'Washers' } }); + fireEvent.click(within(editor).getByRole('button', { name: 'Apply' })); + await waitFor(() => expect(screen.queryByTestId('md-row-form')).toBeNull()); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(batchTransaction).toHaveBeenCalledTimes(1)); + expect(createOps(batchTransaction)).toEqual([ + expect.objectContaining({ data: expect.objectContaining({ name: 'Washers', note: 'Pending' }) }), + ]); + }); +}); diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.seedContext-35940.test.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.seedContext-35940.test.tsx new file mode 100644 index 00000000000..8d17da82dd7 --- /dev/null +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.seedContext-35940.test.tsx @@ -0,0 +1,94 @@ +/** + * 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. + * + * The record page's body-table editor seeds a new line with the values a + * create form of the child seeds (objectstack#35940): its static defaults, and + * the session facts `ObjectForm` threads, so a field defaulted to the acting + * user starts on that user. CONTROL: with no known user that field starts + * empty and is left to the server, as on a create form. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { RecordContextProvider } from '@object-ui/react'; +import { MePermissionsProvider } from '@object-ui/permissions'; +import { registerAllFields } from '@object-ui/fields'; +import { + RecordBodyTableEditor, + RecordEditSessionContext, + type BodyTableEditHandle, + type RecordEditSession, +} from './RecordBodyTableEditor'; + +registerAllFields(); +afterEach(() => cleanup()); + +const USER_ID = 'user-42'; + +const TASK_SCHEMA = { + name: 'meeting_task', + fields: { + name: { type: 'text', label: 'Name', required: true }, + status: { type: 'text', label: 'Status', required: true, defaultValue: 'pending' }, + assignee: { type: 'user', label: 'Assignee', defaultValue: 'current_user' }, + meeting: { type: 'master_detail', label: 'Meeting', reference: 'meeting' }, + }, +}; + +const ME_PERMISSIONS = { + authenticated: true, + userId: USER_ID, + tenantId: 't1', + roles: ['user'], + permissionSets: [], + objects: { '*': { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true } }, + fields: {}, +}; + +function mount(withUser: boolean) { + const ds = { + getObjectSchema: vi.fn(async () => TASK_SCHEMA), + find: vi.fn(async () => ({ data: [] })), + onMutation: () => () => {}, + }; + let handle: BodyTableEditHandle | null = null; + const session: RecordEditSession = { + register: (h) => { + handle = h; + return () => { handle = null; }; + }, + reportDirty: () => {}, + saving: false, + }; + const editor = ( + + + + + + ); + render(withUser ? {editor} : editor); + return { rows: () => (handle as BodyTableEditHandle | null)?.snapshot()?.rows ?? null }; +} + +describe('RecordBodyTableEditor — a new line seeds what a create form seeds (objectstack#35940)', () => { + it('a field defaulted to the acting user starts on that user, beside the static defaults', async () => { + const { rows } = mount(true); + fireEvent.click(await screen.findByTestId('line-items-add')); + await waitFor(() => expect(rows()).toHaveLength(1)); + expect(rows()![0]).toMatchObject({ status: 'pending', assignee: USER_ID }); + }); + + it('CONTROL: with no known user the field starts empty, left to the server', async () => { + const { rows } = mount(false); + fireEvent.click(await screen.findByTestId('line-items-add')); + await waitFor(() => expect(rows()).toHaveLength(1)); + expect(rows()![0]).toMatchObject({ status: 'pending' }); + expect(rows()![0].assignee ?? null).toBeNull(); + }); +}); From e984f45e657c85b49954e83b7118b880bb6d0c8c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 23:25:57 +0000 Subject: [PATCH 3/7] chore: changeset for the master-detail form's new-line defaults (#35940) Claude-Session: https://claude.ai/code/session_01L6bhgWYi6WWWnJAmc7Jtpu Co-authored-by: Claude --- .changeset/35940-master-detail-form-new-lines.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/35940-master-detail-form-new-lines.md diff --git a/.changeset/35940-master-detail-form-new-lines.md b/.changeset/35940-master-detail-form-new-lines.md new file mode 100644 index 00000000000..08fc63fe354 --- /dev/null +++ b/.changeset/35940-master-detail-form-new-lines.md @@ -0,0 +1,14 @@ +--- +'@object-ui/plugin-form': patch +--- + +fix(form): a new detail line on a master-detail create / edit form starts on the child's defaults and does not read red before a save is tried + +Clause-②: no +Metadata-protocol: none + +On a parent object's create or edit form, a line added to a detail table started blank, so a required column with a default (a status that defaults to "Pending") read red at once although saving would store the default. The record page's edit state already started its new lines on their defaults; the form now does the same. + +A new line on the form starts on the child object's static defaults, the values a create form of the child seeds, whether it is added with Add, typed into the trailing entry line, or added in a form-mode collection (the row editor opens on them). A default the server resolves at insert (`NOW()`, a CEL expression) is left to the server. A new line's empty required cell reads red once a save of the form was tried, not the moment the line appears; a stored line is flagged as before. A line added with Add and then applied from the row editor is the user's input and is saved. + +The defaults on both the form and the record page's edit state are now read with the session facts a create form uses: a child field defaulted to the acting user starts on that user, and the organization's currency and time zone seed the fields they seed on a create form. With no known user that field starts empty and the server fills it, as before. From 81bc0082626cf145c2bf06cff3a2c4fb3711c5ff Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:13:25 +0000 Subject: [PATCH 4/7] fix(ui): an untouched added detail line is skipped, said so, and never red, on the form and the record page (#35940) Claude-Session: https://claude.ai/code/session_01L6bhgWYi6WWWnJAmc7Jtpu Co-authored-by: Claude --- .../views/RecordDetailView.harness.test.tsx | 30 +++++++++++ .../app-shell/src/views/RecordDetailView.tsx | 1 + .../app-shell/src/views/recordEditState.tsx | 18 ++++++- .../fields/src/widgets/GridField.test.tsx | 31 +++++++++++ ui/packages/fields/src/widgets/GridField.tsx | 10 +++- ui/packages/i18n/src/locales/ar.ts | 7 +++ ui/packages/i18n/src/locales/de.ts | 3 ++ ui/packages/i18n/src/locales/en.ts | 6 +++ ui/packages/i18n/src/locales/es.ts | 4 ++ ui/packages/i18n/src/locales/fr.ts | 4 ++ ui/packages/i18n/src/locales/ja.ts | 3 ++ ui/packages/i18n/src/locales/ko.ts | 3 ++ ui/packages/i18n/src/locales/pt-BR.ts | 4 ++ ui/packages/i18n/src/locales/ru.ts | 5 ++ ui/packages/i18n/src/locales/zh-Hans.ts | 3 ++ ui/packages/i18n/src/locales/zh-Hant.ts | 3 ++ .../plugin-form/src/MasterDetailForm.test.tsx | 53 ++++++++++++++++++- .../plugin-form/src/MasterDetailForm.tsx | 25 +++++++-- ui/packages/plugin-form/src/formChrome.ts | 5 ++ 19 files changed, 209 insertions(+), 9 deletions(-) diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index 30c5e306c32..6c95bd89a12 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -48,6 +48,7 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest'; import { render, waitFor, cleanup, screen, act, fireEvent } from '@testing-library/react'; import { MemoryRouter, Route, Routes, BrowserRouter } from 'react-router-dom'; +import { toast } from 'sonner'; import { RelatedCountStore } from '@object-ui/components'; import { ComponentRegistry } from '@object-ui/core'; import { I18nProvider, LocalizationProvider, createI18n } from '@object-ui/i18n'; @@ -3162,6 +3163,35 @@ describe('RecordDetailView.recordEditState-35599', () => { expect(summaryInput(view.container)).not.toBeNull(); }); + it('objectstack#35940 (ruling 7056413638): a line Add started and nobody edited is not written, and the save says so', async () => { + const view = renderPage(objectsWith()); + await enterEditState(view); + vi.mocked(toast.info).mockClear(); + fireEvent.change(summaryInput(view.container)!, { target: { value: 'Second' } }); + const lines = editor(view.container, 'showcase_line.quote')!; + fireEvent.click(lines.querySelector('[data-testid="line-items-add"]') as HTMLElement); + await waitFor(() => expect(cells(lines, 'Product').length).toBeGreaterThanOrEqual(4), { timeout: 5000 }); + await act(async () => { fireEvent.click(headerButton('Save')!); }); + await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 }); + // The record's update alone: the untouched line is not created. + const ops = view.dataSource.batchTransaction.mock.calls[0][0] as Array>; + expect(ops.map((o) => [o.object, o.action])).toEqual([[PARENT, 'update']]); + await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); + expect(toast.info).toHaveBeenCalledTimes(1); + expect(toast.info).toHaveBeenCalledWith('1 blank line was not saved'); + }); + + it('CONTROL — a save that skips no untouched line says nothing more', async () => { + const view = renderPage(objectsWith()); + await enterEditState(view); + vi.mocked(toast.info).mockClear(); + editEverything(view.container); + await act(async () => { fireEvent.click(headerButton('Save')!); }); + await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 }); + await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); + expect(toast.info).not.toHaveBeenCalled(); + }); + it('item 5: a child without bulk keeps its table read-only in the edit state, with the notice', async () => { const view = renderPage(objectsWith({ lineEnable: { apiMethods: ['get', 'list', 'create', 'update', 'delete'] } })); await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 85ccacdaa70..c382eb92c9c 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -5674,6 +5674,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri bodyTablesReadOnly={bodyTableIds.size > 0 && !bodyTablesEditable} readOnlyNotice={t('detail.bodyTablesReadOnlyBulk')} unsavedMessage={t('form.unsavedChanges')} + untouchedNotSaved={(count) => t('form.lineItems.untouchedNotSaved', { count })} > string; children: React.ReactNode; } @@ -198,6 +205,7 @@ export const RecordEditStateController: React.FC bodyTablesReadOnly, readOnlyNotice, unsavedMessage, + untouchedNotSaved, children, }) => { const inline = useInlineEdit(); @@ -294,12 +302,19 @@ export const RecordEditStateController: React.FC }) : []; const built = buildRecordEditBatch(objectName, String(recordId), draft, tables); + // objectstack#35940 — the lines the batch skips untouched: never written, + // and said so once the save has landed (or had nothing else to write). + const skipped = tables.reduce((n, table) => n + table.rows.filter(isUntouchedNewRow).length, 0); + const sayWhatWasSkipped = () => { + if (skipped > 0) toast.info(untouchedNotSaved(skipped)); + }; // An untouched record writes no update of its own: op 0 goes when the draft is empty. const hasDraft = Object.keys(draft).length > 0; const ops = hasDraft ? built.ops : built.ops.slice(1); const owners = hasDraft ? built.owners : built.owners.slice(1); if (ops.length === 0) { await finish(); + sayWhatWasSkipped(); return; } setSaving(true); @@ -312,6 +327,7 @@ export const RecordEditStateController: React.FC await runBatchTransaction(dataSource, ops); } await finish(); + sayWhatWasSkipped(); } catch (err) { const refusal = attributeRecordEditRefusal(err, ops, owners); inline.setFieldErrors(refusal.fieldErrors); @@ -323,7 +339,7 @@ export const RecordEditStateController: React.FC inline.setSaving(false); setSaving(false); } - }, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish]); + }, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish, untouchedNotSaved]); const cancel = useCallback(() => { inline?.cancel(); diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index 355116ad4aa..4182c994ab4 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -845,3 +845,34 @@ describe('GridField — a new line starts on its defaults and waits to read red expect(screen.getByTestId('line-items-invalid-0-name')).toBeTruthy(); }); }); + +describe('GridField — a line Add started on its defaults and nobody edited never reads red (objectstack#35940)', () => { + const taskColumns = { + columns: [ + { name: 'name', label: 'Name', type: 'text' as const, required: true }, + { name: 'status', label: 'Status', type: 'text' as const, required: true }, + ], + } as any; + + it('stays unflagged after the host says a save was refused, while an edited new line is flagged', () => { + const rows = [ + { name: null, status: 'pending', [UNTOUCHED_NEW_ROW]: true }, + { name: null, status: 'done' }, + ]; + render( {}} field={taskColumns} newRowValues={{ status: 'pending' }} newRowRequiredShown />); + expect(screen.queryByTestId('line-items-invalid-0-name')).toBeNull(); + expect(screen.getByTestId('line-items-invalid-1-name')).toBeTruthy(); + }); + + it('its first edit makes it input, and from then on it is flagged like any new line', () => { + const onChange = vi.fn(); + const field = { columns: [...taskColumns.columns, { name: 'note', label: 'Note', type: 'text' as const }] } as any; + const rows = [{ name: null, status: 'pending', note: null, [UNTOUCHED_NEW_ROW]: true }]; + const { rerender } = render( + , + ); + fireEvent.change(screen.getAllByDisplayValue('pending')[0], { target: { value: 'done' } }); + rerender(); + expect(screen.getByTestId('line-items-invalid-0-name')).toBeTruthy(); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.tsx b/ui/packages/fields/src/widgets/GridField.tsx index f5bae9ceecd..d81c1fb4b34 100644 --- a/ui/packages/fields/src/widgets/GridField.tsx +++ b/ui/packages/fields/src/widgets/GridField.tsx @@ -696,7 +696,9 @@ type GridFieldProps = FieldWidgetComponentProps & { * no id) is flagged only while it is `true` (objectstack#35816): a line * the user just added does not read red before the host has tried to save * it, and does once a save was refused. A stored line is flagged as - * before. Absent: every line is flagged at once, as before. */ + * before. Absent: every line is flagged at once, as before. A line still + * marked {@link UNTOUCHED_NEW_ROW} is never flagged (objectstack#35940): + * the host skips it at save. */ newRowRequiredShown?: boolean; }; @@ -1575,8 +1577,12 @@ function GridFieldBody({ const required = cellRules(c, row).required; // objectstack#35816 — a new line waits for the host's // word before it reads red; a stored line does not. + // objectstack#35940 — a line Add started on its defaults + // and nobody edited never reads red: the save skips it + // and says so, so there is nothing in it to fix. const newRowWaits = - newRowRequiredShown === false && !isGhost && !rowHasId(row); + (newRowRequiredShown === false && !isGhost && !rowHasId(row)) || + isUntouchedNewRow(row); const invalid = (!isGhost || hostFailedEmpty) && !newRowWaits && diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 0e5533d0853..0c5c51179e0 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -233,6 +233,13 @@ const ar = { notLoaded: "لم يتم تحميل بنود هذا السجل.", loadFailed: "تعذّر تحميل البنود", saveFailed: "تعذّر حفظ البنود", + untouchedNotSaved: "لم يُحفظ {{count}} سطر فارغ", + untouchedNotSaved_zero: "لم يُحفظ {{count}} سطر فارغ", + untouchedNotSaved_one: "لم يُحفظ {{count}} سطر فارغ", + untouchedNotSaved_two: "لم يُحفظ سطران فارغان ({{count}})", + untouchedNotSaved_few: "لم تُحفظ {{count}} أسطر فارغة", + untouchedNotSaved_many: "لم يُحفظ {{count}} سطرًا فارغًا", + untouchedNotSaved_other: "لم يُحفظ {{count}} سطر فارغ", noChildObject: "لم يُكوَّن كائن فرعي لهذه اللوحة: عيّن {{property}} إلى الكائن الذي تسرد صفوفه.", }, keepEditing: "متابعة التحرير", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 524e145960f..2acb448c920 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -219,6 +219,9 @@ const de = { notLoaded: "Die Positionen dieses Datensatzes wurden nicht geladen.", loadFailed: "Positionen konnten nicht geladen werden", saveFailed: "Positionen konnten nicht gespeichert werden", + untouchedNotSaved: "{{count}} leere Position wurde nicht gespeichert", + untouchedNotSaved_one: "{{count}} leere Position wurde nicht gespeichert", + untouchedNotSaved_other: "{{count}} leere Positionen wurden nicht gespeichert", noChildObject: "Für dieses Panel ist kein untergeordnetes Objekt konfiguriert: Setzen Sie {{property}} auf das Objekt, dessen Zeilen es auflistet.", }, keepEditing: "Weiter bearbeiten", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index d849fe57db8..f130429c727 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -351,6 +351,12 @@ const en = { notLoaded: 'This record’s line items have not been loaded.', loadFailed: 'Failed to load line items', saveFailed: 'Failed to save line items', + // The notice after a save that skipped lines Add started on their + // defaults and nobody edited (objectstack#35940): the master-detail + // form and the record page's edit state. `{{count}}` is how many. + untouchedNotSaved: '{{count}} blank line was not saved', + untouchedNotSaved_one: '{{count}} blank line was not saved', + untouchedNotSaved_other: '{{count}} blank lines were not saved', noChildObject: 'This panel has no child object configured: set {{property}} to the object whose rows it lists.', }, keepEditing: 'Keep editing', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 0501f14d953..3065e23cbfb 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -226,6 +226,10 @@ const es = { notLoaded: "Las líneas de detalle de este registro no se han cargado.", loadFailed: "No se pudieron cargar las líneas de detalle", saveFailed: "No se pudieron guardar las líneas de detalle", + untouchedNotSaved: "{{count}} línea vacía no se guardó", + untouchedNotSaved_one: "{{count}} línea vacía no se guardó", + untouchedNotSaved_many: "{{count}} de líneas vacías no se guardaron", + untouchedNotSaved_other: "{{count}} líneas vacías no se guardaron", noChildObject: "Este panel no tiene configurado ningún objeto secundario: establezca {{property}} en el objeto cuyas filas enumera.", }, keepEditing: "Seguir editando", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index d1c21ddfbfc..1dfcc1b9c84 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -221,6 +221,10 @@ const fr = { notLoaded: "Les lignes de cet enregistrement n'ont pas été chargées.", loadFailed: "Échec du chargement des lignes", saveFailed: "Échec de l'enregistrement des lignes", + untouchedNotSaved: "{{count}} ligne vide n’a pas été enregistrée", + untouchedNotSaved_one: "{{count}} ligne vide n’a pas été enregistrée", + untouchedNotSaved_many: "{{count}} de lignes vides n’ont pas été enregistrées", + untouchedNotSaved_other: "{{count}} lignes vides n’ont pas été enregistrées", noChildObject: "Aucun objet enfant n'est configuré pour ce panneau : définissez {{property}} sur l'objet dont il liste les lignes.", }, keepEditing: "Continuer l'édition", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index afb9452b692..933a512dad9 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -219,6 +219,9 @@ const ja = { notLoaded: "このレコードの明細行は読み込まれていません。", loadFailed: "明細行の読み込みに失敗しました", saveFailed: "明細行の保存に失敗しました", + untouchedNotSaved: "空白の明細行 {{count}} 行は保存されませんでした", + untouchedNotSaved_one: "空白の明細行 {{count}} 行は保存されませんでした", + untouchedNotSaved_other: "空白の明細行 {{count}} 行は保存されませんでした", noChildObject: "このパネルには子オブジェクトが設定されていません。{{property}} に、行を一覧表示するオブジェクトを設定してください。", }, keepEditing: "編集を続ける", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 5f81fd6a437..a0196b9affa 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -219,6 +219,9 @@ const ko = { notLoaded: "이 레코드의 라인 항목을 불러오지 않았습니다.", loadFailed: "라인 항목을 불러오지 못했습니다", saveFailed: "라인 항목을 저장하지 못했습니다", + untouchedNotSaved: "빈 명세 행 {{count}}개는 저장되지 않았습니다", + untouchedNotSaved_one: "빈 명세 행 {{count}}개는 저장되지 않았습니다", + untouchedNotSaved_other: "빈 명세 행 {{count}}개는 저장되지 않았습니다", noChildObject: "이 패널에 하위 개체가 구성되지 않았습니다. {{property}}을(를) 행을 나열할 개체로 설정하세요.", }, keepEditing: "계속 편집", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 3b714b36e82..64d8ef15628 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -221,6 +221,10 @@ const pt = { notLoaded: "Os itens de linha deste registro não foram carregados.", loadFailed: "Falha ao carregar os itens de linha", saveFailed: "Falha ao salvar os itens de linha", + untouchedNotSaved: "{{count}} linha em branco não foi salva", + untouchedNotSaved_one: "{{count}} linha em branco não foi salva", + untouchedNotSaved_many: "{{count}} de linhas em branco não foram salvas", + untouchedNotSaved_other: "{{count}} linhas em branco não foram salvas", noChildObject: "Este painel não tem nenhum objeto filho configurado: defina {{property}} como o objeto cujas linhas ele lista.", }, keepEditing: "Continuar editando", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 4affd4f3167..a6786c6488f 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -226,6 +226,11 @@ const ru = { notLoaded: "Позиции этой записи не загружены.", loadFailed: "Не удалось загрузить позиции", saveFailed: "Не удалось сохранить позиции", + untouchedNotSaved: "{{count}} пустая строка не сохранена", + untouchedNotSaved_one: "{{count}} пустая строка не сохранена", + untouchedNotSaved_few: "{{count}} пустые строки не сохранены", + untouchedNotSaved_many: "{{count}} пустых строк не сохранено", + untouchedNotSaved_other: "{{count}} пустой строки не сохранено", noChildObject: "Для этой панели не настроен дочерний объект: укажите в {{property}} объект, строки которого она выводит.", }, keepEditing: "Продолжить редактирование", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 20224f7d44e..2330a032001 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -231,6 +231,9 @@ const zh = { notLoaded: '此记录的明细行尚未加载。', loadFailed: '明细行加载失败', saveFailed: '明细行保存失败', + untouchedNotSaved: '{{count}} 行空白明细未保存', + untouchedNotSaved_one: '{{count}} 行空白明细未保存', + untouchedNotSaved_other: '{{count}} 行空白明细未保存', noChildObject: '此面板未配置子对象:请将 {{property}} 设为其所列行所属的对象。', }, keepEditing: '继续编辑', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index abd7c3573ae..f427b631386 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -231,6 +231,9 @@ const zhHant = { notLoaded: '此記錄的明細行尚未載入。', loadFailed: '明細行載入失敗', saveFailed: '明細行儲存失敗', + untouchedNotSaved: '{{count}} 行空白明細未儲存', + untouchedNotSaved_one: '{{count}} 行空白明細未儲存', + untouchedNotSaved_other: '{{count}} 行空白明細未儲存', noChildObject: '此面板未配置子物件:請將 {{property}} 設為其所列行所屬的物件。', }, keepEditing: '繼續編輯', diff --git a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx index b1f98cfa225..a183b77b64c 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx @@ -18,14 +18,14 @@ import { MasterDetailForm } from './MasterDetailForm'; // single surviving raiser, and only the deep-module mock can see it — the // same reason `MasterDetailForm.outcomeToastSupersede.test.tsx` (#7345) // already mocks this exact path. -const { toastSuccess, toastError } = vi.hoisted(() => ({ toastSuccess: vi.fn(), toastError: vi.fn() })); +const { toastSuccess, toastError, toastInfo } = vi.hoisted(() => ({ toastSuccess: vi.fn(), toastError: vi.fn(), toastInfo: vi.fn() })); vi.mock('@object-ui/components/ui/sonner', async (orig) => { const actual = await (orig as any)(); // Inherit the real toast surface and override only what this file asserts: // a hand-listed double freezes sonner's methods at whatever was typed that // day, and the next one the form calls (`dismiss`, objectui#7345) resolves // to undefined — the `check:vi-mock-inherit` defect, one level down. - return { ...actual, toast: { ...actual.toast, success: toastSuccess, error: toastError } }; + return { ...actual, toast: { ...actual.toast, success: toastSuccess, error: toastError, info: toastInfo } }; }); registerAllFields(); @@ -479,4 +479,53 @@ describe('MasterDetailForm — a new line starts on the child\'s defaults and wa expect.objectContaining({ data: expect.objectContaining({ name: 'Washers', note: 'Pending' }) }), ]); }); + describe('ruling 7056413638: a line Add started and nobody edited is skipped, said so, and never red', () => { + beforeEach(() => toastInfo.mockClear()); + + it('create: the line is not written, the save says so, and a host onSuccess still hears the rest', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }] }); + const onSuccess = vi.fn(); + const { container } = render( + , + ); + await addSeededLine(container); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1)); + expect(createOps(batchTransaction)).toEqual([]); + expect(toastInfo).toHaveBeenCalledTimes(1); + expect(toastInfo.mock.calls[0][0]).toBe('1 blank line was not saved'); + }); + + it('a refused save flags the edited new line and leaves the untouched one unflagged', async () => { + const batchTransaction = vi.fn().mockRejectedValue(new Error('Name is required')); + const { container } = render(); + await addSeededLine(container); + fireEvent.click(screen.getByTestId('line-items-add')); + await waitFor(() => expect(container.querySelectorAll('[data-testid="line-items"] tbody tr').length).toBe(3)); + fireEvent.change(cell(container, 1, 1)!, { target: { value: 'Later' } }); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(screen.getByTestId('line-items-invalid-1-name')).toBeInTheDocument()); + expect(screen.queryByTestId('line-items-invalid-0-name')).toBeNull(); + expect(toastInfo).not.toHaveBeenCalled(); + }); + + it('edit: the skipped line leaves with the save, as on the record page', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'p1' }] }); + const ds = lineDataSource({ + batchTransaction, + find: vi.fn().mockResolvedValue({ data: [{ id: 'l1', po: 'p1', name: 'Nuts', note: 'x' }] }), + findOne: vi.fn().mockResolvedValue({ id: 'p1', ref: 'PO-1' }), + }); + const { container } = render(); + await waitFor(() => expect(cell(container, 0, 0)?.value).toBe('Nuts')); + await waitFor(() => expect(cell(container, 1, 1)?.value).toBe('Pending')); // the entry line + fireEvent.click(screen.getByTestId('line-items-add')); + await waitFor(() => expect(container.querySelectorAll('[data-testid="line-items"] tbody tr').length).toBe(3)); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(toastInfo).toHaveBeenCalledTimes(1)); + expect(createOps(batchTransaction)).toEqual([]); + await waitFor(() => expect(container.querySelectorAll('[data-testid="line-items"] tbody tr').length).toBe(2)); + expect(cell(container, 0, 0)!.value).toBe('Nuts'); + }); + }); }); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index ae4406142a4..69d71feaf95 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -33,7 +33,7 @@ import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types'; import { resolveAffordance, runBatchTransaction } from '@object-ui/core'; -import { LineItemsField, lookupAutofillByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; +import { isUntouchedNewRow, LineItemsField, lookupAutofillByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; import { Button, Card, CardContent, CardHeader, CardTitle, cn, toast } from '@object-ui/components'; import { formatDisplayNumber, @@ -1551,6 +1551,10 @@ export const MasterDetailForm: React.FC = ({ // objectstack#35940 — set when a save is tried, cleared when one lands: a // new line's empty required cell reads red from the try on. const [saveTried, setSaveTried] = useState(false); + // objectstack#35940 (ruling 7056413638) — how many lines the batch in flight + // skips because Add started them on their defaults and nobody edited them. + // A save that lands says so; such a line is never written. + const untouchedSkippedRef = useRef(0); // Bumped after a successful CREATE to remount the parent (which // owns react-hook-form state) so its fields clear for the next entry. @@ -1941,6 +1945,13 @@ export const MasterDetailForm: React.FC = ({ { id: outcomeToastId }, ); } + // Said whoever owns the confirmation: a host's own toast cannot know + // that lines were left out. + const skipped = untouchedSkippedRef.current; + untouchedSkippedRef.current = 0; + if (skipped > 0) { + toast.info(t('form.lineItems.untouchedNotSaved', { count: skipped }), { id: `form-untouched:${formInstanceId}` }); + } // An edit keeps its rows: `submitViaBatch` has already advanced their // baseline to what this save wrote (objectui#10564). if (!isEdit) { @@ -1953,7 +1964,7 @@ export const MasterDetailForm: React.FC = ({ await schema.onSuccess?.(parent); }, // eslint-disable-next-line react-hooks/exhaustive-deps - [isEdit, schema.onSuccess, titleText, entries.length, releaseSave, outcomeToastId, t], + [isEdit, schema.onSuccess, titleText, entries.length, releaseSave, outcomeToastId, formInstanceId, t], ); /** @@ -2002,6 +2013,9 @@ export const MasterDetailForm: React.FC = ({ async (parentValues: Record) => { if (!dataSource) throw new Error('MasterDetailForm: dataSource is required'); const parentData: Record = { ...parentValues }; + untouchedSkippedRef.current = entries + .filter((e) => e.config.relationshipField) + .reduce((n, e) => n + (rowStateRef.current[e.id]?.rows ?? []).filter(isUntouchedNewRow).length, 0); // Client-side rollups merged into the parent payload (hooks can't do // nested writes — see ADR-0001). entries.forEach((e) => { @@ -2074,12 +2088,15 @@ export const MasterDetailForm: React.FC = ({ // flight (objectui#10631), so every such row is still that object. // Were one replaced anyway, it keeps no id: the next save then // deletes the created record and creates the row as it now stands. - const rows = s.createdIds.size === 0 + // A line the save skipped untouched (objectstack#35940) leaves + // with the save, as it does on the record page: it was never + // written, and the notice above says so. + const rows = (s.createdIds.size === 0 ? cur.rows : cur.rows.map((r) => { const id = s.createdIds.get(r); return id === undefined ? r : { ...r, id }; - }); + })).filter((r) => !isUntouchedNewRow(r)); next = { ...next, [s.entryId]: { rows, original: s.original } }; } return next; diff --git a/ui/packages/plugin-form/src/formChrome.ts b/ui/packages/plugin-form/src/formChrome.ts index 227e414a407..9cfcbc84f2c 100644 --- a/ui/packages/plugin-form/src/formChrome.ts +++ b/ui/packages/plugin-form/src/formChrome.ts @@ -86,6 +86,11 @@ const FORM_CHROME_DEFAULTS = { // loading line, a failed read, and the label of a refused line. 'common.loading': 'Loading…', 'form.lineItems.loadFailed': 'Failed to load line items', + // The notice after a save that skipped lines nobody edited since Add started + // them on their defaults (objectstack#35940). + 'form.lineItems.untouchedNotSaved': '{{count}} blank line was not saved', + 'form.lineItems.untouchedNotSaved_one': '{{count}} blank line was not saved', + 'form.lineItems.untouchedNotSaved_other': '{{count}} blank lines were not saved', 'detail.bodyTableRow': 'Row {{row}}', }; From e6be20e11e10138747e69892b4e31598c6110451 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:15:33 +0000 Subject: [PATCH 5/7] test(ui): read the record page's skipped-line notice under the English pack (#35940) Claude-Session: https://claude.ai/code/session_01L6bhgWYi6WWWnJAmc7Jtpu Co-authored-by: Claude --- .../src/views/RecordDetailView.harness.test.tsx | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index 6c95bd89a12..e9a9527af0e 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -2910,7 +2910,8 @@ describe('RecordDetailView.recordEditState-35599', () => { showcase_task: [{ id: 't1', subject: 'Call', quote: RECORD_ID }], }; - function renderPage(objects: ReturnType, opts: { emptyTables?: boolean } = {}) { + /** `i18n`: under the real English provider, so a notice reads as the pack writes it. */ + function renderPage(objects: ReturnType, opts: { emptyTables?: boolean; i18n?: boolean } = {}) { const metadata = { objects, pages: [], loading: false, error: null, refresh: async () => {}, invalidate: () => {}, @@ -2929,7 +2930,7 @@ describe('RecordDetailView.recordEditState-35599', () => { batchTransaction: vi.fn(async (ops: unknown[]) => ({ results: ops.map(() => ({})) })), }; const onEdit = vi.fn(); - const view = render( + const page = ( @@ -2942,7 +2943,12 @@ describe('RecordDetailView.recordEditState-35599', () => { - , + + ); + const view = render( + opts.i18n + ? {page} + : page, ); return { ...view, dataSource, onEdit }; } @@ -3164,7 +3170,7 @@ describe('RecordDetailView.recordEditState-35599', () => { }); it('objectstack#35940 (ruling 7056413638): a line Add started and nobody edited is not written, and the save says so', async () => { - const view = renderPage(objectsWith()); + const view = renderPage(objectsWith(), { i18n: true }); await enterEditState(view); vi.mocked(toast.info).mockClear(); fireEvent.change(summaryInput(view.container)!, { target: { value: 'Second' } }); From 96501c25b1347749b062183a9de0f28e63cb8da1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:18:12 +0000 Subject: [PATCH 6/7] refactor(ui): leave the form-mode Add to the row editor's own create seeding (#35940) Claude-Session: https://claude.ai/code/session_01L6bhgWYi6WWWnJAmc7Jtpu Co-authored-by: Claude --- .changeset/35940-master-detail-form-new-lines.md | 11 ++++++++--- .../plugin-form/src/MasterDetailForm.test.tsx | 15 +-------------- ui/packages/plugin-form/src/MasterDetailForm.tsx | 13 ++----------- 3 files changed, 11 insertions(+), 28 deletions(-) diff --git a/.changeset/35940-master-detail-form-new-lines.md b/.changeset/35940-master-detail-form-new-lines.md index 08fc63fe354..1e320649719 100644 --- a/.changeset/35940-master-detail-form-new-lines.md +++ b/.changeset/35940-master-detail-form-new-lines.md @@ -1,14 +1,19 @@ --- '@object-ui/plugin-form': patch +'@object-ui/fields': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch --- -fix(form): a new detail line on a master-detail create / edit form starts on the child's defaults and does not read red before a save is tried +fix(form): a new detail line on a master-detail create / edit form starts on the child's defaults, does not read red before a save is tried, and a line added and left untouched is skipped with a notice on the form and the record page Clause-②: no Metadata-protocol: none On a parent object's create or edit form, a line added to a detail table started blank, so a required column with a default (a status that defaults to "Pending") read red at once although saving would store the default. The record page's edit state already started its new lines on their defaults; the form now does the same. -A new line on the form starts on the child object's static defaults, the values a create form of the child seeds, whether it is added with Add, typed into the trailing entry line, or added in a form-mode collection (the row editor opens on them). A default the server resolves at insert (`NOW()`, a CEL expression) is left to the server. A new line's empty required cell reads red once a save of the form was tried, not the moment the line appears; a stored line is flagged as before. A line added with Add and then applied from the row editor is the user's input and is saved. +**New lines on the form.** A new line starts on the child object's static defaults, the values a create form of the child seeds, whether it is added with Add or typed into the trailing entry line. A default the server resolves at insert (`NOW()`, a CEL expression) is left to the server. A new line's empty required cell reads red once a save of the form was tried, not the moment the line appears; a stored line is flagged as before. A line added with Add and then applied from the row editor is the user's input and is saved. -The defaults on both the form and the record page's edit state are now read with the session facts a create form uses: a child field defaulted to the acting user starts on that user, and the organization's currency and time zone seed the fields they seed on a create form. With no known user that field starts empty and the server fills it, as before. +**A line added and left untouched** (maintainer ruling, card comment 7056413638: 「跳过并提示未保存」). A line Add started on its defaults that nobody edited holds only those defaults. It is still not written, and the save now says so: once the save lands, the form and the record page's edit state show "1 blank line was not saved" (or "N blank lines were not saved"), also when the host supplies its own save confirmation. Such a line never reads red, before or after a refused save, since there is nothing in it to fix; once the user edits any of its cells it is input, saved and flagged like any other new line. On an edit form that stays open after saving, the skipped line leaves with the save, as it does on the record page. A line the user typed into and then cleared is blank and is skipped as before, without the notice. The pack key is `form.lineItems.untouchedNotSaved`, in every built-in locale. + +**Seeding context.** The defaults on both the form and the record page's edit state are now read with the session facts a create form uses: a child field defaulted to the acting user starts on that user, and the organization's currency and time zone seed the fields they seed on a create form. With no known user that field starts empty and the server fills it, as before. diff --git a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx index a183b77b64c..336eafef7bd 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { act, render, screen, waitFor, fireEvent, within } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, within } from '@testing-library/react'; import React from 'react'; import { registerAllFields } from '@object-ui/fields'; import { MePermissionsProvider } from '@object-ui/permissions'; @@ -439,19 +439,6 @@ describe('MasterDetailForm — a new line starts on the child\'s defaults and wa ]); }); - it('form mode: Add opens the row editor on the defaults', async () => { - const ds = lineDataSource(); - render(); - // The defaults come from the child schema: let its read answer first. - await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalledWith('po_line')); - await act(async () => {}); - fireEvent.click(screen.getByTestId('line-items-add')); - const editor = await waitFor(() => screen.getByTestId('md-row-form')); - await waitFor(() => - expect((editor.querySelector('input[name="note"]') as HTMLInputElement | null)?.value).toBe('Pending'), - ); - }); - it('a line Add started and the row editor then applied is input, and is written', async () => { const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }, { id: 'l1' }] }); const { container } = render( diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 69d71feaf95..84b0b84a6a0 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -1294,8 +1294,6 @@ export const MasterDetailForm: React.FC = ({ const [resolvedEntries, setResolvedEntries] = useState(null); const entries = resolvedEntries ?? baseEntries; // length always matches rawDetails - const entriesRef = useRef(entries); - entriesRef.current = entries; /** * What the line grids draw: `entries`, each derived entry's columns re-run * with the CURRENT session words (objectui#12924). A host that has not @@ -1546,8 +1544,6 @@ export const MasterDetailForm: React.FC = ({ } return out; }, [childSchemas, perms.userId, homeCurrency, homeTimeZone]); - const newRowValuesRef = useRef(newRowValuesByChild); - newRowValuesRef.current = newRowValuesByChild; // objectstack#35940 — set when a save is tried, cleared when one lands: a // new line's empty required cell reads red from the try on. const [saveTried, setSaveTried] = useState(false); @@ -1892,16 +1888,11 @@ export const MasterDetailForm: React.FC = ({ [], ); - /** - * List/form mode "Add": append a row on the child's defaults - * (objectstack#35940) and open it in the full form. - */ + /** List/form mode "Add": append a blank row and open it in the full form. */ const addRowViaForm = useCallback((entryId: string) => { - const childObject = entriesRef.current.find((e) => e.id === entryId)?.config.childObject; - const seed = childObject ? newRowValuesRef.current[childObject] : undefined; setRowState((prev) => { const cur = prev[entryId] ?? { rows: [], original: [] }; - const rows = [...cur.rows, { ...seed }]; + const rows = [...cur.rows, {}]; setExpanded({ entryId, rowIdx: rows.length - 1, isNew: true }); return { ...prev, [entryId]: { ...cur, rows } }; }); From e642739c3d16d4560dff00227b3eb4aecd756a7d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:19:40 +0000 Subject: [PATCH 7/7] test(ui): the live record-page spec reads the skipped-line notice (#35940) Claude-Session: https://claude.ai/code/session_01L6bhgWYi6WWWnJAmc7Jtpu Co-authored-by: Claude --- ui/e2e/live/record-page-polish-35745.spec.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ui/e2e/live/record-page-polish-35745.spec.ts b/ui/e2e/live/record-page-polish-35745.spec.ts index cc6cd9591e2..ab859b774e0 100644 --- a/ui/e2e/live/record-page-polish-35745.spec.ts +++ b/ui/e2e/live/record-page-polish-35745.spec.ts @@ -12,7 +12,8 @@ import { test, expect, type Page } from '@playwright/test'; * 3. in the edit state Save is the one filled button, after Cancel; * 4. a line added to the Expense Lines table starts on the child object's * defaults (Category "Other", Status "Submitted") with no cell flagged - * red, and a line added and left as it came is not stored by the save. + * red, and a line added and left as it came is not stored by the save, + * which says so. * * ⚠️ Layout is the reason this is a Playwright spec: jsdom lays nothing out, * so the 12 px is read here off real boxes. The vitest pins @@ -113,6 +114,8 @@ test('record page polish (#35745, #35816) — showcase Expense Report', async ({ await save.click(); await expect(toolbar.getByRole('button', { name: 'Edit', exact: true })).toBeVisible({ timeout: 15_000 }); + // objectstack#35940 (ruling 7056413638): the save says the line was left out. + await expect(page.getByText('1 blank line was not saved')).toBeVisible(); // Asked of the server for this report's lines only: a filter the route // ignored would answer other reports' lines, and fail the count. const ofThisReport = encodeURIComponent(JSON.stringify([['expense_report', 'equals', id]]));