diff --git a/.changeset/35554-list-no-actions-column.md b/.changeset/35554-list-no-actions-column.md new file mode 100644 index 00000000000..0ab2d98cb20 --- /dev/null +++ b/.changeset/35554-list-no-actions-column.md @@ -0,0 +1,17 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/plugin-list': patch +'@object-ui/components': patch +'@object-ui/i18n': patch +--- + +feat(list): the object list page has no Actions column; a selection swaps the page bar, and a list with no declared pagination loads as it scrolls + +Clause-②: no +Metadata-protocol: none + +- **No Actions column on the list page.** The list's rows carry no control: no Actions column and no "⋮" at the row end, on hover or at rest. A row's actions are reached by selecting it or by right-clicking it. Grids outside a list page (related lists, page blocks, the record drawer) keep their Actions column and their bottom bulk bar. +- **Selection in the page bar.** Ticking rows swaps the page bar to 「对象名 / 已选 N 条」, Cancel, and the actions for what is selected: one record shows its own row actions, two or more show the bulk actions. The first two are buttons (in the order the actions are declared, by their `order`), the rest are behind "⋮", and Delete is never a button. Cancel, or clearing the selection, brings the page bar back. The bottom bulk bar no longer floats over the list on the list page. +- **Context menu.** In a row's menu (its context menu, and the "⋮" where one is still drawn) Delete is the last item, after a separator, in the danger colour; a selection's menu closes with its destructive actions the same way. +- **Checkboxes.** The whole leading cell toggles a row, and Shift extends the selection over the rows between the last toggled row and this one. +- **Scroll loading.** A grid list view that declares no `pagination` draws no pager: it loads 50 rows and the next 50 as the list nears its end, and shows the match total beside the view name. With every loaded row ticked, the page bar offers 「选择全部 M 条」 (capped at 5000 as before). Opening a record on its own page and coming back returns to the same place in the list. A view that declares `pagination` keeps its pager. Footer totals are still computed by the server over every matching record. diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 35f912d8dd5..70c3b74aee3 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -615,7 +615,7 @@ "title": "List-view capability matrix: filter, search, sort, pagination, saved views, inline edit, export, visualization switcher, bulk/row actions, conditional formatting", "since": "v15", "status": "active", - "revision": 10, + "revision": 11, "priority": "P1", "surface": "browser", "personas": [ @@ -649,11 +649,11 @@ "switch to the in_progress saved view; capture the data request — expect `filter` carrying the stored rule as an ObjectQL AST ([[\"status\",\"equals\",\"in_progress\"]]) and a 200; the count bar must read 2. The console spells its list params WITHOUT a `$` — filter, top, skip, search, sort — the same AST under the bare name, so a literal grep for $filter finds nothing", "quick-search 'huaning' on Accounts (or '张' on Contacts); capture the `search` request and the hits (pinyin + CJK recall, ADR-0061)", "open the tabular saved view (sort [{field: 'estimate_hours', order: 'desc'}] — the array form: #17053 retired the bare string clause 'estimate_hours desc' platform-wide, so the objectui#2601 string-crash fixture no longer exists on stock); confirm it renders and the request carries the sort as sort=-estimate_hours", - "page a list past page 1. No stock list holds more rows than the 50-row page (the largest seeded task and contact lists are under it), so stage one first: POST /api/v1/data/showcase_inquiry/createMany with a bare JSON array of 55 rows (name + email + message each — showcase_inquiry requires `message` too, and a name + email body answers 400 \"Message is required\", QA run #24616), then page the Inquiries list; capture `top`/`skip` on every data request; confirm no unpaged full fetch", + "load a list past its first window. No stock list holds more rows than the 50-row window (the largest seeded task and contact lists are under it), so stage one first: POST /api/v1/data/showcase_inquiry/createMany with a bare JSON array of 55 rows (name + email + message each — showcase_inquiry requires `message` too, and a name + email body answers 400 \"Message is required\", QA run #24616). A list view that declares no `pagination` (the stock Inquiries list) draws NO pager since #35554: it loads as it scrolls, so scroll the Inquiries list to its end and capture `top`/`skip` on every data request (top=50, then top=50&skip=50); the count beside the view name reads the server total. Then page a view that DECLARES `pagination` (stage one: PUT a view with pagination: {pageSize: 50} on showcase_inquiry) past page 1 and capture the same; confirm no unpaged full fetch on either", "in the grid saved view (inlineEdit: true), edit one cell in place; save; capture the PATCH; re-read the row via API", "on in_progress, with the export grant from fixtures.requires[3] bound, open the view bar's Options (选项) popover — the Display popover, a text trigger since objectstack#35548 — Export sits in its footer ('Export as CSV / XLSX / JSON'), not as a separate toolbar button — and export each declared format (csv, xlsx, json); capture the requests and files. Without the grant the Export entries are absent and the route answers 403 EXPORT_NOT_PERMITTED — the opt-in working as designed, not a fail of the export variant", "open the visualization switcher on All Tasks; enumerate the offered types; switch through each", - "on bulk_actions, select rows that are NOT done and run showcase_mark_done (per-record) — its visible gate, has(record.done) && record.done != true, judges each selected row, so a done row in the selection drops Mark Done from the bulk bar, or, over a mixed selection, the confirm reports the done rows not eligible and skipped (QA run #27438); either way the dispatch count stops matching the selection — and showcase_recalc_selection (aggregate — ONE dispatch: an api-type action, which the console sends through the action door, POST /api/v1/actions/showcase_task/showcase_recalc_selection with body {params:{_selectedIds:[…]}}; the server forwards those params flat to the action's own target /api/v1/apps/showcase/recalc in-process, buildApiActionRequest in packages/runtime/src/action-execution.ts, so the browser's network log shows the door request and no /recalc request); on legacy_row_actions confirm both named row actions resolve to live menu entries", + "on bulk_actions, select rows that are NOT done and run showcase_mark_done (per-record) — its visible gate, has(record.done) && record.done != true, judges each selected row, so a done row in the selection drops Mark Done from the selection actions the page bar shows (since #35554 the list page has no bottom bulk bar), or, over a mixed selection, the confirm reports the done rows not eligible and skipped (QA run #27438); either way the dispatch count stops matching the selection — and showcase_recalc_selection (aggregate — ONE dispatch: an api-type action, which the console sends through the action door, POST /api/v1/actions/showcase_task/showcase_recalc_selection with body {params:{_selectedIds:[…]}}; the server forwards those params flat to the action's own target /api/v1/apps/showcase/recalc in-process, buildApiActionRequest in packages/runtime/src/action-execution.ts, so the browser's network log shows the door request and no /recalc request); on legacy_row_actions confirm both named row actions resolve to live menu entries", "on Field Zoo, confirm the conditionalFormatting row highlight applies to Specimen — Full (f_lookup set) and not Specimen — Minimal", "at 1280×800 on a zh-CN session, read the list frame on All Tasks, then on its kanban view: a 44px page bar with the object's icon and name on the left and ⋮ (description, import, favorite) and 「+ 新建」 on the right; a 40px view bar with ONE switcher trigger reading type icon → view name → record count → caret on the left and 「筛选」「排序」「选项」 plus the search icon on the right; no condition row height while no condition is set; on the grid a 32px header and 33px rows at 13px; and, on a view whose columns declare a `summary`, each total under its own column with 「计数 N」 leftmost and no doubled colon. The kanban view draws the same two bars (objectstack#35548; the count beside the view name returns, after objectstack#34603 removed it)" ], @@ -677,9 +677,9 @@ "evidence": "request trace + response JSON" }, { - "clause": "paging issues `top`/`skip` requests; the full set is never fetched; a walked page sequence visits every row exactly once (deterministic paging)", + "clause": "loading past the first window issues `top`/`skip` requests and the full set is never fetched: a list with no declared `pagination` appends the next window as it scrolls (no pager), a view declaring `pagination` pages; either walk visits every row exactly once (deterministic paging)", "oracle": "network", - "verify": "page 1 = top=N; page 2 = top=N&skip=N; union of pages has no duplicate and no missing id", + "verify": "window 1 = top=N; window 2 = top=N&skip=N (the scroll-loaded list and the declared pager alike); union of windows has no duplicate and no missing id", "evidence": "the request URLs + the id-union check" }, { @@ -806,6 +806,12 @@ "date": "2026-11-19", "change": "list-frame variant, steps[10] and its acceptance clause added, and steps[6] re-pointed: the list page's frame was redrawn (objectstack#35548, epic #35547). The toolbar's icon-only Display trigger is now the view bar's 「选项」 (Options) text trigger beside 「筛选」 and 「排序」, the view switcher carries the type icon and record count (the count objectstack#34603 had taken away), and the column totals moved into the grid's own last row. No earlier clause changed", "ref": "#35548" + }, + { + "revision": 11, + "date": "2026-11-19", + "change": "steps[4] and acceptance[3] (clause and verify) follow #35554: a list view that declares no `pagination` has no pager and loads its next window as it scrolls (top=50, then top=50&skip=50), and only a view that declares `pagination` pages; the paging variant now walks both. steps[8] names where the bulk actions are offered now — the page bar, while rows are selected — instead of the retired bottom bulk bar. Read at base e01b8bed (after #35548)", + "ref": "#35554" } ] }, @@ -3747,7 +3753,7 @@ "title": "Select-all-matching covers every matching id across pages (server total, not the rendered page); clear resets both selection sources", "since": "v16", "status": "active", - "revision": 9, + "revision": 10, "priority": "P2", "surface": "browser", "personas": [ @@ -3765,9 +3771,9 @@ ] }, "steps": [ - "open the showcase_task 'Bulk Actions' view (…/showcase_task/view/bulk_actions) with the scratch tasks in place and quick-search their shared prefix so the match set exceeds one page (e.g. 'QA bulk' → 55 rows); screenshot; note page shows N rows, count bar shows server total M (M > N)", - "select the whole visible page; the cross-page banner appears offering 'Select all M matching'", - "click select-all-matching; the banner reads 'All M matching records are selected'", + "open the showcase_task 'Bulk Actions' view (…/showcase_task/view/bulk_actions) with the scratch tasks in place and quick-search their shared prefix so the match set exceeds one page (e.g. 'QA bulk' → 55 rows); screenshot; note the list shows its first N loaded rows and the count beside the view name shows the server total M (M > N); the view declares no `pagination`, so it loads as it scrolls (#35554) — leave it at its first window", + "tick the header checkbox (every loaded row); the page bar swaps to 「已选 N 条」 and offers 「已选当前加载的 N 条。」 with 「选择全部 M 条」 (en 'All N loaded records are selected.' / 'Select all M')", + "click 「选择全部 M 条」; the page bar's count reads the whole match set ('M selected (all matches)')", "dispatch a bulk action; capture the requests — resolveBulkRows fans out a paged find (dropping $top/$skip, paging 500) collecting every matching id ACROSS pages", "cross-check the collected id count against a direct API count for the same search: GET /api/v1/data/showcase_task?$search=…&$top=0 (or the response total)", "confirm the AGGREGATE action (showcase_recalc_selection) carries every matching id in `_selectedIds` — it is an api-type action, so the ONE request is the action door, POST /api/v1/actions/showcase_task/showcase_recalc_selection with body {params:{_selectedIds:[…]}} (the grid hands them to the action runner as params._selectedIds, ui/packages/plugin-grid/src/ObjectGrid.tsx; since #27611 the console sends a declared same-origin api action through the door, and the server forwards the params flat to /api/v1/apps/showcase/recalc in-process, buildApiActionRequest in packages/runtime/src/action-execution.ts); the run dialog then reads 'N / 55 processed' for ~15 s (QA run #24616); a per-record action (showcase_mark_done) fans out one dispatch per matching id", @@ -3776,9 +3782,9 @@ ], "acceptance": [ { - "clause": "the cross-page banner reports the SERVER total (totalMatching from the find result.total), not the rendered page count — and only appears when the whole page is selected and more matching rows exist off-screen", + "clause": "the select-all offer in the page bar reports the SERVER total (totalMatching from the find result.total), not the loaded row count — and only appears when every loaded row is selected and more matching rows exist past them", "oracle": "network", - "verify": "the banner's count equals the data request's response total (BulkActionBar totalMatching; ObjectGrid captures result.total into totalMatching)", + "verify": "the offer's count equals the data request's response total (SelectionPageBar totalMatching; ListView hands result.total down as rowCount, read by ObjectGrid as resolvedTotalMatching)", "evidence": "banner screenshot + the find response total" }, { @@ -3884,6 +3890,12 @@ "date": "2026-11-15", "change": "knownGaps[1] retired its 'acceptance[5] expected FAIL until #28552' wording: #28552 is fixed (d5da45b27, #28606), the bar names the 5000 cap through the three *Capped strings, and QA run #33861 read acceptance[5] passing (ledger row 128). acceptance[5] itself never said FAIL and is unchanged. Ledger 6896511848 of the v18.5.0 sweep anchor #33761, carried by batch-A card #33963; read at base 895783a1.", "ref": "#33990" + }, + { + "revision": 10, + "date": "2026-11-19", + "change": "steps[0]–[2] and acceptance[0] follow #35554: the bottom bulk bar is retired on the list page and the selection is shown in the page bar (「已选 N 条」, the cross-window offer 「已选当前加载的 N 条。」 + 「选择全部 M 条」); a list with no declared `pagination` loads as it scrolls, so 'the whole page' is now 'every loaded row'. The cap strings of acceptance[5] are unchanged and the page bar names the cap with the same keys. Read at base 93fa4f97", + "ref": "#35554" } ] }, @@ -6404,7 +6416,7 @@ "title": "Defaults that changed meaning on v18 (ADR-0087 D3 18.* entries): an omitted list-view page size is 50 (was 25), an omitted editInline means editable in place, an autonumber with no `unique` is unique per organization, and a field-heavy form opens as a bounded modal on desktop", "since": "v18", "status": "active", - "revision": 7, + "revision": 8, "priority": "P2", "surface": "mixed", "personas": [ @@ -6437,7 +6449,7 @@ "evidence": "the vitest summary line per pin file, with the package name and the subject sha" }, { - "clause": "the first page of a list view with no pageSize shows 50 rows", + "clause": "the first window of a list view with no pageSize shows 50 rows (no pager since #35554: the next 50 load as the list scrolls)", "oracle": "dom", "verify": "count rendered rows after a screenshot confirms the list painted", "evidence": "row count + one-line screenshot description" @@ -6511,6 +6523,12 @@ "date": "2026-11-15", "change": "acceptance[0].verify names `--reporter=tree`, the reporter that prints the one line per pin file this is scored on: in a runner's non-TTY shell vitest's default reporter prints the run's totals only (RUNNER.md's environment facts; QA run #33784's note 10, comment 6893243542). No clause or threshold changed. Card #33969", "ref": "#34068" + }, + { + "revision": 8, + "date": "2026-11-19", + "change": "acceptance[1] reads 'first window' for 'first page': since #35554 a list view with no declared `pagination` draws no pager and loads its next 50 as it scrolls; the 50-row default it pins is unchanged. Read at base 93fa4f97", + "ref": "#35554" } ] }, diff --git a/ui/e2e/list-no-actions-column-35554.spec.ts b/ui/e2e/list-no-actions-column-35554.spec.ts new file mode 100644 index 00000000000..bcc146a85de --- /dev/null +++ b/ui/e2e/list-no-actions-column-35554.spec.ts @@ -0,0 +1,521 @@ +import { test, expect, type Page, type TestInfo } 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'; + +/** + * Acceptance pin for objectstack#35554: the object list page has no Actions + * column, a selection swaps the page bar, the row's context menu ends with a + * separated Delete, and a list with no declared `pagination` loads as it + * scrolls and comes back to the row it was left at. + * + * ## Why a Playwright spec and not a vitest test + * + * The page bar and the list are siblings, the selection is drawn into the bar + * through a portal, and "the last row is fully visible", "scroll to the end + * loads more" and "back lands near row 60" are questions about layout and + * scrolling, which jsdom does not have. The bundling follows + * `e2e/list-narrow-pinned-columns-35446.spec.ts`. + * + * ## What is real here and what is a fixture + * + * REAL: the Console list page header (`ObjectViewPageHeader` with its chrome + * 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 + * Tailwind compiled for the classes the page carries. + * + * FIXTURES, declared so nobody reads more into a green run than it says: + * + * - The page column is a flex column holding the header and the list, the + * shape `ObjectView` draws; the shell (top bar, sidebar) is out of scope + * and absent, so the column is the viewport. + * - The rows (120 opportunities), the fields and the actions are literals + * shaped like HotCRM's opportunity list; the data source pages them by + * `$skip` / `$top` and answers `total`. Dispatched actions are recorded + * on the page, not run. + * - "Open record 60, come back" is a remount of the page column at the same + * address: what the list keeps across it is session storage, which a + * record page round trip keeps too. + */ + +const REPO_ROOT = uiRoot(); +const source = (rel: string) => path.join(REPO_ROOT, rel); + +const THEME_CSS = source('packages/components/src/index.css'); +// The entry names workspace sources by path, never by package name: the e2e +// type-check program must import no workspace package (it builds nothing first). +const COMPONENTS = source('packages/components/src/index.ts'); +const PLUGIN_GRID = source('packages/plugin-grid/src/index.tsx'); +const PLUGIN_LIST = source('packages/plugin-list/src/index.tsx'); +const FIELDS = source('packages/fields/src/index.tsx'); +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 = [ + { width: 1280, height: 800 }, + { width: 1167, height: 762 }, +] as const; + +const ROW_COUNT = 120; + +interface Case { + /** Declare `pagination` on the view (the list keeps its pager). */ + paged?: boolean; + theme?: 'light' | 'dark'; +} + +const ENTRY = '\0list-no-actions-column:entry'; + +/** `@object-ui/` to `packages//src`, and a subpath into that `src/`. */ +function workspaceSources(): Plugin { + return { + name: 'list-no-actions-column-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; + }, + }; +} + +function entry(): Plugin { + const code = ` +import * as React from 'react'; +import { createRoot } from 'react-dom/client'; +import { MemoryRouter } from 'react-router-dom'; +import ${JSON.stringify(COMPONENTS)}; +import ${JSON.stringify(PLUGIN_GRID)}; +import { ListView } from ${JSON.stringify(PLUGIN_LIST)}; +import { registerAllFields } from ${JSON.stringify(FIELDS)}; +import { ActionProvider, SchemaRendererProvider } from ${JSON.stringify(REACT_BINDINGS)}; +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; +const c = window.__case; +window.__dispatched = []; +window.__finds = []; +if (c.theme === 'dark') document.documentElement.classList.add('dark'); + +const FIELDS = { + id: { name: 'id', type: 'text' }, + name: { name: 'name', label: '商机名称', type: 'text' }, + account: { name: 'account', label: '客户', type: 'text' }, + stage: { name: 'stage', label: '阶段', type: 'text' }, + amount: { name: 'amount', label: '金额', type: 'currency' }, + probability: { name: 'probability', label: '赢率', type: 'percent' }, + owner: { name: 'owner', label: '负责人', type: 'text' }, + close_date: { name: 'close_date', label: '预计成交日期', type: 'date' }, +}; +const STAGES = ['资格审查', '需求分析', '方案报价', '商务谈判']; +const ROWS = Array.from({ length: ${ROW_COUNT} }, (_, i) => ({ + id: 'o' + String(i + 1).padStart(3, '0'), + name: '商机 ' + (i + 1), + account: '客户 ' + ((i % 17) + 1), + stage: STAGES[i % STAGES.length], + amount: 10000 + i * 1000, + probability: (20 + (i % 4) * 20) / 100, + owner: '销售 ' + ((i % 5) + 1), + close_date: '2027-01-' + String((i % 28) + 1).padStart(2, '0'), +})); +const dataSource = { + find: async (_object, params = {}) => { + window.__finds.push({ skip: params.$skip ?? 0, top: params.$top }); + const skip = params.$skip ?? 0; + const top = params.$top ?? ROWS.length; + return { data: ROWS.slice(skip, skip + top), total: ROWS.length }; + }, + getObjectSchema: async (name) => ({ name, label: '商机', fields: FIELDS }), +}; +const record = (name) => async () => { window.__dispatched.push(name); return { success: true }; }; +const rowActionDefs = [ + { name: 'submit_approval', label: '提交审批', locations: ['list_item'] }, + { name: 'make_quote', label: '生成报价单', locations: ['list_item'] }, + { name: 'clone_opportunity', label: '复制', locations: ['list_item'] }, +]; +const bulkActionDefs = [ + { name: 'mass_update', label: '批量更新' }, + { name: 'mass_assign', label: '批量分配' }, + { name: 'mass_tag', label: '批量打标签' }, +]; +const handlers = Object.fromEntries([...rowActionDefs, ...bulkActionDefs].map((d) => [d.name, record(d.name)])); + +const schema = { + type: 'list-view', + objectName: 'opportunity', + viewType: 'grid', + columns: ['name', 'account', 'stage', 'amount', 'probability', 'owner', 'close_date'], + selection: { type: 'multiple' }, + rowActionDefs, + bulkActionDefs, + ...(c.paged ? { pagination: { pageSize: 50 } } : {}), +}; + +function Header() { + const { t } = useObjectTranslation(); + const chrome = useObjectViewHeaderChrome({ + objectCanCreate: true, createVisible: true, createDisabled: false, + actions: { create: () => {} }, t, listActions: [], toolbarActionsWithDeepLink: [], + identityImportEnabled: false, objectCanImport: false, importVisible: false, importDisabled: false, + setShowImport: () => {}, listFavorite: null, isEnvironmentList: false, + toolbarBar: { type: 'action:bar', location: 'list_toolbar', actions: [], maxVisible: 3, mobileMaxVisible: 0 }, + viewAccess: { refusal: null }, + }); + return h(ObjectViewPageHeader, { + objectDef: { name: 'opportunity', label: '商机', pluralLabel: '商机', icon: 'briefcase' }, + objectPluralLabel: () => '商机', + objectDesc: () => undefined, + createButton: chrome.createButton, + importShown: false, + setShowImport: () => {}, + importDisabled: false, + t, + listActions: [], + isEnvironmentList: false, + headerToolbarActions: [], + environmentEntitlements: undefined, + toolbarBar: { type: 'action:bar', location: 'list_toolbar', actions: [], maxVisible: 3, mobileMaxVisible: 0 }, + listFavorite: 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( + h(I18nProvider, { key: ++mounts, config: { defaultLanguage: 'zh-CN', fallbackLanguage: 'en', detectBrowserLanguage: false } }, + h(MemoryRouter, { initialEntries: ['/apps/sales/opportunity/view/open'] }, + h(ActionProvider, { handlers }, + h(SchemaRendererProvider, { dataSource }, + 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, toolbarLeading: (state) => h(ViewBarLead, state), onEdit: () => window.__dispatched.push('edit'), onDelete: () => window.__dispatched.push('delete') }))))))), +); +window.__unmount = () => root.render(null); +window.__remount(); +`; + return { + name: 'list-no-actions-column-entry', + resolveId: (id) => (id === 'list-no-actions-column:entry' ? ENTRY : null), + load: (id) => (id === ENTRY ? code : null), + }; +} + +async function bundlePage(): Promise { + const result = await build({ + configFile: false, + root: REPO_ROOT, + cacheDir: path.join(os.tmpdir(), 'objectui-list-no-actions-column'), + 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-no-actions-column: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; +} + +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 = ''; +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 { + 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 === 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) { + sheet = document.createElement('style'); + sheet.id = 'tailwind'; + document.head.appendChild(sheet); + } + sheet.textContent = text; + }, css); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + } +} + +/** + * 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); + // 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; + 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); +} + +/** A screenshot kept in the test's output folder and attached to its report. */ +async function shoot(page: Page, testInfo: TestInfo, name: string): Promise { + const file = testInfo.outputPath(name); + await page.screenshot({ path: file }); + await testInfo.attach(name, { path: file, contentType: 'image/png' }); +} + +const rowCheckbox = (page: Page, name: string) => + page.locator('tr', { has: page.getByText(name, { exact: true }) }).getByRole('checkbox'); + +const loadedRows = (page: Page) => page.locator('tbody tr:has([data-slot="row-leading-cell"])').count(); + +for (const viewport of VIEWPORTS) { + test.describe(`list page without an Actions column at ${viewport.width}×${viewport.height} (objectstack#35554)`, () => { + test.beforeAll(async () => { + test.setTimeout(240_000); + if (!bundle) bundle = await bundlePage(); + }); + + test('no Actions column, no row-end control on hover; the last column reads in full', async ({ page }) => { + await mount(page, viewport); + await expect(page.locator('th[data-column-key="_actions"]')).toHaveCount(0); + await page.getByText('商机 3', { exact: true }).hover(); + await expect(page.getByTestId('row-action-trigger')).toHaveCount(0); + const fits = await page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]')!; + const last = [...document.querySelectorAll('thead th')].pop()!; + const boxRect = box.getBoundingClientRect(); + const rect = last.getBoundingClientRect(); + return { lastRight: rect.right, boxRight: boxRect.left + box.clientWidth, key: last.getAttribute('data-column-key') }; + }); + expect(fits.key).toBe('close_date'); + expect(fits.lastRight).toBeLessThanOrEqual(fits.boxRight + 0.5); + }); + + test('two rows selected: the page bar reads 「已选 2 条」 with the bulk actions, nothing floats over the rows; Cancel restores it', async ({ page }, testInfo) => { + await mount(page, viewport); + await rowCheckbox(page, '商机 1').click(); + await rowCheckbox(page, '商机 2').click(); + const bar = page.getByTestId('list-selection-page-bar'); + await expect(bar).toBeVisible(); + await expect(bar.getByTestId('list-selection-count')).toHaveText('已选 2 条'); + await expect(bar.getByTestId('bulk-action-mass_update')).toBeVisible(); + await expect(bar.getByTestId('bulk-action-mass_assign')).toBeVisible(); + await expect(bar.getByTestId('bulk-action-mass_tag')).toHaveCount(0); + await expect(page.getByTestId('bulk-actions-bar')).toHaveCount(0); + await expect(page.getByTestId('page-header')).toBeHidden(); + // Nothing is drawn over the bottom of the list: the point just inside + // the scroll box's bottom edge answers the table. + const bottomHit = await page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]')!; + const r = box.getBoundingClientRect(); + const hit = document.elementFromPoint(r.left + 40, Math.min(r.bottom, window.innerHeight) - 4); + return !!hit && box.contains(hit); + }); + expect(bottomHit).toBe(true); + await shoot(page, testInfo, `selected-2-${viewport.width}.png`); + await bar.getByTestId('list-selection-cancel').click(); + await expect(bar).toBeHidden(); + await expect(page.getByTestId('page-header')).toBeVisible(); + }); + + test('one row and two rows expose different actions', async ({ page }) => { + await mount(page, viewport); + await rowCheckbox(page, '商机 1').click(); + const bar = page.getByTestId('list-selection-page-bar'); + await expect(bar.getByTestId('list-selection-count')).toHaveText('已选 1 条'); + await expect(bar.getByTestId('row-action-inline-submit_approval')).toBeVisible(); + await expect(bar.getByTestId('row-action-inline-make_quote')).toBeVisible(); + await expect(bar.getByTestId('bulk-action-mass_update')).toHaveCount(0); + await bar.getByTestId('row-action-inline-make_quote').click(); + await expect.poll(() => page.evaluate(() => (window as any).__dispatched)).toContain('make_quote'); + await rowCheckbox(page, '商机 2').click(); + await expect(bar.getByTestId('row-action-inline-submit_approval')).toHaveCount(0); + await expect(bar.getByTestId('bulk-action-mass_update')).toBeVisible(); + }); + + test('right-click on a row: its actions, 「删除」 last after a separator', async ({ page }) => { + await mount(page, viewport); + await page.getByText('商机 4', { exact: true }).click({ button: 'right' }); + const menu = page.getByRole('menu'); + await expect(menu).toBeVisible(); + const items = menu.getByRole('menuitem'); + await expect(items.last()).toHaveAttribute('data-testid', 'row-action-builtin-delete'); + await expect(items.last()).toHaveText(/删除/); + await expect(menu.getByTestId('row-action-delete-separator')).toHaveCount(1); + const order = await menu.evaluate((el) => + [...el.querySelectorAll('[role="menuitem"], [role="separator"]')].map((n) => n.getAttribute('data-testid') ?? n.getAttribute('role')), + ); + expect(order.slice(-2)).toEqual(['row-action-delete-separator', 'row-action-builtin-delete']); + }); + + 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-view-switcher-count')).toHaveText('120'); + expect(await loadedRows(page)).toBe(50); + await page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]')!; + box.scrollTop = box.scrollHeight; + }); + 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 条'); + await bar.getByTestId('list-selection-select-all').click(); + await expect(bar.getByTestId('list-selection-count')).toContainText('120'); + }); + + test('opening row 60 and coming back lands near row 60', async ({ page }) => { + await mount(page, viewport); + await page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]')!; + box.scrollTop = box.scrollHeight; + }); + await expect.poll(() => loadedRows(page)).toBe(100); + await page.getByText('商机 60', { exact: true }).scrollIntoViewIfNeeded(); + // Let the kept position settle (it is written on the next frame). + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + await page.evaluate(() => (window as any).__unmount()); + await page.evaluate(() => (window as any).__remount()); + await page.getByText('商机 1', { exact: true }).waitFor(); + await expect(page.getByText('商机 60', { exact: true })).toBeInViewport(); + }); + + test('a view that declares `pagination` still pages', async ({ page }) => { + await mount(page, viewport, { paged: true }); + await expect(page.getByRole('button', { name: /下一页|Next page/ })).toBeVisible(); + expect(await loadedRows(page)).toBe(50); + await page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]')!; + box.scrollTop = box.scrollHeight; + }); + await page.waitForTimeout(500); + expect(await loadedRows(page)).toBe(50); + }); + }); +} + +test.describe('visual acceptance at 1280×800, zh-CN (objectstack#35554)', () => { + test.use({ deviceScaleFactor: 2 }); + test.beforeAll(async () => { + test.setTimeout(240_000); + if (!bundle) bundle = await bundlePage(); + }); + for (const theme of ['light', 'dark'] as const) { + test(`${theme}: at rest, one selected, two selected`, async ({ page }, testInfo) => { + await mount(page, VIEWPORTS[0], { theme }); + await shoot(page, testInfo, `rest-${theme}.png`); + await rowCheckbox(page, '商机 1').click(); + await styleUntilStable(page); + await shoot(page, testInfo, `selected-1-${theme}.png`); + await rowCheckbox(page, '商机 2').click(); + await styleUntilStable(page); + await shoot(page, testInfo, `selected-2-${theme}.png`); + await page.getByText('商机 5', { exact: true }).click({ button: 'right' }); + await styleUntilStable(page); + await shoot(page, testInfo, `context-menu-${theme}.png`); + }); + } +}); 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. 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 26869929336..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 @@ -20,7 +20,8 @@ * `?runAction=` deep-link arming, which arms only what the header draws. * * The real chain throughout: the real `ObjectView`, the real `ObjectGrid` and - * its `BulkActionBar` (fed by `resolveBulkActions` from the view's own keys), + * its selection actions (fed by `resolveBulkActions` from the view's own keys; + * on the list page they are drawn into the page bar, objectstack#35554), * the real `action:bar`. Every case is a differential on the view's wiring or * the action's placement, with the same object and the same rows. */ @@ -28,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'; @@ -191,6 +195,24 @@ async function rowBoxes(): Promise { }, { timeout: 5000 }); } +/** + * objectstack#35554 — the selection's actions on the list page: the page bar's + * selection face, its exposed buttons and the ones behind its "⋮". Returns the + * bar and the action names it carries. + */ +async function selectionBar(): Promise<{ bar: HTMLElement; names: string[] }> { + const bar = await screen.findByTestId('list-selection-bar', undefined, { timeout: 5000 }); + const names = within(bar).queryAllByTestId(/^bulk-action-/).map((el) => el.getAttribute('data-testid')!.slice('bulk-action-'.length)); + const more = within(bar).queryByTestId('selection-actions-more'); + if (more) { + await act(async () => { fireEvent.pointerDown(more, { button: 0, ctrlKey: false, pointerType: 'mouse' }); }); + const menu = await screen.findByRole('menu'); + names.push(...within(menu).queryAllByTestId(/^row-context-bulk-/).map((el) => el.getAttribute('data-testid')!.slice('row-context-bulk-'.length))); + await act(async () => { fireEvent.keyDown(menu, { key: 'Escape' }); }); + } + return { bar, names }; +} + async function tickRows(n: number): Promise { const boxes = await rowBoxes(); for (const box of boxes.slice(0, n)) { @@ -208,18 +230,18 @@ describe('objectui#12462 — a bulk-wired, record-scoped list_toolbar action lea // Zero rows: the header has the plain action and not the duplicate; no bar. expect(addToCampaignIn(header)).toBeNull(); - expect(screen.queryByTestId('bulk-actions-bar')).toBeNull(); + expect(screen.queryByTestId('list-selection-bar')).toBeNull(); - // Two rows: the bar floats carrying the action; the header still lacks it. + // Two rows: the selection carries the action; the header still lacks it. await tickRows(2); - const bar = await screen.findByTestId('bulk-actions-bar', undefined, { timeout: 5000 }); - expect(within(bar).getByTestId('bulk-action-create_campaign')).toHaveTextContent('Add to Campaign'); + const { bar, names } = await selectionBar(); + expect(names).toContain('create_campaign'); expect(addToCampaignIn(header)).toBeNull(); expect(within(header).getByRole('button', { name: /Refresh Scores/ })).toBeInTheDocument(); - // Clearing the selection hides the bar. - await act(async () => { fireEvent.click(within(bar).getByRole('button', { name: /Clear/ })); }); - await waitFor(() => expect(screen.queryByTestId('bulk-actions-bar')).toBeNull(), { timeout: 5000 }); + // Cancelling the selection brings the page bar back. + await act(async () => { fireEvent.click(within(bar).getByTestId('list-selection-cancel')); }); + await waitFor(() => expect(screen.queryByTestId('list-selection-bar')).toBeNull(), { timeout: 5000 }); }); it('the view wires it in a `bulkActionDefs` entry: the header lacks it, the bar carries it', async () => { @@ -228,8 +250,7 @@ describe('objectui#12462 — a bulk-wired, record-scoped list_toolbar action lea expect(addToCampaignIn(header)).toBeNull(); await tickRows(2); - const bar = await screen.findByTestId('bulk-actions-bar', undefined, { timeout: 5000 }); - expect(within(bar).getByTestId('bulk-action-create_campaign')).toBeInTheDocument(); + expect((await selectionBar()).names).toContain('create_campaign'); }); it('CONTROL — a view that does not wire it keeps the header button, and its bar does not carry it', async () => { @@ -238,8 +259,7 @@ describe('objectui#12462 — a bulk-wired, record-scoped list_toolbar action lea expect(addToCampaignIn(header)).not.toBeNull(); await tickRows(2); - const bar = await screen.findByTestId('bulk-actions-bar', undefined, { timeout: 5000 }); - expect(within(bar).queryByTestId('bulk-action-create_campaign')).toBeNull(); + expect((await selectionBar()).names).not.toContain('create_campaign'); expect(addToCampaignIn(header)).not.toBeNull(); }); @@ -250,8 +270,7 @@ describe('objectui#12462 — a bulk-wired, record-scoped list_toolbar action lea expect(addToCampaignIn(header)).not.toBeNull(); await tickRows(2); - const bar = await screen.findByTestId('bulk-actions-bar', undefined, { timeout: 5000 }); - expect(within(bar).getByTestId('bulk-action-refresh_scores')).toBeInTheDocument(); + expect((await selectionBar()).names).toContain('refresh_scores'); expect(within(header).getByRole('button', { name: /Refresh Scores/ })).toBeInTheDocument(); }); }); 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 beed3373206..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'; @@ -297,13 +300,11 @@ async function inviteAda(): Promise { async function openRowMenu(email: string): Promise { const cell = await screen.findByText(email, undefined, { timeout: 5000 }); const row = cell.closest('tr')!; - const trigger = await waitFor(() => { - const t = within(row).getAllByRole('button').find((b) => b.getAttribute('aria-haspopup') === 'menu'); - expect(t).toBeDefined(); - return t!; - }, { timeout: 5000 }); - fireEvent.pointerDown(trigger, { button: 0, pointerType: 'mouse' }); - const items = await screen.findAllByRole('menuitem', undefined, { timeout: 5000 }); + // objectstack#35554 — the list page draws no "⋮" on the row: its menu is + // the row's context menu (right-click), the same items. + fireEvent.contextMenu(row.querySelector('td:last-child') ?? row, { button: 2, clientX: 40, clientY: 60 }); + const menu = await screen.findByTestId('row-context-menu', undefined, { timeout: 5000 }); + const items = await within(menu).findAllByRole('menuitem', undefined, { timeout: 5000 }); return items.map((item) => (item.textContent ?? '').trim()); } diff --git a/ui/packages/app-shell/src/views/ObjectView.listOnlyRecordPage-33219.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listOnlyRecordPage-33219.test.tsx index 0d96cf3e8b0..475755fb5d4 100644 --- a/ui/packages/app-shell/src/views/ObjectView.listOnlyRecordPage-33219.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.listOnlyRecordPage-33219.test.tsx @@ -222,13 +222,11 @@ const search = () => screen.getByTestId('location-search').textContent; /** Open the row menu of the row showing `text`; answers the menu's item labels. */ async function rowMenuItems(text: string): Promise { const row = screen.getByText(text).closest('tr')!; - const trigger = await waitFor(() => { - const t = within(row).getAllByRole('button').find((b) => b.getAttribute('aria-haspopup') === 'menu'); - expect(t).toBeDefined(); - return t!; - }, { timeout: 5000 }); - fireEvent.pointerDown(trigger, { button: 0, pointerType: 'mouse' }); - const items = await screen.findAllByRole('menuitem', undefined, { timeout: 5000 }); + // objectstack#35554 — the list page draws no "⋮" on the row: its menu is + // the row's context menu (right-click), the same items. + fireEvent.contextMenu(row.querySelector('td:last-child') ?? row, { button: 2, clientX: 40, clientY: 60 }); + const menu = await screen.findByTestId('row-context-menu', undefined, { timeout: 5000 }); + const items = await within(menu).findAllByRole('menuitem', undefined, { timeout: 5000 }); return items.map((item) => (item.textContent ?? '').trim()); } diff --git a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx index 2b31b057c14..9ee4297712e 100644 --- a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx +++ b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx @@ -10,7 +10,7 @@ * value is passed in as a prop. */ -import { createElement } from 'react'; +import { createElement, useCallback, useState } from 'react'; import type { Dispatch, SetStateAction } from 'react'; import { Button, @@ -34,6 +34,7 @@ import type { useObjectViewToolbarAffordances } from './objectViewToolbarAfforda import type { useObjectViewHeaderToolbar } from './objectViewHeaderToolbar.js'; import type { useObjectViewHeaderChrome } from './objectViewHeaderChrome.js'; import type { ConsoleObjectViewProps } from './ObjectView.js'; +import { useListPageBarHost } from '@object-ui/plugin-grid'; /** * objectstack#35446 — the list header's width under which it takes @@ -80,13 +81,43 @@ export function ObjectViewPageHeader({ foldedHeaderActions: ReturnType['foldedHeaderActions']; }) { const pluralLabel = objectPluralLabel(objectDef); + // objectstack#35554 — the page bar's selection slot (`useListPageBarHost`, + // `@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. + 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 description = objectDef.description ? objectDesc(objectDef) : undefined; // The ⋮ menu: the description (no longer a resident subtitle), Import and // the favorites entry — the page's once-in-a-while acts. const moreShown = !!description || importShown || !!listFavorite; return ( -
+
+ {/* objectstack#35554 — the selection face: the object's name, then + what the list draws into the slot. Always mounted, so the slot + is there the moment a row is ticked; shown only while one is. */} +
+ {/* The list bar's measure (objectstack#35548): 44px, 13px type. */} +
+ + {pluralLabel} + + +
+
+
{ } }; - const handleSelectRow = (rowId: any, checked: boolean) => { + // objectstack#35554 — Shift extends a selection over a range: the row the + // last plain toggle landed on is the anchor, and a Shift toggle sets every + // row between it and the clicked one (inclusive) to the clicked row's new + // state. Rows are counted in the order this table draws them + // (`paginatedData`). The leading cell records the Shift key on the way in + // (`shiftSelectRef`), because the checkbox's own change event carries no + // modifier. + const selectionAnchorRef = React.useRef(null); + const shiftSelectRef = React.useRef(false); + const handleSelectRow = (rowId: any, checked: boolean, rowIndex?: number) => { + const extend = shiftSelectRef.current; + shiftSelectRef.current = false; // Single mode replaces the previous selection instead of accumulating — // the spec's 'single' must never hold two rows (#2941). const newSelected = new Set(selectionMode === 'single' ? [] : selectedRowIds); - if (checked) { + const anchor = selectionAnchorRef.current; + if ( + extend + && selectionMode === 'multiple' + && rowIndex !== undefined + && anchor !== null + && anchor !== rowIndex + && anchor < paginatedData.length + ) { + const from = Math.min(anchor, rowIndex); + const to = Math.max(anchor, rowIndex); + for (let i = from; i <= to; i += 1) { + const id = getRowId(paginatedData[i], (effectivePage - 1) * pageSize + i); + if (checked) newSelected.add(id); + else newSelected.delete(id); + } + } else if (checked) { newSelected.add(rowId); } else { newSelected.delete(rowId); } + if (rowIndex !== undefined) selectionAnchorRef.current = rowIndex; setSelectedRowIds(newSelected); // Call callback if provided @@ -3961,9 +3989,13 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // alone: on a tall row the box is a small target // and a near miss used to open the record. The // checkbox itself handles its own clicks. + onClickCapture={(e) => { shiftSelectRef.current = e.shiftKey; }} onClick={(e) => { if ((e.target as HTMLElement).closest('[role="checkbox"]')) return; - handleSelectRow(rowId, !isSelected); + // Shift+click on a cell would also extend the + // browser's text selection across the rows. + if (e.shiftKey) window.getSelection?.()?.removeAllRanges(); + handleSelectRow(rowId, !isSelected, rowIndex); }} className={cn(cellClassName, "w-10 relative cursor-pointer", showRowNumbers ? "px-0 text-center" : "px-3", frozenColumns > 0 && ["sticky left-0 z-10 bg-background", STICKY_ROW_TINT])} > @@ -4002,7 +4034,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { (objectui#11690). */} handleSelectRow(rowId, checked as boolean)} + onCheckedChange={(checked) => handleSelectRow(rowId, checked as boolean, rowIndex)} aria-label={t('table.selectRow')} /> diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 4de91f63ef4..bc1b2b4941c 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -566,6 +566,22 @@ const ar = { bulkAllMatchingSelectedCapped: "ستتم معالجة أول {{cap}} سجل فقط من السجلات المطابقة ({{total}}).", bulkSelectedAllMatchesCapped: "تم تحديد {{cap}} (إجمالي النتائج المطابقة: {{total}})", bulkActions: "إجراءات جماعية", + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: "تم تحديد {{count}}", + selectedCount_zero: "تم تحديد {{count}}", + selectedCount_one: "تم تحديد {{count}}", + selectedCount_two: "تم تحديد {{count}}", + selectedCount_few: "تم تحديد {{count}}", + selectedCount_many: "تم تحديد {{count}}", + selectedCount_other: "تم تحديد {{count}}", + selectedAllLoaded: "تم تحديد جميع العناصر ({{count}}) في هذه الصفحة.", + selectedAllLoaded_zero: "تم تحديد جميع العناصر ({{count}}) في هذه الصفحة.", + selectedAllLoaded_one: "تم تحديد جميع العناصر ({{count}}) في هذه الصفحة.", + selectedAllLoaded_two: "تم تحديد جميع العناصر ({{count}}) في هذه الصفحة.", + selectedAllLoaded_few: "تم تحديد جميع العناصر ({{count}}) في هذه الصفحة.", + selectedAllLoaded_many: "تم تحديد جميع العناصر ({{count}}) في هذه الصفحة.", + selectedAllLoaded_other: "تم تحديد جميع العناصر ({{count}}) في هذه الصفحة.", + selectAllTotal: "تحديد كل النتائج المطابقة ({{total}})", bulk: { confirmDefault: "سيُطبَّق هذا على {{count}} من السجلات.", confirmDefault_zero: "سيُطبَّق هذا على {{count}} من السجلات.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 141a304d6c1..126c3eb8f9d 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -528,6 +528,14 @@ const de = { bulkAllMatchingSelectedCapped: "Nur die ersten {{cap}} von {{total}} übereinstimmenden Datensätzen werden verarbeitet.", bulkSelectedAllMatchesCapped: "{{cap}} ausgewählt (von {{total}} Treffern)", bulkActions: "Massenaktionen", + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: "{{count}} ausgewählt", + selectedCount_one: "{{count}} ausgewählt", + selectedCount_other: "{{count}} ausgewählt", + selectedAllLoaded: "Alle {{count}} auf dieser Seite sind ausgewählt.", + selectedAllLoaded_one: "{{count}} Datensatz auf dieser Seite ist ausgewählt.", + selectedAllLoaded_other: "Alle {{count}} auf dieser Seite sind ausgewählt.", + selectAllTotal: "Alle {{total}} Treffer auswählen", bulk: { confirmDefault: "Dies wird auf {{count}} Datensätze angewendet.", confirmDefault_one: "Dies wird auf {{count}} Datensatz angewendet.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 823c0c151e5..e1932bb5fe4 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -803,6 +803,14 @@ const en = { bulkAllMatchingSelectedCapped: 'Only the first {{cap}} of {{total}} matching records will be processed.', bulkSelectedAllMatchesCapped: '{{cap}} selected (of {{total}} matches)', bulkActions: 'Bulk actions', + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: '{{count}} selected', + selectedCount_one: '{{count}} selected', + selectedCount_other: '{{count}} selected', + selectedAllLoaded: 'All {{count}} loaded records are selected.', + selectedAllLoaded_one: 'The {{count}} loaded record is selected.', + selectedAllLoaded_other: 'All {{count}} loaded records are selected.', + selectAllTotal: 'Select all {{total}}', empty: 'Empty', yes: 'Yes', no: 'No', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 89ff08678f9..ef55706e3f1 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -541,6 +541,16 @@ const es = { bulkAllMatchingSelectedCapped: "Solo se procesarán los primeros {{cap}} de {{total}} registros coincidentes.", bulkSelectedAllMatchesCapped: "{{cap}} seleccionados (de {{total}} coincidencias)", bulkActions: "Acciones masivas", + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: "{{count}} seleccionados", + selectedCount_one: "{{count}} seleccionado", + selectedCount_many: "{{count}} seleccionados", + selectedCount_other: "{{count}} seleccionados", + selectedAllLoaded: "Están seleccionados los {{count}} de esta página.", + selectedAllLoaded_one: "{{count}} registro de esta página está seleccionado.", + selectedAllLoaded_many: "Están seleccionados los {{count}} de esta página.", + selectedAllLoaded_other: "Están seleccionados los {{count}} de esta página.", + selectAllTotal: "Seleccionar las {{total}} coincidencias", bulk: { confirmDefault: "Esto se aplicará a {{count}} registro(s).", confirmDefault_one: "Esto se aplicará a {{count}} registro.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 0d5c0da01ca..e6c76454a79 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -536,6 +536,16 @@ const fr = { bulkAllMatchingSelectedCapped: "Seuls les {{cap}} premiers des {{total}} enregistrements correspondants seront traités.", bulkSelectedAllMatchesCapped: "{{cap}} sélectionnés (sur {{total}} résultats)", bulkActions: "Actions groupées", + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: "{{count}} sélectionné(s)", + selectedCount_one: "{{count}} sélectionné", + selectedCount_many: "{{count}} sélectionnés", + selectedCount_other: "{{count}} sélectionnés", + selectedAllLoaded: "Les {{count}} éléments de cette page sont sélectionnés.", + selectedAllLoaded_one: "{{count}} enregistrement de cette page est sélectionné.", + selectedAllLoaded_many: "Les {{count}} éléments de cette page sont sélectionnés.", + selectedAllLoaded_other: "Les {{count}} éléments de cette page sont sélectionnés.", + selectAllTotal: "Sélectionner les {{total}} correspondances", bulk: { confirmDefault: "Ceci s'appliquera à {{count}} enregistrement(s).", confirmDefault_one: "Ceci s'appliquera à {{count}} enregistrement.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 35c393dfdd2..5bd474ee182 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -528,6 +528,14 @@ const ja = { bulkAllMatchingSelectedCapped: "該当する {{total}} 件のうち、処理されるのは先頭の {{cap}} 件のみです。", bulkSelectedAllMatchesCapped: "{{cap}} 件を選択中(該当 {{total}} 件中)", bulkActions: "一括操作", + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: "{{count}} 件を選択中", + selectedCount_one: "{{count}} 件を選択中", + selectedCount_other: "{{count}} 件を選択中", + selectedAllLoaded: "このページの {{count}} 件がすべて選択されています。", + selectedAllLoaded_one: "このページの {{count}} 件がすべて選択されています。", + selectedAllLoaded_other: "このページの {{count}} 件がすべて選択されています。", + selectAllTotal: "該当する {{total}} 件すべてを選択", bulk: { confirmDefault: "{{count}} 件のレコードに適用されます。", confirmDefault_one: "{{count}} 件のレコードに適用されます。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 741cd55691c..3627f85fc4a 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -528,6 +528,14 @@ const ko = { bulkAllMatchingSelectedCapped: "일치하는 레코드 {{total}}건 중 처음 {{cap}}건만 처리됩니다.", bulkSelectedAllMatchesCapped: "{{cap}}건 선택됨(일치 항목 {{total}}건 중)", bulkActions: "일괄 작업", + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: "{{count}}건 선택됨", + selectedCount_one: "{{count}}건 선택됨", + selectedCount_other: "{{count}}건 선택됨", + selectedAllLoaded: "이 페이지의 {{count}}건이 모두 선택되었습니다.", + selectedAllLoaded_one: "이 페이지의 {{count}}건이 모두 선택되었습니다.", + selectedAllLoaded_other: "이 페이지의 {{count}}건이 모두 선택되었습니다.", + selectAllTotal: "일치하는 {{total}}건 모두 선택", bulk: { confirmDefault: "레코드 {{count}}건에 적용됩니다.", confirmDefault_one: "레코드 {{count}}건에 적용됩니다.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 78206244c9c..4662d68a6d1 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -536,6 +536,16 @@ const pt = { bulkAllMatchingSelectedCapped: "Apenas os primeiros {{cap}} de {{total}} registros correspondentes serão processados.", bulkSelectedAllMatchesCapped: "{{cap}} selecionados (de {{total}} correspondências)", bulkActions: "Ações em massa", + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: "{{count}} selecionados", + selectedCount_one: "{{count}} selecionado", + selectedCount_many: "{{count}} selecionados", + selectedCount_other: "{{count}} selecionados", + selectedAllLoaded: "Os {{count}} desta página estão selecionados.", + selectedAllLoaded_one: "{{count}} registro desta página está selecionado.", + selectedAllLoaded_many: "Os {{count}} desta página estão selecionados.", + selectedAllLoaded_other: "Os {{count}} desta página estão selecionados.", + selectAllTotal: "Selecionar todas as {{total}} correspondências", bulk: { confirmDefault: "Isto será aplicado a {{count}} registro(s).", confirmDefault_one: "Isto será aplicado a {{count}} registro.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index d8cde732688..9337802c4ef 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -547,6 +547,18 @@ const ru = { bulkAllMatchingSelectedCapped: "Будут обработаны только первые {{cap}} подходящих записей из {{total}}.", bulkSelectedAllMatchesCapped: "Выбрано: {{cap}} (всего совпадений: {{total}})", bulkActions: "Массовые действия", + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: "Выбрано: {{count}}", + selectedCount_one: "Выбрано: {{count}}", + selectedCount_few: "Выбрано: {{count}}", + selectedCount_many: "Выбрано: {{count}}", + selectedCount_other: "Выбрано: {{count}}", + selectedAllLoaded: "Выбраны все {{count}} на этой странице.", + selectedAllLoaded_one: "Выбраны все записи на этой странице ({{count}}).", + selectedAllLoaded_few: "Выбраны все записи на этой странице ({{count}}).", + selectedAllLoaded_many: "Выбраны все записи на этой странице ({{count}}).", + selectedAllLoaded_other: "Выбраны все записи на этой странице ({{count}}).", + selectAllTotal: "Выбрать все совпадения ({{total}})", bulk: { confirmDefault: "Будет применено к записям: {{count}}.", confirmDefault_one: "Будет применено к записям: {{count}}.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 40d8d8912b2..7c6a1f8903b 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -553,6 +553,14 @@ const zh = { bulkAllMatchingSelectedCapped: '将处理前 {{cap}} 条(共匹配 {{total}} 条记录)。', bulkSelectedAllMatchesCapped: '已选择 {{cap}} 项(共匹配 {{total}} 项)', bulkActions: '批量操作', + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: '已选 {{count}} 条', + selectedCount_one: '已选 {{count}} 条', + selectedCount_other: '已选 {{count}} 条', + selectedAllLoaded: '已选当前加载的 {{count}} 条。', + selectedAllLoaded_one: '已选当前加载的 {{count}} 条。', + selectedAllLoaded_other: '已选当前加载的 {{count}} 条。', + selectAllTotal: '选择全部 {{total}} 条', empty: '空', yes: '是', no: '否', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index e58168b5033..5700209b01b 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -553,6 +553,14 @@ const zhHant = { bulkAllMatchingSelectedCapped: '將處理前 {{cap}} 條(共匹配 {{total}} 條記錄)。', bulkSelectedAllMatchesCapped: '已選擇 {{cap}} 項(共匹配 {{total}} 項)', bulkActions: '批次操作', + // objectstack#35554 — the list page bar while rows are selected. + selectedCount: '已選 {{count}} 條', + selectedCount_one: '已選 {{count}} 條', + selectedCount_other: '已選 {{count}} 條', + selectedAllLoaded: '已選當前載入的 {{count}} 條。', + selectedAllLoaded_one: '已選當前載入的 {{count}} 條。', + selectedAllLoaded_other: '已選當前載入的 {{count}} 條。', + selectAllTotal: '選擇全部 {{total}} 條', empty: '空', yes: '是', no: '否', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 65d0315736a..0eae5abd24f 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -22,6 +22,7 @@ */ import React, { useEffect, useState, useCallback, useMemo } from 'react'; +import { createPortal } from 'react-dom'; import type { ObjectGridSchema, DataSource, ViewData, TableSortItem, DataTableSchema, ListViewExportFormat, RecordNavigateAction } from '@object-ui/types'; import { isSystemManagedField, detectStatusField } from '@object-ui/types'; import { SchemaRenderer, isPermissionError, useDataScope, useNavigationOverlay, useAction, useSafeFieldLabel, usePredicateScope, useCapabilityGate, useRelatedRecordActions, notifyDataChanged, useMetadata, claimAnswerWarnings, toastRecordSave, type AnswerWarningClaim, type RecordSaveFeedback } from '@object-ui/react'; @@ -105,6 +106,9 @@ import { resolveObjectGridPersistedColumns } from './objectGridPersistedColumns' import { resolveObjectGridActionsColumn } from './objectGridActionsColumn'; import { useInlineRowActionFold } from './objectGridInlineActionFold'; import { BULK_SELECT_ALL_MATCHING_CAP } from './bulkSelectAllMatchingCap'; +import { useListPageBarSlot, useListPageBarState } from './listPageBarSlot'; +import { SelectionPageBar } from './components/SelectionPageBar'; +import { useInfiniteRowLoad } from './objectGridInfiniteLoad'; export type { RetiredListColumnKey, ObjectGridColumnHolds, ObjectGridColumnDraft, ObjectGridColumn } from './objectGridColumns'; export type { ObjectGridColumnState, ObjectGridFooterSummary, ObjectGridExternalPaginationProps, ObjectGridRowGroup } from './objectGridProps'; @@ -716,6 +720,9 @@ export const ObjectGrid: React.FC = ({ search: hostSearch, onSearchChange: hostOnSearchChange, findParams: hostFindParams, + onLoadMore, + hasMoreRows, + scrollRestoreKey, onColumnStateChange, objectFields: hostObjectFields, showRowNumbers: hostShowRowNumbers, @@ -804,6 +811,18 @@ export const ObjectGrid: React.FC = ({ schema, dataSource, setRefreshKey, setUseCardView, }); + // objectstack#35554 — the list page bar's selection slot + // (`./listPageBarSlot`). A grid inside a list page's page column fills the + // page bar's slot: it draws no row-end control and no bulk bar, and its + // selection swaps the page bar's content instead. Any other host (a related + // list, a page block, the record drawer) finds no slot and keeps both. + const [gridRoot, setGridRoot] = useState(null); + const setRootRef = useCallback((el: HTMLDivElement | null) => { + setGridRoot(el); + (pullRef as React.MutableRefObject).current = el; + }, [pullRef]); + const pageBarSlot = useListPageBarSlot(gridRoot); + // `passedData` — data handed down directly (from ListView) — is destructured // from props above. @@ -1455,6 +1474,24 @@ export const ObjectGrid: React.FC = ({ fetchWindow, serverGroupedFetch, isGrouped, }); + // 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 }); + + // objectstack#35554 — a host that loads its rows window by window + // (`onLoadMore`) is asked for the next window as the table's scroll box + // nears its end, and the box's position is kept across a return to the list + // (`./objectGridInfiniteLoad`). + useInfiniteRowLoad({ + root: gridRoot, + enabled: !!onLoadMore, + hasMore: !!hasMoreRows, + loading, + rowCount: data.length, + onLoadMore, + restoreKey: scrollRestoreKey, + }); + // The authored-input diagnostics (`columns`, `bulkActionDefs`, page size), // three `console.warn` effects, run here in hook order (`./objectGridDiagnostics`). useObjectGridDiagnostics(schema); @@ -1787,6 +1824,7 @@ export const ObjectGrid: React.FC = ({ wantEditAction, wantDeleteAction, mayInvokeRowAction, rowOperations, canEdit, canDelete, recordVerdict, predicateScope, onEdit, onDelete, editPredicates, deletePredicates, executeAction, setRefreshKey, t, foldInlineRowActions: inlineActionFold.folded, + drawRowControls: !pageBarSlot, }); // Density-driven cell padding/font (applied to every column so it actually reaches ). @@ -2844,7 +2882,8 @@ export const ObjectGrid: React.FC = ({ columns: tableColumns, data, summaryRow, - pagination: paginationEnabled, + // objectstack#35554 — a host that loads window by window draws no pager. + pagination: paginationEnabled && !onLoadMore, pageSize: manualPaginationOn ? manualPageSize : pageSize, // Rows-per-page selector options sourced from view metadata // (schema.pagination.pageSizeOptions). When absent the DataTable falls back @@ -4188,7 +4227,7 @@ export const ObjectGrid: React.FC = ({ ); return ( -
+
{/* Re-fetch indicator while existing rows remain visible (filter/sort change). The initial-load skeleton above handles the empty case. */} 0} ariaLabel={t('grid.refreshing')} /> @@ -4207,19 +4246,42 @@ export const ObjectGrid: React.FC = ({ {isGrouped && onRowGroupsChange && ( )} - setSelectAllMatching(true) : undefined} - /> + {pageBarSlot ? ( + // objectstack#35554 — on a list page the selection is the page bar's: + // its content is drawn into the bar's slot, and no bar floats over + // the rows. + selectedRows.length > 0 && createPortal( + setSelectAllMatching(true) : undefined} + />, + pageBarSlot, + ) + ) : ( + setSelectAllMatching(true) : undefined} + /> + )} {navigation.isOverlay && ( => { + const body = JSON.parse(String(init?.body ?? '{}')) as { object?: string; operation?: string; recordId?: string; recordIds?: string[] }; + const base = { allowed: true, object: body.object, operation: body.operation ?? 'update', principal: { userId: 'u' }, layers: [] }; + const payload = Array.isArray(body.recordIds) + ? { ...base, records: body.recordIds.map((recordId) => ({ recordId, visible: true })) } + : typeof body.recordId === 'string' + ? { ...base, record: { recordId: body.recordId, visible: true } } + : base; + return { ok: true, status: 200, json: async () => payload } as unknown as Response; +}; + +beforeEach(() => __clearRecordCrudVerdictCache()); + +registerAllFields(); + +const ROWS = [ + { id: '1', name: 'Alice', amount: 100 }, + { id: '2', name: 'Bob', amount: 200 }, + { id: '3', name: 'Carol', amount: 300 }, +]; + +const SCHEMA: any = { + type: 'object-grid', + objectName: 'test_object', + columns: [ + { field: 'name', label: 'Name' }, + { field: 'amount', label: 'Amount', type: 'number' }, + ], + data: { provider: 'value', items: ROWS }, + selection: { type: 'multiple' }, + rowActionDefs: [ + { name: 'submit_approval', label: 'Submit for approval' }, + { name: 'make_quote', label: 'Make quote' }, + { name: 'clone', label: 'Clone' }, + ], + bulkActionDefs: [ + { name: 'mass_update', label: 'Mass update' }, + { name: 'assign', label: 'Assign' }, + { name: 'tag', label: 'Tag' }, + ], +}; + +/** The fixture page bar: the slot, and the state the list writes. */ +const PageBar: React.FC = () => { + const [slot, setSlot] = React.useState(null); + const [scope, setScope] = React.useState(null); + const state = useListPageBarHost(slot, scope); + return ( +
setScope(el?.parentElement ?? null)} data-testid="page-bar" data-selecting={state.selecting ? 'yes' : 'no'}> +
+
+ ); +}; + +function renderListPage(withPageBar: boolean) { + return render( + + +
+ {withPageBar && } + {}} + onDelete={() => {}} + /> +
+
+
, + ); +} + +const tick = (name: string) => { + const row = screen.getByText(name).closest('tr')!; + fireEvent.click(within(row).getByRole('checkbox')); +}; + +describe('objectstack#35554 — the list page bar takes the row controls', () => { + it('a list page grid draws no Actions column and no hover control', async () => { + const { container } = renderListPage(true); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + expect(container.querySelector('th[data-column-key="_actions"]')).toBeNull(); + expect(screen.queryAllByTestId('row-action-trigger')).toHaveLength(0); + }); + + it('CONTROL: a grid with no page bar keeps its Actions column', async () => { + const { container } = renderListPage(false); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + await waitFor(() => expect(container.querySelector('th[data-column-key="_actions"]')).not.toBeNull()); + expect(screen.getAllByTestId('row-action-trigger').length).toBeGreaterThan(0); + }); + + it('one row selected: the slot holds the count and that record\'s first two actions, no bottom bar', async () => { + renderListPage(true); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + tick('Alice'); + const slot = screen.getByTestId('page-bar-slot'); + await waitFor(() => expect(within(slot).getByTestId('list-selection-bar')).toBeInTheDocument()); + expect(screen.getByTestId('page-bar')).toHaveAttribute('data-selecting', 'yes'); + expect(within(slot).getByTestId('list-selection-count')).toHaveTextContent('1'); + expect(within(slot).getByTestId('row-action-inline-submit_approval')).toBeInTheDocument(); + expect(within(slot).getByTestId('row-action-inline-make_quote')).toBeInTheDocument(); + expect(within(slot).queryByTestId('row-action-inline-clone')).toBeNull(); + expect(within(slot).getByTestId('selection-actions-more')).toBeInTheDocument(); + expect(screen.queryByTestId('bulk-actions-bar')).toBeNull(); + }); + + it('two rows selected: the bulk actions instead; Cancel restores the page bar', async () => { + renderListPage(true); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + tick('Alice'); + tick('Bob'); + const slot = screen.getByTestId('page-bar-slot'); + await waitFor(() => expect(within(slot).getByTestId('list-selection-count')).toHaveTextContent('2')); + expect(within(slot).getByTestId('bulk-action-mass_update')).toBeInTheDocument(); + expect(within(slot).getByTestId('bulk-action-assign')).toBeInTheDocument(); + expect(within(slot).queryByTestId('row-action-inline-submit_approval')).toBeNull(); + expect(screen.queryByTestId('bulk-actions-bar')).toBeNull(); + fireEvent.click(within(slot).getByTestId('list-selection-cancel')); + await waitFor(() => expect(screen.getByTestId('page-bar')).toHaveAttribute('data-selecting', 'no')); + expect(within(slot).queryByTestId('list-selection-bar')).toBeNull(); + expect(screen.getAllByRole('checkbox').filter((c) => c.getAttribute('data-state') === 'checked')).toHaveLength(0); + }); + + it('CONTROL: a grid with no page bar keeps the bottom bulk bar', async () => { + renderListPage(false); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + tick('Alice'); + await waitFor(() => expect(screen.getByTestId('bulk-actions-bar')).toBeInTheDocument()); + }); + + it('Shift extends a selection over the rows between', async () => { + renderListPage(true); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + tick('Alice'); + const carolCell = screen.getByText('Carol').closest('tr')!.querySelector('[data-slot="row-leading-cell"]')!; + fireEvent.click(carolCell, { shiftKey: true }); + const slot = screen.getByTestId('page-bar-slot'); + await waitFor(() => expect(within(slot).getByTestId('list-selection-count')).toHaveTextContent('3')); + }); + + it('right-click on a row: the row\'s actions, Delete last, after a separator, in the danger colour', async () => { + renderListPage(true); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + fireEvent.contextMenu(screen.getByText('Alice').closest('tr')!); + const menu = await screen.findByRole('menu'); + const items = within(menu).getAllByRole('menuitem'); + const last = items[items.length - 1]; + expect(last).toHaveAttribute('data-testid', 'row-action-builtin-delete'); + expect(last.className).toContain('text-destructive'); + const separator = within(menu).getByTestId('row-action-delete-separator'); + expect(separator.compareDocumentPosition(last) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(within(menu).getByTestId('row-action-submit_approval')).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/phoneCardRowActions-29150.test.tsx b/ui/packages/plugin-grid/src/__tests__/phoneCardRowActions-29150.test.tsx index 2c5c8f40c41..7da188b5821 100644 --- a/ui/packages/plugin-grid/src/__tests__/phoneCardRowActions-29150.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/phoneCardRowActions-29150.test.tsx @@ -164,14 +164,16 @@ afterEach(() => { describe('objectstack#29150 · a phone list card offers its row actions', () => { it('at 390 px each card\'s menu lists the desktop row\'s actions, in the same order', async () => { const desktop = await desktopRowActions(); - // The desktop reference is the full set: Edit, Delete, the primary, then - // the secondaries, the gated one only where its predicate holds. + // The desktop reference is the full set: Edit, the primary, then the + // secondaries (the gated one only where its predicate holds), and Delete + // last (objectstack#35554). expect(desktop.Acme).toEqual([ 'row-action-builtin-edit', - 'row-action-builtin-delete', 'row-action-promote', 'row-action-submit_review', 'row-action-archive', + // objectstack#35554: Delete closes the menu, after a separator. + 'row-action-builtin-delete', ]); expect(desktop.Globex).not.toContain('row-action-submit_review'); diff --git a/ui/packages/plugin-grid/src/__tests__/rowContextMenu-28434.test.tsx b/ui/packages/plugin-grid/src/__tests__/rowContextMenu-28434.test.tsx index 5e54a42b0a4..4db3c0b9ab0 100644 --- a/ui/packages/plugin-grid/src/__tests__/rowContextMenu-28434.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/rowContextMenu-28434.test.tsx @@ -197,10 +197,11 @@ describe('objectstack#28434 · a row\'s context menu lists exactly its "⋮" ite expect(context).toEqual([ ...OPEN_ITEMS, 'row-action-builtin-edit', - 'row-action-builtin-delete', 'row-action-promote', 'row-action-submit_review', 'row-action-archive', + // objectstack#35554: Delete closes the menu, after a separator. + 'row-action-builtin-delete', ]); }); diff --git a/ui/packages/plugin-grid/src/components/BulkActionBar.tsx b/ui/packages/plugin-grid/src/components/BulkActionBar.tsx index 1a1672d92a1..37cfea2b6ac 100644 --- a/ui/packages/plugin-grid/src/components/BulkActionBar.tsx +++ b/ui/packages/plugin-grid/src/components/BulkActionBar.tsx @@ -121,19 +121,41 @@ export function isDestructiveBulkDef(def: BulkActionDef): boolean { return def.variant === 'danger' || def.operation === 'delete'; } +/** One entry of a selection's actions, in the order a menu or the page bar draws them. */ +export type OrderedBulkItem = + | { kind: 'def'; key: string; destructive: boolean; def: BulkActionDef } + | { kind: 'legacy'; key: string; destructive: boolean; legacy: LegacyBulkActionItem }; + +/** + * objectstack#35554 — a selection's actions as one list: the rich defs, then + * the legacy names, each in declared order, with every destructive entry moved + * to the end (the order is otherwise kept). The selection's context menu and + * the page bar's selection actions read this one order, so the actions the bar + * exposes are the first entries of the menu, and Delete closes both. + */ +export function orderSelectionMenuItems(items: BulkActionItems): OrderedBulkItem[] { + const all: OrderedBulkItem[] = [ + ...items.defs.map((def) => ({ kind: 'def' as const, key: `def:${def.name}`, destructive: isDestructiveBulkDef(def), def })), + ...items.legacy.map((legacy) => ({ kind: 'legacy' as const, key: `legacy:${legacy.name}`, destructive: legacy.destructive, legacy })), + ]; + return [...all.filter((e) => !e.destructive), ...all.filter((e) => e.destructive)]; +} + /** One rich bulk-action button, offered per {@link useBulkActionItems}. */ -const BulkActionButton: React.FC<{ +export const BulkActionButton: React.FC<{ def: BulkActionDef; selectedRows: any[]; onActionDef?: (def: BulkActionDef, selectedRows: any[]) => void; -}> = ({ def, selectedRows, onActionDef }) => { + /** `page-bar`: the list page bar's button size (objectstack#35554). */ + size?: 'bar' | 'page-bar'; +}> = ({ def, selectedRows, onActionDef, size = 'bar' }) => { const isDestructive = isDestructiveBulkDef(def); const iconName = def.icon ? toKebabIconName(def.icon) : null; return ( + ); +}; + +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..48bb4ee5f78 --- /dev/null +++ b/ui/packages/plugin-grid/src/listPageBarSlot.ts @@ -0,0 +1,127 @@ +/** + * 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 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. + * + * 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; +} + +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 } = state; + React.useLayoutEffect(() => { + const host = hostOf(slot); + if (!host) return undefined; + host.state = { selecting }; + 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]); +} 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 97733f57f81..ab168985d85 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -68,7 +68,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 @@ -2045,7 +2045,8 @@ function ListOptionPicker({ /** * What a function `toolbarLeading` is called with (objectstack#35548). * `recordCount` is the count the record-count bar says — the server's total - * under paging, the rows otherwise, a paged board's view total — or `null` + * under paging and while the list loads as it scrolls (objectstack#35554: the + * matching rows, not the rows loaded so far), the rows otherwise, a paged board's view total — or `null` * while the list says none (loading, a windowed calendar, `showRecordCount: * false`). `layout` is the visualization on screen. */ @@ -2572,6 +2573,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 }); @@ -2774,8 +2786,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); @@ -4320,7 +4356,18 @@ 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, + // 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 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 @@ -4367,13 +4414,24 @@ 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; 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 })); @@ -4415,7 +4473,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) { @@ -4433,7 +4491,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 @@ -4538,7 +4596,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 @@ -4556,6 +4614,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]); @@ -6602,7 +6662,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 @@ -8062,18 +8122,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'] }, 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]); + }); +});