From d22f525298dc4e5a5e7f20d9e8d9aa5323415704 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:13:53 +0000 Subject: [PATCH 1/8] wip(ui): record page business dates read as the date Claude-Session: https://claude.ai/code/session_01L6bhgVhfKtUtFdDWNgeCCE Co-authored-by: Claude --- ui/packages/fields/src/index.tsx | 31 +++++++++++++++---- .../plugin-detail/src/DetailSection.tsx | 3 ++ .../plugin-detail/src/HeaderHighlight.tsx | 3 ++ 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 44b095559a9..73ea57d900c 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -456,10 +456,26 @@ export interface CellRendererProps { * tooltip. A declared `format` still wins, `'relative'` included. * * `ObjectGrid` passes it on every column cell it builds. Absent or `false` - * changes nothing, so the record detail body, the highlights strip and the - * card surfaces keep the relative default. + * changes nothing; the record page asks for the same face through + * `absoluteDate` below. */ inGridColumn?: boolean; + /** + * The cell shows a business date on a record page (objectstack#35745). Read + * by the `date` cell only, with exactly `inGridColumn`'s effect: a `date` + * field that declares no `format` paints `formatDate`'s absolute face, and + * the relative phrase becomes the cell's tooltip. + * + * The relative default made a record page read "6 days ago" for a meeting + * date the list beside it wrote as "Nov 13", and the reader had to work out + * the day. A declared `format` still wins, `'relative'` included. + * + * The record page's field sections and its highlights strip pass it; the + * record footer's system times (created, modified) do not, and keep their + * relative wording. Absent or `false` changes nothing, so the card surfaces + * keep the relative default. + */ + absoluteDate?: boolean; } // `coerceToSafeValue` lives in `./coerceToSafeValue.ts` (objectui#8580) so @@ -1264,7 +1280,7 @@ function isOverdueInstant(date: Date, dueLike: boolean): boolean { /** * Date field cell renderer */ -export function DateCellRenderer({ value, field, deadlineSettled, alwaysShowYear, inGridColumn }: CellRendererProps): React.ReactElement { +export function DateCellRenderer({ value, field, deadlineSettled, alwaysShowYear, inGridColumn, absoluteDate }: CellRendererProps): React.ReactElement { // `useDisplayLocale()`, NOT `useLocalization().locale` (objectui#4468). The // raw tenant locale is `undefined` on any workspace that never configured // one, and `Intl` reads the MACHINE's locale from `undefined` — so a `zh` @@ -1328,10 +1344,13 @@ export function DateCellRenderer({ value, field, deadlineSettled, alwaysShowYear const declaredStyle: string | undefined = dateField.format || undefined; // objectstack#25884 — in a grid column the undeclared default is the // absolute face (`formatDate`'s default, `undefined`), one face per column; - // everywhere else it stays `'relative'`. ⚠️ `ObjectGrid`'s + // a record page's field asks for the same (`absoluteDate`); everywhere else + // it stays `'relative'`. ⚠️ `ObjectGrid`'s // `temporalGroupHeading` restates this selection for its group headings, // and `groupDateHeading-13234.test.tsx` holds the two equal. - const style = declaredStyle ?? (inGridColumn ? undefined : 'relative'); + // objectstack#35745 — a record page's business date reads the same way. + const absoluteByDefault = inGridColumn || absoluteDate; + const style = declaredStyle ?? (absoluteByDefault ? undefined : 'relative'); // Both halves of the affordance come from the shared reads above, so the // `datetime` sibling one function down answers this question identically @@ -1344,7 +1363,7 @@ export function DateCellRenderer({ value, field, deadlineSettled, alwaysShowYear // The relative phrase the grid default no longer paints ("Yesterday", // "Overdue 3d") is the tooltip instead. Outside the ±7-day window the phrase // IS the absolute face, which says nothing new, so the ISO `title` stays. - const relative = inGridColumn && declaredStyle === undefined + const relative = absoluteByDefault && declaredStyle === undefined ? formatDate(safe as string | Date, 'relative', options) : undefined; const title = relative !== undefined && relative !== formatted ? relative : date.toISOString(); diff --git a/ui/packages/plugin-detail/src/DetailSection.tsx b/ui/packages/plugin-detail/src/DetailSection.tsx index e39e0140809..2d01ab7b877 100644 --- a/ui/packages/plugin-detail/src/DetailSection.tsx +++ b/ui/packages/plugin-detail/src/DetailSection.tsx @@ -751,6 +751,9 @@ export const DetailSection: React.FC = ({ // "Oct 2" in a section was two formats on one page. Grid cells // keep the shared face that drops it. alwaysShowYear + // A business date reads as the date, as the list writes it, with + // the relative phrase as its tooltip (objectstack#35745). + absoluteDate /> ); } diff --git a/ui/packages/plugin-detail/src/HeaderHighlight.tsx b/ui/packages/plugin-detail/src/HeaderHighlight.tsx index 143764604a9..de1e8d053f6 100644 --- a/ui/packages/plugin-detail/src/HeaderHighlight.tsx +++ b/ui/packages/plugin-detail/src/HeaderHighlight.tsx @@ -511,6 +511,9 @@ export const HeaderHighlight: React.FC = ({ // ("Start Date Sep 15, 2025") read as next month. // Grid cells keep the shared face that drops it. alwaysShowYear + // The date itself, not "6 days ago" + // (objectstack#35745). + absoluteDate /> )} From 6e61def35623e97c3e24c10339e0a2a791af320a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:17:39 +0000 Subject: [PATCH 2/8] test(ui): pin the record page's absolute business date Claude-Session: https://claude.ai/code/session_01L6bhgVhfKtUtFdDWNgeCCE Co-authored-by: Claude --- .../DetailSection.dateYear-27520.test.tsx | 55 +++++++++++++++++++ .../recordPage.deadlineSettled-11815.test.tsx | 22 ++++++-- 2 files changed, 71 insertions(+), 6 deletions(-) diff --git a/ui/packages/plugin-detail/src/__tests__/DetailSection.dateYear-27520.test.tsx b/ui/packages/plugin-detail/src/__tests__/DetailSection.dateYear-27520.test.tsx index 1de81aa7929..bfbbc3d1528 100644 --- a/ui/packages/plugin-detail/src/__tests__/DetailSection.dateYear-27520.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/DetailSection.dateYear-27520.test.tsx @@ -91,3 +91,58 @@ describe('one date format on a record page (objectstack#27520 row 14)', () => { expect(screen.getByText('Oct 2')).toBeTruthy(); }); }); + +/** + * A business date on a record page reads as the date (objectstack#35745). + * + * The sighting: a meeting's date, Nov 13, read "6 days ago" on the record page + * while the list wrote "Nov 13", so the reader had to work out the day. The + * page's date fields now take the absolute face the list's columns take + * (objectstack#25884), inside the ±7-day window too, and the relative phrase + * is the date's tooltip. A declared `format` still wins. + */ +describe('a record page writes a business date as the date (objectstack#35745)', () => { + const days = { + past: { iso: '2026-10-29', text: 'Oct 29, 2026', phrase: '3 days ago' }, + today: { iso: '2026-11-01', text: 'Nov 1, 2026', phrase: 'Today' }, + future: { iso: '2026-11-05', text: 'Nov 5, 2026', phrase: 'In 4 days' }, + }; + const meetingSchema = { fields: { meeting_date: { name: 'meeting_date', type: 'date', label: 'Meeting Date' } } }; + const meetingSection = { + title: 'Meeting', + fields: [{ name: 'meeting_date', label: 'Meeting Date', type: 'date' }], + } as unknown as DetailViewSection; + + for (const [when, day] of Object.entries(days)) { + it(`a section row writes a ${when} date in the relative window as the date, the phrase as its tooltip`, () => { + render(); + const cell = screen.getByText(day.text); + expect(cell.getAttribute('title')).toBe(day.phrase); + expect(screen.queryByText(day.phrase)).toBeNull(); + }); + } + + it('the highlights strip writes it the same way', () => { + render( + , + ); + expect(screen.getByText(days.past.text).getAttribute('title')).toBe(days.past.phrase); + }); + + it('a declared `relative` format still wins', () => { + const declared = { fields: { meeting_date: { ...meetingSchema.fields.meeting_date, format: 'relative' } } }; + render(); + expect(screen.getByText(days.past.phrase)).toBeTruthy(); + }); + + it('CONTROL: the shared date cell without the record page keeps the relative default', () => { + const DateCell = getCellRenderer('date'); + const field: DateFieldMetadata = { name: 'meeting_date', label: 'Meeting Date', type: 'date' }; + render(); + expect(screen.getByText(days.past.phrase)).toBeTruthy(); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/recordPage.deadlineSettled-11815.test.tsx b/ui/packages/plugin-detail/src/__tests__/recordPage.deadlineSettled-11815.test.tsx index 4c3159de72a..46c93a35711 100644 --- a/ui/packages/plugin-detail/src/__tests__/recordPage.deadlineSettled-11815.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/recordPage.deadlineSettled-11815.test.tsx @@ -19,6 +19,7 @@ import * as React from 'react'; import { DetailSection } from '../DetailSection'; import { HeaderHighlight } from '../HeaderHighlight'; import type { DetailViewSection } from '@object-ui/types'; +import { formatDate } from '@object-ui/core'; beforeAll(() => { Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 }); @@ -48,9 +49,18 @@ const OBJECT_SCHEMA = { const SECTION = { title: 'S', fields: [{ name: 'due_date', label: 'Due' }] } as unknown as DetailViewSection; +// objectstack#35745 — a record page writes a business date as the date (with +// its year, objectui#13331); the relative phrase, the overdue wording +// included, is the date's tooltip. The red styling is the face's, unchanged. +const dateText = (iso: string): string => formatDate(iso, undefined, { alwaysShowYear: true }); + const dueSpan = (container: HTMLElement) => { const span = container.querySelector('span.tabular-nums') as HTMLElement | null; - return { text: span?.textContent ?? '', red: !!span?.className.includes('text-red-600') }; + return { + text: span?.textContent ?? '', + tooltip: span?.getAttribute('title') ?? '', + red: !!span?.className.includes('text-red-600'), + }; }; describe('DetailSection — a declared deadline is judged against the record (objectui#11815)', () => { @@ -58,14 +68,14 @@ describe('DetailSection — a declared deadline is judged against the record (ob const { container } = render( , ); - expect(dueSpan(container)).toEqual({ text: 'Overdue 5d', red: true }); + expect(dueSpan(container)).toEqual({ text: dateText(daysAgo(5)), tooltip: 'Overdue 5d', red: true }); }); it('a done record past the same deadline reads neutral, with no red', () => { const { container } = render( , ); - expect(dueSpan(container)).toEqual({ text: '5 days ago', red: false }); + expect(dueSpan(container)).toEqual({ text: dateText(daysAgo(5)), tooltip: '5 days ago', red: false }); }); it('CONTROL — an undeclared due_date past its day reads neutral on an open record', () => { @@ -73,7 +83,7 @@ describe('DetailSection — a declared deadline is judged against the record (ob const { container } = render( , ); - expect(dueSpan(container)).toEqual({ text: '5 days ago', red: false }); + expect(dueSpan(container)).toEqual({ text: dateText(daysAgo(5)), tooltip: '5 days ago', red: false }); }); }); @@ -84,13 +94,13 @@ describe('HeaderHighlight — the same judgement on the highlights strip (object const { container } = render( , ); - expect(dueSpan(container)).toEqual({ text: 'Overdue 5d', red: true }); + expect(dueSpan(container)).toEqual({ text: dateText(daysAgo(5)), tooltip: 'Overdue 5d', red: true }); }); it('a done record past the same deadline reads neutral, with no red', () => { const { container } = render( , ); - expect(dueSpan(container)).toEqual({ text: '5 days ago', red: false }); + expect(dueSpan(container)).toEqual({ text: dateText(daysAgo(5)), tooltip: '5 days ago', red: false }); }); }); From 8a00251adc2618364578b397679fd8d84fcbb9ae Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:20:05 +0000 Subject: [PATCH 3/8] fix(ui): a new detail line starts on its defaults and reads red only after a refused save Claude-Session: https://claude.ai/code/session_01L6bhgVhfKtUtFdDWNgeCCE Co-authored-by: Claude --- .../fields/src/widgets/GridField.test.tsx | 37 ++++++++++++++++ ui/packages/fields/src/widgets/GridField.tsx | 32 +++++++++++++- ...yTableEditor.recordEditBatch-35599.test.ts | 43 +++++++++++++++++++ .../plugin-form/src/RecordBodyTableEditor.tsx | 22 +++++++++- ui/packages/plugin-form/src/masterDetailTx.ts | 25 +++++++++-- 5 files changed, 152 insertions(+), 7 deletions(-) diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index db58567d181..5a4ecb81569 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -780,3 +780,40 @@ describe('GridField — a boolean column read as a boolean by the cell rules (ob expect(screen.queryByTestId('line-items-invalid-1-reason')).toBeNull(); }); }); + +describe('GridField — a new line starts on its defaults and waits to read red (objectstack#35816)', () => { + 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('Add and the entry line both start a line on the host\'s values', () => { + const onChange = vi.fn(); + const { container } = render( + , + ); + fireEvent.click(screen.getByRole('button', { name: /Add line/i })); + expect(onChange).toHaveBeenLastCalledWith([{ name: null, status: 'pending' }]); + const entryName = container.querySelector('[data-cell="0-0"]') as HTMLInputElement; + fireEvent.change(entryName, { target: { value: 'Book the room' } }); + expect(onChange).toHaveBeenLastCalledWith([{ name: 'Book the room', status: 'pending' }]); + }); + + it('a new line\'s empty required cell is not flagged until the host says so; a stored line is', () => { + const rows = [{ id: 't1', name: null, status: 'open' }, { name: null, status: 'pending' }]; + const { rerender } = render( + {}} field={taskColumns} newRowRequiredShown={false} />, + ); + expect(screen.getByTestId('line-items-invalid-0-name')).toBeTruthy(); + expect(screen.queryByTestId('line-items-invalid-1-name')).toBeNull(); + rerender( {}} field={taskColumns} newRowRequiredShown />); + expect(screen.getByTestId('line-items-invalid-1-name').getAttribute('title')).toBe('Name is required'); + }); + + it('CONTROL: without the host\'s word a new line is flagged at once, as before', () => { + render( {}} field={taskColumns} />); + 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 9d5bd995885..8f190ac19cc 100644 --- a/ui/packages/fields/src/widgets/GridField.tsx +++ b/ui/packages/fields/src/widgets/GridField.tsx @@ -684,6 +684,20 @@ type GridFieldProps = FieldWidgetComponentProps & { * so the master-detail host that holds the header and the child schema * hands it over. A column it does not name is in the tenant currency. */ columnCurrencies?: ColumnCurrencies; + /** The values a new line starts with (objectstack#35816): the child + * object's static field defaults, by field name. A grid column carries no + * default (the spec's inline column refuses `defaultValue`), so the host + * that holds the child schema hands them over. Every new line takes them: + * the trailing entry line, "Add", and a line typed into the entry line. A + * line already in the value keeps what it holds. Absent: a new line starts + * blank, as before. */ + newRowValues?: Row; + /** When the host sets it, an empty required cell on a NEW line (one with + * 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. */ + newRowRequiredShown?: boolean; }; /** @@ -749,6 +763,11 @@ function RetiredGridFieldKeys({ message, keys }: { message: string; keys: readon ); } +/** A line the server already stores carries its id (`id`, `_id` or `recordId`). */ +function rowHasId(row: Row): boolean { + return [row.id, row._id, row.recordId].some((v) => v != null && v !== ''); +} + /** * The `grid` field widget. A field whose metadata carries one of the retired * snake_case keys is refused by name ({@link RetiredGridFieldKeys}); any other @@ -776,6 +795,8 @@ function GridFieldBody({ onAdd, lookupAutofill, columnCurrencies, + newRowValues, + newRowRequiredShown, ...props }: GridFieldProps) { // The field-level keys, read as `GridFieldMetadata` declares them and as @@ -931,8 +952,10 @@ function GridFieldBody({ const blankRow = useCallback((): Row => { const blank: Row = {}; for (const c of columns) blank[c.name] = null; - return blank; - }, [columns]); + // objectstack#35816 — a new line starts on the defaults the host knows, + // so a required column with a default is filled, not flagged empty. + return newRowValues ? { ...blank, ...newRowValues } : blank; + }, [columns, newRowValues]); /** * Merge a field patch into a row. `rowIdx === rows.length` targets the @@ -1523,8 +1546,13 @@ function GridFieldBody({ // grid failed while empty (objectui#3318) — see // `hostFailedEmpty`. 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. + const newRowWaits = + newRowRequiredShown === false && !isGhost && !rowHasId(row); const invalid = (!isGhost || hostFailedEmpty) && + !newRowWaits && !isList && required && !c.computed && diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts index f9190e805e3..014afb89935 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts @@ -79,6 +79,49 @@ describe('buildRecordEditBatch — one batch for the record and all its body tab }); }); +describe('buildRecordEditBatch — a new line that kept the defaults it started on (objectstack#35816)', () => { + const tasks = { + id: 'meeting_task.meeting', + childObject: 'meeting_task', + relationshipField: 'meeting', + childSchema: { + fields: { + id: { type: 'text' }, + name: { type: 'text' }, + status: { type: 'select', defaultValue: 'pending' }, + meeting: { type: 'master_detail' }, + }, + }, + newRowValues: { status: 'pending' }, + original: [], + rows: [ + { name: null, status: 'pending' }, // added, left as it came: no op + { name: 'Book the room', status: 'pending' }, // typed a name: created with the default + { name: null, status: 'done' }, // changed the default: that is input + ], + }; + + it('is skipped like a blank line; a line with input is created, its default included, traced to its position', () => { + const { ops, owners } = buildRecordEditBatch('meeting', 'm1', {}, [tasks]); + expect(ops.map((o) => [o.object, o.action])).toEqual([ + ['meeting', 'update'], + ['meeting_task', 'create'], + ['meeting_task', 'create'], + ]); + expect(ops[1].data).toMatchObject({ name: 'Book the room', status: 'pending', meeting: 'm1' }); + expect(ops[2].data).toMatchObject({ status: 'done', meeting: 'm1' }); + expect(owners.slice(1)).toEqual([ + { kind: 'row', table: 'meeting_task.meeting', row: 1 }, + { kind: 'row', table: 'meeting_task.meeting', row: 2 }, + ]); + }); + + it('CONTROL: without the start values the same untouched line is input and is created', () => { + const { ops } = buildRecordEditBatch('meeting', 'm1', {}, [{ ...tasks, newRowValues: undefined }]); + expect(ops.filter((o) => o.action === 'create')).toHaveLength(3); + }); +}); + describe('attributeRecordEditRefusal — a refused batch is placed where it belongs', () => { const { ops, owners } = buildRecordEditBatch('order', 'o1', { name: 'Renamed' }, [lines, notes]); const refused = (fields: Array<{ field: string; message: string }>) => diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index 1967ac92149..4de008713ec 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -48,6 +48,7 @@ import { import { buildMasterDetailEditBatch, idOf, isBlankRow, type ChildSchema } from './masterDetailTx'; import { applyColumnPermissions } from './fieldWriteGate'; import { deriveDetail } from './deriveMasterDetail'; +import { schemaDefaultValues } from './schemaDefaults'; import { useFormChromeTranslation } from './formChrome'; /** One reason the server gave about one line of a body table. */ @@ -66,6 +67,8 @@ export interface BodyTableSnapshot { rows: Record[]; original: Record[]; childSchema: ChildSchema; + /** The values a new line starts on: the child object's static defaults. */ + newRowValues?: Record; } /** One body-table editor, as the host's session sees it. */ @@ -114,7 +117,7 @@ export function buildRecordEditBatch( // skipping blank rows; then updates; then deletes. const createRows = t.rows .map((r, i) => ({ r, i })) - .filter(({ r }) => !idOf(r) && !isBlankRow({ ...r, [t.relationshipField]: parentId }, t.relationshipField)); + .filter(({ r }) => !idOf(r) && !isBlankRow({ ...r, [t.relationshipField]: parentId }, t.relationshipField, t.newRowValues)); let createCursor = 0; for (const op of tableOps) { let row = -1; @@ -266,9 +269,19 @@ export const RecordBodyTableEditor: React.FC = ({ ob return () => { cancelled = true; }; }, [dataSource, parentId, derived, objectName, relationshipField]); + // objectstack#35816 — a new line starts on the child object's static + // 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. + const newRowValues = useMemo( + () => schemaDefaultValues(childSchema as Parameters[0]), + [childSchema], + ); + const snapshotRef = useRef(null); snapshotRef.current = rows && derived - ? { childObject: objectName, relationshipField, rows, original, childSchema } + ? { childObject: objectName, relationshipField, rows, original, childSchema, newRowValues } : null; const register = session?.register; @@ -317,6 +330,11 @@ export const RecordBodyTableEditor: React.FC = ({ ob disabled={session.saving} contextRecord={record?.data as Record | undefined} lookupAutofill={lookupAutofillByField(childSchema?.fields as Record | undefined)} + newRowValues={newRowValues} + // objectstack#35816 — a new line's empty required cell reads red + // once a save was refused, not the moment the line appears; the + // server stays the judge of what is missing. + newRowRequiredShown={rowErrors !== null || tableErrors !== null} field={({ columns: applyColumnPermissions(derived.columns as GridColumn[], { perms, objectName, mode: 'edit' }), totalField: derived.amountField, diff --git a/ui/packages/plugin-form/src/masterDetailTx.ts b/ui/packages/plugin-form/src/masterDetailTx.ts index 6e692f556a1..444721ee862 100644 --- a/ui/packages/plugin-form/src/masterDetailTx.ts +++ b/ui/packages/plugin-form/src/masterDetailTx.ts @@ -74,6 +74,10 @@ export interface BatchDetailInput { /** When supplied, child write payloads are sanitized against it (drops * computed / read-only / unknown fields). Omit to persist rows as-is. */ childSchema?: ChildSchema; + /** The values a new line started on (`LineItemsField`'s `newRowValues`). + * A new line that still holds only these is no input, and is skipped like + * a blank one ({@link isBlankRow}). */ + newRowValues?: Record; } /** Edit-mode detail input: current rows + the loaded snapshot to diff against. */ @@ -98,14 +102,29 @@ const ID_KEYS = new Set(['id', '_id', 'recordId']); * drop the always-present trailing "ghost" line (and any row the user cleared) * so it never persists as an empty child record. */ -export function isBlankRow(row: Record, relationshipField?: string): boolean { +export function isBlankRow( + row: Record, + relationshipField?: string, + newRowValues?: Record, +): boolean { if (!row) return true; return Object.entries(row).every(([k, v]) => { if (k === relationshipField || ID_KEYS.has(k)) return true; - return v === null || v === undefined || v === ''; + if (v === null || v === undefined || v === '') return true; + // objectstack#35816 — a value the line started on is the default, not + // input: a line the user added and left as it came is still blank. + return newRowValues !== undefined + && Object.prototype.hasOwnProperty.call(newRowValues, k) + && sameValue(v, newRowValues[k]); }); } +function sameValue(a: unknown, b: unknown): boolean { + if (a === b) return true; + if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false; + return JSON.stringify(a) === JSON.stringify(b); +} + /** * Build cross-object batch operations for an ATOMIC master-detail create: * the parent at index 0, then each child with its relationship FK set to @@ -147,7 +166,7 @@ export function buildMasterDetailEditBatch( const withFk = (d.rows || []).map((r) => ({ ...r, [d.relationshipField]: parentId })); const { toCreate, toUpdate, toDelete } = diffRows(d.original || [], withFk); for (const row of toCreate) { - if (isBlankRow(row, d.relationshipField)) continue; // skip the ghost/empty line + if (isBlankRow(row, d.relationshipField, d.newRowValues)) continue; // skip the ghost/empty line // Strip any client-only id so the server generates one. const { id: _omit, _id: _omit2, recordId: _omit3, ...clean } = row as any; ops.push({ object: d.childObject, action: 'create', data: toWritable(clean, d.childSchema) }); From 95d0c441a1c423fb18573ea5800c7450d7ef5b17 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:21:20 +0000 Subject: [PATCH 4/8] fix(ui): Save is the edit state's one filled button, after Cancel Claude-Session: https://claude.ai/code/session_01L6bhgVhfKtUtFdDWNgeCCE Co-authored-by: Claude --- .../app-shell/src/views/RecordDetailView.tsx | 3 + .../page-header-primary-12617.test.tsx | 55 +++++++++++++++++++ .../src/renderers/layout/containers.tsx | 12 +++- 3 files changed, 68 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 8b8b7af456a..a61968f6f46 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -4845,6 +4845,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri icon: 'check', type: 'script', locations: ['record_header'], + // objectstack#35816 — Save is the edit state's one filled button, and + // keeps its place after Cancel, as a form's footer orders them. + variant: 'primary', order: 100, disabled: recordEditSaving, onClick: () => { void recordEditControlRef.current?.save(); }, diff --git a/ui/packages/components/src/__tests__/page-header-primary-12617.test.tsx b/ui/packages/components/src/__tests__/page-header-primary-12617.test.tsx index 29dfa9df573..24c6351eb05 100644 --- a/ui/packages/components/src/__tests__/page-header-primary-12617.test.tsx +++ b/ui/packages/components/src/__tests__/page-header-primary-12617.test.tsx @@ -158,3 +158,58 @@ describe('page:header draws one primary action, the rest secondary (objectui#126 expect(isFilled(buttons[0])).toBe(true); }); }); + +/** + * objectstack#35816: the record page's edit state draws Cancel and Save, and + * Save is the one filled button. The edit state's Cancel came first in `order` + * and so drew as the primary: the hand fell on the button that throws the edit + * away. A host button declaring `variant: 'primary'` is now the primary over + * every page action, and keeps the place the host gave it (Cancel, then Save, + * as a form's footer orders them). + */ +describe("page:header — a host button declaring `variant: 'primary'` is the primary in place (objectstack#35816)", () => { + const EDIT_STATE = [ + { name: 'sys_record_edit_cancel', label: 'Cancel', icon: 'x', variant: 'outline', order: 99, onClick: vi.fn() }, + { name: 'sys_record_edit_save', label: 'Save', icon: 'check', variant: 'primary', order: 100, onClick: vi.fn() }, + { name: 'sys_share', label: 'Share', order: 110, component: 'action:menu', onClick: vi.fn() }, + ]; + const renderEditState = (actions: any[], hosts: any[] = EDIT_STATE) => + render( + + + + + , + ); + const rowButtons = () => toolbarButtons().filter((b) => nameOf(b) !== 'More actions'); + + it('Cancel then Save, Save the only filled button', () => { + renderEditState([]); + const buttons = rowButtons(); + expect(buttons.map(nameOf)).toEqual(['Cancel', 'Save']); + expect(buttons.map(isFilled)).toEqual([false, true]); + expect(isOutline(buttons[0])).toBe(true); + }); + + it("Save stays the primary beside the page's own actions, one declaring `variant: 'primary'` included", () => { + renderEditState([act('log_call', 'Log a Call'), act('convert_lead', 'Convert Lead', { variant: 'primary' })]); + const buttons = rowButtons(); + // The page's actions keep the memo's sort (`variant: 'primary'` breaks the + // `order` tie); only the filled style moves to Save. + expect(buttons.map(nameOf)).toEqual(['Convert Lead', 'Log a Call', 'Cancel', 'Save']); + expect(buttons.map(isFilled)).toEqual([false, false, false, true]); + }); + + it('CONTROL: with no host primary, the first page action still leads as the primary', () => { + renderEditState([act('log_call', 'Log a Call')], EDIT_STATE.map((a) => (a.name === 'sys_record_edit_save' ? { ...a, variant: undefined } : a))); + const buttons = rowButtons(); + expect(buttons.map(nameOf)).toEqual(['Log a Call', 'Cancel', 'Save']); + expect(buttons.map(isFilled)).toEqual([true, false, false]); + }); +}); diff --git a/ui/packages/components/src/renderers/layout/containers.tsx b/ui/packages/components/src/renderers/layout/containers.tsx index c542c310877..23c28bbefef 100644 --- a/ui/packages/components/src/renderers/layout/containers.tsx +++ b/ui/packages/components/src/renderers/layout/containers.tsx @@ -2647,9 +2647,17 @@ export const PageHeaderActions: React.FC = ({ const isHostButton = (a: unknown): boolean => isHostAction(a) && !isDestructiveAction(a); const rowEligible = buttonable.filter((a) => !isHostAction(a) || isHostButton(a)); const primaryCandidates = rowEligible.filter((a) => !isDestructiveAction(a)); + // A HOST button declaring `variant: 'primary'` is the primary whatever the + // page declares, and keeps the place the host gave it (objectstack#35816): + // the record page's edit state draws Cancel then Save, as a form's footer + // does, and Save is the one filled button. Before this the edit state's + // Cancel came first in `order` and drew as the primary, so the hand fell + // on the button that throws the edit away. No other host button declares + // a variant of `primary`, so every other row is unchanged. + const hostPrimary = primaryCandidates.find((a) => isHostButton(a) && a?.variant === 'primary'); const primaryIdx = primaryCandidates.findIndex((a) => a?.variant === 'primary'); - const primaryAction: unknown = primaryCandidates[primaryIdx >= 0 ? primaryIdx : 0]; - const ranked = primaryAction + const primaryAction: unknown = hostPrimary ?? primaryCandidates[primaryIdx >= 0 ? primaryIdx : 0]; + const ranked = primaryAction && !hostPrimary ? [primaryAction, ...buttonable.filter((a) => a !== primaryAction)] : buttonable; // The page's own actions share the `maxVisible` budget; what does not fit From 6da433b0ce08afd12171a73244c32e423c09fd22 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:40:44 +0000 Subject: [PATCH 5/8] fix(ui): the record page's tab row follows its header, with no blank band Claude-Session: https://claude.ai/code/session_01L6bhgVhfKtUtFdDWNgeCCE Co-authored-by: Claude --- .changeset/35745-35816-record-page-polish.md | 20 +++++++++++++++++++ .../app-shell/src/views/RecordDetailView.tsx | 10 +++++++--- .../plugin-detail/src/RecordPageColumns.tsx | 6 +++++- 3 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 .changeset/35745-35816-record-page-polish.md diff --git a/.changeset/35745-35816-record-page-polish.md b/.changeset/35745-35816-record-page-polish.md new file mode 100644 index 00000000000..0c65ca24e87 --- /dev/null +++ b/.changeset/35745-35816-record-page-polish.md @@ -0,0 +1,20 @@ +--- +'@object-ui/fields': minor +'@object-ui/plugin-detail': minor +'@object-ui/plugin-form': minor +'@object-ui/components': minor +'@object-ui/app-shell': minor +--- + +fix(record-page): business dates read as dates, Save is the edit state's primary button, and a new detail line starts on its defaults + +Clause-②: yes (widening) +Metadata-protocol: semantic + +Three things on the record page. + +**Dates.** A `date` field that declares no `format` read as a relative phrase on the record page ("6 days ago", "Tomorrow") while the list beside it wrote the date ("Nov 13"), so the reader had to work the day out. The record page's field sections and its highlights strip now write the date itself, with its year, as the list's columns do; the relative phrase (an overdue deadline's "Overdue 5d" included) is the date's tooltip, and a deadline past due still reads red. A declared `format`, `'relative'` included, still wins. The record footer's created and modified times keep their relative wording, and card surfaces (kanban, gallery) are unchanged. `@object-ui/fields`' cell props gain `absoluteDate`, read by the `date` cell. + +**Edit-state buttons.** In the record page's edit state, Cancel drew as the filled primary button and Save as an outline one, so the hand fell on the button that throws the edit away. Save is now the one filled button, after Cancel, the order a form's footer uses. `page:header` now makes a host button declaring `variant: 'primary'` the primary over the page's own actions, in the place the host gave it; no other host button declares one, so every other header is unchanged. + +**New detail lines.** A line added to a master-detail table in the record page's edit state started blank, so a required column with a default (a status that defaults to "Pending") read red although the save then stored the default. A new line now starts on the child object's static defaults, the values a create form seeds; 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 only after a save was refused, with the server's reason listed under the table; a stored line is flagged as before. A new line left as it came, holding only its defaults, is still skipped at save like a blank one. `LineItemsField` gains `newRowValues` and `newRowRequiredShown`, and `isBlankRow` (with the batch inputs) an optional `newRowValues`; a host that passes neither sees no change. The save request and its transaction are unchanged. diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index a61968f6f46..85ccacdaa70 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -5754,7 +5754,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri handlers={{ api: apiActionHandler, flow: flowHandler, script: serverActionHandler, modal: modalActionHandler }} >
-
+ {/* objectstack#35745 — no top padding here: the record page under + it pads its own top (`RecordPageColumns`, the `page` root), so + the tab row sits 12px under the header instead of under a 48px + band of two paddings stacked. */} +
{/* objectui#12906 — the print page's screen-only chrome. A page that declares `print` holds only the printable component types, and `page:header` is not one of them, so the record's @@ -5771,7 +5775,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri `print` draws none of it and keeps its own `page:header`. */} {pageDeclaresPrint && (
{sharedChrome} @@ -5807,7 +5811,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri its layout effect, before the page paints. */} {approvalBarMounted && approvalGroupHosts === 0 && ( = ({
From f2d8fbd95fe56010325df845518e1e5a2b9569dc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:41:19 +0000 Subject: [PATCH 6/8] test(ui): pin the record page root's 12px top Claude-Session: https://claude.ai/code/session_01L6bhgVhfKtUtFdDWNgeCCE Co-authored-by: Claude --- .../src/__tests__/RecordPageColumns.test.tsx | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx index cbb0ea41891..c11b63a3209 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx @@ -136,6 +136,21 @@ describe('RecordPageColumns — details | the right column (objectstack#27524, T }); }); +describe('RecordPageColumns — the tab row follows the header (objectstack#35745)', () => { + // Measured in the browser (1280, Expense Report): the header's bottom at 92, + // the tab row at 140 — the host scroller's 24px top padding and this root's + // 24px stacked. The host's scroller pads no top now (RecordDetailView), and + // this root's top is 12px at every width; the sides and foot keep the page's. + it("the root's top padding is 12px at every width, its sides and foot the page's", () => { + const { container } = render(); + const root = container.querySelector('[data-page-type="record"]')!; + const classes = root.className.split(/\s+/); + expect(classes).toContain('pt-3'); + expect(classes.filter((c) => /^(?:\w+:)?(?:p|pt|py)-/.test(c) && c !== 'pt-3')).toEqual([]); + expect(classes).toEqual(expect.arrayContaining(['px-3', 'md:px-4', 'lg:px-6', 'pb-3', 'md:pb-4', 'lg:pb-6'])); + }); +}); + describe('RecordPageColumns — the stack (< 760, objectstack#27524, Target 6)', () => { it('ONE column: the details and their footer, then the rail — no tabs without a host', () => { const { container } = render( From b879b395fc321fa1dd9a509dfe419c57962ac198 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:14:51 +0000 Subject: [PATCH 7/8] chore(ui): pay the react runtime load at collection; changeset names the tab gap Claude-Session: https://claude.ai/code/session_01L6bhgVhfKtUtFdDWNgeCCE Co-authored-by: Claude --- .changeset/35745-35816-record-page-polish.md | 6 ++++-- .../src/__tests__/page-header-primary-12617.test.tsx | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.changeset/35745-35816-record-page-polish.md b/.changeset/35745-35816-record-page-polish.md index 0c65ca24e87..4bff908dfff 100644 --- a/.changeset/35745-35816-record-page-polish.md +++ b/.changeset/35745-35816-record-page-polish.md @@ -6,15 +6,17 @@ '@object-ui/app-shell': minor --- -fix(record-page): business dates read as dates, Save is the edit state's primary button, and a new detail line starts on its defaults +fix(record-page): business dates read as dates, Save is the edit state's primary button, a new detail line starts on its defaults, and the tabs follow the header with no blank band Clause-②: yes (widening) Metadata-protocol: semantic -Three things on the record page. +Four things on the record page. **Dates.** A `date` field that declares no `format` read as a relative phrase on the record page ("6 days ago", "Tomorrow") while the list beside it wrote the date ("Nov 13"), so the reader had to work the day out. The record page's field sections and its highlights strip now write the date itself, with its year, as the list's columns do; the relative phrase (an overdue deadline's "Overdue 5d" included) is the date's tooltip, and a deadline past due still reads red. A declared `format`, `'relative'` included, still wins. The record footer's created and modified times keep their relative wording, and card surfaces (kanban, gallery) are unchanged. `@object-ui/fields`' cell props gain `absoluteDate`, read by the `date` cell. **Edit-state buttons.** In the record page's edit state, Cancel drew as the filled primary button and Save as an outline one, so the hand fell on the button that throws the edit away. Save is now the one filled button, after Cancel, the order a form's footer uses. `page:header` now makes a host button declaring `variant: 'primary'` the primary over the page's own actions, in the place the host gave it; no other host button declares one, so every other header is unchanged. **New detail lines.** A line added to a master-detail table in the record page's edit state started blank, so a required column with a default (a status that defaults to "Pending") read red although the save then stored the default. A new line now starts on the child object's static defaults, the values a create form seeds; 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 only after a save was refused, with the server's reason listed under the table; a stored line is flagged as before. A new line left as it came, holding only its defaults, is still skipped at save like a blank one. `LineItemsField` gains `newRowValues` and `newRowRequiredShown`, and `isBlankRow` (with the batch inputs) an optional `newRowValues`; a host that passes neither sees no change. The save request and its transaction are unchanged. + +**The band above the tabs.** The record page's scroller and its column layout each padded their top by 24px on a desktop, so a 48px empty band stood between the header and the tab row. The scroller now pads only its sides and bottom, and the column layout keeps a 12px top on every width, so the tabs follow the header at the gap the rest of the page uses; on a phone the title block keeps 16px to the tabs. The print chrome and the approval actions bar that render above the columns keep their own top margin. Side padding is unchanged. diff --git a/ui/packages/components/src/__tests__/page-header-primary-12617.test.tsx b/ui/packages/components/src/__tests__/page-header-primary-12617.test.tsx index 24c6351eb05..ee06fae6231 100644 --- a/ui/packages/components/src/__tests__/page-header-primary-12617.test.tsx +++ b/ui/packages/components/src/__tests__/page-header-primary-12617.test.tsx @@ -35,6 +35,9 @@ import { ActionProvider, RecordContextProvider } from '@object-ui/react'; // Registers `page:header` at module scope rather than in a hook // (object-ui/no-dynamic-import-in-test-hook, objectui#3010). import '../renderers'; +// `page` reaches the react runtime through a dynamic import: pay that load at +// collection, not inside a clocked case. +import '@object-ui/react-runtime'; function PageHeader({ schema }: { schema: any }) { const Component = ComponentRegistry.get('page:header'); From 1f0b5268ee29b030dfa005d3a53ffacf74f41722 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 21:43:46 +0000 Subject: [PATCH 8/8] fix(ui): skip a new detail line only while untouched; pin datetime, the hosted pages' top and the record page live Claude-Session: https://claude.ai/code/session_01L6bhgVhfKtUtFdDWNgeCCE Co-authored-by: Claude --- .changeset/35745-35816-record-page-polish.md | 6 +- ui/e2e/live/record-page-polish-35745.spec.ts | 124 +++++++++++ .../RecordDetailView.topInset-35745.test.tsx | 197 ++++++++++++++++++ ui/packages/fields/src/index.tsx | 2 +- .../fields/src/widgets/GridField.test.tsx | 32 ++- ui/packages/fields/src/widgets/GridField.tsx | 35 +++- .../DetailSection.dateYear-27520.test.tsx | 24 +++ ...yTableEditor.recordEditBatch-35599.test.ts | 24 ++- .../plugin-form/src/RecordBodyTableEditor.tsx | 6 +- ui/packages/plugin-form/src/masterDetailTx.ts | 32 +-- 10 files changed, 439 insertions(+), 43 deletions(-) create mode 100644 ui/e2e/live/record-page-polish-35745.spec.ts create mode 100644 ui/packages/app-shell/src/views/RecordDetailView.topInset-35745.test.tsx diff --git a/.changeset/35745-35816-record-page-polish.md b/.changeset/35745-35816-record-page-polish.md index 4bff908dfff..e41703fdefc 100644 --- a/.changeset/35745-35816-record-page-polish.md +++ b/.changeset/35745-35816-record-page-polish.md @@ -13,10 +13,10 @@ Metadata-protocol: semantic Four things on the record page. -**Dates.** A `date` field that declares no `format` read as a relative phrase on the record page ("6 days ago", "Tomorrow") while the list beside it wrote the date ("Nov 13"), so the reader had to work the day out. The record page's field sections and its highlights strip now write the date itself, with its year, as the list's columns do; the relative phrase (an overdue deadline's "Overdue 5d" included) is the date's tooltip, and a deadline past due still reads red. A declared `format`, `'relative'` included, still wins. The record footer's created and modified times keep their relative wording, and card surfaces (kanban, gallery) are unchanged. `@object-ui/fields`' cell props gain `absoluteDate`, read by the `date` cell. +**Dates.** A `date` field that declares no `format` read as a relative phrase on the record page ("6 days ago", "Tomorrow") while the list beside it wrote the date ("Nov 13"), so the reader had to work the day out. The record page's field sections and its highlights strip now write the date itself, with its year, as the list's columns do; the relative phrase (an overdue deadline's "Overdue 5d" included) is the date's tooltip, and a deadline past due still reads red. A declared `format`, `'relative'` included, still wins. A `datetime` field already read as an absolute date there (its cell's default face is the compact one, never the relative phrase), and is now pinned to stay so. The record footer's created and modified times keep their relative wording, and card surfaces (kanban, gallery) are unchanged. `@object-ui/fields`' cell props gain `absoluteDate`, read by the `date` cell. **Edit-state buttons.** In the record page's edit state, Cancel drew as the filled primary button and Save as an outline one, so the hand fell on the button that throws the edit away. Save is now the one filled button, after Cancel, the order a form's footer uses. `page:header` now makes a host button declaring `variant: 'primary'` the primary over the page's own actions, in the place the host gave it; no other host button declares one, so every other header is unchanged. -**New detail lines.** A line added to a master-detail table in the record page's edit state started blank, so a required column with a default (a status that defaults to "Pending") read red although the save then stored the default. A new line now starts on the child object's static defaults, the values a create form seeds; 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 only after a save was refused, with the server's reason listed under the table; a stored line is flagged as before. A new line left as it came, holding only its defaults, is still skipped at save like a blank one. `LineItemsField` gains `newRowValues` and `newRowRequiredShown`, and `isBlankRow` (with the batch inputs) an optional `newRowValues`; a host that passes neither sees no change. The save request and its transaction are unchanged. +**New detail lines.** A line added to a master-detail table in the record page's edit state started blank, so a required column with a default (a status that defaults to "Pending") read red although the save then stored the default. A new line now starts on the child object's static defaults, the values a create form seeds; 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 only after a save was refused, with the server's reason listed under the table; a stored line is flagged as before. A line added and never edited, holding only its defaults, is still skipped at save like a blank one; once the user edits a cell of it, it is input and is saved, even when every value they typed equals a default. `LineItemsField` gains `newRowValues` and `newRowRequiredShown`; a line its Add starts on `newRowValues` carries the `UNTOUCHED_NEW_ROW` mark (a symbol key no payload carries) until its first edit, and `isBlankRow` reads that mark. `@object-ui/fields` exports `UNTOUCHED_NEW_ROW` and `isUntouchedNewRow`. A host that passes neither prop sees no change. The save request and its transaction are unchanged. -**The band above the tabs.** The record page's scroller and its column layout each padded their top by 24px on a desktop, so a 48px empty band stood between the header and the tab row. The scroller now pads only its sides and bottom, and the column layout keeps a 12px top on every width, so the tabs follow the header at the gap the rest of the page uses; on a phone the title block keeps 16px to the tabs. The print chrome and the approval actions bar that render above the columns keep their own top margin. Side padding is unchanged. +**The band above the tabs.** The record page's scroller and its column layout each padded their top by 24px on a desktop, so a 48px empty band stood between the header and the tab row. The scroller now pads only its sides and bottom, and the column layout keeps a 12px top on every width, so the tabs follow the header at the gap the rest of the page uses; on a phone the title block keeps 16px to the tabs. The print chrome and the approval actions bar that render above the columns keep their own top margin, and an authored page the page renderer draws keeps its own top padding. Side padding is unchanged. diff --git a/ui/e2e/live/record-page-polish-35745.spec.ts b/ui/e2e/live/record-page-polish-35745.spec.ts new file mode 100644 index 00000000000..5efa6c9fdde --- /dev/null +++ b/ui/e2e/live/record-page-polish-35745.spec.ts @@ -0,0 +1,124 @@ +import { test, expect, type Page } from '@playwright/test'; + +/** + * Live e2e for the record page polish of objectstack#35745 and + * objectstack#35816, on the showcase Expense Report against the REAL stack: + * + * 1. the tab row follows the header with no blank band: the tabs start at + * most 12 px below the top of the page scroller (it used to be 48 px, + * the scroller's and the column layout's 24 px paddings stacked); + * 2. a business `date` with no declared `format` reads as the date, with + * its year, and keeps the relative phrase as its tooltip; + * 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. + * + * ⚠️ 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 + * (`RecordPageColumns.test.tsx`, `RecordDetailView.topInset-35745`, + * `DetailSection.dateYear-27520`, `page-header-primary-12617`, `GridField`, + * `RecordBodyTableEditor.recordEditBatch-35599`) hold each rule's classes and + * state transitions. + * + * The report is created through the API (draft, so no approval locks it) and + * deleted at the end; `request` carries the session cookie of the storageState. + */ +const API = process.env.LIVE_API_URL || 'http://localhost:3000'; +const OBJECT = 'showcase_expense_report'; +const LINE = 'showcase_expense_line'; + +/** `YYYY-MM-DD` of the browser's local day `offset` days from today. */ +function localDay(offset: number): { iso: string; date: Date } { + const d = new Date(); + d.setHours(12, 0, 0, 0); + d.setDate(d.getDate() + offset); + const iso = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; + return { iso, date: d }; +} + +async function openRecord(page: Page, id: string, name: string) { + await page.goto(`/apps/showcase_app/${OBJECT}/record/${encodeURIComponent(id)}`); + await expect(page.getByRole('heading', { name }).first()).toBeVisible({ timeout: 30_000 }); + await expect(page.getByRole('tablist').first()).toBeVisible(); +} + +test.use({ viewport: { width: 1280, height: 900 }, locale: 'en-US' }); + +test('record page polish (#35745, #35816) — showcase Expense Report', async ({ page, request }) => { + test.setTimeout(180_000); + + const name = `Polish e2e ${Date.now()}`; + const day = localDay(-3); + const createRes = await request.post(`${API}/api/v1/data/${OBJECT}`, { + data: { name, status: 'draft', submitted_on: day.iso }, + }); + expect(createRes.ok(), await createRes.text()).toBeTruthy(); + const created = await createRes.json(); + const id: string = created.id ?? created.record?.id ?? created.data?.id; + expect(id, 'created report id').toBeTruthy(); + + try { + await openRecord(page, id, name); + + // ── 1. No band above the tabs. ── + const gap = await page.getByRole('tablist').first().evaluate((tabs) => { + let scroller: HTMLElement | null = tabs.parentElement; + while (scroller && !/(auto|scroll)/.test(getComputedStyle(scroller).overflowY)) scroller = scroller.parentElement; + const h1 = document.querySelector('h1')!.getBoundingClientRect(); + return { + tabsTop: tabs.getBoundingClientRect().top, + scrollerTop: scroller ? scroller.getBoundingClientRect().top : NaN, + titleBottom: h1.bottom, + }; + }); + expect(gap.tabsTop, 'the tabs sit below the record title').toBeGreaterThan(gap.titleBottom); + expect(gap.tabsTop - gap.scrollerTop, 'tabs → top of the page scroller').toBeLessThanOrEqual(12); + + // ── 2. The business date reads as the date; the phrase is its tooltip. ── + const written = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).format(day.date); + const dateCell = page.getByText(written, { exact: true }).first(); + await expect(dateCell).toBeVisible(); + await expect(dateCell).toHaveAttribute('title', '3 days ago'); + await expect(page.getByText('3 days ago', { exact: true })).toHaveCount(0); + + // ── 3. Edit state: Cancel, then Save, Save the one filled button. ── + const toolbar = page.getByRole('toolbar', { name: 'Page header actions' }); + await toolbar.getByRole('button', { name: 'Edit', exact: true }).click(); + const save = toolbar.getByRole('button', { name: 'Save', exact: true }); + const cancel = toolbar.getByRole('button', { name: 'Cancel', exact: true }); + await expect(save).toBeVisible(); + const order = await toolbar.getByRole('button').evaluateAll((els) => + els.map((b) => ({ text: (b.textContent || '').trim(), filled: b.className.includes('bg-primary') })), + ); + const cancelAt = order.findIndex((b) => b.text === 'Cancel'); + const saveAt = order.findIndex((b) => b.text === 'Save'); + expect(cancelAt, JSON.stringify(order)).toBeGreaterThanOrEqual(0); + expect(saveAt, JSON.stringify(order)).toBeGreaterThan(cancelAt); + expect(order.filter((b) => b.filled).map((b) => b.text)).toEqual(['Save']); + await expect(cancel).not.toHaveClass(/bg-primary/); + + // ── 4. A new line starts on its defaults, unflagged; left as it came, it is not stored. ── + const editor = page.locator('[data-body-table-editor]').first(); + await editor.scrollIntoViewIfNeeded(); + const lines = editor.locator('tbody tr'); + const before = await lines.count(); + await editor.getByTestId('line-items-add').click(); + await expect(lines).toHaveCount(before + 1); + // The grid keeps a trailing entry line, so the added line is the one before it. + const added = lines.nth(before - 1); + await expect(added).toContainText('Other'); + await expect(added).toContainText('Submitted'); + await expect(editor.locator('[data-testid^="line-items-invalid"]')).toHaveCount(0); + + 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`); + 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); + 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/packages/app-shell/src/views/RecordDetailView.topInset-35745.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.topInset-35745.test.tsx new file mode 100644 index 00000000000..aa70b9010fd --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.topInset-35745.test.tsx @@ -0,0 +1,197 @@ +/** + * 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. + */ + +/** + * objectstack#35745 — the band above the tabs, on the pages that are NOT laid + * out by `RecordPageColumns`. + * + * The record page's scroller and the column layout each padded their top + * 24px on a desktop, stacking a 48px band under the header. The scroller now + * pads only its sides and foot, and the column layout pads its own top + * (pinned in `RecordPageColumns.test.tsx`). Everything else the scroller + * hosts must still start clear of the header on its own: an authored page the + * page renderer draws carries the renderer's `p-3 md:p-4 lg:p-6`, and a print + * page's screen-only chrome, which sits above that page, takes its own top + * margin. (The loading, error and not-found states are early returns of the + * view and never render inside the scroller.) + * + * Mounted through `RecordDetailView` itself, so the padding is read off the + * scroller and page root the real view and page renderer draw. + */ +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest'; +import { render, waitFor, cleanup } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { MetadataCtx } from '@object-ui/react'; + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }), + createAuthenticatedFetch: () => vi.fn(), +})); +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecordPresence: () => [], + PresenceAvatars: () => null, +})); +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); +// Orthogonal chrome, stubbed. +vi.mock('./ActionConfirmDialog', () => ({ ActionConfirmDialog: () => null })); +vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null })); +vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null })); +vi.mock('./FlowRunner', () => ({ FlowRunner: () => null })); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); + +import { RecordDetailView } from './RecordDetailView'; + +const OBJECT = 'os_35745_project'; +const REC = 'prj-1'; + +const objectDef = { + name: OBJECT, + label: 'Project', + enable: { files: true }, + highlightFields: ['name'], + fields: { + id: { label: 'Id', type: 'text' }, + name: { label: 'Name', type: 'text' }, + owner_email: { label: 'Owner Email', type: 'text' }, + }, +}; + +const RECORD = { + id: REC, + name: 'Website Relaunch', + owner_email: 'auditor@example.com', + created_at: '2026-01-02T03:04:05.000Z', + updated_at: '2026-02-03T04:05:06.000Z', +}; + +/** An authored page the page renderer draws (not laid out by `RecordPageColumns`). */ +const ASSIGNED_PAGE = { + name: 'os_35745_project_detail', + label: 'Project', + type: 'record', + object: OBJECT, + regions: [ + { + name: 'main', + components: [ + { type: 'record:details', id: 'overview', properties: { sections: [{ label: 'Overview', fields: ['owner_email'] }] } }, + ], + }, + ], +}; + +function makeDataSource() { + return { + find: vi.fn(async () => ({ data: [], total: 0, hasMore: false, pageSize: 50 })), + findOne: vi.fn(async (name: string, id: string) => (name === OBJECT ? { ...RECORD, id } : null)), + create: vi.fn(async (_o: string, row: any) => row), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: async (name: string) => ({ name, fields: objectDef.fields }), + } as any; +} + +function makeMetadata(pages: any[]) { + return { + objects: [], pages, loading: false, error: null, + refresh: async () => {}, invalidate: () => {}, + ensureType: async () => pages, getItem: async () => null, + getItemsByType: () => pages, + } as any; +} + +function renderRecordPage(pages: any[]): HTMLElement { + const { container } = render( + + + {}} + objectNameOverride={OBJECT} + recordIdOverride={REC} + embedded + /> + + , + ); + return container; +} + +/** The record page's scroller: the element the view scrolls the page in. */ +function scrollerOf(root: ParentNode): HTMLElement { + const el = root.querySelector('.scroll-pb-48'); + expect(el, 'the view must draw its page scroller').toBeTruthy(); + return el as HTMLElement; +} + +/** Utilities that pad an element's TOP: `p-*`, `pt-*`, `py-*`, at any breakpoint. */ +const topPadding = (el: Element) => + Array.from(el.classList).filter((c) => /^(?:[a-z]+:)?(?:p|pt|py)-\d+$/.test(c)); + +beforeAll(() => { + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 }); +}); + +beforeEach(() => { + cleanup(); + vi.stubGlobal('fetch', vi.fn(async () => + new Response(JSON.stringify({ data: [] }), { + status: 200, headers: { 'content-type': 'application/json' }, + }))); +}); + +afterEach(() => { vi.unstubAllGlobals(); vi.clearAllMocks(); }); + +describe('the scroller pads no top; what it hosts starts clear of the header (objectstack#35745)', () => { + it('an authored page drawn by the page renderer pads its own top, under a scroller that pads none', async () => { + const container = renderRecordPage([ASSIGNED_PAGE]); + await waitFor(() => expect(container.textContent).toContain('auditor@example.com')); + const scroller = scrollerOf(container); + expect(topPadding(scroller)).toEqual([]); + // CONTROL: the scroller still insets its sides and foot. + for (const cls of ['px-3', 'pb-3', 'sm:px-4', 'sm:pb-4', 'lg:px-6', 'lg:pb-6']) expect(scroller.classList).toContain(cls); + const page = container.querySelector('[data-page-type="record"]') as HTMLElement; + expect(page, 'the page renderer must draw the record page root').toBeTruthy(); + expect(scroller.contains(page)).toBe(true); + expect(topPadding(page)).toEqual(expect.arrayContaining(['p-3', 'md:p-4', 'lg:p-6'])); + }); + + it("a print page's screen-only chrome takes its own top margin above the page", async () => { + const PRINT_PAGE = { + ...ASSIGNED_PAGE, + name: 'os_35745_project_print', + isDefault: true, + print: { paperSize: 'A4' }, + regions: [{ name: 'main', components: [{ type: 'text', value: 'Project sheet' }] }], + }; + const container = renderRecordPage([PRINT_PAGE]); + const chrome = await waitFor(() => { + const el = container.querySelector('[data-record-print-chrome]'); + expect(el, 'a page that declares `print` draws the screen-only chrome').toBeTruthy(); + return el as HTMLElement; + }); + const scroller = scrollerOf(container); + expect(scroller.firstElementChild).toBe(chrome); + expect(chrome.classList).toContain('mt-3'); + const page = container.querySelector('[data-print-page]') as HTMLElement; + expect(page, 'the page is drawn as a print page').toBeTruthy(); + expect(topPadding(page)).toEqual(expect.arrayContaining(['p-3', 'md:p-4', 'lg:p-6'])); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 73ea57d900c..a5a0cbc06b1 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -5417,7 +5417,7 @@ export * from './widgets/AutoNumberField.js'; export * from './widgets/UserField.js'; export * from './widgets/ObjectField.js'; export * from './widgets/VectorField.js'; -export { evalArith, lookupAutofillPatch, computeRow, GridField, LineItemsField } from './widgets/GridField.js'; +export { evalArith, lookupAutofillPatch, computeRow, GridField, LineItemsField, UNTOUCHED_NEW_ROW, isUntouchedNewRow } from './widgets/GridField.js'; export type { ColumnCurrencies } from './widgets/GridField.js'; export type { GridColumn } from './widgets/GridField.js'; export * from './widgets/lookupAutofill.js'; diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index 5a4ecb81569..355116ad4aa 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -3,7 +3,7 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import React from 'react'; import { UploadProvider } from './UploadProvider'; import { formatDate, formatDateTime } from '@object-ui/core'; -import { GridField, LineItemsField, sumColumn, lookupAutofillPatch } from './GridField'; +import { GridField, LineItemsField, sumColumn, lookupAutofillPatch, UNTOUCHED_NEW_ROW, isUntouchedNewRow } from './GridField'; const columns = [ { name: 'description', label: 'Description', type: 'text' as const }, @@ -795,12 +795,40 @@ describe('GridField — a new line starts on its defaults and waits to read red , ); fireEvent.click(screen.getByRole('button', { name: /Add line/i })); - expect(onChange).toHaveBeenLastCalledWith([{ name: null, status: 'pending' }]); + expect(onChange).toHaveBeenLastCalledWith([{ name: null, status: 'pending', [UNTOUCHED_NEW_ROW]: true }]); const entryName = container.querySelector('[data-cell="0-0"]') as HTMLInputElement; fireEvent.change(entryName, { target: { value: 'Book the room' } }); expect(onChange).toHaveBeenLastCalledWith([{ name: 'Book the room', status: 'pending' }]); }); + it('a line Add started is marked untouched until its first edit, even an edit back to its default', () => { + const onChange = vi.fn(); + const { rerender } = render( + , + ); + fireEvent.click(screen.getByRole('button', { name: /Add line/i })); + const added = onChange.mock.lastCall![0] as Record[]; + expect(isUntouchedNewRow(added[0])).toBe(true); + // The mark is a symbol key: no write payload or key walk sees it. + expect(Object.keys(added[0])).toEqual(['name', 'status']); + expect(JSON.stringify(added[0])).toBe('{"name":null,"status":"pending"}'); + rerender(); + const status = screen.getAllByDisplayValue('pending')[0] as HTMLInputElement; + fireEvent.change(status, { target: { value: 'done' } }); + rerender(); + fireEvent.change(screen.getAllByDisplayValue('done')[0], { target: { value: 'pending' } }); + const edited = onChange.mock.lastCall![0] as Record[]; + expect(edited[0]).toMatchObject({ status: 'pending' }); + expect(isUntouchedNewRow(edited[0])).toBe(false); + }); + + it('CONTROL: with no `newRowValues` an added line carries no mark, as before', () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: /Add line/i })); + expect(isUntouchedNewRow(onChange.mock.lastCall![0][0])).toBe(false); + }); + it('a new line\'s empty required cell is not flagged until the host says so; a stored line is', () => { const rows = [{ id: 't1', name: null, status: 'open' }, { name: null, status: 'pending' }]; const { rerender } = render( diff --git a/ui/packages/fields/src/widgets/GridField.tsx b/ui/packages/fields/src/widgets/GridField.tsx index 8f190ac19cc..f5bae9ceecd 100644 --- a/ui/packages/fields/src/widgets/GridField.tsx +++ b/ui/packages/fields/src/widgets/GridField.tsx @@ -763,6 +763,30 @@ function RetiredGridFieldKeys({ message, keys }: { message: string; keys: readon ); } +/** + * objectstack#35816 — marks a line that `Add` started on the host's + * `newRowValues` and that nobody has edited since. Such a line holds only its + * defaults, and a host may skip it at save like a blank one; any edit to the + * line takes the mark off, so a value the user typed counts as input even when + * it equals the default. A symbol key: `Object.keys`/`Object.entries` and + * `JSON.stringify` (so every write payload) skip it, while the spread copies a + * host or a renumbering makes keep it. Set only when the host passes + * `newRowValues`, so a host that passes none sees rows exactly as before. + */ +export const UNTOUCHED_NEW_ROW: unique symbol = Symbol.for('@object-ui/fields.untouchedNewRow'); + +/** True for a line `Add` started on its defaults and nobody has edited ({@link UNTOUCHED_NEW_ROW}). */ +export function isUntouchedNewRow(row: unknown): boolean { + return row != null && typeof row === 'object' && (row as Record)[UNTOUCHED_NEW_ROW] === true; +} + +/** The row without its {@link UNTOUCHED_NEW_ROW} mark: an edit makes it input. */ +function touched(row: Row): Row { + if (!isUntouchedNewRow(row)) return row; + const { [UNTOUCHED_NEW_ROW]: _untouched, ...rest } = row as Row & { [UNTOUCHED_NEW_ROW]?: true }; + return rest; +} + /** A line the server already stores carries its id (`id`, `_id` or `recordId`). */ function rowHasId(row: Row): boolean { return [row.id, row._id, row.recordId].some((v) => v != null && v !== ''); @@ -971,7 +995,7 @@ function GridFieldBody({ emit([...rows, computeRow(columns, { ...blankRow(), ...patch }, tenantCurrency, columnCurrencies)]); return; } - emit(rows.map((r, i) => (i === rowIdx ? computeRow(columns, { ...r, ...patch }, tenantCurrency, columnCurrencies) : r)), false); + emit(rows.map((r, i) => (i === rowIdx ? computeRow(columns, { ...touched(r), ...patch }, tenantCurrency, columnCurrencies) : r)), false); }, [rows, columns, maxRows, blankRow, emit, tenantCurrency, columnCurrencies], ); @@ -1026,8 +1050,10 @@ function GridFieldBody({ const addRow = useCallback(() => { if (maxRows != null && rows.length >= maxRows) return; - emit([...rows, blankRow()]); - }, [rows, blankRow, maxRows, emit]); + // objectstack#35816 — a line Add starts on the host's defaults is marked + // untouched until its first edit (`UNTOUCHED_NEW_ROW`). + emit([...rows, newRowValues ? { ...blankRow(), [UNTOUCHED_NEW_ROW]: true } : blankRow()]); + }, [rows, blankRow, maxRows, emit, newRowValues]); // Keyboard navigation across cells (spreadsheet-style): the table is a focus // grid. Enter / ArrowUp / ArrowDown move between rows in the same column; @@ -1072,7 +1098,8 @@ function GridFieldBody({ if (!src) return; const { id: _i, _id: _i2, recordId: _i3, ...copy } = src as any; const next = [...rows]; - next.splice(rowIdx + 1, 0, { ...copy }); + // A copy is a line the user made, so it is not an untouched one. + next.splice(rowIdx + 1, 0, touched({ ...copy })); emit(next); }, [rows, maxRows, emit], diff --git a/ui/packages/plugin-detail/src/__tests__/DetailSection.dateYear-27520.test.tsx b/ui/packages/plugin-detail/src/__tests__/DetailSection.dateYear-27520.test.tsx index bfbbc3d1528..7d29a448dd8 100644 --- a/ui/packages/plugin-detail/src/__tests__/DetailSection.dateYear-27520.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/DetailSection.dateYear-27520.test.tsx @@ -139,6 +139,30 @@ describe('a record page writes a business date as the date (objectstack#35745)', expect(screen.getByText(days.past.phrase)).toBeTruthy(); }); + // #35745 names 日期时间 too. A `datetime` field with no declared `format` + // already paints the compact absolute face everywhere (`DateTimeCellRenderer` + // defaults to `'compact'`), so the record page needs no prop for it; this + // pins that it reads as the date (the compact face, `10/29/2026`), never as + // the relative phrase. + it('a `datetime` field in the relative window reads as its date, in a section row and the highlights strip', () => { + const at = '2026-10-29T12:00:00'; + const schema = { fields: { starts_at: { name: 'starts_at', type: 'datetime', label: 'Starts At' } } }; + const section = { title: 'Meeting', fields: [{ name: 'starts_at', label: 'Starts At', type: 'datetime' }] } as unknown as DetailViewSection; + const { unmount } = render(); + expect(screen.getByText('10/29/2026')).toBeTruthy(); + expect(screen.queryByText(/days? ago/)).toBeNull(); + unmount(); + render( + , + ); + expect(screen.getByText('10/29/2026')).toBeTruthy(); + expect(screen.queryByText(/days? ago/)).toBeNull(); + }); + it('CONTROL: the shared date cell without the record page keeps the relative default', () => { const DateCell = getCellRenderer('date'); const field: DateFieldMetadata = { name: 'meeting_date', label: 'Meeting Date', type: 'date' }; diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts index 014afb89935..5c7144bf554 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts @@ -13,6 +13,7 @@ */ import { describe, it, expect } from 'vitest'; +import { UNTOUCHED_NEW_ROW } from '@object-ui/fields'; import { attributeRecordEditRefusal, buildRecordEditBatch } from './RecordBodyTableEditor'; const childSchema = { @@ -79,7 +80,7 @@ describe('buildRecordEditBatch — one batch for the record and all its body tab }); }); -describe('buildRecordEditBatch — a new line that kept the defaults it started on (objectstack#35816)', () => { +describe('buildRecordEditBatch — a new line nobody edited since Add started it on its defaults (objectstack#35816)', () => { const tasks = { id: 'meeting_task.meeting', childObject: 'meeting_task', @@ -92,13 +93,12 @@ describe('buildRecordEditBatch — a new line that kept the defaults it started meeting: { type: 'master_detail' }, }, }, - newRowValues: { status: 'pending' }, original: [], rows: [ - { name: null, status: 'pending' }, // added, left as it came: no op + { name: null, status: 'pending', [UNTOUCHED_NEW_ROW]: true }, // added, left as it came: no op { name: 'Book the room', status: 'pending' }, // typed a name: created with the default { name: null, status: 'done' }, // changed the default: that is input - ], + ] as Record[], }; it('is skipped like a blank line; a line with input is created, its default included, traced to its position', () => { @@ -116,9 +116,19 @@ describe('buildRecordEditBatch — a new line that kept the defaults it started ]); }); - it('CONTROL: without the start values the same untouched line is input and is created', () => { - const { ops } = buildRecordEditBatch('meeting', 'm1', {}, [{ ...tasks, newRowValues: undefined }]); - expect(ops.filter((o) => o.action === 'create')).toHaveLength(3); + it('a line the user edited back to exactly its defaults is input, and is created', () => { + // Same values as the untouched line above, but an edit took the mark off. + const { ops } = buildRecordEditBatch('meeting', 'm1', {}, [{ ...tasks, rows: [{ name: null, status: 'pending' }] }]); + expect(ops.map((o) => [o.object, o.action])).toEqual([ + ['meeting', 'update'], + ['meeting_task', 'create'], + ]); + expect(ops[1].data).toMatchObject({ status: 'pending', meeting: 'm1' }); + }); + + it('the mark never reaches a write payload', () => { + const { ops } = buildRecordEditBatch('meeting', 'm1', {}, [tasks]); + for (const op of ops) expect(Object.getOwnPropertySymbols(op.data ?? {})).toEqual([]); }); }); diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index 4de008713ec..64851f4000c 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -67,8 +67,6 @@ export interface BodyTableSnapshot { rows: Record[]; original: Record[]; childSchema: ChildSchema; - /** The values a new line starts on: the child object's static defaults. */ - newRowValues?: Record; } /** One body-table editor, as the host's session sees it. */ @@ -117,7 +115,7 @@ export function buildRecordEditBatch( // skipping blank rows; then updates; then deletes. const createRows = t.rows .map((r, i) => ({ r, i })) - .filter(({ r }) => !idOf(r) && !isBlankRow({ ...r, [t.relationshipField]: parentId }, t.relationshipField, t.newRowValues)); + .filter(({ r }) => !idOf(r) && !isBlankRow({ ...r, [t.relationshipField]: parentId }, t.relationshipField)); let createCursor = 0; for (const op of tableOps) { let row = -1; @@ -281,7 +279,7 @@ export const RecordBodyTableEditor: React.FC = ({ ob const snapshotRef = useRef(null); snapshotRef.current = rows && derived - ? { childObject: objectName, relationshipField, rows, original, childSchema, newRowValues } + ? { childObject: objectName, relationshipField, rows, original, childSchema } : null; const register = session?.register; diff --git a/ui/packages/plugin-form/src/masterDetailTx.ts b/ui/packages/plugin-form/src/masterDetailTx.ts index 444721ee862..a02e66fec37 100644 --- a/ui/packages/plugin-form/src/masterDetailTx.ts +++ b/ui/packages/plugin-form/src/masterDetailTx.ts @@ -19,6 +19,7 @@ import type { BatchTransactionOperation } from '@object-ui/types'; // `changedFields` is the ONE dirty-field comparison, shared with the edit // form's own record diff (objectui#10156) — see `isSameStoredValue` there. import { sanitizeFormData, changedFields } from './sanitize'; +import { isUntouchedNewRow } from '@object-ui/fields'; export const idOf = (rec: any): string | undefined => rec == null ? undefined : (rec.id ?? rec._id ?? rec.recordId); @@ -74,10 +75,6 @@ export interface BatchDetailInput { /** When supplied, child write payloads are sanitized against it (drops * computed / read-only / unknown fields). Omit to persist rows as-is. */ childSchema?: ChildSchema; - /** The values a new line started on (`LineItemsField`'s `newRowValues`). - * A new line that still holds only these is no input, and is skipped like - * a blank one ({@link isBlankRow}). */ - newRowValues?: Record; } /** Edit-mode detail input: current rows + the loaded snapshot to diff against. */ @@ -101,30 +98,21 @@ const ID_KEYS = new Set(['id', '_id', 'recordId']); * null while their inputs are blank, so they don't count as input. Used to * drop the always-present trailing "ghost" line (and any row the user cleared) * so it never persists as an empty child record. + * + * objectstack#35816 — a line `Add` started on its defaults that nobody has + * edited (`isUntouchedNewRow`) is blank too: it holds only those defaults. A + * line the user edited is judged by its values alone, so a value typed back to + * the default still counts as input. */ -export function isBlankRow( - row: Record, - relationshipField?: string, - newRowValues?: Record, -): boolean { +export function isBlankRow(row: Record, relationshipField?: string): boolean { if (!row) return true; + if (isUntouchedNewRow(row)) return true; return Object.entries(row).every(([k, v]) => { if (k === relationshipField || ID_KEYS.has(k)) return true; - if (v === null || v === undefined || v === '') return true; - // objectstack#35816 — a value the line started on is the default, not - // input: a line the user added and left as it came is still blank. - return newRowValues !== undefined - && Object.prototype.hasOwnProperty.call(newRowValues, k) - && sameValue(v, newRowValues[k]); + return v === null || v === undefined || v === ''; }); } -function sameValue(a: unknown, b: unknown): boolean { - if (a === b) return true; - if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false; - return JSON.stringify(a) === JSON.stringify(b); -} - /** * Build cross-object batch operations for an ATOMIC master-detail create: * the parent at index 0, then each child with its relationship FK set to @@ -166,7 +154,7 @@ export function buildMasterDetailEditBatch( const withFk = (d.rows || []).map((r) => ({ ...r, [d.relationshipField]: parentId })); const { toCreate, toUpdate, toDelete } = diffRows(d.original || [], withFk); for (const row of toCreate) { - if (isBlankRow(row, d.relationshipField, d.newRowValues)) continue; // skip the ghost/empty line + if (isBlankRow(row, d.relationshipField)) continue; // skip the ghost/empty line // Strip any client-only id so the server generates one. const { id: _omit, _id: _omit2, recordId: _omit3, ...clean } = row as any; ops.push({ object: d.childObject, action: 'create', data: toWritable(clean, d.childSchema) });