diff --git a/.changeset/36149-side-preview-tighten.md b/.changeset/36149-side-preview-tighten.md new file mode 100644 index 00000000000..233b6506dbb --- /dev/null +++ b/.changeset/36149-side-preview-tighten.md @@ -0,0 +1,18 @@ +--- +'@object-ui/components': patch +'@object-ui/plugin-grid': patch +'@object-ui/plugin-detail': patch +'@object-ui/app-shell': patch +--- + +feat(record-page): the side preview opens 460 wide, puts the record's name first with one labelled action, and lists a child tab one row per record + +Clause-②: yes (widening) — new optional members only: `RecordHeaderBar.preview` and `PageHeaderActionsProps.preview` on `@object-ui/components`, `ObjectGridComponentProps.cardFace` on `@object-ui/plugin-grid`; nothing removed or renamed +Metadata-protocol: none + +The record preview that opens beside a list (and a record page's drawer level) is now a narrow pane: + +- **Width.** It opens 460 px wide (at most 92% of the window). Its left edge drags it from 380 to 900 px. The dragged width is remembered in the browser under one key for every object's preview, not per object. A drawer whose `navigation` authors its width (`navigation.size` other than `auto`, or a `navigation.width`, pixel or percent) does not use that key. The list's preview reads the view's `navigation`, then the object's; a record page's drawer reads only its root record's object's `navigation`. Such a drawer keeps the object's per-object key (`recordOverlayWidthStorageKey`, unchanged), which it shares with that object's calendar, gantt, kanban, tree and grid overlays and a resizable `RecordDetailDrawer`, and opens at the authored width until a width is dragged in that drawer or one of those overlays. For an object that authors no size or width, the console's preview no longer shares a width with that object's calendar, gantt, kanban, tree or grid overlay or its `RecordDetailDrawer`. The width and its key belong to the drawer's root and stay with it: child levels keep the root's width, and in the list a record a lookup chip opens as the root takes the list's width and key (the list object's, not the opened record's). On a record page, a drawer closed and next opened on another object's record opens at that object's width, not the width dragged for the previous one. +- **Header.** The record's name comes first. The row shows at most one labelled action, the page's primary. The host's Edit and every other action go into the `⋯` in their usual order. The primary folds into the `⋯` too while the name would be cut below 16 characters' width. The copy-id icon after the name is gone, and 「Copy record ID」 is in the `⋯` instead. The full name is the name's tooltip. An approval's approve / reject levers and the record page's edit state (Cancel, Save) are drawn as before. A page's own header is unchanged. +- **`@object-ui/components`: every resizable drawer's range.** The range lives in `NavigationOverlay`, so it applies to every drawer opened with a `storageKey`: the calendar, gantt, kanban, tree and grid overlays, a resizable `RecordDetailDrawer`, and the console's preview. The drag range was 360 px to 60% of the window; it is now 380 to 900 px. On a 1920 px window the widest drag drops from 1152 to 900 px. On a 1024 px window a dragged or remembered width can now reach 900 px, where 60% of the window (614 px) capped it before; the drawer still never draws wider than the window less 1rem. A remembered width under 380 px is no longer used: the drawer opens at its host's width. A drawer whose `storageKey` changes while it stays mounted now drops the previous key's width when the new key remembers none, and opens at its host's width. +- **Child tabs.** A child list's tab draws one row per record (its title, one summary line and its status chip), the phone's card rows, instead of a table cut off at the pane's edge. `ObjectGrid` takes a new host prop, `cardFace`, that draws those rows at any window width. diff --git a/content/docs/frontend/plugins/plugin-view.mdx b/content/docs/frontend/plugins/plugin-view.mdx index ffd6dcc3d83..9d9384547dc 100644 --- a/content/docs/frontend/plugins/plugin-view.mdx +++ b/content/docs/frontend/plugins/plugin-view.mdx @@ -508,13 +508,29 @@ ignore a modifier click too. In the Console's object pages, a record that opens in the drawer opens in a drawer **over the list**, and the list keeps its full width. The drawer is -720 px wide, and the reader can drag its edge from 360 px to 60% of the -viewport. It draws no dimming overlay and is non-modal, so the list behind it -stays readable and clickable: +460 px wide, and the reader can drag its edge from 380 px to 900 px. The +dragged width is remembered in the browser and applies to every object's +drawer, except one whose `navigation` authors a `size` (other than `auto`) or a +`width` (pixel or percent). The list's drawer reads the view's `navigation`, +then the object's; a record page's drawer reads its root record's object's. +Such a drawer keeps that object's own remembered width, shared with its +calendar, gantt, kanban, tree and grid overlays and a resizable +`RecordDetailDrawer`: it opens at the authored width until a width is dragged +in it or in one of them. The width belongs to the drawer's root. A child level +keeps the root's width, and in the list a record a lookup chip opens as the +root takes the list's width and remembered width, not those of the opened +record's object. The drawer draws no dimming overlay and is non-modal, so the +list behind it stays readable and clickable: - the open record's row is highlighted and follows the drawer's ↑ ↓; - clicking another row swaps the record. +The drawer's header puts the record's name first. It draws at most one +labelled action, the page's primary, and only while the name keeps room for +about 16 characters. There is no Edit button and no copy-id icon: Edit, Copy +record ID and every other action are in the header's `⋯`. A child list's tab +in the drawer lists one row per record (its title and one summary line). + Readers who prefer the full page choose it in the list's Display menu (Open records: Drawer or Full page). That choice is the reader's own, stored in the browser, never metadata. diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index b13546f70b9..4da56724d67 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -1728,7 +1728,7 @@ ] }, "steps": [ - "open the Northwind account's full record page: from /_console/apps/com.example.showcase/showcase_account, clicking Northwind opens a ~720 px record DRAWER (the console's default record-open mode, ui/packages/app-shell/src/views/ObjectView.tsx), not the full page steps[1] reads — open it full page with the drawer's 'Open as full page' (↗), or load /_console/apps/com.example.showcase/showcase_account/record/ID directly", + "open the Northwind account's full record page: from /_console/apps/com.example.showcase/showcase_account, clicking Northwind opens a ~460 px record DRAWER (the console's default record-open mode, ui/packages/app-shell/src/views/ObjectView.tsx), not the full page steps[1] reads — open it full page with the drawer's 'Open as full page' (↗), or load /_console/apps/com.example.showcase/showcase_account/record/ID directly", "screenshot at 1440×900; enumerate the related lists. The page draws the record's tab row — Details (详情), one tab per related list in its order (an empty one muted, with no number), Attachments, Approvals (while a request exists), then Activity (动态) last with its count, the tabs that do not fit folded into its 'More N' (更多 N) dropdown (ui/packages/plugin-detail/src/RecordPageColumns.tsx, the tab row; ui/packages/plugin-detail/src/RecordTabRow.tsx; #35595), so a role=tab strip is expected: enumerate the lists from it (QA run #33861 read the earlier records-first row). The primary lists (relatedList: 'primary' — Invoices on showcase_invoice.account, Projects on showcase_project.account) are body tables among the 详情 tab's details and take no tab, and every non-primary child — Contacts among them — is a tab of its own whose face is the whole list with its pager (packages/spec/src/data/field.zod.ts relatedList: 'true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList)', and for 'primary': 'a body table: part of the record's main content'). With those tables among its details the account's full page never pins the details in a left column (ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPagePinsDetails, #35890): the same tab row at every width, and no right rail (retired, #35890)", "open Contacts' whole list: its tab opens it in place (?related=showcase_contact.account); capture the page-1 data request. An enlarged list whose block names no limit pages 25 rows (ui/packages/plugin-detail/src/RecordPageColumns.tsx, ENLARGED_PAGE_SIZE), so the pager reads 'Page 1 of 2' for Northwind's 26 contacts (QA run #27438)", "click next-page; capture the page-2 request; note the pager text ('Page 2 of 2', one row)", diff --git a/ui/packages/app-shell/src/layout/__tests__/consoleSidebarRail.width-27593.test.tsx b/ui/packages/app-shell/src/layout/__tests__/consoleSidebarRail.width-27593.test.tsx index 20de4b83616..ff38facf6d9 100644 --- a/ui/packages/app-shell/src/layout/__tests__/consoleSidebarRail.width-27593.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/consoleSidebarRail.width-27593.test.tsx @@ -7,15 +7,15 @@ * ruling on objectstack#36112 (7069868269) moved it to 1280 px and accepted * the cost. `CONSOLE_EXPANDED_SIDEBAR_WIDTH` restates the sidebar primitive's * `--sidebar-width` (fixed at 256, objectstack#36112 F2) and - * `RECORD_DRAWER_WIDTH` plugin-view's default drawer width, so this reads both - * off their owners and holds them equal, and the cost stated on the ruling is - * the one the code pays. + * `RECORD_DRAWER_WIDTH` the side preview's default width (objectstack#36149), + * so this reads both off their owners and holds them equal, and the cost the + * code pays is the one stated beside the threshold. */ import '@testing-library/jest-dom/vitest'; import { render } from '@testing-library/react'; import { SidebarProvider } from '@object-ui/components'; -import { overlayWidthFor } from '@object-ui/plugin-view'; +import { RECORD_PREVIEW_DEFAULT_WIDTH } from '../../views/recordDrawerContext'; import { describe, expect, it } from 'vitest'; import { CONSOLE_EXPANDED_SIDEBAR_WIDTH, @@ -56,10 +56,10 @@ describe('the console sidebar threshold (objectstack#27593, #29109, #36112)', () expect(CONSOLE_EXPANDED_SIDEBAR_WIDTH).toBe(256); }); - it('restates the drawer a list record opens in (plugin-view’s md bucket)', () => { - // `min(92vw, 720px)`: the px term is the drawer's width on any desktop window. - const match = /^min\(92vw, (\d+)px\)$/.exec(overlayWidthFor('md', {})); - expect(match, 'overlayWidthFor answers min(92vw, Npx)').not.toBeNull(); + it('restates the drawer a list record opens in (the side preview’s default, objectstack#36149)', () => { + // `min(92vw, 460px)`: the px term is the drawer's width on any desktop window. + const match = /^min\(92vw, (\d+)px\)$/.exec(RECORD_PREVIEW_DEFAULT_WIDTH); + expect(match, 'the default answers min(92vw, Npx)').not.toBeNull(); expect(Number(match![1])).toBe(RECORD_DRAWER_WIDTH); }); @@ -67,12 +67,12 @@ describe('the console sidebar threshold (objectstack#27593, #29109, #36112)', () expect(CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH).toBe(1280); }); - it('pays the cost the ruling accepted: at 1280 px the expanded sidebar leaves the list 304 px beside the drawer, the collapsed one 560', () => { + it('at 1280 px the expanded sidebar leaves the list 564 px beside the 460 px preview, the collapsed one 820: the cost the ruling accepted at 720 is gone', () => { const { expanded } = primitiveSidebarWidths(); - expect(listBesideDrawer(CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH, expanded)).toBe(304); - expect(listBesideDrawer(CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH, expanded)).toBeLessThan(LIST_MIN_COLUMNS_WIDTH); + expect(listBesideDrawer(CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH, expanded)).toBe(564); + expect(listBesideDrawer(CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH, expanded)).toBeGreaterThanOrEqual(LIST_MIN_COLUMNS_WIDTH); // Collapsed, the sidebar is hidden and takes no width (objectstack#35062). - expect(listBesideDrawer(CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH, 0)).toBe(560); + expect(listBesideDrawer(CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH, 0)).toBe(820); }); it('a 1440 px window’s expanded sidebar still leaves the list its columns beside the drawer', () => { diff --git a/ui/packages/app-shell/src/layout/consoleSidebarRail.ts b/ui/packages/app-shell/src/layout/consoleSidebarRail.ts index a8a20742c48..537b7e4a45d 100644 --- a/ui/packages/app-shell/src/layout/consoleSidebarRail.ts +++ b/ui/packages/app-shell/src/layout/consoleSidebarRail.ts @@ -62,12 +62,12 @@ import { export const CONSOLE_EXPANDED_SIDEBAR_WIDTH = 256; /** - * The record drawer's width in CSS pixels: a list record opens in the drawer - * at plugin-view's `md` overlay bucket, `overlayWidthFor('md', …)` = - * `min(92vw, 720px)` (objectstack#27545). `consoleSidebarRail.width-27593.test.tsx` + * The record drawer's width in CSS pixels: a list record opens in the side + * preview at `RECORD_PREVIEW_DEFAULT_WIDTH` = `min(92vw, 460px)` + * (objectstack#36149; 720 before). `consoleSidebarRail.width-27593.test.tsx` * reads that value and holds this equal to it. */ -export const RECORD_DRAWER_WIDTH = 720; +export const RECORD_DRAWER_WIDTH = 460; /** * The narrowest list that still draws its columns, in CSS pixels: the 440 px @@ -84,13 +84,15 @@ export const LIST_MIN_COLUMNS_WIDTH = 440; * wide and the narrow choice are kept on either side of it. * * Chosen, not derived. The record drawer beside the narrowest list that still - * draws its columns, next to an expanded sidebar, needs 440 + 720 + 256 = - * 1416 px, the threshold before; the ruling accepts the cost below that. A - * 1280 px window with the sidebar expanded leaves the list beside an open - * record drawer 1280 − 256 − 720 = 304 px (560 with the sidebar collapsed), - * and on 1280 to 1415 px with the sidebar expanded, opening the record page's - * comment panel returns its fields to the tab row; collapsing the sidebar - * gives the content the width back. The record page's own column tiers are + * draws its columns, next to an expanded sidebar, needed 440 + 720 + 256 = + * 1416 px when the drawer was 720, the threshold before; the ruling accepted + * the cost below that. Since the side preview opens at 460 + * (objectstack#36149), a 1280 px window with the sidebar expanded leaves the + * list beside it 1280 − 256 − 460 = 564 px (820 with the sidebar collapsed), + * so the cost is gone at the preview's default width; a reader who drags it + * wider pays it again. On 1280 to 1415 px with the sidebar expanded, opening + * the record page's comment panel returns its fields to the tab row; + * collapsing the sidebar gives the content the width back. The record page's own column tiers are * measured on the container it gets, so they follow either way. */ export const CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH = 1280; diff --git a/ui/packages/app-shell/src/views/ObjectView.recordOpenPath-35854.test.tsx b/ui/packages/app-shell/src/views/ObjectView.recordOpenPath-35854.test.tsx index 724b54b574f..7716a553e25 100644 --- a/ui/packages/app-shell/src/views/ObjectView.recordOpenPath-35854.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.recordOpenPath-35854.test.tsx @@ -264,3 +264,33 @@ describe('a list opens a record one way: the name opens the page, the icon besid }, ); }); + +/** + * objectstack#36149 — the list host hands its preview the width key the + * navigation resolved (`drawerWidthKey` → `widthKey`): the shared preview key + * for a view that authors no width, the object's own key for one that + * authors a size. Without that hand-over every preview reads the shared key. + */ +describe('the list preview remembers its width under the key its navigation resolves (objectstack#36149)', () => { + const SHARED = 'ov:drawer-width:record-preview'; + const paneWidth = () => + (document.querySelector('[data-record-drawer-card]') as HTMLElement | null)?.style.getPropertyValue('--ov-w').trim(); + afterEach(() => window.localStorage.clear()); + + it('a view that authors `size: xl` opens at its size, not at the shared remembered width', async () => { + window.localStorage.setItem(SHARED, '600'); + await openList(objectsWith({ size: 'xl' })); + fireEvent.click(panelIconOf('Alpha')); + await screen.findByRole('dialog', undefined, { timeout: 5000 }); + expect(paneWidth()).toMatch(/^min\(92vw, \d+px\)$/); + expect(paneWidth()).not.toBe('600px'); + }); + + it('CONTROL: a view that authors no width opens at the shared remembered width', async () => { + window.localStorage.setItem(SHARED, '600'); + await openList(objectsWith()); + fireEvent.click(panelIconOf('Alpha')); + await screen.findByRole('dialog', undefined, { timeout: 5000 }); + expect(paneWidth()).toBe('600px'); + }); +}); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 15211e22275..38522595f75 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -1116,7 +1116,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // objectstack#27058 — on a phone the record is always a page: a row tap // navigates to it, and no pane is mounted beside or over the list. const phone = usePhoneViewport(); - const { listRecordActions, navOverlay, handleDrawerClose, handleRowClick, handleOpenAsPage, handleOpenRowInPanel, handleOpenReferencedRecord, drawerRoot, drawerRestore, handleListRowsChange, handleListTotalChange, handleRootStep, listLabel } = useObjectViewRecordNavigation({ + const { listRecordActions, navOverlay, drawerWidthKey, handleDrawerClose, handleRowClick, handleOpenAsPage, handleOpenRowInPanel, handleOpenReferencedRecord, drawerRoot, drawerRestore, handleListRowsChange, handleListTotalChange, handleRootStep, listLabel } = useObjectViewRecordNavigation({ activeView, objectDef, objects, @@ -1704,6 +1704,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co }, expect(dataSource.findOne.mock.calls.some((call: unknown[]) => call[0] === level.objectName && call[1] === level.recordId)).toBe(true), ); return waitFor(() => { - const sheet = screen.getAllByRole('dialog').find((el) => within(el).queryByRole('button', { name: 'Edit' })); + const sheet = screen.getAllByRole('dialog').find((el) => within(el).queryByRole('button', { name: 'More actions' })); expect(sheet).toBeTruthy(); return sheet!; }, { timeout: 5000 }); } +/** + * The drawer's Edit: an entry of its header's `⋯` (objectstack#36149 — the + * side preview draws no Edit button). + */ +async function clickDrawerEdit(sheet: HTMLElement) { + fireEvent.pointerDown(within(sheet).getByRole('button', { name: 'More actions' }), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + const item = await screen.findByRole('menuitem', { name: 'Edit' }); + fireEvent.click(item); +} + beforeEach(() => { cleanup(); localStorage.clear(); @@ -215,7 +225,7 @@ describe('a drawer level’s Edit names the level’s object (objectstack#33111) it('the record page’s drawer: a child level’s Edit hands the child’s id and the child’s object', async () => { const { onEdit, dataSource } = mountRecordPage([TASK]); const sheet = await drawerShowing(dataSource, TASK); - fireEvent.click(within(sheet).getByRole('button', { name: 'Edit' })); + await clickDrawerEdit(sheet); expect(onEdit).toHaveBeenCalledTimes(1); expect(onEdit).toHaveBeenCalledWith({ id: TASK.recordId }, TASK.objectName); }); @@ -223,7 +233,7 @@ describe('a drawer level’s Edit names the level’s object (objectstack#33111) it('the list’s drawer: a child level’s Edit hands the child’s id and the child’s object', async () => { const { onEdit, dataSource } = mountListDrawer([LEAD, TASK]); const sheet = await drawerShowing(dataSource, TASK); - fireEvent.click(within(sheet).getByRole('button', { name: 'Edit' })); + await clickDrawerEdit(sheet); expect(onEdit).toHaveBeenCalledTimes(1); expect(onEdit).toHaveBeenCalledWith({ id: TASK.recordId }, TASK.objectName); }); @@ -239,7 +249,48 @@ describe('a drawer level’s Edit names the level’s object (objectstack#33111) it('CONTROL: the list drawer’s root level names the route’s object', async () => { const { onEdit, dataSource } = mountListDrawer(); const sheet = await drawerShowing(dataSource, LEAD); - fireEvent.click(within(sheet).getByRole('button', { name: 'Edit' })); + await clickDrawerEdit(sheet); expect(onEdit).toHaveBeenCalledWith({ id: LEAD.recordId }, LEAD.objectName); }); }); + +/** + * objectstack#36149 — the side preview's header (the list's drawer and the + * record page's): no Edit button and no copy-id icon after the name; Edit and + * 「Copy record ID」 are entries of its `⋯`. CONTROL: the record page's own + * header keeps both as they were. + */ +describe('the side preview’s header: Edit and the id’s copy are in its ⋯ (objectstack#36149)', () => { + it('the list’s drawer draws no Edit button and no copy-id icon; its ⋯ holds both, and the copy writes the id', async () => { + const writeText = vi.fn(async () => {}); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + const { dataSource } = mountListDrawer(); + const sheet = await drawerShowing(dataSource, LEAD); + expect(within(sheet).queryByRole('button', { name: 'Edit' })).toBeNull(); + expect(within(sheet).queryByRole('button', { name: 'Copy record ID' })).toBeNull(); + fireEvent.pointerDown(within(sheet).getByRole('button', { name: 'More actions' }), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + expect(await screen.findByRole('menuitem', { name: 'Edit' })).toBeTruthy(); + fireEvent.click(await screen.findByRole('menuitem', { name: 'Copy record ID' })); + await waitFor(() => expect(writeText).toHaveBeenCalledWith(LEAD.recordId)); + delete (navigator as { clipboard?: unknown }).clipboard; + }); + + it('the record page’s drawer: the same ⋯ entries on its level', async () => { + const { dataSource } = mountRecordPage([TASK]); + const sheet = await drawerShowing(dataSource, TASK); + expect(within(sheet).queryByRole('button', { name: 'Edit' })).toBeNull(); + fireEvent.pointerDown(within(sheet).getByRole('button', { name: 'More actions' }), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + expect(await screen.findByRole('menuitem', { name: 'Edit' })).toBeTruthy(); + expect(await screen.findByRole('menuitem', { name: 'Copy record ID' })).toBeTruthy(); + }); + + it('CONTROL: the record page’s own header keeps its Edit button and its copy-id icon, and no copy entry', async () => { + const { dataSource } = mountRecordPage(); + await waitFor(() => expect(dataSource.findOne).toHaveBeenCalled()); + expect(await screen.findByRole('button', { name: 'Edit' }, { timeout: 5000 })).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Copy record ID' })).toBeTruthy(); + fireEvent.pointerDown(screen.getByRole('button', { name: 'More actions' }), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + await screen.findByRole('menu'); + expect(screen.queryByRole('menuitem', { name: 'Copy record ID' })).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 809b659044f..2377a921ae5 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -5413,6 +5413,30 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri onClick: () => recordPane.openAsPage(), } as any); } + // objectstack#36149 — a side preview's header draws no copy-id icon after + // the name; the copy is this `⋯` entry instead. + if (embedded && paneHeaderBar?.preview && pureRecordId) { + items.push({ + name: 'sys_copy_record_id', + label: t('detail.copyRecordId', { defaultValue: 'Copy record ID' }), + icon: 'copy', + type: 'script', + locations: ['record_header'], + variant: 'outline', + order: 113, + component: 'action:menu', + onClick: async () => { + const label = t('detail.copyRecordId', { defaultValue: 'Copy record ID' }); + try { + await navigator.clipboard.writeText(String(pureRecordId)); + toast.success(t('detail.copied', { defaultValue: 'Copied!' })); + } catch (err: any) { + // A clipboard the page may not write (not focused, not https) says so. + toast.error(err?.message ? `${label}: ${err.message}` : label); + } + }, + } as any); + } if (affordances.delete) { items.push({ name: 'sys_delete', diff --git a/ui/packages/app-shell/src/views/__tests__/recordPreviewWidth-36149.test.tsx b/ui/packages/app-shell/src/views/__tests__/recordPreviewWidth-36149.test.tsx new file mode 100644 index 00000000000..1304b56f53f --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/recordPreviewWidth-36149.test.tsx @@ -0,0 +1,217 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36149 — one remembered width for the side preview of every + * object: a width the reader drags in one object's preview is the width the + * next preview opens at, whatever its object, on both hosts that draw it (the + * list's `ObjectViewRecordOverlay` and a record page's `RecordPageDrawerHost`). + * + * Control: an object that authors its drawer's width (a `navigation.size` + * other than `auto`, or a pixel `navigation.width`) never takes the shared + * width. It remembers only a width dragged in its own pane, under its own + * per-object key. + */ + +import * as React from 'react'; +import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; +import '@testing-library/jest-dom'; +import { recordOverlayWidthStorageKey } from '@object-ui/components'; + +vi.mock('../RecordDetailView.js', () => ({ + RecordDetailView: ({ objectNameOverride, recordIdOverride }: { objectNameOverride?: string; recordIdOverride?: string }) => ( +
{`${objectNameOverride}/${recordIdOverride}`}
+ ), +})); + +import { ObjectViewRecordOverlay } from '../objectViewRecordOverlay'; +import { RecordPageDrawerHost } from '../recordDrawerStack'; +import { RECORD_PREVIEW_WIDTH_KEY, recordPaneWidth, recordPreviewWidthKey, useRecordDrawer } from '../recordDrawerContext'; + +const OBJECTS = [ + { name: 'crm_lead', label: 'Lead' }, + { name: 'crm_task', label: 'Task' }, + { name: 'crm_contract', label: 'Contract', navigation: { width: 720 } }, + { name: 'crm_quote', label: 'Quote', navigation: { size: 'xl' } }, +]; + +beforeEach(() => window.localStorage.clear()); +afterEach(() => { + cleanup(); + window.localStorage.clear(); +}); + +const drawerWidth = () => + (document.querySelector('[data-record-drawer-card]') as HTMLElement | null)?.style.getPropertyValue('--ov-w').trim(); + +/** The list's preview of `objectName`'s record `recordId`. */ +function mountListPreview(objectName: string, recordId: string, widthKey?: string) { + return render( + + + } + handleDrawerClose={() => {}} + objectDef={OBJECTS.find((o) => o.name === objectName) as any} + handleOpenAsPage={(() => {}) as any} + drawerRoot={{ objectName, recordId }} + drawerRestore={undefined} + handleRootStep={() => {}} + dataSource={{} as any} + objects={OBJECTS as any} + onEdit={() => {}} + /> + } + /> + + , + ); +} + +/** Drag the open pane's edge so it is `px` wide (the pane is right-anchored at the window's edge). */ +function dragTo(px: number) { + const handle = screen.getByRole('separator'); + act(() => { + fireEvent.mouseDown(handle); + fireEvent.mouseMove(window, { clientX: window.innerWidth - px }); + fireEvent.mouseUp(window); + }); +} + +function OpenButton({ objectName, recordId }: { objectName: string; recordId: string }) { + const drawer = useRecordDrawer(); + return ( + + ); +} + +function RecordPage() { + const location = useLocation(); + const [, objectName, , recordId] = location.pathname.split('/').slice(2); + return ( +
{`${l.objectName}/${l.recordId}`}
} + > + + + +
+ ); +} + +function mountRecordPage() { + return render( + + + } /> + + , + ); +} + +describe('the side preview has one remembered width for every object (objectstack#36149)', () => { + it("a width dragged in one object's list preview is the width another object's list preview opens at", () => { + const first = mountListPreview('crm_lead', 'L-1'); + expect(drawerWidth()).toBe('min(92vw, 460px)'); + dragTo(640); + expect(drawerWidth()).toBe('640px'); + expect(window.localStorage.getItem(`ov:${RECORD_PREVIEW_WIDTH_KEY}`)).toBe('640'); + first.unmount(); + + mountListPreview('crm_task', 'T-1'); + expect(drawerWidth()).toBe('640px'); + }); + + it("a record page's drawer opens another object's record at the width dragged in a list preview", () => { + const first = mountListPreview('crm_lead', 'L-1'); + dragTo(600); + first.unmount(); + + mountRecordPage(); + fireEvent.click(screen.getByRole('button', { name: 'open crm_task' })); + expect(screen.getByTestId('record-body')).toHaveTextContent('crm_task/T-1'); + expect(drawerWidth()).toBe('600px'); + }); + + it("CONTROL: an object that authors its drawer's width opens at it, not at the shared width", () => { + window.localStorage.setItem(`ov:${RECORD_PREVIEW_WIDTH_KEY}`, '600'); + mountRecordPage(); + fireEvent.click(screen.getByRole('button', { name: 'open crm_contract' })); + expect(screen.getByTestId('record-body')).toHaveTextContent('crm_contract/K-1'); + expect(drawerWidth()).toBe('720px'); + // A drag in its own pane is remembered under its own key, never the shared one. + dragTo(500); + expect(window.localStorage.getItem(`ov:${recordOverlayWidthStorageKey('crm_contract')}`)).toBe('500'); + expect(window.localStorage.getItem(`ov:${RECORD_PREVIEW_WIDTH_KEY}`)).toBe('600'); + }); + + it('CONTROL: the list preview of an object whose view authors a size keeps its own key', () => { + window.localStorage.setItem(`ov:${RECORD_PREVIEW_WIDTH_KEY}`, '600'); + mountListPreview('crm_lead', 'L-1', recordPreviewWidthKey('crm_lead', { size: 'xl' })); + expect(drawerWidth()).toBe('min(92vw, 460px)'); + }); + + it('recordPreviewWidthKey: the shared key unless a size other than auto, or a width, is authored', () => { + expect(recordPreviewWidthKey('crm_lead', undefined)).toBe(RECORD_PREVIEW_WIDTH_KEY); + expect(recordPreviewWidthKey('crm_lead', {})).toBe(RECORD_PREVIEW_WIDTH_KEY); + expect(recordPreviewWidthKey('crm_lead', { size: 'auto' })).toBe(RECORD_PREVIEW_WIDTH_KEY); + expect(recordPreviewWidthKey('crm_lead', { size: 'xl' })).toBe(recordOverlayWidthStorageKey('crm_lead')); + expect(recordPreviewWidthKey('crm_lead', { width: 720 })).toBe(recordOverlayWidthStorageKey('crm_lead')); + }); + + it("one mounted record-page drawer: a task at the shared width, then a contract that authors 720 opens at 720", () => { + window.localStorage.setItem(`ov:${RECORD_PREVIEW_WIDTH_KEY}`, '600'); + mountRecordPage(); + fireEvent.click(screen.getByRole('button', { name: 'open crm_task' })); + expect(drawerWidth()).toBe('600px'); + fireEvent.keyDown(document.body, { key: 'Escape' }); + expect(screen.queryByTestId('record-body')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'open crm_contract' })); + expect(screen.getByTestId('record-body')).toHaveTextContent('crm_contract/K-1'); + expect(drawerWidth()).toBe('720px'); + }); + + it('one mounted record-page drawer, the reverse: a contract at its own dragged 500, then a task opens at the default', () => { + window.localStorage.setItem(`ov:${recordOverlayWidthStorageKey('crm_contract')}`, '500'); + mountRecordPage(); + fireEvent.click(screen.getByRole('button', { name: 'open crm_contract' })); + expect(drawerWidth()).toBe('500px'); + fireEvent.keyDown(document.body, { key: 'Escape' }); + expect(screen.queryByTestId('record-body')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'open crm_task' })); + expect(screen.getByTestId('record-body')).toHaveTextContent('crm_task/T-1'); + expect(drawerWidth()).toBe('min(92vw, 460px)'); + }); + + it("a record page's drawer opens an object that authors `size: 'xl'` at that size, as the list does", () => { + window.localStorage.setItem(`ov:${RECORD_PREVIEW_WIDTH_KEY}`, '600'); + mountRecordPage(); + fireEvent.click(screen.getByRole('button', { name: 'open crm_quote' })); + expect(screen.getByTestId('record-body')).toHaveTextContent('crm_quote/Q-1'); + const xl = recordPaneWidth({ size: 'xl' }, OBJECTS[3]); + expect(xl).toMatch(/^min\(92vw, \d+px\)$/); + expect(drawerWidth()).toBe(xl); + }); + + it('recordPaneWidth: an authored width as written, else the size bucket, else 460', () => { + expect(recordPaneWidth(undefined, {})).toBe('min(92vw, 460px)'); + expect(recordPaneWidth({ size: 'auto' }, {})).toBe('min(92vw, 460px)'); + expect(recordPaneWidth({ width: '50%' }, {})).toBe('50%'); + expect(recordPaneWidth({ width: 720, size: 'sm' }, {})).toBe(720); + expect(recordPaneWidth({ size: 'xl' }, {})).not.toBe('min(92vw, 460px)'); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectViewRecordNavigation.ts b/ui/packages/app-shell/src/views/objectViewRecordNavigation.ts index 98d53a1b446..783909a642f 100644 --- a/ui/packages/app-shell/src/views/objectViewRecordNavigation.ts +++ b/ui/packages/app-shell/src/views/objectViewRecordNavigation.ts @@ -46,7 +46,7 @@ import { useMemo, useCallback, useEffect, useRef, useState } from 'react'; import type { NavigateFunction, Location, SetURLSearchParams } from 'react-router-dom'; -import { deriveRecordSurface, overlayWidthFor } from '@object-ui/plugin-view/core'; +import { deriveRecordSurface } from '@object-ui/plugin-view/core'; import { useNavigationOverlay } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import type { ViewNavigationConfig } from '@object-ui/types'; @@ -55,6 +55,7 @@ import { RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.j import { viewTabLabel } from './viewTabLabel.js'; import { listRecordDetailUrl, listRecordActionsValue } from './objectViewRecordLinks.js'; import { RECORD_PAGE_PUSHED_STATE } from './recordPagePush.js'; +import { recordPaneWidth, recordPreviewWidthKey } from './recordDrawerContext.js'; import { servesRecordRead } from '../utils/recordReadServed.js'; import { expandedRecordPath, @@ -185,17 +186,6 @@ function splitRecordFormSearch(search: string): { form: string; origin: URLSearc return { form: form.toString(), origin }; } -type OverlaySizeBucket = 'sm' | 'md' | 'lg' | 'xl' | 'full'; - -/** - * The record pane's size bucket (objectstack#27545): `auto` — or no size — - * is `md` (720 px) whatever the object's field count; an authored bucket - * stands as authored. - */ -function recordPaneSize(size: 'auto' | OverlaySizeBucket | undefined): OverlaySizeBucket { - return !size || size === 'auto' ? 'md' : size; -} - export function useObjectViewRecordNavigation({ activeView, objectDef, @@ -261,19 +251,20 @@ export function useObjectViewRecordNavigation({ // view that declares one behaves as one that declares nothing. // The drawer's width still reads the authored `size` bucket (or the // deprecated pixel `width`, objectstack-ai/objectstack#2578): `auto` - // is the pane's 720 (objectstack#27545), clamped to the viewport. + // is the side preview's 460 (objectstack#36149), clamped to the viewport. // `openNewTab: true` stays live: the name opens the page in a new tab. return { mode: 'drawer', openNewTab: authored?.openNewTab, - width: authored?.width ?? overlayWidthFor( - recordPaneSize((authored as { size?: 'auto' | OverlaySizeBucket } | undefined)?.size), - objectDef, - ), + width: recordPaneWidth(authored, objectDef), }; }, [activeView?.navigation, objectDef, phone, recordServed] ); + // objectstack#36149 — where the drawer remembers a dragged width: the + // shared preview key, or this object's own key when the view or the + // object authors the drawer's width (`recordPreviewWidthKey`). + const drawerWidthKey = recordPreviewWidthKey(objectDef.name, phone ? undefined : activeView?.navigation ?? objectDef.navigation); const drawerRecordId = searchParams.get(RECORD_DRAWER_PARAM); // objectstack#36015 — the root's object when a lookup chip opened a record // of another object; `null` for the listed object's own rows. @@ -582,5 +573,5 @@ export function useObjectViewRecordNavigation({ navOverlay.close(); } }, [drawerRecordId, drawerForeignObject, phone, drawerRootServed]); - return { listRecordActions, navOverlay, handleDrawerClose, handleRowClick, handleOpenAsPage, handleOpenRowInPanel, handleOpenReferencedRecord, drawerRoot, drawerRestore, handleListRowsChange, handleListTotalChange, handleRootStep, listLabel }; + return { listRecordActions, navOverlay, drawerWidthKey, handleDrawerClose, handleRowClick, handleOpenAsPage, handleOpenRowInPanel, handleOpenReferencedRecord, drawerRoot, drawerRestore, handleListRowsChange, handleListTotalChange, handleRootStep, listLabel }; } diff --git a/ui/packages/app-shell/src/views/objectViewRecordOverlay.tsx b/ui/packages/app-shell/src/views/objectViewRecordOverlay.tsx index 2f852de3ad9..1b4b33ac6cb 100644 --- a/ui/packages/app-shell/src/views/objectViewRecordOverlay.tsx +++ b/ui/packages/app-shell/src/views/objectViewRecordOverlay.tsx @@ -21,6 +21,7 @@ import { lazy, Suspense, type ReactNode } from 'react'; import type { NavigationOverlayMode } from '@object-ui/components'; import { SkeletonDetail } from '../skeletons/index.js'; import { RecordStackDrawer, useRecordDrawerStack } from './recordDrawerStack.js'; +import { RECORD_PREVIEW_WIDTH_KEY } from './recordDrawerContext.js'; import type { useObjectViewRecordNavigation } from './objectViewRecordNavigation.js'; import type { ConsoleObjectViewProps } from './ObjectView.js'; @@ -33,6 +34,7 @@ const RecordDetailView = lazy(() => import('./RecordDetailView.js').then((m) => export function ObjectViewRecordOverlay({ navOverlay, mode, + widthKey = RECORD_PREVIEW_WIDTH_KEY, list, handleDrawerClose, objectDef, @@ -48,6 +50,11 @@ export function ObjectViewRecordOverlay({ navOverlay: RecordNavigation['navOverlay']; /** The object's resolved mode: `drawer` draws the record over the list. */ mode: NavigationOverlayMode; + /** + * Where the drawer remembers a dragged width (`recordPreviewWidthKey`, + * objectstack#36149). Absent: the side preview's shared key. + */ + widthKey?: string; /** The list, drawn whether or not a record is open; pass a stable element. */ list: ReactNode; handleDrawerClose: RecordNavigation['handleDrawerClose']; @@ -75,7 +82,9 @@ export function ObjectViewRecordOverlay({ onClose={handleDrawerClose} onOpenAsPage={handleOpenAsPage} stepScope={stepScope} - storageKey={`drawer-width:${objectDef.name}`} + // objectstack#36149 — one remembered width for every object + // whose width is not authored. + storageKey={widthKey} objects={objects} renderRecord={(level) => ( }> diff --git a/ui/packages/app-shell/src/views/recordDrawerContext.ts b/ui/packages/app-shell/src/views/recordDrawerContext.ts index f040123fa4a..5cfa206a57d 100644 --- a/ui/packages/app-shell/src/views/recordDrawerContext.ts +++ b/ui/packages/app-shell/src/views/recordDrawerContext.ts @@ -16,6 +16,8 @@ */ import { createContext, useContext } from 'react'; +import { recordOverlayWidthStorageKey } from '@object-ui/components'; +import { overlayWidthFor } from '@object-ui/plugin-view/core'; /** What a record link inside a drawer host calls to open a record in place. */ export interface RecordDrawerApi { @@ -85,3 +87,51 @@ export function opensInRecordDrawer(objectDef: unknown): boolean { const mode = (objectDef as { navigation?: { mode?: unknown } } | null | undefined)?.navigation?.mode; return mode == null || mode === 'drawer'; } + +/** + * The side preview's width until the reader drags it (objectstack#36149): + * 460 px — the list beside it keeps its first three columns on a 1440 px + * window — never wider than the viewport allows. + */ +export const RECORD_PREVIEW_DEFAULT_WIDTH = 'min(92vw, 460px)'; + +/** + * The one remembered width of the side preview, every object's + * (objectstack#36149): a width the reader dragged is kept for the next + * record, whatever its object, so the preview never changes width from one + * record to the next. `NavigationOverlay` stores it as `ov:` + this key; the + * hyphen keeps it apart from every per-object key (`drawer-width:` + an + * object's snake_case name). + */ +export const RECORD_PREVIEW_WIDTH_KEY = 'drawer-width:record-preview'; + +/** + * Where a record pane remembers its dragged width (objectstack#36149): the + * one shared key ({@link RECORD_PREVIEW_WIDTH_KEY}), unless the object (or + * the view that opens it) authors the pane's width — a `navigation.size` + * other than `auto`, or a `navigation.width` (pixel or percent). Such an + * object keeps its per-object key (`recordOverlayWidthStorageKey`), which it + * shares with its calendar, gantt, kanban, tree and grid overlays, so a width + * dragged in another object's preview never takes the place of the author's: + * it opens at the authored width until a width is dragged in its own pane or + * in one of those overlays. + */ +export function recordPreviewWidthKey(objectName: string, navigation: unknown): string { + const nav = navigation as { size?: unknown; width?: unknown } | null | undefined; + const authored = nav != null && (nav.width != null || (nav.size != null && nav.size !== 'auto')); + return authored ? recordOverlayWidthStorageKey(objectName) : RECORD_PREVIEW_WIDTH_KEY; +} + +/** + * The record pane's width before any drag (objectstack#36149), the same on + * the list's preview and on a record page's drawer level: an authored + * `navigation.width` (pixel or percent) as written, else an authored `size` + * bucket; `auto`, or no size, is the side preview's 460, whatever the + * object's field count. + */ +export function recordPaneWidth(navigation: unknown, objectDef: unknown): string | number { + const nav = navigation as { size?: unknown; width?: string | number | null } | null | undefined; + if (nav?.width != null) return nav.width; + const size = nav?.size as Parameters[0] | null | undefined; + return !size || size === 'auto' ? RECORD_PREVIEW_DEFAULT_WIDTH : overlayWidthFor(size, objectDef); +} diff --git a/ui/packages/app-shell/src/views/recordDrawerStack.tsx b/ui/packages/app-shell/src/views/recordDrawerStack.tsx index 943a856261d..3eb1ba5d9fb 100644 --- a/ui/packages/app-shell/src/views/recordDrawerStack.tsx +++ b/ui/packages/app-shell/src/views/recordDrawerStack.tsx @@ -63,7 +63,6 @@ import { type RecordHeaderBar, ObjectIconTile, } from '@object-ui/components'; -import { overlayWidthFor } from '@object-ui/plugin-view/core'; import type { FieldContainerLike } from '@object-ui/core'; import { useObjectLabel, useObjectTranslation } from '@object-ui/i18n'; import { servedObjectLabel, servedObjectPluralLabel } from '../hooks/servedObjectLabel.js'; @@ -86,6 +85,8 @@ import { type RecordDrawerApi, type RecordPaneApi, type RecordPaneBarApi, + recordPaneWidth, + recordPreviewWidthKey, } from './recordDrawerContext.js'; export { @@ -526,8 +527,10 @@ export function RecordStackDrawer({ const [headerTitleSlot, setHeaderTitleSlot] = useState(null); const [headerActionSlot, setHeaderActionSlot] = useState(null); const [headerClaimed, setHeaderClaimed] = useState(false); + // objectstack#36149 / objectstack#36201 — the pane is the side preview: the + // record's name first, one labelled action, Edit and the id's copy in `⋯`. const headerBar = useMemo( - () => ({ titleSlot: headerTitleSlot, actionSlot: headerActionSlot, claim: setHeaderClaimed }), + () => ({ titleSlot: headerTitleSlot, actionSlot: headerActionSlot, claim: setHeaderClaimed, preview: true }), [headerTitleSlot, headerActionSlot], ); const currentObject = current?.objectName; @@ -945,9 +948,10 @@ export function RecordPageDrawerHost({ ); const rootDef = root ? objects.find((o) => (o as { name?: unknown } | null)?.name === root.objectName) : undefined; - // The pane's own width (objectstack#27545): an authored one, else `md`. - const rootWidth = (rootDef as { navigation?: { width?: string | number } } | undefined)?.navigation?.width - ?? overlayWidthFor('md', rootDef); + // The pane's own width (objectstack#27545): an authored width or size + // bucket, else the side preview's 460 (`recordPaneWidth`, objectstack#36149). + const rootNavigation = (rootDef as { navigation?: unknown } | undefined)?.navigation; + const rootWidth = recordPaneWidth(rootNavigation, rootDef); return ( @@ -956,7 +960,7 @@ export function RecordPageDrawerHost({ stack={stack} open={!!root} width={rootWidth} - storageKey={root ? `drawer-width:${root.objectName}` : undefined} + storageKey={root ? recordPreviewWidthKey(root.objectName, rootNavigation) : undefined} objects={objects} onClose={close} onOpenAsPage={openAsPage} diff --git a/ui/packages/components/src/__tests__/navigation-overlay-9299.test.tsx b/ui/packages/components/src/__tests__/navigation-overlay-9299.test.tsx index 3d3cc6bfd9f..73ce313d3f9 100644 --- a/ui/packages/components/src/__tests__/navigation-overlay-9299.test.tsx +++ b/ui/packages/components/src/__tests__/navigation-overlay-9299.test.tsx @@ -25,10 +25,10 @@ * `RecordDetailDrawer`'s retired `objectui.drawerWidth.OBJECT`, must carry * over — ⛔ not be silently reset. The starting state of every case below is * therefore an EXISTING persisted width; a case that only checked the new key - * would prove nothing about the migration. Since objectstack#27545 a - * remembered width draws inside the drag range (`min(Npx, 60vw)`), and an - * authored width is no longer floored at `min(60vw, 880px)`: the pane's - * default is 720 and the reader drags it. + * would prove nothing about the migration. A remembered width draws inside + * the drag range (380 to 900 px since objectstack#36149), and an authored + * width is no longer floored at `min(60vw, 880px)` (objectstack#27545): the + * host's default is drawn as given and the reader drags it. */ import React from 'react'; @@ -126,7 +126,7 @@ describe('objectui#9299 item 4 — the persisted width carries over, it is not r expect(await screen.findByTestId('payload')).toBeInTheDocument(); // The user's width is what renders — not the authored default — bounded // by the drag range (objectstack#27545). - expect(readWidth()).toBe('min(640px, 60vw)'); + expect(readWidth()).toBe('640px'); // … and it has MOVED, so this is a migration and not a permanent second // read: the new key holds it and the retired one is gone. expect(window.localStorage.getItem(KEY)).toBe('640'); @@ -142,7 +142,7 @@ describe('objectui#9299 item 4 — the persisted width carries over, it is not r legacyStorageKey: LEGACY, }); expect(await screen.findByTestId('payload')).toBeInTheDocument(); - expect(readWidth()).toBe('min(700px, 60vw)'); + expect(readWidth()).toBe('700px'); }); it('CONTROL: with no persisted width at all the authored width is what applies', async () => { diff --git a/ui/packages/components/src/__tests__/navigation-overlay-drawer-27545.test.tsx b/ui/packages/components/src/__tests__/navigation-overlay-drawer-27545.test.tsx index cbdbe767c58..5154e872b8a 100644 --- a/ui/packages/components/src/__tests__/navigation-overlay-drawer-27545.test.tsx +++ b/ui/packages/components/src/__tests__/navigation-overlay-drawer-27545.test.tsx @@ -193,29 +193,34 @@ describe('2 — the drawer is a floating card with one ⤢, which opens the page }); }); -describe('the drag range: 360 px to 60vw, remembered per object, a remembered width clamped', () => { +describe('the drag range: 380 px to 900 px (objectstack#36149), remembered under the key, a remembered width clamped', () => { const drawerWidth = () => drawer()!.style.getPropertyValue('--ov-w').trim(); - it('a remembered 1300 is drawn inside the range', () => { + it('a remembered 1300 is drawn at 900', () => { window.localStorage.setItem('ov:drawer-width:lead', '1300'); render(overlay({ storageKey: 'drawer-width:lead' })); - expect(drawerWidth()).toBe('min(1300px, 60vw)'); + expect(drawerWidth()).toBe('900px'); }); - it('a drag stops at 60vw and at 360 px, and the width is remembered under the key', () => { + it('a remembered width below 380 is not used', () => { + window.localStorage.setItem('ov:drawer-width:lead', '370'); + render(overlay({ storageKey: 'drawer-width:lead', width: 'min(92vw, 460px)' })); + expect(drawerWidth()).toBe('min(92vw, 460px)'); + }); + + it('a drag stops at 900 px and at 380 px, and the width is remembered under the key', () => { render(overlay({ storageKey: 'drawer-width:lead' })); const handle = screen.getByRole('separator'); - const maxPx = Math.floor((window.innerWidth * 60) / 100); act(() => { fireEvent.mouseDown(handle); fireEvent.mouseMove(window, { clientX: -5000 }); }); - expect(drawerWidth()).toBe(`min(${maxPx}px, 60vw)`); + expect(drawerWidth()).toBe('900px'); act(() => { fireEvent.mouseMove(window, { clientX: 5000 }); fireEvent.mouseUp(window); }); - // The drawer's right edge is the viewport's: the handle's parent measures 0 in jsdom. - expect(Number(window.localStorage.getItem('ov:drawer-width:lead'))).toBeGreaterThanOrEqual(360); + expect(drawerWidth()).toBe('380px'); + expect(window.localStorage.getItem('ov:drawer-width:lead')).toBe('380'); }); }); diff --git a/ui/packages/components/src/__tests__/page-header-record-bar-35593.test.tsx b/ui/packages/components/src/__tests__/page-header-record-bar-35593.test.tsx index cc72c99deca..37fd154fa32 100644 --- a/ui/packages/components/src/__tests__/page-header-record-bar-35593.test.tsx +++ b/ui/packages/components/src/__tests__/page-header-record-bar-35593.test.tsx @@ -19,7 +19,7 @@ import * as React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import { render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react'; import { ComponentRegistry } from '@object-ui/core'; import { ActionProvider, RecordContextProvider } from '@object-ui/react'; import '../renderers'; @@ -76,13 +76,24 @@ const act = (name: string, label: string, extra: Record = {}) = const ACTIONS = [act('convert', 'Convert', { variant: 'primary' }), act('log_call', 'Log call'), act('send_email', 'Send email')]; /** A host bar: two slots and a claim, as the record page's top bar offers. */ -function BarHost({ claim, children }: { claim: (claimed: boolean) => void; children: React.ReactNode }) { +function BarHost({ + claim, + preview, + children, +}: { + claim: (claimed: boolean) => void; + preview?: boolean; + children: React.ReactNode; +}) { const [titleSlot, setTitleSlot] = React.useState(null); const [actionSlot, setActionSlot] = React.useState(null); - const bar = React.useMemo(() => ({ titleSlot, actionSlot, claim }), [titleSlot, actionSlot, claim]); + const bar = React.useMemo( + () => ({ titleSlot, actionSlot, claim, ...(preview ? { preview } : {}) }), + [titleSlot, actionSlot, claim, preview], + ); return ( <> -
+
@@ -94,8 +105,16 @@ function BarHost({ claim, children }: { claim: (claimed: boolean) => void; child function renderHeader({ schema = { type: 'page:header', actions: ACTIONS }, bar, + preview, state, -}: { schema?: any; bar?: (claimed: boolean) => void; state?: RecordHeaderState } = {}) { + hostActions = HOST_ACTIONS, +}: { + schema?: any; + bar?: (claimed: boolean) => void; + preview?: boolean; + state?: RecordHeaderState; + hostActions?: unknown[]; +} = {}) { const header = ( @@ -111,7 +130,7 @@ function renderHeader({ ); - return render(bar ? {header} : header); + return render(bar ? {header} : header); } const inlineButtons = (root: HTMLElement) => @@ -351,3 +370,134 @@ describe('page:header in the host bar re-measures the width fold on another reco expect(inlineButtons(actionSlot)).toContain('Edit'); }); }); + +/** The open `⋯` menu's entries, in order. */ +async function moreEntries(root: HTMLElement): Promise { + const trigger = Array.from(root.querySelectorAll('button')).find((b) => b.getAttribute('aria-label') === 'More actions'); + expect(trigger, 'the ⋯ trigger').toBeTruthy(); + fireEvent.pointerDown(trigger!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + await waitFor(() => expect(screen.getByRole('menu')).toBeTruthy()); + return Array.from(screen.getByRole('menu').querySelectorAll('[role="menuitem"]')).map((el) => (el.textContent ?? '').trim()); +} + +/** + * objectstack#36201 / objectstack#36149 — a side preview's bar + * (`RecordHeaderBar.preview`): the record's name first. The row draws ONE + * labelled action, the primary, however wide the preview is; the rest — the + * host's Edit too — go into the `⋯` in their order; no copy-id icon after the + * name, whose full text is its tooltip; and that one action folds as well + * while the name is cut below sixteen characters' width. + */ +describe('page:header in a side preview\'s bar (objectstack#36201, objectstack#36149)', () => { + afterEach(() => vi.restoreAllMocks()); + + it('draws one labelled action, the primary, and Edit and the rest in the ⋯ in their order', async () => { + renderHeader({ bar: vi.fn(), preview: true }); + const actionSlot = screen.getByTestId('action-slot'); + await waitFor(() => expect(inlineButtons(actionSlot)).toContain('Convert')); + expect(inlineButtons(actionSlot)).toEqual(['Convert', 'More actions']); + expect(await moreEntries(actionSlot)).toEqual(['Log call', 'Send email', 'Edit', 'Delete']); + }); + + it('an authored maxVisible does not bring more buttons back', async () => { + renderHeader({ bar: vi.fn(), preview: true, schema: { type: 'page:header', actions: ACTIONS, maxVisible: 3 } }); + const actionSlot = screen.getByTestId('action-slot'); + await waitFor(() => expect(inlineButtons(actionSlot)).toContain('Convert')); + expect(inlineButtons(actionSlot)).toEqual(['Convert', 'More actions']); + }); + + it('a record with no action of its own draws no labelled button: Edit is in the ⋯', async () => { + renderHeader({ bar: vi.fn(), preview: true, schema: { type: 'page:header' } }); + const actionSlot = screen.getByTestId('action-slot'); + await waitFor(() => expect(inlineButtons(actionSlot)).toEqual(['More actions'])); + expect(await moreEntries(actionSlot)).toEqual(['Edit', 'Delete']); + }); + + it('the host\'s edit state keeps its Cancel and Save in the row; the page\'s actions fold', async () => { + const editState = [ + { name: 'sys_record_edit_cancel', label: 'Cancel', order: 99, variant: 'outline', onClick: vi.fn() }, + { name: 'sys_record_edit_save', label: 'Save', order: 100, variant: 'primary', onClick: vi.fn() }, + ]; + renderHeader({ bar: vi.fn(), preview: true, hostActions: editState }); + const actionSlot = screen.getByTestId('action-slot'); + await waitFor(() => expect(inlineButtons(actionSlot)).toContain('Save')); + expect(inlineButtons(actionSlot)).toEqual(['Cancel', 'Save', 'More actions']); + }); + + it('draws no copy-id icon after the name, and the name\'s full text is its tooltip', async () => { + renderHeader({ bar: vi.fn(), preview: true }); + const titleSlot = screen.getByTestId('title-slot'); + await waitFor(() => expect(titleSlot.querySelector('h1')?.textContent).toBe('Mira Costa')); + expect(copyIdButton(titleSlot)).toBeUndefined(); + expect(titleSlot.querySelector('h1 [data-record-header-name]')?.getAttribute('title')).toBe('Mira Costa'); + }); + + it('CONTROL — a page\'s bar keeps the copy-id icon and draws no tooltip node', async () => { + renderHeader({ bar: vi.fn() }); + const titleSlot = screen.getByTestId('title-slot'); + await waitFor(() => expect(titleSlot.querySelector('h1')?.textContent).toBe('Mira Costa')); + expect(copyIdButton(titleSlot)).toBeTruthy(); + expect(titleSlot.querySelector('[data-record-header-name]')).toBeNull(); + }); + + /** The chip's copy-id icon (its label is the bundle key with no `I18nProvider`). */ + const copyIdButton = (root: HTMLElement) => + Array.from(root.querySelectorAll('button')).find((b) => /copy/i.test(b.getAttribute('aria-label') ?? '')); + + /** jsdom lays nothing out: the name's drawn and full widths are stubbed. */ + function stubName(shown: number, full: number) { + vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(function (this: HTMLElement) { + return this.tagName === 'H1' ? shown : 0; + }); + vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(function (this: HTMLElement) { + return this.tagName === 'H1' ? full : 0; + }); + } + + it('a name cut below sixteen characters\' width folds the one action too', async () => { + // 16 px text: sixteen characters are 256 px. + stubName(120, 300); + renderHeader({ bar: vi.fn(), preview: true }); + const actionSlot = screen.getByTestId('action-slot'); + await waitFor(() => expect(inlineButtons(actionSlot)).toEqual(['More actions'])); + expect(await moreEntries(actionSlot)).toEqual(['Convert', 'Log call', 'Send email', 'Edit', 'Delete']); + }); + + it('CONTROL — a name cut, but with sixteen characters\' room, keeps the action', async () => { + stubName(260, 400); + renderHeader({ bar: vi.fn(), preview: true }); + const actionSlot = screen.getByTestId('action-slot'); + await waitFor(() => expect(inlineButtons(actionSlot)).toContain('Convert')); + expect(inlineButtons(actionSlot)).toEqual(['Convert', 'More actions']); + }); + + it('CONTROL — a short name drawn in full keeps the action', async () => { + stubName(80, 80); + renderHeader({ bar: vi.fn(), preview: true }); + const actionSlot = screen.getByTestId('action-slot'); + await waitFor(() => expect(inlineButtons(actionSlot)).toContain('Convert')); + expect(inlineButtons(actionSlot)).toEqual(['Convert', 'More actions']); + }); + + it('CONTROL — a page\'s bar never folds for the name', async () => { + stubName(120, 300); + renderHeader({ bar: vi.fn() }); + const actionSlot = screen.getByTestId('action-slot'); + await waitFor(() => expect(inlineButtons(actionSlot)).toContain('Send email')); + expect(inlineButtons(actionSlot)).toContain('Convert'); + }); + + it('CONTROL — a state\'s levers (an approval\'s approve / reject) are drawn as the state draws them', async () => { + const group = (parts: RecordHeaderGroupParts) => ( + <> + + + {parts.recordMenuItems ? : null} + + ); + renderHeader({ bar: vi.fn(), preview: true, state: { group } }); + const actionSlot = screen.getByTestId('action-slot'); + await waitFor(() => expect(inlineButtons(actionSlot)).toEqual(['通过', '拒绝'])); + expect(actionSlot.querySelector('[data-testid="state-menu"]')).toBeTruthy(); + }); +}); diff --git a/ui/packages/components/src/custom/navigation-overlay.tsx b/ui/packages/components/src/custom/navigation-overlay.tsx index c6a8dd0706f..671df74f0cb 100644 --- a/ui/packages/components/src/custom/navigation-overlay.tsx +++ b/ui/packages/components/src/custom/navigation-overlay.tsx @@ -302,10 +302,14 @@ export interface NavigationOverlayProps { * The one `storageKey` spelling every record overlay uses, keyed by object. * * `NavigationOverlay` prefixes it with `ov:` on the way to `localStorage`, so - * the stored key is `ov:drawer-width:OBJECT`. The console's own object page - * (`app-shell`'s `ObjectView`) has always used this spelling; after - * objectui#9299 the five list-type renderers use it too, so one object has one - * remembered overlay width no matter which view type the user resized it on. + * the stored key is `ov:drawer-width:OBJECT`. After objectui#9299 the five + * list-type renderers use it, so one object has one remembered overlay width + * no matter which of them the user resized it on. The console's own record + * preview (`app-shell`'s `ObjectView` and a record page's drawer) uses it only + * for an object that authors its drawer's width; every other object's preview + * shares one key of its own (objectstack#36149), so it no longer shares a + * width with that object's calendar, gantt, kanban, tree or grid overlay. + * This helper's spelling is unchanged. */ export function recordOverlayWidthStorageKey(objectName: string): string { return `drawer-width:${objectName}`; @@ -329,14 +333,15 @@ function resolveWidth(width: string | number | undefined): string | undefined { return width; } -/** Hard floor for drag-resize — narrower than this and the body becomes unusable. */ -const DRAWER_MIN_PX = 360; /** - * The widest a reader can drag the pane, as a share of the viewport - * (objectstack#27545: wider than that is what the full page is for). A - * remembered width beyond it draws at this bound. + * The drag range of the pane (objectstack#36149): 380 px to 900 px. Narrower + * and the body becomes unusable; wider is what the full page is for. A + * remembered width below it is not used, one above it draws at 900, and the + * pane never draws wider than the viewport leaves it + * (`sm:w-[calc(100%-1rem)]`). */ -const DRAWER_MAX_VW = 60; +const DRAWER_MIN_PX = 380; +const DRAWER_MAX_PX = 900; /** * Whether an `Esc` belongs to the element it was pressed in rather than to the @@ -386,20 +391,30 @@ function useDrawerResize( // ⚠️ `parseInt` is deliberate for the legacy value: that is how // `RecordDetailDrawer` read its own key, and reading it with a stricter // parser than the writer used would drop widths rather than carry them over. + // + // objectstack#36149 — a host that keeps one pane mounted and switches its + // key (a record page's drawer, from one object's record to another's) gets + // the width the NEW key holds: a key with no usable width, or no key at + // all, drops the previous key's width, so the host's own width applies. React.useEffect(() => { - if (!storageKey || typeof window === 'undefined') return; + if (typeof window === 'undefined') return; + if (!storageKey) { + setWidth(null); + return; + } try { const raw = window.localStorage.getItem(`ov:${storageKey}`); if (raw) { const n = Number(raw); - if (Number.isFinite(n) && n >= DRAWER_MIN_PX) setWidth(n); + setWidth(Number.isFinite(n) && n >= DRAWER_MIN_PX ? n : null); + return; + } + const legacyRaw = legacyStorageKey ? window.localStorage.getItem(legacyStorageKey) : null; + const legacy = legacyRaw ? parseInt(legacyRaw, 10) : Number.NaN; + if (!legacyStorageKey || !Number.isFinite(legacy) || legacy < DRAWER_MIN_PX) { + setWidth(null); return; } - if (!legacyStorageKey) return; - const legacyRaw = window.localStorage.getItem(legacyStorageKey); - if (!legacyRaw) return; - const legacy = parseInt(legacyRaw, 10); - if (!Number.isFinite(legacy) || legacy < DRAWER_MIN_PX) return; setWidth(legacy); window.localStorage.setItem(`ov:${storageKey}`, String(legacy)); // Removing it is what makes this a MIGRATION rather than a permanent @@ -407,7 +422,8 @@ function useDrawerResize( // width must stay gone. window.localStorage.removeItem(legacyStorageKey); } catch { - // ignore (private mode / quota) + // private mode / quota: nothing remembered, the host's width applies + setWidth(null); } }, [storageKey, legacyStorageKey]); @@ -416,7 +432,7 @@ function useDrawerResize( e.preventDefault(); draggingRef.current = true; - const maxPx = Math.floor((window.innerWidth * DRAWER_MAX_VW) / 100); + const maxPx = DRAWER_MAX_PX; // The drawer is right-anchored, at the viewport's edge. const paneRight = e.currentTarget.parentElement?.getBoundingClientRect().right || window.innerWidth; document.body.style.cursor = 'col-resize'; @@ -563,7 +579,7 @@ export const NavigationOverlay: React.FC = ({ // even when it was remembered at a wider viewport; otherwise the host's // width as given. const paneWidthCss = resize.width != null - ? `min(${resize.width}px, ${DRAWER_MAX_VW}vw)` + ? `${Math.min(resize.width, DRAWER_MAX_PX)}px` : resolveWidth(width) ?? '42rem'; const widthStyle: React.CSSProperties = { ['--ov-w' as any]: paneWidthCss, diff --git a/ui/packages/components/src/renderers/layout/containers.tsx b/ui/packages/components/src/renderers/layout/containers.tsx index 3e6e8640456..6043c1d01f5 100644 --- a/ui/packages/components/src/renderers/layout/containers.tsx +++ b/ui/packages/components/src/renderers/layout/containers.tsx @@ -1929,6 +1929,27 @@ function recordPictureUrl(value: unknown): string | undefined { */ const PHONE_ACTION_BAR_BUTTONS = 2; +/** + * The room a side preview keeps for the record's name before any button + * (objectstack#36201): sixteen characters, measured in the name's own `em`. + */ +const PREVIEW_NAME_MIN_EM = 16; + +/** + * Whether the record's name in the bar around `row` is cut short of the + * room a side preview keeps for it (objectstack#36201): it does not show in + * full, and it shows less than {@link PREVIEW_NAME_MIN_EM} characters' width. + */ +function previewNameSqueezed(row: HTMLElement): boolean { + const bar = row.closest('[data-record-top-bar]'); + const name = bar?.querySelector('[data-record-header-title] h1'); + if (!name) return false; + const shown = name.clientWidth; + if (name.scrollWidth <= shown + 1) return false; + const em = Number.parseFloat(getComputedStyle(name).fontSize) || 16; + return shown < PREVIEW_NAME_MIN_EM * em; +} + /** * The props of {@link PageHeaderActions}. * @@ -1991,6 +2012,17 @@ export interface PageHeaderActionsProps { * action set (objectstack#35997). The host's buttons (Edit) still never fold. */ fitWidth?: boolean; + /** + * The row is a side preview's (objectstack#36149, objectstack#36201; + * `RecordHeaderBar.preview`): on the desktop it draws ONE labelled action, + * the page's primary, and every other button folds into the `⋯` in its + * band and order — the host's buttons too (Edit), except the buttons of the + * host's edit state (Cancel, Save), which are that state's. With + * {@link fitWidth} that one action folds as well while the record's name in + * the bar is cut below sixteen characters' width. No effect on a phone or + * in the bottom bar. + */ + preview?: boolean; } /** The refresh entry of the header's `⋯` menu — see {@link PageHeaderActionsProps.refresh}. */ @@ -2025,6 +2057,7 @@ export const PageHeaderActions: React.FC = ({ face = 'row', defaultMaxVisible, fitWidth = false, + preview = false, }) => { const ctx = useRecordContext(); // objectstack#35853 — the width fold ({@link PageHeaderActionsProps.fitWidth}): @@ -2037,10 +2070,11 @@ export const PageHeaderActions: React.FC = ({ React.useLayoutEffect(() => { if (!fitWidth || !fitRow) return; const items = Array.from(fitRow.children) as HTMLElement[]; - if (items.length < 2) return; - const wrapped = items[items.length - 1].offsetTop > items[0].offsetTop + 1; + const wrapped = items.length >= 2 && items[items.length - 1].offsetTop > items[0].offsetTop + 1; + // objectstack#36201 — a side preview's buttons give way to the name first. + const squeezed = preview && previewNameSqueezed(fitRow); const { inline, floor, key } = fitDrawn.current; - if (wrapped && inline > floor) setWidthCap({ key, cap: inline - 1 }); + if ((wrapped || squeezed) && inline > floor) setWidthCap({ key, cap: inline - 1 }); }); React.useEffect(() => { if (!fitWidth || !fitRow || typeof ResizeObserver === 'undefined') return; @@ -2730,24 +2764,44 @@ export const PageHeaderActions: React.FC = ({ // record (objectstack#35997) draws the full budget and the next layout // measures again. A string key, so an equal set never re-arms the fold. const fitsWidth = fitWidth && !barFace && !isMobile; + // objectstack#36201 — a side preview's row: one labelled action, the + // page's own primary (never a host button, never a destructive one), and + // only the host's edit state keeps its buttons (Cancel, Save) in the row. + // Its width fold goes down to none: the name keeps its room first. + const previewRow = preview && !barFace && !isMobile; + const previewPick: unknown[] = !previewRow || hostPrimary + ? [] + : [ + primaryCandidates.find((a) => !isHostAction(a) && a?.variant === 'primary') + ?? primaryCandidates.find((a) => !isHostAction(a)), + ].filter((a) => a !== undefined); + const rowButtons = previewRow ? previewPick : authoredButtons; + const rowMax = previewRow ? 1 : maxVisible; const fitKey = JSON.stringify([ctx?.recordId, authoredButtons.map((a: any) => a?.name || a?.id)]); const rowCap = widthCap?.key === fitKey ? widthCap.cap : null; - const rowBudget = fitsWidth && rowCap != null ? Math.min(maxVisible, rowCap) : maxVisible; + const rowBudget = fitsWidth && rowCap != null ? Math.min(rowMax, rowCap) : rowMax; if (fitsWidth) { - fitDrawn.current = { inline: Math.min(rowBudget, authoredButtons.length), floor: authoredButtons.length > 0 ? 1 : 0, key: fitKey }; + fitDrawn.current = { + inline: Math.min(rowBudget, rowButtons.length), + floor: !previewRow && rowButtons.length > 0 ? 1 : 0, + key: fitKey, + }; } - const inlineAuthored = new Set(authoredButtons.slice(0, rowBudget)); + const inlineAuthored = new Set(rowButtons.slice(0, rowBudget)); + // The host's buttons that keep the row: all of them on a page; in a side + // preview only those of the host's edit state. + const hostKeepsRow = (a: unknown): boolean => isHostButton(a) && (!previewRow || !!hostPrimary); const inlineActions = barFace ? barQueue.slice(0, maxVisible) - : ranked.filter((a) => isHostButton(a) || inlineAuthored.has(a)); + : ranked.filter((a) => hostKeepsRow(a) || inlineAuthored.has(a)); const foldedButtons = barFace ? [ ...barQueue.slice(maxVisible), ...ranked.filter((a) => isHostAction(a) && !isHostButton(a)), ] : [ - ...authoredButtons.slice(rowBudget), - ...ranked.filter((a) => isHostAction(a) && !isHostButton(a)), + ...ranked.filter((a) => !isHostAction(a) && !inlineAuthored.has(a)), + ...ranked.filter((a) => isHostAction(a) && !hostKeepsRow(a)), ]; // The overflow reads as one list in three bands (objectui#12529): the // authored actions first, then the host's menu chrome (favorites / @@ -2861,8 +2915,9 @@ export const PageHeaderActions: React.FC = ({ // target. const hostEditPick = action === primaryAction && !barFace && isHostAction(action) && action?.variant !== 'primary'; + // A side preview's one action is its row's primary (objectstack#36201). const variant = - action === primaryAction && !hostEditPick + (action === primaryAction && !hostEditPick) || previewPick.includes(action) ? 'default' : isDestructiveAction(action) ? 'destructive' : 'outline'; const size = action.size || 'sm'; @@ -3250,6 +3305,8 @@ const PageHeaderRenderer: React.FC = ({ schema, className, ...props }) => { // objectstack#35853 — the bar's budget is 3, as anywhere else, and // what does not fit the bar's width folds into the `⋯`. fitWidth={inBar} + // objectstack#36201 — a side preview's bar: one labelled action. + preview={inBar && !!headerBar?.preview} /> ); if (!phoneFace) return row; @@ -3569,11 +3626,17 @@ const PageHeaderRenderer: React.FC = ({ schema, className, ...props }) => { // (`text-base`). The navigation row names the object or the list, so the // chip does not repeat it. Nothing is drawn until the host's slots exist. if (drawsInBar && headerBar) { + // objectstack#36149 / objectstack#36201 — a side preview's name: no + // copy-id icon after it (the host's `⋯` offers the copy), and its full + // text as its tooltip, since the preview's width can cut it. + const preview = !!headerBar.preview; const title = headerBar.titleSlot ? createPortal( {chipTitleNode ?? chipTitle} + : chipTitleNode} icon={recordPicture} // The bar's crumb names the object; a host note on it (how a // Setup record's object is managed) keeps its label beside the @@ -3581,7 +3644,7 @@ const PageHeaderRenderer: React.FC = ({ schema, className, ...props }) => { objectLabel={ctx?.objectLabelNote ? objectLabel : undefined} objectLabelNote={ctx?.objectLabelNote} resourceId={data?.id ? String(data.id) : undefined} - showCopyId={showCopyId} + showCopyId={showCopyId && !preview} isFavorite={ctx?.isFavorite} onToggleFavorite={ ctx?.onToggleFavorite diff --git a/ui/packages/components/src/renderers/layout/record-header-bar-context.ts b/ui/packages/components/src/renderers/layout/record-header-bar-context.ts index 7de6d5c18dc..66e8961637c 100644 --- a/ui/packages/components/src/renderers/layout/record-header-bar-context.ts +++ b/ui/packages/components/src/renderers/layout/record-header-bar-context.ts @@ -30,6 +30,20 @@ export interface RecordHeaderBar { actionSlot: HTMLElement | null; /** The header took the bar (`true`) or gave it back (`false`). */ claim(claimed: boolean): void; + /** + * The bar is a side preview's (objectstack#36149, objectstack#36201): the + * record's name comes first. The row draws at most ONE labelled action — + * the page's primary — and the host's buttons (Edit) go into the `⋯` with + * the rest, in their order; that one action folds into the `⋯` too while + * the name has less than 16 characters' room and is cut. No copy-id icon + * follows the name: a host that offers the copy does so in its `⋯`. The + * name's full text is its tooltip. A state's own levers (an approval's + * approve / reject) are drawn as the state draws them. A child list's tab + * under the bar draws one row per record (its title and one summary line), + * the phone's card rows, instead of a table. Absent: a page's bar, as + * before. + */ + preview?: boolean; } export const RecordHeaderBarContext = React.createContext(null); diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index 5be8b16260d..524579cd365 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -31,6 +31,7 @@ import { useIsMobile, RelatedCountStore, ObjectIconTile, + RecordHeaderBarContext, } from '@object-ui/components'; import { SchemaRenderer, ActionCtxReact, useCapabilityGate, useCondition, toPredicateInput, useSettledSchema, useFilterScope, useResolvedFilter, usePredicateScope, classifyLoadError, answeredLoadFailure, declaredUserMessage, type LoadErrorKind, type RelatedRowActionDef } from '@object-ui/react'; import { @@ -1481,6 +1482,11 @@ export const RelatedList: React.FC = ({ // objectstack#27524 — drawn as the record page's active tab: the toolbar // face below (`RelatedListEnlargedContext`). const enlargedFace = React.useContext(RelatedListEnlargedContext) && !compact; + // objectstack#36149 — in a side preview (its header bar says so) the tab's + // rows are the phone's card rows, one per record: the title and one summary + // line, never a table cut off at the preview's edge. + const headerBar = React.useContext(RecordHeaderBarContext); + const previewFace = enlargedFace && !!headerBar?.preview; // objectstack#35601 — the related tab's add, decided by the relationship // when the page authored none (`derivedAddOf`). The rest of this component // reads `add` alone, so a derived add takes the authored one's path. @@ -3792,8 +3798,10 @@ export const RelatedList: React.FC = ({ // tab's own query), and selection with the floating bar (bulk delete). // One growing window, no pager: `data` is every row loaded so far and // `rowCount` the match total, which the footer leads with. + const cardFace = previewFace ? { cardFace: true } : {}; if (tabList) { return { + ...cardFace, manualPagination: true, rowCount: total ?? sortedData.length, page: 1, @@ -3815,6 +3823,7 @@ export const RelatedList: React.FC = ({ }; } return { + ...cardFace, manualPagination: true, rowCount, page: currentPage + 1, @@ -3827,7 +3836,7 @@ export const RelatedList: React.FC = ({ ...(onRowDelete ? { onDelete: handleDeleteRow } : {}), ...(writeTabColumnState ? { onColumnStateChange: writeTabColumnState } : {}), }; - }, [writeTabColumnState, enlargedGrid, windowed, total, currentPage, effectivePageSize, relatedData.length, hasMore, sortedData.length, paginatedData.length, activeSort, handleTableSort, objectSchema, onRowEdit, onRowDelete, handleDeleteRow, tabList, tabRecordCountLead, pickTabSummary, tabFindParams, handleBulkDeleteRows, tabBulkDelete]); + }, [writeTabColumnState, enlargedGrid, windowed, total, currentPage, effectivePageSize, relatedData.length, hasMore, sortedData.length, paginatedData.length, activeSort, handleTableSort, objectSchema, onRowEdit, onRowDelete, handleDeleteRow, tabList, tabRecordCountLead, pickTabSummary, tabFindParams, handleBulkDeleteRows, tabBulkDelete, previewFace]); // objectstack#35601 — a stateful child (tasks) is grouped by its status on // the related tab: open groups first, completed last (`statusGroupsOf`). diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.previewCardFace-36149.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.previewCardFace-36149.test.tsx new file mode 100644 index 00000000000..7a1b39bbea0 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.previewCardFace-36149.test.tsx @@ -0,0 +1,114 @@ +/** + * 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#36149 — the related tab in a side preview (its header bar says + * `preview`) hands the grid `cardFace`: one row per record, its title and one + * summary line, rather than a table cut off at the preview's 460 px edge. + * + * Controls: the same tab under a page's bar, or under no bar, hands no + * `cardFace` (the table, as before); a related list that is not the tab hands + * none even inside a preview. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, render, waitFor } from '@testing-library/react'; +import * as React from 'react'; +import { RecordHeaderBarContext, type RecordHeaderBar } from '@object-ui/components'; +import { RelatedList } from '../RelatedList'; +import { RelatedListEnlargedContext } from '../relatedListCompact'; + +/** Capture what `RelatedList` hands to `SchemaRenderer`. */ +const h = vi.hoisted(() => ({ props: null as any })); +vi.mock('@object-ui/react', async (importOriginal) => { + const actual = await importOriginal>(); + return { + ...actual, + SchemaRenderer: (props: any) => { + h.props = props; + return null; + }, + }; +}); + +afterEach(() => { + cleanup(); + h.props = null; +}); + +const ROWS = [ + { id: 'a1', name: 'Call Ada', subject: 'Renewal', account: 'ACC-1' }, + { id: 'a2', name: 'Email Alan', subject: 'Pricing', account: 'ACC-1' }, +]; + +const bar = (preview: boolean): RecordHeaderBar => ({ + titleSlot: null, + actionSlot: null, + claim: () => {}, + ...(preview ? { preview: true } : {}), +}); + +function renderList({ enlarged, headerBar }: { enlarged: boolean; headerBar: RecordHeaderBar | null }) { + const dataSource = { + find: vi.fn(async () => ({ data: ROWS, total: ROWS.length })), + getObjectSchema: vi.fn(async () => ({ + name: 'activity', + fields: { + name: { type: 'text', label: 'Name' }, + subject: { type: 'text', label: 'Subject' }, + account: { type: 'lookup', reference: 'account', label: 'Account' }, + }, + })), + }; + return render( + + + + + , + ); +} + +describe('the related tab in a side preview draws one card row per record (objectstack#36149)', () => { + it('a preview bar: the grid is handed cardFace', async () => { + renderList({ enlarged: true, headerBar: bar(true) }); + await waitFor(() => expect(h.props?.schema?.data?.items).toHaveLength(2)); + expect(h.props.schema.type).toBe('object-grid'); + expect(h.props.cardFace).toBe(true); + }); + + it('CONTROL: a page bar hands no cardFace', async () => { + renderList({ enlarged: true, headerBar: bar(false) }); + await waitFor(() => expect(h.props?.schema?.data?.items).toHaveLength(2)); + expect(h.props.schema.type).toBe('object-grid'); + expect(h.props.cardFace).toBeUndefined(); + }); + + it('CONTROL: no bar hands no cardFace', async () => { + renderList({ enlarged: true, headerBar: null }); + await waitFor(() => expect(h.props?.schema?.data?.items).toHaveLength(2)); + expect(h.props.cardFace).toBeUndefined(); + }); + + it('CONTROL: a related list that is not the tab hands no cardFace inside a preview', async () => { + renderList({ enlarged: false, headerBar: bar(true) }); + await waitFor(() => expect(h.props?.schema?.data).toBeDefined()); + expect(h.props.schema.type).not.toBe('object-grid'); + expect(h.props.cardFace).toBeUndefined(); + }); +}); diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 22df4102fa5..4c26e3d5947 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -266,6 +266,14 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr * authored metadata. */ residentSummaryRow?: boolean; + /** + * [objectstack#36149] Draw the phone's card rows (the record's title, one + * summary line and its status chip) at any window width: a host whose box + * is a phone's width on a desktop window, the side preview's child tab. + * Absent: card rows below the 768 px app breakpoint only, as before. A HOST + * prop, never authored metadata. + */ + cardFace?: boolean; /** * [objectstack#35702] The host's own wording of the record count that leads * the footer row (the list's 「42 records」, plural forms included). Absent ⇒ @@ -926,6 +934,7 @@ export const ObjectGrid: React.FC = ({ showRowNumbers: hostShowRowNumbers, onColumnSummaryChange, residentSummaryRow, + cardFace: hostCardFace, summaryRowLead, onColumnSummaryPick, summaryPickFields, @@ -952,7 +961,10 @@ export const ObjectGrid: React.FC = ({ // `error`). Read only by the undeclared-name warning's readiness below, so a // failed read reports the names instead of dropping them silently. const [objectSchemaReadFailed, setObjectSchemaReadFailed] = useState(false); - const [useCardView, setUseCardView] = useState(false); + const [windowCardView, setUseCardView] = useState(false); + // The card rows: a phone's window, or a host that asks for them + // (`cardFace`, objectstack#36149). + const useCardView = windowCardView || !!hostCardFace; // objectstack#28434 — the record URL a row links to, for its context menu's // "Open in new tab": the host's own builder, the one `LinkCell` draws the // row's anchor from. diff --git a/ui/packages/plugin-grid/src/__tests__/cardFaceHost-36149.test.tsx b/ui/packages/plugin-grid/src/__tests__/cardFaceHost-36149.test.tsx new file mode 100644 index 00000000000..10f44d6ffeb --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/cardFaceHost-36149.test.tsx @@ -0,0 +1,102 @@ +/** + * 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#36149 — a host whose box is a phone's width on a desktop window + * (the side preview's child tab) asks for the phone's card rows with the + * `cardFace` host prop: one row per record, its title and one summary line, + * at any window width. + * + * Control: without `cardFace` a desktop window keeps the table, and a phone's + * window keeps its cards. + */ + +import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; + +registerAllFields(); + +beforeAll(() => { + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn() as any; + } +}); + +const ORIGINAL_INNER_WIDTH = window.innerWidth; +function setWidth(px: number) { + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: px }); +} + +afterEach(() => { + cleanup(); + setWidth(ORIGINAL_INNER_WIDTH); +}); + +const ROWS = [ + { id: 'r1', name: 'Call Ada', subject: 'Renewal', notes: 'Monday' }, + { id: 'r2', name: 'Email Alan', subject: 'Pricing', notes: 'Friday' }, +]; + +function renderGrid({ width, cardFace }: { width: number; cardFace?: boolean }) { + const dataSource = { + find: vi.fn(async () => ({ data: ROWS, total: ROWS.length, hasMore: false, pageSize: 50 })), + getObjectSchema: async (name: string) => ({ + name, + nameField: 'name', + fields: { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + subject: { type: 'text', label: 'Subject' }, + notes: { type: 'text', label: 'Notes' }, + }, + }), + } as any; + const schema: any = { + type: 'object-grid', + objectName: 'activity', + columns: [{ field: 'name' }, { field: 'subject' }, { field: 'notes' }], + pagination: { pageSize: 50 }, + }; + setWidth(width); + render( + + + + + , + ); +} + +describe('the cardFace host prop draws the phone card rows at any width (objectstack#36149)', () => { + it('a desktop window with cardFace: one card row per record, its title and one summary line', async () => { + renderGrid({ width: 1440, cardFace: true }); + const titles = await screen.findAllByTestId('grid-card-title'); + expect(titles.map((el) => el.textContent)).toEqual(['Call Ada', 'Email Alan']); + const subtitles = screen.getAllByTestId('grid-card-subtitle'); + expect(subtitles.map((el) => el.textContent)).toEqual(['Renewal · Monday', 'Pricing · Friday']); + expect(screen.queryByRole('columnheader', { name: /Subject/ })).toBeNull(); + }); + + it('CONTROL: a desktop window without cardFace keeps the table', async () => { + renderGrid({ width: 1440 }); + await waitFor(() => expect(screen.getAllByText('Call Ada').length).toBeGreaterThan(0)); + expect(screen.queryAllByTestId('grid-card-title')).toHaveLength(0); + }); + + it('CONTROL: a phone window without cardFace keeps its cards', async () => { + renderGrid({ width: 390 }); + const titles = await screen.findAllByTestId('grid-card-title'); + expect(titles).toHaveLength(2); + }); +});