diff --git a/.changeset/35446-list-narrow-fixed-columns.md b/.changeset/35446-list-narrow-fixed-columns.md new file mode 100644 index 00000000000..75e9d006942 --- /dev/null +++ b/.changeset/35446-list-narrow-fixed-columns.md @@ -0,0 +1,15 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/components': patch +'@object-ui/app-shell': patch +--- + +fix(grid): a list in a narrowed main area keeps every data cell clear of its fixed columns, shows its horizontal scrollbar, and draws a short header + +Clause-②: no +Metadata-protocol: none + +- **Row actions column.** While a list's table is wider than its box (the AI panel docked, a small window, the record drawer open), the row actions column (the row's "⋮") is drawn right after the frozen name column and frozen with it, instead of pinned to the right edge, where it covered the data column reaching that edge (an amount cut to 「¥94,0」). Every data column then scrolls sideways under the frozen columns, and none is covered at rest. Once the box is wide enough for the whole table again, the column goes back to the right edge, so a list that fits looks as before. Inline primary row actions still fold into the "⋮" menu first, as before. Columns an author pinned to the right stay where the author put them; the grouped list is unchanged. +- **Horizontal scrollbar.** A table wider than its box draws its scrollbar at rest instead of only while the pointer is over it, so columns out of view are announced. A table that fits keeps the scrollbar that shows on hover. +- **List header.** While the list page's header is narrower than 768 px, it draws no description, and Import moves into the 「⋯」 menu beside New. A wider header is unchanged. This is opt-in: the console `PageHeader` gains `compactBelow` (a width in px; below it the one-row header drops its description and draws its folded actions), which only the list page passes, so other pages that use `PageHeader` are unchanged. Setup's two-line header ignores it. +- No column is hidden and no column configuration changes. diff --git a/ui/e2e/list-header-narrow-35446.spec.ts b/ui/e2e/list-header-narrow-35446.spec.ts new file mode 100644 index 00000000000..eb2aa7496d2 --- /dev/null +++ b/ui/e2e/list-header-narrow-35446.spec.ts @@ -0,0 +1,382 @@ +import { test, expect, type Page } from '@playwright/test'; +import { compile } from 'tailwindcss'; +import { build, type Plugin, type Rollup } from 'vite'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { uiRoot } from '../scripts/ui-root.mjs'; + +/** + * GEOMETRY pin for objectstack#35446, the header half: an app list whose main + * area narrows (the AI panel docked, a small window, the record drawer open) + * draws a short header row: the title, New, and the 「⋯」 menu holding Import; + * the description is not drawn. A full-width list keeps its description and + * its Import button, as before. + * + * ## The rule + * + * The list page opts into `PageHeader`'s compact form (`compactBelow` in + * `ObjectViewPageHeader`): below that width of the header itself, the header + * drops the description and draws the folded actions. Other `PageHeader` pages + * pass nothing and are unchanged. + * + * ## Why a Playwright spec and not a vitest test + * + * The rule reads the header's own width; happy-dom lays nothing out. The + * vitest harness (`PageHeader.actionsFold-12705.test.tsx`) pins the logic + * against a width model; this spec pins it against Chromium's layout, through + * the list page's own header component. The bundling follows + * `e2e/list-narrow-pinned-columns-35446.spec.ts`. + * + * ## What is real here and what is a fixture + * + * REAL: app-shell's `ObjectViewPageHeader` and the actions its page builds + * for it (`useObjectViewHeaderChrome`: New, Import, the folded 「⋯」 menu as an + * `action:bar`), `PageHeader`, and the `action:bar` renderer, bundled by Vite + * from their source files and mounted in Chromium with React's client + * renderer; the stylesheet is real Tailwind, compiled for the classes on the + * page. The 「⋯」 menu is opened and Import run with real pointer clicks. + * + * FIXTURES, declared so nobody reads more into a green run than it says: + * + * - The object, its description, the view title and the translator are + * literals (English keys answered by a small map); Import is recorded on + * the page, not run. + * - The width is set by a frame around the header, not by the AI panel: the + * rule reads the header's own box. 699 px is the main area the card + * measured with the AI panel docked in a 1167 px window; 1184 px is the + * list page's width at a 1440 px window with the sidebar open. + * - Fonts are Chromium's fallbacks. The assertions are which controls and + * text are drawn and that nothing in the row is clipped, not pixels. + */ + +const REPO_ROOT = uiRoot(); +const source = (rel: string) => path.join(REPO_ROOT, rel); + +const THEME_CSS = source('packages/components/src/index.css'); +// The entry names workspace sources by path, never by package name: the e2e +// type-check program must import no workspace package (it builds nothing first). +const COMPONENTS = source('packages/components/src/index.ts'); +const REACT_BINDINGS = source('packages/react/src/index.ts'); +const PAGE_HEADER = source('packages/app-shell/src/views/objectViewPageHeader.tsx'); +const HEADER_CHROME = source('packages/app-shell/src/views/objectViewHeaderChrome.tsx'); + +/** The main area with the AI panel docked in a 1167 px window (the card's case). */ +const AI_PANEL_MAIN = 699; +/** The list page's width at a 1440 px window (see the header). */ +const FULL_PAGE = 1184; + +/** Short enough that the full-width header keeps every action labelled beside it. */ +const DESCRIPTION = 'Open deals and their expected close dates'; + +/** + * The view's label in the title 「Opportunities / VIEW」. Long enough that the + * title is wider than 60 % of the narrow row in any font, the share the full + * row keeps for its title beside the description. + */ +const VIEW_LABEL = 'Open opportunities this quarter'; + +interface Case { + name: string; + viewport: number; + frame: number; +} + +const ENTRY = '\0list-header-narrow:entry'; + +/** `@object-ui/` to `packages//src`, and a subpath into that `src/`. */ +function workspaceSources(): Plugin { + return { + name: 'list-header-narrow-workspace-src', + enforce: 'pre', + async resolveId(id, importer) { + const m = /^@object-ui\/([a-z0-9-]+)(?:\/(.+))?$/.exec(id); + if (!m) return null; + const [, pkg, sub] = m; + const target = + pkg === 'types' && sub === 'zod' + ? source('packages/types/src/zod/index.zod.ts') + : source(`packages/${pkg}/src${sub ? `/${sub}` : ''}`); + const resolved = await this.resolve(target, importer, { skipSelf: true }); + if (!resolved) throw new Error(`${id} did not resolve to a source file under ${target}`); + return resolved; + }, + }; +} + +/** The page: the list header of the case named by `window.__case`, mounted with the client renderer. */ +function entry(): Plugin { + const code = ` +import * as React from 'react'; +import { createRoot } from 'react-dom/client'; +import { MemoryRouter } from 'react-router-dom'; +import ${JSON.stringify(COMPONENTS)}; +import { ActionProvider } from ${JSON.stringify(REACT_BINDINGS)}; +import { ObjectViewPageHeader } from ${JSON.stringify(PAGE_HEADER)}; +import { useObjectViewHeaderChrome } from ${JSON.stringify(HEADER_CHROME)}; + +const h = React.createElement; +const c = window.__case; +window.__imports = 0; +const TEXT = { + 'console.objectView.new': 'New', + 'console.objectView.import': 'Import', + 'console.objectView.importTitle': 'Import records', +}; +const t = (key, opts) => TEXT[key] ?? (opts && opts.defaultValue) ?? key; +const objectDef = { name: 'opportunity', label: 'Opportunity', pluralLabel: 'Opportunities', icon: 'briefcase', description: ${JSON.stringify(DESCRIPTION)} }; +const toolbarBar = { type: 'action:bar', location: 'list_toolbar', actions: [], maxVisible: 3, mobileMaxVisible: 0 }; +const listFavorite = { isFavorite: false, toggle: () => {} }; +const VIEW_LABEL = ${JSON.stringify(VIEW_LABEL)}; + +function Header() { + const [, setShowImport] = React.useState(false); + const openImport = (value) => { if (value) window.__imports += 1; setShowImport(value); }; + const chrome = useObjectViewHeaderChrome({ + objectCanCreate: true, createVisible: true, createDisabled: false, + actions: { create: () => {} }, t, listActions: [], toolbarActionsWithDeepLink: [], + identityImportEnabled: false, objectCanImport: true, importVisible: true, importDisabled: false, + setShowImport: openImport, listFavorite, isEnvironmentList: false, toolbarBar, + viewAccess: { refusal: null }, + }); + return h(ObjectViewPageHeader, { + objectDef, + titleSwitcher: h('span', { 'data-testid': 'view-switcher' }, VIEW_LABEL), + titleLabel: VIEW_LABEL, + objectListHref: '/apps/sales/opportunity', + objectPluralLabel: () => 'Opportunities', + objectDesc: (def) => def.description, + createButton: chrome.createButton, + importShown: chrome.importShown, + setShowImport: openImport, + importDisabled: false, + t, + listActions: [], + isEnvironmentList: false, + headerToolbarActions: [], + environmentEntitlements: undefined, + toolbarBar, + listFavorite, + personalizedMarker: null, + foldedHeaderActions: chrome.foldedHeaderActions, + }); +} + +const root = createRoot(document.getElementById('root')); +let mounts = 0; +// A fresh header: its fold keeps what it read on its first frame, so the +// spec mounts it again once the stylesheet is in, as a page load would. +window.__remount = () => root.render( + h(MemoryRouter, { key: ++mounts, initialEntries: ['/apps/sales/opportunity/view/open'] }, + h(ActionProvider, null, + h('div', { id: 'frame', className: 'bg-background', style: { width: c.frame + 'px' } }, h(Header)))), +); +window.__remount(); +`; + return { + name: 'list-header-narrow-entry', + resolveId: (id) => (id === 'list-header-narrow:entry' ? ENTRY : null), + load: (id) => (id === ENTRY ? code : null), + }; +} + +/** Bundle the page once, from source, to one ES module held in memory. */ +async function bundlePage(): Promise { + const result = await build({ + configFile: false, + root: REPO_ROOT, + // Out of the tree: this run must leave nothing behind in the checkout. + cacheDir: path.join(os.tmpdir(), 'objectui-list-header-narrow'), + logLevel: 'error', + mode: 'production', + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + plugins: [workspaceSources(), entry()], + build: { + write: false, + minify: false, + target: 'es2022', + modulePreload: false, + reportCompressedSize: false, + rollupOptions: { + input: 'list-header-narrow:entry', + output: { format: 'es', codeSplitting: false }, + }, + }, + }); + const outputs = (Array.isArray(result) ? result : [result]) as Rollup.RollupOutput[]; + const chunks = outputs.flatMap((o) => o.output).filter((o): o is Rollup.OutputChunk => o.type === 'chunk'); + if (chunks.length !== 1) throw new Error(`expected one bundled chunk, got ${chunks.length}`); + return chunks[0].code; +} + +/** The real theme sheet, compiled for the given class candidates. */ +async function tailwindFor(candidates: string[]): Promise { + const requireFromComponents = createRequire(source('packages/components/package.json')); + const twEntry = requireFromComponents.resolve('tailwindcss/index.css'); + const compiler = await compile(readFileSync(THEME_CSS, 'utf8'), { + base: path.dirname(THEME_CSS), + loadStylesheet: async (id: string, base: string) => { + const file = id === 'tailwindcss' ? twEntry : path.resolve(base, id); + return { path: file, base: path.dirname(file), content: readFileSync(file, 'utf8') }; + }, + loadModule: async (id: string) => { + const file = requireFromComponents.resolve(id); + const mod = await import(pathToFileURL(file).href); + return { path: file, base: path.dirname(file), module: mod.default ?? mod }; + }, + }); + return compiler.build(candidates); +} + +let bundle = ''; + +/** Compile the stylesheet until the page's class set stops growing. */ +async function styleUntilStable(page: Page, compiled: Set): Promise { + const classesOnPage = () => + page.evaluate(() => [ + ...new Set( + [...document.querySelectorAll('[class]')].flatMap((el) => (el.getAttribute('class') ?? '').split(/\s+/)).filter(Boolean), + ), + ]); + for (let round = 0; ; round++) { + const candidates = await classesOnPage(); + if (round > 0 && candidates.every((cls) => compiled.has(cls))) break; + if (round === 5) throw new Error('the page kept adding classes; the stylesheet never caught up'); + candidates.forEach((cls) => compiled.add(cls)); + const css = await tailwindFor([...compiled]); + await page.evaluate((text) => { + let sheet = document.getElementById('tailwind'); + if (!sheet) { + sheet = document.createElement('style'); + sheet.id = 'tailwind'; + document.head.appendChild(sheet); + } + sheet.textContent = text; + }, css); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + } +} + +/** Mount the case, style it, and wait until the header holds still. */ +async function mount(page: Page, c: Case): Promise { + await page.setViewportSize({ width: c.viewport, height: 900 }); + await page.setContent('
'); + await page.evaluate((value) => { + (window as unknown as { __case: Case }).__case = value; + }, c); + await page.addScriptTag({ content: bundle, type: 'module' }); + await page.locator('[data-testid="page-header"]').waitFor({ state: 'attached', timeout: 30_000 }); + const compiled = new Set(); + await styleUntilStable(page, compiled); + await page.evaluate(() => document.fonts?.ready); + // The header first measured itself unstyled; mount it afresh under the + // stylesheet, as a real page load draws it, and style what it draws then. + await page.evaluate(() => (window as unknown as { __remount: () => void }).__remount()); + await styleUntilStable(page, compiled); + await page.evaluate(() => (window as unknown as { __remount: () => void }).__remount()); + // The header decides its face from its width after layout: wait for a face + // that holds across 300 ms, then style whatever it drew. + let last = ''; + for (let i = 0; i < 20; i++) { + const now = await page.evaluate(() => { + const header = document.querySelector('[data-testid="page-header"]'); + const cluster = document.querySelector('[data-testid="page-header-actions"]'); + return `${header?.getAttribute('data-compact')}:${cluster?.getAttribute('data-folded')}:${header?.textContent}`; + }); + if (now === last) break; + last = now; + await page.waitForTimeout(300); + } + await styleUntilStable(page, compiled); +} + +interface Reading { + width: number; + compact: boolean; + folded: string | null; + descriptionDrawn: boolean; + importButton: boolean; + newButton: boolean; + /** Controls of the row whose box spills past the header's right edge. */ + spill: string[]; + /** The title is cut (its content wider than its box). */ + titleClipped: boolean; + /** The title's box, its content, and the row's text block it sits in, in px. */ + title: { box: number; content: number; block: number; maxWidth: string }; +} + +async function read(page: Page): Promise { + return page.evaluate((description) => { + const header = document.querySelector('[data-testid="page-header"]')!; + const hr = header.getBoundingClientRect(); + const visible = (el: Element | null) => !!el && (el as HTMLElement).offsetParent !== null; + const descriptionEl = [...header.querySelectorAll('p')].find((p) => (p.textContent ?? '').includes(description)) ?? null; + const spill = [...header.querySelectorAll('[data-testid="page-header-actions"] > *')] + .filter((el) => el.getBoundingClientRect().right > hr.right + 0.5) + .map((el) => el.getAttribute('data-testid') ?? el.tagName.toLowerCase()); + const h1 = header.querySelector('h1')!; + return { + width: Math.round(hr.width), + compact: header.getAttribute('data-compact') === 'true', + folded: document.querySelector('[data-testid="page-header-actions"]')?.getAttribute('data-folded') ?? null, + descriptionDrawn: visible(descriptionEl), + importButton: visible(header.querySelector('[data-testid="object-view-import-button"]')), + newButton: visible(header.querySelector('[data-testid="object-view-new-button"]')), + spill, + titleClipped: h1.scrollWidth > h1.clientWidth + 1, + title: { + box: h1.clientWidth, + content: h1.scrollWidth, + block: h1.parentElement!.clientWidth, + maxWidth: getComputedStyle(h1).maxWidth, + }, + }; + }, DESCRIPTION); +} + +function report(testInfo: import('@playwright/test').TestInfo, c: Case, r: Reading): void { + testInfo.annotations.push({ type: `list-header-narrow@${c.name}`, description: JSON.stringify(r) }); + process.stdout.write(`[list-header-narrow ${c.name}] ${JSON.stringify(r)}\n`); +} + +test.describe('app list header in a narrowed main area — no description, Import in the 「⋯」 (objectstack#35446)', () => { + test.beforeAll(async () => { + test.setTimeout(240_000); + bundle = await bundlePage(); + }); + + test(`AI panel docked (${AI_PANEL_MAIN} px main area): title, New and the 「⋯」 holding Import; no description`, async ({ page }, testInfo) => { + test.setTimeout(120_000); + const c: Case = { name: 'aiPanel', viewport: 1167, frame: AI_PANEL_MAIN }; + await mount(page, c); + const r = await read(page); + report(testInfo, c, r); + expect(r.compact, 'the list header did not take its compact form').toBe(true); + expect(r.descriptionDrawn, 'the description is still drawn').toBe(false); + expect(r.importButton, 'Import is still a button in the row').toBe(false); + expect(r.newButton).toBe(true); + expect(r.folded).toBe('true'); + expect(r.spill, 'a header control spills past the header').toEqual([]); + expect(r.titleClipped, 'the title is cut').toBe(false); + // Import is one click into the 「⋯」. + await page.locator('[data-testid="page-header-actions"] button:not([data-testid="object-view-new-button"])').last().click(); + await page.getByRole('menuitem', { name: 'Import' }).click(); + await expect.poll(() => page.evaluate(() => (window as unknown as { __imports: number }).__imports)).toBe(1); + }); + + test('CONTROL: on the full list page the description and the Import button stay', async ({ page }, testInfo) => { + test.setTimeout(120_000); + const c: Case = { name: 'fullPage1440', viewport: 1440, frame: FULL_PAGE }; + await mount(page, c); + const r = await read(page); + report(testInfo, c, r); + expect(r.compact).toBe(false); + expect(r.descriptionDrawn).toBe(true); + expect(r.importButton).toBe(true); + expect(r.newButton).toBe(true); + expect(r.folded).toBe('false'); + expect(r.spill).toEqual([]); + }); +}); diff --git a/ui/e2e/list-narrow-pinned-columns-35446.spec.ts b/ui/e2e/list-narrow-pinned-columns-35446.spec.ts new file mode 100644 index 00000000000..93737d1a3ef --- /dev/null +++ b/ui/e2e/list-narrow-pinned-columns-35446.spec.ts @@ -0,0 +1,436 @@ +import { test, expect, type Page } from '@playwright/test'; +import { compile } from 'tailwindcss'; +import { build, type Plugin, type Rollup } from 'vite'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { uiRoot } from '../scripts/ui-root.mjs'; + +/** + * GEOMETRY pin for objectstack#35446: an app list whose main area narrows (the + * AI panel docked, a small window, the record drawer open) keeps every data + * cell clear of the grid's fixed columns, keeps its name column frozen, and + * shows its horizontal scrollbar while columns lie out of view. + * + * ## The defect + * + * The grid pinned its row-actions column (the row's "⋮") to the scroll box's + * right edge. In a narrow box the table overflows, so at rest the pinned + * column sat over whichever data column reached that edge (the card measured + * the amount column cut to 「¥94,0」), and the scrollbar was transparent until + * the pointer was over the box, so nothing said more columns lay to the right. + * Now, while the table overflows its box, the "⋮" column joins the frozen zone + * beside the name column (`useInlineRowActionFold` in plugin-grid) and the + * scroll box draws its scrollbar at rest (`data-table`). + * + * ## Why a Playwright spec and not a vitest test + * + * jsdom and happy-dom have no layout engine: no widths, no sticky offsets, no + * `elementFromPoint`, and the move is decided from the widths the table draws. + * The bundling follows `e2e/related-list-pinned-actions-width.spec.ts`. + * + * ## What is real here and what is a fixture + * + * REAL: plugin-grid's `ObjectGrid`, the `data-table` and `RowActionMenu`, + * bundled by Vite from their source files and mounted in Chromium with React's + * client renderer; the stylesheet is real Tailwind + * (`packages/components/src/index.css`, its `@theme` included), compiled for + * exactly the classes the mounted page carries. The row menu is opened and its + * action dispatched with real pointer clicks. + * + * FIXTURES, declared so nobody reads more into a green run than it says: + * + * - The rows, the object's fields and the row actions are literals shaped + * like the card's opportunity list; the data source answers them and the + * dispatched action is recorded on the page, not run. + * - The width is set by a frame around the grid, not by the AI panel, a + * window or a drawer: the rule reads the grid's own box, so the cause of + * the narrowing is not an input. 699 px is the main area the card measured + * with the AI panel docked in a 1167 px window; 1184 px is the list page's + * table width at a 1440 px window with the sidebar open (the reading + * `related-list-pinned-actions-width.spec.ts` names). + * - Fonts are Chromium's fallbacks. The assertions are overlaps, hits and + * which edge a column sticks to, not pixels; the readings go to the report. + */ + +const REPO_ROOT = uiRoot(); +const source = (rel: string) => path.join(REPO_ROOT, rel); + +const THEME_CSS = source('packages/components/src/index.css'); +// The entry names workspace sources by path, never by package name: the e2e +// type-check program must import no workspace package (it builds nothing first). +const PLUGIN_GRID = source('packages/plugin-grid/src/index.tsx'); +const FIELDS = source('packages/fields/src/index.tsx'); +const REACT_BINDINGS = source('packages/react/src/index.ts'); + +/** The main area with the AI panel docked in a 1167 px window (the card's case). */ +const AI_PANEL_MAIN = 699; +/** The list page's table width at a 1440 px window (see the header). */ +const FULL_PAGE = 1184; + +/** The card's opportunity list, name first and the close date last. */ +const COLUMNS = ['name', 'account', 'stage', 'amount', 'probability', 'expected_revenue', 'close_date']; +/** Few enough to fit the narrow frame: nothing overflows, nothing moves. */ +const FEW_COLUMNS = ['name', 'stage', 'amount']; + +interface Case { + name: string; + viewport: number; + frame: number; + columns: string[]; + /** Give each row one inline primary action beside the "⋮". */ + inlinePrimary?: boolean; +} + +const ENTRY = '\0list-narrow-pinned-columns:entry'; + +/** `@object-ui/` to `packages//src`, and a subpath into that `src/`. */ +function workspaceSources(): Plugin { + return { + name: 'list-narrow-pinned-columns-workspace-src', + enforce: 'pre', + async resolveId(id, importer) { + const m = /^@object-ui\/([a-z0-9-]+)(?:\/(.+))?$/.exec(id); + if (!m) return null; + const [, pkg, sub] = m; + const target = + pkg === 'types' && sub === 'zod' + ? source('packages/types/src/zod/index.zod.ts') + : source(`packages/${pkg}/src${sub ? `/${sub}` : ''}`); + const resolved = await this.resolve(target, importer, { skipSelf: true }); + if (!resolved) throw new Error(`${id} did not resolve to a source file under ${target}`); + return resolved; + }, + }; +} + +/** The page: the case named by `window.__case`, mounted with the client renderer. */ +function entry(): Plugin { + const code = ` +import * as React from 'react'; +import { createRoot } from 'react-dom/client'; +import { ObjectGrid } from ${JSON.stringify(PLUGIN_GRID)}; +import { registerAllFields } from ${JSON.stringify(FIELDS)}; +import { ActionProvider, SchemaRendererProvider } from ${JSON.stringify(REACT_BINDINGS)}; + +registerAllFields(); +const h = React.createElement; +const c = window.__case; +window.__dispatched = []; +const FIELDS = { + id: { name: 'id', type: 'text' }, + name: { name: 'name', label: 'Opportunity name', type: 'text' }, + account: { name: 'account', label: 'Account', type: 'text' }, + stage: { name: 'stage', label: 'Stage', type: 'text' }, + amount: { name: 'amount', label: 'Amount', type: 'currency' }, + probability: { name: 'probability', label: 'Probability', type: 'percent' }, + expected_revenue: { name: 'expected_revenue', label: 'Expected revenue', type: 'currency' }, + close_date: { name: 'close_date', label: 'Expected close date', type: 'date' }, +}; +const ROWS = [ + ['Vertex Enterprise Rollout', 'Vertex Analytics', 'Negotiation', 94000, 80], + ['Wayne Enterprise License', 'Wayne Enterprises', 'Negotiation', 1200000, 80], + ['Lattice Education Renewal', 'Lattice Education', 'Proposal', 87000, 60], +].map(([name, account, stage, amount, probability], i) => ({ + id: 'o' + (i + 1), name, account, stage, amount, probability, + expected_revenue: amount * probability / 100, close_date: '2026-12-0' + (i + 1), +})); +const dataSource = { + find: async () => ({ data: ROWS, total: ROWS.length }), + getObjectSchema: async (name) => ({ name, fields: FIELDS }), +}; +const rowActionDefs = [ + ...(c.inlinePrimary ? [{ name: 'advance', label: 'Advance', variant: 'primary' }] : []), + { name: 'archive', label: 'Archive' }, +]; +createRoot(document.getElementById('root')).render( + h(ActionProvider, { handlers: Object.fromEntries(rowActionDefs.map((d) => [d.name, async () => { window.__dispatched.push(d.name); return { success: true }; }])) }, + h(SchemaRendererProvider, { dataSource }, + h('div', { id: 'frame', className: 'flex flex-col bg-background', style: { width: c.frame + 'px', height: '520px' } }, + h(ObjectGrid, { + dataSource, + schema: { + type: 'object-grid', + objectName: 'opportunity', + columns: c.columns.map((field) => ({ field, label: FIELDS[field].label })), + rowActionDefs, + }, + })))), +); +`; + return { + name: 'list-narrow-pinned-columns-entry', + resolveId: (id) => (id === 'list-narrow-pinned-columns:entry' ? ENTRY : null), + load: (id) => (id === ENTRY ? code : null), + }; +} + +/** Bundle the page once, from source, to one ES module held in memory. */ +async function bundlePage(): Promise { + const result = await build({ + configFile: false, + root: REPO_ROOT, + // Out of the tree: this run must leave nothing behind in the checkout. + cacheDir: path.join(os.tmpdir(), 'objectui-list-narrow-pinned-columns'), + logLevel: 'error', + mode: 'production', + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + plugins: [workspaceSources(), entry()], + build: { + write: false, + minify: false, + target: 'es2022', + modulePreload: false, + reportCompressedSize: false, + rollupOptions: { + input: 'list-narrow-pinned-columns:entry', + output: { format: 'es', codeSplitting: false }, + }, + }, + }); + const outputs = (Array.isArray(result) ? result : [result]) as Rollup.RollupOutput[]; + const chunks = outputs.flatMap((o) => o.output).filter((o): o is Rollup.OutputChunk => o.type === 'chunk'); + if (chunks.length !== 1) throw new Error(`expected one bundled chunk, got ${chunks.length}`); + return chunks[0].code; +} + +/** The real theme sheet, compiled for the given class candidates. */ +async function tailwindFor(candidates: string[]): Promise { + const requireFromComponents = createRequire(source('packages/components/package.json')); + const twEntry = requireFromComponents.resolve('tailwindcss/index.css'); + const compiler = await compile(readFileSync(THEME_CSS, 'utf8'), { + base: path.dirname(THEME_CSS), + loadStylesheet: async (id: string, base: string) => { + const file = id === 'tailwindcss' ? twEntry : path.resolve(base, id); + return { path: file, base: path.dirname(file), content: readFileSync(file, 'utf8') }; + }, + loadModule: async (id: string) => { + const file = requireFromComponents.resolve(id); + const mod = await import(pathToFileURL(file).href); + return { path: file, base: path.dirname(file), module: mod.default ?? mod }; + }, + }); + return compiler.build(candidates); +} + +let bundle = ''; + +/** Compile the stylesheet until the page's class set stops growing. */ +async function styleUntilStable(page: Page, compiled: Set): Promise { + const classesOnPage = () => + page.evaluate(() => [ + ...new Set( + [...document.querySelectorAll('[class]')].flatMap((el) => (el.getAttribute('class') ?? '').split(/\s+/)).filter(Boolean), + ), + ]); + for (let round = 0; ; round++) { + const candidates = await classesOnPage(); + if (round > 0 && candidates.every((cls) => compiled.has(cls))) break; + if (round === 5) throw new Error('the page kept adding classes; the stylesheet never caught up'); + candidates.forEach((cls) => compiled.add(cls)); + const css = await tailwindFor([...compiled]); + await page.evaluate((text) => { + let sheet = document.getElementById('tailwind'); + if (!sheet) { + sheet = document.createElement('style'); + sheet.id = 'tailwind'; + document.head.appendChild(sheet); + } + sheet.textContent = text; + }, css); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + } +} + +/** Mount the case, style it, and wait until the table's geometry holds still. */ +async function mount(page: Page, c: Case): Promise { + await page.setViewportSize({ width: c.viewport, height: 900 }); + await page.setContent('
'); + await page.evaluate((value) => { + (window as unknown as { __case: Case }).__case = value; + }, c); + await page.addScriptTag({ content: bundle, type: 'module' }); + await page.locator('th[data-column-key="_actions"]').first().waitFor({ state: 'attached', timeout: 30_000 }); + const compiled = new Set(); + await styleUntilStable(page, compiled); + await page.evaluate(() => document.fonts?.ready); + // The table sizes its columns over several passes and the fold and the move + // are read once its size holds: wait for a geometry that holds across 500 ms. + let last = ''; + for (let i = 0; i < 20; i++) { + const now = await page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]'); + const host = document.querySelector('[data-row-actions-inline]'); + const state = `${host?.getAttribute('data-row-actions-inline') ?? ''}:${host?.getAttribute('data-row-actions-column') ?? ''}`; + return box ? `${box.clientWidth}:${box.scrollWidth}:${state}` : `none:${state}`; + }); + if (now === last) break; + last = now; + await page.waitForTimeout(500); + } + await styleUntilStable(page, compiled); +} + +interface Reading { + box: { clientWidth: number; scrollWidth: number; scrollbarHeight: number; scrollbarColor: string }; + /** The edge the "⋮" column sticks to, and its box inside the scroll box. */ + actions: { stick: 'left' | 'right' | 'none'; left: number; width: number }; + inlineButtons: number; + /** The header keys in drawn order. */ + order: string[]; + /** The frozen (left-sticky) header keys. */ + frozen: string[]; + /** + * The largest overlap, in px, of a fixed cell's box with a data cell's box + * in the same row (header row and first body row), and the pair. + */ + overlap: { px: number; fixed: string | null; data: string | null }; + /** Data cells of the first body row whose centre lies in view but answers something else. */ + covered: string[]; +} + +/** The table at rest: nothing scrolled. */ +async function readAtRest(page: Page): Promise { + return page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]')!; + box.scrollLeft = 0; + const boxRect = box.getBoundingClientRect(); + const view = { left: boxRect.left + box.clientLeft, right: boxRect.left + box.clientLeft + box.clientWidth }; + const headRow = box.querySelector('thead tr')!; + const bodyRow = box.querySelector('tbody tr')!; + const keyAt = (i: number) => (headRow.children[i] as HTMLElement).getAttribute('data-column-key') ?? `#${i}`; + const sticky = (el: Element) => getComputedStyle(el).position === 'sticky'; + let worst = { px: 0, fixed: null as string | null, data: null as string | null }; + for (const row of [headRow, bodyRow]) { + const cells = [...row.children] as HTMLElement[]; + cells.forEach((fixed, i) => { + if (!sticky(fixed)) return; + const f = fixed.getBoundingClientRect(); + cells.forEach((data, j) => { + if (sticky(data) || !headRow.children[j]?.getAttribute('data-column-key')) return; + const d = data.getBoundingClientRect(); + const px = Math.max(0, Math.min(f.right, d.right) - Math.max(f.left, d.left)); + if (px > worst.px) worst = { px: Math.round(px * 10) / 10, fixed: keyAt(i), data: keyAt(j) }; + }); + }); + } + const covered: string[] = []; + ([...bodyRow.children] as HTMLElement[]).forEach((cell, j) => { + const key = headRow.children[j]?.getAttribute('data-column-key'); + if (!key || key === '_actions' || sticky(cell)) return; + const r = cell.getBoundingClientRect(); + const x = r.left + r.width / 2; + if (x <= view.left || x >= view.right) return; + const at = document.elementFromPoint(x, r.top + r.height / 2); + if (!at || !(at === cell || cell.contains(at))) covered.push(key); + }); + const actionsHead = box.querySelector('th[data-column-key="_actions"]')!; + const ar = actionsHead.getBoundingClientRect(); + const cs = getComputedStyle(actionsHead); + const stick = cs.position !== 'sticky' ? 'none' : cs.right === '0px' && cs.left === 'auto' ? 'right' : 'left'; + const heads = [...headRow.children] as HTMLElement[]; + return { + box: { + clientWidth: box.clientWidth, + scrollWidth: box.scrollWidth, + scrollbarHeight: box.offsetHeight - box.clientHeight - box.clientTop * 2, + scrollbarColor: getComputedStyle(box).scrollbarColor, + }, + actions: { stick, left: Math.round(ar.left - boxRect.left), width: Math.round(ar.width) }, + inlineButtons: box.querySelectorAll('[data-testid^="row-action-inline-"]').length, + order: heads.map((h) => h.getAttribute('data-column-key')).filter((k): k is string => !!k), + frozen: heads + .filter((h) => h.getAttribute('data-column-key') && sticky(h) && getComputedStyle(h).left !== 'auto') + .map((h) => h.getAttribute('data-column-key')!), + overlap: worst, + covered, + }; + }); +} + +/** Scrolled to the far right: does the last column's header answer at its centre? */ +async function lastColumnReachable(page: Page, key: string): Promise { + return page.evaluate(async (k) => { + const box = document.querySelector('[data-table-scroll-box]')!; + box.scrollLeft = box.scrollWidth; + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + const head = box.querySelector(`th[data-column-key="${k}"]`)!; + const r = head.getBoundingClientRect(); + const at = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); + const hit = !!at && (at === head || head.contains(at)); + box.scrollLeft = 0; + return hit; + }, key); +} + +function report(testInfo: import('@playwright/test').TestInfo, c: Case, r: Reading): void { + testInfo.annotations.push({ type: `list-narrow-pinned-columns@${c.name}`, description: JSON.stringify(r) }); + process.stdout.write(`[list-narrow-pinned-columns ${c.name}] ${JSON.stringify(r)}\n`); +} + +/** Open the first row's "⋮" menu with the pointer and run Archive from it. */ +async function archiveFromMenu(page: Page): Promise { + await page.getByTestId('row-action-trigger').first().click(); + await page.getByRole('menuitem', { name: 'Archive' }).click(); + await expect + .poll(() => page.evaluate(() => (window as unknown as { __dispatched: unknown[] }).__dispatched.length)) + .toBe(1); +} + +test.describe('app list in a narrowed main area — no fixed column covers a data cell (objectstack#35446)', () => { + test.beforeAll(async () => { + test.setTimeout(240_000); + bundle = await bundlePage(); + }); + + for (const inlinePrimary of [false, true]) { + test(`AI panel docked (${AI_PANEL_MAIN} px main area${inlinePrimary ? ', inline primary action' : ''}): the "⋮" joins the frozen zone and the rest scrolls`, async ({ page }, testInfo) => { + test.setTimeout(120_000); + const c: Case = { name: `aiPanel${inlinePrimary ? 'Inline' : ''}`, viewport: 1167, frame: AI_PANEL_MAIN, columns: COLUMNS, inlinePrimary }; + await mount(page, c); + const r = await readAtRest(page); + report(testInfo, c, r); + expect(r.box.scrollWidth, 'the fixture no longer overflows the narrow frame').toBeGreaterThan(r.box.clientWidth + 1); + expect(r.overlap.px, `the fixed column ${r.overlap.fixed} covers ${r.overlap.data} by ${r.overlap.px} px at rest`).toBeLessThanOrEqual(0.5); + expect(r.covered, 'data cells in view answer another element at their centre').toEqual([]); + expect(r.actions.stick, 'the "⋮" column is not in the frozen zone').toBe('left'); + expect(r.frozen).toEqual(['name', '_actions']); + expect(r.inlineButtons, 'inline buttons are drawn although the table overflows').toBe(0); + // Headless Chromium draws no scrollbar at all (its room reads 0 either + // way), so the bar is read from its colour at rest. + expect(r.box.scrollbarColor, 'the scrollbar is transparent at rest').not.toMatch(/^(transparent|rgba\(0, 0, 0, 0\))/); + expect(await lastColumnReachable(page, 'close_date'), 'the last column cannot be reached by scrolling').toBe(true); + await archiveFromMenu(page); + }); + } + + test('CONTROL: on the full list page nothing moves and nothing is covered', async ({ page }, testInfo) => { + test.setTimeout(120_000); + const c: Case = { name: 'fullPage1440', viewport: 1440, frame: FULL_PAGE, columns: COLUMNS }; + await mount(page, c); + const r = await readAtRest(page); + report(testInfo, c, r); + expect(r.box.scrollWidth - r.box.clientWidth, 'the fixture overflows the full page').toBeLessThanOrEqual(1); + expect(r.actions.stick).toBe('right'); + expect(r.order[r.order.length - 1]).toBe('_actions'); + expect(r.frozen).toEqual(['name']); + expect(r.overlap.px).toBeLessThanOrEqual(0.5); + expect(r.covered).toEqual([]); + expect(r.box.scrollbarColor, 'a table that fits draws its scrollbar at rest').toMatch(/^(transparent|rgba\(0, 0, 0, 0\))/); + await archiveFromMenu(page); + }); + + test('CONTROL: a narrow list whose columns fit keeps the "⋮" at the right edge', async ({ page }, testInfo) => { + test.setTimeout(120_000); + const c: Case = { name: 'aiPanelFew', viewport: 1167, frame: AI_PANEL_MAIN, columns: FEW_COLUMNS }; + await mount(page, c); + const r = await readAtRest(page); + report(testInfo, c, r); + expect(r.box.scrollWidth - r.box.clientWidth).toBeLessThanOrEqual(1); + expect(r.actions.stick).toBe('right'); + expect(r.frozen).toEqual(['name']); + expect(r.overlap.px).toBeLessThanOrEqual(0.5); + }); +}); diff --git a/ui/e2e/related-list-pinned-actions-width.spec.ts b/ui/e2e/related-list-pinned-actions-width.spec.ts index 9da687ba241..50ee178dc86 100644 --- a/ui/e2e/related-list-pinned-actions-width.spec.ts +++ b/ui/e2e/related-list-pinned-actions-width.spec.ts @@ -397,10 +397,11 @@ test.describe('enlarged related list in a record drawer — the pinned Actions c report(testInfo, c, r); expect(r.folded).toBe(true); expect(r.inlineButtons).toBe(0); - // Still wider than the drawer: the pinned column sits at the box's edge - // over whichever column scrolls under it, as on any list that scrolls - // sideways. A scroll to the end shows Status whole. + // Still wider than the drawer: the Actions column leaves the right edge + // for the frozen zone beside the name column (objectstack#35446), and a + // scroll to the end shows Status whole. expect(r.box.scrollWidth).toBeGreaterThan(r.box.clientWidth); + expect(r.actions.left, 'the Actions column still sits at the right edge').toBeLessThan(r.box.clientWidth / 2); const end = await page.evaluate(async () => { const box = document.querySelector('[data-table-scroll-box]')!; box.scrollLeft = box.scrollWidth; diff --git a/ui/packages/app-shell/src/layout/PageHeader.tsx b/ui/packages/app-shell/src/layout/PageHeader.tsx index f2b2303e4f5..1bdb7dc3cf8 100644 --- a/ui/packages/app-shell/src/layout/PageHeader.tsx +++ b/ui/packages/app-shell/src/layout/PageHeader.tsx @@ -35,6 +35,12 @@ * the header is too narrow for `actions` and its text, it draws that instead, * so the actions fold before the title or the description is cut: * [icon] Title [kind] | the whole description [refresh] [primary] [⋯] + * + * The compact form — a page may opt in with `compactBelow` (objectstack#35446): + * while the one-row header is narrower than that, it drops the description and + * draws `foldedActions` whatever the text needs, so a main area narrowed by a + * docked panel, a small window or the record drawer gets a short header row: + * [icon] Title [kind] [refresh] [primary] [⋯] */ import * as React from 'react'; @@ -140,6 +146,17 @@ export interface ConsolePageHeaderProps { * trade the page's actions for its description. */ foldedActions?: React.ReactNode; + /** + * Opt-in compact form for a narrow header (objectstack#35446): while the + * one-row header is narrower than this many pixels, the description (and + * the hairline before it) is not drawn and `foldedActions`, when given, is + * drawn in place of `actions`. At this width and above the header behaves + * exactly as without it. Read from the header's own width, never the + * viewport's, so any narrowing of the main area counts. Setup's posture, + * whose description sits on its own line, ignores it. A page that passes + * nothing keeps today's header at every width. + */ + compactBelow?: number; /** * CSS color used to tint the top hairline, icon chip background, and * icon stroke. Defaults to the Shadcn `--primary` token so the header @@ -184,6 +201,7 @@ export function PageHeader({ refresh, actions, foldedActions, + compactBelow, accentColor, sticky = false, className, @@ -198,8 +216,12 @@ export function PageHeader({ // objectui#12705 — the actions fold before the text is cut. const canFold = foldedActions != null && foldedActions !== false; - const { rootRef, textRef, descriptionRef, clusterRef, folded } = useActionsFold(canFold, setup); - const drawnActions = canFold && folded ? foldedActions : actions; + const { rootRef, textRef, descriptionRef, clusterRef, folded, compact } = useActionsFold( + canFold, + setup, + setup ? undefined : compactBelow, + ); + const drawnActions = canFold && (folded || compact) ? foldedActions : actions; const refreshButton = refresh ? (