diff --git a/.changeset/35890-record-details-pinned.md b/.changeset/35890-record-details-pinned.md new file mode 100644 index 00000000000..13a959c04be --- /dev/null +++ b/.changeset/35890-record-details-pinned.md @@ -0,0 +1,22 @@ +--- +'@object-ui/plugin-detail': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): on a wide full record page the details are pinned in a left column and the other tabs sit beside them; the right summary rail is retired + +Clause-②: yes (widening) +Metadata-protocol: none + +The synthesized record page (objectstack#35890, ruling on the card 7064066204): + +- **Pinned details.** A full page whose content fits a 320 px details column, a 24 px gap and 400 px of tabs pins the record's details in a left column and draws the other tabs (related lists, Attachments, Approvals, 动态) beside them, opening on the first. The column is 400 px wide and narrows toward 320 px on a tight page; its edge is a separator the reader drags, or moves with ←/→ (Home/End for the ends). The dragged width is kept per object in the console's workspace preference store (`record.columns.details-width`, this browser). Each column scrolls on its own. A page with no other tab draws the details across the page with no tab row; a page whose details hold a related table among the fields (objectstack#35889) is not pinned and keeps its one-column tab row. Narrowing out of the pinned layout keeps the tab that was shown, writing it to the address with `replace`. +- **The right rail is retired** at every width, with its ⊟ switch and `⌘⇧,` shortcut and the `record.columns.related` preference (an old stored choice is no longer read). Its cards (approval, attachments, recent activity, other related) are the tabs they summarised. A list the reader hid still opens, from its item in 「更多」 or from an address that names it (`?related=`). +- **「详情」.** The first tab is named Details (详情) in every locale. +- **「审批中 · 当前步骤」.** For everyone but the approver, the header's in-approval tag names the step the request waits at, when it has one. +- **Drawer, split pane and phone** keep their one-column tab row and never pin. What reaches them: the rail is gone there too, and the first tab reads 「详情」 / Details. Authored pages are untouched. + +`RecordPageColumns` gains the optional `fullPage`, `detailsWidth`, `onDetailsWidthChange` and `onShownTabChange` props, and `onEnlargeRelated` an optional `{ replace }`; `rightColumn` and `rail` are kept as deprecated props that do nothing. `@object-ui/plugin-detail` exports `RECORD_PAGE_DETAILS_WIDTH`, `RECORD_PAGE_PIN_MIN_WIDTH` and `recordPagePinsDetails`; `recordPageTierHasRightColumn` stays exported, answering as before, and is now `@deprecated` (no tier draws a right rail). + +`@object-ui/i18n` widens: two new keys in every pack, `detail.approvalPendingStep` (`In approval · {{step}}`) and `detail.detailsColumnResize` (the separator's name), and `detail.recordTabOverview` changes its text from 概览 / Overview to 详情 / Details. Every key the rail read (`detail.relatedColumn`, `detail.relatedHiddenCount` and its plural forms, `detail.relatedShowHidden`, the six `detail.summary*` keys and `shortcuts.toggleRelated`) stay in every pack, unread, so a host that reads them keeps its text; retiring them is a separate change. diff --git a/content/docs/ui/pages.mdx b/content/docs/ui/pages.mdx index 0ebf271eb8b..5395b0fd79d 100644 --- a/content/docs/ui/pages.mdx +++ b/content/docs/ui/pages.mdx @@ -180,41 +180,38 @@ replacement. ### The synthesized default A record page needs no authoring. With no page assigned, the Console synthesizes one from -the object: a header, the record's **details**, and a right column of -panels: the related lists, then the attachments of an object with `enable: { files: true }`, -then **Approvals** when the record has approval requests, and **动态** (Activity) last. On a -narrow screen the same panels follow the details in one column, so **动态** ends the page. A -relationship whose child field declares `relatedList: 'primary'` is part of the record's body: -its list is a full-width table in the details, after the first field section, with no panel of -its own. **动态** is one stream: the discussion, the activity and, with -`enable: { trackHistory: true }`, the record's field changes; there is no separate History tab. -Its panel shows a one-line composer and the newest entries, and its header opens the whole -stream (`?related=timeline`), filtered by All / Activity / Discussion / Changes. A related -panel's header opens that list's whole table the same way (`?related=.`). -Each of those faces is also a tab: a row of tabs closes the record header, **Overview** first, -then one tab per related panel in the reader's order, then **动态** last, each with its count. The -row shows as many tabs as its width fits and folds the rest into a **+N** menu; the open tab -is always on the row, and **Overview** or Esc returns to the page. +the object: a header, the record's **details** (the **Details** tab), and one tab per related +list, then **Attachments** for an object with `enable: { files: true }`, **Approvals** when the +record has approval requests, and **动态** (Activity) last, each with its count. A relationship +whose child field declares `relatedList: 'primary'` is part of the record's body: its list is a +full-width table in the details, after the first field section, with no tab of its own. **动态** +(`?related=timeline`) holds the record's system entries: its activity and, with +`enable: { trackHistory: true }`, its field changes; there is no separate History tab. On the +desktop the record's comments are not in it but in the comment panel, opened from the +comments icon in the record header ([the record's comment panel](/docs/frontend/plugins/plugin-detail#the-records-comment-panel)); on a phone they are still +in **动态**, with its All / Activity / Discussion / Changes filter. A list's tab is that list's +whole table (`?related=.`). The tab row shows as many tabs as its width fits and folds the +rest into a **+N** menu; the open tab is always on the row. The related tabs are the reader's +to arrange: move one before or after its neighbour, hide one, and bring hidden ones back. The +arrangement is kept per user and object, never in the object's declaration. Moving a child table into the record's body is therefore a one-word change on the relationship field, not a page-authoring task, and `relatedList: false` leaves a child off the page. -The Console lays the page out by the width of the surface it occupies (the full page, the split -pane or the drawer), never by the viewport, and by one rule. From 760 px the details sit beside -the right column, 320 px wide; from 1120 px the right column is 380 px and a details section -takes up to three field columns. Below 760 px (the split pane, a phone) the page is one column: -the details, then the right column's panels in their order. The **⊟** switch at the end of the -record header's actions (`⌘⇧,`) hides the right column for the reader, per object. The related -panels are the reader's to arrange, too: drag a panel's **⠿** handle (or **⌥↑** / **⌥↓** on it) -to reorder, hide a panel from its header, and bring hidden panels back from the column's last -line. The arrangement is kept per user and object, never in the object's declaration. - -The related panels load in steps, and the details never wait for them. The page asks every -panel's count in one request set, sent beside the record read, and the panels show -placeholders until those counts land. A panel counted at 0 reads no rows, and two or more of -them fold into one line. A panel above 0 reads its first three rows once it scrolls into view, -asking only for the record's name field and one status or date field. In a drawer, the record -that **↑** / **↓** would show next has its related counts read ahead. +The Console lays the page out by the width of the surface it occupies, never by the viewport. +On a full page wide enough for a 320 px details column beside 400 px of tabs, the details are +pinned in a left column and the other tabs sit beside them, opening on the first: the column +is 400 px wide, narrows toward 320 px when the page is tight, and can be dragged (or moved with +←/→ on its edge); the width is kept per object, in the browser. A page without other tabs, or one +whose details hold a related table, draws the details across the page. Narrower full pages, +the drawer and a phone draw one column: the tab row, **Details** first, and the open tab +under it. + +The related lists load in steps, and the details never wait for them. The page asks every +list's count in one request set, sent beside the record read, and draws each list's tab +before those counts land; a list counted at 0 reads no rows, and its tab is muted, with no +number. A list reads its rows when its tab opens. In a drawer, the record that **↑** / **↓** +would show next has its related counts read ahead. ### Slotted pages diff --git a/ui/e2e/record-tabs-rail-35595.spec.ts b/ui/e2e/record-tabs-35595.spec.ts similarity index 77% rename from ui/e2e/record-tabs-rail-35595.spec.ts rename to ui/e2e/record-tabs-35595.spec.ts index 9199c4ed041..02d8f4c5c4e 100644 --- a/ui/e2e/record-tabs-rail-35595.spec.ts +++ b/ui/e2e/record-tabs-35595.spec.ts @@ -10,21 +10,24 @@ import { uiRoot } from '../scripts/ui-root.mjs'; /** * GEOMETRY and INTERACTION pin for objectstack#35595 (the record page's tab - * row) and objectstack#35596 (the 概览 tab's right rail), zh-CN. + * row) and objectstack#35890 (the pinned details; the 概览 right rail of + * objectstack#35596 is retired), zh-CN. * * - The tab row folds by WIDTH only: a row sized from its own measured * tabs to hold the first eight draws exactly those and folds the tail * into 「更多 N ▾」, whose items keep their counts; CONTROL, the same page * at the 1184 px a 1440 window leaves draws every tab. - * - On 概览 the stage path and the key fields are at the top across the - * whole width — both columns; CONTROL, the details column beside the rail - * is narrower than they are. Since objectstack#35891 the default page - * draws no strip, so the fixture places one in the `highlights` slot, as - * an authored page does. - * - The rail is the 概览 tab's: another tab open draws no rail and no - * strip; CONTROL, back on 概览 both are drawn again. - * - A rail card's title opens its tab; CONTROL, the 概览 tab returns. - * - A card measures radius 8, a 14 px title with a grey count, 26 px rows. + * - Not a full page (the drawer): one column. The stage path and the key + * fields sit at the top of 「详情」 across the details' width, and no + * page draws a rail. Since objectstack#35891 the default page draws no + * strip, so the fixture places one in the `highlights` slot, as an + * authored page does. + * - The strip is 「详情」's: another tab open draws no strip; CONTROL, back + * on 「详情」 it is drawn again. + * - objectstack#35890: a full page wide enough pins the details 400 px on + * the left and draws the other tabs beside them, opening on the first + * list; dragging the separator widens the details and never leaves the + * tabs less than 400 px. * - objectstack#35783: an open list's tab is its menu — 「左移」 / 「右移」 * move it, 「隐藏」 sends it to 「更多」 — and 「更多」's 「恢复默认顺序」 * brings the default back. Order only: no width is read. @@ -36,8 +39,7 @@ import { uiRoot } from '../scripts/ui-root.mjs'; * * ## What is real here and what is a fixture * - * REAL: plugin-detail's `RecordPageColumns`, `RecordTabRow` and - * `RecordSummaryRail`, the page synthesizer (`buildDefaultPageSchema` → + * REAL: plugin-detail's `RecordPageColumns` and `RecordTabRow`, the page synthesizer (`buildDefaultPageSchema` → * `buildDefaultPageColumns`), the related-count store and the zh-Hans pack * through `I18nProvider`, bundled by Vite from their source files and mounted * in Chromium with React's client renderer; the stylesheet is real Tailwind, @@ -58,7 +60,8 @@ import { uiRoot } from '../scripts/ui-root.mjs'; * fold, a width computed from what the row measures its own tabs at * (below); 1184 px (a 1440 window with the sidebar open) for its * CONTROL; and 1024 px (a 1280 × 800 window with the sidebar open) for - * the 概览 placement and the rail. + * the 「详情」 placement and the pinned layout. The host is the drawer's + * (`fullPage` off) unless the case says `fullPage`. * - Fonts are whatever the machine has, and the fold does not depend on * them. A CJK label is about 13 px a glyph where a CJK font is installed * and about 8 px where none is (measured: 概览 26 px against 16 px), so @@ -99,19 +102,21 @@ interface Case { name: string; viewport: number; frame: number; + /** objectstack#35890 — the full record page, which pins its details when it fits. */ + fullPage?: boolean; } -const ENTRY = '\0record-tabs-rail:entry'; -const REACT_SHIM = '\0record-tabs-rail:react'; -const STUB = '\0record-tabs-rail:stub'; +const ENTRY = '\0record-tabs-35595:entry'; +const REACT_SHIM = '\0record-tabs-35595:react'; +const STUB = '\0record-tabs-35595:stub'; /** `@object-ui/` to `packages//src`; the page's `@object-ui/react` to the shim. */ function workspaceSources(): Plugin { return { - name: 'record-tabs-rail-workspace-src', + name: 'record-tabs-35595-workspace-src', enforce: 'pre', async resolveId(id, importer) { - if (id === 'record-tabs-rail:react-real') { + if (id === 'record-tabs-35595:react-real') { return this.resolve(REACT_BINDINGS, importer, { skipSelf: true }); } const m = /^@object-ui\/([a-z0-9-]+)(?:\/(.+))?$/.exec(id); @@ -156,7 +161,7 @@ export function SchemaRenderer({ schema }) { `; const SHIM_CODE = ` -export * from 'record-tabs-rail:react-real'; +export * from 'record-tabs-35595:react-real'; export { SchemaRenderer } from ${JSON.stringify(STUB)}; `; @@ -165,7 +170,7 @@ function entry(): Plugin { const code = ` import * as React from 'react'; import { createRoot } from 'react-dom/client'; -import { RecordContextProvider } from 'record-tabs-rail:react-real'; +import { RecordContextProvider } from 'record-tabs-35595:react-real'; import { I18nProvider } from ${JSON.stringify(I18N)}; import { RelatedCountStore } from ${JSON.stringify(COUNT_STORE)}; import { RecordPageColumns } from ${JSON.stringify(PAGE_COLUMNS)}; @@ -219,6 +224,7 @@ function Host() { const [open, setOpen] = React.useState(undefined); return h(RecordPageColumns, { tier: recordPageTierFor(c.frame), + fullPage: !!c.fullPage, columns, enlargedRelated: open, onEnlargeRelated: setOpen, @@ -242,8 +248,8 @@ window.__remount = () => { window.__remount(); `; return { - name: 'record-tabs-rail-entry', - resolveId: (id) => (id === 'record-tabs-rail:entry' ? ENTRY : id === REACT_SHIM || id === STUB ? id : null), + name: 'record-tabs-35595-entry', + resolveId: (id) => (id === 'record-tabs-35595:entry' ? ENTRY : id === REACT_SHIM || id === STUB ? id : null), load: (id) => (id === ENTRY ? code : id === REACT_SHIM ? SHIM_CODE : id === STUB ? STUB_CODE : null), }; } @@ -254,7 +260,7 @@ async function bundlePage(): Promise { configFile: false, root: REPO_ROOT, // Out of the tree: this run must leave nothing behind in the checkout. - cacheDir: path.join(os.tmpdir(), 'objectui-record-tabs-rail'), + cacheDir: path.join(os.tmpdir(), 'objectui-record-tabs-35595'), logLevel: 'error', mode: 'production', define: { 'process.env.NODE_ENV': JSON.stringify('production') }, @@ -266,7 +272,7 @@ async function bundlePage(): Promise { modulePreload: false, reportCompressedSize: false, rollupOptions: { - input: 'record-tabs-rail:entry', + input: 'record-tabs-35595:entry', output: { format: 'es', codeSplitting: false }, }, }, @@ -330,11 +336,8 @@ const face = (page: Page) => page.evaluate(() => { const tabs = [...document.querySelectorAll('[role="tab"]')].map((el) => el.textContent).join('|'); const more = document.querySelector('[data-record-tab-more]')?.textContent ?? ''; - const cards = [...document.querySelectorAll('[data-record-summary-card]')] - .filter((el) => !(el as HTMLElement).hidden) - .map((el) => el.textContent) - .join('|'); - return `${tabs}#${more}#${cards}`; + const columns = document.querySelector('[data-record-columns]')?.getAttribute('style') ?? ''; + return `${tabs}#${more}#${columns}`; }); async function settle(page: Page, compiled: Set): Promise { @@ -348,7 +351,7 @@ async function settle(page: Page, compiled: Set): Promise { await styleUntilStable(page, compiled); } -/** Mount the case, style it, and wait until the row and the rail hold still. */ +/** Mount the case, style it, and wait until the row and the columns hold still. */ async function mount(page: Page, c: Case): Promise> { await page.setViewportSize({ width: c.viewport, height: 800 }); await page.setContent('
'); @@ -403,7 +406,7 @@ const readRow = (page: Page): Promise => }; }); -/** Every tab the page offers, in order: 概览, the eight lists, 附件, 审批, 动态. */ +/** Every tab the page offers, in order: 详情, the eight lists, 附件, 审批, 动态. */ const ALL_TABS = [ 'overview', 'contact.account_id', @@ -420,8 +423,8 @@ const ALL_TABS = [ ]; function report(testInfo: import('@playwright/test').TestInfo, name: string, reading: unknown): void { - testInfo.annotations.push({ type: `record-tabs-rail@${name}`, description: JSON.stringify(reading) }); - process.stdout.write(`[record-tabs-rail ${name}] ${JSON.stringify(reading)}\n`); + testInfo.annotations.push({ type: `record-tabs-35595@${name}`, description: JSON.stringify(reading) }); + process.stdout.write(`[record-tabs-35595 ${name}] ${JSON.stringify(reading)}\n`); } const box = (page: Page, selector: string) => @@ -432,7 +435,7 @@ const box = (page: Page, selector: string) => return { left: Math.round(r.left), right: Math.round(r.right), top: Math.round(r.top), width: Math.round(r.width) }; }, selector); -test.describe('the record page\'s tabs and 概览 rail, zh-CN (objectstack#35595, objectstack#35596)', () => { +test.describe('the record page\'s tabs and pinned details, zh-CN (objectstack#35595, objectstack#35890)', () => { test.skip(({ browserName }) => browserName !== 'chromium', 'one engine is enough for a layout pin'); test.beforeAll(async () => { @@ -480,11 +483,13 @@ test.describe('the record page\'s tabs and 概览 rail, zh-CN (objectstack#35595 ); report(testInfo, 'fold-menu', menu); expect(menu.map((m) => m.id)).toEqual(ALL_TABS.slice(r.shown.length)); - // The folded lists keep their numbers; 审批 its dot; 动态 its size. + // The folded lists keep their numbers; 审批 its dot. (动态's number is + // the host's stream count, which this fixture has no discussion for: + // `RecordDetailView.timelineCount-28737` pins it on the real host.) const byId = Object.fromEntries(menu.map((m) => [m.id, m])); expect(byId['task.what_id']?.count).toBe('6'); expect(byId['approvals']?.dot).toBe(true); - expect(byId['timeline']?.count).toBe('4'); + expect(byId['timeline']).toBeTruthy(); }); test('CONTROL: the same page at 1184 px draws every tab, the empty ones muted, and no 「更多」', async ({ page }, testInfo) => { @@ -504,99 +509,108 @@ test.describe('the record page\'s tabs and 概览 rail, zh-CN (objectstack#35595 expect(await page.locator('[data-record-tab="case.account_id"] [data-record-tab-count]').count()).toBe(0); }); - test('1280 × 800: on 概览 the stage path and the key fields span both columns, above them', async ({ page }, testInfo) => { + test('not a full page, 1024 px: one column, the strip at the top of 「详情」 across the details, and no rail', async ({ page }, testInfo) => { test.setTimeout(120_000); await mount(page, { name: 'overview1280', viewport: 1280, frame: PAGE_1280 }); const strip = await box(page, '[data-record-overview-strip]'); const details = await box(page, '[data-record-column="details"]'); - const rail = await box(page, '[data-record-column="right"]'); const row = await box(page, '[data-record-tab-row]'); - report(testInfo, 'overview1280', { strip, details, rail, row }); - expect(strip && details && rail && row).toBeTruthy(); - // Across the whole width: from the details' left edge to the rail's right edge. + const rail = await page.evaluate(() => ({ + right: document.querySelectorAll('[data-record-column="right"]').length, + cards: document.querySelectorAll('[data-record-summary-card]').length, + pinned: document.querySelectorAll('[data-record-page-pinned]').length, + shown: document.querySelector('[data-record-columns]')?.getAttribute('data-record-columns-shown') ?? null, + })); + report(testInfo, 'overview1280', { strip, details, row, rail }); + expect(strip && details && row).toBeTruthy(); + expect(rail).toEqual({ right: 0, cards: 0, pinned: 0, shown: 'details' }); + // Across the details' width, below the tab row. expect(Math.abs(strip!.left - details!.left)).toBeLessThanOrEqual(1); - expect(Math.abs(strip!.right - rail!.right)).toBeLessThanOrEqual(1); - // Below the tab row, above both columns. + expect(Math.abs(strip!.right - details!.right)).toBeLessThanOrEqual(1); expect(strip!.top).toBeGreaterThanOrEqual(row!.top); - expect(details!.top).toBeGreaterThan(strip!.top); - expect(rail!.top).toBeGreaterThan(strip!.top); - // CONTROL: the details column beside the rail is narrower than the strip. - expect(details!.width).toBeLessThan(strip!.width - 200); + await expect(page.locator('[data-record-tab="overview"]')).toHaveAttribute('aria-selected', 'true'); + await expect(page.locator('[data-record-tab="overview"]')).toContainText('详情'); }); - test('the rail and the strip are 概览\'s: another tab draws neither; CONTROL, 概览 brings both back', async ({ page }, testInfo) => { + test('the strip is 「详情」\'s: another tab draws none; CONTROL, 「详情」 brings it back', async ({ page }, testInfo) => { test.setTimeout(120_000); const compiled = await mount(page, { name: 'otherTab1280', viewport: 1280, frame: PAGE_1280 }); - // CONTROL first: on 概览 both are drawn. - await expect(page.locator('[data-record-column="right"]')).toHaveCount(1); + // CONTROL first: on 「详情」 the strip is drawn. await expect(page.locator('[data-record-overview-strip]')).toHaveCount(1); await page.locator('[data-record-tab="contact.account_id"]').click(); await expect(page.locator('[data-record-tab="contact.account_id"]')).toHaveAttribute('aria-selected', 'true'); await settle(page, compiled); const opened = await page.evaluate(() => ({ - rail: document.querySelectorAll('[data-record-column="right"]').length, - cards: document.querySelectorAll('[data-record-summary-card]').length, strip: document.querySelectorAll('[data-record-overview-strip], [data-node="record:highlights"], [data-node="record:path"]').length, face: document.querySelector('[data-related-enlarged]')?.getAttribute('data-related-enlarged') ?? null, })); report(testInfo, 'otherTab1280', opened); - expect(opened).toEqual({ rail: 0, cards: 0, strip: 0, face: 'contact.account_id' }); + expect(opened).toEqual({ strip: 0, face: 'contact.account_id' }); await page.locator('[data-record-tab="overview"]').click(); - await expect(page.locator('[data-record-column="right"]')).toHaveCount(1); await expect(page.locator('[data-record-overview-strip]')).toHaveCount(1); }); - test('a rail card\'s title opens its tab; the rail reads 审批, 附件, 最近动态, 其他相关, sized 8 / 13 / 26', async ({ page }, testInfo) => { + test('a full page at 1024 px pins the details 400 px left, the tabs beside them on the first list; the separator drags, the tabs keep 400 px (objectstack#35890)', async ({ page }, testInfo) => { test.setTimeout(120_000); - await mount(page, { name: 'railClick1280', viewport: 1280, frame: PAGE_1280 }); - const rail = await page.evaluate(() => { - const cards = [...document.querySelectorAll('[data-record-summary-card]')].filter((el) => !el.hidden); - const first = cards[0]; - const title = first.querySelector('[data-record-summary-card-title]')!; - const row = document.querySelector('[data-record-summary-row]')!; - const count = document.querySelector('[data-record-summary-card-count]')!; - return { - order: cards.map((el) => el.getAttribute('data-record-summary-card')), - rows: cards.map((el) => el.querySelectorAll('[data-record-summary-row]').length), - radius: getComputedStyle(first).borderTopLeftRadius, - titleSize: getComputedStyle(title).fontSize, - rowHeight: Math.round(row.getBoundingClientRect().height), - countColor: getComputedStyle(count).color, - titleColor: getComputedStyle(title).color, - other: document.querySelector('[data-record-summary-other]')?.textContent ?? null, - emptyLine: /还有\s*\d+\s*个空关联/.test(document.body.textContent ?? ''), - }; - }); - report(testInfo, 'railClick1280', rail); - // 审批, 附件, 最近动态, then 其他相关: the six lists with records, in their order. - expect(rail.order).toEqual([ - 'approvals', - 'attachments', - 'timeline', - 'contact.account_id', - 'opportunity.account_id', - 'contract.account_id', - 'quote.account_id', - 'campaign_member.account_id', - 'task.what_id', - ]); - expect(Math.max(...rail.rows)).toBeLessThanOrEqual(3); - expect(rail.radius).toBe('8px'); - expect(rail.titleSize).toBe('14px'); - expect(rail.rowHeight).toBe(26); - expect(rail.countColor).not.toBe(rail.titleColor); - expect(rail.other).toBe('其他相关'); - expect(rail.emptyLine).toBe(false); - // The whole title opens the tab. - await page.locator('[data-record-summary-card="quote.account_id"] [data-record-summary-card-title]').click(); - await expect(page.locator('[data-record-tab="quote.account_id"]')).toHaveAttribute('aria-selected', 'true'); - await expect(page.locator('[data-related-enlarged="quote.account_id"]')).toHaveCount(1); - // CONTROL: 概览 returns, and the rail with it. - await page.locator('[data-record-tab="overview"]').click(); - await expect(page.locator('[data-record-tab="overview"]')).toHaveAttribute('aria-selected', 'true'); - await expect(page.locator('[data-record-summary-card="quote.account_id"]')).toHaveCount(1); - await page.locator('[data-record-summary-card="approvals"] [data-record-summary-card-title]').click(); - await expect(page.locator('[data-record-tab="approvals"]')).toHaveAttribute('aria-selected', 'true'); + const compiled = await mount(page, { name: 'pinned1280', viewport: 1280, frame: PAGE_1280, fullPage: true }); + const read = () => + page.evaluate(() => { + const r = (sel: string) => { + const el = document.querySelector(sel); + if (!el) return null; + const b = el.getBoundingClientRect(); + return { left: Math.round(b.left), right: Math.round(b.right), top: Math.round(b.top), width: Math.round(b.width) }; + }; + return { + pinned: !!document.querySelector('[data-record-page-pinned]'), + shown: document.querySelector('[data-record-columns]')?.getAttribute('data-record-columns-shown') ?? null, + details: r('[data-record-column="details"]'), + handle: r('[data-record-details-resize]'), + tabs: r('[data-record-column="tabs"]'), + row: r('[data-record-tab-row]'), + tabIds: [...document.querySelectorAll('[data-record-tab-row] [role="tab"]')].map((el) => el.getAttribute('data-record-tab')), + active: document.querySelector('[data-record-tab-row] [aria-selected="true"]')?.getAttribute('data-record-tab') ?? null, + face: document.querySelector('[data-record-column="tabs"] [data-related-enlarged]')?.getAttribute('data-related-enlarged') ?? null, + strip: document.querySelector('[data-record-column="details"] [data-record-overview-strip]') ? 'in details' : null, + rail: document.querySelectorAll('[data-record-summary-card], [data-record-column="right"]').length, + }; + }); + const at = await read(); + report(testInfo, 'pinned1280', at); + expect(at.pinned).toBe(true); + expect(at.shown).toBe('details tabs'); + expect(at.rail).toBe(0); + expect(at.details!.width).toBe(400); + expect(at.handle!.width).toBe(24); + expect(at.handle!.left).toBe(at.details!.right); + expect(at.tabs!.left).toBe(at.handle!.right); + // The tab row is the right column's; 「详情」 is the left column, so it has no tab. + expect(at.row!.left).toBeGreaterThanOrEqual(at.tabs!.left); + expect(at.tabIds).not.toContain('overview'); + expect(at.active).toBe('contact.account_id'); + expect(at.face).toBe('contact.account_id'); + expect(at.strip).toBe('in details'); + // Drag the separator 300 px right: the details widen until the tabs have 400 px left. + const h = at.handle!; + await page.mouse.move(h.left + h.width / 2, h.top + 40); + await page.mouse.down(); + await page.mouse.move(h.left + h.width / 2 + 150, h.top + 40, { steps: 5 }); + await page.mouse.move(h.left + h.width / 2 + 300, h.top + 40, { steps: 5 }); + await page.mouse.up(); + await settle(page, compiled); + const dragged = await read(); + report(testInfo, 'pinned1280-dragged', dragged); + expect(dragged.details!.width).toBeGreaterThan(400); + expect(dragged.tabs!.width).toBe(400); + expect(dragged.details!.width + 24 + 400).toBe(at.details!.width + 24 + at.tabs!.width); + // CONTROL: another tab opens in the right column, the details stay. The last + // tab still on the 400 px row (the rest are in 「更多」; how many fit follows + // the tab text size, 14 px since objectstack#36047). + const other = dragged.tabIds.at(-1)!; + expect(other).not.toBe(dragged.active); + await page.locator(`[data-record-tab-row] [role="tab"][data-record-tab="${other}"]`).click(); + await expect(page.locator(`[data-record-column="tabs"] [data-related-enlarged="${other}"]`)).toHaveCount(1); + await expect(page.locator('[data-record-column="details"]')).toHaveCount(1); }); }); @@ -635,7 +649,7 @@ test.describe('a related tab\'s menu moves and hides it, and 「更多」 restor expect(moved.slice(0, 2)).toEqual(['opportunity.account_id', 'contact.account_id']); await arrange(page, 'contact.account_id', '左移'); expect(await listTabs(page)).toEqual(lists); - // CONTROL: 概览 opens no menu. + // CONTROL: 「详情」 opens no menu. await page.locator('[role="tab"][data-record-tab="overview"]').click(); await page.locator('[role="tab"][data-record-tab="overview"]').click(); await expect(page.locator('[data-record-tab-arrange-menu]')).toHaveCount(0); diff --git a/ui/packages/app-shell/src/utils/workspacePreference.hook.test.tsx b/ui/packages/app-shell/src/utils/workspacePreference.hook.test.tsx index e039460151c..89ba29ce34e 100644 --- a/ui/packages/app-shell/src/utils/workspacePreference.hook.test.tsx +++ b/ui/packages/app-shell/src/utils/workspacePreference.hook.test.tsx @@ -18,7 +18,7 @@ import * as React from 'react'; import { describe, it, expect, afterEach, vi } from 'vitest'; import { render, screen, cleanup, act, fireEvent } from '@testing-library/react'; import { - RECORD_RELATED_COLUMN_PREFERENCE, + APPROVAL_QUEUE_OPEN_NEXT_PREFERENCE, objectPreferenceScope, useWorkspacePreference, workspacePreferenceStorageKey, @@ -28,10 +28,10 @@ import { const LEAD = objectPreferenceScope('crm_lead'); const PRODUCT = objectPreferenceScope('crm_product'); -const LEAD_KEY = workspacePreferenceStorageKey(RECORD_RELATED_COLUMN_PREFERENCE, LEAD); +const LEAD_KEY = workspacePreferenceStorageKey(APPROVAL_QUEUE_OPEN_NEXT_PREFERENCE, LEAD); function Probe({ id, scope, fallback }: { id: string; scope: WorkspacePreferenceScope; fallback: PreferenceSwitch }) { - const [value, setValue] = useWorkspacePreference(RECORD_RELATED_COLUMN_PREFERENCE, scope, fallback); + const [value, setValue] = useWorkspacePreference(APPROVAL_QUEUE_OPEN_NEXT_PREFERENCE, scope, fallback); return ( - - )} - {hiddenCount > 0 && rearranged && ' · '} - {rearranged && ( - - )} -

- ); -}; - /** * A column stacks its blocks 16 px apart. A related list folded into its * stack's empty line stays MOUNTED with its content `hidden` @@ -311,35 +291,176 @@ const RelatedFootLine: React.FC<{ */ const COLUMN_STACK = 'flex min-w-0 flex-col gap-4 [&>*:has(>[hidden]:only-child)]:hidden'; +/** The nearest ancestor of `el` that scrolls vertically, or `null`. */ +function scrollParentOf(el: HTMLElement): HTMLElement | null { + const view = el.ownerDocument.defaultView; + if (!view) return null; + for (let node = el.parentElement; node; node = node.parentElement) { + const overflowY = view.getComputedStyle(node).overflowY; + if (overflowY === 'auto' || overflowY === 'scroll') return node; + } + return null; +} + +/** The content-box width of `el`, measured before paint and on every resize; 0 while unknown. */ +function useContentWidth(el: HTMLElement | null): number { + const [width, setWidth] = React.useState(0); + React.useLayoutEffect(() => { + if (!el) return undefined; + const measure = () => setWidth(el.clientWidth); + measure(); + if (typeof ResizeObserver === 'undefined') return undefined; + const observer = new ResizeObserver(measure); + observer.observe(el); + return () => observer.disconnect(); + }, [el]); + return width; +} + +/** Below this, the pinned columns are not bounded: the page scrolls as one. */ +const PINNED_MIN_HEIGHT = 360; + +/** + * The height the pinned columns take so each scrolls on its own + * (objectstack#35890, card item 2): the rest of the scroller the page sits in, + * below the columns' top and above the paddings under them, so the page + * itself does not scroll. `null` — the columns flow with the page — with no + * scrolling ancestor (a test environment) or less room than + * {@link PINNED_MIN_HEIGHT}. + */ +function usePinnedHeight(grid: HTMLElement | null, frame: HTMLElement | null): number | null { + const [height, setHeight] = React.useState(null); + React.useLayoutEffect(() => { + if (!grid || !frame) { + setHeight(null); + return undefined; + } + const scroller = scrollParentOf(frame); + if (!scroller) { + setHeight(null); + return undefined; + } + const view = frame.ownerDocument.defaultView!; + const measure = () => { + const top = grid.getBoundingClientRect().top - scroller.getBoundingClientRect().top - scroller.clientTop + + scroller.scrollTop; + const below = (parseFloat(view.getComputedStyle(frame).paddingBottom) || 0) + + (parseFloat(view.getComputedStyle(scroller).paddingBottom) || 0); + const room = Math.floor(scroller.clientHeight - top - below); + setHeight(room >= PINNED_MIN_HEIGHT ? room : null); + }; + measure(); + if (typeof ResizeObserver === 'undefined') return undefined; + const observer = new ResizeObserver(measure); + observer.observe(scroller); + observer.observe(frame); + return () => observer.disconnect(); + }, [grid, frame]); + return height; +} + +/** How far one arrow-key press moves the pinned left column's edge. */ +const DETAILS_WIDTH_KEY_STEP = 16; + +/** + * The pinned left column's drag handle (objectstack#35890: 「左栏宽 400,可以 + * 拖宽,拖过的宽度按人记住」), sitting in the gap between the columns: a + * vertical separator, dragged with the pointer or moved with ← → (Home / End + * to either end). `onPreview` follows the drag; `onCommit` keeps the width + * once the drag ends. + */ +const DetailsWidthHandle: React.FC<{ + width: number; + max: number; + onPreview: (width: number | null) => void; + onCommit: (width: number) => void; +}> = ({ width, max, onPreview, onCommit }) => { + const { t } = useDetailTranslation(); + const drag = React.useRef<{ x: number; width: number; last: number } | null>(null); + const clamp = (w: number) => Math.round(Math.max(RECORD_PAGE_DETAILS_MIN_WIDTH, Math.min(w, max))); + return ( +
{ + if (event.button !== 0) return; + event.preventDefault(); + event.currentTarget.setPointerCapture?.(event.pointerId); + drag.current = { x: event.clientX, width, last: width }; + }} + onPointerMove={(event) => { + const start = drag.current; + if (!start) return; + start.last = clamp(start.width + event.clientX - start.x); + onPreview(start.last); + }} + onPointerUp={(event) => { + const start = drag.current; + drag.current = null; + event.currentTarget.releasePointerCapture?.(event.pointerId); + onPreview(null); + if (start && start.last !== start.width) onCommit(start.last); + }} + onPointerCancel={() => { + drag.current = null; + onPreview(null); + }} + onKeyDown={(event) => { + const next = + event.key === 'ArrowLeft' ? width - DETAILS_WIDTH_KEY_STEP + : event.key === 'ArrowRight' ? width + DETAILS_WIDTH_KEY_STEP + : event.key === 'Home' ? RECORD_PAGE_DETAILS_MIN_WIDTH + : event.key === 'End' ? max + : null; + if (next === null) return; + event.preventDefault(); + if (clamp(next) !== width) onCommit(clamp(next)); + }} + > +
+ ); +}; + /** * The synthesized default record page, laid out by the width it has * (objectstack#26678; one rule since objectstack#27524, Target 6): one record - * header, the record's tab row (objectstack#35595: 概览, one tab per related - * list in the reader's arrangement, 附件, 审批, then 动态 last — every tab - * there at first paint, an empty list muted with no number, the width the - * row's only fold), then the open tab's face. + * header, the record's tab row (objectstack#35595: 「详情」, one tab per + * related list in the reader's arrangement, 附件, 审批, then 动态 last — every + * tab there at first paint, an empty list muted with no number, the width the + * row's only fold), then the open tab's face drawn the full width. A page with + * only the details draws no tab row. * - * 概览 draws a strip the page places (`record:path`, `record:highlights`, a - * slotted page's `highlights`; the default page places none since - * objectstack#35891) across the whole width, then the details and the right - * rail — the summary of the other tabs - * (`RecordSummaryRail`, objectstack#35596: 审批, 附件, 最近动态, then the - * lists with records; a card with nothing to show is not drawn, and a rail - * known to have none folds away). Every other tab draws its block in full in - * place of all three. + * Pinned (objectstack#35890, figure 41; `recordPagePinsDetails` — a full page + * with room for both columns, another tab, and no related table among the + * fields): the details are a left column (400 px, dragged by the reader, and + * narrowing on their own to leave the tabs 400 — `clampDetailsWidth`), no + * longer a tab. Beside them sit the tab row without 「详情」 and the open + * tab, the first of the row when the address names none. The two scroll + * apart. Narrowed out of the pinned layout, the page keeps the tab it showed: + * the implied one is written to the address (`onEnlargeRelated` with + * `replace`). * - * - `two-column` / `wide`: details | the rail (320 / 380 px). The wide tier - * lets a details section take three field columns (two otherwise, - * `DetailsColumnCapContext`). The reader's ⊟ (`rightColumn`) takes the - * rail out; the details then take the row. A host that draws no rail (a - * drawer, `rail={false}`) draws the details alone. - * - `stack`: ONE column — the details, then the rail. + * A strip the page places (`record:path`, `record:highlights`, a slotted + * page's `highlights`; the default page places none since objectstack#35891) + * sits atop the details. The right rail of summary cards (objectstack#35596) + * is gone, at every width: each tab's count carries what it said. * * The frame mirrors the record page frame `PageRenderer` draws (its padding * and background, the header nodes 16 px apart), so the header sits where an * authored page's would. The nodes are the page's own — the same * `page:header`, `record:details`, `record:activity` and - * `record:related_list` nodes its tab strip holds — so every tier shows the + * `record:related_list` nodes its tab strip holds — so every width shows the * same header and the same sections. `data-record-columns-shown` names the * columns drawn side by side. */ @@ -347,8 +468,10 @@ export const RecordPageColumns: React.FC = ({ tier, columns, footer, - rightColumn = true, - rail = true, + fullPage = false, + detailsWidth, + onDetailsWidthChange, + onShownTabChange, relatedArrangement, onRelatedArrangementChange, onEnlargeRelated, @@ -360,15 +483,9 @@ export const RecordPageColumns: React.FC = ({ const { t } = useDetailTranslation(); const ctx = useRecordContext(); const bodyTableIds = React.useMemo(() => new Set(relatedListIdsIn(columns.details)), [columns.details]); - // objectstack#35941 — the details sections report the rows they draw, and - // the meta line closing the details column reads them: the owner is left - // off that line when a section already draws `owner_id`. const [bodyFields] = React.useState(createRecordBodyFields); const hasTimeline = columns.timeline.length > 0; - const wide = tier === 'wide'; - const besideDetails = tier !== 'stack'; - // ── The right column's blocks: the related lists, 附件 and 审批 ── const approvalsNode = columns.related.find((node) => node?.type === 'record:approvals'); const attachmentsNode = columns.related.find((node) => node?.type === 'record:attachments'); const panelNodes = new Map(); @@ -376,13 +493,7 @@ export const RecordPageColumns: React.FC = ({ const id = relatedNodeId(node); if (id && !panelNodes.has(id)) panelNodes.set(id, node); } - const hasPanels = hasTimeline || columns.related.length > 0; - // objectstack#35596 — the rail is the 概览 tab's, and a drawer draws none. - const drawsPanels = rail && hasPanels && (!besideDetails || rightColumn); - // ── The reader's arrangement of the related lists, read for the tab row ── - // A host without a preference store keeps the reader's choices here, for - // this view. const [localArrangement, setLocalArrangement] = React.useState(undefined); const arrangement = onRelatedArrangementChange ? relatedArrangement : localArrangement; const onArrangementChange = onRelatedArrangementChange ?? setLocalArrangement; @@ -390,9 +501,6 @@ export const RecordPageColumns: React.FC = ({ const defaultOrder = Array.from(panelNodes.keys()); const resolved = resolveRelatedArrangement(defaultOrder, arrangement, now); - // ── The related lists' counts, one set for the tabs and the rail ── - // The hidden lists are counted too: their tabs sit in the row's dropdown - // with their counts. const countTargets: RelatedCountTarget[] = []; for (const id of [...resolved.order, ...resolved.hidden]) { const target = relatedCountTargetOf(panelNodes.get(id)); @@ -407,14 +515,9 @@ export const RecordPageColumns: React.FC = ({ const state = counts.stateOf(id); return state.kind === 'counted' ? state.count : null; }; - // objectstack#35595 — 附件 counts the record's files; 审批 carries a dot - // while an approval waits. const attachmentCount = useRecordAttachmentCount(!!attachmentsNode); - const approvalPending = !!approvalsNode && approvalSummaryRows(nodeProps(approvalsNode).approvals, undefined) !== null; + const approvalPending = !!approvalsNode && approvalsHoldPendingRequest(nodeProps(approvalsNode).approvals); - // ── The 动态 stream's size, for its card and its tab ── - // Held per record, so a pane stepping to the next record never shows the - // last one's number; kept while neither face that reports it is drawn. const recordKey = ctx?.recordId === undefined || ctx?.recordId === null ? '' : String(ctx.recordId); const [timelineCount, setTimelineCount] = React.useState<{ record: string; count: number | null }>({ record: recordKey, @@ -428,94 +531,123 @@ export const RecordPageColumns: React.FC = ({ }, []); const streamCount = timelineCount.record === recordKey ? timelineCount.count : null; - // ── The active tab: the open face ── - // A related list, 附件, 审批 or the 动态 stream in full — body tables (in the - // details) open in place too (their ⤢), and take a tab of their own while - // open. - let enlarged: React.ReactNode = null; - let activeTab = RECORD_TAB_OVERVIEW; - let openBodyTable: RecordTab | null = null; + // ── The tabs after 「详情」, in the row's order ────────────────────────── const attachmentsTitle = t('detail.attachments', { defaultValue: 'Attachments' }); const approvalsTitle = t('detail.approvalsPanelTitle', { defaultValue: 'Approvals' }); + const timelineTitle = t('detail.timeline', { defaultValue: 'Activity' }); + const panelTab = (id: RelatedCardId): RecordTab => ({ + id, + label: relatedNodeTitle(panelNodes.get(id)), + count: countOf(id), + }); + const arrangedTab = (id: RelatedCardId, index: number): RecordTab => ({ + ...panelTab(id), + arrange: { before: index > 0, after: index < resolved.order.length - 1 }, + }); + // A body table the details draw (a field group places it) opens as a tab of + // its own while it is open: it has no tab of its own otherwise. + const bodyTableNode = + enlargedRelated && !panelNodes.has(enlargedRelated) + ? columns.details.find((n) => relatedNodeId(n) === enlargedRelated) + : undefined; + const otherTabs: RecordTab[] = resolved.order.map(arrangedTab); + if (bodyTableNode) otherTabs.push({ id: enlargedRelated!, label: relatedNodeTitle(bodyTableNode) }); + if (attachmentsNode) otherTabs.push({ id: RECORD_TAB_ATTACHMENTS, label: attachmentsTitle, count: attachmentCount }); + if (approvalsNode) otherTabs.push({ id: RECORD_TAB_APPROVALS, label: approvalsTitle, dot: approvalPending }); + if (hasTimeline) otherTabs.push({ id: RECORD_PAGE_TIMELINE_PANEL, label: timelineTitle, count: streamCount }); + const hiddenTabs = resolved.hidden.map(panelTab); + + // ── Pinned or not: the page content's own width decides ──────────────── + const [contentEl, setContentEl] = React.useState(null); + const [frameEl, setFrameEl] = React.useState(null); + const [gridEl, setGridEl] = React.useState(null); + const contentWidth = useContentWidth(contentEl); + const pinned = recordPagePinsDetails(contentWidth, columns, fullPage) && otherTabs.length > 0; + const pinnedHeight = usePinnedHeight(pinned ? gridEl : null, frameEl); + + // 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 + // narrows out of the pinned layout). + // A list the reader hid still opens: from its item in 「更多」, or from an + // address that names it (card acceptance: 「带页签参数的链接仍然打开对应页签」). + const requested = + enlargedRelated && (otherTabs.some((tab) => tab.id === enlargedRelated) || resolved.hidden.includes(enlargedRelated)) + ? enlargedRelated + : undefined; + const impliedTab = pinned && !requested ? otherTabs[0].id : undefined; + const openTab = requested ?? impliedTab; + const activeTab = openTab ?? RECORD_TAB_OVERVIEW; + + // Esc leaves a tab for 「详情」; pinned, the details are on screen already. + const closeFace = pinned ? undefined : onCloseEnlargedRelated; const blockFace = (id: string, title: string, node: any) => ( - + ); - if (enlargedRelated === RECORD_PAGE_TIMELINE_PANEL && hasTimeline) { - activeTab = RECORD_PAGE_TIMELINE_PANEL; - enlarged = ( - + let face: React.ReactNode = null; + if (openTab === RECORD_PAGE_TIMELINE_PANEL) { + face = ( + {drawNodes(columns.timeline)} ); - } else if (enlargedRelated === RECORD_SUMMARY_ATTACHMENTS && attachmentsNode) { - activeTab = RECORD_SUMMARY_ATTACHMENTS; - enlarged = blockFace(RECORD_SUMMARY_ATTACHMENTS, attachmentsTitle, attachmentsNode); - } else if (enlargedRelated === RECORD_SUMMARY_APPROVALS && approvalsNode) { - activeTab = RECORD_SUMMARY_APPROVALS; - enlarged = blockFace(RECORD_SUMMARY_APPROVALS, approvalsTitle, approvalsNode); - } else if (enlargedRelated) { - const node = [...columns.related, ...columns.details].find((n) => relatedNodeId(n) === enlargedRelated); + } else if (openTab === RECORD_TAB_ATTACHMENTS && attachmentsNode) { + face = blockFace(RECORD_TAB_ATTACHMENTS, attachmentsTitle, attachmentsNode); + } else if (openTab === RECORD_TAB_APPROVALS && approvalsNode) { + face = blockFace(RECORD_TAB_APPROVALS, approvalsTitle, approvalsNode); + } else if (openTab) { + const node = panelNodes.get(openTab) ?? bodyTableNode; if (node) { - activeTab = enlargedRelated; - if (!panelNodes.has(enlargedRelated)) openBodyTable = { id: enlargedRelated, label: relatedNodeTitle(node) }; - enlarged = ( - + face = ( + {enlargedRelatedList(node)} ); } } - // ── The tab row (objectstack#35595): 概览, every related list, 附件, 审批, 动态 ── - // Every related list has its tab whether or not it has records — muted and - // without a number at 0 — so no tab moves when the counts land; the width - // is the row's only fold (「更多 N ▾」, `RecordTabRow`). 动态 is the row's - // last tab (objectstack#34590). - const panelTab = (id: RelatedCardId): RecordTab => ({ - id, - label: relatedNodeTitle(panelNodes.get(id)), - count: countOf(id), - }); - // objectstack#35783 — a shown list's tab is the reader's to move one place - // either way among the lists, or to hide; the other tabs stay where they are. - const arrangedTab = (id: RelatedCardId, index: number): RecordTab => ({ - ...panelTab(id), - arrange: { before: index > 0, after: index < resolved.order.length - 1 }, - }); - const tabs: RecordTab[] = [{ id: RECORD_TAB_OVERVIEW, label: t('detail.recordTabOverview', { defaultValue: 'Overview' }) }]; - tabs.push(...resolved.order.map(arrangedTab)); - if (openBodyTable) tabs.push(openBodyTable); - if (attachmentsNode) tabs.push({ id: RECORD_SUMMARY_ATTACHMENTS, label: attachmentsTitle, count: attachmentCount }); - if (approvalsNode) tabs.push({ id: RECORD_SUMMARY_APPROVALS, label: approvalsTitle, dot: approvalPending }); - if (hasTimeline) { - tabs.push({ id: RECORD_PAGE_TIMELINE_PANEL, label: t('detail.timeline', { defaultValue: 'Activity' }), count: streamCount }); - } - const hiddenTabs = resolved.hidden.map(panelTab); + // Narrowed out of the pinned layout on the same record, the page keeps the + // tab it showed rather than falling back to 「详情」 (card acceptance: + // 「当前选中的页签不丢」): the implied tab goes into the address, replacing + // the entry, so Back still leaves the record. + const shownBefore = React.useRef<{ record: string; implied: string | undefined }>({ record: recordKey, implied: undefined }); + const otherTabIds = otherTabs.map((tab) => tab.id).join('\n'); + React.useEffect(() => { + const before = shownBefore.current; + shownBefore.current = { record: recordKey, implied: impliedTab }; + if (pinned || !before.implied || before.record !== recordKey || enlargedRelated) return; + if (!otherTabIds.split('\n').includes(before.implied)) return; + onEnlargeRelated?.(before.implied, { replace: true }); + }, [pinned, impliedTab, recordKey, enlargedRelated, otherTabIds, onEnlargeRelated]); + + // The host reads which tab is on screen (the 动态 tab reads its window when + // it is, addressed or implied). + React.useEffect(() => { + onShownTabChange?.(activeTab); + }, [activeTab, onShownTabChange]); + + const tabs: RecordTab[] = pinned + ? otherTabs + : [{ id: RECORD_TAB_OVERVIEW, label: t('detail.recordTabOverview', { defaultValue: 'Details' }) }, ...otherTabs]; const selectTab = (id: string) => { if (id === RECORD_TAB_OVERVIEW) onCloseEnlargedRelated?.(); - else onEnlargeRelated?.(id); + else if (id !== impliedTab) onEnlargeRelated?.(id); }; const editArrangement = (edit: RelatedArrangementEdit) => onArrangementChange(editRelatedArrangement(defaultOrder, arrangement, edit, now)); const arrangeTab = (id: string, edit: RecordTabArrangeEdit) => { if (edit === 'hide') { editArrangement({ kind: 'hide', id }); - // The open list hidden: its face goes with its tab, back to 概览. - if (id === activeTab) onCloseEnlargedRelated?.(); + if (id === requested) onCloseEnlargedRelated?.(); } else { editArrangement({ kind: edit === 'move-before' ? 'move-up' : 'move-down', id }); } }; const tabRow = - onEnlargeRelated && tabs.length + hiddenTabs.length > 1 ? ( + onEnlargeRelated && (pinned ? tabs.length + hiddenTabs.length > 0 : tabs.length + hiddenTabs.length > 1) ? ( = ({ } /> ) : null; + const defaultChangedHint = tabRow && resolved.defaultChanged ? ( + editArrangement({ kind: 'restore-default-order' })} /> + ) : null; + // A face without the 动态 tab open still names the stream's count on its + // tab (objectstack#27524): counted from the feed the host holds. + const probesTimelineCount = hasTimeline && !!tabRow && activeTab !== RECORD_PAGE_TIMELINE_PANEL; - // The provenance line closes the details column in every tier - // (objectstack#27055): it describes the record the details show. - const detailsColumn = ( -
+ const details = ( + <> + {/* objectstack#35595 — a strip the page places is the details' top. */} + {columns.strip.length > 0 && ( +
+ {drawNodes(columns.strip)} +
+ )} {drawDetailsNodes(columns.details)} {footer} -
+ ); - // objectstack#35596 — a rail with nothing to show takes no column: once - // every card is KNOWN to be absent (no approval waiting, no files, a - // counted stream with no entries, every list counted with no records — a - // refused count draws no card either — and nothing at the foot), the - // details take the row. While a count is still out the column stays, so a - // page whose cards land does not shift. A slotted chatter stream reports - // no count, so its card always draws. - const streamCounted = columns.timeline.some((node) => node?.type === 'record:activity'); - const railKnownEmpty = - !approvalPending - && (!attachmentsNode || attachmentCount === 0) - && (!hasTimeline || (streamCounted && streamCount === 0)) - && resolved.order.every((id) => { - const state = counts.stateOf(id); - return state.kind !== 'pending' && !(state.kind === 'counted' && state.count > 0); - }) - && resolved.hidden.length === 0 - && !resolved.rearranged - && !resolved.defaultChanged; - const drawsRail = drawsPanels && !railKnownEmpty; - const rightPanels = drawsRail ? ( - - ) : null; - // A face with no 动态 card drawn — another tab open, the right column - // switched off, or a drawer — still names the stream's count on the 动态 - // tab (objectstack#27524): counted from the feed the host holds. - // A rail folded away for want of cards still learns of a new entry: the - // probe counts for it, and the rail comes back with its 最近动态 card. - const probesTimelineCount = hasTimeline && activeTab !== RECORD_PAGE_TIMELINE_PANEL - && ((!!tabRow && (enlarged !== null || !drawsPanels)) || (enlarged === null && drawsPanels && !drawsRail)); - // Folded away, the rail keeps the size its card last read: a probe that - // cannot count (no feed held by the host — the stream reads its own) says - // nothing rather than unknown, so the rail does not come back empty. - const railFolded = enlarged === null && drawsPanels && !drawsRail; - const reportProbedCount = React.useCallback( - (count: number | null) => { - if (count !== null) reportTimelineCount(count); - }, - [reportTimelineCount], + + // The pinned left column's width: the reader's dragged one (the host's + // preference store, or this view's own), narrowed to leave the tabs room. + const [localDetailsWidth, setLocalDetailsWidth] = React.useState(undefined); + const askedDetailsWidth = onDetailsWidthChange ? detailsWidth : localDetailsWidth; + const [dragWidth, setDragWidth] = React.useState(null); + const leftWidth = dragWidth ?? clampDetailsWidth(askedDetailsWidth, contentWidth); + const maxLeftWidth = Math.max( + RECORD_PAGE_DETAILS_MIN_WIDTH, + contentWidth - RECORD_PAGE_PINNED_GAP - RECORD_PAGE_TABS_MIN_WIDTH, ); - const sideBySide = besideDetails && drawsRail; - const template = sideBySide ? (wide ? GRID_TEMPLATE.wide : GRID_TEMPLATE.twoColumn) : GRID_TEMPLATE.oneColumn; + const commitDetailsWidth = (width: number) => (onDetailsWidthChange ?? setLocalDetailsWidth)(width); + const bounded = pinnedHeight !== null; + + let body: React.ReactNode; + if (pinned) { + body = ( +
+
+ {details} +
+ +
+ {tabRow} + {defaultChangedHint} + {probesTimelineCount && } + {face} +
+
+ ); + } else { + body = ( + <> + {tabRow} + {defaultChangedHint} + {probesTimelineCount && } + {face ?? ( +
+
+ {details} +
+
+ )} + + ); + } return ( - +
= ({ className={cn('w-full bg-background px-3 pb-3 pt-3 md:px-4 md:pb-4 lg:px-6 lg:pb-6', className)} data-page-type="record" data-record-page-tier={tier} + data-record-page-pinned={pinned ? '' : undefined} > -
+
{drawNodes(columns.header)} - {tabRow} - {probesTimelineCount && ( - - )} - {enlarged ?? ( - <> - {/* objectstack#35595 — the stage path and the key fields are the - 概览 tab's top, across the whole width (both columns), and - no other tab's. */} - {columns.strip.length > 0 && ( -
- {drawNodes(columns.strip)} -
- )} -
- {detailsColumn} - {rightPanels} -
- - )} + {body}
diff --git a/ui/packages/plugin-detail/src/RecordSummaryRail.tsx b/ui/packages/plugin-detail/src/RecordSummaryRail.tsx deleted file mode 100644 index a685fbd5ae3..00000000000 --- a/ui/packages/plugin-detail/src/RecordSummaryRail.tsx +++ /dev/null @@ -1,544 +0,0 @@ -/** - * 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'; -import { ChevronRight } from 'lucide-react'; -import { cn, RelatedCountStore, useRelatedCountVersion } from '@object-ui/components'; -import { columnIdentity, composeParentScopeFilter, mergeFilterNodes, type FieldContainerLike } from '@object-ui/core'; -import { formatCurrency } from '@object-ui/fields'; -import { resolveFieldCurrency, useDisplayLocale, useLocalization, withFollowedParent } from '@object-ui/i18n'; -import { SchemaRenderer, toRenderableSchema, useRecordContext } from '@object-ui/react'; -import { RecordTimelinePanelContext, type RecordTimelinePanel } from './recordTimelineStream'; -import { resolveTitleField } from './synth/buildDefaultPageSchema'; -import type { RelatedCardId } from './synth/relatedArrangement'; -import { useDetailTranslation } from './useDetailTranslation'; - -/** - * The 概览 tab's right rail (objectstack#35596): one small summary card per - * other tab that has something to show, in a fixed order — 审批, 附件, 最近动态, - * then 「其他相关」 with one card per related list that HAS records. Each card - * is a title, a grey count (or a status), and at most three rows; the whole - * title opens its tab. A card with nothing in it is not drawn, and nothing - * stands in for the empty lists (no 「还有 N 个空关联」 line). Nothing in the - * rail is editable: no composer, no upload. - * - * The rail is a summary of the tabs, never a second copy of them: each card - * reads what the tab's own block reads (the approvals the host hands the - * `record:approvals` node, the record's `sys_attachment` rows, the 动态 - * stream, a related list's first rows) and the tab draws the whole. - */ - -/** The ids of the rail's own cards; a related card's id is its relationship id. */ -export const RECORD_SUMMARY_APPROVALS = 'approvals'; -export const RECORD_SUMMARY_ATTACHMENTS = 'attachments'; - -/** The most rows a summary card shows. */ -export const RECORD_SUMMARY_ROWS = 3; - -const rowsOf = (res: any): any[] => (Array.isArray(res) ? res : Array.isArray(res?.data) ? res.data : []); - -/** - * The rows a summary card draws, for one question (`null`: nothing to ask). - * The record page's one read (objectstack#27627) holds each list's first rows - * in the related-count store: `take` hands them over, once; without them the - * card reads for itself (`read`). The answer is kept per question, so an - * effect React runs twice (StrictMode) draws the rows it took instead of - * finding the hand-off spent and reading again. A refused read draws no rows. - */ -function useSummaryRows( - question: string | null, - take: () => Promise<{ rows: any[] }> | undefined, - read: () => Promise, -): any[] | null { - const [rows, setRows] = React.useState(null); - const asked = React.useRef<{ question: string; answer: Promise } | null>(null); - React.useEffect(() => { - if (question === null) return undefined; - let answer = asked.current?.question === question ? asked.current.answer : undefined; - if (!answer) { - const seeded = take(); - answer = (seeded ? seeded.then((res) => res.rows) : read()).catch(() => []); - asked.current = { question, answer }; - } - let cancelled = false; - void answer.then((next) => { - if (!cancelled) setRows(next); - }); - return () => { - cancelled = true; - }; - // `take` and `read` answer the question; it names everything they read. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [question]); - return rows; -} - -export interface RecordSummaryRelated { - id: RelatedCardId; - /** The tab's `record:related_list` node. */ - node: any; - /** Its count; `null` while unknown. Only a count above 0 draws a card. */ - count: number | null; -} - -export interface RecordSummaryRailProps { - /** The related lists, in the tab row's order. */ - related: readonly RecordSummaryRelated[]; - /** The 审批 tab's `record:approvals` node, when the page has one. */ - approvals?: any; - /** Whether the page has an 附件 tab, and the count it shows. */ - attachments?: { count: number | null } | null; - /** The 动态 tab's blocks, and the count the tab shows. */ - timeline: any[]; - timelineCount: number | null; - onTimelineCount: (count: number | null) => void; - /** Open a tab: the card's title. Absent: the titles open nothing. */ - onOpen?: (id: string) => void; - /** The child objects' field definitions the host holds. */ - fieldsOf?: (objectName: string) => FieldContainerLike; - /** Drawn after the cards (the related panels' hidden-line). */ - footer?: React.ReactNode; -} - -/** - * One summary card: radius 8, a 13 px title with its grey count, rows 26 px - * high (objectstack#35596 item 5). The title is one button, the card's whole - * header, ending in 「›」. - */ -export const RecordSummaryCard: React.FC<{ - id: string; - title: string; - count?: number | null; - status?: React.ReactNode; - onOpen?: (id: string) => void; - hidden?: boolean; - children?: React.ReactNode; -}> = ({ id, title, count, status, onOpen, hidden, children }) => ( - -); - -/** A card's row: 26 px, the text on the left and its value on the right. */ -const SummaryRow: React.FC<{ left: React.ReactNode; right?: React.ReactNode; title?: string }> = ({ left, right, title }) => ( -
  • - {left} - {right !== undefined && right !== null && right !== '' && ( - {right} - )} -
  • -); - -const SummaryRows: React.FC<{ children: React.ReactNode }> = ({ children }) => ( -
      {children}
    -); - -type PageNode = Record; - -const propsOf = (node: unknown): PageNode => { - const raw = (node && typeof node === 'object' ? node : {}) as PageNode; - return raw.properties && typeof raw.properties === 'object' ? { ...raw, ...raw.properties } : raw; -}; - -// ── 审批 ─────────────────────────────────────────────────────────────────── - -interface ApprovalStepRow { - key: string; - label: string; - state: 'done' | 'mine' | 'waiting'; - waitingOn?: string; -} - -/** - * The pending approval's steps, at most three, ending at the step it waits - * on: the request's own route (`flow_route`, the server's) when it carries - * one, else the pending step alone. `null` when nothing is pending — the card - * is drawn only while an approval runs (objectstack#35596 item 4). - */ -export function approvalSummaryRows(approvals: any, currentUserId: string | undefined): ApprovalStepRow[] | null { - const pending = approvals?.pendingRequest; - if (!pending || typeof pending !== 'object') return null; - const approvers: string[] = Array.isArray(pending.pending_approvers) ? pending.pending_approvers : []; - const mine = pending.viewer?.can_act === true || (!!currentUserId && approvers.includes(currentUserId)); - const names: Record = pending.pending_approver_names ?? {}; - const waitingOn = approvers.map((id) => names[id]).filter((n): n is string => typeof n === 'string' && n !== ''); - const currentLabel: string = pending.step_label || pending.current_step || pending.process_label || pending.process_name || ''; - const current: ApprovalStepRow = { - key: 'current', - label: currentLabel, - state: mine ? 'mine' : 'waiting', - ...(waitingOn.length > 0 ? { waitingOn: waitingOn.join(', ') } : {}), - }; - const steps: any[] = Array.isArray(pending.flow_route?.steps) ? pending.flow_route.steps : []; - const at = steps.findIndex((s) => s?.state === 'current'); - if (at < 0) return [current]; - const rows: ApprovalStepRow[] = steps - .slice(0, at) - .filter((s) => s?.state === 'done') - .map((s, i) => ({ key: `done-${s.id ?? i}`, label: String(s.label ?? s.id ?? ''), state: 'done' as const })); - rows.push({ ...current, label: String(steps[at].label ?? currentLabel) }); - return rows.slice(-RECORD_SUMMARY_ROWS); -} - -const ApprovalsSummary: React.FC<{ node: any; onOpen?: (id: string) => void }> = ({ node, onOpen }) => { - const { t } = useDetailTranslation(); - const p = propsOf(node); - const rows = approvalSummaryRows(p.approvals, p.currentUserId); - if (!rows) return null; - const stateText = (row: ApprovalStepRow) => - row.state === 'done' - ? t('detail.summaryApprovalDone', { defaultValue: 'Approved' }) - : row.state === 'mine' - ? t('detail.summaryApprovalMine', { defaultValue: 'Awaiting you' }) - : row.waitingOn - ? t('detail.summaryApprovalWaitingOn', { name: row.waitingOn, defaultValue: 'Waiting on {{name}}' }) - : t('detail.summaryApprovalWaiting', { defaultValue: 'Waiting' }); - return ( - - - {rows.map((row) => ( - {stateText(row)}} - /> - ))} - - - ); -}; - -// ── 附件 ─────────────────────────────────────────────────────────────────── - -/** - * The related-count store key the record's attachments are counted under: the - * synthetic relationship the 附件 tab badge probes (`page:tabs`), which the - * record page payload seeds and the panel takes its rows from. - */ -export const attachmentsCountField = (objectName: string): string => `attachments:${objectName}`; - -/** - * How many attachments the record holds, through the store the tab badge and - * the panel share: the probe is the badge's own (the `(parent_object, - * parent_id)` scope), so a page payload that seeded it answers at once. - * `null` while unknown, or with nothing to ask. - */ -export function useRecordAttachmentCount(enabled: boolean): number | null { - const ctx = useRecordContext(); - useRelatedCountVersion(); - const objectName = ctx?.objectName; - const parentId = ctx?.recordId === undefined || ctx?.recordId === null ? undefined : String(ctx.recordId); - const ds: any = ctx?.dataSource; - const field = objectName ? attachmentsCountField(objectName) : undefined; - const cached = enabled && field && parentId ? RelatedCountStore.get('sys_attachment', field, parentId) : undefined; - React.useEffect(() => { - if (!enabled || !field || !parentId || !ds || typeof ds.find !== 'function') return; - if (RelatedCountStore.get('sys_attachment', field, parentId) !== undefined) return; - const finder = (object: string, query: any) => - ds.find(object, { ...query, $filter: { parent_object: objectName, parent_id: parentId } }); - void RelatedCountStore.fetch(finder, 'sys_attachment', field, parentId).catch(() => 0); - }, [enabled, field, parentId, ds, objectName, cached]); - return typeof cached === 'number' ? cached : null; -} - -const formatSize = (bytes: unknown): string => { - if (typeof bytes !== 'number' || !Number.isFinite(bytes)) return ''; - if (bytes < 1024) return `${bytes} B`; - if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; - return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; -}; - -const AttachmentsSummary: React.FC<{ count: number | null; onOpen?: (id: string) => void }> = ({ count, onOpen }) => { - const { t } = useDetailTranslation(); - const ctx = useRecordContext(); - const ds: any = ctx?.dataSource; - const objectName = ctx?.objectName; - const parentId = ctx?.recordId === undefined || ctx?.recordId === null ? undefined : String(ctx.recordId); - const has = typeof count === 'number' && count > 0; - const rows = useSummaryRows( - has && ds && typeof ds.find === 'function' && objectName && parentId - ? JSON.stringify([objectName, parentId, count]) - : null, - // The payload's newest attachments, under the key the 附件 tab counts. - () => RelatedCountStore.takeRows('sys_attachment', attachmentsCountField(objectName!), parentId!, undefined, RECORD_SUMMARY_ROWS), - async () => - rowsOf( - await ds.find('sys_attachment', { - $filter: { parent_object: objectName, parent_id: parentId }, - $orderby: { created_at: 'desc' }, - $top: RECORD_SUMMARY_ROWS, - }), - ), - ); - if (!has) return null; - return ( - - {rows && rows.length > 0 && ( - - {rows.slice(0, RECORD_SUMMARY_ROWS).map((row, i) => ( - - ))} - - )} - - ); -}; - -// ── 最近动态 ──────────────────────────────────────────────────────────────── - -/** - * The 动态 card: the stream's own blocks in their peek face, the newest three, - * with no composer (`showCommentInput: false` — nothing in the rail is - * editable) and no 「查看全部」 of their own (the title opens the tab). It stays - * mounted, `hidden`, until the stream reports entries, because the count it - * shows is the one the stream reports. A slotted page's `record:chatter` / - * `record:discussion` stream reports no count, so its card is drawn as it - * comes — its first page of three, read-only (`feed.showCommentInput: false`, - * `feed.limit: 3`). - */ -const TimelineSummary: React.FC<{ - nodes: any[]; - count: number | null; - onCount: (count: number | null) => void; - onOpen?: (id: string) => void; - timelineId: string; -}> = ({ nodes, count, onCount, onOpen, timelineId }) => { - const { t } = useDetailTranslation(); - const panel = React.useMemo( - () => ({ entries: RECORD_SUMMARY_ROWS, onCount }), - [onCount], - ); - const peekNodes = React.useMemo(() => nodes.map(readOnlyStreamNode), [nodes]); - const counted = nodes.some((node) => node && typeof node === 'object' && node.type === 'record:activity'); - return ( - - ); -}; - -/** A stream block as the rail draws it: read-only, the newest few. */ -function readOnlyStreamNode(node: any): any { - if (!node || typeof node !== 'object') return node; - const props = node.properties ?? {}; - if (node.type === 'record:activity') return { ...node, properties: { ...props, showCommentInput: false } }; - if (node.type === 'record:chatter' || node.type === 'record:discussion') { - const feed = { ...(node.feed ?? {}), ...(props.feed ?? {}), showCommentInput: false, limit: RECORD_SUMMARY_ROWS }; - return { ...node, ...(node.feed ? { feed } : {}), properties: { ...props, feed } }; - } - return node; -} - -// ── 其他相关 ──────────────────────────────────────────────────────────────── - -// A list column's field: the one shared reader, canonical-first (objectui#3104). -const columnKey = (col: unknown): string | undefined => columnIdentity(col); - -const fieldMap = (fields: FieldContainerLike | undefined): Record => { - if (!fields) return {}; - if (Array.isArray(fields)) { - const out: Record = {}; - for (const f of fields as any[]) if (f && typeof f.name === 'string') out[f.name] = f; - return out; - } - return fields as Record; -}; - -const KEY_VALUE_TYPES = ['currency', 'select', 'status'] as const; - -/** - * The key value a related row shows beside its name (objectstack#35596 item - * 2): the list's first amount column, else its first status column — read off - * the list's declared columns, then the child's fields in order. - */ -export function relatedKeyValueField(columns: unknown, fields: FieldContainerLike | undefined): string | null { - const defs = fieldMap(fields); - const declared = Array.isArray(columns) ? columns.map(columnKey).filter((k): k is string => !!k) : []; - const keys = declared.length > 0 ? declared : Object.keys(defs); - for (const type of KEY_VALUE_TYPES) { - const hit = keys.find((k) => defs[k]?.type === type); - if (hit) return hit; - } - return null; -} - -const RelatedSummary: React.FC<{ - entry: RecordSummaryRelated; - onOpen?: (id: string) => void; - fieldsOf?: (objectName: string) => FieldContainerLike; -}> = ({ entry, onOpen, fieldsOf }) => { - const ctx = useRecordContext(); - const ds: any = ctx?.dataSource; - const parentId = ctx?.recordId; - const locale = useDisplayLocale(); - const { currency: tenantCurrency } = useLocalization(); - const p = propsOf(entry.node); - const objectName: string = p.objectName; - const relationshipField: string = p.relationshipField; - const title: string = typeof p.title === 'string' && p.title ? p.title : objectName; - const [fields, setFields] = React.useState(() => fieldsOf?.(objectName)); - const filterKey = JSON.stringify(p.filter ?? null); - // The child's field definitions: the host's, else the data source's. Read - // once per object; the scope filter and the row's name and value need them. - const defsRead = React.useRef<{ objectName: string; read: Promise } | null>(null); - const defsOf = (): Promise => { - if (defsRead.current?.objectName !== objectName) { - const held = fieldsOf?.(objectName); - const read: Promise = - held || !ds || typeof ds.getObjectSchema !== 'function' - ? Promise.resolve(held) - : Promise.resolve(ds.getObjectSchema(objectName)).then((schema: any) => schema?.fields, () => undefined); - defsRead.current = { objectName, read }; - } - return defsRead.current.read; - }; - React.useEffect(() => { - let cancelled = false; - void defsOf().then((defs) => { - if (!cancelled) setFields(defs); - }); - return () => { - cancelled = true; - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ds, objectName]); - const rows = useSummaryRows( - ds && typeof ds.find === 'function' && parentId !== undefined && parentId !== null - ? JSON.stringify([objectName, relationshipField, String(parentId), filterKey, entry.count]) - : null, - // The record page's one read (objectstack#27627) holds each list's first - // rows: take them rather than read again. - () => RelatedCountStore.takeRows(objectName, relationshipField, String(parentId), p.filter ?? undefined, RECORD_SUMMARY_ROWS), - async () => { - const scope = composeParentScopeFilter(relationshipField, parentId as string | number, await defsOf()); - return rowsOf(await ds.find(objectName, { $filter: mergeFilterNodes(scope, p.filter), $top: RECORD_SUMMARY_ROWS })); - }, - ); - - const defs = fieldMap(fields); - const nameField = resolveTitleField({ name: objectName, fields: defs } as any) ?? 'name'; - const valueField = relatedKeyValueField(p.columns, fields); - const valueOf = (row: any): string => { - if (!valueField) return ''; - const def = defs[valueField]; - const raw = row?.[valueField]; - if (raw === null || raw === undefined || raw === '') return ''; - if (def?.type === 'currency') { - const n = typeof raw === 'number' ? raw : Number(raw); - if (!Number.isFinite(n)) return ''; - const code = resolveFieldCurrency(def, tenantCurrency, withFollowedParent(row, def, ctx?.data as any)); - return formatCurrency(n, code, locale); - } - const options: any[] = Array.isArray(def?.options) ? def.options : []; - const option = options.find((o) => (o && typeof o === 'object' ? o.value : o) === raw); - return option && typeof option === 'object' && typeof option.label === 'string' ? option.label : String(raw); - }; - return ( - - {rows && rows.length > 0 && ( - - {rows.slice(0, RECORD_SUMMARY_ROWS).map((row, i) => { - const name = row?.[nameField] ?? row?.name ?? row?.id ?? ''; - return ; - })} - - )} - - ); -}; - -/** The 动态 tab's id (`RECORD_PAGE_TIMELINE_PANEL`), passed in to keep this file free of the page module. */ -const TIMELINE_ID = 'timeline'; - -export const RecordSummaryRail: React.FC = ({ - related, - approvals, - attachments, - timeline, - timelineCount, - onTimelineCount, - onOpen, - fieldsOf, - footer, -}) => { - const { t } = useDetailTranslation(); - const withRecords = related.filter((entry) => typeof entry.count === 'number' && entry.count > 0); - return ( - <> - {approvals && } - {attachments && } - {timeline.length > 0 && ( - - )} - {withRecords.length > 0 && ( - <> -

    - {t('detail.summaryOtherRelated', { defaultValue: 'Other related' })} -

    - {withRecords.map((entry) => ( - - ))} - - )} - {footer} - - ); -}; diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.readerArrangement-35595.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.readerArrangement-35595.test.tsx index 7dd6062a1fa..35171c16ebb 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.readerArrangement-35595.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.readerArrangement-35595.test.tsx @@ -90,32 +90,20 @@ describe('the reader\'s arrangement orders the tab row (objectstack#35595, carry expect(container.querySelector('[data-related-foot-line]')).toBeNull(); }); - it("draws the stored reader's order, and 「恢复默认顺序」 at the rail's foot restores the default", () => { - const onWrite = vi.fn(); + it("draws the stored reader's order; with the rail gone (objectstack#35890) no foot line — 「更多」 holds the reset", () => { const dragged = editRelatedArrangement(DEFAULT, undefined, { kind: 'move', id: 'call.lead_id', to: 0 }, Date.now()); - const { container } = render(); + const { container } = render(); expect(listTabs()).toEqual(['call.lead_id', 'task.lead_id', 'note.parent_id']); - const foot = container.querySelector('[data-record-column="right"] [data-related-foot-line]')!; - expect(foot).not.toBeNull(); - const restore = foot.querySelector('[data-related-restore-default-order]') as HTMLButtonElement; - expect(restore.textContent).toBe('Restore default order'); - fireEvent.click(restore); - expect(listTabs()).toEqual(DEFAULT); - expect(onWrite.mock.calls.at(-1)![0].order).toEqual([]); expect(container.querySelector('[data-related-foot-line]')).toBeNull(); + expect(document.querySelector('[data-record-tab-more]')).not.toBeNull(); }); - it('a hidden list leaves the row for the end of 「更多 N ▾」; the foot line brings it back', () => { + it('a hidden list leaves the row for the end of 「更多 N ▾」', () => { const hidden = editRelatedArrangement(DEFAULT, undefined, { kind: 'hide', id: 'task.lead_id' }, Date.now()); const { container } = render(); expect(listTabs()).toEqual(['note.parent_id', 'call.lead_id']); expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('More 1'); - const line = container.querySelector('[data-related-hidden-line]')!; - expect(line).toBeTruthy(); - fireEvent.click(line.querySelector('button')!); - expect(listTabs()).toEqual(DEFAULT); expect(container.querySelector('[data-related-hidden-line]')).toBeNull(); - expect(document.querySelector('[data-record-tab-more]')).toBeNull(); }); it('says when the default changed under a dragged order, and restores it', () => { @@ -130,13 +118,12 @@ describe('the reader\'s arrangement orders the tab row (objectstack#35595, carry expect(container.querySelector('[data-related-default-changed]')).toBeNull(); }); - it('CONTROL: the rail draws no card chrome — no ⠿ handle, no 隐藏, no related list drawn whole', () => { + it('CONTROL: no rail is drawn, so no list is drawn whole beside the details (objectstack#35890)', () => { const dragged = editRelatedArrangement(DEFAULT, undefined, { kind: 'move', id: 'call.lead_id', to: 0 }, Date.now()); const { container } = render(); - const rail = container.querySelector('[data-record-column="right"]')!; - expect(rail).not.toBeNull(); - expect(rail.querySelector('[data-related-card-id]')).toBeNull(); - expect(rail.querySelector('[data-node="record:related_list"]')).toBeNull(); + expect(container.querySelector('[data-record-column="right"]')).toBeNull(); + expect(container.querySelector('[data-related-card-id]')).toBeNull(); + expect(container.querySelector('[data-node="record:related_list"]')).toBeNull(); }); }); @@ -251,6 +238,45 @@ describe('a related tab\'s menu and 「更多」\'s reset (objectstack#35783)', expect(hiddenItem?.getAttribute('data-record-tab-menu-item')).toBe('note.parent_id'); }); + it('a hidden list still opens: from its item in 「更多」, and from an address that names it (objectstack#35890)', async () => { + const user = userEvent.setup(); + const hidden = editRelatedArrangement(DEFAULT, undefined, { kind: 'hide', id: 'note.parent_id' }, Date.now()); + const { container, unmount } = render(); + expect(listTabs()).toEqual(['task.lead_id', 'call.lead_id']); + await user.click(document.querySelector('[data-record-tab-more]') as HTMLElement); + await user.click( + document.querySelector('[data-record-tab-hidden][data-record-tab-menu-item="note.parent_id"]') as HTMLElement, + ); + expect(container.querySelector('[data-related-enlarged="note.parent_id"]')).not.toBeNull(); + unmount(); + // The address names the hidden list (?related=note.parent_id): its face opens. + const page = render( + , + ); + expect(page.container.querySelector('[data-related-enlarged="note.parent_id"]')).not.toBeNull(); + // CONTROL: an id naming no list still draws the columns. + page.rerender( + , + ); + expect(page.container.querySelector('[data-related-enlarged]')).toBeNull(); + }); + it('「更多」 ends with 「恢复默认顺序」 while the arrangement is not the default: the default order, every list shown — in a drawer too', async () => { const user = userEvent.setup(); const onWrite = vi.fn(); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.switches-27052.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.switches-27052.test.tsx deleted file mode 100644 index f36ff8b7cb3..00000000000 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.switches-27052.test.tsx +++ /dev/null @@ -1,88 +0,0 @@ -/** - * 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#27052 → objectstack#27524, Target 4 — `RecordPageColumns` with - * the reader's ONE switch, ⊟ (the right column). The timeline switch, its - * folded 「动态」 card and the related rail retired. Since objectstack#35596 the - * right column is the 概览 tab's summary rail (审批, 附件, 最近动态, 其他相关), - * so ⊟ takes the whole rail out, and the details take the row. The stack has no right column, so - * the switch does not reach it. The blocks are stubbed (each node draws its - * type), so what is measured is where each node lands. - */ - -import * as React from 'react'; -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, cleanup } from '@testing-library/react'; - -vi.mock('@object-ui/react', async (importOriginal) => ({ - ...(await importOriginal>()), - SchemaRenderer: ({ schema }: { schema: any }) => ( -
    {schema?.properties?.objectName ?? schema?.type}
    - ), -})); - -import { RecordPageColumns } from '../RecordPageColumns'; -import { buildDefaultPageColumns } from '../synth/recordPageColumns'; -import { buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; - -const page = buildDefaultPageSchema( - { name: 'lead', label: 'Lead', fields: { name: { name: 'name', type: 'text' } } }, - { - related: [ - { objectName: 'task', relationshipField: 'lead_id', title: 'Tasks' }, - { objectName: 'note', relationshipField: 'parent_id', title: 'Notes' }, - ], - }, -); -const columns = buildDefaultPageColumns(page)!; - -const column = (container: HTMLElement, name: string) => - container.querySelector(`[data-record-column="${name}"]`) as HTMLElement | null; -const nodesIn = (el: Element | null) => - Array.from(el?.querySelectorAll('[data-node]') ?? []).map((n) => n.getAttribute('data-node')); -const shown = (container: HTMLElement) => - container.querySelector('[data-record-columns]')?.getAttribute('data-record-columns-shown'); - -afterEach(() => cleanup()); - -describe('RecordPageColumns — the right-column switch ⊟ (objectstack#27052, objectstack#27524)', () => { - it('absent or on: details | the rail (objectstack#35596)', () => { - for (const rightColumn of [undefined, true]) { - const { container, unmount } = render(); - expect(shown(container)).toBe('details right'); - // The rail: no list drawn whole; the 最近动态 card mounted (hidden until the stream reports entries). - expect(nodesIn(column(container, 'right'))).toEqual(['record:activity']); - expect(column(container, 'right')!.querySelector('[data-record-summary-card="timeline"]')).not.toBeNull(); - unmount(); - } - }); - - for (const tier of ['wide', 'two-column'] as const) { - it(`off, ${tier}: the details alone take the row — no right column, no 动态 panel, no lists, no rail`, () => { - const { container } = render( - meta

    } />, - ); - expect(shown(container)).toBe('details'); - expect(column(container, 'right')).toBeNull(); - expect(container.querySelector('[data-record-timeline-panel]')).toBeNull(); - expect(container.querySelector('[data-record-summary-card]')).toBeNull(); - expect(container.querySelectorAll('[data-node="record:related_list"]')).toHaveLength(0); - expect(container.querySelector('[data-testid="record-related-rail-toggle"]')).toBeNull(); - expect(container.querySelector('[data-record-folded-timeline]')).toBeNull(); - expect(column(container, 'details')!.lastElementChild?.getAttribute('data-testid')).toBe('meta-footer'); - }); - } - - it('the stack does not read it: its rail follows the details whatever the switch says', () => { - const { container } = render(); - expect(shown(container)).toBe('details'); - expect(column(container, 'right')!.querySelector('[data-record-summary-card="timeline"]')).not.toBeNull(); - expect(nodesIn(column(container, 'right'))).toEqual(['record:activity']); - }); -}); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.tabRow-27524.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.tabRow-27524.test.tsx index 67e0f508189..13e99f09949 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.tabRow-27524.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.tabRow-27524.test.tsx @@ -68,7 +68,7 @@ beforeEach(() => RelatedCountStore._reset()); afterEach(() => cleanup()); describe('the record page tab row (objectstack#27524, Target 8)', () => { - it('sits at the bottom of the header: 概览, the panels in the reader\'s order, then 动态 (objectstack#34590)', () => { + it('sits at the bottom of the header: 详情, the panels in the reader\'s order, then 动态 (objectstack#34590)', () => { const stored = editRelatedArrangement(DEFAULT, undefined, { kind: 'move', id: 'call.lead_id', to: 0 }, Date.now()); const { container } = render( { // objectstack#34590 supersedes objectstack#27524 Target 8's 动态-second: 「「动态」在最后」 expect(tabIds()).toEqual(['overview', 'call.lead_id', 'task.lead_id', 'note.parent_id', RECORD_PAGE_TIMELINE_PANEL]); expect(activeTab()).toBe('overview'); - expect(document.querySelector('[data-record-tab="overview"]')?.textContent).toBe('Overview'); + // objectstack#35890 — the first tab holds only the fields now: 「详情」. + expect(document.querySelector('[data-record-tab="overview"]')?.textContent).toBe('Details'); // After the header nodes, before the page's columns. const frame = container.querySelector('[data-page-type="record"] > div')!; const children = Array.from(frame.children); @@ -108,7 +109,7 @@ describe('the record page tab row (objectstack#27524, Target 8)', () => { expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('More 1'); }); - it('each panel tab carries its count — the hidden ones counted too — and 动态 the stream\'s size', async () => { + it('each panel tab carries its count — the hidden ones counted too', async () => { const find = vi.fn(async (objectName: string, _query?: Record) => ({ data: [{ id: 'x' }], total: objectName === 'task' ? 2 : objectName === 'note' ? 0 : 5 })); const dataSource = { find, getObjectSchema: vi.fn(async () => ({ fields: {} })) }; const stored = editRelatedArrangement(DEFAULT, undefined, { kind: 'hide', id: 'call.lead_id' }, Date.now()); @@ -132,11 +133,10 @@ describe('the record page tab row (objectstack#27524, Target 8)', () => { expect(tabCount('note.parent_id')).toBeNull(); expect(document.querySelector('[data-record-tab="note.parent_id"]')?.hasAttribute('data-record-tab-empty')).toBe(true); expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('More 1'); - await waitFor(() => expect(tabCount(RECORD_PAGE_TIMELINE_PANEL)).toBe('7')); // The hidden list was counted as well: its tab sits in the dropdown with its count. const counted = find.mock.calls.filter((call) => call[1]?.$count === true); expect(counted.map((call) => call[0]).sort()).toEqual(['call', 'note', 'task']); - // One count set feeds the tabs and the rail: no relationship is counted twice. + // One count set feeds the tabs: no relationship is counted twice. expect(counted).toHaveLength(3); }); @@ -298,11 +298,11 @@ describe('the enlarged state is the active tab (objectstack#27524, Target 9)', ( expect(tabCount(RECORD_PAGE_TIMELINE_PANEL)).toBeNull(); }); - it('the right column switched off names the 动态 count too', async () => { + it('with no rail at any width (objectstack#35890), the details face names the 动态 count from the feed the host holds', async () => { const items = [{ id: 'c1', type: 'comment', actor: 'Ada', body: 'hi', createdAt: '2026-10-30T10:00:00Z' }]; const { container } = render( - + , ); expect(container.querySelector('[data-record-column="right"]')).toBeNull(); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx index d594d2e6ed0..b986189abb7 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx @@ -11,9 +11,9 @@ * synthesized record page laid out by one rule. The blocks themselves are * stubbed (each node draws its type, and reports the details column cap it * is drawn under), so what is measured here is the layout alone: where each - * node lands, that the header is drawn once, the 概览 tab's rail in the right - * column and its order (objectstack#35596, re-setting objectstack#34590), and - * each tier's measures. + * node lands, that the header is drawn once, the details pinned to a left + * column beside the other tabs on a wide full page (objectstack#35890), and + * that no width draws the right rail of summary cards any more. * * One describe (objectstack#35253) opts each `record:details` stub into * mounting the `DetailView` the real block mounts (`showHeader: false`, @@ -23,7 +23,7 @@ import * as React from 'react'; import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; -import { render, screen, cleanup, within, waitFor, fireEvent } from '@testing-library/react'; +import { render, screen, cleanup, within, waitFor, fireEvent, act } from '@testing-library/react'; import { RelatedCountStore } from '@object-ui/components'; import { RecordContextProvider } from '@object-ui/react'; @@ -31,21 +31,14 @@ const harness = vi.hoisted(() => ({ /** Set by the objectstack#35253 describe: a `record:details` stub mounts `body`. */ detailBodies: false, body: null as React.ComponentType | null, - /** Set by the objectstack#35596 describe: the size a stream block reports. */ - timelineCount: undefined as number | undefined, + /** The content width every element reports (jsdom lays nothing out). */ + width: 0, })); vi.mock('@object-ui/react', async (importOriginal) => { const { DetailsColumnCapContext } = await import('../defaultRecordPage'); - const { RecordTimelinePanelContext } = await import('../recordTimelineStream'); const Stub = ({ schema }: { schema: any }) => { const Body = harness.detailBodies && schema?.type === 'record:details' ? harness.body : null; - // objectstack#35596 — a stream block in the rail's 最近动态 card reports - // the stream's size, as the real one does. - const panel = React.useContext(RecordTimelinePanelContext); - React.useEffect(() => { - if (schema?.type === 'record:activity' && panel && harness.timelineCount !== undefined) panel.onCount(harness.timelineCount); - }, [panel, schema?.type]); return (
    {schema?.properties?.objectName ?? schema?.type} @@ -61,7 +54,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { import { RecordPageColumns } from '../RecordPageColumns'; import { buildDefaultPageColumns } from '../synth/recordPageColumns'; -import { buildDefaultHighlights, buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; +import { buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; import { DetailView } from '../DetailView'; import { InlineEditProvider } from '@object-ui/react'; @@ -81,56 +74,56 @@ const column = (container: HTMLElement, name: string) => const nodesIn = (el: HTMLElement | null) => Array.from(el?.querySelectorAll('[data-node]') ?? []).map((n) => n.getAttribute('data-node')); const grid = (container: HTMLElement) => container.querySelector('[data-record-columns]') as HTMLElement; +const tabNames = () => screen.queryAllByRole('tab').map((tab) => tab.getAttribute('data-record-tab')); -afterEach(() => cleanup()); +beforeEach(() => { + harness.width = 0; + vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(() => harness.width); +}); +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); -describe('RecordPageColumns — details | the right column (objectstack#27524, Target 6)', () => { - it('wide (≥ 1120): one header, details | right column at 380 px holding the rail, no tab strip without a host', () => { - const { container } = render( - meta

    } />, - ); - expect(container.querySelector('[data-record-page-tier="wide"]')).not.toBeNull(); - expect(screen.queryByRole('tablist')).toBeNull(); - expect(container.querySelectorAll('[data-node="page:header"]')).toHaveLength(1); - expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details right'); - expect(grid(container).className).toContain('grid-cols-[minmax(0,1fr)_23.75rem]'); - expect(nodesIn(column(container, 'details'))).toEqual(['record:details']); - // objectstack#35596 — the right column is the 概览 tab's rail: summary - // cards, never a related list drawn whole (the lists are tabs, - // objectstack#35595). With no counts read, only the 最近动态 card is - // mounted, hidden until the stream reports entries. - const right = column(container, 'right')!; - expect(right.querySelector('[data-node="record:related_list"]')).toBeNull(); - expect(nodesIn(right)).toEqual(['record:activity']); - expect((right.querySelector('[data-record-summary-card="timeline"]') as HTMLElement).hidden).toBe(true); - // No timeline column exists any more (「动态是面板,不是栏」). - expect(column(container, 'timeline')).toBeNull(); - // The meta line closes the details column (objectstack#27055). - expect(within(right).queryByTestId('meta-footer')).toBeNull(); - expect(column(container, 'details')!.lastElementChild?.getAttribute('data-testid')).toBe('meta-footer'); - // Wide: a details section may take three field columns. - expect(column(container, 'details')!.querySelector('[data-node="record:details"]')!.getAttribute('data-cap')).toBe('3'); - }); +describe('RecordPageColumns — no right rail at any width (objectstack#35890 retires objectstack#35596)', () => { + for (const tier of ['wide', 'two-column', 'stack'] as const) { + it(`${tier}: one header, the details alone the full width, the footer closing them, no summary card`, () => { + const { container } = render( + meta

    } />, + ); + expect(container.querySelector(`[data-record-page-tier="${tier}"]`)).not.toBeNull(); + expect(screen.queryByRole('tablist')).toBeNull(); + expect(container.querySelectorAll('[data-node="page:header"]')).toHaveLength(1); + expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details'); + expect(grid(container).className).toContain('grid-cols-1'); + expect(column(container, 'right')).toBeNull(); + 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'); + }); + } - it('two-column (760 – 1119): the right column at 320 px holding the rail — no toggle', () => { - const { container } = render(); - expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details right'); - expect(grid(container).className).toContain('grid-cols-[minmax(0,1fr)_20rem]'); - // objectstack#35596 — the rail's cards, not the lists themselves. - expect(nodesIn(column(container, 'right'))).toEqual(['record:activity']); - expect(screen.queryByRole('button', { name: /Related/ })).toBeNull(); - expect(container.querySelector('[data-testid="record-related-rail-toggle"]')).toBeNull(); - // Beside the 320 px column a details section takes two field columns at most. - expect(column(container, 'details')!.querySelector('[data-node="record:details"]')!.getAttribute('data-cap')).toBe('2'); + it('the retired `rightColumn` / `rail` props change nothing (the ⊟ switch went with the rail)', () => { + const drawn = (props: Record) => { + const { container, unmount } = render(); + const shown = grid(container).getAttribute('data-record-columns-shown'); + unmount(); + return shown; + }; + expect([drawn({}), drawn({ rightColumn: false }), drawn({ rail: true }), drawn({ rail: false })]).toEqual([ + 'details', 'details', 'details', 'details', + ]); }); - it('a page with nothing for the right column draws the details alone; the footer closes them', () => { + it('a page with nothing but its details draws them alone; the footer closes them', () => { const bare = buildDefaultPageColumns(buildDefaultPageSchema({ name: 'thing', fields: {} }, { hideDiscussion: true }))!; + harness.width = 1600; const { container } = render( - meta

    } />, + meta

    } />, ); - expect(column(container, 'details')).not.toBeNull(); - expect(column(container, 'right')).toBeNull(); + expect(container.querySelector('[data-record-page-pinned]')).toBeNull(); expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details'); expect(within(column(container, 'details')!).getByTestId('meta-footer')).toBeTruthy(); }); @@ -151,237 +144,179 @@ describe('RecordPageColumns — the tab row follows the header (objectstack#3574 }); }); -describe('RecordPageColumns — the stack (< 760, objectstack#27524, Target 6)', () => { - it('ONE column: the details and their footer, then the rail — no tabs without a host', () => { - const { container } = render( - meta

    } />, - ); - expect(container.querySelector('[data-record-page-tier="stack"]')).not.toBeNull(); - expect(screen.queryByRole('tablist')).toBeNull(); - expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details'); - expect(grid(container).className).toContain('grid-cols-1'); - // Details first, the panels after them, in one flow. - const [details, right] = Array.from(grid(container).children) as HTMLElement[]; - expect(details.getAttribute('data-record-column')).toBe('details'); - expect(right.getAttribute('data-record-column')).toBe('right'); - expect(details.lastElementChild?.getAttribute('data-testid')).toBe('meta-footer'); - // objectstack#35596 — the rail's cards, under the details. - expect(nodesIn(right)).toEqual(['record:activity']); - // The stack's details are the whole width: the section's own container decides. - expect(details.querySelector('[data-node="record:details"]')!.getAttribute('data-cap')).toBe('3'); - }); -}); - /** - * objectstack#35596 — the 概览 tab's right rail summarizes the other tabs, in - * a fixed order: 审批, 附件, 最近动态, then 「其他相关」 (one card per related - * list that has records). This re-sets objectstack#34590's column order (the - * related panels, then 动态 last): the related lists are tabs now - * (objectstack#35595), and the rail draws a card only for a tab that has - * something to show. The stack draws the same rail under the details. + * objectstack#35890 (figure 41) — on a full page with room for a 320 px left + * column and 400 px of tabs, the details are pinned left and the other tabs + * sit beside them, open on the first; the left column is 400 px, dragged by + * the reader, and narrows on its own to leave the tabs 400. */ -describe('RecordPageColumns — the rail: 审批, 附件, 最近动态, 其他相关 (objectstack#35596, re-setting objectstack#34590)', () => { - beforeEach(() => { - RelatedCountStore._reset(); - harness.timelineCount = 4; - }); - afterEach(() => { - harness.timelineCount = undefined; - }); - const relatedLists = [ - { objectName: 'task', relationshipField: 'lead_id', title: 'Tasks' }, - { objectName: 'note', relationshipField: 'parent_id', title: 'Notes' }, - { objectName: 'call', relationshipField: 'lead_id', title: 'Calls' }, - ]; - const PENDING = { - approvals: { - available: true, - requests: [{ id: 'req_1' }], - pendingRequest: { id: 'req_1', step_label: 'Manager review', pending_approvers: ['u2'], pending_approver_names: { u2: 'Wang' } }, - }, - }; - const synth = (opts: { files: boolean; approvals: boolean }) => - buildDefaultPageColumns( - buildDefaultPageSchema( - { - name: 'lead', - label: 'Lead', - fields: { name: { name: 'name', type: 'text' } }, - ...(opts.files ? { enable: { files: true } } : {}), - }, - { related: relatedLists, ...(opts.approvals ? { approvals: { count: 1, node: PENDING } } : {}) }, - ), - )!; - /** task 0 and call 0 are empty; note has 2; the record holds 5 files. */ - const TOTALS: Record = { task: 0, note: 2, call: 0, sys_attachment: 5 }; - const find = vi.fn(async (objectName: string) => ({ - data: TOTALS[objectName] ? [{ id: `${objectName}-1`, name: `${objectName} one` }] : [], - total: TOTALS[objectName] ?? 0, - })); - // A record of its own per draw: the count hook keeps a parent's first set. +describe('RecordPageColumns — the details pinned left on a wide full page (objectstack#35890)', () => { + beforeEach(() => RelatedCountStore._reset()); + const find = vi.fn(async () => ({ data: [], total: 0 })); let draws = 0; - const drawPage = (tier: 'wide' | 'two-column' | 'stack', cols: ReturnType, extra: Record = {}) => - render( + const drawPage = (cols: typeof columns, extra: Record = {}) => { + const onEnlargeRelated = vi.fn(); + const utils = render( ({ fields: {} })) } as any} > - meta

    } {...extra} /> + meta

    } + {...extra} + />
    , ); - /** The rail's cards as drawn (a `hidden` card is not drawn), in document order. */ - const cards = (container: HTMLElement) => - Array.from(column(container, 'right')?.querySelectorAll('[data-record-summary-card]') ?? []) - .filter((el) => !(el as HTMLElement).hidden) - .map((el) => el.getAttribute('data-record-summary-card')); - - const cases = [ - { files: false, approvals: false }, - { files: true, approvals: false }, - { files: false, approvals: true }, - { files: true, approvals: true }, - ]; - for (const tier of ['wide', 'two-column', 'stack'] as const) { - for (const opts of cases) { - it(`${tier}, attachments ${opts.files ? 'on' : 'off'}, approvals ${opts.approvals ? 'on' : 'off'}: the rail's order`, async () => { - const { container } = drawPage(tier, synth(opts)); - const expected = [ - ...(opts.approvals ? ['approvals'] : []), - ...(opts.files ? ['attachments'] : []), - 'timeline', - 'note.parent_id', - ]; - await waitFor(() => expect(cards(container)).toEqual(expected)); - // 「其他相关」 heads the related cards, after 最近动态. - const other = column(container, 'right')!.querySelector('[data-record-summary-other]')!; - const timeline = column(container, 'right')!.querySelector('[data-record-summary-card="timeline"]')!; - expect(timeline.compareDocumentPosition(other) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - // No related list is drawn whole in the rail: the lists are tabs. - expect(column(container, 'right')!.querySelector('[data-node="record:related_list"]')).toBeNull(); - if (tier === 'stack') { - const [details, rail] = Array.from(grid(container).children) as HTMLElement[]; - expect(details.getAttribute('data-record-column')).toBe('details'); - expect(rail.getAttribute('data-record-column')).toBe('right'); - expect(details.lastElementChild?.getAttribute('data-testid')).toBe('meta-footer'); - } else { - expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details right'); - } - }); - } - } + return { ...utils, onEnlargeRelated }; + }; - it('an empty card is absent, and nothing stands in for the empty lists (no 「还有 N 个空关联」)', async () => { - const { container } = drawPage('wide', synth({ files: false, approvals: false })); - await waitFor(() => expect(cards(container)).toContain('note.parent_id')); - expect(cards(container)).not.toContain('task.lead_id'); - expect(cards(container)).not.toContain('call.lead_id'); - expect(container.querySelector('[data-related-empty-fold]')).toBeNull(); - expect(container.textContent).not.toMatch(/还有\s*\d+\s*个空关联|more empty/i); + it('pins: details left at 400 px, one field a row; beside them the tabs without 「详情」, open on the first list', () => { + harness.width = 1184; + const { container } = drawPage(columns); + expect(container.querySelector('[data-record-page-pinned]')).not.toBeNull(); + expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details tabs'); + expect(grid(container).style.gridTemplateColumns).toBe('400px 24px minmax(0,1fr)'); + const details = column(container, 'details')!; + expect(nodesIn(details)).toEqual(['record:details']); + expect(details.querySelector('[data-node="record:details"]')!.getAttribute('data-cap')).toBe('1'); + expect(details.lastElementChild?.getAttribute('data-testid')).toBe('meta-footer'); + // The tab row is beside the details, never above both; 「详情」 is not a tab. + const tabs = column(container, 'tabs')!; + expect(within(tabs).getByRole('tablist')).toBeTruthy(); + expect(tabNames()).toEqual(['task.lead_id', 'note.parent_id', 'timeline']); + expect(screen.getByRole('tab', { selected: true }).getAttribute('data-record-tab')).toBe('task.lead_id'); + expect(tabs.querySelector('[data-related-enlarged="task.lead_id"]')).not.toBeNull(); + expect(nodesIn(tabs)).toContain('record:related_list'); + // Nothing is drawn twice, and there is no rail. + expect(container.querySelectorAll('[data-node="record:details"]')).toHaveLength(1); + expect(container.querySelector('[data-record-summary-card]')).toBeNull(); }); - it('CONTROL: a stream with no entries draws no 最近动态 card; the same page with entries does', async () => { - harness.timelineCount = 0; - const { container, unmount } = drawPage('wide', synth({ files: false, approvals: false })); - await waitFor(() => expect(cards(container)).toEqual(['note.parent_id'])); + it('opens on the address\'s tab when it names one; choosing the implied tab writes nothing', () => { + harness.width = 1184; + const { container, onEnlargeRelated, unmount } = drawPage(columns, { enlargedRelated: 'timeline' }); + expect(screen.getByRole('tab', { selected: true }).getAttribute('data-record-tab')).toBe('timeline'); + expect(column(container, 'tabs')!.querySelector('[data-related-enlarged="timeline"]')).not.toBeNull(); unmount(); - harness.timelineCount = 4; - RelatedCountStore._reset(); - const again = drawPage('wide', synth({ files: false, approvals: false })); - await waitFor(() => expect(cards(again.container)).toEqual(['timeline', 'note.parent_id'])); + const second = drawPage(columns); + fireEvent.click(screen.getByRole('tab', { name: /Tasks/ })); + expect(second.onEnlargeRelated).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('tab', { name: /Notes/ })); + expect(second.onEnlargeRelated).toHaveBeenCalledWith('note.parent_id'); + expect(onEnlargeRelated).not.toHaveBeenCalled(); }); - it('a card shows at most three rows, a grey count after its 14 px title, rows 26 px high, radius 8', async () => { - TOTALS.note = 9; - find.mockImplementation(async (objectName: string) => ({ - data: Array.from({ length: Math.min(TOTALS[objectName] ?? 0, 5) }, (_, i) => ({ id: `${objectName}-${i}`, name: `${objectName} ${i}` })), - total: TOTALS[objectName] ?? 0, - })); - try { - const { container } = drawPage('wide', synth({ files: false, approvals: false })); - const card = () => container.querySelector('[data-record-summary-card="note.parent_id"]') as HTMLElement | null; - await waitFor(() => expect(card()?.querySelectorAll('[data-record-summary-row]').length).toBe(3)); - expect(card()!.className).toContain('rounded-[8px]'); - const title = card()!.querySelector('[data-record-summary-card-title]')!; - expect(title.className).toContain('text-sm'); - const count = title.querySelector('[data-record-summary-card-count]')!; - expect(count.textContent).toBe('9'); - expect(count.className).toContain('text-muted-foreground'); - expect(card()!.querySelector('[data-record-summary-row]')!.className).toContain('h-[26px]'); - } finally { - TOTALS.note = 2; - find.mockImplementation(async (objectName: string) => ({ - data: TOTALS[objectName] ? [{ id: `${objectName}-1`, name: `${objectName} one` }] : [], - total: TOTALS[objectName] ?? 0, - })); - } + it('with no related list, the first other tab is 动态', () => { + harness.width = 1184; + const noLists = buildDefaultPageColumns(buildDefaultPageSchema({ name: 'thing', fields: {} }))!; + drawPage(noLists); + expect(tabNames()).toEqual(['timeline']); + expect(screen.getByRole('tab', { selected: true }).getAttribute('data-record-tab')).toBe('timeline'); }); - it('the whole title opens its tab', async () => { - const onEnlargeRelated = vi.fn(); - const { container } = drawPage('wide', synth({ files: true, approvals: true }), { onEnlargeRelated }); - await waitFor(() => expect(cards(container)).toEqual(['approvals', 'attachments', 'timeline', 'note.parent_id'])); - for (const id of ['approvals', 'attachments', 'timeline', 'note.parent_id']) { - fireEvent.click(container.querySelector(`[data-record-summary-card="${id}"] [data-record-summary-card-title]`)!); - expect(onEnlargeRelated).toHaveBeenLastCalledWith(id); - } + it('the left column narrows on its own to leave the tabs 400, down to 320; under that the page does not pin', () => { + harness.width = 744 + 80; + const { container, unmount } = drawPage(columns); + expect(grid(container).style.gridTemplateColumns).toBe('400px 24px minmax(0,1fr)'); + unmount(); + harness.width = 800; + const narrower = drawPage(columns); + expect(grid(narrower.container).style.gridTemplateColumns).toBe('376px 24px minmax(0,1fr)'); + narrower.unmount(); + harness.width = 744; + const least = drawPage(columns); + expect(grid(least.container).style.gridTemplateColumns).toBe('320px 24px minmax(0,1fr)'); + least.unmount(); + // CONTROL: one pixel less and the details are the first tab again. + harness.width = 743; + const tabbed = drawPage(columns); + expect(tabbed.container.querySelector('[data-record-page-pinned]')).toBeNull(); + expect(tabNames()[0]).toBe('overview'); }); - it('the rail is the 概览 tab\'s: another tab open draws none, and the strip leaves with it', async () => { - // A slotted page placing the strip: the default page draws none since - // objectstack#35891, and the columns still draw a placed one on 概览. - const lead = { name: 'lead', fields: { name: { type: 'text' }, email: { type: 'email' }, rating: { type: 'select' } } } as any; - const cols = buildDefaultPageColumns( - buildDefaultPageSchema(lead, { - related: relatedLists, - slots: { - highlights: buildDefaultHighlights(lead, { - highlightFields: ['email'], - statusField: 'rating', - stages: [{ value: 'hot', label: 'Hot' }], - }), - }, - }), + it('the reader\'s dragged width holds, clamped the same way; the handle moves it by keyboard', () => { + harness.width = 1184; + const onDetailsWidthChange = vi.fn(); + const { container } = drawPage(columns, { detailsWidth: 520, onDetailsWidthChange }); + expect(grid(container).style.gridTemplateColumns).toBe('520px 24px minmax(0,1fr)'); + const handle = screen.getByRole('separator'); + expect(handle.getAttribute('aria-valuenow')).toBe('520'); + expect(handle.getAttribute('aria-valuemin')).toBe('320'); + expect(handle.getAttribute('aria-valuemax')).toBe(String(1184 - 24 - 400)); + fireEvent.keyDown(handle, { key: 'ArrowRight' }); + expect(onDetailsWidthChange).toHaveBeenLastCalledWith(536); + fireEvent.keyDown(handle, { key: 'Home' }); + expect(onDetailsWidthChange).toHaveBeenLastCalledWith(320); + fireEvent.keyDown(handle, { key: 'End' }); + expect(onDetailsWidthChange).toHaveBeenLastCalledWith(760); + }); + + it('a drag previews and keeps the width once it ends', () => { + harness.width = 1184; + const onDetailsWidthChange = vi.fn(); + const { container } = drawPage(columns, { onDetailsWidthChange }); + const handle = screen.getByRole('separator'); + fireEvent.pointerDown(handle, { button: 0, clientX: 400, pointerId: 1 }); + fireEvent.pointerMove(handle, { clientX: 460, pointerId: 1 }); + expect(grid(container).style.gridTemplateColumns).toBe('460px 24px minmax(0,1fr)'); + expect(onDetailsWidthChange).not.toHaveBeenCalled(); + fireEvent.pointerUp(handle, { clientX: 460, pointerId: 1 }); + expect(onDetailsWidthChange).toHaveBeenCalledWith(460); + }); + + it('a drawer or pane (no `fullPage`) never pins: the details stay its first tab', () => { + harness.width = 1600; + const { container } = drawPage(columns, { fullPage: false }); + expect(container.querySelector('[data-record-page-pinned]')).toBeNull(); + expect(tabNames()).toEqual(['overview', 'task.lead_id', 'note.parent_id', 'timeline']); + expect(screen.getByRole('tab', { selected: true }).getAttribute('data-record-tab')).toBe('overview'); + }); + + it('a page whose field groups place a related table among the fields does not pin (objectstack#35889)', () => { + harness.width = 1600; + const withBody = buildDefaultPageColumns( + buildDefaultPageSchema( + { name: 'quote', label: 'Quote', fields: { name: { name: 'name', type: 'text' } } }, + { related: [{ objectName: 'quote_line', relationshipField: 'quote_id', title: 'Lines', isPrimary: true }] }, + ), )!; - expect(cols.strip.length).toBeGreaterThan(0); - const overview = drawPage('wide', cols, { onEnlargeRelated: vi.fn() }); - // CONTROL: on 概览 the rail and the strip are drawn, the strip above the columns. - expect(column(overview.container, 'right')).not.toBeNull(); - const strip = overview.container.querySelector('[data-record-overview-strip]')!; - expect(strip).not.toBeNull(); - expect(strip.compareDocumentPosition(grid(overview.container)) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(grid(overview.container).contains(strip)).toBe(false); - overview.unmount(); - const other = drawPage('wide', cols, { onEnlargeRelated: vi.fn(), enlargedRelated: 'note.parent_id' }); - expect(column(other.container, 'right')).toBeNull(); - expect(other.container.querySelector('[data-record-summary-card]')).toBeNull(); - expect(other.container.querySelector('[data-record-overview-strip]')).toBeNull(); - expect(other.container.querySelector('[data-node="record:highlights"]')).toBeNull(); - expect(other.container.querySelector('[data-node="record:path"]')).toBeNull(); + const { container } = drawPage(withBody); + expect(container.querySelector('[data-record-page-pinned]')).toBeNull(); + expect(tabNames()[0]).toBe('overview'); }); - it('a rail with nothing to show takes no column once every count is in; CONTROL: one list with records keeps it', async () => { - harness.timelineCount = 0; - TOTALS.note = 0; - try { - const { container, unmount } = drawPage('wide', synth({ files: false, approvals: false })); - await waitFor(() => expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details')); - expect(column(container, 'right')).toBeNull(); - unmount(); - } finally { - TOTALS.note = 2; - } - RelatedCountStore._reset(); - const again = drawPage('wide', synth({ files: false, approvals: false })); - await waitFor(() => expect(cards(again.container)).toEqual(['note.parent_id'])); - expect(grid(again.container).getAttribute('data-record-columns-shown')).toBe('details right'); + it('narrowed out of the pinned layout, the implied tab goes into the address (replacing), so it stays open', async () => { + const observed: Array<() => void> = []; + vi.stubGlobal('ResizeObserver', class { + constructor(callback: () => void) { observed.push(callback); } + observe() {} + unobserve() {} + disconnect() {} + }); + harness.width = 1184; + const { onEnlargeRelated } = drawPage(columns); + expect(screen.getByRole('tab', { selected: true }).getAttribute('data-record-tab')).toBe('task.lead_id'); + harness.width = 700; + act(() => observed.forEach((measure) => measure())); + await waitFor(() => expect(onEnlargeRelated).toHaveBeenCalledWith('task.lead_id', { replace: true })); + expect(onEnlargeRelated).toHaveBeenCalledTimes(1); + vi.unstubAllGlobals(); }); - it('a drawer draws no rail (`rail={false}`): the details alone, the tabs carry the rest', () => { - const { container } = drawPage('wide', synth({ files: true, approvals: true }), { rail: false }); - expect(column(container, 'right')).toBeNull(); - expect(container.querySelector('[data-record-summary-card]')).toBeNull(); - expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details'); + it('tells the host which tab is on screen, implied or addressed', () => { + harness.width = 1184; + const onShownTabChange = vi.fn(); + drawPage(columns, { onShownTabChange }); + expect(onShownTabChange).toHaveBeenLastCalledWith('task.lead_id'); + cleanup(); + harness.width = 0; + drawPage(columns, { onShownTabChange }); + expect(onShownTabChange).toHaveBeenLastCalledWith('overview'); }); }); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel.chatterInset-34676.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel.chatterInset-34676.test.tsx index 3917de4d6ea..462cfa60bf0 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel.chatterInset-34676.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel.chatterInset-34676.test.tsx @@ -14,14 +14,13 @@ * timeline's panel face — the 全部动态 filter, full rows — which pads only its * top, so its icons and long rows would sit on the card's border. * - * objectstack#35596 moved the card into the 概览 tab's rail as 「最近动态」 - * (`RecordSummaryRail`, replacing `RecordTimelinePanel` on the page): the - * same inset holds there, and nothing in the rail is editable — neither face - * offers a composer. + * objectstack#35596 moved the card into the 概览 tab's rail as 「最近动态」; + * objectstack#35890 retired the rail, so on the record page the chatter block + * is drawn only in the 动态 tab, de-boxed. * * Drawn here through the real default record page (`buildDefaultPageSchema` * → `buildDefaultPageColumns` → `RecordPageColumns`, real block renderers), so - * the chatter node lands in the rail's card the way it does on the page. + * the chatter node lands in the 动态 tab the way it does on the page. * jsdom lays nothing out, so the pins read the classes that make the inset. */ @@ -54,8 +53,6 @@ const chatterColumns = () => slots: { discussion: { type: 'record:chatter', id: 'account_chatter', label: 'Discussion', properties: {} } }, } as any), )!; -/** The synthesized default: the `record:activity` stream. */ -const activityColumns = () => buildDefaultPageColumns(buildDefaultPageSchema(OBJECT as any, {}))!; function draw(columns: ReturnType, enlarged?: string) { return render( @@ -70,62 +67,11 @@ function draw(columns: ReturnType, enlarged?: string) { ); } -const classesOf = (el: Element | null | undefined) => (el?.getAttribute('class') ?? '').split(/\s+/).filter(Boolean); -const hasInlinePadding = (el: Element | null | undefined) => - classesOf(el).some((c) => /^(px|pl|pr|p)-/.test(c)); const CARD = '[data-record-summary-card="timeline"]'; -describe('the rail\'s 最近动态 card holding a record:chatter block (objectstack#34676, objectstack#35596)', () => { - it('the chatter timeline is inset inside the card: horizontal and bottom padding, one divider under the head', () => { - const { container } = draw(chatterColumns()); - const panel = container.querySelector(CARD) as HTMLElement; - expect(panel).not.toBeNull(); - // A chatter stream reports no count: its card is drawn as it comes. - expect(panel.hidden).toBe(false); - // The block in the card is the chatter's panel face (filter), not a peek. - expect(panel.querySelector('[data-record-timeline-peek]')).toBeNull(); - const timeline = panel.querySelector('section[aria-label="Discussion"]') as HTMLElement; - expect(timeline).not.toBeNull(); - // Nothing in the rail is editable (objectstack#35596): no composer. - expect(timeline.querySelector('textarea')).toBeNull(); - const cls = classesOf(timeline); - // Inset on both sides and at the foot, like the related panels' rows (px-3). - expect(cls).toContain('px-3'); - expect(cls).toContain('py-3'); - expect(cls).not.toContain('pt-5'); - // One divider between the panel head and the body, in the card's border colour. - expect(cls).toContain('border-t'); - expect(cls).toContain('border-border'); - expect(cls).not.toContain('border-border/60'); - // Nothing between the card and the timeline pads or borders it a second time. - for (let el = timeline.parentElement; el && el !== panel; el = el.parentElement) { - expect(hasInlinePadding(el)).toBe(false); - expect(classesOf(el).some((c) => c === 'border' || c.startsWith('border-t') || c.startsWith('border-l'))).toBe(false); - } - }); - - it('CONTROL — record:activity in the same card keeps its peek face, edge to edge, rows padding themselves', () => { - const { container } = draw(activityColumns()); - const panel = container.querySelector(CARD) as HTMLElement; - const peek = panel.querySelector('[data-record-timeline-peek]') as HTMLElement; - expect(peek).not.toBeNull(); - // The peek root carries no class of its own: its rows bleed to the card's edge. - expect(peek.getAttribute('class')).toBeNull(); - for (let el = peek.parentElement; el && el !== panel; el = el.parentElement) { - expect(hasInlinePadding(el)).toBe(false); - } - const rows = Array.from(panel.querySelectorAll('[data-record-timeline-peek-row]')); - // The newest three (the rail's row cap), each padding itself. - expect(rows).toHaveLength(3); - for (const row of rows) { - expect(row.getAttribute('class')).toBe('flex h-8 items-center gap-2 border-t border-border px-3 text-sm'); - } - // Read-only: the peek's composer is not offered in the rail. - expect(panel.querySelector('[data-record-timeline-composer]')).toBeNull(); - }); - - it('CONTROL — the 动态 tab draws the same chatter block with no card, so no inset: the de-boxed face', () => { +describe('the 动态 tab holding a record:chatter block (objectstack#34676; the rail card retired, objectstack#35890)', () => { + it('the 动态 tab draws the chatter block with no card, so no inset: the de-boxed face', () => { const { container } = draw(chatterColumns(), RECORD_PAGE_TIMELINE_PANEL); const face = container.querySelector(`[data-related-enlarged="${RECORD_PAGE_TIMELINE_PANEL}"]`) as HTMLElement; expect(face).not.toBeNull(); diff --git a/ui/packages/plugin-detail/src/defaultRecordPage.ts b/ui/packages/plugin-detail/src/defaultRecordPage.ts index ac23ce05ea8..7844fbf6912 100644 --- a/ui/packages/plugin-detail/src/defaultRecordPage.ts +++ b/ui/packages/plugin-detail/src/defaultRecordPage.ts @@ -141,12 +141,12 @@ export function useApprovalBandOnce(): { draws: boolean; mark: React.ReactNode } /** * The most columns a frameless detail section may take on the page being - * drawn (objectstack#27524, Target 6): the record page's layout sets 2 in its - * two-column tier, where the details share the row with the 320 px right - * column, and leaves 3 in the wide tier and the stack, where the section's - * own container width decides. 3 anywhere else. + * 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. */ -export const DetailsColumnCapContext = React.createContext<2 | 3>(3); +export const DetailsColumnCapContext = React.createContext<1 | 2 | 3>(3); /** * How many columns a frameless detail section lays its fields in, by the @@ -154,8 +154,8 @@ export const DetailsColumnCapContext = React.createContext<2 | 3>(3); * 1–3 列」): one field takes one column, two to five take two, six and more * take three — never more than `cap` ({@link DetailsColumnCapContext}). */ -export function framelessSectionColumns(visibleFieldCount: number, cap: 2 | 3 = 3): 1 | 2 | 3 { - if (visibleFieldCount <= 1) return 1; +export function framelessSectionColumns(visibleFieldCount: number, cap: 1 | 2 | 3 = 3): 1 | 2 | 3 { + if (visibleFieldCount <= 1 || cap === 1) return 1; if (visibleFieldCount <= 5 || cap === 2) return 2; return 3; } diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 06895dc9686..cfbf3878a66 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -213,6 +213,9 @@ export type { // details and panels, and the layout. export { RECORD_PAGE_TWO_COLUMN_MIN_WIDTH, + RECORD_PAGE_DETAILS_WIDTH, + RECORD_PAGE_PIN_MIN_WIDTH, + recordPagePinsDetails, recordPageTierFor, recordPageTierHasRightColumn, buildDefaultPageColumns, diff --git a/ui/packages/plugin-detail/src/recordTabBadges.ts b/ui/packages/plugin-detail/src/recordTabBadges.ts new file mode 100644 index 00000000000..9930be010f7 --- /dev/null +++ b/ui/packages/plugin-detail/src/recordTabBadges.ts @@ -0,0 +1,55 @@ +/** + * 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'; +import { RelatedCountStore, useRelatedCountVersion } from '@object-ui/components'; +import { useRecordContext } from '@object-ui/react'; + +/** + * The ids of the record page's 审批 and 附件 tabs, which the host's + * `?related=` names (a related list's tab id is its relationship id). + */ +export const RECORD_TAB_APPROVALS = 'approvals'; +export const RECORD_TAB_ATTACHMENTS = 'attachments'; + +/** Whether the approvals a `record:approvals` node carries hold a pending request (the 审批 tab's dot). */ +export function approvalsHoldPendingRequest(approvals: unknown): boolean { + const pending = (approvals as { pendingRequest?: unknown } | null | undefined)?.pendingRequest; + return !!pending && typeof pending === 'object'; +} + +/** + * The related-count store key the record's attachments are counted under: the + * synthetic relationship the 附件 tab badge probes (`page:tabs`), which the + * record page payload seeds and the panel takes its rows from. + */ +export const attachmentsCountField = (objectName: string): string => `attachments:${objectName}`; + +/** + * How many attachments the record holds, through the store the tab badge and + * the panel share: the probe is the badge's own (the `(parent_object, + * parent_id)` scope), so a page payload that seeded it answers at once. + * `null` while unknown, or with nothing to ask. + */ +export function useRecordAttachmentCount(enabled: boolean): number | null { + const ctx = useRecordContext(); + useRelatedCountVersion(); + const objectName = ctx?.objectName; + const parentId = ctx?.recordId === undefined || ctx?.recordId === null ? undefined : String(ctx.recordId); + const ds: any = ctx?.dataSource; + const field = objectName ? attachmentsCountField(objectName) : undefined; + const cached = enabled && field && parentId ? RelatedCountStore.get('sys_attachment', field, parentId) : undefined; + React.useEffect(() => { + if (!enabled || !field || !parentId || !ds || typeof ds.find !== 'function') return; + if (RelatedCountStore.get('sys_attachment', field, parentId) !== undefined) return; + const finder = (object: string, query: any) => + ds.find(object, { ...query, $filter: { parent_object: objectName, parent_id: parentId } }); + void RelatedCountStore.fetch(finder, 'sys_attachment', field, parentId).catch(() => 0); + }, [enabled, field, parentId, ds, objectName, cached]); + return typeof cached === 'number' ? cached : null; +} diff --git a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts index 832c10e4090..dd005312560 100644 --- a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts +++ b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts @@ -16,19 +16,23 @@ * one rule wherever it is drawn (the page, the split pane, the overlay drawer, * the maximized pane, a phone): * - * - 760 px and up: details | the right rail (320 px) — the 概览 tab's - * summary of the other tabs (objectstack#35596: 审批, 附件, 最近动态, then - * the related lists with records); - * - 1120 px and up: the same, wide — the details field grid takes three - * columns, the right rail 380 px; - * - below 760 px: ONE column — the details sections, then the rail. + * - a full page with room for a 320 px left column and 400 px of tabs + * (objectstack#35890, figure 41, `RECORD_PAGE_PIN_MIN_WIDTH`): the details + * pinned to a left column (400 px, the reader may drag it; it narrows on + * its own to leave the tabs 400), the other tabs beside it — the tab row + * without the details, open on its first tab — each side scrolling on its + * own; + * - anywhere else (narrower, a drawer, a pane, a phone, a page with no other + * tab, or one whose field groups place a related table): the tab row with + * the details as its first tab, 「详情」, the open tab drawn the full width. + * The field grid takes up to three columns; pinned, one. * - * (Container widths — see the two constants for how they are derived.) Above - * the columns sit the header, the record's tab row — 概览, one tab per related - * list, 附件, 审批, 动态 (objectstack#35595) — and, on 概览 only, the strip - * (`record:path`, `record:highlights`) across the whole width. Every other - * tab draws its block in full in place of the columns; the 动态 stream is a - * tab, never a column. + * (Container widths — see the two constants for how they are derived.) The + * tab row is the details, one tab per related list, 附件, 审批, 动态 + * (objectstack#35595); a page with only the details draws none. A strip the + * page places (`record:path`, `record:highlights`) sits atop the details. + * The right rail of summary cards (objectstack#35596) is gone: each tab's + * count carries what it said (objectstack#35890). * * ## Why the layout is derived, never authored * @@ -127,11 +131,78 @@ export function recordPageTierFor(width: number): RecordPageTier { return 'stack'; } -/** Whether a tier draws the right column beside the details (`⊟` applies). */ +/** + * Whether a tier is one that drew the right rail beside the details. + * + * @deprecated No tier draws a right rail since objectstack#35890; the pinned + * layout is {@link recordPagePinsDetails}. Kept, answering as it did, for a + * caller that still reads it. + */ export function recordPageTierHasRightColumn(tier: RecordPageTier | null | undefined): boolean { return tier === 'two-column' || tier === 'wide'; } +/** The pinned left column's width when the reader never dragged it (objectstack#35890). */ +export const RECORD_PAGE_DETAILS_WIDTH = 400; +/** + * The narrowest the pinned left column gets, dragged or yielding room to the + * tabs beside it (objectstack#35890). + */ +export const RECORD_PAGE_DETAILS_MIN_WIDTH = 320; +/** The least the pinned layout keeps for the tabs beside the left column. */ +export const RECORD_PAGE_TABS_MIN_WIDTH = 400; +/** The gap between the pinned left column and the tabs; the drag handle sits in it. */ +export const RECORD_PAGE_PINNED_GAP = 24; + +/** + * The narrowest page content (inside the page's padding) that pins the + * details (objectstack#35890): the narrowest left column, the gap and the + * least the tabs keep. ONE rule decides both whether the page pins and how + * wide the left column is ({@link clampDetailsWidth}): a narrower page — a + * window without room, or a page the comment panel narrowed — keeps the + * details as its first tab. + */ +export const RECORD_PAGE_PIN_MIN_WIDTH = + RECORD_PAGE_DETAILS_MIN_WIDTH + RECORD_PAGE_PINNED_GAP + RECORD_PAGE_TABS_MIN_WIDTH; + +/** + * Whether the synthesized record page pins its details to a left column, the + * other tabs beside it (objectstack#35890, figure 41): only on a full page (a + * drawer or a pane keeps the details as its first tab), only when its content + * is at least {@link RECORD_PAGE_PIN_MIN_WIDTH} wide, only when the page has + * another tab to put beside them, and never when a field group places a + * related table among the fields (objectstack#35889) — a table does not fit + * the left column, so that page keeps the details as its full-width first tab. + * An unknown width (zero or not a number) never pins. + */ +export function recordPagePinsDetails( + contentWidth: number, + columns: Pick | null | undefined, + fullPage: boolean, +): boolean { + if (!fullPage || !columns || !(contentWidth >= RECORD_PAGE_PIN_MIN_WIDTH)) return false; + if (columns.timeline.length === 0 && columns.related.length === 0) return false; + return relatedListIdsIn(columns.details).length === 0; +} + +/** + * The width the pinned left column takes in page content `contentWidth` CSS + * px wide, from the reader's dragged `width` (absent: {@link + * RECORD_PAGE_DETAILS_WIDTH}): never under {@link + * RECORD_PAGE_DETAILS_MIN_WIDTH}, and yielding to the tabs beside it, which + * keep at least {@link RECORD_PAGE_TABS_MIN_WIDTH} — the left column narrows + * on its own when room is short, and takes the asked width back when it + * returns. An unknown content width keeps the width asked, clamped from + * below. + */ +export function clampDetailsWidth(width: number | undefined, contentWidth: number): number { + const asked = typeof width === 'number' && Number.isFinite(width) ? width : RECORD_PAGE_DETAILS_WIDTH; + const max = contentWidth > 0 + ? contentWidth - RECORD_PAGE_PINNED_GAP - RECORD_PAGE_TABS_MIN_WIDTH + : Number.POSITIVE_INFINITY; + return Math.round(Math.max(RECORD_PAGE_DETAILS_MIN_WIDTH, Math.min(asked, max))); +} + /** * The 动态 tab's id in the host's `?related=` (objectstack#27524, Target 5): * the 动态 panel's 「查看全部 N 条 →」 opens it, beside the related lists'