diff --git a/.changeset/35678-floating-selection-bar.md b/.changeset/35678-floating-selection-bar.md new file mode 100644 index 00000000000..306b8c78ca8 --- /dev/null +++ b/.changeset/35678-floating-selection-bar.md @@ -0,0 +1,21 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/components': patch +'@object-ui/types': patch +'@object-ui/app-shell': patch +--- + +feat(plugin-grid): selected rows get one small bar floating at the bottom centre of the list + +Clause-②: yes (widening) +Metadata-protocol: none + +Selecting rows in a grid now shows one bar floating at the bottom centre of the list area: 「已选 N 条」 and ×, up to three labelled actions, and the rest under 「更多」. When the selection offers no more than three actions they are all buttons, so a lone Delete is a button; over three, Delete goes behind 「更多」 with the rest. The bar sits above the footer calc row, the list keeps room after its last row so that row scrolls fully clear of the bar, and when every loaded row is selected and more match, the bar offers 「选择全部 N 条」. × or Esc clears the selection; Esc that belongs to a field, or to another open menu or dialog, does not. + +The same bar serves the object list page, a record's child-table tabs, the side record and embedded tables. The old bottom strip and the list page's 「已选」 face in the view bar are both retired, so the top of the list page no longer changes when rows are selected. On the list page, where rows draw no actions of their own, one selected record offers that record's actions; elsewhere the bar offers the bulk actions at any count. A narrow list gives actions back to 「更多」 until the bar fits on one line. + +- `@object-ui/plugin-grid`: `BulkActionBar` is redrawn as the floating bar; its props gain `singleRowMenu`. `useListPageScope(scope)` replaces the unpublished `useListPageBarHost`. +- `@object-ui/types` / `@object-ui/components`: `DataTableSchema.floatingBar` is a runtime slot (refused by the zod twin like the other runtime slots). The table floats it over its scroll box, above its summary row, with room after its last row. +- `@object-ui/app-shell`: the list page header and the view bar no longer swap to a selection face. + +This supersedes the selection behaviour in the list-page entry of this release (no Actions column on the list page): the selection is no longer shown in the page bar, up to three actions are buttons and a lone Delete is one, and grids outside a list page no longer draw a bottom bulk bar. diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 9bba7b25ae3..6fd674d1d47 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -621,7 +621,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": 13, + "revision": 14, "priority": "P1", "surface": "browser", "personas": [ @@ -659,7 +659,7 @@ "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 settings) popover beside the view name — the Display popover, named 选项 (Options) until objectstack#35878 moved it there — 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 selection actions the view bar's right end shows (since #35554 the list page has no bottom bulk bar; since #35878 the selection face is the view bar's right end, with ⋮ still last), 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 floating selection bar shows (since #35678 one bar floats at the bottom centre of the list and the view bar does not change on selection; over three actions the rest are under 「更多」), 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: no page bar (objectstack#35878): a 40px view bar with the object's icon and name, 「/」, ONE switcher trigger reading type icon → view name → record count → caret, and 「视图设置」 on the left, and the search icon, 「+ 新建」 and ⋮ (description, import, favorite) last on the right; under it a 40px condition row that is always drawn — dashed 「排序」 and 「筛选」 while no condition is set, one 「按 X 排序」 chip (with +N) and the filter chips once set — so the table's header does not move when a condition is set or reset; 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 rows (objectstack#35548; the count beside the view name returns, after objectstack#34603 removed it)", "at 1280×800 with the sidebar open, read the left edges of the list page on All Tasks (a list whose columns fit) and on a list that scrolls sideways (stage one by showing every field of showcase_task through 视图设置 → 添加列): the view bar's object icon, the header's select-all box, each row's checkbox and the footer's record count each start 16px from the main area's left; the selection column is 40px on both lists and stays 40px, pinned at the left, after scrolling to the far right and back; no row shows a number and each row's checkbox shows without a hover; the view bar's last control, ⋮, ends its icon 16px from the right; at 375 wide no leading item sits closer than 12px to the left (objectstack#35663)" @@ -832,7 +832,8 @@ "change": "steps[11] and its acceptance clause added: the list page's left edge (objectstack#35663, epic #35547). The page bar's icon, the view bar's icon, the select-all box, every row's checkbox and the footer's count share one 16px line, the selection column is 40px at any width and under a sideways scroll, and the grid draws no row numbers (each row's checkbox shows at rest). No earlier clause changed", "ref": "#35663" }, - { "revision": 13, "date": "2026-11-20", "change": "steps[6], [8], [10], [11] and the clauses acceptance[10] and acceptance[11] follow #35878: the list page draws two rows, not three. There is no page bar; the view bar leads with the object's icon and name, then the switcher and 「视图设置」 (was 「选项」), and ends with search, 「+ 新建」 and ⋮ last (#35678). The condition row is always drawn at 40px, so the frame clause reads condition row 40 where it read 'no condition row height', and the left-edge clause's first item is the view bar's object icon where it was the page bar's (the view icon no longer leads the bar). Filter N and Sort N left the bar for the condition row", "ref": "#35878" } + { "revision": 13, "date": "2026-11-20", "change": "steps[6], [8], [10], [11] and the clauses acceptance[10] and acceptance[11] follow #35878: the list page draws two rows, not three. There is no page bar; the view bar leads with the object's icon and name, then the switcher and 「视图设置」 (was 「选项」), and ends with search, 「+ 新建」 and ⋮ last (#35678). The condition row is always drawn at 40px, so the frame clause reads condition row 40 where it read 'no condition row height', and the left-edge clause's first item is the view bar's object icon where it was the page bar's (the view icon no longer leads the bar). Filter N and Sort N left the bar for the condition row", "ref": "#35878" }, + { "revision": 14, "date": "2026-11-21", "change": "steps[8] follows #35678: the selection actions are in one bar floating at the bottom centre of the list, and the view bar no longer changes on selection; what Mark Done's visible gate does is unchanged", "ref": "#35678" } ] }, { @@ -3826,7 +3827,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": 11, + "revision": 12, "priority": "P2", "surface": "browser", "personas": [ @@ -3845,20 +3846,20 @@ }, "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 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 view bar's right end swaps to 「已选 N 条」 and offers 「已选当前加载的 N 条。」 with 「选择全部 M 条」 (en 'All N loaded records are selected.' / 'Select all M')", - "click 「选择全部 M 条」; the selection face's count reads the whole match set ('M selected (all matches)')", + "tick the header checkbox (every loaded row); the selection bar floats at the bottom centre of the list reading 「已选 N 条」 and offers 「选择全部 M 条」 (en 'N selected' / 'Select all M'); the view bar does not change", + "click 「选择全部 M 条」; the selection 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", "click clear; confirm both selection sources reset (the toolbar empties AND the row checkboxes clear)", - "cap leg (acceptance[5]): provision more than 5000 matching scratch tasks — POST /api/v1/data/showcase_task/createMany with a bare JSON array of at most 200 records per call (the batch doors' default maxBatchSize; a 201-record call answers 400 BATCH_TOO_LARGE), e.g. 26 calls of 200 sharing one prefix — then repeat steps[1] and steps[2] and screenshot the banner and the selected count before and after Select all; delete the rows afterwards (POST /api/v1/data/showcase_task/deleteMany with {\"ids\": [...]}, at most 200 ids per call; a bare array answers 400)" + "cap leg (acceptance[5]): provision more than 5000 matching scratch tasks — POST /api/v1/data/showcase_task/createMany with a bare JSON array of at most 200 records per call (the batch doors' default maxBatchSize; a 201-record call answers 400 BATCH_TOO_LARGE), e.g. 26 calls of 200 sharing one prefix — then repeat steps[1] and steps[2] and screenshot the selection bar and its count (with its title) before and after Select all; delete the rows afterwards (POST /api/v1/data/showcase_task/deleteMany with {\"ids\": [...]}, at most 200 ids per call; a bare array answers 400)" ], "acceptance": [ { - "clause": "the select-all offer in the view bar's selection face 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", + "clause": "the select-all offer in the floating selection 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 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" + "verify": "the offer's count equals the data request's response total (BulkActionBar totalMatching; ListView hands result.total down as rowCount, read by ObjectGrid as resolvedTotalMatching)", + "evidence": "selection bar screenshot + the find response total" }, { "clause": "select-all-matching resolves EVERY matching id across pages: the dispatched set equals a direct filtered API count, not just the visible page (paged fan-out with $top/$skip dropped, capped at 5000)", @@ -3885,15 +3886,15 @@ "evidence": "the collected-set size vs the server total" }, { - "clause": "past the cap the banner names it: when the server total exceeds HARD_CAP 5000, the cross-page offer, the all-selected line and the selected count say the action covers the first 5000 (e.g. 「将处理前 5000 条」, 'the first 5000 will be processed'), never the uncapped total alone — a banner claiming all M matching while the dispatch stops at 5000 is a silent partial execution", + "clause": "past the cap the selection bar names it: when the server total exceeds HARD_CAP 5000, the cross-page offer, the all-selected line and the selected count say the action covers the first 5000 (e.g. 「将处理前 5000 条」, 'the first 5000 will be processed'), never the uncapped total alone — a bar claiming all M matching while the dispatch stops at 5000 is a silent partial execution", "oracle": "dom", - "verify": "with more than 5000 matching rows (steps[7]), after a screenshot confirms the bar rendered: read the bulk-cross-page-banner text and the selected count before and after Select all; PASS when each names the 5000 cap, FAIL when any presents the uncapped total M as the set the action will process. The fan-out itself is acceptance[4]'s; this clause scores only what the banner tells the user", - "evidence": "the banner screenshot and its DOM text before and after Select all, the find response total, the collected-set size" + "verify": "with more than 5000 matching rows (steps[7]), after a screenshot confirms the bar rendered: read the bulk-select-all-matching offer text and the bulk-selection-count chip (its text and its title) before and after Select all; PASS when each names the 5000 cap, FAIL when any presents the uncapped total M as the set the action will process. The fan-out itself is acceptance[4]'s; this clause scores only what the bar tells the user", + "evidence": "the selection bar screenshot and its DOM text before and after Select all, the find response total, the collected-set size" } ], "negative": [ "a 'select all matching' that only acts on the RENDERED page (ids = page rows, not the server match set) is THE FAIL this item extends list-view-capabilities (page-local bulk) to catch", - "a banner total that disagrees with the filtered API count is a FAIL", + "a selection bar total that disagrees with the filtered API count is a FAIL", "a clear that leaves the row checkboxes ticked while the toolbar empties (or vice versa) is a FAIL (#3056 drift)" ], "traps": [ @@ -3905,7 +3906,7 @@ "ref": "objectui: packages/plugin-grid/src/__tests__/{objectBulkActionDispatch,BulkActionBar,bulkActionRefresh}.test.tsx — component layer, jsdom, over a mocked data source. None of the three exercises resolveBulkRows' paged fan-out or its HARD_CAP, so acceptance[1], acceptance[4] and negative[0] are not pinned by them. packages/plugin-grid/src/__tests__/bulkFanoutHostParams.test.tsx, outside this list, does drive that fan-out at the same component layer (500-record pages that replay the host's query, and 'still honours HARD_CAP over a match set larger than the cap'): it is evidence beside those clauses, never their pass, because their oracle is the dispatched set against a live filtered count (RUNNER rule 6). bulkActionRefresh.test.tsx's 'bulk bar Clear resets both selection sources' case asserts acceptance[3] and negative[2] in jsdom; their dom oracle wants the rendered page, screenshot first" }, "source": [ - "objectui: packages/plugin-grid/src/ObjectGrid.tsx (selectAllMatching, resolveBulkRows paged fan-out + HARD_CAP, resetSelection #3056, totalMatching), packages/plugin-grid/src/components/BulkActionBar.tsx (cross-page banner)", + "objectui: packages/plugin-grid/src/ObjectGrid.tsx (selectAllMatching, resolveBulkRows paged fan-out + HARD_CAP, resetSelection #3056, totalMatching), packages/plugin-grid/src/components/SelectionBar.tsx (the selection bar: count chip, select-all-matching offer)", "examples/app-showcase/src/ui/views/task.view.ts#bulk_actions (the 'Bulk Actions' view: bulkActions + the aggregate bulkActionDefs entry — this item's fixture since #23169; the stock 10 tasks need the scratch rows to exceed a page) — not examples/app-showcase/src/data/seed/index.ts's Northwind 26, which page the Account → Contacts related list (objectui#2711)", "PENDING-GAPS §C bulk-select-all-matching; cross-ref records-forms.list-view-capabilities (bulk-actions, page-local)" ], @@ -3970,7 +3971,8 @@ "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" }, - { "revision": 11, "date": "2026-11-20", "change": "steps[1], steps[2] and the clause acceptance[0] follow #35878: the list page has no page bar, so the selection face (「已选 N 条」, the cross-window offer) is the view bar's right end, with ⋮ still last. What it reports is unchanged", "ref": "#35878" } + { "revision": 11, "date": "2026-11-20", "change": "steps[1], steps[2] and the clause acceptance[0] follow #35878: the list page has no page bar, so the selection face (「已选 N 条」, the cross-window offer) is the view bar's right end, with ⋮ still last. What it reports is unchanged", "ref": "#35878" }, + { "revision": 12, "date": "2026-11-21", "change": "steps[1]–[3], acceptance[0], acceptance[5], the negative and the source ref follow #35678: the selection is shown in one bar floating at the bottom centre of the list (「已选 N 条」, ×, 「选择全部 M 条」) and the view bar no longer changes; the cross-window sentence is gone, and past the cap the count chip's text and title carry the cap strings acceptance[5] reads. What it reports is unchanged", "ref": "#35678" } ] }, { diff --git a/examples/app-showcase/e2e/bulk-capability-gate.spec.ts b/examples/app-showcase/e2e/bulk-capability-gate.spec.ts index 00d02fd49c2..50cf9c0df67 100644 --- a/examples/app-showcase/e2e/bulk-capability-gate.spec.ts +++ b/examples/app-showcase/e2e/bulk-capability-gate.spec.ts @@ -44,16 +44,16 @@ test('selection bar hides capability-gated inline defs from a caller without the await selectAll.waitFor({ state: 'visible', timeout: 25_000 }); await selectAll.click(); - // The bar offers the ungated defs: it draws the first two as buttons and - // the rest behind its "⋮" (`SELECTION_EXPOSED_ACTIONS`, ui plugin-grid - // `SelectionPageBar.tsx`, citing #35554 「露出一到两个,其余进⋮」), where a - // def is a `row-context-bulk-NAME` menu item instead of a + // The bar offers the ungated defs: it draws the first three as buttons and + // the rest behind its More (`SELECTION_EXPOSED_ACTIONS`, ui plugin-grid + // `SelectionBar.tsx`, objectstack#35678: up to three labelled actions, the rest behind More), + // where a def is a `row-context-bulk-NAME` menu item instead of a // `bulk-action-NAME` button. All four ungated defs are read, so none of // them can drop out of the bar unnoticed. await expect(page.getByTestId('bulk-action-set_labels')).toBeVisible({ timeout: 15_000 }); await expect(page.getByTestId('bulk-action-assign_team')).toBeVisible(); + await expect(page.getByTestId('bulk-action-reassign_account')).toBeVisible(); await page.getByTestId('selection-actions-more').click(); - await expect(page.getByTestId('row-context-bulk-reassign_account')).toBeVisible(); await expect(page.getByTestId('row-context-bulk-reschedule')).toBeVisible(); // …and neither gated def, as a button or as an item of the open "⋮" — the diff --git a/ui/e2e/list-no-actions-column-35554.spec.ts b/ui/e2e/list-no-actions-column-35554.spec.ts index bcc146a85de..ad41ad29c51 100644 --- a/ui/e2e/list-no-actions-column-35554.spec.ts +++ b/ui/e2e/list-no-actions-column-35554.spec.ts @@ -10,14 +10,16 @@ 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. + * column, 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. Since objectstack#35678 a selection no longer swaps the page + * bar: one bar floats at the bottom centre of the list, and the cases at the + * end pin it on a child-table tab and the side record too. * * ## 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 + * The bar floats over the list's scroller, and "the bar sits above the summary + * row", "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`. @@ -37,6 +39,10 @@ import { uiRoot } from '../scripts/ui-root.mjs'; * - 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 record page (a header, a tab strip and a child-table tab) and the + * side record (a right-hand dialog over the list page) are plain markup + * shaped like the console's; the grid in each is the real `ObjectGrid` + * over one opportunity's 30 line items, with no list-page scope. * - 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 @@ -74,6 +80,11 @@ interface Case { /** Declare `pagination` on the view (the list keeps its pager). */ paged?: boolean; theme?: 'light' | 'dark'; + /** + * objectstack#35678 — where the grid sits: the list page (default), a + * record page's child-table tab, or a side record panel over the list. + */ + face?: 'list' | 'tab' | 'drawer'; } const ENTRY = '\0list-no-actions-column:entry'; @@ -104,7 +115,7 @@ 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 { ObjectGrid } from ${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)}; @@ -141,14 +152,31 @@ const ROWS = Array.from({ length: ${ROW_COUNT} }, (_, i) => ({ owner: '销售 ' + ((i % 5) + 1), close_date: '2027-01-' + String((i % 28) + 1).padStart(2, '0'), })); +// objectstack#35678 — a child object for the record page's tab and the side +// record panel: one opportunity's line items. +const LINE_FIELDS = { + id: { name: 'id', type: 'text' }, + product: { name: 'product', label: '产品', type: 'text' }, + quantity: { name: 'quantity', label: '数量', type: 'number' }, + price: { name: 'price', label: '单价', type: 'currency' }, +}; +const LINES = Array.from({ length: 30 }, (_, i) => ({ + id: 'l' + String(i + 1).padStart(3, '0'), + product: '产品 ' + (i + 1), + quantity: (i % 7) + 1, + price: 500 + i * 50, +})); const dataSource = { - find: async (_object, params = {}) => { - window.__finds.push({ skip: params.$skip ?? 0, top: params.$top }); + find: async (object, params = {}) => { + const rows = object === 'opportunity_line' ? LINES : ROWS; + if (object !== 'opportunity_line') 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 }; + const top = params.$top ?? rows.length; + return { data: rows.slice(skip, skip + top), total: rows.length }; }, - getObjectSchema: async (name) => ({ name, label: '商机', fields: FIELDS }), + getObjectSchema: async (name) => name === 'opportunity_line' + ? { name, label: '商机明细', fields: LINE_FIELDS } + : { name, label: '商机', fields: FIELDS }, }; const record = (name) => async () => { window.__dispatched.push(name); return { success: true }; }; const rowActionDefs = [ @@ -161,7 +189,31 @@ const bulkActionDefs = [ { name: 'mass_assign', label: '批量分配' }, { name: 'mass_tag', label: '批量打标签' }, ]; -const handlers = Object.fromEntries([...rowActionDefs, ...bulkActionDefs].map((d) => [d.name, record(d.name)])); +const lineBulkActionDefs = [ + { name: 'line_discount', label: '批量折扣' }, + { name: 'line_reprice', label: '重新定价' }, +]; +const handlers = Object.fromEntries([...rowActionDefs, ...bulkActionDefs, ...lineBulkActionDefs].map((d) => [d.name, record(d.name)])); +const lineSchema = { + type: 'object-grid', + objectName: 'opportunity_line', + columns: ['product', 'quantity', 'price'], + selection: { type: 'multiple' }, + bulkActionDefs: lineBulkActionDefs, +}; +// The line grid as a record page's child-table tab and as the side record +// panel draw it: no list-page scope, so its rows keep their own actions. +const lineGrid = () => h('div', { 'data-testid': 'line-grid' }, + h(ObjectGrid, { schema: lineSchema, dataSource, onEdit: () => {}, onDelete: () => {} })); +const recordHeader = () => h('div', { className: 'border-b border-border px-6 py-5' }, + h('h1', { className: 'text-xl font-semibold' }, '商机 1'), + h('p', { className: 'mt-1 text-sm text-muted-foreground' }, '客户 1 · 资格审查 · 销售 1'), + h('div', { className: 'mt-4 grid grid-cols-3 gap-4 text-sm' }, + ...['金额', '赢率', '预计成交日期'].map((label) => h('div', { key: label }, + h('div', { className: 'text-muted-foreground' }, label), h('div', null, '—'))))); +const tabStrip = () => h('div', { role: 'tablist', className: 'flex gap-4 border-b border-border px-6' }, + h('button', { role: 'tab', 'aria-selected': 'false', className: 'py-2 text-sm text-muted-foreground' }, '详情'), + h('button', { role: 'tab', 'aria-selected': 'true', className: 'border-b-2 border-primary py-2 text-sm font-medium' }, '商机明细')); const schema = { type: 'list-view', @@ -217,17 +269,27 @@ function ViewBarLead({ recordCount, layout }) { })); } +const listPage = () => 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') }))); +// A record page scrolls as one column, its child-table tab inside it. +const recordPage = () => h('div', { id: 'page-column', 'data-testid': 'record-page', className: 'h-screen overflow-y-auto bg-background text-foreground' }, + recordHeader(), tabStrip(), h('div', { className: 'p-6' }, lineGrid())); +// The side record panel over the list page: a dialog with its own scroller. +const sideRecord = () => h(React.Fragment, null, + listPage(), + h('div', { role: 'dialog', 'aria-label': '商机 1', 'data-testid': 'side-record', className: 'fixed inset-y-0 right-0 flex w-[480px] max-w-full flex-col border-l border-border bg-background text-foreground shadow-xl' }, + h('div', { className: 'min-h-0 flex-1 overflow-y-auto' }, recordHeader(), tabStrip(), h('div', { className: 'p-4' }, lineGrid())))); +const face = c.face === 'tab' ? recordPage : c.face === 'drawer' ? sideRecord : listPage; + 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') }))))))), + h(SchemaRendererProvider, { dataSource }, face())))), ); window.__unmount = () => root.render(null); window.__remount(); @@ -391,38 +453,68 @@ for (const viewport of VIEWPORTS) { 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) => { + test('two rows selected: the bar floats at the bottom centre of the list, above the summary row; the page header stays; × clears', 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 styleUntilStable(page); + // objectstack#35678 — one floating bar, drawn by the table itself. + const bar = page.getByTestId('data-table-floating-bar').getByTestId('bulk-actions-bar'); await expect(bar).toBeVisible(); - await expect(bar.getByTestId('list-selection-count')).toHaveText('已选 2 条'); + await expect(page.getByTestId('bulk-actions-bar')).toHaveCount(1); + await expect(bar.getByTestId('bulk-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); + await expect(bar.getByTestId('bulk-action-mass_tag')).toBeVisible(); + // Three actions: three buttons, nothing behind More. + await expect(bar.getByTestId('selection-actions-more')).toHaveCount(0); + // The top of the page does not change. + await expect(page.getByTestId('page-header')).toBeVisible(); + const geometry = await page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]')!.getBoundingClientRect(); + const bar = document.querySelector('[data-testid="bulk-actions-bar"]')!.getBoundingClientRect(); + const foot = document.querySelector('[data-table-scroll-box] tfoot')?.getBoundingClientRect() ?? null; + return { boxCentre: box.left + box.width / 2, barCentre: bar.left + bar.width / 2, barBottom: bar.bottom, boxBottom: box.bottom, footTop: foot?.top ?? null }; }); - expect(bottomHit).toBe(true); + // Centred on the list area, not the window. + expect(Math.abs(geometry.barCentre - geometry.boxCentre)).toBeLessThanOrEqual(1); + expect(geometry.barBottom).toBeLessThanOrEqual(geometry.boxBottom); + // Above the footer calc row when the list draws one. + if (geometry.footTop !== null) expect(geometry.barBottom).toBeLessThanOrEqual(geometry.footTop); 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(); + // At the end of the list the last row clears the bar. + for (let i = 0; i < 4; i++) { + await page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]')!; + box.scrollTop = box.scrollHeight; + }); + await page.waitForTimeout(300); + } + await expect.poll(() => loadedRows(page)).toBe(ROW_COUNT); + await page.evaluate(() => { + const box = document.querySelector('[data-table-scroll-box]')!; + box.scrollTop = box.scrollHeight; + }); + const clearance = await page.evaluate(() => { + const rows = document.querySelectorAll('tbody tr:has([data-slot="row-leading-cell"])'); + const last = rows[rows.length - 1].getBoundingClientRect(); + const bar = document.querySelector('[data-testid="bulk-actions-bar"]')!.getBoundingClientRect(); + return { lastBottom: last.bottom, barTop: bar.top }; + }); + expect(clearance.lastBottom).toBeLessThanOrEqual(clearance.barTop); + await shoot(page, testInfo, `selected-2-end-${viewport.width}.png`); + await bar.getByTestId('bulk-selection-clear').click(); + await expect(page.getByTestId('bulk-actions-bar')).toHaveCount(0); + await expect(page.getByTestId('data-table-floating-bar-room')).toHaveCount(0); + await expect(rowCheckbox(page, '商机 1')).not.toBeChecked(); }); - test('one row and two rows expose different actions', async ({ page }) => { + test('one row and two rows expose different actions; Esc clears', 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 styleUntilStable(page); + const bar = page.getByTestId('bulk-actions-bar'); + await expect(bar.getByTestId('bulk-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); @@ -431,6 +523,8 @@ for (const viewport of VIEWPORTS) { 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(); + await page.keyboard.press('Escape'); + await expect(page.getByTestId('bulk-actions-bar')).toHaveCount(0); }); test('right-click on a row: its actions, 「删除」 last after a separator', async ({ page }) => { @@ -460,11 +554,11 @@ for (const viewport of VIEWPORTS) { await expect.poll(() => loadedRows(page)).toBe(100); await page.locator('thead').getByRole('checkbox').click(); await styleUntilStable(page); - const bar = page.getByTestId('list-selection-page-bar'); - await expect(bar.getByTestId('list-selection-count')).toHaveText('已选 100 条'); - await expect(bar.getByTestId('list-selection-select-all')).toHaveText('选择全部 120 条'); - await bar.getByTestId('list-selection-select-all').click(); - await expect(bar.getByTestId('list-selection-count')).toContainText('120'); + const bar = page.getByTestId('bulk-actions-bar'); + await expect(bar.getByTestId('bulk-selection-count')).toHaveText('已选 100 条'); + await expect(bar.getByTestId('bulk-select-all-matching')).toHaveText('选择全部 120 条'); + await bar.getByTestId('bulk-select-all-matching').click(); + await expect(bar.getByTestId('bulk-selection-count')).toContainText('120'); }); test('opening row 60 and coming back lands near row 60', async ({ page }) => { @@ -519,3 +613,119 @@ test.describe('visual acceptance at 1280×800, zh-CN (objectstack#35554)', () => }); } }); + +/** + * objectstack#35678 — one floating selection bar on every face a grid has: the + * list page, a record page's child-table tab, the side record panel; light and + * dark; and a 375px window, where it stays on one line inside the window. + */ +async function barBox(page: Page) { + return page.evaluate(() => { + const bar = document.querySelector('[data-testid="bulk-actions-bar"]')!; + const r = bar.getBoundingClientRect(); + const cs = getComputedStyle(bar); + return { + top: r.top, bottom: r.bottom, left: r.left, right: r.right, height: r.height, + centre: r.left + r.width / 2, + overflows: bar.scrollWidth > bar.clientWidth, + border: cs.borderTopColor, background: cs.backgroundColor, + page: getComputedStyle(document.body).backgroundColor, + viewportWidth: window.innerWidth, viewportHeight: window.innerHeight, + }; + }); +} + +test.describe('the selection bar on every face (objectstack#35678)', () => { + 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}: the list page`, async ({ page }, testInfo) => { + await mount(page, VIEWPORTS[0], { theme }); + await rowCheckbox(page, '商机 1').click(); + await rowCheckbox(page, '商机 2').click(); + await styleUntilStable(page); + const bar = await barBox(page); + expect(bar.border).not.toBe(bar.background); + await shoot(page, testInfo, `bar-list-${theme}.png`); + }); + + test(`${theme}: a record page's child-table tab`, async ({ page }, testInfo) => { + await mount(page, VIEWPORTS[0], { theme, face: 'tab' }); + await page.getByText('产品 1', { exact: true }).waitFor(); + await rowCheckbox(page, '产品 1').click(); + await rowCheckbox(page, '产品 2').click(); + await styleUntilStable(page); + const grid = page.getByTestId('line-grid'); + await expect(grid.getByTestId('bulk-actions-bar')).toBeVisible(); + await expect(grid.getByTestId('bulk-selection-count')).toHaveText('已选 2 条'); + // Outside the list page the rows keep their own menu: two bulk actions. + await expect(grid.getByTestId('bulk-action-line_discount')).toBeVisible(); + await expect(grid.getByTestId('bulk-action-line_reprice')).toBeVisible(); + const gridBox = (await grid.boundingBox())!; + const bar = await barBox(page); + // The record page scrolls as one column: the bar holds to the bottom + // of the window while the tab's table runs past it, centred on the table. + expect(bar.bottom).toBeLessThanOrEqual(bar.viewportHeight); + expect(Math.abs(bar.centre - (gridBox.x + gridBox.width / 2))).toBeLessThanOrEqual(1); + expect(bar.border).not.toBe(bar.background); + await shoot(page, testInfo, `bar-tab-${theme}.png`); + await page.getByTestId('record-page').evaluate((el) => { el.scrollTop = el.scrollHeight; }); + const clearance = await page.evaluate(() => { + const rows = document.querySelectorAll('[data-testid="line-grid"] tbody tr:has([data-slot="row-leading-cell"])'); + const last = rows[rows.length - 1].getBoundingClientRect(); + const bar = document.querySelector('[data-testid="bulk-actions-bar"]')!.getBoundingClientRect(); + return { lastBottom: last.bottom, barTop: bar.top }; + }); + expect(clearance.lastBottom).toBeLessThanOrEqual(clearance.barTop); + await shoot(page, testInfo, `bar-tab-end-${theme}.png`); + }); + + test(`${theme}: the side record`, async ({ page }, testInfo) => { + await mount(page, VIEWPORTS[0], { theme, face: 'drawer' }); + const panel = page.getByTestId('side-record'); + await panel.getByText('产品 1', { exact: true }).waitFor(); + await rowCheckbox(page, '产品 1').click(); + await rowCheckbox(page, '产品 2').click(); + await styleUntilStable(page); + await expect(panel.getByTestId('bulk-actions-bar')).toBeVisible(); + await expect(page.getByTestId('bulk-actions-bar')).toHaveCount(1); + const panelBox = (await panel.getByTestId('line-grid').boundingBox())!; + const bar = await barBox(page); + expect(bar.left).toBeGreaterThanOrEqual(panelBox.x); + expect(bar.right).toBeLessThanOrEqual(panelBox.x + panelBox.width); + expect(bar.bottom).toBeLessThanOrEqual(bar.viewportHeight); + expect(bar.border).not.toBe(bar.background); + await shoot(page, testInfo, `bar-side-record-${theme}.png`); + // Esc inside the panel that holds the bar still clears it. + await page.keyboard.press('Escape'); + await expect(page.getByTestId('bulk-actions-bar')).toHaveCount(0); + }); + } + + for (const face of ['list', 'drawer'] as const) { + test(`375px, ${face === 'list' ? 'the list page' : 'the side record'}: one line, inside the window`, async ({ page }, testInfo) => { + await mount(page, VIEWPORTS[0], { face }); + const scope = face === 'list' ? page.locator('body') : page.getByTestId('side-record'); + const [first, second] = face === 'list' ? ['商机 1', '商机 2'] : ['产品 1', '产品 2']; + await scope.getByText(first, { exact: true }).waitFor(); + await rowCheckbox(page, first).click(); + await rowCheckbox(page, second).click(); + // The selection outlives the move to a phone-width window. + await page.setViewportSize({ width: 375, height: 812 }); + await styleUntilStable(page); + await expect(page.getByTestId('bulk-actions-bar')).toBeVisible(); + await expect(page.getByTestId('bulk-selection-count')).toHaveText('已选 2 条'); + const bar = await barBox(page); + expect(bar.overflows).toBe(false); + expect(Math.round(bar.height)).toBe(44); + expect(bar.left).toBeGreaterThanOrEqual(0); + expect(bar.right).toBeLessThanOrEqual(375); + expect(bar.bottom).toBeLessThanOrEqual(812); + await shoot(page, testInfo, `bar-375-${face}.png`); + }); + } +}); 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 68255245c3b..fb9125ba8d5 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 @@ -196,12 +196,12 @@ async function rowBoxes(): Promise { } /** - * 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 + * objectstack#35678 — the selection's actions on the list page: the floating + * selection bar, its exposed buttons and the ones behind its More. 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 bar = await screen.findByTestId('bulk-actions-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) { @@ -230,7 +230,7 @@ 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('list-selection-bar')).toBeNull(); + expect(screen.queryByTestId('bulk-actions-bar')).toBeNull(); // Two rows: the selection carries the action; the header still lacks it. await tickRows(2); @@ -239,9 +239,9 @@ describe('objectui#12462 — a bulk-wired, record-scoped list_toolbar action lea expect(addToCampaignIn(header)).toBeNull(); expect(within(header).getByRole('button', { name: /Refresh Scores/ })).toBeInTheDocument(); - // 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 }); + // × clears the selection and the bar goes. + await act(async () => { fireEvent.click(within(bar).getByTestId('bulk-selection-clear')); }); + await waitFor(() => expect(screen.queryByTestId('bulk-actions-bar')).toBeNull(), { timeout: 5000 }); }); it('the view wires it in a `bulkActionDefs` entry: the header lacks it, the bar carries it', async () => { diff --git a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx index f7ced1166ca..3aef9c9bdd2 100644 --- a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx +++ b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx @@ -35,7 +35,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'; +import { useListPageScope } from '@object-ui/plugin-grid'; /** * objectstack#35446 — the list header's width under which it takes @@ -167,39 +167,18 @@ export function ObjectViewPageHeader(props: ObjectViewPageBarProps) { const { objectDef, objectPluralLabel, foldedHeaderActions } = props; const actionProps = props; 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); + // objectstack#35554 — this page column is a list page's scope + // (`useListPageScope`, `@object-ui/plugin-grid`): the list in it draws no + // row-end controls. A selection changes nothing up here: the list floats + // its own selection bar at its bottom (objectstack#35678). const [pageColumn, setPageColumn] = useState(null); const headerRootRef = useCallback((el: HTMLDivElement | null) => { setPageColumn(el?.parentElement ?? null); }, []); - const pageBar = useListPageBarHost(selectionSlot, pageColumn); + useListPageScope(pageColumn); 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} - - -
-
-
setHosted(false); }, [setHosted]); - const [selectionSlot, setSelectionSlot] = useState(null); const [pageColumn, setPageColumn] = useState(null); const rootRef = useCallback((el: HTMLDivElement | null) => { setPageColumn(el?.closest(`[${OBJECT_VIEW_PAGE_COLUMN_ATTR}]`) ?? null); }, []); - const pageBar = useListPageBarHost(selectionSlot, pageColumn); + useListPageScope(pageColumn); return (
- {/* Always mounted, so the slot is there the moment a row is ticked. */} -
- {/* Hidden, not unmounted, while rows are selected: the search keeps - its term and the header acts keep following the selection. */} -
+
{tools} diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index cfc79a5366f..bfc01957ca2 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -1511,6 +1511,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { disableInnerScroll = false, rowGroups, summaryRow, + floatingBar, isRowEditable, // Read ONLY to diagnose it. `data-table` does not resolve `bind` and the // objectui#6575 ruling is explicit that it must not start — see @@ -5401,6 +5402,14 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { * height stability instead. */} )} + {/* objectstack#35678 — the room kept after the last row while a + bar floats over the bottom of the scroll box: the last row + scrolls clear of it. Not a row anyone reads. */} + {floatingBar != null && ( + + + + )} {/* The summary row (objectstack#35548): the table's own last row, held at the bottom of the scroll box, each figure in its @@ -5464,6 +5473,24 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { style={{ right: rightShadow.right, bottom: rightShadow.bottom }} /> )} + {/* objectstack#35678 — the host's floating bar (`floatingBar`), centred + at the bottom of the scroll box, above the summary row. A zero-height + box after the scroll box, held at the bottom of the viewport while a + table taller than its page runs past it (`sticky`). */} + {floatingBar != null && ( +
+
+ {floatingBar} +
+
+ )}
{/* Pagination — hidden when only one page (no controls would be actionable) */} diff --git a/ui/packages/plugin-grid/README.md b/ui/packages/plugin-grid/README.md index 51eba2388b6..fa5642489f0 100644 --- a/ui/packages/plugin-grid/README.md +++ b/ui/packages/plugin-grid/README.md @@ -591,6 +591,15 @@ const schema: ObjectGridBlockNode = { deprecated legacy alias, read only when `selection` is absent. Declaring bulk actions auto-enables multi-select, so the two keys agree by construction. +Selected rows get one bar floating at the bottom centre of the grid +(`BulkActionBar`, objectstack#35678): the count and ×, up to three labelled +actions and the rest under More (Delete last), and "Select all N" when every +loaded row is selected and more match. × or Esc clears the selection. The bar +floats above the summary row, and the grid keeps room after its last row so +that row scrolls clear of it. A host that draws the object list page registers +its page column with `useListPageScope(element)`: there rows draw no actions of their +own, and one selected record offers that record's actions in the bar. + To react to a selection in React, pass the `onRowSelect` **component prop** — see [Row callbacks are component props](#row-callbacks-are-component-props). diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 7bd85d57cfa..337a3c21c63 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -22,7 +22,6 @@ */ 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, useOwnWrites, createOwnWrites, type AnswerWarningClaim, type RecordSaveFeedback } from '@object-ui/react'; @@ -92,7 +91,7 @@ import { resolveBulkActions, resolvePromotedBulkParams } from './resolveBulkActi import { useUndeclaredActionNamesWarning } from './undeclaredActionNames'; import { partitionBulkRows } from './bulkEligibility'; import { RowActionMenu, formatActionLabel } from './components/RowActionMenu'; -import { BulkActionBar } from './components/BulkActionBar'; +import { BulkActionBar, FloatingSelectionBarAnchor } from './components/SelectionBar'; import { RowContextMenuItems, SelectionContextMenuItems } from './components/RowContextMenu'; import { BulkActionDialog } from './components/BulkActionDialog'; import type { BulkResult } from './hooks/useBulkExecutor'; @@ -126,8 +125,7 @@ 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 { useIsListPageGrid } from './listPageScope'; import { useInfiniteRowLoad } from './objectGridInfiniteLoad'; export type { RetiredListColumnKey, ObjectGridColumnHolds, ObjectGridColumnDraft, ObjectGridColumn } from './objectGridColumns'; export type { ObjectGridColumnState, ObjectGridFooterSummary, ObjectGridExternalPaginationProps, ObjectGridRowGroup } from './objectGridProps'; @@ -942,17 +940,16 @@ 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. + // objectstack#35554 — a grid inside a list page's page column (`./listPageScope`) + // draws no row-end control; any other host (a related list, a page block, the + // record drawer) keeps it. Every grid draws the same selection bar + // (objectstack#35678). const [gridRoot, setGridRoot] = useState(null); const setRootRef = useCallback((el: HTMLDivElement | null) => { setGridRoot(el); (pullRef as React.MutableRefObject).current = el; }, [pullRef]); - const pageBarSlot = useListPageBarSlot(gridRoot); + const listPageGrid = useIsListPageGrid(gridRoot); // `passedData` — data handed down directly (from ListView) — is destructured // from props above. @@ -1717,10 +1714,6 @@ export const ObjectGrid: React.FC = ({ onResidentSummaryRowChange?.(residentRowDrawn); }, [onResidentSummaryRowChange, residentRowDrawn]); - // 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 @@ -2067,7 +2060,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, + drawRowControls: !listPageGrid, }); // Density-driven cell padding/font (applied to every column so it actually reaches ). @@ -2298,7 +2291,7 @@ export const ObjectGrid: React.FC = ({ // rather than merely currently-wired-right: a host that forgets `findParams` // loses the affordance, it does not silently get the whole object. // - // ONE condition, consumed by both `BulkActionBar` sites below. Do NOT re-spell + // ONE condition, consumed by the selection bar below. Do NOT re-spell // it at a consumption site — a second copy is how one of them gets missed // (objectui#4138, #4464). const canOfferSelectAllMatching = !singleSelection && bulkFanoutParams !== null; @@ -2349,7 +2342,7 @@ export const ObjectGrid: React.FC = ({ // below already guards. // // [#4140] So this is the ONE reset — dispatch, delete, dialog-close AND the - // bulk bar's own `onClearSelection`. Both `BulkActionBar` sites previously + // selection bar's own `onClearSelection`. The bulk bar sites previously // hand-wrote `setSelectedRows([]); setSelectAllMatching(false);`, which is // this function minus the key bump: Clear emptied the toolbar and left every // checkbox ticked. Never re-implement the reset inline — call this. @@ -3267,6 +3260,34 @@ export const ObjectGrid: React.FC = ({ ); }; + // objectstack#35678 — the selection bar: one bar for every face of every + // grid, floated at the bottom centre of the face's scroller. The flat table + // floats it itself (`floatingBar`), above its summary row and with room after + // its last row; every other face floats it in `FloatingSelectionBarAnchor`. + // On the list page, where rows draw no actions of their own (#35554), one + // selected record offers that record's actions; elsewhere the row keeps its + // own menu and the bar offers the bulk actions at any count. + const selecting = selectedRows.length > 0; + const selectionBar = selecting ? ( + setSelectAllMatching(true) : undefined} + /> + ) : null; + // The room a face that is not the table keeps at its scroller's end while + // the bar floats there, so its last row scrolls clear of the bar. + const selectionBarClearance = selecting ? 'pb-16' : undefined; + // objectstack#35548 — the column summaries as the table's own last row, each // under its column, led by the count of the records they summarise. A host // that draws them itself (`onColumnSummaryChange`) gets no row here. @@ -3330,6 +3351,7 @@ export const ObjectGrid: React.FC = ({ columns: tableColumns, data: patchedRows(data), summaryRow, + floatingBar: selectionBar ?? undefined, // objectstack#35554 — a host that loads window by window draws no pager. pagination: paginationEnabled && !onLoadMore, pageSize: manualPaginationOn ? manualPageSize : pageSize, @@ -3353,8 +3375,8 @@ export const ObjectGrid: React.FC = ({ search: manualSearchOn ? manualSearch : undefined, onSearchChange: manualSearchOn ? manualOnSearchChange : undefined, selectable: selectionMode, - // ObjectGrid surfaces the selection via its own bottom BulkActionBar - // (count + Clear + bulk actions). Suppress the data-table's built-in + // ObjectGrid surfaces the selection via its own selection bar + // (count + Clear + actions). Suppress the data-table's built-in // "N selected" toolbar so it doesn't render a duplicate, orphaned row // above the table when search/export are handled by the outer toolbar. showSelectionCount: false, @@ -3611,6 +3633,8 @@ export const ObjectGrid: React.FC = ({ rowGroups, // A grouped grid draws no summary row (its summaries are withheld). summaryRow: undefined, + // The grouped scroller floats the selection bar (see grouped `gridContent`). + floatingBar: undefined, // Pages are the grid's: whole groups (`groupedPager`), and on a // server-grouped grid each open group's own rows (its band footer). pagination: false, @@ -4088,7 +4112,7 @@ export const ObjectGrid: React.FC = ({ return ( <>
@@ -4099,6 +4123,7 @@ export const ObjectGrid: React.FC = ({
{cardPager}
+ {selectionBar && {selectionBar}} {navigation.isOverlay && ( = ({
) : null; - // Every branch fills the remaining height (flex-1 + min-h-0) so the - // BulkActionBar rendered *after* gridContent stays inside the flex column - // and remains visible; otherwise an h-full table pushes the bar past the - // bottom of an overflow-hidden ancestor and clips it. + // Every branch fills the remaining height (flex-1 + min-h-0), so its + // scroller is bounded and the selection bar floated at its end stays in view + // (objectstack#35678). // // objectstack#26896 — on a phone (`useCardView`, the plain list's card // breakpoint) a grouped list draws the same bands in the same order, each @@ -4464,7 +4488,7 @@ export const ObjectGrid: React.FC = ({ const gridContent = isGrouped && cardFace ? (
@@ -4481,6 +4505,7 @@ export const ObjectGrid: React.FC = ({ )); })()}
+ {selectionBar && {selectionBar}} {groupedPager}
) : isGrouped ? ( @@ -4493,13 +4518,14 @@ export const ObjectGrid: React.FC = ({ 0 ? 'pinned' : 'edge'} outerClassName="flex flex-col flex-1 min-h-0" - className="flex-1 min-h-0 overflow-auto [-webkit-overflow-scrolling:touch]" + className={cn('flex-1 min-h-0 overflow-auto [-webkit-overflow-scrolling:touch]', selectionBarClearance)} data-testid="grouped-grid-scroller" >
+ {selectionBar && {selectionBar}} {groupedPager}
) : ( @@ -4722,42 +4748,6 @@ export const ObjectGrid: React.FC = ({ {isGrouped && onRowGroupsChange && ( )} - {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 && ( { + it('once selected, the chip counts CAP and its title says only the first CAP will be processed', async () => { renderBar('en', total, true); - const banner = await screen.findByTestId('bulk-cross-page-banner'); - expect(banner).toHaveTextContent(fill(en.grid.bulkAllMatchingSelectedCapped, { cap: CAP, total })); - expect(banner).toHaveTextContent(String(CAP)); - expect(banner).not.toHaveTextContent(fill(en.grid.bulkAllMatchingSelected, { count: total })); - const bar = screen.getByTestId('bulk-actions-bar'); - expect(bar).toHaveTextContent(fill(en.grid.bulkSelectedAllMatchesCapped, { cap: CAP, total })); - expect(bar).not.toHaveTextContent(fill(en.grid.bulkSelectedAllMatches, { count: total })); + const chip = await screen.findByTestId('bulk-selection-count'); + expect(chip).toHaveAttribute('title', fill(en.grid.bulkAllMatchingSelectedCapped, { cap: CAP, total })); + expect(chip).toHaveTextContent(fill(en.grid.bulkSelectedAllMatchesCapped, { cap: CAP, total })); + expect(chip).not.toHaveTextContent(fill(en.grid.bulkSelectedAllMatches, { count: total })); }); - it('under zh, the banner reads the zh pack', async () => { + it('under zh, the chip reads the zh pack', async () => { expect(zh.grid.bulkAllMatchingSelectedCapped).not.toBe(en.grid.bulkAllMatchingSelectedCapped); renderBar('zh', total, true); - const banner = await screen.findByTestId('bulk-cross-page-banner'); - expect(banner).toHaveTextContent(fill(zh.grid.bulkAllMatchingSelectedCapped, { cap: CAP, total })); + const chip = await screen.findByTestId('bulk-selection-count'); + expect(chip).toHaveAttribute('title', fill(zh.grid.bulkAllMatchingSelectedCapped, { cap: CAP, total })); + expect(chip).toHaveTextContent(fill(zh.grid.bulkSelectedAllMatchesCapped, { cap: CAP, total })); }); it("the selection's context menu counts CAP of the total", async () => { @@ -106,16 +106,16 @@ describe('the bulk bar names the select-all-matching cap (objectstack#28552)', ( ['exactly at the cap', CAP], ['under the cap', CAP - 3800], ])('%s', (_name, total) => { - it("the select-all button reads today's text", async () => { + it('the select-all button offers all of them', async () => { renderBar('en', total, false); const button = await screen.findByTestId('bulk-select-all-matching'); - expect(button).toHaveTextContent(fill(en.grid.bulkSelectAllMatching, { count: total })); + expect(button).toHaveTextContent(fill(en.grid.selectAllTotal, { total })); }); - it("once selected, the banner and the chip read today's text", async () => { + it('once selected, the chip counts every match and its title says so', async () => { renderBar('en', total, true); - const banner = await screen.findByTestId('bulk-cross-page-banner'); - expect(banner).toHaveTextContent(fill(en.grid.bulkAllMatchingSelected, { count: total })); + const chip = await screen.findByTestId('bulk-selection-count'); + expect(chip).toHaveAttribute('title', fill(en.grid.bulkAllMatchingSelected, { count: total })); expect(within(screen.getByTestId('bulk-actions-bar')).getByText(fill(en.grid.bulkSelectedAllMatches, { count: total }))).toBeInTheDocument(); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/BulkActionBar.test.tsx b/ui/packages/plugin-grid/src/__tests__/BulkActionBar.test.tsx index 2987746333e..0275f5b8f0e 100644 --- a/ui/packages/plugin-grid/src/__tests__/BulkActionBar.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/BulkActionBar.test.tsx @@ -6,63 +6,191 @@ * LICENSE file in the root directory of this source tree. */ -import { render, screen, fireEvent } from '@testing-library/react'; -import { describe, it, expect, vi } from 'vitest'; +/** + * objectstack#35678 — the selection bar: 「已选 N 条」 and ×, up to three + * labelled actions (all of them when the selection offers no more than three, + * Delete included), the rest behind More; 「选择全部 N 条」 when every loaded + * row is selected and more match; × and Esc clear the selection. + */ +import '@testing-library/jest-dom/vitest'; +import { render, screen, fireEvent, within, cleanup } from '@testing-library/react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; import React from 'react'; import { I18nProvider } from '@object-ui/react'; -import { BulkActionBar } from '../components/BulkActionBar'; +import type { BulkActionDef } from '@object-ui/types'; +import { + BulkActionBar, + SELECTION_EXPOSED_ACTIONS, + planExposedEntries, + singleRecordEntries, +} from '../components/SelectionBar'; +import type { RowActionMenuPlan } from '../components/RowActionMenu'; + +afterEach(cleanup); const rows = (n: number) => Array.from({ length: n }, (_, i) => ({ id: String(i + 1) })); +const def = (name: string, extra: Partial = {}): BulkActionDef => ({ name, label: name, ...extra }) as BulkActionDef; -// BulkActionBar surfaces its strings via useObjectTranslation, so tests wrap in -// an English i18n provider — otherwise `{{count}}` interpolation never runs and +// The bar surfaces its strings via useObjectTranslation, so tests wrap in an +// English i18n provider — otherwise `{{count}}` interpolation never runs and // the raw templates leak into the DOM. const renderBar = (ui: React.ReactElement) => render( - + {ui} , ); +const exposedNames = () => + within(screen.getByTestId('bulk-actions-bar')) + .queryAllByRole('button') + .map((b) => b.getAttribute('data-testid')) + .filter((id) => id !== 'bulk-selection-clear' && id !== 'selection-actions-more'); + +describe('planExposedEntries', () => { + const entries = (...keys: string[]) => keys.map((key) => ({ key, destructive: key.startsWith('delete') })); + const notDestructive = (e: { destructive: boolean }) => !e.destructive; + + it('the budget is three', () => { + expect(SELECTION_EXPOSED_ACTIONS).toBe(3); + }); + + it('exposes every entry, Delete included, when there are no more than the budget', () => { + const all = entries('a', 'b', 'delete'); + expect(planExposedEntries(all, notDestructive, 3)).toEqual({ exposed: all, rest: [] }); + const lone = entries('delete'); + expect(planExposedEntries(lone, notDestructive, 3)).toEqual({ exposed: lone, rest: [] }); + }); + + it('over the budget, exposes the first entries the predicate admits and leaves the rest in menu order', () => { + const all = entries('a', 'b', 'c', 'd', 'delete'); + const { exposed, rest } = planExposedEntries(all, notDestructive, 3); + expect(exposed.map((e) => e.key)).toEqual(['a', 'b', 'c']); + expect(rest.map((e) => e.key)).toEqual(['d', 'delete']); + }); + + it('a narrower fit gives the trailing exposed entries back to the menu, in order', () => { + const all = entries('a', 'b', 'c', 'delete'); + const { exposed, rest } = planExposedEntries(all, notDestructive, 3, 1); + expect(exposed.map((e) => e.key)).toEqual(['a']); + expect(rest.map((e) => e.key)).toEqual(['b', 'c', 'delete']); + expect(planExposedEntries(all, notDestructive, 3, 0).exposed).toEqual([]); + }); +}); + +describe('singleRecordEntries', () => { + it("lists one record's actions in its row menu's order, Delete last", () => { + const plan: RowActionMenuPlan = { + inline: [{ name: 'approve' }], + custom: [{ name: 'share' }], + edit: true, + remove: true, + legacy: ['archive'], + menuCount: 4, + }; + expect(singleRecordEntries(plan).map((e) => e.key)).toEqual(['def:approve', 'def:share', 'edit', 'legacy:archive', 'delete']); + }); +}); + describe('BulkActionBar', () => { it('renders nothing when selection empty', () => { - const { container } = renderBar( - , - ); - // I18nProvider adds no DOM of its own, so an empty bar means no bar. - expect(container.querySelector('[data-testid="bulk-actions-bar"]')).toBeNull(); + renderBar(); + expect(screen.queryByTestId('bulk-actions-bar')).toBeNull(); }); - it('shows count + Clear even with no bulk actions configured', () => { - // The bar is the single canonical selection indicator: with no actions it - // still surfaces "N selected / Clear" so the embedded table needn't draw - // its own (unstyled) selection toolbar. + it('shows the count and × even with no actions, and no More', () => { renderBar(); - expect(screen.getByTestId('bulk-actions-bar')).toBeTruthy(); - expect(screen.getByText(/2 selected/)).toBeTruthy(); - expect(screen.getByText('Clear')).toBeTruthy(); - // …but no action buttons. - expect(screen.queryByTestId('bulk-action-delete')).toBeNull(); + expect(screen.getByTestId('bulk-selection-count')).toHaveTextContent('2 selected'); + expect(screen.getByTestId('bulk-selection-clear')).toHaveAccessibleName('Clear'); + expect(screen.queryByTestId('selection-actions-more')).toBeNull(); + expect(exposedNames()).toEqual([]); + }); + + it('a selection whose only action is Delete shows Delete as a button, not behind More', () => { + renderBar(); + expect(screen.getByTestId('bulk-action-delete')).toHaveTextContent('Delete'); + expect(screen.queryByTestId('selection-actions-more')).toBeNull(); }); - it('shows N selected for the current-page case', () => { - renderBar(); - expect(screen.getByText(/3 selected/)).toBeTruthy(); + it('three actions are three buttons; a fourth sends Delete and the overflow behind More', () => { + const { unmount } = renderBar( + , + ); + expect(exposedNames()).toEqual(['bulk-action-assign', 'bulk-action-tag', 'bulk-action-delete']); + expect(screen.queryByTestId('selection-actions-more')).toBeNull(); + unmount(); + + renderBar( + , + ); + expect(exposedNames()).toEqual(['bulk-action-assign', 'bulk-action-tag', 'bulk-action-export']); + expect(screen.getByTestId('selection-actions-more')).toHaveTextContent('More'); + }); + + it('More opens the actions not exposed, Delete last', async () => { + const onAction = vi.fn(); + renderBar( + , + ); + const more = screen.getByTestId('selection-actions-more'); + fireEvent.pointerDown(more, { button: 0, pointerType: 'mouse' }); + const menu = await screen.findByRole('menu'); + const items = within(menu).getAllByRole('menuitem').map((i) => i.textContent); + expect(items).toEqual(['merge', 'Delete']); + fireEvent.click(within(menu).getByText('Delete')); + expect(onAction).toHaveBeenCalledWith('delete', rows(2)); }); - it('does not show cross-page banner when total ≤ page', () => { + it("one selected record offers that record's own actions, not the bulk ones", () => { + const row = { id: '7' }; + const onEdit = vi.fn(); renderBar( {}, rowActionDefs: [{ name: 'share', label: 'Share' }] }} />, ); - expect(screen.queryByTestId('bulk-cross-page-banner')).toBeNull(); + expect(screen.getByTestId('bulk-selection-count')).toHaveTextContent('1 selected'); + expect(screen.queryByTestId('bulk-action-assign')).toBeNull(); + // Share, Edit and Delete: three, so all three are buttons. + expect(exposedNames()).toEqual(['row-action-inline-share', 'selection-action-edit', 'selection-action-delete']); + fireEvent.click(screen.getByTestId('selection-action-edit')); + expect(onEdit).toHaveBeenCalledWith(row); }); - it('offers "Select all N matching" when full page is selected and more exist', () => { + it("over three of one record's actions, Delete stays behind More", () => { + const row = { id: '7' }; + renderBar( + {}, + canDelete: true, + onDelete: () => {}, + rowActionDefs: [{ name: 'share', label: 'Share' }, { name: 'clone', label: 'Clone' }], + }} + />, + ); + expect(exposedNames()).toEqual(['row-action-inline-share', 'row-action-inline-clone', 'selection-action-edit']); + expect(screen.queryByTestId('selection-action-delete')).toBeNull(); + expect(screen.getByTestId('selection-actions-more')).toBeInTheDocument(); + }); + + it('offers 「Select all N」 when every loaded row is selected and more match', () => { const onSelectAll = vi.fn(); renderBar( { onSelectAllMatching={onSelectAll} />, ); - const banner = screen.getByTestId('bulk-cross-page-banner'); - expect(banner.textContent).toMatch(/All 10 on this page are selected/); const cta = screen.getByTestId('bulk-select-all-matching'); - expect(cta.textContent).toMatch(/Select all 137 matching/); + expect(cta).toHaveTextContent('Select all 137'); fireEvent.click(cta); expect(onSelectAll).toHaveBeenCalledTimes(1); }); - it('shows "all matches selected" summary once user opts in', () => { + it('does not offer it when nothing more matches', () => { + renderBar( {}} />); + expect(screen.queryByTestId('bulk-select-all-matching')).toBeNull(); + }); + + it('counts every match once the user opts in', () => { renderBar( - , + , ); - expect(screen.getByText(/All 137 matching records are selected/)).toBeTruthy(); - expect(screen.getByText(/137 selected \(all matches\)/)).toBeTruthy(); + expect(screen.getByTestId('bulk-selection-count')).toHaveTextContent('137 selected (all matches)'); expect(screen.queryByTestId('bulk-select-all-matching')).toBeNull(); }); - it('calls onClearSelection and clears cross-page when Clear is clicked', () => { + it('× clears the selection', () => { + const onClear = vi.fn(); + renderBar(); + fireEvent.click(screen.getByTestId('bulk-selection-clear')); + expect(onClear).toHaveBeenCalledTimes(1); + }); + + it('Esc clears the selection, unless it belongs to a field or another open layer', () => { const onClear = vi.fn(); renderBar( - , + <> + + + , + ); + fireEvent.keyDown(screen.getByTestId('field'), { key: 'Escape' }); + expect(onClear).not.toHaveBeenCalled(); + + const dialog = document.createElement('div'); + dialog.setAttribute('role', 'dialog'); + document.body.appendChild(dialog); + fireEvent.keyDown(document.body, { key: 'Escape' }); + expect(onClear).not.toHaveBeenCalled(); + dialog.remove(); + + fireEvent.keyDown(document.body, { key: 'Escape' }); + expect(onClear).toHaveBeenCalledTimes(1); + }); + + it('Esc inside the dialog that holds the bar still clears it (a grid in the record drawer)', () => { + const onClear = vi.fn(); + renderBar( +
+ +
, ); - fireEvent.click(screen.getByText('Clear')); + fireEvent.keyDown(document.body, { key: 'Escape' }); expect(onClear).toHaveBeenCalledTimes(1); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/bulk-action-visible.test.tsx b/ui/packages/plugin-grid/src/__tests__/bulk-action-visible.test.tsx index 06bdcdcc4a6..8767bec3306 100644 --- a/ui/packages/plugin-grid/src/__tests__/bulk-action-visible.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/bulk-action-visible.test.tsx @@ -16,7 +16,7 @@ import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; import { PredicateScopeProvider } from '@object-ui/react'; -import { BulkActionBar } from '../components/BulkActionBar'; +import { BulkActionBar } from '../components/SelectionBar'; function renderBar(actionDefs: any[], scope: Record = {}) { return render( diff --git a/ui/packages/plugin-grid/src/__tests__/bulkActionCapabilityGate.test.tsx b/ui/packages/plugin-grid/src/__tests__/bulkActionCapabilityGate.test.tsx index 52b477adad3..c92ffab08c5 100644 --- a/ui/packages/plugin-grid/src/__tests__/bulkActionCapabilityGate.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/bulkActionCapabilityGate.test.tsx @@ -31,7 +31,7 @@ import '@testing-library/jest-dom'; import React from 'react'; import { ActionProvider, PredicateScopeProvider } from '@object-ui/react'; import type { BulkActionDef } from '@object-ui/types'; -import { BulkActionBar } from '../components/BulkActionBar'; +import { BulkActionBar } from '../components/SelectionBar'; const GATED: BulkActionDef = { name: 'push_down', diff --git a/ui/packages/plugin-grid/src/__tests__/bulkActionRefresh.test.tsx b/ui/packages/plugin-grid/src/__tests__/bulkActionRefresh.test.tsx index fd64883f3d9..f216016211f 100644 --- a/ui/packages/plugin-grid/src/__tests__/bulkActionRefresh.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/bulkActionRefresh.test.tsx @@ -463,7 +463,7 @@ describe('ObjectGrid — bulk bar Clear resets both selection sources (#4140)', // Escalate to the cross-page selection, then Clear it. // - // The banner's two branches are told apart *structurally*, by whether the + // The bar's two states are told apart *structurally*, by whether the // escalation button is still offered — not by its copy. These grid tests // wrap in `ActionProvider` only, with no `I18nProvider`, so `{{count}}` // interpolation never runs and count-bearing strings reach the DOM as the @@ -477,7 +477,8 @@ describe('ObjectGrid — bulk bar Clear resets both selection sources (#4140)', await waitFor(() => expect(screen.queryByTestId('bulk-select-all-matching')).not.toBeInTheDocument(), ); - expect(screen.getByTestId('bulk-cross-page-banner')).toBeInTheDocument(); + // objectstack#35678 — the count chip carries the all-matching sentence. + expect(screen.getByTestId('bulk-selection-count')).toHaveAttribute('title'); clickClear(); diff --git a/ui/packages/plugin-grid/src/__tests__/bulkFanoutHostParams.test.tsx b/ui/packages/plugin-grid/src/__tests__/bulkFanoutHostParams.test.tsx index 458f9962be4..e685b2285a3 100644 --- a/ui/packages/plugin-grid/src/__tests__/bulkFanoutHostParams.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/bulkFanoutHostParams.test.tsx @@ -244,7 +244,6 @@ describe('#4501 clause 1b — the abstain floor', () => { await selectWholePage(); - expect(screen.queryByTestId('bulk-cross-page-banner')).not.toBeInTheDocument(); expect(screen.queryByTestId('bulk-select-all-matching')).not.toBeInTheDocument(); // The ordinary page selection is untouched — only the escalation is gone. expect(within(screen.getByTestId('bulk-actions-bar')).getByText(/10 selected/)).toBeInTheDocument(); @@ -270,7 +269,6 @@ describe('#4501 clause 1b — the abstain floor', () => { fireEvent.click(rowCheckboxes()[0]); await waitFor(() => expect(screen.getByTestId('bulk-actions-bar')).toBeInTheDocument()); // Params ARE available here; the suppression is the `single` clause alone. - expect(screen.queryByTestId('bulk-cross-page-banner')).not.toBeInTheDocument(); expect(screen.queryByTestId('bulk-select-all-matching')).not.toBeInTheDocument(); }); }); @@ -283,7 +281,7 @@ describe('#4501 clause 2 — the escalation resets when the host\'s query change await selectWholePage(); fireEvent.click(await screen.findByTestId('bulk-select-all-matching')); await waitFor(() => - expect(screen.getByTestId('bulk-cross-page-banner')).toHaveTextContent(/matching records are selected/), + expect(screen.getByTestId('bulk-selection-count')).toHaveAttribute('title', expect.stringMatching(/matching records are selected/)), ); // The user changes the filter in the host's toolbar. @@ -292,9 +290,9 @@ describe('#4501 clause 2 — the escalation resets when the host\'s query change await waitFor(() => expect(screen.getByTestId('bulk-select-all-matching')).toBeInTheDocument(), ); - expect(screen.getByTestId('bulk-cross-page-banner')).toHaveTextContent( - 'All 10 on this page are selected.', - ); + // objectstack#35678 — the bar counts the page again, with no all-matching title. + expect(screen.getByTestId('bulk-selection-count')).toHaveTextContent('10 selected'); + expect(screen.getByTestId('bulk-selection-count')).not.toHaveAttribute('title'); }); it('survives a re-render that hands down an EQUAL query (a plain refetch)', async () => { @@ -304,16 +302,14 @@ describe('#4501 clause 2 — the escalation resets when the host\'s query change await selectWholePage(); fireEvent.click(await screen.findByTestId('bulk-select-all-matching')); await waitFor(() => - expect(screen.getByTestId('bulk-cross-page-banner')).toHaveTextContent(/matching records are selected/), + expect(screen.getByTestId('bulk-selection-count')).toHaveAttribute('title', expect.stringMatching(/matching records are selected/)), ); // A fresh object with identical content — what a host re-render produces. rerender(tree(ds, onBulkDelete, hostProps({ findParams: { ...HOST_PARAMS } }))); - await waitFor(() => expect(screen.getByTestId('bulk-cross-page-banner')).toBeInTheDocument()); - expect(screen.getByTestId('bulk-cross-page-banner')).toHaveTextContent( - /matching records are selected/, - ); + await waitFor(() => expect(screen.getByTestId('bulk-selection-count')).toHaveAttribute('title')); + expect(screen.getByTestId('bulk-selection-count')).toHaveAttribute('title', expect.stringMatching(/matching records are selected/)); expect(screen.queryByTestId('bulk-select-all-matching')).not.toBeInTheDocument(); }); }); @@ -369,9 +365,10 @@ describe('#4501 must-not-change — the internal-loader path', () => { await selectWholePage(); fireEvent.click(await screen.findByTestId('bulk-select-all-matching')); - // objectstack#28552 — the banner names the number the fan-out delivers, - // read from the one constant both sides read. - expect(screen.getByTestId('bulk-cross-page-banner')).toHaveTextContent( + // objectstack#28552 — the count chip's title names the number the fan-out + // delivers, read from the one constant both sides read. + expect(screen.getByTestId('bulk-selection-count')).toHaveAttribute( + 'title', en.grid.bulkAllMatchingSelectedCapped .replace('{{cap}}', String(BULK_SELECT_ALL_MATCHING_CAP)) .replace('{{total}}', String(BIG)), diff --git a/ui/packages/plugin-grid/src/__tests__/listPageScope-35678.test.tsx b/ui/packages/plugin-grid/src/__tests__/listPageScope-35678.test.tsx new file mode 100644 index 00000000000..be90834b6eb --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/listPageScope-35678.test.tsx @@ -0,0 +1,76 @@ +/** + * 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#35678 — the list-page scope is counted per page column. The page + * header and the view bar's trailing end both register the same column, and + * one unmounts as the other mounts; the column stays a list page until its + * LAST registrant goes, whatever order React runs their effects in. + */ +import '@testing-library/jest-dom/vitest'; +import { render, screen, cleanup } from '@testing-library/react'; +import { describe, it, expect, afterEach } from 'vitest'; +import React from 'react'; +import { useListPageScope, useIsListPageGrid } from '../listPageScope'; + +afterEach(cleanup); + +const Registrant: React.FC<{ scope: HTMLElement }> = ({ scope }) => { + useListPageScope(scope); + return null; +}; + +const Probe: React.FC<{ root: HTMLElement }> = ({ root }) => ( + {useIsListPageGrid(root) ? 'list page' : 'elsewhere'} +); + +function column(): { scope: HTMLElement; grid: HTMLElement } { + const scope = document.createElement('div'); + const grid = document.createElement('div'); + scope.appendChild(grid); + document.body.appendChild(scope); + return { scope, grid }; +} + +describe('useListPageScope (objectstack#35678)', () => { + it('two registrants of one column: unmounting one keeps the scope; unmounting both drops it', () => { + const { scope, grid } = column(); + const view = (a: boolean, b: boolean) => ( + <> + {a && } + {b && } + + + ); + const { rerender } = render(view(true, false)); + expect(screen.getByTestId('probe')).toHaveTextContent('list page'); + // The trailing end registers first, then the header goes, in the order + // that dropped the scope while it was a plain set. + rerender(view(true, true)); + rerender(view(false, true)); + expect(screen.getByTestId('probe')).toHaveTextContent('list page'); + rerender(view(false, false)); + expect(screen.getByTestId('probe')).toHaveTextContent('elsewhere'); + scope.remove(); + }); + + it('CONTROL: a grid outside every registered column is not a list page', () => { + const { scope } = column(); + const outside = document.createElement('div'); + document.body.appendChild(outside); + render( + <> + + + , + ); + expect(screen.getByTestId('probe')).toHaveTextContent('elsewhere'); + scope.remove(); + outside.remove(); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/lookupPredicateParity.test.tsx b/ui/packages/plugin-grid/src/__tests__/lookupPredicateParity.test.tsx index 5a8c237dece..72fba0e212c 100644 --- a/ui/packages/plugin-grid/src/__tests__/lookupPredicateParity.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/lookupPredicateParity.test.tsx @@ -27,7 +27,7 @@ import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; import { PredicateScopeProvider } from '@object-ui/react'; -import { BulkActionBar } from '../components/BulkActionBar'; +import { BulkActionBar } from '../components/SelectionBar'; import { RowActionMenu } from '../components/RowActionMenu'; import { partitionBulkRows } from '../bulkEligibility'; diff --git a/ui/packages/plugin-grid/src/__tests__/listPageBarSlot-35554.test.tsx b/ui/packages/plugin-grid/src/__tests__/selectionBar-35678.test.tsx similarity index 55% rename from ui/packages/plugin-grid/src/__tests__/listPageBarSlot-35554.test.tsx rename to ui/packages/plugin-grid/src/__tests__/selectionBar-35678.test.tsx index 729d9a3f5c4..570938f48d7 100644 --- a/ui/packages/plugin-grid/src/__tests__/listPageBarSlot-35554.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/selectionBar-35678.test.tsx @@ -7,14 +7,18 @@ */ /** - * objectstack#35554 — a list page's grid carries no row control and no bulk - * bar: its selection is drawn into the page bar's slot (`./listPageBarSlot`). - * A grid outside any page bar's scope (a related list, a page block) keeps - * its Actions column and its bottom bar. + * objectstack#35678 — every grid draws ONE selection bar, floated at the + * bottom centre of its table: 「已选 N 条」 and ×, up to three labelled + * actions, the rest behind More. Nothing above the list changes. The table + * keeps room after its last row while the bar floats there. * - * The page bar here is a fixture built on the same `useListPageBarHost` the - * Console page header calls; the grid, its table, the selection bar and the - * menus are real. + * objectstack#35554 — a list page's grid (inside a registered list page scope, + * `./listPageScope`) still carries no row-end control; a grid outside any + * scope (a related list, a page block) keeps its Actions column. + * + * The page column here is a fixture built on the same `useListPageScope` the + * Console page bars call; the grid, its table, the selection bar and the menus + * are real. */ import { describe, it, expect, beforeEach } from 'vitest'; import { render, screen, waitFor, fireEvent, within } from '@testing-library/react'; @@ -22,7 +26,7 @@ import '@testing-library/jest-dom'; import React from 'react'; import { ObjectGrid } from '../ObjectGrid'; -import { useListPageBarHost } from '../listPageBarSlot'; +import { useListPageScope } from '../listPageScope'; import { registerAllFields } from '@object-ui/fields'; import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; @@ -74,14 +78,14 @@ const SCHEMA: any = { ], }; -/** The fixture page bar: the slot, and the state the list writes. */ +/** The fixture page bar: it registers its page column as a list page scope. */ const PageBar: React.FC = () => { - const [slot, setSlot] = React.useState(null); const [scope, setScope] = React.useState(null); - const state = useListPageBarHost(slot, scope); + useListPageScope(scope); return ( -
setScope(el?.parentElement ?? null)} data-testid="page-bar" data-selecting={state.selecting ? 'yes' : 'no'}> -
+
setScope(el?.parentElement ?? null)} data-testid="page-bar"> + Accounts +
); }; @@ -108,7 +112,10 @@ const tick = (name: string) => { fireEvent.click(within(row).getByRole('checkbox')); }; -describe('objectstack#35554 — the list page bar takes the row controls', () => { +const bar = () => screen.getByTestId('bulk-actions-bar'); +const checked = () => screen.getAllByRole('checkbox').filter((c) => c.getAttribute('data-state') === 'checked'); + +describe('objectstack#35678 — one floating selection bar for every grid', () => { 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()); @@ -116,50 +123,76 @@ describe('objectstack#35554 — the list page bar takes the row controls', () => expect(screen.queryAllByTestId('row-action-trigger')).toHaveLength(0); }); - it('CONTROL: a grid with no page bar keeps its Actions column', async () => { + it('CONTROL: a grid in no list page scope 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 () => { + it("one row selected: the bar floats in the table with that record's first three actions; the page bar is untouched", async () => { + renderListPage(true); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + const pageBarBefore = screen.getByTestId('page-bar').outerHTML; + tick('Alice'); + await waitFor(() => expect(bar()).toBeInTheDocument()); + expect(screen.getByTestId('data-table-floating-bar')).toContainElement(bar()); + expect(within(bar()).getByTestId('bulk-selection-count')).toHaveTextContent('1'); + expect(within(bar()).getByTestId('row-action-inline-submit_approval')).toBeInTheDocument(); + expect(within(bar()).getByTestId('row-action-inline-make_quote')).toBeInTheDocument(); + expect(within(bar()).getByTestId('row-action-inline-clone')).toBeInTheDocument(); + // Edit and Delete are the fourth and fifth: behind More. + expect(within(bar()).queryByTestId('selection-action-edit')).toBeNull(); + expect(within(bar()).getByTestId('selection-actions-more')).toBeInTheDocument(); + expect(screen.getByTestId('page-bar').outerHTML).toBe(pageBarBefore); + }); + + it('while the bar floats, the table keeps room after its last row; × takes both away', async () => { renderListPage(true); await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + expect(screen.queryByTestId('data-table-floating-bar-room')).toBeNull(); 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(); + tick('Bob'); + await waitFor(() => expect(within(bar()).getByTestId('bulk-selection-count')).toHaveTextContent('2')); + const room = screen.getByTestId('data-table-floating-bar-room'); + expect(room).toHaveAttribute('aria-hidden', 'true'); + // The room is the table body's last row, after Carol. + expect(room.parentElement!.lastElementChild).toBe(room); + fireEvent.click(within(bar()).getByTestId('bulk-selection-clear')); + await waitFor(() => expect(screen.queryByTestId('bulk-actions-bar')).toBeNull()); + expect(screen.queryByTestId('data-table-floating-bar-room')).toBeNull(); + expect(checked()).toHaveLength(0); }); - it('two rows selected: the bulk actions instead; Cancel restores the page bar', async () => { + it('two rows selected: the bulk actions instead', 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); + await waitFor(() => expect(within(bar()).getByTestId('bulk-selection-count')).toHaveTextContent('2')); + expect(within(bar()).getByTestId('bulk-action-mass_update')).toBeInTheDocument(); + expect(within(bar()).getByTestId('bulk-action-assign')).toBeInTheDocument(); + expect(within(bar()).getByTestId('bulk-action-tag')).toBeInTheDocument(); + expect(within(bar()).queryByTestId('row-action-inline-submit_approval')).toBeNull(); }); - it('CONTROL: a grid with no page bar keeps the bottom bulk bar', async () => { + it('Esc clears the selection', async () => { + renderListPage(true); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + tick('Alice'); + await waitFor(() => expect(bar()).toBeInTheDocument()); + fireEvent.keyDown(document.body, { key: 'Escape' }); + await waitFor(() => expect(screen.queryByTestId('bulk-actions-bar')).toBeNull()); + expect(checked()).toHaveLength(0); + }); + + it('CONTROL: a grid in no list page scope draws the same bar', async () => { renderListPage(false); await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); tick('Alice'); - await waitFor(() => expect(screen.getByTestId('bulk-actions-bar')).toBeInTheDocument()); + tick('Bob'); + await waitFor(() => expect(within(bar()).getByTestId('bulk-selection-count')).toHaveTextContent('2')); + expect(screen.getByTestId('data-table-floating-bar')).toContainElement(bar()); }); it('Shift extends a selection over the rows between', async () => { @@ -168,8 +201,7 @@ describe('objectstack#35554 — the list page bar takes the row controls', () => 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')); + await waitFor(() => expect(within(bar()).getByTestId('bulk-selection-count')).toHaveTextContent('3')); }); it('right-click on a row: the row\'s actions, Delete last, after a separator, in the danger colour', async () => { diff --git a/ui/packages/plugin-grid/src/components/BulkActionBar.tsx b/ui/packages/plugin-grid/src/components/BulkActionBar.tsx index 37cfea2b6ac..9bb213a476d 100644 --- a/ui/packages/plugin-grid/src/components/BulkActionBar.tsx +++ b/ui/packages/plugin-grid/src/components/BulkActionBar.tsx @@ -8,14 +8,13 @@ import React from 'react'; import { Button } from '@object-ui/components'; -import { Trash2, CheckSquare, X } from 'lucide-react'; +import { Trash2 } from 'lucide-react'; import { LazyIcon, toKebabIconName } from '@object-ui/components'; import { useObjectTranslation, usePredicateScope, useCapabilityGate } from '@object-ui/react'; import { isActionSwitchedOff } from '@object-ui/core'; import type { BulkActionDef } from '@object-ui/types'; import { partitionBulkRows, hasVisibilityGate } from '../bulkEligibility'; import { formatActionLabel } from './RowActionMenu'; -import { BULK_SELECT_ALL_MATCHING_CAP, exceedsBulkSelectAllMatchingCap } from '../bulkSelectAllMatchingCap'; /** * Is this rich bulk def offered for this selection? `visible` is evaluated @@ -54,7 +53,7 @@ export interface LegacyBulkActionItem { destructive: boolean; } -/** What a selection is offered — the bar's buttons, and the selection's context menu. */ +/** What a selection is offered — the selection bar's buttons, and the selection's context menu. */ export interface BulkActionItems { /** Rich defs that pass the capability gate, the switch-off and their per-record `visible`, in declared order. */ defs: BulkActionDef[]; @@ -64,7 +63,7 @@ export interface BulkActionItems { /** * THE bulk-action resolver (objectstack#28434): what a selection is offered, - * read by both of its entry points — {@link BulkActionBar} and the context + * read by both of its entry points — the selection bar (`./SelectionBar`) and the context * menu a right-click on a selected row opens (`./RowContextMenu`). Both call * this hook, so a bulk action shows in both or in neither. * @@ -130,8 +129,8 @@ export type OrderedBulkItem = * 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. + * the selection bar 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[] = [ @@ -141,226 +140,28 @@ export function orderSelectionMenuItems(items: BulkActionItems): OrderedBulkItem return [...all.filter((e) => !e.destructive), ...all.filter((e) => e.destructive)]; } -/** One rich bulk-action button, offered per {@link useBulkActionItems}. */ +/** One rich bulk-action button, offered per {@link useBulkActionItems}, at the selection bar's size. */ export const BulkActionButton: React.FC<{ def: BulkActionDef; selectedRows: any[]; onActionDef?: (def: BulkActionDef, selectedRows: any[]) => void; - /** `page-bar`: the list page bar's button size (objectstack#35554). */ - size?: 'bar' | 'page-bar'; -}> = ({ def, selectedRows, onActionDef, size = 'bar' }) => { +}> = ({ def, selectedRows, onActionDef }) => { const isDestructive = isDestructiveBulkDef(def); const iconName = def.icon ? toKebabIconName(def.icon) : null; return ( ); }; - -export interface BulkActionBarProps { - /** Array of selected row records */ - selectedRows: any[]; - /** - * Bulk/batch action identifiers (legacy string list) that resolved to no - * declared action — dispatched by name for consumers that registered a - * runner handler under it. Names that DID resolve arrive in `actionDefs` - * instead (see `resolveBulkActions`), so the two lists never overlap. - */ - actions: string[]; - /** Rich action definitions — authored inline or derived from the object. */ - actionDefs?: BulkActionDef[]; - /** - * The object's field definitions (`objectSchema.fields`). Passed to each - * def's per-record `visible` so a relation field is bound as the FOREIGN KEY - * the server stores rather than the record `$expand` substituted for it — the - * selected rows come straight off the grid's expanded fetch, where every - * relational COLUMN is an object (see `toPredicateRecord`). - */ - objectFields?: unknown; - /** Callback when a legacy string-id bulk action button is clicked */ - onAction?: (action: string, selectedRows: any[]) => void; - /** Callback when a rich-def bulk action button is clicked. */ - onActionDef?: (def: BulkActionDef, selectedRows: any[]) => void; - /** Callback to clear selection */ - onClearSelection?: () => void; - /** - * Cross-page selection — number of rows currently loaded on the page. - * When `selectedRows.length === pageSize` and `totalMatching > pageSize`, - * we offer to extend the selection across the entire match set. - */ - pageSize?: number; - /** Total matching record count from the most recent find. */ - totalMatching?: number; - /** True when the user has opted into the cross-page selection. */ - allMatchingSelected?: boolean; - /** Invoked when the user clicks "Select all N matching". */ - onSelectAllMatching?: () => void; -} - -export const BulkActionBar: React.FC = ({ - selectedRows, - actions, - actionDefs, - objectFields, - onAction, - onActionDef, - onClearSelection, - pageSize, - totalMatching, - allMatchingSelected, - onSelectAllMatching, -}) => { - const { t } = useObjectTranslation(); - // The one resolver the selection's context menu reads too (objectstack#28434). - const items = useBulkActionItems({ selectedRows, actions, actionDefs, objectFields }); - // Render whenever rows are selected — this bar is the single, canonical - // selection indicator (count + Clear). Bulk-action buttons are optional: with - // none configured it still surfaces "N selected / Clear", so the embedded - // data-table needn't draw its own (unstyled, orphaned) selection toolbar. - if (selectedRows.length === 0) return null; - - // Cross-page affordance: show banner when the user has selected the - // entire visible page AND there are more matching records off-screen. - const showCrossPageAffordance = - !allMatchingSelected - && typeof totalMatching === 'number' - && typeof pageSize === 'number' - && pageSize > 0 - && selectedRows.length >= pageSize - && totalMatching > pageSize; - // Over the cap, every string that counts the match set says that only the - // first BULK_SELECT_ALL_MATCHING_CAP records are processed. - const overCap = exceedsBulkSelectAllMatchingCap(totalMatching); - - return ( -
- {(showCrossPageAffordance || allMatchingSelected) && ( -
- {allMatchingSelected ? ( - <> - - - {overCap - ? t('grid.bulkAllMatchingSelectedCapped', { - cap: BULK_SELECT_ALL_MATCHING_CAP, - total: totalMatching, - defaultValue: 'Only the first {{cap}} of {{total}} matching records will be processed.', - }) - : t('grid.bulkAllMatchingSelected', { - count: totalMatching, - defaultValue: 'All {{count}} matching records are selected.', - })} - - - ) : ( - <> - - {t('grid.bulkAllOnPage', { - count: pageSize, - defaultValue: 'All {{count}} on this page are selected.', - })} - - - - )} -
- )} -
- - - - {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.bulkSelected', { - count: selectedRows.length, - defaultValue: '{{count}} selected', - })} - - -
- {items.defs.map(def => ( - - ))} - {items.legacy.map(({ name: action, label, destructive: isDestructive }) => { - const Icon = isDestructive ? Trash2 : null; - return ( - - ); - })} -
- -
-
- ); -}; diff --git a/ui/packages/plugin-grid/src/components/RowActionMenu.tsx b/ui/packages/plugin-grid/src/components/RowActionMenu.tsx index dc7bc06466b..26bfff29fcc 100644 --- a/ui/packages/plugin-grid/src/components/RowActionMenu.tsx +++ b/ui/packages/plugin-grid/src/components/RowActionMenu.tsx @@ -562,9 +562,10 @@ export const RowActionInlineButton: React.FC<{ row: any; objectFields?: unknown; onActionDef?: (def: RowActionDef, row: any) => void; - /** objectstack#35554 — the page bar draws its exposed actions as outline buttons. */ + /** objectstack#35678 — the selection bar draws its exposed actions as outline buttons, at its own size. */ buttonVariant?: 'default' | 'secondary' | 'destructive' | 'ghost' | 'link' | 'outline'; -}> = ({ def, row, objectFields, onActionDef, buttonVariant }) => { + buttonClassName?: string; +}> = ({ def, row, objectFields, onActionDef, buttonVariant, buttonClassName }) => { const scope = usePredicateScope(); const isVisible = React.useMemo( () => isCustomRowActionVisible(def, row, scope, objectFields), @@ -582,7 +583,7 @@ export const RowActionInlineButton: React.FC<{ + ); +}; + +/** The bar's More: a labelled button opening the actions that are not exposed. */ +const MoreMenu: React.FC<{ label: string; children: React.ReactNode; onOpen?: () => void }> = ({ label, children, onOpen }) => ( + { if (open) onOpen?.(); }}> + + + + {children} + +); + +const Divider: React.FC = () =>