Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit d0ae5d0

Browse files
fix(plugin-list,plugin-grid): a grouped list view under a toolbar search groups on the server, with the searched counts (objectui#11021) (#11243)
Fixes #11021 Clause-②: no The ListView half of objectui#11021. The grid half (PR objectui#11178, merged as `7e4fa1bb2`) made a server-grouped grid send its search term on the group header query and on every group's row query. This PR makes the console's grouped **list view** use it. With this, all four of the card's acceptance lines hold through the list view, so the PR closes the card. ## What changes - **`packages/plugin-list/src/ListView.tsx`**: `gridOwnsGroupedFetch` loses its `!searchTerm` carve-out and its comment. That comment gave "`$search` has no counterpart on the header query" as the reason, which is false against the installed `@objectstack/spec` plus PR objectui#11178. Under a toolbar search, a grouped grid over a data source that answers `queryGroupHeaders` is still handed **no rows**. It gets the list's term as its `search` host prop (an empty one too: the list owns the term), and the view's `searchableFields` on its node, beside the effective `filter` it already carried. `ListView`'s own fetch sends that same pair as `$search` / `$searchFields`. - **`packages/plugin-grid/src/ObjectGrid.tsx`**, only in the three regions the claim names: - **Host search.** `hostOwnsSearch` / `querySearchTerm`: a host that passes `search` owns the term, under host-driven paging (unchanged) and also when the grid fetches for itself. The load effect's `$search` reads that term, so `groupSearchOf(groupRowQuery)` carries it to both group queries. With no `search` prop, the term is the grid's own box, as before. - **Re-entry reset.** `groupRowQuery` goes back to `null` when the grid leaves server grouping. Before, re-entering grouping asked the first header query with the query held from the last grouped phase, and painted that answer before the fresh one (see the measurements). - **Comments.** The false `manualSearchOn` comment is rewritten to say what the code does, and so is the `manualSearch` comment. `ObjectGridExternalPaginationProps` gains one paragraph: `search` is read outside host-driven paging too. - These regions are disjoint from objectui#9547's hunks (merged into this branch from `main`, and the merge was clean). - **`packages/plugin-grid/package.json`**: the `@objectstack/spec` floor goes `^17.4.0` to `^17.5.0` on both lines. `pnpm install` rewrote one lockfile specifier line, and the resolved version did not move (it was already `17.5.0`). - **Prose this change made false** (AGENTS.md #2): three docs and one comment said a `ListView` keeps grouping its own window under a search. Those are `packages/plugin-list/README.md`, `packages/plugin-grid/README.md`, `content/docs/plugins/plugin-grid.mdx`, and a `useGroupedData.ts` comment. The grid half's still-pending changeset `.changeset/11021-grouped-grid-search-both-queries.md` ended on the same sentence, and that paragraph is removed; this is a prose correction to a not-yet-released declaration, and its package names are untouched. Three plugin-list test comments carried the same claim and are corrected too. - **Changeset**: `.changeset/11021-listview-grouped-search.md`, with `@object-ui/plugin-list` and `@object-ui/plugin-grid` at patch. ## Measurements of the dispatch's mechanism assumptions (all at `origin/main` `3c13675e5f`) 1. **Carve-out: confirmed, and reproduced red first** through the real `ListView` + real `ObjectGrid`, with no source edits. The new pin `packages/app-shell/src/__tests__/listViewGroupedSearch-11021.test.tsx` uses 186 rows in five units (86/61/31/7/1) and the term `#1`. The term matches 34 rows, and the view's page is 20. On base, the searched grouped list drew `{ Northgate Operations: 11, Northgate Plant: 9 }`: the page of 20 grouped in the browser. The query's answer is `{ 11, 11, 11, 1 }`. The result was `Tests 3 failed | 2 passed (5)`. 2. **Channel: confirmed, one channel.** `ListView` fed the grid no search at all before, since its flat grid is handed a window that is already searched. The grid's existing host prop `search` now carries the term. The measured widening beyond "server-grouped mode" is deliberate. Under `gridOwnsGroupedFetch`, the grid can still fetch a flat or bucketed window of its own, when the grouping key is unreadable or known-masked. Reading `search` only when server-grouped would drop the term there, which is a regression, so a passed `search` is read wherever the grid fetches for itself. Searchable fields ride the node's declared `searchableFields`, the key the grid's own `$searchFields` already reads. No new prop was added. The box stays hidden: a host that owns the term but passes no `onSearchChange` gets none. 3. **Re-entry staleness: confirmed and fixed.** On base, the tightened grid pin (search, flat, clear, regroup) saw a header query after re-entry that carried `search: '#1'` and `searchFields: ['subject']`. A second ablation leg (below) switched the query-level check off and left only the paint check. Without the reset, **both** pins then went red on a painted searched header set, `{ 11, 11, 11, 1 }`, before the unsearched one. With the reset, no re-entry header query carries the term and no searched set paints, while at least one set was sampled. 4. **`manualSearchOn` comment: rewritten.** `manualSearchOn` itself does not change. A grouped grid renders no flat table, and each group's table is `searchable: false`, so this flag governs only the flat table. 5. **Floor: raised.** The specifier moved; the resolved version stayed `17.5.0`. `pnpm install --frozen-lockfile` answered "Lockfile is up to date". ## Tests - New `packages/app-shell/src/__tests__/listViewGroupedSearch-11021.test.tsx` mounts the real `ListView` and the real registered `object-grid`. It has five cases: - the fixture precondition: the matches outnumber the page; - SEARCHED: only the groups holding matches, each count equal to its matches, each group drawing exactly those rows, and both queries carrying `search` / `searchFields`; - UNSEARCHED: the five whole units, with no search key on either query; - clearing through the toolbar box, which restores the five units, and whose last header query and each unit's latest row page carry no term; - re-entry: grouping off, the term cleared, grouping on. No header query after re-entry carries the term, and no searched group set is painted. - `plugin-grid` `serverGroupedSearch-11021.test.tsx`: the clearing case now asserts no stale ask and no stale paint on re-entry. It used to tolerate both, in a comment. A new case covers a host's `search` prop driving both queries and clearing them. - `plugin-list`: `ListView.groupedGridOwnsFetch-7189.test.tsx` gains the searched handoff (no rows; `search` and `searchableFields` equal to the list's own `$search` / `$searchFields`; the filter unchanged) and an ungrouped control (a searched window, no term handed). In `ListView.groupingNeedsHeaderQuery-10881.test.tsx`, the case that pinned "a grouped grid handed a searched window" pinned the very branch this PR deletes. It is replaced by the same question asked of the new behaviour: no window and no host paging. **Ablation**, one-shot, from committed `620c07cd76`, through objectstack's `scripts/ablation-replace.mjs`. Every mutation was proven on disk (anchor x1 to x0, replacement x0 to x1, blob moved). Every restore was proven by the blob equal to HEAD and an empty `git diff HEAD`, and no permanent test file was left. The pins resolve `@object-ui/plugin-grid` and `@object-ui/plugin-list` through the vitest alias to `src`, so no `dist/` is in the path. - Leg A, the reset line removed: `Tests 2 failed | 7 passed (9)`. The grid clearing case and the list re-entry case went red on a re-entry header query carrying `search: "#1"`. - Leg A-paint, the reset removed and both query loops skipped: `Tests 2 failed | 7 skipped (9)`, both on `expect(counts).not.toEqual(SEARCHED)`. - Leg B, `&& !searchTerm` restored: `Tests 5 failed | 10 passed (15)`. SEARCHED, clearing and re-entry through the list failed, and so did the 7189 searched handoff and the 10881 replacement. - Leg C, host `search` read only under host paging: `Tests 4 failed | 5 passed (9)`. The grid host-search case failed, and so did the three searched list cases. ## Gates Branch head `cee5c02158`: `620c07cd76` merged with `main` at `dded788ada`, which brought in objectui#9547. Every exit was captured before any pipe. Heavy runs went through the shared verify lock. **At `cee5c02158`:** - `pnpm install --frozen-lockfile`: exit 0, "Lockfile is up to date". - `pnpm turbo run build --filter='@object-ui/app-shell^...' --concurrency=2`: exit 0, 28/28 tasks. This closure contains both `@object-ui/plugin-list^...` and `@object-ui/plugin-grid^...`. - Type-check, `pnpm --filter @object-ui/plugin-grid type-check && … plugin-list … && … app-shell …`: exit 0. Each run echoed `tsc --noEmit && tsc -p tsconfig.test.json`. - `pnpm exec vitest run packages/plugin-grid/`: exit 0, `Test Files 174 passed (174)`, `Tests 1596 passed (1596)`. - The pins plus the importer set, 14 files: exit 0, `Tests 148 passed (148)`. That is the new app-shell pin, the six changed plugin-list files, `displayPageSizeFromSpec-9853`, four plugin-view `ObjectView` suites, two app-shell `ObjectView` suites and `data-objectstack` `queryGroupHeaders-7189`. - The 18 suites that `scripts/markdown-test-inputs.mjs --list` names as readers of the five changed markdown files (`doc-version-claims.test.ts` among them): exit 0, `Tests 841 passed (841)`. - Exit 0: - `check-changeset-presence` ("10 source file(s) of 3 released package(s) changed, and this change declares 1 changeset(s)"); - `check-changeset-no-major`, `check-changeset-fixed`; - `check-changeset-claims` and `check-changeset-overwrite` (both report-only); - `check:pending-changeset-literals`, `check:installed-pin-claims`, `check:control-bytes`; - `check:new-line-citations` ("0 new citation(s)"); - `check:doc-fences`, `check-doc-links` ("Links are valid across 17 scan roots"), `check-doc-expression-carriage`, `check:doc-types`, `check-doc-example-ids`; - `check-lockfile-integrity` ("VERDICT clean"), `check-lockfile-dedupe` ("VERDICT deduped"), `check:phantom-deps`; - `check:test-path-roots`, `check-vi-mock-specifiers`, `check:unreferenced-sources`, `check-type-check-coverage`, `check-lint-coverage`, `check:spec-symbols`; - `markdown-test-inputs --audit`; - `check-governed-queue-guard --test` over the changed paths ("An ordinary pull request"). - **NOT MEASURED:** - `check:spec-floors` exited 1 on 5 `no-artifact` findings, for `app-shell`, `cli`, `plugin-gantt`, `plugin-timeline` and `plugin-tree`: packages outside this diff that this worktree did not build. That is a prerequisite refusal, not a verdict. `plugin-grid`, whose floor moved, was built and judged, with no finding. - `check:readme-exports` exited 1 on 88 "`./dist/index.d.ts` is not on disk" refusals, none of them for the two READMEs changed here. This diff changes 0 fence lines in any doc. **At `620c07cd76`** (the same diff before the merge): - `pnpm exec vitest run packages/plugin-list/`, in two shards: exit 0 both times, 55 + 54 files, 387 + 814 tests. The merge changed no `plugin-list` file. - `pnpm exec vitest run scripts/__tests__/`, in two shards: exit 0 both times, 177 files passed and 2 skipped of 179, 5371 tests passed and 2 skipped. - `tsc -p tsconfig.test.json --listFiles` counts: the new app-shell pin appears once, the grid pin once, and the five changed plugin-list suites once each. - eslint on the 10 changed TypeScript files: 0 errors. Compared per rule with base, the only delta is +1 `react-hooks/set-state-in-effect` in `ObjectGrid.tsx`, from the reset effect. The config is not type-aware, so no untouched file's verdict can move. CI is not waited on; its verdict is the merge queue's. ## Deviations from the declared file surface (each forced by what the change made false, or by the pin the dispatch asks for) - The real-`ListView`-plus-real-`ObjectGrid` pin lives in **`packages/app-shell/src/__tests__/`**, not `packages/plugin-list/src/__tests__/`. `plugin-list` declares no `plugin-grid` edge, so a pin there would need either a `vitest.config.mts` `heavyDomTests` entry (a root config that dozens of `scripts/__tests__` suites read) or an undeclared test import (`check:phantom-deps`). `app-shell` already declares both packages, the route `displayPageSizeFromSpec-9853.test.tsx` takes. - The docs, the `useGroupedData.ts` comment, the pending grid-half changeset and the three test comments listed above. ## Acceptance notes - `ObjectGrid.tsx` gains one `react-hooks/set-state-in-effect` warning, from the reset effect. The file carries that pattern already (its `setSearchTerm('')` reset on an object change), and eslint reports 0 errors. Every other changed file's per-rule warning set is identical to base. - Commits `7470afd89b` and `620c07cd76` end with a `Co-Authored-By` trailer that carries a model name, copied from the harness's attribution reminder. The model-free pair is what AGENTS.md asks for, and the merge commit carries it. History is not rewritten: objectui forbids force-push. Session: `https://claude.ai/code/session_0122Knsowci76D2rBWReCzzZ` --- _Generated by [Claude Code](https://claude.ai/code/session_0122Knsowci76D2rBWReCzzZ)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 615346d commit d0ae5d0

17 files changed

Lines changed: 519 additions & 69 deletions

‎.changeset/11021-grouped-grid-search-both-queries.md‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,3 @@ matching rows, each header counts its matching rows, the rows under it are
2020
those rows, and clearing the term restores the unsearched groups. The
2121
ObjectStack adapter already posts the header query verbatim, so it needs no
2222
change.
23-
24-
A `ListView` still keeps grouping its own window while its toolbar search is
25-
active: it does not hand the term to the grid.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
'@object-ui/plugin-list': patch
3+
'@object-ui/plugin-grid': patch
4+
---
5+
6+
fix(plugin-list,plugin-grid): a grouped list view under a toolbar search groups on the server, and each group counts all its matching rows
7+
8+
A grouped list view whose data source answers the group header query hands
9+
the grid its own fetch, so the groups and their counts come from the server.
10+
A toolbar search used to take that back: the list view fetched one page of
11+
searched rows and the grid grouped that page in the browser, so once the
12+
matches outnumbered the page a group's count was the page's slice of it, and
13+
a group whose matches all fell past the page was missing.
14+
15+
The list view now hands the grid its toolbar term (the grid's `search` prop)
16+
and the view's `searchableFields`, and the grid sends them on the group header
17+
query and on every group's row query. A searched grouped list view shows only
18+
the groups that hold matching rows, each counting all its matches, and
19+
clearing the search restores the unsearched groups.
20+
21+
`ObjectGrid` now reads a host's `search` whenever one is passed, not only
22+
under host-driven paging: the host then owns the term, and the grid's own
23+
queries carry it. Turning grouping back on no longer asks for, or briefly
24+
shows, the groups of the query the grid held when it last grouped (a cleared
25+
search, or an old filter or sort). `@object-ui/plugin-grid` now declares
26+
`@objectstack/spec` `^17.5.0`, the release whose group header query takes a
27+
search.

‎content/docs/plugins/plugin-grid.mdx‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -426,10 +426,11 @@ makes the same refusal before it mounts such a grid. To group, implement
426426
A **search** term the grid queries with goes on the group header query and on
427427
every group's row query, as one pair (`search` / `searchFields`, which the
428428
header query declares beside `where`): the headers count the
429-
searched rows, and the rows under them are those rows (objectui#11021). A
430-
`ListView` does not hand its toolbar search to the grid: over a data source
431-
that answers the header query it keeps grouping its own window while a search
432-
term is active, so those group counts are the window's, not the query's.
429+
searched rows, and the rows under them are those rows (objectui#11021). The
430+
term is the one typed into the grid's box, or the one a host hands down as the
431+
`search` prop: a host that passes `search` owns the term even where the grid
432+
fetches for itself. That is how a `ListView` hands its toolbar search to the
433+
grid that groups for it, with the view's `searchableFields` on the grid's node.
433434

434435
### ObjectQL Integration
435436

Lines changed: 302 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,302 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectui#11021 — a grouped LIST VIEW under a toolbar search groups on the
11+
* server, and its group counts are the searched rows' counts.
12+
*
13+
* objectui#7189 ruling A: "the set of groups and every number in a group
14+
* header ... are properties of the query, not of the fetched page". Since
15+
* `@objectstack/spec` 17.5.0 the group header query takes ADR-0061
16+
* `search` / `searchFields`, and the grid sends the term on the header query
17+
* and on every group's row query as one pair. What reaches the console's
18+
* grouped list view is the other half: `ListView` has to hand its toolbar term
19+
* to the grid that groups on the server, instead of grouping one fetched
20+
* window of searched rows in the browser (whose counts are page slices once
21+
* the matches outnumber the window).
22+
*
23+
* ## Why this file lives in `app-shell`
24+
*
25+
* The claim is about two components at once — the toolbar term is
26+
* `ListView`'s, the queries are `ObjectGrid`'s — so both are mounted for real.
27+
* `app-shell` already depends on `plugin-list` and `plugin-grid`, so this adds
28+
* no dependency edge (the same reason `displayPageSizeFromSpec-9853.test.tsx`
29+
* lives here). `plugin-list`'s own handoff pin, over a stub grid, is
30+
* `ListView.groupedGridOwnsFetch-7189.test.tsx`; the grid's own reading of the
31+
* handed term is `serverGroupedSearch-11021.test.tsx` in `plugin-grid`.
32+
*
33+
* ## What the double answers
34+
*
35+
* `queryGroupHeaders` and `find` apply ONE matcher to the whole store: the
36+
* compiled `where` / `$filter`, then `search` / `$search` over `searchFields`
37+
* / `$searchFields`. The term `#1` matches numbers 1 and 10-19 of each unit:
38+
* 34 rows, more than the view's page of 20, and none of the Depot's one row.
39+
*/
40+
import React from 'react';
41+
import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest';
42+
import { render, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react';
43+
import '@testing-library/jest-dom';
44+
import { ListView } from '@object-ui/plugin-list';
45+
// Registers `object-grid`, the renderer `ListView` mounts through the registry.
46+
import '@object-ui/plugin-grid';
47+
import { registerAllFields } from '@object-ui/fields';
48+
import { ActionProvider, SchemaRendererProvider } from '@object-ui/react';
49+
50+
beforeAll(() => {
51+
registerAllFields();
52+
});
53+
54+
const OBJECT = 'duly_task';
55+
const OBJECT_FIELDS = {
56+
id: { type: 'text', label: 'Id' },
57+
subject: { type: 'text', label: 'Subject' },
58+
business_unit: { type: 'text', label: 'Business Unit' },
59+
};
60+
61+
/** 186 rows over five units sized 86/61/31/7/1, as objectui#7189's fixture. */
62+
const UNITS: Array<[string, number]> = [
63+
['Northgate Operations', 86],
64+
['Northgate Plant', 61],
65+
['Northgate Quality', 31],
66+
['Riverside Plant', 7],
67+
['Riverside Depot', 1],
68+
];
69+
const UNSEARCHED: Record<string, number> = Object.fromEntries(UNITS);
70+
71+
interface Row { id: string; subject: string; business_unit: string }
72+
const ROWS: Row[] = UNITS.flatMap(([unit, n]) =>
73+
Array.from({ length: n }, (_, i) => ({ id: `${unit}-${i}`, subject: `${unit} #${i}`, business_unit: unit })),
74+
);
75+
76+
const TERM = '#1';
77+
const SEARCH_FIELDS = ['subject'];
78+
/** Numbers 1 and 10-19 of each unit: the Depot's one row (#0) has none. */
79+
const SEARCHED: Record<string, number> = {
80+
'Northgate Operations': 11,
81+
'Northgate Plant': 11,
82+
'Northgate Quality': 11,
83+
'Riverside Plant': 1,
84+
};
85+
/** The view's page: fewer rows than the term matches. */
86+
const PAGE_SIZE = 20;
87+
88+
/** The `FilterCondition` subset the compiled queries use: `$and`, `$eq`, `$null`, equality. */
89+
function matchesWhere(row: Record<string, unknown>, cond: unknown): boolean {
90+
if (cond === undefined || cond === null) return true;
91+
return Object.entries(cond as Record<string, unknown>).every(([key, value]) => {
92+
if (key === '$and') return (value as unknown[]).every((c) => matchesWhere(row, c));
93+
if (value && typeof value === 'object' && !Array.isArray(value)) {
94+
const op = value as Record<string, unknown>;
95+
if ('$eq' in op) return row[key] === op.$eq;
96+
if ('$null' in op) return op.$null ? row[key] == null : row[key] != null;
97+
throw new Error(`double: unsupported operator ${JSON.stringify(op)}`);
98+
}
99+
return row[key] === value;
100+
});
101+
}
102+
103+
/** ADR-0061 as the double serves it: a substring over the searched fields. */
104+
function matchesSearch(row: Record<string, unknown>, term: unknown, fields: unknown): boolean {
105+
if (term === undefined) return true;
106+
if (typeof term !== 'string' || term === '') throw new Error(`double: a search that is not a term: ${JSON.stringify(term)}`);
107+
const over = Array.isArray(fields) ? (fields as string[]) : ['subject', 'business_unit'];
108+
return over.some((f) => String(row[f] ?? '').toLowerCase().includes(term.toLowerCase()));
109+
}
110+
111+
type HeaderQuery = { where?: unknown; groupBy?: string[]; search?: unknown; searchFields?: unknown };
112+
113+
/** A data source serving BOTH compiled queries, and the list's own window, with one matcher. */
114+
const makeServerDataSource = () => ({
115+
queryGroupHeaders: vi.fn(async (_object: string, query: HeaderQuery) => {
116+
const groupBy = query.groupBy ?? [];
117+
const buckets = new Map<string, number>();
118+
for (const row of ROWS) {
119+
if (!matchesWhere(row as any, query.where) || !matchesSearch(row as any, query.search, query.searchFields)) continue;
120+
const key = JSON.stringify(groupBy.map((f) => (row as any)[f] ?? null));
121+
buckets.set(key, (buckets.get(key) ?? 0) + 1);
122+
}
123+
return [...buckets.entries()].map(([key, count]) => {
124+
const values = JSON.parse(key) as unknown[];
125+
return { ...Object.fromEntries(groupBy.map((f, i) => [f, values[i]])), count };
126+
});
127+
}),
128+
find: vi.fn(async (_object: string, params: Record<string, unknown>) => {
129+
const matching = ROWS.filter((r) =>
130+
matchesWhere(r as any, params.$filter) && matchesSearch(r as any, params.$search, params.$searchFields));
131+
const skip = (params.$skip as number | undefined) ?? 0;
132+
const top = (params.$top as number | undefined) ?? matching.length;
133+
return { data: matching.slice(skip, skip + top), total: matching.length };
134+
}),
135+
findOne: vi.fn(),
136+
create: vi.fn(),
137+
update: vi.fn(),
138+
delete: vi.fn(),
139+
getObjectSchema: vi.fn(async () => ({ name: OBJECT, fields: OBJECT_FIELDS })),
140+
});
141+
type ServerDataSource = ReturnType<typeof makeServerDataSource>;
142+
143+
const GROUPING = { fields: [{ field: 'business_unit', order: 'asc', collapsed: false }] };
144+
145+
const listSchema = (grouped: boolean) => ({
146+
type: 'list-view',
147+
objectName: OBJECT,
148+
columns: ['subject'],
149+
searchableFields: SEARCH_FIELDS,
150+
pagination: { pageSize: PAGE_SIZE },
151+
...(grouped ? { grouping: GROUPING } : {}),
152+
}) as any;
153+
154+
const view = (ds: ServerDataSource, grouped: boolean) => (
155+
<SchemaRendererProvider dataSource={ds as any}>
156+
<ActionProvider>
157+
<ListView schema={listSchema(grouped)} dataSource={ds as any} />
158+
</ActionProvider>
159+
</SchemaRendererProvider>
160+
);
161+
162+
const groupRows = () => [...document.querySelectorAll('[data-testid^="group-row-"]')];
163+
const headerOf = (el: Element) => ({
164+
label: el.querySelector('.group-label')?.textContent ?? '',
165+
count: el.querySelector('.group-count')?.textContent ?? '',
166+
});
167+
const headerCounts = () => Object.fromEntries(groupRows().map((r) => { const h = headerOf(r); return [h.label, Number(h.count)]; }));
168+
const groupRowEl = (label: string) => groupRows().find((r) => headerOf(r).label === label)!;
169+
const subjectsIn = (el: Element, unit: string) =>
170+
within(el as HTMLElement).queryAllByText(new RegExp(`^${unit} #\\d+$`)).map((n) => n.textContent);
171+
172+
/** The grid's row page queries: each one carries a group key under `$and`. */
173+
const groupRowFinds = (ds: ServerDataSource, from = 0) =>
174+
ds.find.mock.calls.slice(from).map(([, p]) => p).filter((p) => Array.isArray((p.$filter as { $and?: unknown } | undefined)?.$and));
175+
176+
/** Type into the list's toolbar Search box (the popover's input). */
177+
function typeInToolbarSearch(value: string) {
178+
if (!screen.queryByPlaceholderText(/search/i)) fireEvent.click(screen.getByTestId('search-icon-button'));
179+
fireEvent.change(screen.getByPlaceholderText(/search/i), { target: { value } });
180+
}
181+
182+
/** Every header set the grid paints, sampled on each DOM mutation. */
183+
function recordPaintedHeaders() {
184+
const painted: Array<Record<string, number>> = [];
185+
const observer = new MutationObserver(() => {
186+
const counts = headerCounts();
187+
if (Object.keys(counts).length > 0) painted.push(counts);
188+
});
189+
observer.observe(document.body, { childList: true, subtree: true, characterData: true });
190+
return { painted, stop: () => observer.disconnect() };
191+
}
192+
193+
afterEach(() => cleanup());
194+
195+
describe('a grouped list view under a toolbar search groups on the server (objectui#11021)', () => {
196+
it('the fixture: the term matches more rows than the view\'s page', () => {
197+
const matches = Object.values(SEARCHED).reduce((a, b) => a + b, 0);
198+
expect(matches).toBeGreaterThan(PAGE_SIZE);
199+
});
200+
201+
it('SEARCHED: only the groups holding matches, each counting all its matches, over exactly those rows', async () => {
202+
const ds = makeServerDataSource();
203+
render(view(ds, true));
204+
await waitFor(() => expect(headerCounts()).toEqual(UNSEARCHED));
205+
206+
typeInToolbarSearch(TERM);
207+
208+
await waitFor(() => expect(headerCounts()).toEqual(SEARCHED));
209+
// The Depot's one row does not match, so it is not a group at all.
210+
expect(groupRows().map((r) => headerOf(r).label)).not.toContain('Riverside Depot');
211+
// Each group draws the rows its header counted.
212+
for (const [unit, count] of Object.entries(SEARCHED)) {
213+
await waitFor(() => expect(subjectsIn(groupRowEl(unit), unit)).toHaveLength(count));
214+
}
215+
216+
// One pair on both of the grid's queries.
217+
const [, headerQuery] = ds.queryGroupHeaders.mock.calls.at(-1)!;
218+
expect(headerQuery.search).toBe(TERM);
219+
expect(headerQuery.searchFields).toEqual(SEARCH_FIELDS);
220+
const rowFinds = groupRowFinds(ds).slice(-Object.keys(SEARCHED).length);
221+
expect(rowFinds).toHaveLength(Object.keys(SEARCHED).length);
222+
for (const params of rowFinds) {
223+
expect(params.$search).toBe(TERM);
224+
expect(params.$searchFields).toEqual(SEARCH_FIELDS);
225+
}
226+
});
227+
228+
it('UNSEARCHED: the five whole units, and no search key on either of the grid\'s queries', async () => {
229+
const ds = makeServerDataSource();
230+
render(view(ds, true));
231+
232+
await waitFor(() => expect(headerCounts()).toEqual(UNSEARCHED));
233+
for (const [, query] of ds.queryGroupHeaders.mock.calls) {
234+
expect(query).not.toHaveProperty('search');
235+
expect(query).not.toHaveProperty('searchFields');
236+
}
237+
await waitFor(() => expect(groupRowFinds(ds).length).toBeGreaterThanOrEqual(UNITS.length));
238+
for (const params of groupRowFinds(ds)) {
239+
expect(params).not.toHaveProperty('$search');
240+
expect(params).not.toHaveProperty('$searchFields');
241+
}
242+
});
243+
244+
it('clearing the toolbar search restores the unsearched groups, and drops the term from both queries', async () => {
245+
const ds = makeServerDataSource();
246+
render(view(ds, true));
247+
typeInToolbarSearch(TERM);
248+
await waitFor(() => expect(headerCounts()).toEqual(SEARCHED));
249+
for (const [unit, count] of Object.entries(SEARCHED)) {
250+
await waitFor(() => expect(subjectsIn(groupRowEl(unit), unit)).toHaveLength(count));
251+
}
252+
253+
const findsBefore = ds.find.mock.calls.length;
254+
typeInToolbarSearch('');
255+
256+
await waitFor(() => expect(headerCounts()).toEqual(UNSEARCHED));
257+
const [, lastHeaderQuery] = ds.queryGroupHeaders.mock.calls.at(-1)!;
258+
expect(lastHeaderQuery).not.toHaveProperty('search');
259+
expect(lastHeaderQuery).not.toHaveProperty('searchFields');
260+
// Every unit's latest row page is asked without the term.
261+
await waitFor(() => expect(subjectsIn(groupRowEl('Riverside Depot'), 'Riverside Depot')).toHaveLength(1));
262+
for (const [unit] of UNITS) {
263+
const pages = groupRowFinds(ds, findsBefore).filter((p) =>
264+
JSON.stringify((p.$filter as { $and: unknown[] }).$and).includes(JSON.stringify({ business_unit: { $eq: unit } })));
265+
expect(pages.length).toBeGreaterThan(0);
266+
expect(pages.at(-1)).not.toHaveProperty('$search');
267+
expect(pages.at(-1)).not.toHaveProperty('$searchFields');
268+
}
269+
});
270+
271+
it('turning grouping back on after the term was cleared asks and paints no stale searched groups', async () => {
272+
const ds = makeServerDataSource();
273+
const { rerender } = render(view(ds, true));
274+
typeInToolbarSearch(TERM);
275+
await waitFor(() => expect(headerCounts()).toEqual(SEARCHED));
276+
277+
// Grouping off: a flat list. The term is cleared while nothing is grouped.
278+
rerender(view(ds, false));
279+
await waitFor(() => expect(groupRows()).toHaveLength(0));
280+
typeInToolbarSearch('');
281+
await waitFor(() => expect(ds.find.mock.calls.at(-1)?.[1]).not.toHaveProperty('$search'));
282+
283+
// Grouping back on.
284+
const headerCallsBefore = ds.queryGroupHeaders.mock.calls.length;
285+
const recorder = recordPaintedHeaders();
286+
rerender(view(ds, true));
287+
await waitFor(() => expect(headerCounts()).toEqual(UNSEARCHED));
288+
recorder.stop();
289+
290+
// No header query after the re-entry carries the cleared term…
291+
const reentryHeaderQueries = ds.queryGroupHeaders.mock.calls.slice(headerCallsBefore).map(([, q]) => q);
292+
expect(reentryHeaderQueries.length).toBeGreaterThan(0);
293+
for (const query of reentryHeaderQueries) {
294+
expect(query).not.toHaveProperty('search');
295+
}
296+
// …and no searched group set is painted on the way to the unsearched one.
297+
expect(recorder.painted.length).toBeGreaterThan(0);
298+
for (const counts of recorder.painted) {
299+
expect(counts).not.toEqual(SEARCHED);
300+
}
301+
});
302+
});

‎packages/plugin-grid/README.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -544,10 +544,11 @@ makes the same refusal before it mounts such a grid. To group, implement
544544
A **search** term the grid queries with goes on the group header query and on
545545
every group's row query, as one pair (`search` / `searchFields`, which the
546546
header query declares beside `where`): the headers count the
547-
searched rows, and the rows under them are those rows (objectui#11021). A
548-
`ListView` does not hand its toolbar search to the grid: over a data source
549-
that answers the header query it keeps grouping its own window while a search
550-
term is active, so those group counts are the window's, not the query's.
547+
searched rows, and the rows under them are those rows (objectui#11021). The
548+
term is the one typed into the grid's box, or the one a host hands down as the
549+
`search` prop: a host that passes `search` owns the term even where the grid
550+
fetches for itself. That is how a `ListView` hands its toolbar search to the
551+
grid that groups for it, with the view's `searchableFields` on the grid's node.
551552

552553
## Integration with Data Sources
553554

‎packages/plugin-grid/package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
"@object-ui/plugin-detail": "workspace:*",
3232
"@object-ui/react": "workspace:*",
3333
"@object-ui/types": "workspace:*",
34-
"@objectstack/spec": "^17.4.0",
34+
"@objectstack/spec": "^17.5.0",
3535
"@tanstack/react-virtual": "^3.14.9",
3636
"exceljs": "^4.4.0",
3737
"lucide-react": "^1.43.0"
@@ -44,7 +44,7 @@
4444
"@object-ui/data-objectstack": "workspace:*",
4545
"@object-ui/sdui-parser": "workspace:*",
4646
"@object-ui/test-support": "workspace:*",
47-
"@objectstack/spec": "^17.4.0",
47+
"@objectstack/spec": "^17.5.0",
4848
"@tailwindcss/postcss": "^4.3.3",
4949
"@vitejs/plugin-react": "^6.0.5",
5050
"msw": "^2.15.0",

0 commit comments

Comments
 (0)