Skip to content
Merged
22 changes: 22 additions & 0 deletions .changeset/35745-35816-record-page-polish.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
'@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, a new detail line starts on its defaults, and the tabs follow the header with no blank band

Clause-②: yes (widening)
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. 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 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, and an authored page the page renderer draws keeps its own top padding. Side padding is unchanged.
124 changes: 124 additions & 0 deletions ui/e2e/live/record-page-polish-35745.spec.ts
Original file line number Diff line number Diff line change
@@ -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)}`);
}
});
Original file line number Diff line number Diff line change
@@ -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<Record<string, unknown>>()),
useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }),
createAuthenticatedFetch: () => vi.fn(),
}));
vi.mock('@object-ui/collaboration', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
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(
<MemoryRouter initialEntries={[`/app/demo/${OBJECT}/${REC}`]}>
<MetadataCtx.Provider value={makeMetadata(pages)}>
<RecordDetailView
dataSource={makeDataSource()}
objects={[objectDef]}
onEdit={() => {}}
objectNameOverride={OBJECT}
recordIdOverride={REC}
embedded
/>
</MetadataCtx.Provider>
</MemoryRouter>,
);
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']));
});
});
Loading
Loading