|
| 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 | +}); |
0 commit comments