diff --git a/.changeset/36147-record-field-list.md b/.changeset/36147-record-field-list.md new file mode 100644 index 00000000000..ab961bf89ff --- /dev/null +++ b/.changeset/36147-record-field-list.md @@ -0,0 +1,24 @@ +--- +'@object-ui/plugin-detail': patch +'@object-ui/fields': patch +'@object-ui/i18n': patch +--- + +feat(console): the record page's field area is one list — one field a row in the side preview, on a phone and in the wide page's pinned left column + +Clause-②: yes (widening) +Metadata-protocol: none + +The synthesized record page's field area (objectstack#36147, ruling on the card 7066516044): + +- **One column at any width.** The drawer (at any width), the split pane, the phone's 「详情」 tab, the wide page's pinned left column and a desktop full page that has other tabs but is not pinned (an opportunity's 详情 tab goes from three columns to one) draw the fields one a row: label left, value right, a hairline between rows. The phone's own grouped-inset face is gone there; it is the same list. A full page whose details are its only face (no other tab, none hidden) keeps laying a group out by width. +- **Group title row.** The title sits left and its chevron at the row's right end, pointing down while the group is folded and up while it is open; the whole row toggles. +- **Referenced records are chips.** A lookup value is drawn as a pill with the referenced object's colour tile (`ObjectSchema.color` / `icon`, objectstack#35985) and the record's whole name, wrapping rather than cut. A click on the chip opens the record; the rest of an editable lookup's row edits it. Everywhere else a reference keeps its link face. +- **Empty fields fold into one row.** Every empty field of every group is folded into the list's one last row (「显示 N 个空字段」), replacing the per-group toggle and the 「N 个空分组」 line on this page. The reader's choice is the per-object record-page preference `showEmptyFields` (objectstack#25883), so it holds for the next record of the object. An authored `hideEmpty` group stays hidden and is not counted. +- **「系统信息」 is the last group,** folded until opened: created by, created on, updated by, updated on (when the record was updated), the owner (when the body does not draw it) and the record ID, one fact a row. On this page it **replaces the one-line meta footer that objectui#12307 introduced**; outside the laid-out record page that line is unchanged. +- **A click edits; no pencil.** A single click on an editable value enters edit (a click on a link, a button or a text selection inside it is not taken); the hover pencil is no longer drawn, and stays in the DOM only as the keyboard's way in (visible on focus). A double click is no longer needed. **A read-only value takes no click any more**: the click-to-copy on read-only rows is removed on this page. For a mouse or a keyboard its copy icon, shown on hover or keyboard focus, stays; a touch screen shows none, and the value is selected by a long press. +- Authored record pages and every other DetailView keep their faces. + +`@object-ui/fields` widens: it exports `ReferenceChipContext` (a boolean React context, default `false`) that switches `LookupCellRenderer`'s reference link to the chip face. + +`@object-ui/i18n` widens: five new keys in every pack, `detail.systemInfo` (系统信息 / System information), `detail.createdTime`, `detail.updatedTime`, `detail.recordNumber` and `detail.clickToEdit`. diff --git a/ui/e2e/live/inline-edit-polish-2572.spec.ts b/ui/e2e/live/inline-edit-polish-2572.spec.ts index 3814f6fc1e0..4659c62a261 100644 --- a/ui/e2e/live/inline-edit-polish-2572.spec.ts +++ b/ui/e2e/live/inline-edit-polish-2572.spec.ts @@ -56,7 +56,9 @@ const REPO_ROOT = decodeURIComponent(new URL(import.meta.url).pathname) .slice(0, -SELF_DEPTH_BELOW_REPO_ROOT) .join('/'); -const EDIT_HINT = 'Double-click to edit'; +// The record page's field list enters edit on a click of the value +// (objectstack#36147); the value carries this title. +const EDIT_HINT = 'Click to edit'; function authToken(): string { const state = JSON.parse(readFileSync(join(REPO_ROOT, 'e2e/live/.auth/state.json'), 'utf8')); @@ -117,12 +119,12 @@ test('record inline-edit polish (#2572) — showcase Project end-to-end', async if (/\/api\/v1\/data\/showcase_account\/[^/?]+/.test(r.url())) accountHydrations.push(r.url()); }); - // ── Enter the shared inline-edit session (double-click a details-body field). ── + // ── Enter the shared inline-edit session (click a details-body field). ── const spentGroup = page .locator('div.group') .filter({ has: page.getByText('Spent', { exact: true }) }) .last(); - await spentGroup.locator(`[title="${EDIT_HINT}"]`).dblclick(); + await spentGroup.locator(`[title="${EDIT_HINT}"]`).click(); const saveBtn = page.getByRole('button', { name: 'Save', exact: true }); await expect(saveBtn, 'save bar appears once the session is live').toBeVisible(); @@ -149,7 +151,7 @@ test('record inline-edit polish (#2572) — showcase Project end-to-end', async .locator('div.group') .filter({ has: page.getByText('Budget', { exact: true }) }) .last(); - await budgetGroup.locator(`[title="${EDIT_HINT}"]`).dblclick(); + await budgetGroup.locator(`[title="${EDIT_HINT}"]`).click(); await expect(saveBtn).toBeVisible(); const budgetInput2 = page.locator('input[type="number"][min="0"][step="0.01"]').first(); // Above the flow's 500k decision edge, so approving `manager_review` routes @@ -220,7 +222,7 @@ test('record inline-edit polish (#2572) — showcase Project end-to-end', async await expect(approvalTag, 'the header names the pending approval').toBeVisible(); await expect(approvalTag, 'an unlocked approval step does not lock the tag').not.toHaveAttribute('data-record-approval-locked'); // A double-click on the budget still opens an inline-edit session. - await budgetGroupOnPage().locator(`[title="${EDIT_HINT}"]`).dblclick(); + await budgetGroupOnPage().locator(`[title="${EDIT_HINT}"]`).click(); await expect(saveBtn, 'inline editing stays live during an unlocked approval').toBeVisible(); await page.keyboard.press('Escape'); await expect(saveBtn).toBeHidden(); @@ -261,7 +263,7 @@ test('record inline-edit polish (#2572) — showcase Project end-to-end', async await expect(approvalTag, 'the header names the locking approval').toBeVisible(); await expect(approvalTag, 'the approval tag carries the lock').toHaveAttribute('data-record-approval-locked', ''); - // …and a double-click on the (former) budget field must NOT open a session. - await budgetGroupOnPage().dblclick(); + // …and a click on the (former) budget field must NOT open a session. + await budgetGroupOnPage().click(); await expect(saveBtn).toBeHidden(); }); diff --git a/ui/e2e/live/read-only-member-record.spec.ts b/ui/e2e/live/read-only-member-record.spec.ts index 6b1535cfbf0..363da9d5a61 100644 --- a/ui/e2e/live/read-only-member-record.spec.ts +++ b/ui/e2e/live/read-only-member-record.spec.ts @@ -39,9 +39,12 @@ const writesInquiry = writesRecordsOf(OBJECT); // The record header's Edit CTA and the record body's inline-edit pencils carry // no test id; their accessible names are the `detail.edit` and -// `detail.editInlineHint` strings, en or zh. +// `detail.editInlineHint` strings, en or zh, or `detail.clickToEdit` on the +// record page's field list (objectstack#36147), where the pencil is the +// keyboard's way in, `sr-only` until focused, so it is counted, not seen. const editButton = (page: Page) => page.getByRole('button', { name: /^(Edit|编辑)$/ }); -const inlineEditPencils = (page: Page) => page.getByRole('button', { name: /^(Double-click to edit|双击编辑)$/ }); +const inlineEditPencils = (page: Page) => + page.getByRole('button', { name: /^(Double-click to edit|双击编辑|Click to edit|点击编辑)$/ }); test.use({ viewport: { width: 1440, height: 900 } }); @@ -116,7 +119,7 @@ test('a member who may read but not write an inquiry gets a read-only form and n await test.step('control, as the admin: the same form is editable and its save persists', async () => { await page.goto(recordPath(id)); await expect(editButton(page)).toBeVisible({ timeout: 30_000 }); - await expect(inlineEditPencils(page).first()).toBeVisible(); + await expect.poll(() => inlineEditPencils(page).count(), { timeout: 30_000 }).toBeGreaterThan(0); await page.goto(formPath(id)); const dialog = page.getByRole('dialog'); diff --git a/ui/e2e/record-flow-phone-targets.spec.ts b/ui/e2e/record-flow-phone-targets.spec.ts index bfd9ffcabe3..6199f9295c6 100644 --- a/ui/e2e/record-flow-phone-targets.spec.ts +++ b/ui/e2e/record-flow-phone-targets.spec.ts @@ -22,6 +22,12 @@ import { uiRoot } from '../scripts/ui-root.mjs'; * `min-h-[44px] sm:min-h-0` spellings) and shows the pencil on a coarse * pointer. Above `sm` every control keeps its desktop size. * + * On the synthesized record page's field list (objectstack#36147) a phone + * enters edit by tapping the value, and no pencil is drawn there: the pencil + * measured here is the one every other face of a section still draws + * (`PENCIL_CLASS`), and the field list's own button (`FIELD_LIST_PENCIL_CLASS`) + * is the keyboard's way in, `sr-only` until focused. + * * ⚠️ A Playwright spec and not a vitest test for the reason * `record-path-phone-row.spec.ts` gives: jsdom has no layout engine, so a * size read there is 0 and an assertion on it is vacuous. @@ -86,7 +92,8 @@ const CLS = { cardRowName: g('related', /className="(min-h-11 [^"]*text-primary hover:underline[^"]*)"/, ['min-h-11', 'sm:min-h-0']), cardMenu: g('cardMenu', /className="([^"]+)"\s*aria-label=\{t\('detail\.relatedCardMenu'/, ['h-11', 'w-11', 'sm:h-6']), cardHandle: g('cardMenu', /'(inline-flex h-11 w-11 [^']*)'/, ['h-11', 'w-11', 'sm:h-6']), - pencil: g('section', /className="([^"]+)"\s*aria-label=\{t\('detail\.editInlineHint'\)\}/, ['min-h-[44px]', 'pointer-coarse:opacity-100', 'opacity-0']), + pencil: g('section', /const PENCIL_CLASS =\s*'([^']+)'/, ['min-h-[44px]', 'pointer-coarse:opacity-100', 'opacity-0']), + fieldListPencil: g('section', /const FIELD_LIST_PENCIL_CLASS = '([^']+)'/, ['sr-only', 'focus-visible:not-sr-only']), stripPencil: g('strip', /className="([^"]+)"\s*aria-label=\{t\('detail\.editInlineHint'\)\}/, ['min-h-[44px]', 'pointer-coarse:opacity-100', 'opacity-0']), saveCancel: g('saveBar', /disabled=\{inline\.saving\}\s*className="([^"]+)"/, ['h-11', 'sm:h-9']), saveSave: g('saveBar', /disabled=\{inline\.saving \|\| locked\}\s*className="([^"]+)"/, ['h-11', 'sm:h-9']), @@ -262,6 +269,20 @@ test.describe('the record flow at phone width (objectstack#29071)', () => { }); } + test('on the field list a phone taps the value: its pencil takes no room and is no target until focused (objectstack#36147)', async ({ browser }) => { + const page = await open(browser, 375, 812, true); + await measure(page, `
Acme Corp
`); + const before = await page.evaluate(() => document.getElementById('list-pencil')!.getBoundingClientRect()); + expect(before.width).toBeLessThanOrEqual(1); + expect(before.height).toBeLessThanOrEqual(1); + // The keyboard's way in: focused, it is drawn at its own size. + // A keyboard focus (Tab), so `:focus-visible` holds. + await page.keyboard.press('Tab'); + const focused = await page.evaluate(() => document.getElementById('list-pencil')!.getBoundingClientRect()); + expect(focused.width).toBeGreaterThan(1); + await page.context().close(); + }); + test('above `sm`, with a mouse, the controls keep their desktop size and the pencil waits for hover', async ({ browser }) => { const page = await open(browser, 1280, 800, false); const r = await measure(page, fixture()); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index c8483659fe8..c1a38577213 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -3029,7 +3029,9 @@ describe('RecordDetailView.recordEditState-35599', () => { const headerButton = (label: string) => (Array.from(document.querySelectorAll('button')).find((b) => (b.textContent ?? '').trim() === label) as HTMLButtonElement | undefined) ?? null; - const pencils = (container: HTMLElement) => container.querySelectorAll('button[aria-label="Double-click to edit"]').length; + // The field list's pencil is named for a click (objectstack#36147), every other face's for a double-click. + const pencils = (container: HTMLElement) => + container.querySelectorAll('button[aria-label="Double-click to edit"], button[aria-label="Click to edit"]').length; const editor = (container: HTMLElement, id: string) => container.querySelector(`[data-body-table-editor="${id}"]`) as HTMLElement | null; const cells = (scope: HTMLElement, label: string) => Array.from(scope.querySelectorAll(`input[aria-label="${label}"]`)) as HTMLInputElement[]; const summaryInput = (container: HTMLElement) => @@ -3058,9 +3060,13 @@ describe('RecordDetailView.recordEditState-35599', () => { fireEvent.change(cells(tasks, 'Subject')[0], { target: { value: 'Visit' } }); } - /** The pencil of the Summary field (the inline-edit entry), on the details column. */ + /** + * The pencil of the Summary field (the inline-edit entry), on the details + * column: the keyboard's way in on the field list, named for a click + * (objectstack#36147). + */ const summaryPencil = (container: HTMLElement) => - (Array.from(container.querySelectorAll('[data-record-column="details"] button[aria-label="Double-click to edit"]')) as HTMLElement[]) + (Array.from(container.querySelectorAll('[data-record-column="details"] button[aria-label="Click to edit"]')) as HTMLElement[]) .find((b) => (b.closest('.group')?.textContent ?? '').includes('Summary')) ?? null; const saveBar = () => document.querySelector('[role="region"][aria-label="Edit fields"]') as HTMLElement | null; const detailInputValues = (container: HTMLElement) => diff --git a/ui/packages/app-shell/src/views/RecordDetailView.phoneOwnerLine-28909.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.phoneOwnerLine-28909.test.tsx index ae786e42763..ac35e6b6fc1 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.phoneOwnerLine-28909.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.phoneOwnerLine-28909.test.tsx @@ -28,11 +28,15 @@ * body draws the owner (the meta line does not), and an object whose body * draws no `owner_id` (the field is `hidden`) keeps the owner on the meta * line. + * + * On the laid-out page the meta line is the details column's last group, + * 「系统信息」 (objectstack#36147), folded until opened: the owner and the + * record ID it keeps are that group's rows, read here with the group opened. */ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, cleanup, waitFor } from '@testing-library/react'; +import { render, cleanup, waitFor, fireEvent, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { MetadataCtx } from '@object-ui/react'; import { RelatedCountStore } from '@object-ui/components'; @@ -172,7 +176,17 @@ async function metaLineLoaded(): Promise { ); } -const ownerEntry = (metaLine: HTMLElement) => metaLine.querySelector('[data-record-meta-owner]'); +/** Open the 「系统信息」 group the meta line is on the laid-out page (objectstack#36147). */ +function openSystemInfo(metaLine: HTMLElement) { + const toggle = within(metaLine).getByRole('button', { name: 'System information' }); + if (toggle.getAttribute('aria-expanded') !== 'true') fireEvent.click(toggle); +} +/** The value of the system group's row labelled `label`, or `null`. */ +const systemRow = (metaLine: HTMLElement, label: string) => { + const el = Array.from(metaLine.querySelectorAll('[data-detail-field-label]')).find((l) => l.textContent === label); + return (el?.closest('[data-detail-field-row]') as HTMLElement | null) ?? null; +}; +const ownerEntry = (metaLine: HTMLElement) => systemRow(metaLine, 'Owner'); /** How many times the owner's name is painted on the whole page. */ const ownerCount = () => document.body.textContent!.split('Ada Admin').length - 1; @@ -214,11 +228,12 @@ describe('the owner at every width, once (objectstack#28909)', () => { mountPage(); const metaLine = await metaLineLoaded(); expect(document.querySelector('[data-highlights-face]')).toBeNull(); + openSystemInfo(metaLine); await waitFor(() => expect(ownerCount()).toBe(1)); expect(ownerEntry(metaLine)).toBeNull(); expect(metaLine.textContent).not.toContain('Ada Admin'); // The rest of the meta line is still drawn. - expect(metaLine.querySelector('[data-record-meta-id]')!.textContent).toBe('r-1'); + expect(systemRow(metaLine, 'Record ID')!.textContent).toContain('r-1'); }); it.each([ @@ -229,11 +244,16 @@ describe('the owner at every width, once (objectstack#28909)', () => { mountPage(OBJECTS_OWNER_HIDDEN); const metaLine = await metaLineLoaded(); expect(document.querySelector('[data-highlights-face]')).toBeNull(); - const owner = ownerEntry(metaLine); + openSystemInfo(metaLine); + const owner = await waitFor(() => { + const row = ownerEntry(metaLine); + expect(row?.textContent).toContain('Ada Admin'); + return row; + }); expect(owner).toBeTruthy(); expect(owner!.textContent).toContain('Ada Admin'); expect(ownerCount()).toBe(1); // The rest of the meta line is still drawn. - expect(metaLine.querySelector('[data-record-meta-id]')!.textContent).toBe('r-1'); + expect(systemRow(metaLine, 'Record ID')!.textContent).toContain('r-1'); }); }); diff --git a/ui/packages/app-shell/src/views/RecordMetaFooter.ownerOnceBody-35941.test.tsx b/ui/packages/app-shell/src/views/RecordMetaFooter.ownerOnceBody-35941.test.tsx index a4da599c909..f0b1e46a159 100644 --- a/ui/packages/app-shell/src/views/RecordMetaFooter.ownerOnceBody-35941.test.tsx +++ b/ui/packages/app-shell/src/views/RecordMetaFooter.ownerOnceBody-35941.test.tsx @@ -25,6 +25,10 @@ * is read from the sections the block actually mounts, and the owner is * counted over the whole page. * + * On the laid-out page the meta line is the details column's last group, + * 「系统信息」 (objectstack#36147), folded until opened: the owner the line + * kept is that group's Owner row, read here with the group opened. + * * The strip half of the rule (a highlight strip that draws the owner) is * pinned in `@object-ui/plugin-detail`'s `RecordMetaFooter.ownerOnce-28868` * and `RecordMetaFooter.drawnStrip-28909`, unchanged. @@ -95,7 +99,18 @@ function renderDefaultPage(objectDef: ObjectDef) { const footerOf = (container: HTMLElement) => container.querySelector('[data-testid="record-meta-footer"]') as HTMLElement | null; -const footerOwner = (container: HTMLElement) => footerOf(container)?.querySelector('[data-record-meta-owner]') ?? null; +/** Open the 「系统信息」 group the meta line is on the laid-out page (objectstack#36147). */ +function openSystemInfo(container: HTMLElement) { + const toggle = within(footerOf(container)!).getByRole('button', { name: 'System information' }); + if (toggle.getAttribute('aria-expanded') !== 'true') fireEvent.click(toggle); +} +/** The system group's Owner row, or `null` when it has none. */ +const footerOwner = (container: HTMLElement) => { + const footer = footerOf(container); + if (!footer) return null; + const label = Array.from(footer.querySelectorAll('[data-detail-field-label]')).find((el) => el.textContent === 'Owner'); + return (label?.closest('[data-detail-field-row]') as HTMLElement | null) ?? null; +}; const detailsColumn = (container: HTMLElement) => container.querySelector('[data-record-column="details"]') as HTMLElement; /** How many times the owner's name is painted on the whole page. */ @@ -136,7 +151,8 @@ describe('the body draws owner_id: the meta line leaves the owner out (objectsta }); // Live control: the body and the meta line both drew. expect(within(detailsColumn(container)).getByText('grace@example.com')).toBeTruthy(); - expect(footerOf(container)!.querySelector('[data-record-meta-id]')!.textContent).toBe('C-35941'); + openSystemInfo(container); + expect(within(footerOf(container)!).getByText('C-35941')).toBeTruthy(); expect(footerOwner(container)).toBeNull(); expect(ownerCount(container)).toBe(1); @@ -149,6 +165,7 @@ describe('the body draws owner_id: the meta line leaves the owner out (objectsta const { container } = renderDefaultPage({ name: OBJECT, fields: FIELDS }); expect(within(detailsColumn(container)).getByText('grace@example.com')).toBeTruthy(); expect(footerOf(container)).not.toBeNull(); + openSystemInfo(container); expect(footerOwner(container)).toBeNull(); expect(ownerCount(container)).toBe(1); @@ -166,6 +183,7 @@ describe('the body draws owner_id: the meta line leaves the owner out (objectsta }, }); expect(within(detailsColumn(container)).getByText('Other')).toBeTruthy(); + openSystemInfo(container); expect(footerOwner(container)).toBeNull(); expect(ownerCount(container)).toBe(1); @@ -185,6 +203,7 @@ describe('the body does not draw owner_id: the meta line keeps the owner (object }, }); expect(within(detailsColumn(container)).getByText('grace@example.com')).toBeTruthy(); + openSystemInfo(container); expect(footerOwner(container)).not.toBeNull(); expect(footerOwner(container)!.textContent).toContain(OWNER_NAME); @@ -206,6 +225,7 @@ describe('the body does not draw owner_id: the meta line keeps the owner (object }, }); // Collapsed, the group draws its heading and no rows. + openSystemInfo(container); expect(footerOwner(container)).not.toBeNull(); expect(ownerCount(container)).toBe(1); diff --git a/ui/packages/fields/src/__tests__/referenceChip-36147.test.tsx b/ui/packages/fields/src/__tests__/referenceChip-36147.test.tsx new file mode 100644 index 00000000000..f2c5f7523d7 --- /dev/null +++ b/ui/packages/fields/src/__tests__/referenceChip-36147.test.tsx @@ -0,0 +1,95 @@ +/** + * 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#36147 item 4 — on a record page's field area a referenced + * record is a chip: the referenced object's colour tile (`ObjectSchema.color` + * and `icon`, objectstack#35985), then the record's whole name, wrapping, not + * cut. A click opens that record and is not the row's. Everywhere else a + * reference keeps its link face. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'; +import React from 'react'; + +import { LookupCellRenderer, ReferenceChipContext } from '../index'; +import { RelatedRecordActionsProvider, SchemaRendererProvider } from '@object-ui/react'; + +afterEach(() => cleanup()); + +const ACCOUNT = { name: 'account', label: 'Account', nameField: 'name', color: 'blue', icon: 'building', fields: { name: { type: 'text' } } }; +const LONG_NAME = 'Shenzhen Xinghe E-Commerce Company Limited'; + +function makeSource() { + return { + find: vi.fn(async () => ({ data: [] })), + findOne: vi.fn(async () => null), + getObjectSchema: vi.fn(async (objectName: string) => (objectName === 'account' ? ACCOUNT : undefined)), + }; +} + +function makeHost() { + return { + resolve: () => ({}), + recordHref: (objectName: string, recordId: string | number) => `/apps/crm/${objectName}/record/${recordId}`, + openRecord: vi.fn(), + } as any; +} + +function renderCell({ chip, host }: { chip: boolean; host: any }) { + const onRowClick = vi.fn(); + const utils = render( + + + +
+ +
+
+
+
, + ); + return { ...utils, onRowClick }; +} + +describe('a reference drawn as a chip (objectstack#36147 item 4)', () => { + it('draws the referenced object colour tile and the whole name, on a pill that opens the record', async () => { + const host = makeHost(); + const { container, onRowClick } = renderCell({ chip: true, host }); + const chip = container.querySelector('a[data-record-chip]') as HTMLAnchorElement; + expect(chip).not.toBeNull(); + expect(chip.getAttribute('href')).toBe('/apps/crm/account/record/acc-1'); + await waitFor(() => expect(chip.querySelector('[data-object-icon-tile="blue"]')).not.toBeNull()); + const name = Array.from(chip.querySelectorAll('span')).find((el) => el.textContent === LONG_NAME)!; + expect(name).toBeTruthy(); + expect(name.className).not.toMatch(/\btruncate\b/); + expect(name.className).toContain('break-words'); + // Not the link face: no primary-coloured text. + expect(chip.className).not.toContain('text-primary'); + + fireEvent.click(chip); + expect(host.openRecord).toHaveBeenCalledWith('account', 'acc-1'); + expect(onRowClick).not.toHaveBeenCalled(); + }); + + it('with no route to the record, the chip is the same pill and not a link', () => { + const { container } = renderCell({ chip: true, host: null }); + expect(container.querySelector('a')).toBeNull(); + const pill = container.querySelector('span[data-record-chip]'); + expect(pill?.textContent).toBe(LONG_NAME); + expect(pill?.querySelector('[data-object-icon-tile]')).not.toBeNull(); + }); + + it('outside a field area a reference keeps its link face', () => { + const { container } = renderCell({ chip: false, host: makeHost() }); + const link = container.querySelector('a[data-record-link]') as HTMLAnchorElement; + expect(link.hasAttribute('data-record-chip')).toBe(false); + expect(link.className).toContain('text-primary'); + expect(link.querySelector('[data-object-icon-tile]')).toBeNull(); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 7a7061a336f..e3fdce1e7cc 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -17,7 +17,7 @@ import { ComponentRegistry, percentDisplayValue, type PercentScale, getRecordDis import { valueSchemaFor, resolveFieldScale } from '@objectstack/spec/data'; import type { ReferenceNameOnlyValue } from '@objectstack/spec/data'; import { useLocalization, useDisplayLocale, formatDisplayNumber, readHomeAmountSource } from '@object-ui/i18n'; -import { Badge, Avatar, AvatarImage, AvatarFallback, Button, Checkbox, EmptyValue, cn, setFieldReadFaceResolver } from '@object-ui/components'; +import { Badge, Avatar, AvatarImage, AvatarFallback, Button, Checkbox, EmptyValue, ObjectIconTile, cn, setFieldReadFaceResolver } from '@object-ui/components'; import { Check, Copy, Phone as PhoneIcon, MapPin, CircleQuestionMark, Lock, Star } from 'lucide-react'; import { useObjectTranslation, classifyLoadError } from '@object-ui/react'; import { SchemaRendererContext as _SchemaRendererContext } from '@object-ui/react'; @@ -2475,6 +2475,19 @@ function referencedRecordId(item: unknown): string | number | undefined { * link address" behave the way a link is supposed to; a plain left click is * handed to the host so navigation stays in-app. */ +/** + * Whether a referenced record is drawn as a chip (objectstack#36147): the + * referenced object's colour tile (`ObjectSchema.color` and `icon`, + * objectstack#35985) then the record's name, on a muted pill, the name + * wrapping instead of truncating. A record page's field area provides it; + * everywhere else a reference keeps its link face. A chip with no host route + * is the same pill, not a link. + */ +export const ReferenceChipContext = React.createContext(false); + +const REFERENCE_CHIP_CLASS = + 'inline-flex max-w-full items-start gap-1.5 rounded-md bg-muted px-1.5 py-0.5 align-top text-foreground'; + function ReferencedRecordLink({ objectName, recordId, @@ -2493,13 +2506,34 @@ function ReferencedRecordLink({ children: React.ReactNode; }): React.ReactElement { const host = useRelatedRecordActions(); + const chip = React.useContext(ReferenceChipContext); const navigable = !!objectName && recordId != null && recordId !== ''; const href = navigable && host?.recordHref ? host.recordHref(objectName as string, recordId as string | number) : null; - if (!href) return <>{children}; + const face = chip ? ( + <> + + {label || children} + + ) : children; + + if (!href) { + return chip ? ( + + {face} + + ) : ( + <>{children} + ); + } // Hovering the link (or Space on it) shows the referenced record's card // (objectstack#27604): the same reference, a glance instead of a visit. @@ -2507,7 +2541,11 @@ function ReferencedRecordLink({ - {children} + {face} ); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 266d2ced82a..6c7356f88fa 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1430,6 +1430,12 @@ const ar = { unknownUser: "غير معروف", created: "أُنشئ", updated: "حُدِّث", + // Record page field list (objectstack#36147). + systemInfo: "معلومات النظام", + createdTime: "تاريخ الإنشاء", + updatedTime: "تاريخ التعديل", + recordNumber: "معرّف السجل", + clickToEdit: "انقر للتحرير", back: "رجوع", edit: "تحرير", editInline: "تحرير", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 403ca6ae1bb..ea9f684a4a7 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1648,6 +1648,12 @@ const de = { updatedBy: "Aktualisiert von", created: "Erstellt", updated: "Aktualisiert", + // Record page field list (objectstack#36147). + systemInfo: "Systeminformationen", + createdTime: "Erstellt am", + updatedTime: "Geändert am", + recordNumber: "Datensatz-ID", + clickToEdit: "Zum Bearbeiten klicken", // objectui#3863 — base key. de's categories are exactly `one`/`other`, so this // slot is unreachable here and equals `_other` for key-set parity. showEmptyRelated: "+ {{count}} leer", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 9ff4af973f9..49e03f888aa 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1895,6 +1895,12 @@ const en = { updatedBy: 'Updated by', created: 'Created', updated: 'Updated', + // Record page field list (objectstack#36147). + systemInfo: 'System information', + createdTime: 'Created on', + updatedTime: 'Updated on', + recordNumber: 'Record ID', + clickToEdit: 'Click to edit', // Attachments dropFilesToUpload: 'Drop files here or click to upload', attachmentCount: '{{count}} attachment', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 96159fc8ce3..e9b9d8fa3ba 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1702,6 +1702,12 @@ const es = { updatedBy: "Actualizado por", created: "Creado", updated: "Actualizado", + // Record page field list (objectstack#36147). + systemInfo: "Información del sistema", + createdTime: "Fecha de creación", + updatedTime: "Fecha de modificación", + recordNumber: "ID del registro", + clickToEdit: "Haga clic para editar", // objectui#3863 — base key, answering only a call made without a count. es's // `many` (exact millions) has its own slot since objectui#11432; it repeats // `_other` here because the count governs no noun complement. diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 2134308f32e..3dc9aabd09e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1325,6 +1325,12 @@ const fr = { unknownUser: "Inconnu", created: "Créé", updated: "Mis à jour", + // Record page field list (objectstack#36147). + systemInfo: "Informations système", + createdTime: "Créé le", + updatedTime: "Modifié le", + recordNumber: "ID de l’enregistrement", + clickToEdit: "Cliquez pour modifier", back: "Retour", edit: "Modifier", editInline: "Modifier", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 63cd1c97184..d6e1298aa99 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1648,6 +1648,12 @@ const ja = { updatedBy: "更新者", created: "作成", updated: "更新", + // Record page field list (objectstack#36147). + systemInfo: "システム情報", + createdTime: "作成日時", + updatedTime: "更新日時", + recordNumber: "レコード ID", + clickToEdit: "クリックで編集", // objectui#3863 — base key. ja has a single plural category (`other`), so this // slot is unreachable here and equals `_other` for key-set parity. showEmptyRelated: "+ {{count}} 件(空)", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index ff3406710af..d837e447619 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1648,6 +1648,12 @@ const ko = { updatedBy: "업데이트한 사람", created: "작성됨", updated: "업데이트됨", + // Record page field list (objectstack#36147). + systemInfo: "시스템 정보", + createdTime: "생성 일시", + updatedTime: "수정 일시", + recordNumber: "레코드 ID", + clickToEdit: "클릭하여 편집", // objectui#3863 — base key. ko has a single plural category (`other`), so this // slot is unreachable here and equals `_other` for key-set parity. showEmptyRelated: "+ {{count}}개 비어 있음", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 5ac02b304b5..fe6bf097635 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1325,6 +1325,12 @@ const pt = { unknownUser: "Desconhecido", created: "Criado", updated: "Atualizado", + // Record page field list (objectstack#36147). + systemInfo: "Informações do sistema", + createdTime: "Criado em", + updatedTime: "Atualizado em", + recordNumber: "ID do registro", + clickToEdit: "Clique para editar", back: "Voltar", edit: "Editar", editInline: "Editar", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index d3ea838ac67..364f18ae00d 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1363,6 +1363,12 @@ const ru = { unknownUser: "Неизвестно", created: "Создано", updated: "Обновлено", + // Record page field list (objectstack#36147). + systemInfo: "Системная информация", + createdTime: "Дата создания", + updatedTime: "Дата изменения", + recordNumber: "ID записи", + clickToEdit: "Нажмите, чтобы изменить", back: "Назад", edit: "Редактировать", editInline: "Редактировать", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 9b480b27879..0b5153fe625 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1595,6 +1595,12 @@ const zh = { updatedBy: '更新人', created: '创建于', updated: '更新于', + // Record page field list (objectstack#36147). + systemInfo: '系统信息', + createdTime: '创建时间', + updatedTime: '修改时间', + recordNumber: '记录编号', + clickToEdit: '点击编辑', // Attachments dropFilesToUpload: '拖拽文件到此处或点击上传', attachmentCount: '{{count}} 个附件', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 459582fd35b..323eb9edea2 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1595,6 +1595,12 @@ const zhHant = { updatedBy: '更新人', created: '創建於', updated: '更新於', + // Record page field list (objectstack#36147). + systemInfo: '系統資訊', + createdTime: '建立時間', + updatedTime: '修改時間', + recordNumber: '記錄編號', + clickToEdit: '點選編輯', // Attachments dropFilesToUpload: '拖拽檔案到此處或點選上傳', attachmentCount: '{{count}} 個附件', diff --git a/ui/packages/plugin-detail/src/DetailSection.tsx b/ui/packages/plugin-detail/src/DetailSection.tsx index 398040ff907..ee0440d0672 100644 --- a/ui/packages/plugin-detail/src/DetailSection.tsx +++ b/ui/packages/plugin-detail/src/DetailSection.tsx @@ -25,7 +25,7 @@ import { useIsMobile, LazyIcon, } from '@object-ui/components'; -import { ChevronDown, ChevronRight, Copy, Check, Eye, EyeOff, Pencil } from 'lucide-react'; +import { ChevronDown, ChevronRight, ChevronUp, Copy, Check, Eye, EyeOff, Pencil } from 'lucide-react'; import { SchemaRenderer, toRenderableSchema, @@ -51,6 +51,7 @@ import { TextAreaField, TextCellRenderer, TextField, + ReferenceChipContext, } from '@object-ui/fields'; import type { DetailViewSection as DetailViewSectionType, DetailViewField, FieldMetadata } from '@object-ui/types'; import { applyDetailAutoLayout } from './autoLayout'; @@ -63,6 +64,7 @@ import { DetailsColumnCapContext, framelessSectionColumns, useDefaultRecordPage import { hasCellValue } from './emptiness'; import { RecordPageProvenanceContext } from './recordPageProvenance'; import { useReportBodyFields } from './recordBodyFields'; +import { useRecordFieldList, useReportEmptyFields } from './recordFieldList'; import { enrichDetailField, isComputedDetailField, @@ -142,6 +144,22 @@ export function framelessSpanClass(span: number | undefined, columns: 1 | 2 | 3) */ const ignoreReadOnlyChange = (): void => {}; +/** + * The inline-edit pencil beside a field. A real Tab stop, revealed on keyboard + * focus as well as on hover (objectstack#25883); a touch screen has no hover, + * so there it is always drawn, and below `sm` it is a 44 px target + * (objectstack#29071). + */ +const PENCIL_CLASS = + 'h-6 w-6 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100 transition-opacity shrink-0'; + +/** + * The field list draws no pencil (objectstack#36147): a click or a tap on the + * value is the way in, and the button stays only as the keyboard's way in, + * drawn while it has focus. + */ +const FIELD_LIST_PENCIL_CLASS = 'sr-only h-px w-px focus-visible:not-sr-only focus-visible:h-6 focus-visible:w-6 shrink-0'; + /** What a section reports while it draws no row of the page's record. */ const NO_REPORTED_FIELDS: readonly string[] = []; @@ -164,6 +182,19 @@ const NO_REPORTED_FIELDS: readonly string[] = []; * one predicate. ⛔ Not a `stopPropagation` on each link instead: that fixes * one descendant kind at a time and leaves the next one cancelled. */ +/** + * Whether a click on a field row belongs to something inside the value — a + * link, a button, a control — or ends a text selection the reader is making, + * rather than to the row (objectstack#36147: the row's click enters edit). + */ +function clickBelongsElsewhere(e: React.MouseEvent): boolean { + const target = e.target instanceof Element ? e.target : null; + const control = target?.closest('a, button, input, textarea, select, [role="button"], [role="link"], [role="checkbox"]'); + if (control && control !== e.currentTarget && e.currentTarget.contains(control)) return true; + const selection = typeof window !== 'undefined' ? window.getSelection?.() : null; + return !!selection && !selection.isCollapsed && !!selection.anchorNode && e.currentTarget.contains(selection.anchorNode); +} + function isRowActivationKey(e: React.KeyboardEvent): boolean { if (e.target !== e.currentTarget) return false; return e.key === 'Enter' || e.key === ' '; @@ -231,8 +262,14 @@ export const DetailSection: React.FC = ({ // drawn frameless: a title, a hairline and the field grid, no card. Paper // keeps the card face (objectui#12732), so a print page never takes it. const frameless = useDefaultRecordPage() && !isPrintPage; - // The record page's two-column tier caps the grid at two (objectstack#27524). + // The record page's layout caps the grid (objectstack#27524); at 1 the + // section is a row of the record's one field list (objectstack#36147). const framelessColumnCap = React.useContext(DetailsColumnCapContext); + const listFace = frameless && framelessColumnCap === 1; + // objectstack#36147 — on the laid-out record page every group folds its + // empty rows into the field list's one last row, not a toggle of its own. + const fieldList = useRecordFieldList(); + const foldsIntoList = frameless && fieldList !== null; const [copiedField, setCopiedField] = React.useState(null); const [visibleCount, setVisibleCount] = React.useState(undefined); // objectstack#25883 — "Show N empty fields" is the reader's choice for the @@ -405,6 +442,7 @@ export const DetailSection: React.FC = ({ const AUTO_HIDE_RATIO = isMobile ? 0.2 : 0.25; const filledCount = section.fields.length - emptyCount; const shouldAutoHideEmpty = + !foldsIntoList && !isPrintPage && !isEditing && section.fields.length >= AUTO_HIDE_MIN_FIELDS && @@ -464,14 +502,21 @@ export const DetailSection: React.FC = ({ // renders every row as an input (the ruling leaves it unchanged), and a print // page prints every declared row with no toggle (objectui#12717). const foldAllEmptySection = - allFieldsEmpty && !hideAllEmptySection && !isEditing && !isPrintPage; + !foldsIntoList && allFieldsEmpty && !hideAllEmptySection && !isEditing && !isPrintPage; // The authored all-empty hide is not the reader's to undo: it applies // whatever the reader's "show empty fields" choice is, now that the choice is // one per object and reaches sections that never drew the toggle // (objectstack#25883). const hideEmptyEffective = - hideAllEmptySection || (!showEmptyOverride && (shouldAutoHideEmpty || foldAllEmptySection)); + hideAllEmptySection || + (foldsIntoList + ? fieldList?.showEmpty !== true && !isEditing + : !showEmptyOverride && (shouldAutoHideEmpty || foldAllEmptySection)); + // In a field list the group's empty rows are the list's to count, hidden + // or shown: an all-empty group then draws nothing until they are shown. + // An authored all-empty hide is not the reader's to undo, so not counted. + useReportEmptyFields(foldsIntoList && !isEditing && !hideAllEmptySection ? emptyCount : 0); // Filter out empty fields when the auto-hide heuristic kicked in, when an // all-empty section is folded, or when one is hiding itself (its early @@ -802,7 +847,18 @@ export const DetailSection: React.FC = ({ // An editable field surfaces the pencil (edit) affordance instead of the // copy affordance, and reserves single-click for text selection — so // click-to-copy only applies to non-editable fields. - const copyInteractive = copyOffered && !canInlineEditField; + // The frameless face (the record page's field list, objectstack#36147) + // takes no click on a read-only row: a click there selects text, and the + // value is copied from its hover / focus button. An editable row's click + // enters edit instead. + const copyInteractive = copyOffered && !canInlineEditField && !frameless; + // The edit hint names the gesture the face takes: a click on the field + // list (objectstack#36147), a double-click elsewhere. The pencil, its + // tooltip and the value's title read it, so a screen reader hears the + // gesture that works. + const editHintLabel = frameless + ? t('detail.clickToEdit', { defaultValue: 'Click to edit' }) + : t('detail.editInlineHint'); const isCopied = copiedField === field.name; const fieldLabelText = fieldLabel(objectName || '', field.name, field.label || field.name); @@ -810,7 +866,7 @@ export const DetailSection: React.FC = ({ // hairline-separated rows inside the section card. The native-feeling // settings/detail form for the mobile target. Editing falls back to the // stacked layout below so inputs have room. - if (isMobile && !(isEditing && fieldEditable)) { + if (isMobile && !frameless && !(isEditing && fieldEditable)) { return (
= ({ className={cn( frameless ? 'group flex min-w-0 items-start gap-3' : 'space-y-1.5 group min-w-0', frameless ? framelessSpanClass(field.span, framelessColumns) : spanClass, + // The field list (objectstack#36147): one row under the other, a + // hairline between them. + listFace && 'border-b border-border/50 py-1.5 last:border-b-0', )} data-detail-field-row={frameless ? '' : undefined} > @@ -902,12 +961,22 @@ export const DetailSection: React.FC = ({ frameless && "min-w-0 flex-1", copyInteractive && "cursor-pointer active:bg-muted/60 transition-colors", // Editable fields hint interactivity on hover and enter edit on - // double-click (Salesforce/Airtable pattern). The negative margin - // keeps the hover highlight flush with the label above. + // double-click (Salesforce/Airtable pattern), on the frameless + // face on a click (objectstack#36147). The negative margin keeps + // the hover highlight flush with the label above. canInlineEditField && "cursor-pointer hover:bg-muted/40 transition-colors -mx-1.5 px-1.5" )} - onClick={copyInteractive ? () => handleCopyField(field.name, value) : undefined} - onDoubleClick={canInlineEditField ? () => onEnterInlineEdit?.(field.name) : undefined} + onClick={ + copyInteractive + ? () => handleCopyField(field.name, value) + : frameless && canInlineEditField + ? (e: React.MouseEvent) => { + if (clickBelongsElsewhere(e)) return; + onEnterInlineEdit?.(field.name); + } + : undefined + } + onDoubleClick={canInlineEditField && !frameless ? () => onEnterInlineEdit?.(field.name) : undefined} onKeyDown={copyInteractive ? (e: React.KeyboardEvent) => { if (isRowActivationKey(e)) { e.preventDefault(); @@ -916,7 +985,7 @@ export const DetailSection: React.FC = ({ } : undefined} role={copyInteractive ? "button" : undefined} tabIndex={copyInteractive ? 0 : undefined} - title={canInlineEditField ? t('detail.editInlineHint') : undefined} + title={canInlineEditField ? editHintLabel : undefined} >
= ({ - {t('detail.editInlineHint')} + {editHintLabel} @@ -964,7 +1027,14 @@ export const DetailSection: React.FC = ({ size="icon" // A real Tab stop, so it is revealed on keyboard focus as // well as on hover, like the pencil above (objectstack#26329). - className="h-6 w-6 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 transition-opacity shrink-0" + // On the field list a touch screen draws no copy icon + // (objectstack#36147, ruling 1): a tap sets `:hover`, which + // would reveal it; the reader long-presses the value instead. + className={cn( + "h-6 w-6 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 transition-opacity shrink-0", + frameless && "pointer-coarse:hidden", + )} + data-detail-copy="" // objectui#12625 — an icon-only button; the tooltip is // closed at rest, so without this it has no name. aria-label={t('detail.copyToClipboard')} @@ -1037,7 +1107,7 @@ export const DetailSection: React.FC = ({ const content = ( <> - {renderedFields.length === 0 ? null : isMobile ? ( + {renderedFields.length === 0 ? null : isMobile && !frameless ? (
{renderedFields.map(renderField)}
@@ -1095,7 +1165,12 @@ export const DetailSection: React.FC = ({ if (frameless) { const titleRow = 'flex min-h-11 sm:min-h-9 w-full items-center justify-between gap-2 py-1.5 text-left text-sm font-medium text-foreground'; return ( -
+ +
{section.title && !section.collapsible && (

@@ -1118,10 +1193,12 @@ export const DetailSection: React.FC = ({ {section.icon && } {section.title} + {/* At the row's right end, pointing down while the group is + folded and up while it is open (objectstack#36147). */} {isCollapsed ? ( - - ) : ( + ) : ( + )}

@@ -1131,6 +1208,7 @@ export const DetailSection: React.FC = ({ )} {!isCollapsed &&
{content}
}
+
); } diff --git a/ui/packages/plugin-detail/src/DetailView.tsx b/ui/packages/plugin-detail/src/DetailView.tsx index 4c410ca82b2..998bd2b9dea 100644 --- a/ui/packages/plugin-detail/src/DetailView.tsx +++ b/ui/packages/plugin-detail/src/DetailView.tsx @@ -45,6 +45,7 @@ import { RecordComments } from './RecordComments'; import { ActivityTimeline } from './ActivityTimeline'; import { HistoryTimeline } from './HistoryTimeline'; import { RecordMetaFooter } from './RecordMetaFooter'; +import { useRecordFieldList } from './recordFieldList'; import { RecordPageProvenanceContext } from './recordPageProvenance'; import { SchemaRenderer, SchemaErrorBoundary, toRenderableSchema, useSafeFieldLabel, useDataInvalidation, useInlineEdit, useRowPredicate, resolveApprovalLock, usePrintPage, useRecordContext, usePredicateScope } from '@object-ui/react'; import { buildExpandFields, declaredNameField, getRecordDisplayName, formatTitleTemplate, recordDelete, recordDisplayValueAt, resolveAffordance, toDisplayDate, userActionPredicates, withoutDeniedFields } from '@object-ui/core'; @@ -340,7 +341,12 @@ export const DetailView: React.FC = ({ // whole-body fold (`EmptySectionsFold`). const inRecordDetailsBody = React.useContext(EmptySectionsLineContext); const onDefaultRecordPage = useDefaultRecordPage(); - const emptySectionsAsLine = inRecordDetailsBody || onDefaultRecordPage; + // objectstack#36147 — in the laid-out record page's field list every + // section folds its own empty rows into the list's one last row, so this + // body draws its sections as they are, with neither fold. + const fieldList = useRecordFieldList(); + const foldsIntoFieldList = fieldList !== null && onDefaultRecordPage && !isPrintPage; + const emptySectionsAsLine = (inRecordDetailsBody || onDefaultRecordPage) && !foldsIntoFieldList; const isInlineEditing = inline?.editing ?? false; const editedValues = inline?.draft ?? EMPTY_DRAFT; const autoFocusField = inline?.autoFocusField ?? null; @@ -1206,7 +1212,7 @@ export const DetailView: React.FC = ({ // for the whole body (`EmptySectionsFold`). Only when the sections ARE the // body: section groups draw fields of their own beside them. const foldEmptySections = (rendered: React.ReactNode) => - drawn.sectionGroups?.length ? rendered : ( + drawn.sectionGroups?.length || foldsIntoFieldList ? rendered : ( = ({ ); }; + +/** + * The field list's last row (objectstack#36147): every empty field of every + * group the list holds, folded into one 「显示 N 个空字段」 row. The groups + * hide their own empty rows and report them (`useReportEmptyFields`); this + * row reads the total and reveals them all in place, then reads 「隐藏空字段」. + * Draws nothing when no group holds an empty row, and outside a field list. + */ +export const EmptyFieldsRow: React.FC = () => { + const { t } = useDetailTranslation(); + const list = useRecordFieldList(); + const total = useEmptyFieldTotal(); + if (!list || total === 0) return null; + const shown = list.showEmpty; + return ( +
+ +
+ ); +}; diff --git a/ui/packages/plugin-detail/src/RecordMetaFooter.tsx b/ui/packages/plugin-detail/src/RecordMetaFooter.tsx index 860a5759278..dde591c3b6d 100644 --- a/ui/packages/plugin-detail/src/RecordMetaFooter.tsx +++ b/ui/packages/plugin-detail/src/RecordMetaFooter.tsx @@ -18,6 +18,10 @@ import { hasCellValue } from './emptiness'; import { useDefaultRecordPage } from './defaultRecordPage'; import { deriveHighlightFields } from './synth/buildDefaultPageSchema'; import { useBodyDrawnFieldNames } from './recordBodyFields'; +import { useRecordFieldList } from './recordFieldList'; +import { RecordPageProvenanceContext } from './recordPageProvenance'; +import { DetailSection } from './DetailSection'; +import type { DetailViewField } from '@object-ui/types'; /** * The record's reassignable owner column — the canonical injected @@ -250,6 +254,9 @@ export const RecordMetaFooter: React.FC = ({ // The fields the page's body draws (objectstack#35941), read before the // early return so hook order never varies; `null` outside the laid-out page. const bodyFields = useBodyDrawnFieldNames(); + // objectstack#36147 — in the record page's field list the provenance is the + // list's last group, 「系统信息」, folded until opened, not a line of its own. + const fieldList = useRecordFieldList(); if (!data) return null; const createdAt = toDate(data[AUDIT_FIELDS.createdAt]); @@ -285,6 +292,39 @@ export const RecordMetaFooter: React.FC = ({ if (!hasCreated && !hasUpdated && !owner && !recordId) return null; + if (fieldList && v3MetaLine) { + const actorField = (name: string, label: string): DetailViewField => { + const def = objectSchema?.fields?.[name]; + return { name, label, type: def?.type || 'lookup', reference: def?.reference || 'sys_user', readonly: true } as DetailViewField; + }; + const fields: DetailViewField[] = []; + if (createdBy) fields.push(actorField(AUDIT_FIELDS.createdBy, t('detail.createdBy'))); + if (createdAt) fields.push({ name: AUDIT_FIELDS.createdAt, label: t('detail.createdTime', { defaultValue: 'Created on' }), type: 'datetime', readonly: true } as DetailViewField); + if (hasUpdated && updatedBy) fields.push(actorField(AUDIT_FIELDS.updatedBy, t('detail.updatedBy'))); + if (hasUpdated && updatedAt) fields.push({ name: AUDIT_FIELDS.updatedAt, label: t('detail.updatedTime', { defaultValue: 'Updated on' }), type: 'datetime', readonly: true } as DetailViewField); + if (owner) fields.push(actorField(OWNER_FIELD, t('detail.owner', { defaultValue: 'Owner' }))); + if (recordId) fields.push({ name: 'id', label: t('detail.recordNumber', { defaultValue: 'Record ID' }), type: 'text', readonly: true } as DetailViewField); + // Its rows are not the body's: they report no drawn field, so the owner + // rule above reads the body alone. No object name, so each row reads the + // label given here, and no row offers edit. + return ( + +
+ +
+
+ ); + } + return (
= ({ const ctx = useRecordContext(); const bodyTableIds = React.useMemo(() => new Set(relatedListIdsIn(columns.details)), [columns.details]); const [bodyFields] = React.useState(createRecordBodyFields); + // objectstack#36147 — the field area is one list: its groups fold every + // empty row into the list's last row, shown or not by the reader's one + // per-object choice (objectstack#25883), or this view's own without a store. + const [emptyFields] = React.useState(createEmptyFieldTally); + const recordPagePreferences = useRecordPagePreferences(); + const preferenceObject = typeof ctx?.objectName === 'string' && ctx.objectName ? ctx.objectName : undefined; + const [localShowEmpty, setLocalShowEmpty] = React.useState(false); + const showEmpty = + recordPagePreferences && preferenceObject + ? recordPagePreferences.get(preferenceObject).showEmptyFields === true + : localShowEmpty; + const fieldList = React.useMemo( + () => ({ + showEmpty, + toggleShowEmpty: () => { + if (recordPagePreferences && preferenceObject) { + recordPagePreferences.update(preferenceObject, { showEmptyFields: !showEmpty }); + } else { + setLocalShowEmpty((shown) => !shown); + } + }, + emptyFields, + }), + [showEmpty, recordPagePreferences, preferenceObject, emptyFields], + ); const hasTimeline = columns.timeline.length > 0; const approvalsNode = columns.related.find((node) => node?.type === 'record:approvals'); @@ -564,6 +591,11 @@ export const RecordPageColumns: React.FC = ({ const contentWidth = useContentWidth(contentEl); const pinned = recordPagePinsDetails(contentWidth, columns, fullPage) && otherTabs.length > 0; const pinnedHeight = usePinnedHeight(pinned ? gridEl : null, frameEl); + // objectstack#36147 — the field area is one column wherever it is drawn + // beside other tabs or as one of them: a drawer, a phone, a narrow page and + // the pinned left column. Only a full page whose details are its only face + // (no other tab, objectstack#35890 item 4) keeps laying them out by width. + const detailsFillPage = fullPage && otherTabs.length === 0 && resolved.hidden.length === 0; // The open tab: the address's when it names one this page has; pinned, the // first of the row otherwise (it is implied, never written, until the page @@ -676,6 +708,7 @@ export const RecordPageColumns: React.FC = ({ )} {drawDetailsNodes(columns.details)} {footer} + ); @@ -745,7 +778,8 @@ export const RecordPageColumns: React.FC = ({ - + +
= ({
+ diff --git a/ui/packages/plugin-detail/src/__tests__/DetailSection.fieldList-36147.test.tsx b/ui/packages/plugin-detail/src/__tests__/DetailSection.fieldList-36147.test.tsx new file mode 100644 index 00000000000..5cde54efa4a --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/DetailSection.fieldList-36147.test.tsx @@ -0,0 +1,296 @@ +/** + * 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#36147 — the record page's field area is one list, drawn the + * same in the side preview, on a phone and in the wide page's pinned left + * column: one field a row (label left, value right, a hairline between rows), + * a group's title left and its chevron at the row's right end (down folded, + * up open), no pencil beside a field (a click on an editable value edits it, + * a click on a read-only one does nothing), and every empty row folded into + * the list's one last row. + * + * Drawn here as the laid-out record page draws it: the default record page's + * frameless face (`DefaultRecordPageContext`), the column cap of 1 and the + * page's field list (`RecordFieldListContext`). + */ +import * as React from 'react'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import type { DetailViewSection } from '@object-ui/types'; +import { DetailSection } from '../DetailSection'; +import { DefaultRecordPageContext, DetailsColumnCapContext } from '../defaultRecordPage'; +import { createEmptyFieldTally, RecordFieldListContext, type RecordFieldList } from '../recordFieldList'; +import { EmptyFieldsRow } from '../EmptySectionsFold'; + +const objectSchema = { + fields: { + name: { type: 'text', label: 'Name' }, + amount: { type: 'currency', label: 'Amount' }, + code: { type: 'auto_number', label: 'Code' }, + note: { type: 'text', label: 'Note' }, + phone: { type: 'text', label: 'Phone' }, + website: { type: 'url', label: 'Website' }, + }, +}; + +const section = { + title: 'Overview', + fields: [ + { name: 'name', label: 'Name' }, + { name: 'amount', label: 'Amount' }, + { name: 'code', label: 'Code' }, + { name: 'note', label: 'Note' }, + { name: 'phone', label: 'Phone' }, + { name: 'website', label: 'Website' }, + ], +} as unknown as DetailViewSection; + +const data = { name: 'Atlas deal', amount: 174000, code: 'D-0004', note: null, phone: '', website: 'https://example.com' }; + +function makeList(showEmpty = false): RecordFieldList { + return { showEmpty, toggleShowEmpty: vi.fn(), emptyFields: createEmptyFieldTally() }; +} + +function Page({ list, cap = 1, children }: { list: RecordFieldList | null; cap?: 1 | 3; children: React.ReactNode }) { + return ( + + + {children} + + + ); +} + +const rows = (container: HTMLElement) => Array.from(container.querySelectorAll('[data-detail-field-row]')); +const rowOf = (label: string) => screen.getByText(label, { exact: true }).closest('[data-detail-field-row]') as HTMLElement; + +let innerWidth: number; +beforeEach(() => { + innerWidth = window.innerWidth; + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 }); +}); +afterEach(() => { + cleanup(); + Object.defineProperty(window, 'innerWidth', { configurable: true, value: innerWidth }); +}); + +describe('the field list: one field a row at any width (objectstack#36147 items 1–2)', () => { + it('under the cap of 1 the group draws one column of label-left rows, a hairline between them', () => { + const { container } = render( + + + , + ); + expect(container.querySelector('[data-detail-section-list]')).not.toBeNull(); + const grid = container.querySelector('[data-detail-section-list] .grid') as HTMLElement; + expect(grid.className.split(/\s+/)).toContain('grid-cols-1'); + expect(grid.className).not.toMatch(/grid-cols-2|grid-cols-3/); + for (const row of rows(container)) { + expect(row.className).toContain('border-b'); + expect(row.querySelector('[data-detail-field-label]')).not.toBeNull(); + } + }); + + it('on a phone the rows are the same rows: no grouped-inset face of its own', () => { + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 375 }); + const { container } = render( + + + , + ); + expect(rows(container).length).toBeGreaterThan(0); + expect(container.querySelector('.divide-y')).toBeNull(); + expect(rowOf('Name').querySelector('[data-detail-field-label]')).not.toBeNull(); + }); + + it('a full page whose details are its only face keeps laying a group out by width (cap 3)', () => { + const { container } = render( + + + , + ); + expect(container.querySelector('[data-detail-section-list]')).toBeNull(); + expect(rows(container)[0].className).not.toContain('border-b'); + }); +}); + +describe('a group: title left, chevron at the right end, down folded and up open (objectstack#36147 item 3)', () => { + it('the whole title row toggles, and the chevron turns', () => { + const { container } = render( + + + , + ); + const toggle = screen.getByRole('button', { name: 'Overview' }); + expect(toggle.getAttribute('aria-expanded')).toBe('true'); + expect(toggle.lastElementChild?.getAttribute('class')).toContain('lucide-chevron-up'); + fireEvent.click(toggle); + expect(toggle.getAttribute('aria-expanded')).toBe('false'); + expect(toggle.lastElementChild?.getAttribute('class')).toContain('lucide-chevron-down'); + expect(rows(container)).toHaveLength(0); + }); +}); + +describe('no pencil: a click on an editable value edits it (objectstack#36147 item 7)', () => { + it('a single click on an editable value enters edit; a read-only value takes no click', () => { + const onEnter = vi.fn(); + render( + + + , + ); + fireEvent.click(screen.getByText('Atlas deal')); + expect(onEnter).toHaveBeenCalledWith('name'); + onEnter.mockClear(); + fireEvent.click(screen.getByText('D-0004')); + expect(onEnter).not.toHaveBeenCalled(); + // A read-only row is not a copy button any more. + expect(rowOf('Code').querySelector('[role="button"]')).toBeNull(); + }); + + it('the pencil is not drawn beside a field: it stays only as the keyboard’s way in', () => { + render( + + + , + ); + const pencil = rowOf('Name').querySelector('button') as HTMLButtonElement; + expect(pencil).not.toBeNull(); + expect(pencil.className.split(/\s+/)).toContain('sr-only'); + expect(pencil.className).not.toContain('pointer-coarse:opacity-100'); + // It names the gesture that works here: a click, not a double-click. + expect(pencil.getAttribute('aria-label')).toBe('Click to edit'); + }); + + it('a touch screen draws no copy icon on a read-only value (ruling 1): a tap would reveal it through :hover', () => { + render( + + + , + ); + const copy = rowOf('Code').querySelector('[data-detail-copy]') as HTMLButtonElement; + expect(copy).not.toBeNull(); + expect(copy.className.split(/\s+/)).toContain('pointer-coarse:hidden'); + }); + + it('control: outside the field list the copy icon and the double-click hint are as before', () => { + const { container } = render( + , + ); + const copies = Array.from(container.querySelectorAll('[data-detail-copy]')); + expect(copies.length).toBeGreaterThan(0); + for (const copy of copies) expect(copy.className).not.toContain('pointer-coarse:hidden'); + expect(container.querySelector('button[aria-label="Double-click to edit"]')).not.toBeNull(); + expect(container.querySelector('button[aria-label="Click to edit"]')).toBeNull(); + }); + + it('a click on a link inside an editable value is the link’s, not the row’s', () => { + const onEnter = vi.fn(); + render( + + + , + ); + const link = rowOf('Website').querySelector('a') as HTMLAnchorElement; + expect(link).not.toBeNull(); + link.addEventListener('click', (e) => e.preventDefault()); + fireEvent.click(link); + expect(onEnter).not.toHaveBeenCalled(); + }); +}); + +describe('empty fields fold into the list’s one last row (objectstack#36147 item 5)', () => { + it('a group hides its empty rows, draws no toggle of its own, and reports them to the list', () => { + const list = makeList(); + const { container } = render( + + + + , + ); + expect(screen.queryByText('Note')).toBeNull(); + expect(screen.queryByText('Phone')).toBeNull(); + expect(list.emptyFields.getTotal()).toBe(2); + const row = container.querySelector('[data-empty-fields-row]') as HTMLElement; + expect(row.getAttribute('data-empty-fields-count')).toBe('2'); + expect(row.querySelectorAll('button')).toHaveLength(1); + // The section draws no toggle of its own: the list's row is the only one. + expect(container.querySelectorAll('button[aria-expanded]')).toHaveLength(1); + fireEvent.click(row.querySelector('button')!); + expect(list.toggleShowEmpty).toHaveBeenCalledTimes(1); + }); + + it('shown, the empty rows return in place and the row offers to hide them', () => { + const list = makeList(true); + const { container } = render( + + + + , + ); + expect(screen.getByText('Note')).toBeTruthy(); + expect(screen.getByText('Phone')).toBeTruthy(); + const button = container.querySelector('[data-empty-fields-row] button') as HTMLButtonElement; + expect(button.getAttribute('aria-expanded')).toBe('true'); + }); + + it('a group with only empty rows draws nothing until they are shown; the list still counts them', () => { + const list = makeList(); + const empty = { title: 'Address', fields: [{ name: 'note', label: 'Note' }, { name: 'phone', label: 'Phone' }] } as unknown as DetailViewSection; + const { container, rerender } = render( + + + , + ); + expect(container.querySelector('section')).toBeNull(); + expect(screen.queryByText('Address')).toBeNull(); + expect(list.emptyFields.getTotal()).toBe(2); + rerender( + + + , + ); + expect(screen.getByText('Address')).toBeTruthy(); + }); + + it('an authored all-empty hide is not the reader’s to undo, and is not counted', () => { + const list = makeList(true); + const hidden = { title: 'Hidden', hideEmpty: true, fields: [{ name: 'note', label: 'Note' }] } as unknown as DetailViewSection; + render( + + + , + ); + expect(screen.queryByText('Hidden')).toBeNull(); + expect(list.emptyFields.getTotal()).toBe(0); + }); + + it('a group leaving the list withdraws its count', () => { + const list = makeList(); + const { unmount } = render( + + + , + ); + expect(list.emptyFields.getTotal()).toBe(2); + act(() => unmount()); + expect(list.emptyFields.getTotal()).toBe(0); + }); + + it('outside the laid-out page a group keeps its own toggle', () => { + const { container } = render( + + + , + ); + const toggles = Array.from(container.querySelectorAll('section button')).filter((b) => /2/.test(b.textContent ?? '')); + expect(toggles).toHaveLength(1); + expect(container.querySelector('[data-empty-fields-row]')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordMetaFooter.systemInfo-36147.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordMetaFooter.systemInfo-36147.test.tsx new file mode 100644 index 00000000000..19a6e81a819 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RecordMetaFooter.systemInfo-36147.test.tsx @@ -0,0 +1,90 @@ +/** + * 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#36147 item 6 — in the record page's field list the record's + * provenance is its last group, 「系统信息」, folded until opened: created by, + * created on, updated by, updated on, the owner when the body does not draw + * it, and the record id, one field a row like every other group. It replaces + * the one-line meta footer there (objectui#12307's line); outside the field + * list the line is unchanged. + */ + +import React from 'react'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { render, cleanup, fireEvent, screen } from '@testing-library/react'; +import { RecordMetaFooter } from '../RecordMetaFooter'; +import { DefaultRecordPageContext, DetailsColumnCapContext } from '../defaultRecordPage'; +import { createEmptyFieldTally, RecordFieldListContext } from '../recordFieldList'; + +afterEach(cleanup); + +const data = { + id: 'C-1', + created_at: '2026-10-16T08:00:00Z', + created_by: 'Ada Admin', + updated_at: '2026-11-02T09:30:00Z', + updated_by: 'Bo Builder', + owner_id: 'Cy Owner', +}; +const contact = { name: 'contact', fields: { name: { type: 'text', label: 'Name' } } }; + +const inFieldList = (node: React.ReactNode) => ( + + + + {node} + + + +); + +const rowLabels = (container: HTMLElement) => + Array.from(container.querySelectorAll('[data-detail-field-label]')).map((el) => el.textContent); + +describe('「系统信息」: the provenance as the field list’s last group (objectstack#36147 item 6)', () => { + it('is one folded group, opened by its title row, holding one row per fact', () => { + const { container } = render(inFieldList()); + expect(container.querySelector('[data-record-system-info]')).not.toBeNull(); + // Not the one-line footer. + expect(container.querySelector('[data-record-meta-entry]')).toBeNull(); + const toggle = screen.getByRole('button', { name: 'System information' }); + expect(toggle.getAttribute('aria-expanded')).toBe('false'); + expect(rowLabels(container)).toEqual([]); + fireEvent.click(toggle); + expect(toggle.getAttribute('aria-expanded')).toBe('true'); + expect(rowLabels(container)).toEqual(['Created by', 'Created on', 'Updated by', 'Updated on', 'Owner', 'Record ID']); + expect(screen.getByText('C-1')).toBeTruthy(); + }); + + it('no row offers edit, and none reports a field the body draws', () => { + const { container } = render(inFieldList()); + fireEvent.click(screen.getByRole('button', { name: 'System information' })); + for (const row of Array.from(container.querySelectorAll('[data-detail-field-row]'))) { + expect(row.querySelector('[aria-label="Double-click to edit"], [aria-label="Click to edit"]')).toBeNull(); + } + }); + + it('a record never updated after it was made has no updated rows', () => { + const fresh = { ...data, updated_at: data.created_at, updated_by: data.created_by }; + const { container } = render(inFieldList()); + fireEvent.click(screen.getByRole('button', { name: 'System information' })); + expect(rowLabels(container)).toEqual(['Created by', 'Created on', 'Owner', 'Record ID']); + }); + + it('control: outside the field list the one-line footer is unchanged', () => { + const { container } = render( + + + , + ); + expect(container.querySelector('[data-record-system-info]')).toBeNull(); + expect(container.querySelectorAll('[data-record-meta-entry]').length).toBeGreaterThan(0); + expect(container.querySelector('[data-record-meta-id]')!.textContent).toBe('C-1'); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx index b986189abb7..02bcf25b384 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx @@ -53,6 +53,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { RecordPageColumns } from '../RecordPageColumns'; +import { useReportEmptyFields } from '../recordFieldList'; import { buildDefaultPageColumns } from '../synth/recordPageColumns'; import { buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; import { DetailView } from '../DetailView'; @@ -100,8 +101,8 @@ describe('RecordPageColumns — no right rail at any width (objectstack#35890 re expect(container.querySelector('[data-record-summary-card]')).toBeNull(); expect(nodesIn(column(container, 'details'))).toEqual(['record:details']); expect(column(container, 'details')!.lastElementChild?.getAttribute('data-testid')).toBe('meta-footer'); - // The details alone take the row: a section's own width decides, up to three. - expect(column(container, 'details')!.querySelector('[data-node="record:details"]')!.getAttribute('data-cap')).toBe('3'); + // A drawer or pane (no `fullPage`): one field a row (objectstack#36147). + expect(column(container, 'details')!.querySelector('[data-node="record:details"]')!.getAttribute('data-cap')).toBe('1'); }); } @@ -428,3 +429,84 @@ describe('RecordPageColumns — the approval band is drawn once per page (object expect(screen.getAllByText('In approval · editable')).toHaveLength(1); }); }); + +/** + * objectstack#36147 — the field area is one list wherever it sits beside other + * tabs or is one of them: the drawer, the phone, the narrow page and the + * pinned left column draw it one field a row. Only a full page whose details + * are its only face (objectstack#35890 item 4) lays them out by width. The + * list ends in one row folding every empty field of its groups. + */ +describe('RecordPageColumns — the field area is one list (objectstack#36147)', () => { + beforeEach(() => RelatedCountStore._reset()); + const find = vi.fn(async () => ({ data: [], total: 0 })); + let draws = 0; + const drawPage = (cols: typeof columns, extra: Record = {}) => + render( + ({ fields: {} })) } as any} + > + + , + ); + const capOf = (container: HTMLElement) => + container.querySelector('[data-record-column="details"] [data-node="record:details"]')?.getAttribute('data-cap'); + + it('one column in a drawer at any width, on a narrow page with tabs, and pinned', () => { + harness.width = 1600; + const drawer = drawPage(columns, { fullPage: false }); + expect(capOf(drawer.container)).toBe('1'); + drawer.unmount(); + harness.width = 600; + const narrow = drawPage(columns, { fullPage: true }); + expect(narrow.container.querySelector('[data-record-page-pinned]')).toBeNull(); + expect(capOf(narrow.container)).toBe('1'); + narrow.unmount(); + harness.width = 1184; + const pinned = drawPage(columns, { fullPage: true }); + expect(pinned.container.querySelector('[data-record-page-pinned]')).not.toBeNull(); + expect(capOf(pinned.container)).toBe('1'); + }); + + it('a full page whose details are its only face keeps laying them out by width', () => { + const bare = buildDefaultPageColumns(buildDefaultPageSchema({ name: 'thing', fields: {} }, { hideDiscussion: true }))!; + harness.width = 1600; + const { container } = drawPage(bare, { fullPage: true }); + expect(capOf(container)).toBe('3'); + }); + + it('the details end in one row folding every empty field the groups report, after the footer', () => { + const Reporter = ({ count }: { count: number }) => { + useReportEmptyFields(count); + return null; + }; + harness.width = 600; + const { container } = drawPage(columns, { + footer: ( + <> + + +

meta

+ + ), + }); + const details = column(container, 'details')!; + const row = details.lastElementChild as HTMLElement; + expect(row.hasAttribute('data-empty-fields-row')).toBe(true); + expect(row.getAttribute('data-empty-fields-count')).toBe('5'); + expect(row.previousElementSibling?.getAttribute('data-testid')).toBe('meta-footer'); + const button = within(row).getByRole('button'); + expect(button.getAttribute('aria-expanded')).toBe('false'); + expect(button.textContent).toMatch(/5/); + fireEvent.click(button); + expect(within(column(container, 'details')!.lastElementChild as HTMLElement).getByRole('button').getAttribute('aria-expanded')).toBe('true'); + }); + + it('no empty field, no row', () => { + harness.width = 600; + const { container } = drawPage(columns, { footer:

meta

}); + expect(container.querySelector('[data-empty-fields-row]')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/defaultRecordPage.ts b/ui/packages/plugin-detail/src/defaultRecordPage.ts index 7844fbf6912..a881ff6276c 100644 --- a/ui/packages/plugin-detail/src/defaultRecordPage.ts +++ b/ui/packages/plugin-detail/src/defaultRecordPage.ts @@ -141,10 +141,13 @@ export function useApprovalBandOnce(): { draws: boolean; mark: React.ReactNode } /** * The most columns a frameless detail section may take on the page being - * drawn: the record page's layout sets 1 while the details are pinned to its - * left column (objectstack#35890: one field a row, a long text the full width) - * and leaves 3 otherwise, where the section's own container width decides. - * 3 anywhere else. + * drawn: the record page's layout sets 1 wherever the details sit beside other + * tabs or are one of them — a drawer, a phone, a narrow page, the pinned left + * column (objectstack#36147: one field a row, label left and value right, at + * any width) — and leaves 3 only on a full page whose details are its only + * face, where the section's own container width decides. 3 anywhere else. + * 1 is also the field list face: `DetailSection` draws its rows one under the + * other with a hairline between them. */ export const DetailsColumnCapContext = React.createContext<1 | 2 | 3>(3); diff --git a/ui/packages/plugin-detail/src/recordFieldList.ts b/ui/packages/plugin-detail/src/recordFieldList.ts new file mode 100644 index 00000000000..141162bf85a --- /dev/null +++ b/ui/packages/plugin-detail/src/recordFieldList.ts @@ -0,0 +1,115 @@ +/** + * 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. + */ + +import * as React from 'react'; + +/** + * The record page's field area as ONE list (objectstack#36147): the side + * preview, the phone's 「详情」 tab and the wide page's pinned left column all + * draw the record's fields through `DetailSection`'s frameless face, and the + * laid-out page (`RecordPageColumns`) mounts this context around them. + * + * Under it the field area folds every empty field of every group into ONE + * row at the end of the list (「显示 N 个空字段」) instead of a toggle per + * group: each section hides its empty rows and reports how many it hid, the + * list's last row reads the total and reveals them all. The reader's choice + * is the one per-object record-page preference `showEmptyFields` + * (objectstack#25883), so it holds for the next record of the object. + * + * Module-internal on purpose, the way `RecordBodyFieldsContext` is: not in + * the package barrel, and neither a prop nor a schema key. Outside it a + * section keeps its own per-group toggle. + */ +export interface RecordFieldList { + /** Whether the reader asked to see the empty fields. */ + showEmpty: boolean; + /** Flip `showEmpty`. */ + toggleShowEmpty: () => void; + /** The tally of empty rows the list's sections hold. */ + emptyFields: EmptyFieldTally; +} + +/** How many empty rows the sections of one list hold, summed. */ +export interface EmptyFieldTally { + getTotal: () => number; + subscribe: (listener: () => void) => () => void; + /** Report one section's empty rows; `0` withdraws it. */ + report: (sectionId: string, count: number) => void; + withdraw: (sectionId: string) => void; +} + +export function createEmptyFieldTally(): EmptyFieldTally { + const bySection = new Map(); + const listeners = new Set<() => void>(); + let total = 0; + const recompute = () => { + let next = 0; + for (const count of bySection.values()) next += count; + if (next === total) return; + total = next; + for (const listener of Array.from(listeners)) listener(); + }; + return { + getTotal: () => total, + subscribe(listener) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + report(sectionId, count) { + if (count <= 0) { + if (bySection.delete(sectionId)) recompute(); + return; + } + bySection.set(sectionId, count); + recompute(); + }, + withdraw(sectionId) { + if (bySection.delete(sectionId)) recompute(); + }, + }; +} + +export const RecordFieldListContext = React.createContext(null); + +/** The field list a section is drawn in, or `null` outside the laid-out record page. */ +export function useRecordFieldList(): RecordFieldList | null { + return React.useContext(RecordFieldListContext); +} + +const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect; + +/** + * Report the empty rows a section holds, for as long as it holds them. A + * layout effect, so the list's last row has its count before the page paints. + * Nothing is reported outside a field list. + */ +export function useReportEmptyFields(count: number): void { + const list = React.useContext(RecordFieldListContext); + const sectionId = React.useId(); + useIsomorphicLayoutEffect(() => { + if (!list) return undefined; + list.emptyFields.report(sectionId, count); + return () => list.emptyFields.withdraw(sectionId); + }, [list, sectionId, count]); +} + +const NO_SUBSCRIPTION = () => () => {}; +const NO_TOTAL = () => 0; + +/** How many empty rows the list's sections hold; `0` outside a field list. */ +export function useEmptyFieldTotal(): number { + const list = React.useContext(RecordFieldListContext); + const tally = list?.emptyFields; + return React.useSyncExternalStore( + tally ? tally.subscribe : NO_SUBSCRIPTION, + tally ? tally.getTotal : NO_TOTAL, + tally ? tally.getTotal : NO_TOTAL, + ); +}