Skip to content

Commit c7174c3

Browse files
fix(ui): record page polish — dates read as dates, Save is the primary, new detail lines start on their defaults, no band above the tabs (#35937)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuNEeCbXSi4Z8618BgVLuSfe)_ Fixes #35745 Fixes #35816 Clause-②: yes (widening) Metadata-protocol: semantic Skills-docs: none — no skill text describes the record page's date face, its edit-state buttons or a new detail line's start values; a field's `format` and `defaultValue` keep the meaning the skills already teach ## 维护者速读 - 记录详情页上:日期直接写成日期(悬停才显示"5 天前"),页签上方不再空出一大块,编辑时"保存"成了唯一的实心按钮,主从明细新加的一行一开始就带好默认值、不再一片红。 - 属于「记录详情页重做」专题,替日常录入和查看记录的业务用户解决读日期要换算、误点取消、新行假报错的问题。 - 出错时最坏是某处日期或按钮样式不对、或新行默认值没带上,保存请求和事务都没动,可以直接撤回本次改动。 - 无。 ## What changes Four record-page fixes, one PR (the two cards were folded by the seat). **#35745 — business dates as dates.** `DateCellRenderer` gains an `absoluteDate` cell prop: with no declared `format`, the cell writes the date (with its year) and keeps the relative phrase as the `title`, the same face a grid column already uses (`inGridColumn`, #25884). `DetailSection` and `HeaderHighlight` pass it, so the record page's field sections and highlights strip read like the list beside them. A declared `format` (`'relative'` included) still wins; an overdue deadline still reads red, with "Overdue 5d" as the tooltip. A `datetime` field with no `format` already paints the compact absolute face (its cell's default, never the relative phrase); a test now pins that on the record page too. The record footer's created/modified times and card surfaces are untouched. **#35745 — the band above the tabs.** The page scroller (`RecordDetailView`) and `RecordPageColumns` each padded their top 24px on desktop, stacking a 48px band between the header and the tab row. The scroller now pads sides and bottom only; `RecordPageColumns` keeps a 12px top at every width. The print chrome and the approval-fallback actions bar above the columns take `mt-3` so they keep their spacing. An authored page the page renderer draws (no `RecordPageColumns` root, a print page included) keeps the renderer's own `p-3 md:p-4 lg:p-6`, so it still starts clear of the header (24px on a desktop, from 48); the loading, error, not-found and forbidden states are early returns of the view and never render inside the scroller. Side padding is unchanged. **#35816 — Save is the primary button.** `sys_record_edit_save` declares `variant: 'primary'`, and `page:header` now lets a host button that declares `variant: 'primary'` be the primary, in the place the host gave it (Cancel, then Save). No other host button declares a variant, so every other header ranks as before. **#35816 — a new detail line starts on its defaults.** `RecordBodyTableEditor` computes the child object's static defaults with `schemaDefaultValues` (the values a create form seeds) and hands them to `LineItemsField` as `newRowValues`; the ghost line starts on them. A new line's empty required cell reads red only once a save was refused (`newRowRequiredShown`), so the server's reason and the red cell arrive together; a stored line is flagged as before. A line `Add` starts on `newRowValues` carries `UNTOUCHED_NEW_ROW` (a symbol key: `Object.entries`, `JSON.stringify` and so every payload skip it) until its first edit; `isBlankRow` treats a marked line as blank, so a line added and left as it came is skipped at save, while a line the user edited is judged by its values alone and is saved even when every typed value equals a default. `@object-ui/fields` exports `UNTOUCHED_NEW_ROW` and `isUntouchedNewRow`. Server-resolved defaults (`NOW()`, CEL) are left to the server. The batch request and transaction are unchanged. ## Tests - Added: `DetailSection.dateYear-27520` (#35745: past / today / future date, highlights strip, declared `relative` wins, CONTROL bare cell); `RecordPageColumns` (root padding pinned); `page-header-primary-12617` (#35816: Cancel then Save with Save the only filled button; Save stays primary beside page actions, one declaring `variant: 'primary'` included; CONTROL with no host primary the first page action leads); `GridField` (#35816: Add and the entry line start on the host's values; a line Add started is marked untouched until its first edit, even an edit back to its default; CONTROL with no `newRowValues` no mark; a new line's empty required cell waits for the host's word while a stored line is flagged; CONTROL without that word a new line is flagged at once); `RecordBodyTableEditor.recordEditBatch-35599` (#35816: an untouched new line is skipped, a line with input created with its default; a line edited back to exactly its defaults is created; the mark never reaches a write payload); `DetailSection.dateYear-27520` also pins a `datetime` field reading as its date in a section row and the highlights strip; `RecordDetailView.topInset-35745` (mounted through the view: an authored page pads its own top under a scroller that pads none, CONTROL the scroller keeps sides and foot; a print page's chrome takes its top margin); live e2e `ui/e2e/live/record-page-polish-35745.spec.ts` (showcase Expense Report on the real stack: tabs ≤ 12px under the scroller top, the date and its tooltip, Cancel then Save with Save the only filled button, a new line on Other / Submitted with no red cell, and an added untouched line not stored). - Migrated: `recordPage.deadlineSettled-11815` — the record page now writes the absolute date, so its text assertions read `formatDate(iso, undefined, { alwaysShowYear: true })` and the relative phrase ("Overdue 5d" / "5 days ago") moved to the tooltip assertion. Same records, same red/settled verdicts. - Voided: none. - Ablations (each restored, tree clean): `absoluteDate` removed from `DetailSection` → 3/9 red; `hostPrimary` forced undefined → 2/8 red; `!newRowWaits` removed from `GridField` → 1/54 red; `newRowValues` dropped from `isBlankRow` → 1/7 red. Rework: scroller padding back to `p-3 sm:p-4 lg:p-6` plus print chrome `mt-3` removed → 2/2 red (`topInset-35745`); `DateTimeCellRenderer` default `'compact'` → `'relative'` → 1/10 red; `touched(r)` removed from `GridField`'s edit path plus the mark check removed from `isBlankRow` → 2/64 red; under the live spec, scroller padding back → red (tabs 36px under the scroller top), mark check removed → red (the untouched line is sent, the save is refused, the edit state stays). ## Acceptance notes - #35853 (header two rows, seat 5) had not landed when this was built, so this is on current `main`; `overlap-check` shows it merging cleanly with #35910 and #35921, the open PRs sharing `RecordDetailView.tsx`. The header and band hunks were done last, and keep off the breadcrumb/frame hunks #35853 changes. - The branch is a harness-assigned `claude/project-thread-*` name. - The horizontal double inset (scroller + columns, 48px on each side at desktop) is left as it is; this PR removes only the vertical band the card names. - On a 375 phone the title block sits inside the page; title block → tabs is 16px (the page's own gap), page top 12px. - `buildDefaultPageSchema.ts` and the save transaction are untouched. - Follow-up: #35940 (new MasterDetailForm rows: prefill defaults, no early required flags) - Review rework (L2 record 7050830297, S1–S4): S1 a `datetime` field is pinned absolute; S2 the other pages the scroller hosts are checked and one is pinned through the view; S3 a line is skipped only while untouched, by the mark above, instead of by comparing its values with the defaults; S4 the claimed `ui/e2e` spec is added under `e2e/live`, since the band only shows in real layout. The L2 nit and L1-c's two nits ride #35940. Read first (by risk): `ui/packages/components/src/renderers/layout/containers.tsx` (the primary pick — every record header goes through it); `ui/packages/fields/src/widgets/GridField.tsx` (`newRowWaits` in the invalid computation); `ui/packages/plugin-form/src/masterDetailTx.ts` (`isBlankRow`). Two-minute check: open any Expense Report record, click Edit → the header reads Cancel (outline) then Save (filled); Add line in Expense Lines → the new line shows Other / No / Submitted and no red cell. ## Verification Browser evidence (light and dark, 1280 desktop and 375 phone, showcase app on a fresh seed) is in the project's evidence folder; readings below. <details><summary>Browser readings</summary> - Gap header → tabs: before 48px (92 → 140), after 12px (92 → 104) on four records, light and dark; phone 16px. - Submitted On (date, no format): Nov 15, 2026 / tooltip "5 days ago"; Nov 19 / "Yesterday"; Nov 20 / "Today"; Nov 25 / "In 5 days" — desktop and 375, light and dark. Footer keeps "Created 9m ago". - Edit state: Cancel outline then Save filled, desktop header and 375 bottom bar, light and dark. - New line: prefilled Other / No / Submitted, 0 red cells; Amount only → Save → `400 VALIDATION_FAILED`, merchant cell red "Merchant is required", list "Row 3 · Merchant: Merchant is required", still in edit state; Merchant filled → stored with status `submitted`; an untouched added line → save succeeds, no line created. </details> <details><summary>Unit tests and type-check (under the verify lock)</summary> - `@object-ui/fields` 308 files / 4688 passed; `@object-ui/plugin-form` 241 / 2697; `@object-ui/plugin-detail` 393 / 3606; `@object-ui/components` 492 / 4733; `@object-ui/app-shell` 2350 / 22040 — all exit 0; `type-check` exit 0 in all five. - After merging `main` (643fe3b): the six touched test files plus the `components` tests `main` changed — 12 files / 156 passed; `check:type-check-debt` (with `--re-measure`) OK. - Rework head `1f0b5268`: `@object-ui/fields` 308 files / 4690 passed; `@object-ui/plugin-form` 241 / 2698; `type-check` of fields, plugin-form, app-shell and `type-check:e2e` exit 0; `DetailSection.dateYear-27520`, `RecordDetailView.topInset-35745`, `RecordDetailView.appendInset-27520` 3 files / 14 passed; the live spec passed against a local showcase stack (1 passed, 9.5s). </details> <details><summary>Card gates (dispatch-gates)</summary> - `dispatch-gates --ran`: 40 derived, 40 run, 0 NOT-MEASURED, 0 UNRUN. 39 exit 0 at head `0baf37d5`. On the rework head `1f0b5268` the same 40 re-derived and re-run: 40 exit 0, `vitest run scripts/` included (it completed this time against the built console). - `overlap-check` on `1f0b5268`: clean against `main` and #35910, #35921, #35938; `check:test-source-alias` and `check:nul-bytes` OK. - `pnpm --dir ui exec vitest run scripts/`: NOT MEASURED locally — with the console closure built (76/76 turbo tasks), the run was OOM-killed by the container's memory limit; CI's lint workflow runs it on this head. - `check:test-source-alias` first flagged `page-header-primary-12617.test.tsx` (it reaches the react runtime's dynamic import during a clocked case); fixed with the module-top import the gate names, re-run exit 0. - `overlap-check`: clean against `main` and #35910, #35921. `check:nul-bytes` OK. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgVhfKtUtFdDWNgeCCE <!-- signed: repo:objectstack#1 · os-sales · session_01L6bhgVhfKtUtFdDWNgeCCE --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6b360ab commit c7174c3

18 files changed

Lines changed: 771 additions & 26 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@object-ui/fields': minor
3+
'@object-ui/plugin-detail': minor
4+
'@object-ui/plugin-form': minor
5+
'@object-ui/components': minor
6+
'@object-ui/app-shell': minor
7+
---
8+
9+
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
10+
11+
Clause-②: yes (widening)
12+
Metadata-protocol: semantic
13+
14+
Four things on the record page.
15+
16+
**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.
17+
18+
**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.
19+
20+
**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.
21+
22+
**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.
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
import { test, expect, type Page } from '@playwright/test';
2+
3+
/**
4+
* Live e2e for the record page polish of objectstack#35745 and
5+
* objectstack#35816, on the showcase Expense Report against the REAL stack:
6+
*
7+
* 1. the tab row follows the header with no blank band: the tabs start at
8+
* most 12 px below the top of the page scroller (it used to be 48 px,
9+
* the scroller's and the column layout's 24 px paddings stacked);
10+
* 2. a business `date` with no declared `format` reads as the date, with
11+
* its year, and keeps the relative phrase as its tooltip;
12+
* 3. in the edit state Save is the one filled button, after Cancel;
13+
* 4. a line added to the Expense Lines table starts on the child object's
14+
* defaults (Category "Other", Status "Submitted") with no cell flagged
15+
* red, and a line added and left as it came is not stored by the save.
16+
*
17+
* ⚠️ Layout is the reason this is a Playwright spec: jsdom lays nothing out,
18+
* so the 12 px is read here off real boxes. The vitest pins
19+
* (`RecordPageColumns.test.tsx`, `RecordDetailView.topInset-35745`,
20+
* `DetailSection.dateYear-27520`, `page-header-primary-12617`, `GridField`,
21+
* `RecordBodyTableEditor.recordEditBatch-35599`) hold each rule's classes and
22+
* state transitions.
23+
*
24+
* The report is created through the API (draft, so no approval locks it) and
25+
* deleted at the end; `request` carries the session cookie of the storageState.
26+
*/
27+
const API = process.env.LIVE_API_URL || 'http://localhost:3000';
28+
const OBJECT = 'showcase_expense_report';
29+
const LINE = 'showcase_expense_line';
30+
31+
/** `YYYY-MM-DD` of the browser's local day `offset` days from today. */
32+
function localDay(offset: number): { iso: string; date: Date } {
33+
const d = new Date();
34+
d.setHours(12, 0, 0, 0);
35+
d.setDate(d.getDate() + offset);
36+
const iso = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
37+
return { iso, date: d };
38+
}
39+
40+
async function openRecord(page: Page, id: string, name: string) {
41+
await page.goto(`/apps/showcase_app/${OBJECT}/record/${encodeURIComponent(id)}`);
42+
await expect(page.getByRole('heading', { name }).first()).toBeVisible({ timeout: 30_000 });
43+
await expect(page.getByRole('tablist').first()).toBeVisible();
44+
}
45+
46+
test.use({ viewport: { width: 1280, height: 900 }, locale: 'en-US' });
47+
48+
test('record page polish (#35745, #35816) — showcase Expense Report', async ({ page, request }) => {
49+
test.setTimeout(180_000);
50+
51+
const name = `Polish e2e ${Date.now()}`;
52+
const day = localDay(-3);
53+
const createRes = await request.post(`${API}/api/v1/data/${OBJECT}`, {
54+
data: { name, status: 'draft', submitted_on: day.iso },
55+
});
56+
expect(createRes.ok(), await createRes.text()).toBeTruthy();
57+
const created = await createRes.json();
58+
const id: string = created.id ?? created.record?.id ?? created.data?.id;
59+
expect(id, 'created report id').toBeTruthy();
60+
61+
try {
62+
await openRecord(page, id, name);
63+
64+
// ── 1. No band above the tabs. ──
65+
const gap = await page.getByRole('tablist').first().evaluate((tabs) => {
66+
let scroller: HTMLElement | null = tabs.parentElement;
67+
while (scroller && !/(auto|scroll)/.test(getComputedStyle(scroller).overflowY)) scroller = scroller.parentElement;
68+
const h1 = document.querySelector('h1')!.getBoundingClientRect();
69+
return {
70+
tabsTop: tabs.getBoundingClientRect().top,
71+
scrollerTop: scroller ? scroller.getBoundingClientRect().top : NaN,
72+
titleBottom: h1.bottom,
73+
};
74+
});
75+
expect(gap.tabsTop, 'the tabs sit below the record title').toBeGreaterThan(gap.titleBottom);
76+
expect(gap.tabsTop - gap.scrollerTop, 'tabs → top of the page scroller').toBeLessThanOrEqual(12);
77+
78+
// ── 2. The business date reads as the date; the phrase is its tooltip. ──
79+
const written = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).format(day.date);
80+
const dateCell = page.getByText(written, { exact: true }).first();
81+
await expect(dateCell).toBeVisible();
82+
await expect(dateCell).toHaveAttribute('title', '3 days ago');
83+
await expect(page.getByText('3 days ago', { exact: true })).toHaveCount(0);
84+
85+
// ── 3. Edit state: Cancel, then Save, Save the one filled button. ──
86+
const toolbar = page.getByRole('toolbar', { name: 'Page header actions' });
87+
await toolbar.getByRole('button', { name: 'Edit', exact: true }).click();
88+
const save = toolbar.getByRole('button', { name: 'Save', exact: true });
89+
const cancel = toolbar.getByRole('button', { name: 'Cancel', exact: true });
90+
await expect(save).toBeVisible();
91+
const order = await toolbar.getByRole('button').evaluateAll((els) =>
92+
els.map((b) => ({ text: (b.textContent || '').trim(), filled: b.className.includes('bg-primary') })),
93+
);
94+
const cancelAt = order.findIndex((b) => b.text === 'Cancel');
95+
const saveAt = order.findIndex((b) => b.text === 'Save');
96+
expect(cancelAt, JSON.stringify(order)).toBeGreaterThanOrEqual(0);
97+
expect(saveAt, JSON.stringify(order)).toBeGreaterThan(cancelAt);
98+
expect(order.filter((b) => b.filled).map((b) => b.text)).toEqual(['Save']);
99+
await expect(cancel).not.toHaveClass(/bg-primary/);
100+
101+
// ── 4. A new line starts on its defaults, unflagged; left as it came, it is not stored. ──
102+
const editor = page.locator('[data-body-table-editor]').first();
103+
await editor.scrollIntoViewIfNeeded();
104+
const lines = editor.locator('tbody tr');
105+
const before = await lines.count();
106+
await editor.getByTestId('line-items-add').click();
107+
await expect(lines).toHaveCount(before + 1);
108+
// The grid keeps a trailing entry line, so the added line is the one before it.
109+
const added = lines.nth(before - 1);
110+
await expect(added).toContainText('Other');
111+
await expect(added).toContainText('Submitted');
112+
await expect(editor.locator('[data-testid^="line-items-invalid"]')).toHaveCount(0);
113+
114+
await save.click();
115+
await expect(toolbar.getByRole('button', { name: 'Edit', exact: true })).toBeVisible({ timeout: 15_000 });
116+
const stored = await request.get(`${API}/api/v1/data/${LINE}?$top=500`);
117+
expect(stored.ok(), await stored.text()).toBeTruthy();
118+
const body = await stored.json();
119+
const rows: any[] = (body.records ?? body.data ?? []).filter((r: any) => r.expense_report === id);
120+
expect(rows, 'an added line left on its defaults is not stored').toHaveLength(0);
121+
} finally {
122+
await request.delete(`${API}/api/v1/data/${OBJECT}/${encodeURIComponent(id)}`);
123+
}
124+
});
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#35745 — the band above the tabs, on the pages that are NOT laid
11+
* out by `RecordPageColumns`.
12+
*
13+
* The record page's scroller and the column layout each padded their top
14+
* 24px on a desktop, stacking a 48px band under the header. The scroller now
15+
* pads only its sides and foot, and the column layout pads its own top
16+
* (pinned in `RecordPageColumns.test.tsx`). Everything else the scroller
17+
* hosts must still start clear of the header on its own: an authored page the
18+
* page renderer draws carries the renderer's `p-3 md:p-4 lg:p-6`, and a print
19+
* page's screen-only chrome, which sits above that page, takes its own top
20+
* margin. (The loading, error and not-found states are early returns of the
21+
* view and never render inside the scroller.)
22+
*
23+
* Mounted through `RecordDetailView` itself, so the padding is read off the
24+
* scroller and page root the real view and page renderer draw.
25+
*/
26+
import * as React from 'react';
27+
import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest';
28+
import { render, waitFor, cleanup } from '@testing-library/react';
29+
import { MemoryRouter } from 'react-router-dom';
30+
import { MetadataCtx } from '@object-ui/react';
31+
32+
vi.mock('@object-ui/auth', async (importOriginal) => ({
33+
...(await importOriginal<Record<string, unknown>>()),
34+
useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }),
35+
createAuthenticatedFetch: () => vi.fn(),
36+
}));
37+
vi.mock('@object-ui/collaboration', async (importOriginal) => ({
38+
...(await importOriginal<Record<string, unknown>>()),
39+
useRecordPresence: () => [],
40+
PresenceAvatars: () => null,
41+
}));
42+
vi.mock('sonner', () => ({
43+
toast: Object.assign(vi.fn(), {
44+
success: vi.fn(), error: vi.fn(), info: vi.fn(),
45+
warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(),
46+
}),
47+
}));
48+
// Orthogonal chrome, stubbed.
49+
vi.mock('./ActionConfirmDialog', () => ({ ActionConfirmDialog: () => null }));
50+
vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null }));
51+
vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null }));
52+
vi.mock('./FlowRunner', () => ({ FlowRunner: () => null }));
53+
vi.mock('./MetadataInspector', () => ({
54+
MetadataPanel: () => null,
55+
useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }),
56+
}));
57+
58+
import { RecordDetailView } from './RecordDetailView';
59+
60+
const OBJECT = 'os_35745_project';
61+
const REC = 'prj-1';
62+
63+
const objectDef = {
64+
name: OBJECT,
65+
label: 'Project',
66+
enable: { files: true },
67+
highlightFields: ['name'],
68+
fields: {
69+
id: { label: 'Id', type: 'text' },
70+
name: { label: 'Name', type: 'text' },
71+
owner_email: { label: 'Owner Email', type: 'text' },
72+
},
73+
};
74+
75+
const RECORD = {
76+
id: REC,
77+
name: 'Website Relaunch',
78+
owner_email: 'auditor@example.com',
79+
created_at: '2026-01-02T03:04:05.000Z',
80+
updated_at: '2026-02-03T04:05:06.000Z',
81+
};
82+
83+
/** An authored page the page renderer draws (not laid out by `RecordPageColumns`). */
84+
const ASSIGNED_PAGE = {
85+
name: 'os_35745_project_detail',
86+
label: 'Project',
87+
type: 'record',
88+
object: OBJECT,
89+
regions: [
90+
{
91+
name: 'main',
92+
components: [
93+
{ type: 'record:details', id: 'overview', properties: { sections: [{ label: 'Overview', fields: ['owner_email'] }] } },
94+
],
95+
},
96+
],
97+
};
98+
99+
function makeDataSource() {
100+
return {
101+
find: vi.fn(async () => ({ data: [], total: 0, hasMore: false, pageSize: 50 })),
102+
findOne: vi.fn(async (name: string, id: string) => (name === OBJECT ? { ...RECORD, id } : null)),
103+
create: vi.fn(async (_o: string, row: any) => row),
104+
update: vi.fn(async () => ({})),
105+
delete: vi.fn(async () => ({})),
106+
getObjectSchema: async (name: string) => ({ name, fields: objectDef.fields }),
107+
} as any;
108+
}
109+
110+
function makeMetadata(pages: any[]) {
111+
return {
112+
objects: [], pages, loading: false, error: null,
113+
refresh: async () => {}, invalidate: () => {},
114+
ensureType: async () => pages, getItem: async () => null,
115+
getItemsByType: () => pages,
116+
} as any;
117+
}
118+
119+
function renderRecordPage(pages: any[]): HTMLElement {
120+
const { container } = render(
121+
<MemoryRouter initialEntries={[`/app/demo/${OBJECT}/${REC}`]}>
122+
<MetadataCtx.Provider value={makeMetadata(pages)}>
123+
<RecordDetailView
124+
dataSource={makeDataSource()}
125+
objects={[objectDef]}
126+
onEdit={() => {}}
127+
objectNameOverride={OBJECT}
128+
recordIdOverride={REC}
129+
embedded
130+
/>
131+
</MetadataCtx.Provider>
132+
</MemoryRouter>,
133+
);
134+
return container;
135+
}
136+
137+
/** The record page's scroller: the element the view scrolls the page in. */
138+
function scrollerOf(root: ParentNode): HTMLElement {
139+
const el = root.querySelector('.scroll-pb-48');
140+
expect(el, 'the view must draw its page scroller').toBeTruthy();
141+
return el as HTMLElement;
142+
}
143+
144+
/** Utilities that pad an element's TOP: `p-*`, `pt-*`, `py-*`, at any breakpoint. */
145+
const topPadding = (el: Element) =>
146+
Array.from(el.classList).filter((c) => /^(?:[a-z]+:)?(?:p|pt|py)-\d+$/.test(c));
147+
148+
beforeAll(() => {
149+
Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 });
150+
});
151+
152+
beforeEach(() => {
153+
cleanup();
154+
vi.stubGlobal('fetch', vi.fn(async () =>
155+
new Response(JSON.stringify({ data: [] }), {
156+
status: 200, headers: { 'content-type': 'application/json' },
157+
})));
158+
});
159+
160+
afterEach(() => { vi.unstubAllGlobals(); vi.clearAllMocks(); });
161+
162+
describe('the scroller pads no top; what it hosts starts clear of the header (objectstack#35745)', () => {
163+
it('an authored page drawn by the page renderer pads its own top, under a scroller that pads none', async () => {
164+
const container = renderRecordPage([ASSIGNED_PAGE]);
165+
await waitFor(() => expect(container.textContent).toContain('auditor@example.com'));
166+
const scroller = scrollerOf(container);
167+
expect(topPadding(scroller)).toEqual([]);
168+
// CONTROL: the scroller still insets its sides and foot.
169+
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);
170+
const page = container.querySelector('[data-page-type="record"]') as HTMLElement;
171+
expect(page, 'the page renderer must draw the record page root').toBeTruthy();
172+
expect(scroller.contains(page)).toBe(true);
173+
expect(topPadding(page)).toEqual(expect.arrayContaining(['p-3', 'md:p-4', 'lg:p-6']));
174+
});
175+
176+
it("a print page's screen-only chrome takes its own top margin above the page", async () => {
177+
const PRINT_PAGE = {
178+
...ASSIGNED_PAGE,
179+
name: 'os_35745_project_print',
180+
isDefault: true,
181+
print: { paperSize: 'A4' },
182+
regions: [{ name: 'main', components: [{ type: 'text', value: 'Project sheet' }] }],
183+
};
184+
const container = renderRecordPage([PRINT_PAGE]);
185+
const chrome = await waitFor(() => {
186+
const el = container.querySelector('[data-record-print-chrome]');
187+
expect(el, 'a page that declares `print` draws the screen-only chrome').toBeTruthy();
188+
return el as HTMLElement;
189+
});
190+
const scroller = scrollerOf(container);
191+
expect(scroller.firstElementChild).toBe(chrome);
192+
expect(chrome.classList).toContain('mt-3');
193+
const page = container.querySelector('[data-print-page]') as HTMLElement;
194+
expect(page, 'the page is drawn as a print page').toBeTruthy();
195+
expect(topPadding(page)).toEqual(expect.arrayContaining(['p-3', 'md:p-4', 'lg:p-6']));
196+
});
197+
});

0 commit comments

Comments
 (0)