From c52f6706ae257b7816c2a38ae10f0e0d0e316e0e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 13:27:46 +0000 Subject: [PATCH 01/13] test(e2e): geometry harness for the narrowed app list's fixed columns Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .../list-narrow-pinned-columns-35446.spec.ts | 434 ++++++++++++++++++ 1 file changed, 434 insertions(+) create mode 100644 ui/e2e/list-narrow-pinned-columns-35446.spec.ts 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..0306e716503 --- /dev/null +++ b/ui/e2e/list-narrow-pinned-columns-35446.spec.ts @@ -0,0 +1,434 @@ +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); + expect(r.box.scrollbarHeight, 'the horizontal scrollbar takes no room').toBeGreaterThan(0); + expect(r.box.scrollbarColor, 'the scrollbar is transparent at rest').not.toMatch(/^transparent/); + 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([]); + 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); + }); +}); From 2a640fac2f23e6c6446a1f07df41cf9f03087796 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 13:32:58 +0000 Subject: [PATCH 02/13] fix(grid): the row-actions column joins the frozen zone while the table overflows its box Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .../list-narrow-pinned-columns-35446.spec.ts | 6 +- .../src/renderers/complex/data-table.tsx | 37 +++++++++- ui/packages/plugin-grid/src/ObjectGrid.tsx | 49 +++++++++---- .../src/objectGridInlineActionFold.ts | 70 +++++++++++++++---- 4 files changed, 133 insertions(+), 29 deletions(-) diff --git a/ui/e2e/list-narrow-pinned-columns-35446.spec.ts b/ui/e2e/list-narrow-pinned-columns-35446.spec.ts index 0306e716503..93737d1a3ef 100644 --- a/ui/e2e/list-narrow-pinned-columns-35446.spec.ts +++ b/ui/e2e/list-narrow-pinned-columns-35446.spec.ts @@ -398,8 +398,9 @@ test.describe('app list in a narrowed main area — no fixed column covers a dat 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); - expect(r.box.scrollbarHeight, 'the horizontal scrollbar takes no room').toBeGreaterThan(0); - expect(r.box.scrollbarColor, 'the scrollbar is transparent at rest').not.toMatch(/^transparent/); + // 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); }); @@ -417,6 +418,7 @@ test.describe('app list in a narrowed main area — no fixed column covers a dat 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); }); diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index d0f38ee79ed..6bde1bf334a 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -1120,6 +1120,17 @@ function keepsBrowserContextMenu(target: HTMLElement, row: HTMLElement): boolean ); } +/** + * The scroll box's scrollbar while the table is wider than the box + * (objectstack#35446): drawn at rest in the theme's muted foreground, the + * colour the shared hover-only bar (`HOVER_SCROLLBAR_CLASSES`) turns on hover, + * and as thin. Marked important for the same reason that one is: a host may + * theme every scrollbar with an unlayered `*` rule. One complete literal: + * Tailwind builds only from scanned source text. + */ +const SIDEWAYS_SCROLLBAR_CLASSES = + '[scrollbar-width:thin]! [scrollbar-color:var(--color-muted-foreground)_transparent]!'; + /** * A right-pinned column: its sticky utilities arrive on `col.className` (the * auto-pinned row-actions column, and an author's `pinned: 'right'`, both @@ -2918,6 +2929,30 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { return () => observer?.disconnect(); }, [overflowRight, columns, leadingCellCount, paginatedData.length]); + /** + * objectstack#35446 — while the table is wider than its box, the box draws + * its scrollbar at rest ({@link SIDEWAYS_SCROLLBAR_CLASSES}): columns out of + * view are announced by the bar itself, in a narrowed main area as anywhere, + * not only once the pointer is over the box. A table that fits keeps the + * shared hover-only bar (objectui#12708). A grouped sub-table + * (`disableInnerScroll`) scrolls in a shared ancestor and draws no bar. + */ + const [scrollsSideways, setScrollsSideways] = useState(false); + useLayoutEffect(() => { + const box = scrollBoxRef.current; + if (disableInnerScroll || !box) { + setScrollsSideways(false); + return; + } + const read = () => setScrollsSideways(box.scrollWidth - box.clientWidth > 1); + read(); + if (typeof ResizeObserver === 'undefined') return undefined; + const observer = new ResizeObserver(read); + observer.observe(box); + if (tableRef.current) observer.observe(tableRef.current); + return () => observer.disconnect(); + }, [disableInnerScroll, columns, paginatedData.length]); + const [rovingCell, setRovingCell] = useState<{ rowIndex: number; colIndex: number }>({ rowIndex: 0, colIndex: 0 }); const rovingRowIndex = Math.max(0, Math.min(rovingCell.rowIndex, paginatedData.length - 1)); const rovingColIndex = Math.max(0, Math.min(rovingCell.colIndex, columns.length - 1)); @@ -3435,7 +3470,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // sub-tables share one horizontal scrollbar with aligned columns. disableInnerScroll ? "overflow-visible" - : ["flex-1 min-h-0 overflow-auto [-webkit-overflow-scrolling:touch]", HOVER_SCROLLBAR_CLASSES], + : ["flex-1 min-h-0 overflow-auto [-webkit-overflow-scrolling:touch]", scrollsSideways ? SIDEWAYS_SCROLLBAR_CLASSES : HOVER_SCROLLBAR_CLASSES], !borderless && "rounded-md border", )}> {/* This div is already the (bounded) scroll container for BOTH axes — diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 65a9d161079..4c522fc8f4d 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -1952,25 +1952,47 @@ export const ObjectGrid: React.FC = ({ const applyColumnChrome = (col: any) => withOneLineRichText(withSortability(applyDensity(col))); - const orderedColumns = hasPinnedColumns - ? [ - ...pinnedLeftCols.map(applyColumnChrome), - ...unpinnedCols.map(applyColumnChrome), - ...pinnedRightCols.map((col: any) => ({ - ...applyColumnChrome(col), - className: ['px-3', col.className, rightPinnedClasses].filter(Boolean).join(' '), - cellClassName: [rowHeightCellClass, col.cellClassName, rightPinnedCellClasses].filter(Boolean).join(' '), - })), - ] - : columnsWithActions.map(applyColumnChrome); - // Calculate frozenColumns: if the USER pinned columns, use their left-pinned // count; otherwise fall back to the schema default (freeze the first column). // The auto-pinned actions column is intentionally not counted here. - const effectiveFrozenColumns = hasUserPinnedColumns + const declaredFrozenColumns = hasUserPinnedColumns ? userLeftPinnedCount : (schema.frozenColumns ?? 1); + // objectstack#35446 — while the table overflows its box, the Actions column + // is drawn right after the frozen columns and frozen with them, instead of + // pinned to the right edge, where it sat over the data column reaching that + // edge at rest (`./objectGridInlineActionFold`). Every data column then + // scrolls and none is ever covered at rest. An author's own right pin is + // the author's layout and stays where it is. + const actionsColumn = pinnedRightCols.find((col: any) => col.accessorKey === '_actions'); + const actionsInFrozenZone = inlineActionFold.actionsFrozen && !!actionsColumn; + const scrollingColumns = [...pinnedLeftCols, ...unpinnedCols].map(applyColumnChrome); + const actionsFrozenAt = Math.min(declaredFrozenColumns, scrollingColumns.length); + const rightPinned = (col: any) => ({ + ...applyColumnChrome(col), + className: ['px-3', col.className, rightPinnedClasses].filter(Boolean).join(' '), + cellClassName: [rowHeightCellClass, col.cellClassName, rightPinnedCellClasses].filter(Boolean).join(' '), + }); + + const orderedColumns = actionsInFrozenZone + ? [ + ...scrollingColumns.slice(0, actionsFrozenAt), + { + ...applyColumnChrome(actionsColumn), + pinned: undefined, + className: ['px-3', actionsColumn.className].filter(Boolean).join(' '), + cellClassName: [rowHeightCellClass, actionsColumn.cellClassName].filter(Boolean).join(' '), + }, + ...scrollingColumns.slice(actionsFrozenAt), + ...pinnedRightCols.filter((col: any) => col !== actionsColumn).map(rightPinned), + ] + : hasPinnedColumns + ? [...scrollingColumns, ...pinnedRightCols.map(rightPinned)] + : columnsWithActions.map(applyColumnChrome); + + const effectiveFrozenColumns = actionsInFrozenZone ? actionsFrozenAt + 1 : declaredFrozenColumns; + // The floor. With no query to replay there is no honest "all N matching", so // the escalation is not offered — the same answer as a match set that does not // exist. This is what makes an unfiltered fan-out structurally unreachable @@ -3975,6 +3997,7 @@ export const ObjectGrid: React.FC = ({ ref={inlineActionFold.hostRef} className="flex flex-col flex-1 min-h-0" data-row-actions-inline={inlineActionFold.folded ? 'folded' : undefined} + data-row-actions-column={inlineActionFold.actionsFrozen ? 'frozen' : undefined} > diff --git a/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts b/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts index 53abf59026e..fb643f738af 100644 --- a/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts +++ b/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts @@ -1,6 +1,7 @@ /** * Whether `ObjectGrid` folds its inline primary row actions into the row's - * "⋮" menu (objectstack#33230). + * "⋮" menu (objectstack#33230), and whether the Actions column leaves the + * right edge for the frozen zone (objectstack#35446). * * The Actions column is pinned to the scroll box's right edge * (`./objectGridActionsColumn`), so while the table overflows the box the @@ -15,9 +16,19 @@ * moves to the top of its row's "⋮" menu (`planRowActionMenu`'s inline budget * of 0), so no action is dropped, and the pinned column shrinks to the * trigger. The buttons come back once the box is as wide as the table was with - * them. Where the table still overflows menu-only, the narrower pinned column - * still sits over the data at the box's edge, as on any list that scrolls - * sideways. + * them. + * + * Where the table still overflows menu-only, a column pinned to the right edge + * would sit over the data column that reaches that edge at rest (the amount + * column of a list in a main area narrowed by the AI panel, a small window or + * the record drawer). So while the table overflows, the Actions column joins + * the frozen zone instead (`actionsFrozen`): `ObjectGrid` draws it right after + * the frozen columns, which never cover a column at rest, and the data columns + * all scroll. It goes back to the right edge once the box is as wide as the + * table was when it moved. The move swaps the frozen zone's edge rule from the + * name column to the Actions column, a few pixels at most + * ({@link MOVE_WIDTH_SLACK_PX}), so the way back reads the width recorded + * before the move and the two placements cannot flip-flop. * * Every reading is taken once the table's size has held for two frames: the * table re-sizes its columns from what their cells drew over several passes, @@ -28,17 +39,28 @@ import * as React from 'react'; /** Sub-pixel rounding is not an overflow. */ const OVERFLOW_SLACK_PX = 1; +/** + * How much the move to the frozen zone may narrow the table (the edge rules it + * swaps). A frozen table that fits its box with more room than this to spare + * goes back to the right edge even before the box reaches the width recorded + * at the move, so a table that shrank while frozen is not held there. + */ +const MOVE_WIDTH_SLACK_PX = 4; /** Frames the table's size must hold before it is read. */ const SETTLED_FRAMES = 2; /** * Reads the grid's table scroll box under the element `hostRef` is attached - * to and answers whether the inline row actions fold. Starts unfolded, and - * starts again unfolded whenever `rows` or `columnsKey` change. + * to and answers whether the inline row actions fold and whether the Actions + * column is drawn in the frozen zone. Starts unfolded, and starts again + * unfolded whenever `rows` or `columnsKey` change; the column's placement is + * kept across those changes and read again from the widths they draw, so a + * refresh does not move it to the right edge and back. */ export function useInlineRowActionFold(rows: unknown, columnsKey: string): { hostRef: (element: HTMLElement | null) => void; folded: boolean; + actionsFrozen: boolean; } { const [host, setHost] = React.useState(null); const [folded, setFolded] = React.useState(false); @@ -46,6 +68,10 @@ export function useInlineRowActionFold(rows: unknown, columnsKey: string): { const foldedRef = React.useRef(false); // While folded: the table's width with the buttons, read when it folded. const unfoldedWidthRef = React.useRef(0); + const [actionsFrozen, setActionsFrozen] = React.useState(false); + const frozenRef = React.useRef(false); + // While frozen: the table's width with the column at the right edge. + const pinnedWidthRef = React.useRef(0); React.useLayoutEffect(() => { unfoldedWidthRef.current = 0; @@ -67,18 +93,36 @@ export function useInlineRowActionFold(rows: unknown, columnsKey: string): { foldedRef.current = next; setFolded(next); }; + const freeze = (next: boolean, tableWidth: number) => { + if (next === frozenRef.current) return; + frozenRef.current = next; + if (next) pinnedWidthRef.current = tableWidth; + setActionsFrozen(next); + }; const read = (box: HTMLElement) => { const boxWidth = box.clientWidth; if (boxWidth <= 0) return; + const tableWidth = box.scrollWidth; + const overflow = tableWidth - boxWidth; if (foldedRef.current) { - if (boxWidth >= unfoldedWidthRef.current) decide(false); + if (boxWidth >= unfoldedWidthRef.current) { + // The buttons fit again, so the table fits at the right edge too. + freeze(false, tableWidth); + decide(false); + return; + } + } else if (overflow > OVERFLOW_SLACK_PX && box.querySelector('[data-testid^="row-action-inline-"]')) { + // Fold first: the column's placement is read from the menu-only face. + unfoldedWidthRef.current = tableWidth; + decide(true); return; } - const tableWidth = box.scrollWidth; - if (tableWidth - boxWidth <= OVERFLOW_SLACK_PX) return; - if (!box.querySelector('[data-testid^="row-action-inline-"]')) return; - unfoldedWidthRef.current = tableWidth; - decide(true); + if (!box.querySelector('th[data-column-key="_actions"]')) return; + if (!frozenRef.current) { + if (overflow > OVERFLOW_SLACK_PX) freeze(true, tableWidth); + } else if (boxWidth >= pinnedWidthRef.current || overflow < -MOVE_WIDTH_SLACK_PX) { + freeze(false, tableWidth); + } }; const tick = () => { frame = 0; @@ -128,5 +172,5 @@ export function useInlineRowActionFold(rows: unknown, columnsKey: string): { }; }, [host]); - return { hostRef: setHost, folded }; + return { hostRef: setHost, folded, actionsFrozen }; } From 4c89023176617f6bc223ef2aa49286c4d2ae24c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 13:52:16 +0000 Subject: [PATCH 03/13] test(grid): pin the row-actions column's frozen-zone placement and the at-rest scrollbar Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .../related-list-pinned-actions-width.spec.ts | 7 ++- .../data-table-scroll-shadow-12463.test.tsx | 47 +++++++++++++++ .../src/__tests__/row-action-sticky.test.tsx | 59 +++++++++++++++++++ .../src/objectGridInlineActionFold.ts | 4 +- 4 files changed, 113 insertions(+), 4 deletions(-) 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/components/src/renderers/complex/__tests__/data-table-scroll-shadow-12463.test.tsx b/ui/packages/components/src/renderers/complex/__tests__/data-table-scroll-shadow-12463.test.tsx index f5b6dc5b8c6..07621302e61 100644 --- a/ui/packages/components/src/renderers/complex/__tests__/data-table-scroll-shadow-12463.test.tsx +++ b/ui/packages/components/src/renderers/complex/__tests__/data-table-scroll-shadow-12463.test.tsx @@ -140,3 +140,50 @@ describe('data-table scroll box, sticky columns and right-edge shadow (objectui# expect(queryByTestId('data-table-scroll-shadow-right')).toBeNull(); }); }); + +/** + * objectstack#35446 — while the table is wider than its box the box draws its + * scrollbar at rest, so columns out of view are announced without the pointer + * over the box; a table that fits keeps the shared hover-only bar + * (objectui#12708). The box's geometry is stubbed before the table mounts, + * because the read is taken at mount and on resize, not on scroll. + */ +describe('data-table scrollbar at rest while the table scrolls sideways (objectstack#35446)', () => { + const AT_REST = '[scrollbar-color:var(--color-muted-foreground)_transparent]!'; + const TRANSPARENT = '[scrollbar-color:transparent_transparent]!'; + + function stubBoxWidths(scrollWidth: number, clientWidth: number): () => void { + const proto = HTMLElement.prototype; + const isBox = (el: HTMLElement) => el.hasAttribute('data-table-scroll-box'); + Object.defineProperty(proto, 'scrollWidth', { configurable: true, get(this: HTMLElement) { return isBox(this) ? scrollWidth : 0; } }); + Object.defineProperty(proto, 'clientWidth', { configurable: true, get(this: HTMLElement) { return isBox(this) ? clientWidth : 0; } }); + return () => { + delete (proto as unknown as Record).scrollWidth; + delete (proto as unknown as Record).clientWidth; + }; + } + + it('a table wider than its box draws the bar at rest', () => { + const restore = stubBoxWidths(1400, 700); + try { + const { getByTestId } = renderTable(baseSchema); + const classes = getByTestId('data-table-scroll-box').className.split(/\s+/); + expect(classes).toContain(AT_REST); + expect(classes).not.toContain(TRANSPARENT); + } finally { + restore(); + } + }); + + it('CONTROL: a table that fits keeps the hover-only bar', () => { + const restore = stubBoxWidths(700, 700); + try { + const { getByTestId } = renderTable(baseSchema); + const classes = getByTestId('data-table-scroll-box').className.split(/\s+/); + expect(classes).toContain(TRANSPARENT); + expect(classes).not.toContain(AT_REST); + } finally { + restore(); + } + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/row-action-sticky.test.tsx b/ui/packages/plugin-grid/src/__tests__/row-action-sticky.test.tsx index 1acbcfcff6a..5bd2a7175cd 100644 --- a/ui/packages/plugin-grid/src/__tests__/row-action-sticky.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/row-action-sticky.test.tsx @@ -87,3 +87,62 @@ describe('row-actions column sticky-right', () => { await waitFor(() => expect(screen.getAllByTestId('row-action-inline-open').length).toBe(ROWS.length)); }); }); + +/** + * objectstack#35446 — while the table overflows its box, the row-actions + * column leaves the right edge, where it sat over the data column reaching + * that edge at rest, and joins the frozen zone right after the name column; + * a table that fits keeps it pinned right (the cases above). jsdom does no + * layout, so the box's widths are stubbed; the geometry itself is pinned in + * Chromium by `e2e/list-narrow-pinned-columns-35446.spec.ts`. + */ +describe('row-actions column in the frozen zone while the table overflows (objectstack#35446)', () => { + function stubBoxWidths(scrollWidth: number, clientWidth: number): () => void { + const proto = HTMLElement.prototype; + const isBox = (el: HTMLElement) => el.hasAttribute('data-table-scroll-box'); + Object.defineProperty(proto, 'scrollWidth', { configurable: true, get(this: HTMLElement) { return isBox(this) ? scrollWidth : 0; } }); + Object.defineProperty(proto, 'clientWidth', { configurable: true, get(this: HTMLElement) { return isBox(this) ? clientWidth : 0; } }); + return () => { + delete (proto as unknown as Record).scrollWidth; + delete (proto as unknown as Record).clientWidth; + }; + } + + const headerKeys = () => + Array.from(document.querySelectorAll('thead th')) + .map((th) => th.getAttribute('data-column-key')) + .filter(Boolean); + + it('draws the actions column after the frozen name column, frozen with it, not pinned right', async () => { + const restore = stubBoxWidths(1000, 600); + try { + renderGrid({ rowActionDefs: [{ name: 'archive', label: 'Archive' }] }); + await waitFor(() => expect(document.querySelector('[data-row-actions-column="frozen"]')).not.toBeNull()); + expect(headerKeys()).toEqual(['name', '_actions', 'amount']); + const actionsHeader = document.querySelector('th[data-column-key="_actions"]') as HTMLElement; + expect(actionsHeader.className).toContain('sticky'); + expect(actionsHeader.className).not.toContain('right-0'); + const actionsCell = screen.getAllByTestId('row-action-trigger')[0].closest('td')!; + expect(actionsCell.className).toContain('sticky'); + expect(actionsCell.className).not.toContain('right-0'); + // The name column stays frozen ahead of it. + expect(screen.getByText('Alice').closest('td')!.className).toContain('sticky'); + expect(document.querySelector('td.right-0')).toBeNull(); + } finally { + restore(); + } + }); + + it('folds an inline primary action into the row menu first, then moves the column', async () => { + const restore = stubBoxWidths(1000, 600); + try { + renderGrid(); + await waitFor(() => expect(document.querySelector('[data-row-actions-column="frozen"]')).not.toBeNull()); + expect(document.querySelector('[data-row-actions-inline="folded"]')).not.toBeNull(); + expect(screen.queryAllByTestId('row-action-inline-open')).toHaveLength(0); + expect(headerKeys()).toEqual(['name', '_actions', 'amount']); + } finally { + restore(); + } + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts b/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts index fb643f738af..e02f996eb02 100644 --- a/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts +++ b/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts @@ -112,9 +112,11 @@ export function useInlineRowActionFold(rows: unknown, columnsKey: string): { return; } } else if (overflow > OVERFLOW_SLACK_PX && box.querySelector('[data-testid^="row-action-inline-"]')) { - // Fold first: the column's placement is read from the menu-only face. + // Fold first: the column's placement is read from the menu-only face, + // once it has drawn, whether or not the fold resizes the box. unfoldedWidthRef.current = tableWidth; decide(true); + schedule(); return; } if (!box.querySelector('th[data-column-key="_actions"]')) return; From 8f9b54adb5fc7947ae2742b9c2802f7481aafaf5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 14:06:45 +0000 Subject: [PATCH 04/13] fix(grid): type the frozen-zone column read and add the changeset Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .changeset/35446-list-narrow-fixed-columns.md | 13 +++++++++++++ ui/packages/plugin-grid/src/ObjectGrid.tsx | 15 +++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-) create mode 100644 .changeset/35446-list-narrow-fixed-columns.md diff --git a/.changeset/35446-list-narrow-fixed-columns.md b/.changeset/35446-list-narrow-fixed-columns.md new file mode 100644 index 00000000000..8489e063a22 --- /dev/null +++ b/.changeset/35446-list-narrow-fixed-columns.md @@ -0,0 +1,13 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/components': patch +--- + +fix(grid): a list in a narrowed main area keeps every data cell clear of its fixed columns and shows its horizontal scrollbar + +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. +- No column is hidden and no column configuration changes. diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 4c522fc8f4d..6345cbb3d61 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -1974,16 +1974,19 @@ export const ObjectGrid: React.FC = ({ className: ['px-3', col.className, rightPinnedClasses].filter(Boolean).join(' '), cellClassName: [rowHeightCellClass, col.cellClassName, rightPinnedCellClasses].filter(Boolean).join(' '), }); + // The same cell padding as at the right edge; the frozen zone's own sticky + // classes, offset and edge rule come from `data-table`. + const inFrozenZone = (col: any) => ({ + ...applyColumnChrome(col), + pinned: undefined, + className: ['px-3', col.className].filter(Boolean).join(' '), + cellClassName: [rowHeightCellClass, col.cellClassName].filter(Boolean).join(' '), + }); const orderedColumns = actionsInFrozenZone ? [ ...scrollingColumns.slice(0, actionsFrozenAt), - { - ...applyColumnChrome(actionsColumn), - pinned: undefined, - className: ['px-3', actionsColumn.className].filter(Boolean).join(' '), - cellClassName: [rowHeightCellClass, actionsColumn.cellClassName].filter(Boolean).join(' '), - }, + inFrozenZone(actionsColumn), ...scrollingColumns.slice(actionsFrozenAt), ...pinnedRightCols.filter((col: any) => col !== actionsColumn).map(rightPinned), ] From 8c4a9542d6f20c9f891236032f4daa91fa5de1ea Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:15:32 +0000 Subject: [PATCH 05/13] fix(console): the list page header drops its description and folds its actions while narrow Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .../app-shell/src/layout/PageHeader.tsx | 56 +++++++++++++++--- .../PageHeader.actionsFold-12705.test.tsx | 59 ++++++++++++++++++- .../src/views/objectViewPageHeader.tsx | 10 ++++ 3 files changed, 116 insertions(+), 9 deletions(-) diff --git a/ui/packages/app-shell/src/layout/PageHeader.tsx b/ui/packages/app-shell/src/layout/PageHeader.tsx index f2b2303e4f5..ce128f83a7a 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 ? ( + ); +}; + +const OverflowMenu: React.FC<{ label: string; children: React.ReactNode; onOpen?: () => void }> = ({ label, children, onOpen }) => ( + { if (open) onOpen?.(); }}> + + + + {children} + +); + +/** One selected record: its own actions, exactly as its row menu resolves them. */ +const SingleRecordActions: React.FC<{ menu: RowActionMenuProps; moreLabel: string; editLabel: string }> = ({ + menu, moreLabel, editLabel, +}) => { + const plan = useRowActionPlan(menu, 0); + const { exposed, exposeEdit, rest } = planExposedRowActions(plan); + React.useEffect(() => { + menu.onActionsDemand?.(); + }, [menu.onActionsDemand]); + return ( + <> + {exposed.map((def) => ( + + ))} + {exposeEdit && } + {rest.menuCount > 0 && ( + + + + )} + + ); +}; + +/** Two or more selected records: the bulk actions, the same set the bulk bar offered. */ +const BulkActions: React.FC<{ + selectedRows: any[]; + actions: string[]; + actionDefs?: BulkActionDef[]; + objectFields?: unknown; + onAction?: (action: string, selectedRows: any[]) => void; + onActionDef?: (def: BulkActionDef, selectedRows: any[]) => void; + moreLabel: string; +}> = ({ selectedRows, actions, actionDefs, objectFields, onAction, onActionDef, moreLabel }) => { + const items = useBulkActionItems({ selectedRows, actions, actionDefs, objectFields }); + const ordered = orderSelectionMenuItems(items); + const exposed = ordered.filter((e) => !e.destructive).slice(0, SELECTION_EXPOSED_ACTIONS); + const exposedKeys = new Set(exposed.map((e) => e.key)); + const rest = ordered.filter((e) => !exposedKeys.has(e.key)); + return ( + <> + {exposed.map((entry) => + entry.kind === 'def' ? ( + + ) : ( + + ), + )} + {rest.length > 0 && ( + + + + )} + + ); +}; + +export interface SelectionPageBarProps { + selectedRows: any[]; + /** The props the ONE selected row's menu renders with (its "⋮" and its context menu). */ + singleRowMenu?: RowActionMenuProps; + actions: string[]; + actionDefs?: BulkActionDef[]; + objectFields?: unknown; + onAction?: (action: string, selectedRows: any[]) => void; + onActionDef?: (def: BulkActionDef, selectedRows: any[]) => void; + onClearSelection: () => void; + /** Rows the list holds now (all of them are selectable by the header box). */ + loadedCount: number; + /** Every row the query matches, when known. */ + totalMatching?: number; + allMatchingSelected?: boolean; + /** Absent ⇒ the selection cannot grow past the loaded rows. */ + onSelectAllMatching?: () => void; +} + +/** + * objectstack#35554 — what the list page bar shows while rows are selected, + * in place of its title and actions: 「已选 N 条」, Cancel, and the actions for + * what is selected (one record: its own actions; two or more: the bulk + * actions), the first {@link SELECTION_EXPOSED_ACTIONS} as buttons and the rest + * behind a "⋮". With every loaded row selected and more matching, it offers + * 「选择全部 M 条」, the cross-window selection the bulk bar used to offer. + */ +export const SelectionPageBar: React.FC = ({ + selectedRows, + singleRowMenu, + actions, + actionDefs, + objectFields, + onAction, + onActionDef, + onClearSelection, + loadedCount, + totalMatching, + allMatchingSelected, + onSelectAllMatching, +}) => { + const { t } = useObjectTranslation(); + const overCap = exceedsBulkSelectAllMatchingCap(totalMatching); + const count = selectedRows.length; + const offerAll = + !allMatchingSelected + && !!onSelectAllMatching + && typeof totalMatching === 'number' + && loadedCount > 0 + && count >= loadedCount + && totalMatching > loadedCount; + const moreLabel = t('detail.moreActions', { defaultValue: 'More actions' }); + return ( +
+ + {allMatchingSelected + ? overCap + ? t('grid.bulkSelectedAllMatchesCapped', { + cap: BULK_SELECT_ALL_MATCHING_CAP, + total: totalMatching, + defaultValue: '{{cap}} selected (of {{total}} matches)', + }) + : t('grid.bulkSelectedAllMatches', { count: totalMatching, defaultValue: '{{count}} selected (all matches)' }) + : t('grid.selectedCount', { count, defaultValue: '{{count}} selected' })} + + + {offerAll && ( + + + {t('grid.selectedAllLoaded', { count: loadedCount, defaultValue: 'All {{count}} loaded records are selected.' })} + + + + )} +
+ {count === 1 && !allMatchingSelected && singleRowMenu ? ( + + ) : ( + + )} +
+
+ ); +}; diff --git a/ui/packages/plugin-grid/src/index.tsx b/ui/packages/plugin-grid/src/index.tsx index c1ad54fb5ac..0d39d059ab3 100644 --- a/ui/packages/plugin-grid/src/index.tsx +++ b/ui/packages/plugin-grid/src/index.tsx @@ -37,6 +37,12 @@ export { useGroupedData } from './useGroupedData'; export { GroupRow } from './GroupRow'; export { RowActionMenu, formatActionLabel } from './components/RowActionMenu'; export { BulkActionBar } from './components/BulkActionBar'; +// objectstack#35554 — the list page bar's selection slot, read by the Console +// page header, and the kept scroll position a list host loads back to. +export { useListPageBarHost } from './listPageBarSlot'; +export type { ListPageBarState } from './listPageBarSlot'; +export { readListScrollState } from './objectGridInfiniteLoad'; +export type { ListScrollState } from './objectGridInfiniteLoad'; // The bare-name fold, its development warning and the bar's own gate (the // capability check, the switch-off and the per-record `visible`), for the one // other surface that draws a selection bar of its own: plugin-list's ListView diff --git a/ui/packages/plugin-grid/src/listPageBarSlot.ts b/ui/packages/plugin-grid/src/listPageBarSlot.ts new file mode 100644 index 00000000000..9b75ea93335 --- /dev/null +++ b/ui/packages/plugin-grid/src/listPageBarSlot.ts @@ -0,0 +1,130 @@ +/** + * 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#35554 — the list page bar's selection slot. + * + * On the object list page the page bar (the Console's page header) and the + * grid are siblings: neither renders the other, and the component that renders + * both is not the place a selection belongs. The page bar therefore offers a + * SLOT, and the grid fills it: + * + * - The page bar registers a host: the element its selection content is drawn + * into (`slot`) and the element whose subtree it speaks for (`scope`, the + * page column that holds the page bar and the list). + * - A grid whose root sits inside a host's scope is that page's list. It + * portals its selection content (「已选 N 条」, Cancel, the actions) into the + * slot, tells the host when a selection is open, and reports its match total + * for the count beside the view name. + * - A grid inside no host's scope — a related list, a page block, a grid in + * the record drawer (which is not inside the page column) — finds no host + * and keeps its own row-end actions and its own bulk bar, as before. + * + * The host's state lives here rather than in a React context because no + * common ancestor of the two is in reach of either package; the store is a + * plain external store read through `useSyncExternalStore`. + */ + +import React from 'react'; + +export interface ListPageBarState { + /** A selection is open: the page bar shows the slot in place of its own content. */ + selecting: boolean; + /** The list's match total (every row the query matches), when the list knows it. */ + total?: number; +} + +interface Host { + slot: HTMLElement; + scope: HTMLElement; + state: ListPageBarState; +} + +const EMPTY_STATE: ListPageBarState = { selecting: false }; + +const hosts = new Set(); +const listeners = new Set<() => void>(); + +function emit(): void { + for (const listener of listeners) listener(); +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +function hostOf(slot: HTMLElement | null): Host | undefined { + if (!slot) return undefined; + for (const host of hosts) if (host.slot === slot) return host; + return undefined; +} + +/** + * The page bar's side: register `slot` (drawn by the page bar) for the subtree + * of `scope`, and read the state the list writes. Unregisters on unmount. + */ +export function useListPageBarHost( + slot: HTMLElement | null, + scope: HTMLElement | null, +): ListPageBarState { + React.useLayoutEffect(() => { + if (!slot || !scope) return undefined; + const host: Host = { slot, scope, state: EMPTY_STATE }; + hosts.add(host); + emit(); + return () => { + hosts.delete(host); + emit(); + }; + }, [slot, scope]); + return React.useSyncExternalStore( + subscribe, + () => hostOf(slot)?.state ?? EMPTY_STATE, + () => EMPTY_STATE, + ); +} + +/** The slot of the host whose scope holds `el`, or `null`. */ +function findSlotFor(el: HTMLElement | null): HTMLElement | null { + if (!el) return null; + for (const host of hosts) if (host.scope.contains(el)) return host.slot; + return null; +} + +/** + * The grid's side: the page bar slot the grid rooted at `root` fills, or + * `null` when the grid is not a list page's list. + */ +export function useListPageBarSlot(root: HTMLElement | null): HTMLElement | null { + return React.useSyncExternalStore( + subscribe, + () => findSlotFor(root), + () => null, + ); +} + +/** Write the list's side of the host state (a no-op when `slot` is `null`). */ +export function useListPageBarState(slot: HTMLElement | null, state: ListPageBarState): void { + const { selecting, total } = state; + React.useLayoutEffect(() => { + const host = hostOf(slot); + if (!host) return undefined; + host.state = { selecting, total }; + emit(); + return () => { + // Only clear what is still ours: a re-render may have written newer state. + if (hosts.has(host)) { + host.state = EMPTY_STATE; + emit(); + } + }; + }, [slot, selecting, total]); +} diff --git a/ui/packages/plugin-grid/src/objectGridActionsColumn.tsx b/ui/packages/plugin-grid/src/objectGridActionsColumn.tsx index a0cc46ec488..16d0d6e977e 100644 --- a/ui/packages/plugin-grid/src/objectGridActionsColumn.tsx +++ b/ui/packages/plugin-grid/src/objectGridActionsColumn.tsx @@ -30,7 +30,7 @@ export function resolveObjectGridActionsColumn({ schema, data, objectSchema, persistedColumns, operations, resolvedRowActionDefs, wantEditAction, wantDeleteAction, mayInvokeRowAction, rowOperations, canEdit, canDelete, recordVerdict, predicateScope, onEdit, onDelete, editPredicates, deletePredicates, executeAction, - setRefreshKey, t, foldInlineRowActions = false, + setRefreshKey, t, foldInlineRowActions = false, drawRowControls = true, }: { schema: ObjectGridSchema; data: any[]; @@ -60,6 +60,13 @@ export function resolveObjectGridActionsColumn({ * (`./objectGridInlineActionFold`). */ foldInlineRowActions?: boolean; + /** + * objectstack#35554 — `false` on a list page, whose rows carry no control at + * all: no Actions column is drawn, and a row's actions are reached through + * the page bar (its selection) and the row's context menu, which read the + * same `rowActionMenuProps`. + */ + drawRowControls?: boolean; }) { // `operations`, the row-action lists and the row CRUD affordance verdict are // resolved further up, next to the permission reads they AND with — this @@ -101,7 +108,7 @@ export function resolveObjectGridActionsColumn({ }); return plan.inline.length > 0 || plan.menuCount > 0; }; - const drawActionsColumn = (hasActions || hasRowActions) && data.some(rowOffersAction); + const drawActionsColumn = drawRowControls && (hasActions || hasRowActions) && data.some(rowOffersAction); /** * The props ONE row's "⋮" cell renders with — and, verbatim, the props its diff --git a/ui/packages/plugin-grid/src/objectGridInfiniteLoad.ts b/ui/packages/plugin-grid/src/objectGridInfiniteLoad.ts new file mode 100644 index 00000000000..43e47525cd4 --- /dev/null +++ b/ui/packages/plugin-grid/src/objectGridInfiniteLoad.ts @@ -0,0 +1,153 @@ +/** + * 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#35554 — a list that loads as it scrolls, and comes back where + * it was left. + * + * The host owns the rows and the fetch (`ListView` on the list page): it hands + * the grid `onLoadMore` and `hasMoreRows`, and this hook calls `onLoadMore` + * when the table's own scroll box (`data-table-scroll-box`) comes within + * {@link LOAD_MORE_THRESHOLD_PX} of its end — or when the loaded rows do not + * fill the box at all, so a short first window never strands the rest. + * + * The scroll position is kept in session storage under the host's + * `scrollRestoreKey`, with the number of rows loaded when it was taken. The + * host reads that number back on its next mount ({@link readListScrollState}) + * to load as many rows again, and this hook restores the position once they + * are on screen. Clicking into a record on its own page and coming back + * therefore lands near the row that was left. + */ + +import React from 'react'; + +/** How close to the end of the scroll box the next window is asked for. */ +export const LOAD_MORE_THRESHOLD_PX = 320; + +const STORAGE_PREFIX = 'os:list-scroll:'; + +export interface ListScrollState { + /** The scroll box's `scrollTop`. */ + top: number; + /** Rows the list held when the position was taken. */ + rows: number; +} + +/** The kept position of the list `key` names, or `null`. Never throws. */ +export function readListScrollState(key: string | undefined): ListScrollState | null { + if (!key) return null; + try { + const raw = window.sessionStorage.getItem(STORAGE_PREFIX + key); + if (!raw) return null; + const parsed = JSON.parse(raw) as Partial; + if (typeof parsed?.top !== 'number' || typeof parsed?.rows !== 'number') return null; + if (!Number.isFinite(parsed.top) || !Number.isFinite(parsed.rows) || parsed.top < 0 || parsed.rows < 0) return null; + return { top: parsed.top, rows: parsed.rows }; + } catch { + return null; + } +} + +function writeListScrollState(key: string, state: ListScrollState): void { + try { + window.sessionStorage.setItem(STORAGE_PREFIX + key, JSON.stringify(state)); + } catch { + // Storage refused (private mode, quota): the position is a convenience. + } +} + +function scrollBoxOf(root: HTMLElement | null): HTMLElement | null { + return root?.querySelector('[data-table-scroll-box]') ?? null; +} + +export function useInfiniteRowLoad({ + root, + enabled, + hasMore, + loading, + rowCount, + onLoadMore, + restoreKey, +}: { + root: HTMLElement | null; + enabled: boolean; + hasMore: boolean; + loading: boolean; + rowCount: number; + onLoadMore?: () => void; + restoreKey?: string; +}): void { + // The latest inputs, read by the scroll listener without re-binding it. + const latest = React.useRef({ enabled, hasMore, loading, rowCount, onLoadMore, restoreKey }); + React.useLayoutEffect(() => { + latest.current = { enabled, hasMore, loading, rowCount, onLoadMore, restoreKey }; + }); + // One request per row count: the host's next window arrives as more rows, + // and only then may the end of the box ask again. + const askedAtRows = React.useRef(null); + // The kept position, read once per list, restored once its rows are loaded. + const pendingRestore = React.useRef<{ key: string; state: ListScrollState } | null>(null); + const restoreReadFor = React.useRef(undefined); + + const maybeLoadMore = React.useCallback((box: HTMLElement) => { + const now = latest.current; + if (!now.enabled || !now.hasMore || now.loading || !now.onLoadMore) return; + if (pendingRestore.current) return; // the host is still loading back to the kept position + if (askedAtRows.current === now.rowCount) return; + // A box with no height is not laid out (hidden, or not yet measured): it + // has no end to be near, so it asks for nothing. + if (box.clientHeight === 0) return; + const remaining = box.scrollHeight - box.scrollTop - box.clientHeight; + if (remaining > LOAD_MORE_THRESHOLD_PX) return; + askedAtRows.current = now.rowCount; + now.onLoadMore(); + }, []); + + // A new window landed (or a load ended): allow the next ask, restore a kept + // position once enough rows are back, and fill a box the rows do not. + React.useLayoutEffect(() => { + if (!enabled) return; + if (restoreKey && restoreReadFor.current !== restoreKey) { + restoreReadFor.current = restoreKey; + const state = readListScrollState(restoreKey); + pendingRestore.current = state && state.top > 0 ? { key: restoreKey, state } : null; + } + if (askedAtRows.current !== null && askedAtRows.current !== rowCount) askedAtRows.current = null; + const box = scrollBoxOf(root); + if (!box || loading) return; + const pending = pendingRestore.current; + if (pending && (rowCount >= pending.state.rows || !hasMore)) { + pendingRestore.current = null; + box.scrollTop = pending.state.top; + } + maybeLoadMore(box); + }, [enabled, root, rowCount, loading, hasMore, restoreKey, maybeLoadMore]); + + React.useEffect(() => { + if (!enabled) return undefined; + const box = scrollBoxOf(root); + if (!box) return undefined; + let frame = 0; + const onScroll = () => { + if (frame) return; + frame = window.requestAnimationFrame(() => { + frame = 0; + const now = latest.current; + if (now.restoreKey && !pendingRestore.current) { + writeListScrollState(now.restoreKey, { top: box.scrollTop, rows: now.rowCount }); + } + maybeLoadMore(box); + }); + }; + box.addEventListener('scroll', onScroll, { passive: true }); + return () => { + box.removeEventListener('scroll', onScroll); + if (frame) window.cancelAnimationFrame(frame); + }; + }, [enabled, root, rowCount, maybeLoadMore]); +} diff --git a/ui/packages/plugin-grid/src/objectGridProps.ts b/ui/packages/plugin-grid/src/objectGridProps.ts index abb6668b4fe..ec801a2cb53 100644 --- a/ui/packages/plugin-grid/src/objectGridProps.ts +++ b/ui/packages/plugin-grid/src/objectGridProps.ts @@ -142,4 +142,20 @@ export interface ObjectGridExternalPaginationProps * escalation. */ findParams?: Record | null; + /** + * objectstack#35554 — the host loads its rows window by window (a list with + * no declared `pagination`): the grid draws no pager and asks for the next + * window through this as the table's scroll box nears its end. `rowCount` + * stays the whole match total, so 「选择全部 M 条」 and the count beside the + * view name read it. + */ + onLoadMore?: () => void; + /** objectstack#35554 — more rows match than the host has loaded. Read only with `onLoadMore`. */ + hasMoreRows?: boolean; + /** + * objectstack#35554 — where the table's scroll position is kept across a + * return to the list (session storage, under this key). The host names the + * list it shows; absent ⇒ nothing is kept. + */ + scrollRestoreKey?: string; } diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 01383274351..a9ce75997ea 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -67,7 +67,7 @@ import { canonicalAstOperator, isVirtualSearchField, platformProvisionsStorage, import { SystemFieldName } from '@objectstack/spec/system'; import { usePermissions } from '@object-ui/permissions'; import { RecordDetailPanel } from '@object-ui/plugin-detail'; -import { resolveBulkActions, useBulkActionItems, useUndeclaredActionNamesWarning } from '@object-ui/plugin-grid'; +import { resolveBulkActions, useBulkActionItems, useUndeclaredActionNamesWarning, readListScrollState } from '@object-ui/plugin-grid'; /** * The `case 'map'` branch below builds an `object-map` schema by flattening @@ -2554,6 +2554,17 @@ export const ListView = React.forwardRef(({ // call it from closures taken renders ago. A move to the page already shown // tells the host nothing. const [ownPage, setOwnPage] = React.useState(1); + // objectstack#35554 — the infinite list's windows (see `infiniteScroll`). + // The key the list's scroll position is kept under: this list as the + // address bar names it, read once. + const [scrollRestoreKey] = React.useState(() => + typeof window === 'undefined' + ? undefined + : `${schema.objectName ?? ''}|${window.location.pathname}${window.location.search}`, + ); + const [restoreRows] = React.useState(() => readListScrollState(scrollRestoreKey)?.rows ?? null); + const [loadedWindows, setLoadedWindows] = React.useState(null); + const infiniteAppendSkipRef = React.useRef(null); const pageControlled = page !== undefined; const serverPage = pageControlled ? page : ownPage; const pageMoveRef = React.useRef({ controlled: pageControlled, current: serverPage, onPageChange }); @@ -2756,8 +2767,32 @@ export const ListView = React.forwardRef(({ if (message) console.warn(message); }, [dynamicPageSize, authoredPageSize, schema.objectName, paginate]); - const fetchSkip = paginate ? (serverPage - 1) * effectivePageSize : 0; + // objectstack#35554 — a grid list with no DECLARED `pagination` loads as it + // scrolls: no pager, the next window is asked for as the table nears its + // end (`onLoadMore` below) and appended. A view that declares `pagination` + // keeps its pager. Spec `pagination` is optional with no default + // (`view.zod.ts`), so its presence is the declaration. The capped posture + // (a page block's bounded list) keeps its one window. + const infiniteScroll = paginate && !cappedWindow && schema.pagination === undefined; + // How many windows the list holds. `null` until the reader scrolls: then + // it is the windows needed to cover the rows a kept position was taken over + // (`readListScrollState`), so a return to the list loads back to the row it + // left from, in one request. + const loadedWindowCount = loadedWindows ?? Math.max(1, Math.ceil((restoreRows ?? 0) / effectivePageSize)); + const fetchSkip = infiniteScroll + ? (loadedWindowCount - 1) * effectivePageSize + : paginate ? (serverPage - 1) * effectivePageSize : 0; const serverTotal = paginate ? fetchedTotal : null; + const hasMoreRows = infiniteScroll && ( + serverTotal != null ? data.length < serverTotal : dataLimitReached + ); + const loadMoreRows = React.useCallback(() => { + // The window this ask appends: the effect below appends it to the rows on + // screen only when it is the one asked for here, so any other re-run with + // several windows held (a refresh after a write) re-reads them all. + infiniteAppendSkipRef.current = loadedWindowCount * effectivePageSize; + setLoadedWindows(loadedWindowCount + 1); + }, [loadedWindowCount, effectivePageSize]); // Row color state (initialized from schema, user can configure via popover) const [rowColorConfig, setRowColorConfig] = React.useState(schema.rowColor); @@ -4310,7 +4345,13 @@ export const ListView = React.forwardRef(({ // this effect's dependency list, so what reaches the wire and what // re-runs this effect are the same number — there is no second // spelling free to drift from it. - const skip = fetchSkip; + // objectstack#35554 — an infinite list appends the window `loadMoreRows` + // asked for; any other run with several windows held (a refresh, the + // first load back to a kept position) re-reads them all from the top. + const appendWindow = infiniteScroll && fetchSkip > 0 && infiniteAppendSkipRef.current === fetchSkip; + infiniteAppendSkipRef.current = null; + const skip = infiniteScroll && !appendWindow ? 0 : fetchSkip; + const windowSize = infiniteScroll && !appendWindow ? fetchSkip + effectivePageSize : effectivePageSize; // Hoisted out of the `find` call so the exact params that produced this // window can be handed down with it (objectui#4501). One object, one @@ -4322,7 +4363,7 @@ export const ListView = React.forwardRef(({ // [objectui#12081] The calendar's window is walked in fetch-batch // steps, so its first request asks for the batch; the walk sets // each later step's `$top` and `$skip` itself. - $top: calendarWindowNode ? DEFAULT_LIST_FETCH_BATCH_SIZE : effectivePageSize, + $top: calendarWindowNode ? DEFAULT_LIST_FETCH_BATCH_SIZE : windowSize, ...(skip > 0 ? { $skip: skip } : {}), ...(selectFields ? { $select: selectFields } : {}), ...(expandFields.length > 0 ? { $expand: expandFields } : {}), @@ -4363,7 +4404,8 @@ export const ListView = React.forwardRef(({ items = readListRows(results); } - setData(items); + if (appendWindow) setData((held) => [...held, ...items]); + else setData(items); if (windowCeiling) { const truncated = windowCeiling.truncated; setHeldCalendarWindow((held) => (held.truncated === truncated ? held : { ...held, truncated })); @@ -4405,7 +4447,7 @@ export const ListView = React.forwardRef(({ // Without a numeric total the grid is never handed a pager (the // `serverTotal != null` gate on the handoff), so no page past 1 is // reachable to clamp from. - if (skip > 0 && items.length === 0 && knownTotal !== null) { + if (!infiniteScroll && skip > 0 && items.length === 0 && knownTotal !== null) { const lastReachablePage = Math.max(1, Math.ceil(knownTotal / effectivePageSize)); const requestedPage = Math.floor(skip / effectivePageSize) + 1; if (lastReachablePage < requestedPage) { @@ -4423,7 +4465,7 @@ export const ListView = React.forwardRef(({ // A calendar's window is walked to its end, so it hides no reachable // row behind a batch: when the ceiling stops it, the a′ footnote says // so instead (objectui#12081). - setDataLimitReached(!calendarWindowNode && items.length >= effectivePageSize); + setDataLimitReached(!calendarWindowNode && items.length >= windowSize); } catch (err) { // Only log + surface errors from the latest request. A failed fetch is // NOT an empty result — record it so the render shows an error panel @@ -4528,7 +4570,7 @@ export const ListView = React.forwardRef(({ // silently un-suppresses nothing, because the finding it was suppressing // simply moves elsewhere. Add prose ABOVE this point, never below it. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [schema.objectName, schema.data, dataSource, authoredFilter, effectivePageSize, serverSort, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, refreshKey, searchTerm, searchFieldsSent, schema.columns, schema.kanban, schema.calendar, schema.gallery, schema.timeline, schema.gantt, schema.map, objectDef?.fields, objectDefLoaded, schema.refreshTrigger, perms, fetchSkip, groupingConfig, predicateProjectionKey, invalidationNonce, groupingNeedsHeaderQuery, calendarWindowKey, rowsCarryConcurrencyToken, queryDropFields]); // Re-fetch on filter/sort/search/refreshTrigger/perms/window change; `rowsCarryConcurrencyToken` (objectui#12292) re-reads the rows with their token when inline edit turns on + }, [schema.objectName, schema.data, dataSource, authoredFilter, effectivePageSize, serverSort, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, refreshKey, searchTerm, searchFieldsSent, schema.columns, schema.kanban, schema.calendar, schema.gallery, schema.timeline, schema.gantt, schema.map, objectDef?.fields, objectDefLoaded, schema.refreshTrigger, perms, fetchSkip, infiniteScroll, groupingConfig, predicateProjectionKey, invalidationNonce, groupingNeedsHeaderQuery, calendarWindowKey, rowsCarryConcurrencyToken, queryDropFields]); // Re-fetch on filter/sort/search/refreshTrigger/perms/window change; `rowsCarryConcurrencyToken` (objectui#12292) re-reads the rows with their token when inline edit turns on // Any change to the result-defining inputs (object, filters, sort, search, // grouping, page size) invalidates the current page number — snap back to @@ -4546,6 +4588,8 @@ export const ListView = React.forwardRef(({ if (prevPageResetSignature.current !== pageResetSignature) { prevPageResetSignature.current = pageResetSignature; setServerPage(1); + // objectstack#35554 — and an infinite list starts again from its first window. + setLoadedWindows(1); } }, [pageResetSignature]); @@ -6593,7 +6637,7 @@ export const ListView = React.forwardRef(({ const recordCountShown = !loading && data.length > 0 && surfaceDrawsFetchedRows && schema.showRecordCount !== false; const dataLimitWarningShown = - recordCountShown && dataLimitReached && !(paginate && serverTotal != null); + recordCountShown && dataLimitReached && !(paginate && serverTotal != null) && !infiniteScroll; // objectui#12619 — a board that pages its own lanes draws every record of the // view, a page per lane at a time, so the footer counts the VIEW: the total // this component's own query answered, which is the sum of the board's lane @@ -8036,18 +8080,32 @@ export const ListView = React.forwardRef(({ // own loading state only when it has nothing to draw. loading={calendarWindowed ? loading && data.length === 0 : loading} onRowSelect={setSelectedRows} - {...(paginate && serverTotal != null + {...((paginate && serverTotal != null) || infiniteScroll ? { // Drive the flat grid's single (DataTable) pager from the // server: it renders THIS window as the current page, the real // total sets the page count, and turning the page asks ListView // to refetch the next window. One pager, server-backed (objectstack-ai/objectstack#2212). manualPagination: true, - rowCount: serverTotal, - page: serverPage, - pageSize: effectivePageSize, - onPageChange: (p: number) => setServerPage(p), - onPageSizeChange: (n: number) => { setDynamicPageSize(n); setServerPage(1); }, + rowCount: serverTotal ?? data.length, + ...(infiniteScroll + ? { + // objectstack#35554 — no pager: every loaded window is + // one page of rows, the grid asks for the next as it + // nears its end, and `rowCount` stays the match total. + page: 1, + pageSize: Math.max(data.length, effectivePageSize), + onPageChange: () => {}, + onLoadMore: loadMoreRows, + hasMoreRows, + scrollRestoreKey, + } + : { + page: serverPage, + pageSize: effectivePageSize, + onPageChange: (p: number) => setServerPage(p), + onPageSizeChange: (n: number) => { setDynamicPageSize(n); setServerPage(1); }, + }), // …and its sort from the same place (#3106). The column // headers and the toolbar's sort builder are two controls over // ONE `currentSort`, so a header click is a shortcut into the diff --git a/ui/packages/plugin-list/src/__tests__/ListView.calendarDateWindow-12081.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.calendarDateWindow-12081.test.tsx index a009c85220c..6215fed6634 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.calendarDateWindow-12081.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.calendarDateWindow-12081.test.tsx @@ -274,7 +274,9 @@ describe('CONTROL — every other view asks exactly what it asked before (object it('the paged grid: one page, its `$top`, no window, and the next page by `$skip`', async () => { const ds = makeDataSource(contractsIn(9, 122, 'oct')); - renderList({ viewType: 'grid' }, ds); + // A grid that declares `pagination` pages; one that declares none loads + // as it scrolls (objectstack#35554), which is not the window under test. + renderList({ viewType: 'grid', pagination: {} }, ds); await waitFor(() => expect(lastGridProps?.manualPagination).toBe(true)); expect(ds.calls).toEqual([ { $orderby: undefined, $top: SPEC_DISPLAY_DEFAULT, $select: ['id', 'name', 'status'] }, From 3712353acc6ea6d06fee72a8430a29a1f057e7a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 17:55:52 +0000 Subject: [PATCH 08/13] test(e2e): style the list fixture before it mounts and serve it at a real origin An unstyled scroll box has no height bound, so the list read it as always near its end and loaded every row; the console's stylesheet is there first. Session storage, which keeps the list position, is refused on about:blank. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZL84qjxXbtxcXE8rW --- ui/e2e/list-no-actions-column-35554.spec.ts | 40 ++++++++++++++++++--- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/ui/e2e/list-no-actions-column-35554.spec.ts b/ui/e2e/list-no-actions-column-35554.spec.ts index c819f61dbc7..238252f663d 100644 --- a/ui/e2e/list-no-actions-column-35554.spec.ts +++ b/ui/e2e/list-no-actions-column-35554.spec.ts @@ -134,7 +134,7 @@ const ROWS = Array.from({ length: ${ROW_COUNT} }, (_, i) => ({ account: '客户 ' + ((i % 17) + 1), stage: STAGES[i % STAGES.length], amount: 10000 + i * 1000, - probability: 20 + (i % 4) * 20, + probability: (20 + (i % 4) * 20) / 100, owner: '销售 ' + ((i % 5) + 1), close_date: '2027-01-' + String((i % 28) + 1).padStart(2, '0'), })); @@ -273,6 +273,8 @@ async function tailwindFor(candidates: string[]): Promise { let bundle = ''; const compiled = new Set(); +/** The last stylesheet compiled: a mount starts from it (see `mount`). */ +let stylesheet = ''; /** Compile the stylesheet until the page's class set stops growing. */ async function styleUntilStable(page: Page): Promise { @@ -288,6 +290,7 @@ async function styleUntilStable(page: Page): Promise { if (round === 6) throw new Error('the page kept adding classes; the stylesheet never caught up'); candidates.forEach((cls) => compiled.add(cls)); const css = await tailwindFor([...compiled]); + stylesheet = css; await page.evaluate((text) => { let sheet = document.getElementById('tailwind'); if (!sheet) { @@ -301,12 +304,40 @@ async function styleUntilStable(page: Page): Promise { } } +/** + * The fixture page at a real origin: the list keeps its scroll position in + * session storage, which an `about:blank` page (an opaque origin) refuses. + */ +const FIXTURE_URL = 'http://list-fixture.test/apps/sales/opportunity/view/open'; +async function openFixturePage(page: Page, html: string): Promise { + await page.route(FIXTURE_URL, (route) => route.fulfill({ status: 200, contentType: 'text/html', body: html })); + await page.goto(FIXTURE_URL); + await page.unroute(FIXTURE_URL); +} + async function mount(page: Page, viewport: { width: number; height: number }, c: Case = {}): Promise { await page.setViewportSize(viewport); - await page.setContent('
'); - await page.evaluate((value) => { + // The list asks for its next window while its scroll box is near its end, + // which an unstyled box (no height bound) always is: a page mounted before + // its stylesheet would load every row at once, which the console, whose + // stylesheet is there first, never does. So the page is styled BEFORE the + // list mounts: the first mount of a worker is a throwaway that collects the + // page's classes, and every mount then starts from the compiled sheet. + if (!stylesheet) { + 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.getByText('商机 1', { exact: true }).waitFor({ timeout: 30_000 }); + await styleUntilStable(page); + } + await openFixturePage(page, '
'); + await page.evaluate(({ value, css }) => { (window as unknown as { __case: Case }).__case = value; - }, c); + document.getElementById('tailwind')!.textContent = css; + try { window.sessionStorage.clear(); } catch { /* a fresh page holds nothing */ } + }, { value: c, css: stylesheet }); await page.addScriptTag({ content: bundle, type: 'module' }); await page.getByText('商机 1', { exact: true }).waitFor({ timeout: 30_000 }); await styleUntilStable(page); @@ -415,6 +446,7 @@ for (const viewport of VIEWPORTS) { }); await expect.poll(() => loadedRows(page)).toBe(100); await page.locator('thead').getByRole('checkbox').click(); + await styleUntilStable(page); const bar = page.getByTestId('list-selection-page-bar'); await expect(bar.getByTestId('list-selection-count')).toHaveText('已选 100 条'); await expect(bar.getByTestId('list-selection-select-all')).toHaveText('选择全部 120 条'); From bcfec2893ac087e9d3fdf93d6714498564f44fd3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:01:49 +0000 Subject: [PATCH 09/13] refactor(list): the page bar carries no count chip The count beside the view name is the view switcher's, so the page bar's badge stays as it was and the selection slot reports only that a selection is open. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZL84qjxXbtxcXE8rW --- .../app-shell/src/views/objectViewPageHeader.tsx | 14 +------------- ui/packages/plugin-grid/src/ObjectGrid.tsx | 2 +- .../src/__tests__/listPageBarSlot-35554.test.tsx | 1 - ui/packages/plugin-grid/src/listPageBarSlot.ts | 11 ++++------- 4 files changed, 6 insertions(+), 22 deletions(-) diff --git a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx index e616ead1c87..4ba0485e295 100644 --- a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx +++ b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx @@ -19,7 +19,6 @@ import { DropdownMenuTrigger, } from '@object-ui/components'; import { Upload, MoreHorizontal } from 'lucide-react'; -import { useDisplayLocale } from '@object-ui/i18n'; import type { useObjectLabel, useObjectTranslation } from '@object-ui/i18n'; import { FavoriteMenuItem } from '../layout/SidebarItemMenu.js'; import type { useObjectListFavorite } from '../layout/SidebarItemMenu.js'; @@ -134,23 +133,12 @@ export function ObjectViewPageHeader({ // `@object-ui/plugin-grid`). The list in this page column fills it while // rows are selected — 「已选 N 条」, Cancel and the actions for what is // selected — and this bar shows it in place of its title and actions. - // The list also reports its match total, drawn beside the view name. const [selectionSlot, setSelectionSlot] = useState(null); const [pageColumn, setPageColumn] = useState(null); const headerRootRef = useCallback((el: HTMLDivElement | null) => { setPageColumn(el?.parentElement ?? null); }, []); const pageBar = useListPageBarHost(selectionSlot, pageColumn); - const displayLocale = useDisplayLocale(); - const totalCount = typeof pageBar.total === 'number' ? ( - - {pageBar.total.toLocaleString(displayLocale)} - - ) : null; // A view with no label is already called by the plural (objectui#12774): // the switcher names the object, and a crumb would say it twice. const title = titleSwitcher == null @@ -192,7 +180,7 @@ export function ObjectViewPageHeader({ // (objectui#12606). // objectstack#28950 — and, before it, the 「Personalized」 // marker while the reader's list differs from the view. - badge={<>{totalCount}{personalizedMarker}} + badge={<>{personalizedMarker}} subtitle={objectDef.description ? objectDesc(objectDef) : undefined} // `createElement`, not a JSX tag: the looked-up icon is a value, // which react-hooks/static-components refuses in tag position diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 24a7a03917e..52904c9b93a 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -1463,7 +1463,7 @@ export const ObjectGrid: React.FC = ({ // objectstack#35554 — tell the page bar whether a selection is open and how // many rows the list's query matches (the count beside the view name). - useListPageBarState(pageBarSlot, { selecting: selectedRows.length > 0, total: resolvedTotalMatching }); + useListPageBarState(pageBarSlot, { selecting: selectedRows.length > 0 }); // objectstack#35554 — a host that loads its rows window by window // (`onLoadMore`) is asked for the next window as the table's scroll box diff --git a/ui/packages/plugin-grid/src/__tests__/listPageBarSlot-35554.test.tsx b/ui/packages/plugin-grid/src/__tests__/listPageBarSlot-35554.test.tsx index e5c9b051351..729d9a3f5c4 100644 --- a/ui/packages/plugin-grid/src/__tests__/listPageBarSlot-35554.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/listPageBarSlot-35554.test.tsx @@ -81,7 +81,6 @@ const PageBar: React.FC = () => { const state = useListPageBarHost(slot, scope); return (
setScope(el?.parentElement ?? null)} data-testid="page-bar" data-selecting={state.selecting ? 'yes' : 'no'}> - {state.total ?? ''}
); diff --git a/ui/packages/plugin-grid/src/listPageBarSlot.ts b/ui/packages/plugin-grid/src/listPageBarSlot.ts index 9b75ea93335..48bb4ee5f78 100644 --- a/ui/packages/plugin-grid/src/listPageBarSlot.ts +++ b/ui/packages/plugin-grid/src/listPageBarSlot.ts @@ -19,8 +19,7 @@ * page column that holds the page bar and the list). * - A grid whose root sits inside a host's scope is that page's list. It * portals its selection content (「已选 N 条」, Cancel, the actions) into the - * slot, tells the host when a selection is open, and reports its match total - * for the count beside the view name. + * slot and tells the host when a selection is open. * - A grid inside no host's scope — a related list, a page block, a grid in * the record drawer (which is not inside the page column) — finds no host * and keeps its own row-end actions and its own bulk bar, as before. @@ -35,8 +34,6 @@ import React from 'react'; export interface ListPageBarState { /** A selection is open: the page bar shows the slot in place of its own content. */ selecting: boolean; - /** The list's match total (every row the query matches), when the list knows it. */ - total?: number; } interface Host { @@ -113,11 +110,11 @@ export function useListPageBarSlot(root: HTMLElement | null): HTMLElement | null /** Write the list's side of the host state (a no-op when `slot` is `null`). */ export function useListPageBarState(slot: HTMLElement | null, state: ListPageBarState): void { - const { selecting, total } = state; + const { selecting } = state; React.useLayoutEffect(() => { const host = hostOf(slot); if (!host) return undefined; - host.state = { selecting, total }; + host.state = { selecting }; emit(); return () => { // Only clear what is still ours: a re-render may have written newer state. @@ -126,5 +123,5 @@ export function useListPageBarState(slot: HTMLElement | null, state: ListPageBar emit(); } }; - }, [slot, selecting, total]); + }, [slot, selecting]); } From 4e3218a6729f16894440dc23ecb32587653e3c31 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:01:13 +0000 Subject: [PATCH 10/13] test(e2e): the list pin reads the count from the view bar's switcher After the list page frame landed, the match total is the switcher's count (fed by the list through ListRecordCountContext); the fixture draws the real switcher in the view bar as the console does, and the selection face takes the 44px page bar's measure. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZL84qjxXbtxcXE8rW --- ui/e2e/list-no-actions-column-35554.spec.ts | 27 +++++++++++++++------ 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/ui/e2e/list-no-actions-column-35554.spec.ts b/ui/e2e/list-no-actions-column-35554.spec.ts index 238252f663d..bcc146a85de 100644 --- a/ui/e2e/list-no-actions-column-35554.spec.ts +++ b/ui/e2e/list-no-actions-column-35554.spec.ts @@ -25,7 +25,8 @@ import { uiRoot } from '../scripts/ui-root.mjs'; * ## What is real here and what is a fixture * * REAL: the Console list page header (`ObjectViewPageHeader` with its chrome - * hook), plugin-list's `ListView` (its fetch, its windows and its handoff to + * hook), the view bar's switcher (`ObjectViewTitleSwitcher`, handed the list's + * own count as the console hands it), plugin-list's `ListView` (its fetch, its windows and its handoff to * the grid), plugin-grid's `ObjectGrid`, the `data-table`, the selection bar, * the menus, the zh-Hans pack through the real `I18nProvider`, all bundled by * Vite from their source files and mounted in Chromium; the stylesheet is real @@ -59,6 +60,7 @@ const REACT_BINDINGS = source('packages/react/src/index.ts'); const I18N = source('packages/i18n/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'); +const TITLE_SWITCHER = source('packages/app-shell/src/views/objectViewTitleSwitcher.tsx'); /** The two windows the card accepts at. */ const VIEWPORTS = [ @@ -109,6 +111,7 @@ import { ActionProvider, SchemaRendererProvider } from ${JSON.stringify(REACT_BI import { I18nProvider, useObjectTranslation } from ${JSON.stringify(I18N)}; import { ObjectViewPageHeader } from ${JSON.stringify(PAGE_HEADER)}; import { useObjectViewHeaderChrome } from ${JSON.stringify(HEADER_CHROME)}; +import { ObjectViewTitleSwitcher, ListRecordCountContext } from ${JSON.stringify(TITLE_SWITCHER)}; registerAllFields(); const h = React.createElement; @@ -183,9 +186,6 @@ function Header() { }); return h(ObjectViewPageHeader, { objectDef: { name: 'opportunity', label: '商机', pluralLabel: '商机', icon: 'briefcase' }, - titleSwitcher: h('span', { 'data-testid': 'view-switcher' }, '进行中商机'), - titleLabel: '进行中商机', - objectListHref: '/apps/sales/opportunity', objectPluralLabel: () => '商机', objectDesc: () => undefined, createButton: chrome.createButton, @@ -199,11 +199,24 @@ function Header() { environmentEntitlements: undefined, toolbarBar: { type: 'action:bar', location: 'list_toolbar', actions: [], maxVisible: 3, mobileMaxVisible: 0 }, listFavorite: null, - personalizedMarker: null, foldedHeaderActions: chrome.foldedHeaderActions, }); } +// The view bar's lead, as the console draws it (objectstack#35548): the real +// switcher, fed the list's own count through ListRecordCountContext. +function ViewBarLead({ recordCount, layout }) { + const { t } = useObjectTranslation(); + return h(ListRecordCountContext.Provider, { value: { count: recordCount, layout } }, + h(ObjectViewTitleSwitcher, { + views: [{ id: 'open', label: '进行中商机', type: 'grid', authored: true }], + activeViewId: 'open', + activeLabel: '进行中商机', + onViewChange: () => {}, + t, + })); +} + const root = createRoot(document.getElementById('root')); let mounts = 0; window.__remount = () => root.render( @@ -214,7 +227,7 @@ window.__remount = () => root.render( h('div', { id: 'page-column', className: 'h-screen flex flex-col bg-background min-w-0 overflow-hidden' }, h(Header), h('div', { className: 'flex-1 min-h-0 flex flex-col' }, - h(ListView, { schema, dataSource, onEdit: () => window.__dispatched.push('edit'), onDelete: () => window.__dispatched.push('delete') }))))))), + h(ListView, { schema, dataSource, toolbarLeading: (state) => h(ViewBarLead, state), onEdit: () => window.__dispatched.push('edit'), onDelete: () => window.__dispatched.push('delete') }))))))), ); window.__unmount = () => root.render(null); window.__remount(); @@ -438,7 +451,7 @@ for (const viewport of VIEWPORTS) { test('no pager; scrolling to the end loads more; header select-all offers 「选择全部 120 条」', async ({ page }) => { await mount(page, viewport); await expect(page.getByRole('button', { name: /下一页|Next page/ })).toHaveCount(0); - await expect(page.getByTestId('list-total-count')).toHaveText('120'); + await expect(page.getByTestId('list-view-switcher-count')).toHaveText('120'); expect(await loadedRows(page)).toBe(50); await page.evaluate(() => { const box = document.querySelector('[data-table-scroll-box]')!; From dfa9840d697d0432f0717cf5965a5581bf136a12 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:39:15 +0000 Subject: [PATCH 11/13] test(console): two list-page tests pay the lint load at collection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZL84qjxXbtxcXE8rW --- .../views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx | 3 +++ .../src/views/ObjectView.inviteOutcome-27797.test.tsx | 3 +++ 2 files changed, 6 insertions(+) diff --git a/ui/packages/app-shell/src/views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx b/ui/packages/app-shell/src/views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx index c78c39f536a..d2918a78c51 100644 --- a/ui/packages/app-shell/src/views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx @@ -29,6 +29,9 @@ import * as React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, cleanup, screen, fireEvent, waitFor, act, within } from '@testing-library/react'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { toast } from 'sonner'; import { createI18n, I18nProvider } from '@object-ui/i18n'; diff --git a/ui/packages/app-shell/src/views/ObjectView.inviteOutcome-27797.test.tsx b/ui/packages/app-shell/src/views/ObjectView.inviteOutcome-27797.test.tsx index 7013b020322..042c14a69f1 100644 --- a/ui/packages/app-shell/src/views/ObjectView.inviteOutcome-27797.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.inviteOutcome-27797.test.tsx @@ -41,6 +41,9 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, cleanup, screen, fireEvent, waitFor, act, within } from '@testing-library/react'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { toast } from 'sonner'; import { createI18n, I18nProvider } from '@object-ui/i18n'; From 2fba403ab6a30de59aa14fde367d30e1f04f622c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 20:13:11 +0000 Subject: [PATCH 12/13] test(e2e): live row-action specs open the row menu by right-click MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The list page draws no row "⋮" any more; a row's actions are its context menu, the same items. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZL84qjxXbtxcXE8rW --- ui/e2e/live/action-modal.spec.ts | 7 +++++-- ui/e2e/live/list-row-action-cel.spec.ts | 8 +++++--- ui/e2e/live/screen-flow.spec.ts | 8 +++++--- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/ui/e2e/live/action-modal.spec.ts b/ui/e2e/live/action-modal.spec.ts index 42ee6caa837..e7f7bfea0f1 100644 --- a/ui/e2e/live/action-modal.spec.ts +++ b/ui/e2e/live/action-modal.spec.ts @@ -7,8 +7,11 @@ import { test, expect } from '@playwright/test'; */ test('a row Edit action opens a modal form and closes', async ({ page }) => { await page.goto('/apps/showcase_app/showcase_task'); - await page.locator('[data-testid="row-action-trigger"]').first().waitFor(); - await page.locator('[data-testid="row-action-trigger"]').first().click(); + // objectstack#35554 — the list page draws no row "⋮": a row's actions are + // its context menu (right-click), the same items. + const row = page.locator('tbody tr').filter({ hasText: /\S/ }).first(); + await row.waitFor(); + await row.locator('td').last().click({ button: 'right' }); await page.getByRole('menuitem', { name: /^Edit$/i }).click(); const dialog = page.getByRole('dialog'); diff --git a/ui/e2e/live/list-row-action-cel.spec.ts b/ui/e2e/live/list-row-action-cel.spec.ts index f4b35261d3a..503722f7331 100644 --- a/ui/e2e/live/list-row-action-cel.spec.ts +++ b/ui/e2e/live/list-row-action-cel.spec.ts @@ -32,9 +32,11 @@ const API = process.env.LIVE_API_URL || 'http://localhost:3000'; test('row-action `visible` predicates are CEL-evaluated on the showcase task list', async ({ page }) => { await page.goto('/apps/showcase_app/showcase_task'); - const trigger = page.locator('[data-testid="row-action-trigger"]').first(); - await trigger.waitFor(); - await trigger.click(); + // objectstack#35554 — the list page draws no row "⋮": a row's actions are + // its context menu (right-click), the same items. + const row = page.locator('tbody tr').filter({ hasText: /\S/ }).first(); + await row.waitFor(); + await row.locator('td').last().click({ button: 'right' }); // The row menu renders; its items are gated by CEL `visible` predicates. // "Edit" is always present — proves the menu opened. diff --git a/ui/e2e/live/screen-flow.spec.ts b/ui/e2e/live/screen-flow.spec.ts index 6713a1875a8..dfba92262e9 100644 --- a/ui/e2e/live/screen-flow.spec.ts +++ b/ui/e2e/live/screen-flow.spec.ts @@ -39,9 +39,11 @@ test('a row flow action renders its screen and resumes the run', async ({ page } }); await page.goto('/apps/showcase_app/showcase_task'); - const rowMenu = page.locator('[data-testid="row-action-trigger"]').first(); - await rowMenu.waitFor(); - await rowMenu.click(); + // objectstack#35554 — the list page draws no row "⋮": a row's actions are + // its context menu (right-click), the same items. + const row = page.locator('tbody tr').filter({ hasText: /\S/ }).first(); + await row.waitFor(); + await row.locator('td').last().click({ button: 'right' }); await page.getByTestId('row-action-showcase_bulk_reassign').click(); // The run paused at its screen node — the console renders it as a dialog. From 2a4b0b4de52ffb9d137f26bce9922d88f1d5d9e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 20:43:21 +0000 Subject: [PATCH 13/13] fix(list): re-read the held windows one window per request A host caps a read's top and refuses a read over it, so a list that held several windows and re-read them as one read after a write, or on coming back to a kept position, failed to read at all there. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZL84qjxXbtxcXE8rW --- ui/packages/plugin-list/src/ListView.tsx | 21 ++- ...tView.infiniteRereadPageCap-35554.test.tsx | 137 ++++++++++++++++++ 2 files changed, 155 insertions(+), 3 deletions(-) create mode 100644 ui/packages/plugin-list/src/__tests__/ListView.infiniteRereadPageCap-35554.test.tsx diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 8cbb159edfa..ab168985d85 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -4358,11 +4358,16 @@ export const ListView = React.forwardRef(({ // spelling free to drift from it. // objectstack#35554 — an infinite list appends the window `loadMoreRows` // asked for; any other run with several windows held (a refresh, the - // first load back to a kept position) re-reads them all from the top. + // first load back to a kept position) re-reads them all from the top, + // ONE WINDOW PER REQUEST: a host caps a read's `$top` + // (`OS_DATA_MAX_PAGE_SIZE`, refused with 400 MAX_RECORDS_EXCEEDED, never + // clamped), so the held rows are never asked for in one read. const appendWindow = infiniteScroll && fetchSkip > 0 && infiniteAppendSkipRef.current === fetchSkip; infiniteAppendSkipRef.current = null; const skip = infiniteScroll && !appendWindow ? 0 : fetchSkip; - const windowSize = infiniteScroll && !appendWindow ? fetchSkip + effectivePageSize : effectivePageSize; + const rereadWindows = infiniteScroll && !appendWindow ? fetchSkip / effectivePageSize + 1 : 1; + // Every row this run asks for, across its windows. + const windowSize = rereadWindows * effectivePageSize; // Hoisted out of the `find` call so the exact params that produced this // window can be handed down with it (objectui#4501). One object, one @@ -4374,7 +4379,7 @@ export const ListView = React.forwardRef(({ // [objectui#12081] The calendar's window is walked in fetch-batch // steps, so its first request asks for the batch; the walk sets // each later step's `$top` and `$skip` itself. - $top: calendarWindowNode ? DEFAULT_LIST_FETCH_BATCH_SIZE : windowSize, + $top: calendarWindowNode ? DEFAULT_LIST_FETCH_BATCH_SIZE : effectivePageSize, ...(skip > 0 ? { $skip: skip } : {}), ...(selectFields ? { $select: selectFields } : {}), ...(expandFields.length > 0 ? { $expand: expandFields } : {}), @@ -4409,6 +4414,16 @@ export const ListView = React.forwardRef(({ windowCeiling = applyNonGridRowCeiling(walked); results = walked; items = windowCeiling.rows; + } else if (rereadWindows > 1) { + // objectstack#35554 — the held windows, each its own read (above). + const objectName = schema.objectName; + const windows = await Promise.all( + Array.from({ length: rereadWindows }, (_, w) => + dataSource.find(objectName, w === 0 ? findParams : { ...findParams, $skip: w * effectivePageSize })), + ); + if (!isCurrentRequest()) return; + results = windows[0]; + items = windows.flatMap((w) => readListRows(w)); } else { results = await dataSource.find(schema.objectName, findParams); if (!isCurrentRequest()) return; diff --git a/ui/packages/plugin-list/src/__tests__/ListView.infiniteRereadPageCap-35554.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.infiniteRereadPageCap-35554.test.tsx new file mode 100644 index 00000000000..67cefd6b315 --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.infiniteRereadPageCap-35554.test.tsx @@ -0,0 +1,137 @@ +/** + * 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#35554 — a list that loads as it scrolls re-reads the windows it + * holds ONE WINDOW PER REQUEST, never as one read of every held row. + * + * A host caps a read's `$top` (`OS_DATA_MAX_PAGE_SIZE`, `query-read-limits.ts` + * in `@objectstack/types`) and refuses a read over it with 400 + * MAX_RECORDS_EXCEEDED — it refuses, it never clamps. A list that held five + * windows and then re-read them as `$top=250` after a write, or on coming back + * to a kept position, failed to read at all on such a host. + * + * The data source here refuses any `$top` over one window, as such a host + * does. Two runs re-read several held windows: the first load back to a kept + * scroll position, and the refresh after a write. + */ +import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest'; +import { act, cleanup, render, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { ComponentRegistry, ValueDataSource } from '@object-ui/core'; +import { SchemaRendererProvider } from '@object-ui/react'; +import { ListView, type ListViewHandle } from '../ListView'; + +type Row = Record; + +/** The list's window, the spec's display default for an unauthored page size. */ +const WINDOW = 50; +const ROWS: Row[] = Array.from({ length: 120 }, (_, i) => ({ id: `r${i + 1}`, name: `Row ${i + 1}` })); + +let lastGridProps: any = null; +let previous: unknown; +beforeAll(() => { + previous = ComponentRegistry.get('object-grid'); + ComponentRegistry.register('object-grid', (props: any) => { + lastGridProps = props; + return
; + }); +}); +afterAll(() => { + if (previous) ComponentRegistry.register('object-grid', previous as any); + else ComponentRegistry.unregister('object-grid'); +}); +beforeEach(() => { + lastGridProps = null; + window.sessionStorage.clear(); +}); +afterEach(() => { + cleanup(); + window.sessionStorage.clear(); +}); + +/** A data source that refuses a read over `maxTop`, as a capped host does. */ +function cappedDataSource(maxTop: number) { + const store = new ValueDataSource({ items: ROWS }); + const calls: Array> = []; + return { + calls, + find: vi.fn(async (object: string, params: any) => { + calls.push(params); + if (typeof params?.$top === 'number' && params.$top > maxTop) { + throw Object.assign(new Error(`limit ${params.$top} exceeds the maximum page size ${maxTop}`), { + status: 400, + code: 'MAX_RECORDS_EXCEEDED', + }); + } + return store.find(object, params); + }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: async (name: string) => ({ + name, + fields: { id: { type: 'text' }, name: { type: 'text' } }, + }), + } as any; +} + +/** The rows the grid was last handed. */ +const handedRows = (): Row[] => (lastGridProps?.data ?? lastGridProps?.schema?.data?.items ?? []) as Row[]; + +function renderList(ds: any, ref?: React.Ref) { + return render( + + + , + ); +} + +/** Keep a scroll position over `rows` rows, the way the grid does as it scrolls. */ +function keepPosition(rows: number) { + const key = `capped_object|${window.location.pathname}${window.location.search}`; + window.sessionStorage.setItem(`os:list-scroll:${key}`, JSON.stringify({ top: 4000, rows })); +} + +describe('objectstack#35554 — held windows are re-read one window per request', () => { + it('coming back to a kept position past one window: every held row is back, and no read asks over one window', async () => { + keepPosition(110); + const ds = cappedDataSource(WINDOW); + renderList(ds); + await waitFor(() => expect(handedRows()).toHaveLength(120)); + expect(handedRows().map((r) => r.id)).toEqual(ROWS.map((r) => r.id)); + expect(ds.calls.length).toBeGreaterThanOrEqual(3); + expect(Math.max(...ds.calls.map((c: any) => c.$top))).toBe(WINDOW); + expect(ds.calls.map((c: any) => c.$skip ?? 0).sort((a: number, b: number) => a - b)).toEqual([0, 50, 100]); + }); + + it('a refresh with three windows held re-reads the three, one window each', async () => { + const ds = cappedDataSource(WINDOW); + const ref = React.createRef(); + renderList(ds, ref); + await waitFor(() => expect(handedRows()).toHaveLength(WINDOW)); + // Scroll to the end twice: the grid asks the list for its next window. + await act(async () => { lastGridProps.onLoadMore(); }); + await waitFor(() => expect(handedRows()).toHaveLength(100)); + await act(async () => { lastGridProps.onLoadMore(); }); + await waitFor(() => expect(handedRows()).toHaveLength(120)); + + ds.calls.length = 0; + await act(async () => { ref.current!.refresh(); }); + await waitFor(() => expect(ds.calls.length).toBeGreaterThanOrEqual(3)); + await waitFor(() => expect(handedRows()).toHaveLength(120)); + expect(Math.max(...ds.calls.map((c: any) => c.$top))).toBe(WINDOW); + expect(ds.calls.map((c: any) => c.$skip ?? 0).sort((a: number, b: number) => a - b)).toEqual([0, 50, 100]); + }); +});