@sincpro/web-framework 3.15.0 → 3.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,36 @@
1
1
  "use client";
2
- import { resumingFrom, } from "@sincpro/criteria";
3
- import { areGroups, NotGrouped } from "../core/groups.js";
2
+ import { resumingFrom } from "@sincpro/criteria";
3
+ import { areGroups, groupKeyOf, isGroupedAnswer, levelQuestion, nextGroups, NotGrouped, rowsQuestion, } from "../core/groups.js";
4
4
  import { measuresOf, sumsOf } from "../core/measure.js";
5
5
  import { useFramework } from "./context.js";
6
6
  import { useWrites } from "./useWrites.js";
7
7
  import { useCallback, useEffect, useRef, useState } from "react";
8
- /** The most groups a level answers: a split into ten thousand groups is a list, not a split. */
9
- const MAX_GROUPS = 100;
10
- /** A group is known by its criteria: unique per group, and stable across renders. */
11
- const keyOf = (bucket) => JSON.stringify(bucket.criteria);
8
+ const IDLE = {
9
+ status: "idle",
10
+ buckets: [],
11
+ error: null,
12
+ groupsCount: null,
13
+ records: null,
14
+ };
15
+ /** A group is known by the values of its path — what survives a new question, unlike its
16
+ * criteria, which carries the search. */
17
+ const keyOf = (path) => JSON.stringify(path);
18
+ /** Whether `path` is `above` or lies under it. */
19
+ const within = (path, above) => above.length <= path.length && above.every((part, index) => path[index] === part);
20
+ const without = (map, above) => {
21
+ const kept = [...map].filter(([, value]) => !within(value.path, above));
22
+ return kept.length === map.size ? map : new Map(kept);
23
+ };
12
24
  export function useGroups(listing, options = {}) {
13
25
  const { transport, context } = useFramework();
14
26
  // A named list may open grouped (`groupBy`); a person regroups from there.
15
27
  const [levels, setLevels] = useState(() => listing.definition?.groupBy ?? []);
16
- const [state, setState] = useState({ status: "idle", buckets: [], error: null });
28
+ const [root, setRoot] = useState(IDLE);
29
+ const [below, setBelow] = useState(new Map());
17
30
  const [rows, setRows] = useState(new Map());
18
- // A group being read: a second «more» before the first answer would ask for the same page.
19
- const reading = useRef(new Set());
31
+ const [opened, setOpened] = useState(new Set());
20
32
  const pageSize = options.pageSize ?? 50;
33
+ const groupPageSize = options.groupPageSize ?? 80;
21
34
  const maxRows = options.maxRows ?? 500;
22
35
  // The question without what pages it: a cursor or a limit of rows has no meaning for groups.
23
36
  const { pagination: _page, ...asked } = listing.question;
@@ -31,93 +44,337 @@ export function useGroups(listing, options = {}) {
31
44
  // What adds up by default is read from the model: without it yet, asking now and again when
32
45
  // it arrives would be two questions — and the groups on screen replaced under the pointer.
33
46
  const waiting = options.sums === undefined && listing.meta === null;
47
+ const grouped = levels.length > 0;
48
+ // Grouped, the list's own page is nobody's: it waits until the grouping ends.
49
+ const hold = listing.hold;
34
50
  useEffect(() => {
35
- setRows(new Map());
36
- reading.current.clear();
37
- if (levels.length === 0) {
38
- setState({ status: "idle", buckets: [], error: null });
51
+ hold(grouped);
52
+ return () => hold(false);
53
+ }, [hold, grouped]);
54
+ // What a reading answering later needs NOW — a callback made in an older render would page
55
+ // from groups no longer on screen.
56
+ const now = useRef({ levels, below, rows, opened, root, measured });
57
+ now.current = { levels, below, rows, opened, root, measured };
58
+ // Where each bucket sits: its values from the first level down, written as it arrives.
59
+ const paths = useRef(new WeakMap());
60
+ // A reading of an older question answers into nothing; each question has its own signal.
61
+ const generation = useRef({ id: 0, signal: new AbortController().signal });
62
+ const inFlight = useRef(new Set());
63
+ const pathOf = (bucket) => paths.current.get(bucket) ?? [groupKeyOf(bucket)];
64
+ const measuresNow = () => now.current.measured === ""
65
+ ? undefined
66
+ : JSON.parse(now.current.measured);
67
+ /** Reads the rows of a group of the deepest level: its first page, the next, or again. */
68
+ const readRows = useCallback((bucket, path, mode) => {
69
+ const key = keyOf(path);
70
+ const tag = `rows:${key}`;
71
+ if (inFlight.current.has(tag))
39
72
  return;
73
+ const had = now.current.rows.get(key);
74
+ if (mode === "more" && (had === undefined || had.after === null))
75
+ return;
76
+ inFlight.current.add(tag);
77
+ const { id, signal } = generation.current;
78
+ // Read again, as many as were on screen: a search does not undo the person's «more».
79
+ const limit = mode === "again"
80
+ ? Math.min(maxRows, Math.max(pageSize, had?.rows.length ?? 0))
81
+ : pageSize;
82
+ const first = rowsQuestion(bucket, limit);
83
+ const criteria = mode === "more" && had !== undefined ? resumingFrom(first, had.after) : first;
84
+ if (had !== undefined)
85
+ setRows((map) => new Map(map).set(key, { ...had, reading: true, error: null }));
86
+ transport.list(route, criteria, signal).then((page) => {
87
+ inFlight.current.delete(tag);
88
+ if (generation.current.id !== id)
89
+ return;
90
+ setRows((map) => {
91
+ const before = mode === "more" ? (map.get(key)?.rows ?? []) : [];
92
+ return new Map(map).set(key, {
93
+ path,
94
+ rows: [...before, ...page.rows],
95
+ after: page.cursor,
96
+ reading: false,
97
+ error: null,
98
+ });
99
+ });
100
+ }, (error) => {
101
+ inFlight.current.delete(tag);
102
+ if (generation.current.id !== id)
103
+ return;
104
+ setRows((map) => new Map(map).set(key, {
105
+ ...(map.get(key) ?? { path, rows: [], after: null }),
106
+ reading: false,
107
+ error,
108
+ }));
109
+ });
110
+ }, [transport, route, pageSize, maxRows]);
111
+ /**
112
+ * What arrived at a level, under `above`: each bucket learns its path, an open one reads what
113
+ * it holds again, and a closed one forgets it — reopened later, it reads it fresh.
114
+ */
115
+ const arrived = useRef(() => { });
116
+ /** Reads a level below an open group: its first page of groups, the next, or again. */
117
+ const readLevel = useCallback((bucket, path, mode) => {
118
+ const key = keyOf(path);
119
+ const tag = `level:${key}`;
120
+ const level = now.current.levels[path.length];
121
+ if (level === undefined || inFlight.current.has(tag))
122
+ return;
123
+ const had = now.current.below.get(key);
124
+ if (mode === "more" && had === undefined)
125
+ return;
126
+ inFlight.current.add(tag);
127
+ const { id, signal } = generation.current;
128
+ const limit = mode === "again" ? Math.max(groupPageSize, had?.buckets.length ?? 0) : groupPageSize;
129
+ const offset = mode === "more" ? (had?.buckets.length ?? 0) : 0;
130
+ const measures = measuresNow();
131
+ const criteria = levelQuestion(bucket.criteria, level, { limit, offset }, measures === undefined ? {} : { measures });
132
+ setBelow((map) => new Map(map).set(key, {
133
+ ...(had ?? { path, buckets: [], count: null }),
134
+ reading: true,
135
+ error: null,
136
+ }));
137
+ transport.list(route, criteria, signal).then((page) => {
138
+ inFlight.current.delete(tag);
139
+ if (generation.current.id !== id)
140
+ return;
141
+ if (!areGroups(page.rows)) {
142
+ const error = new NotGrouped(route);
143
+ setBelow((map) => new Map(map).set(key, {
144
+ ...(map.get(key) ?? { path, buckets: [], count: null }),
145
+ reading: false,
146
+ error,
147
+ }));
148
+ return;
149
+ }
150
+ const arriving = page.rows;
151
+ setBelow((map) => {
152
+ const before = mode === "more" ? (map.get(key)?.buckets ?? []) : [];
153
+ return new Map(map).set(key, {
154
+ path,
155
+ buckets: [...before, ...arriving],
156
+ count: page.groupsCount ?? null,
157
+ reading: false,
158
+ error: null,
159
+ });
160
+ });
161
+ arrived.current(arriving, path);
162
+ }, (error) => {
163
+ inFlight.current.delete(tag);
164
+ if (generation.current.id !== id)
165
+ return;
166
+ setBelow((map) => new Map(map).set(key, {
167
+ ...(map.get(key) ?? { path, buckets: [], count: null }),
168
+ reading: false,
169
+ error,
170
+ }));
171
+ });
172
+ }, [transport, route, groupPageSize]);
173
+ arrived.current = (buckets, above) => {
174
+ const deepest = above.length === now.current.levels.length - 1;
175
+ const closed = [];
176
+ for (const bucket of buckets) {
177
+ const path = [...above, groupKeyOf(bucket)];
178
+ paths.current.set(bucket, path);
179
+ if (!now.current.opened.has(keyOf(path)))
180
+ closed.push(path);
181
+ else if (deepest)
182
+ readRows(bucket, path, "again");
183
+ else
184
+ readLevel(bucket, path, "again");
40
185
  }
186
+ if (closed.length === 0)
187
+ return;
188
+ setBelow((map) => closed.reduce((kept, path) => without(kept, path), map));
189
+ setRows((map) => closed.reduce((kept, path) => without(kept, path), map));
190
+ };
191
+ // Another split starts closed; the same split under another question keeps what is open.
192
+ const split = JSON.stringify(levels);
193
+ const shownSplit = useRef(split);
194
+ useEffect(() => {
195
+ const fresh = shownSplit.current !== split;
196
+ shownSplit.current = split;
41
197
  const aborter = new AbortController();
42
- setState((now) => ({ ...now, status: "loading", error: null }));
198
+ generation.current = { id: generation.current.id + 1, signal: aborter.signal };
199
+ const { id } = generation.current;
200
+ inFlight.current.clear();
201
+ if (fresh) {
202
+ setOpened(new Set());
203
+ setBelow(new Map());
204
+ setRows(new Map());
205
+ }
206
+ const first = now.current.levels[0];
207
+ if (first === undefined) {
208
+ setRoot(IDLE);
209
+ return () => aborter.abort();
210
+ }
211
+ setRoot((was) => ({
212
+ ...(fresh ? IDLE : was),
213
+ status: "loading",
214
+ error: null,
215
+ }));
43
216
  if (waiting)
44
217
  return () => aborter.abort();
45
- const criteria = {
46
- ...JSON.parse(question),
47
- grouping: {
48
- group_by: levels.map((level) => ({ ...level })),
49
- ...(measured === ""
50
- ? {}
51
- : { measures: JSON.parse(measured) }),
52
- pagination: { limit: MAX_GROUPS },
53
- },
54
- // One id per group is the least a grouped answer carries; the rows come on opening.
55
- pagination: { limit: 1 },
56
- };
218
+ // As many groups as were on screen: a search does not undo the person's «more groups».
219
+ const shown = fresh ? 0 : now.current.root.buckets.length;
220
+ const measures = measuresNow();
221
+ const criteria = levelQuestion(JSON.parse(question), first, { limit: Math.max(groupPageSize, shown) }, { counted: true, ...(measures === undefined ? {} : { measures }) });
57
222
  transport.list(route, criteria, aborter.signal).then((page) => {
58
- if (aborter.signal.aborted)
223
+ if (generation.current.id !== id)
59
224
  return;
60
225
  // Records answered to a grouped question are not groups: the list's failure, never a
61
226
  // table drawing piles without a count.
62
- if (!areGroups(page.rows))
63
- setState({ status: "failed", buckets: [], error: new NotGrouped(route) });
64
- else
65
- setState({ status: "ready", buckets: page.rows, error: null });
227
+ if (!isGroupedAnswer(page)) {
228
+ setRoot({ ...IDLE, status: "failed", error: new NotGrouped(route) });
229
+ return;
230
+ }
231
+ const buckets = page.rows;
232
+ setRoot({
233
+ status: "ready",
234
+ buckets,
235
+ error: null,
236
+ groupsCount: page.groupsCount ?? null,
237
+ records: page.count?.value ?? null,
238
+ });
239
+ arrived.current(buckets, []);
66
240
  }, (error) => {
67
- if (!aborter.signal.aborted)
68
- setState({ status: "failed", buckets: [], error });
241
+ if (generation.current.id === id)
242
+ setRoot({ ...IDLE, status: "failed", error });
69
243
  });
70
244
  return () => aborter.abort();
71
- }, [transport, route, question, levels, measured, waiting, context, writes]);
72
- /** One page of a group: the first (`after` null) or the one the cursor points at. */
73
- const read = useCallback((bucket, after) => {
74
- const key = keyOf(bucket);
75
- if (reading.current.has(key))
245
+ // `listing.question` is read through `question`, its content.
246
+ // eslint-disable-next-line react-hooks/exhaustive-deps
247
+ }, [transport, route, question, split, measured, waiting, context, writes, groupPageSize]);
248
+ /** The first page of the root, more of it: offset past what is in hand. */
249
+ const moreRoot = () => {
250
+ const first = levels[0];
251
+ const tag = "level:[]";
252
+ if (first === undefined || root.status !== "ready" || inFlight.current.has(tag))
76
253
  return;
77
- reading.current.add(key);
78
- const { grouping: _grouping, pagination: _pagination, ...own } = bucket.criteria;
79
- const first = { ...own, pagination: { limit: pageSize } };
80
- void transport.list(route, after === null ? first : resumingFrom(first, after)).then((page) => {
81
- reading.current.delete(key);
82
- setRows((now) => {
83
- const before = after === null ? [] : (now.get(key)?.rows ?? []);
84
- return new Map(now).set(key, {
85
- rows: [...before, ...page.rows],
86
- after: page.cursor,
87
- });
88
- });
254
+ if (!nextGroups(root.buckets.length, root.groupsCount, groupPageSize))
255
+ return;
256
+ inFlight.current.add(tag);
257
+ const { id, signal } = generation.current;
258
+ const measures = measuresNow();
259
+ const criteria = levelQuestion(JSON.parse(question), first, { limit: groupPageSize, offset: root.buckets.length }, measures === undefined ? {} : { measures });
260
+ setRoot((was) => ({ ...was, status: "loading" }));
261
+ transport.list(route, criteria, signal).then((page) => {
262
+ inFlight.current.delete(tag);
263
+ if (generation.current.id !== id)
264
+ return;
265
+ if (!areGroups(page.rows)) {
266
+ setRoot((was) => ({ ...was, status: "failed", error: new NotGrouped(route) }));
267
+ return;
268
+ }
269
+ const arriving = page.rows;
270
+ setRoot((was) => ({
271
+ ...was,
272
+ status: "ready",
273
+ buckets: [...was.buckets, ...arriving],
274
+ groupsCount: page.groupsCount ?? was.groupsCount,
275
+ }));
276
+ arrived.current(arriving, []);
89
277
  }, (error) => {
90
- reading.current.delete(key);
91
- setState((now) => ({ ...now, error }));
278
+ inFlight.current.delete(tag);
279
+ if (generation.current.id === id)
280
+ setRoot((was) => ({ ...was, status: "ready", error }));
92
281
  });
93
- }, [transport, route, pageSize]);
94
- const open = useCallback((bucket) => read(bucket, null), [read]);
95
- const readOf = (bucket) => rows.get(keyOf(bucket));
282
+ };
283
+ const isDeepest = (bucket) => pathOf(bucket).length >= levels.length;
284
+ const levelOf = (bucket) => below.get(keyOf(pathOf(bucket)));
285
+ const readOf = (bucket) => rows.get(keyOf(pathOf(bucket)));
96
286
  const hasMore = (bucket) => {
97
- const now = readOf(bucket);
98
- return now !== undefined && now.after !== null && now.rows.length < maxRows;
287
+ const read = readOf(bucket);
288
+ return read !== undefined && read.after !== null && read.rows.length < maxRows;
289
+ };
290
+ const open = (bucket) => {
291
+ const path = pathOf(bucket);
292
+ const key = keyOf(path);
293
+ if (!opened.has(key))
294
+ setOpened((was) => new Set(was).add(key));
295
+ // Read once; a reading that failed is tried again when the group is opened again.
296
+ const unread = (read) => read === undefined || (read.error !== null && read.error !== undefined);
297
+ if (isDeepest(bucket)) {
298
+ if (unread(rows.get(key)))
299
+ readRows(bucket, path, "first");
300
+ }
301
+ else if (unread(below.get(key)))
302
+ readLevel(bucket, path, "first");
303
+ };
304
+ const close = (bucket) => {
305
+ const key = keyOf(pathOf(bucket));
306
+ setOpened((was) => {
307
+ if (!was.has(key))
308
+ return was;
309
+ const next = new Set(was);
310
+ next.delete(key);
311
+ return next;
312
+ });
99
313
  };
100
314
  return {
101
315
  levels,
102
316
  group: setLevels,
103
- ...state,
104
- capped: state.buckets.length >= MAX_GROUPS,
317
+ status: root.status,
318
+ buckets: root.buckets,
319
+ error: root.error,
320
+ groupsCount: root.groupsCount,
321
+ records: root.records,
322
+ capped: nextGroups(root.buckets.length, root.groupsCount, groupPageSize) !== false &&
323
+ root.groupsCount !== null,
324
+ moreGroups: (parent) => {
325
+ if (parent === null)
326
+ return moreRoot();
327
+ const level = levelOf(parent);
328
+ if (level === undefined || level.reading)
329
+ return;
330
+ if (!nextGroups(level.buckets.length, level.count, groupPageSize))
331
+ return;
332
+ readLevel(parent, pathOf(parent), "more");
333
+ },
334
+ bringsGroups: (parent) => {
335
+ if (parent === null)
336
+ return root.status === "idle" || root.status === "failed"
337
+ ? undefined
338
+ : nextGroups(root.buckets.length, root.groupsCount, groupPageSize);
339
+ const level = levelOf(parent);
340
+ return level === undefined
341
+ ? undefined
342
+ : nextGroups(level.buckets.length, level.count, groupPageSize);
343
+ },
344
+ isDeepest,
345
+ isOpen: (bucket) => opened.has(keyOf(pathOf(bucket))),
105
346
  open,
106
- rowsOf: (bucket) => readOf(bucket)?.rows,
347
+ close,
348
+ toggle: (bucket) => (opened.has(keyOf(pathOf(bucket))) ? close(bucket) : open(bucket)),
349
+ groupsOf: (bucket) => {
350
+ const level = levelOf(bucket);
351
+ // Still unread: nothing to draw yet — a group never opens onto an empty level.
352
+ return level === undefined || (level.buckets.length === 0 && level.count === null)
353
+ ? undefined
354
+ : level.buckets;
355
+ },
356
+ groupsCountOf: (bucket) => levelOf(bucket)?.count,
357
+ rowsOf: (bucket) => {
358
+ const read = readOf(bucket);
359
+ // Unread until the first page answered: a group that failed holds no rows.
360
+ return read === undefined || (read.rows.length === 0 && read.reading)
361
+ ? undefined
362
+ : read.rows;
363
+ },
107
364
  more: (bucket) => {
108
- const now = readOf(bucket);
109
- if (now !== undefined && hasMore(bucket))
110
- read(bucket, now.after);
365
+ if (hasMore(bucket))
366
+ readRows(bucket, pathOf(bucket), "more");
111
367
  },
112
368
  hasMore,
113
369
  brings: (bucket) => {
114
- const now = readOf(bucket);
115
- if (now === undefined)
370
+ const read = readOf(bucket);
371
+ if (read === undefined)
116
372
  return undefined;
117
373
  if (!hasMore(bucket))
118
374
  return false;
119
- const left = Math.min(maxRows, bucket.count) - now.rows.length;
375
+ const left = Math.min(maxRows, bucket.count) - read.rows.length;
120
376
  return Math.max(0, Math.min(pageSize, left));
121
377
  },
378
+ errorOf: (bucket) => (isDeepest(bucket) ? readOf(bucket) : levelOf(bucket))?.error ?? null,
122
379
  };
123
380
  }
@@ -80,6 +80,16 @@ export type Listing<T, C extends CommandBodies = CommandBodies> = {
80
80
  resize: (size: number) => void;
81
81
  /** `more` mode reached its ceiling: refine the search instead of loading on. */
82
82
  capped: boolean;
83
+ /**
84
+ * Stops reading its rows while another reading answers for the same set — the list grouped
85
+ * (`useGroups` asks the groups, and each group its own rows): `hold(true)`. The question on
86
+ * screen keeps following the search, the filter and the order, so the groups ask the right
87
+ * one; `hold(false)` reads it once, if it changed meanwhile.
88
+ *
89
+ * Context: grouped, the list kept asking its ungrouped page under the groups on every
90
+ * narrowing — a request whose answer nobody drew.
91
+ */
92
+ hold: (on: boolean) => void;
83
93
  };
84
94
  /**
85
95
  * - `pages`: one page on screen at a time, walked by the server's own cursor (keyset — no
@@ -50,11 +50,18 @@ export function useListing(given, own = {}) {
50
50
  // kept, never a reading started over.
51
51
  const writes = useWrites(route);
52
52
  const askedFor = useRef({ context, writes });
53
+ // Held while another reading answers for the set (`hold`): what would have been asked is only
54
+ // marked, and asked once when the hold ends.
55
+ const held = useRef(false);
56
+ const stale = useRef(false);
53
57
  useEffect(() => {
54
58
  if (askedFor.current.context === context && askedFor.current.writes === writes)
55
59
  return;
56
60
  askedFor.current = { context, writes };
57
- void reading.reload();
61
+ if (held.current)
62
+ stale.current = true;
63
+ else
64
+ void reading.reload();
58
65
  }, [context, writes, reading]);
59
66
  const narrowed = (next) => {
60
67
  let criteria = base;
@@ -72,7 +79,10 @@ export function useListing(given, own = {}) {
72
79
  const refine = useCallback((next) => {
73
80
  // Another question starts on its first page: a cursor belongs to one order and one filter.
74
81
  setCursors([null]);
75
- void reading.refine(narrowed(next));
82
+ if (held.current)
83
+ stale.current = true;
84
+ else
85
+ void reading.refine(narrowed(next));
76
86
  },
77
87
  // `base` is the caller's literal: its identity changes every render, its content does not.
78
88
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -118,6 +128,16 @@ export function useListing(given, own = {}) {
118
128
  else
119
129
  refine(next);
120
130
  };
131
+ // Stable: a screen holds it from an effect, and reads only refs.
132
+ const hold = useCallback((on) => {
133
+ if (held.current === on)
134
+ return;
135
+ held.current = on;
136
+ if (on || !stale.current)
137
+ return;
138
+ stale.current = false;
139
+ latest.current(now.current);
140
+ }, []);
121
141
  return {
122
142
  entity,
123
143
  ...(definition === undefined ? {} : { definition }),
@@ -168,5 +188,6 @@ export function useListing(given, own = {}) {
168
188
  narrow({ size: rows }, false);
169
189
  },
170
190
  capped,
191
+ hold,
171
192
  };
172
193
  }
@@ -282,6 +282,8 @@ export function EntityList({ listing, api, columns: askedColumns, cells, yesNo,
282
282
  elsewhere.join(),
283
283
  openingIn === undefined,
284
284
  dateStyle,
285
+ // The tags' colours: a new map of tones redraws the table's cells, as it does the sheet's.
286
+ look.tones,
285
287
  ]);
286
288
  // A state the application gave colours to is the row's tag — and not again among its facts.
287
289
  const stateField = summaryFieldsOf(meta, {}, listing.entity.summary).state;
@@ -325,7 +327,12 @@ export function EntityList({ listing, api, columns: askedColumns, cells, yesNo,
325
327
  id: column.id,
326
328
  header: String(column.header),
327
329
  ...(column.numeric === true ? { numeric: true } : {}),
328
- })), [shown]);
330
+ // A state in a toned tag, as the table draws it — not a painted cell, which is how
331
+ // a sheet marks a value out of range.
332
+ ...(look.tones?.[column.id] === undefined
333
+ ? {}
334
+ : { look: "tag" }),
335
+ })), [shown, look.tones]);
329
336
  const sortStates = useMemo(() => listing.order.map((one) => ({
330
337
  key: one.field,
331
338
  direction: one.descending ? "desc" : "asc",
@@ -369,9 +376,10 @@ export function EntityList({ listing, api, columns: askedColumns, cells, yesNo,
369
376
  };
370
377
  const cardOfRow = cardFrom(look.card);
371
378
  const tileOfRow = cardFrom(look.tile, "tile");
372
- // Grouped: the SERVER counts the groups; a group's rows are read when it is opened, so every
373
- // group starts closed. Every face of web-ui (1.4) draws these piles, the table included, and
374
- // each says what its next «more» brings (1.5).
379
+ // Grouped: the SERVER counts the groups, a page of them at a time; a level below and a group's
380
+ // rows are read when it is opened, so every group starts closed. Every face of web-ui (1.4)
381
+ // draws these piles, the table included; each says what its next «more» brings (1.5), and a
382
+ // level that holds fewer groups than it counts offers the next page of them (2.19).
375
383
  const groups = useGroups(listing, sums === undefined ? {} : { sums: sums || [] });
376
384
  const grouped = groups.levels.length > 0;
377
385
  // A table and a sheet say a group's sums under their columns (web-ui 2.9): beside the group's
@@ -382,24 +390,20 @@ export function EntityList({ listing, api, columns: askedColumns, cells, yesNo,
382
390
  ? []
383
391
  : [column.field])
384
392
  : []);
385
- const { piles, bucketAt } = pilesOf(groups.buckets, groups.levels, meta, locale, groups.rowsOf, groups.brings, underColumns);
386
- const [opened, setOpened] = useState(() => new Set());
387
- useEffect(() => setOpened(new Set()), [groups.buckets]);
388
- const collapsed = [...bucketAt.keys()].filter((key) => !opened.has(key));
393
+ const { piles, bucketAt } = pilesOf(groups.buckets, groups.levels, meta, locale, groups.rowsOf, groups.brings, underColumns, groups);
394
+ // What is open is the groups' (it survives a search); a group above another is drawn open
395
+ // only once its level arrived — an empty open group would read as one with no rows.
396
+ const collapsed = [...bucketAt].flatMap(([key, bucket]) => groups.isOpen(bucket) &&
397
+ (groups.isDeepest(bucket) || groups.groupsOf(bucket) !== undefined)
398
+ ? []
399
+ : [key]);
389
400
  const toggle = (key) => {
390
- const next = new Set(opened);
391
- if (next.has(key))
392
- next.delete(key);
393
- else {
394
- next.add(key);
395
- const bucket = bucketAt.get(key);
396
- const deepest = bucket !== undefined && (bucket.groups ?? []).length === 0;
397
- if (deepest && groups.rowsOf(bucket) === undefined)
398
- groups.open(bucket);
399
- }
400
- setOpened(next);
401
+ const bucket = bucketAt.get(key);
402
+ if (bucket !== undefined)
403
+ groups.toggle(bucket);
401
404
  };
402
405
  const failure = grouped && groups.status === "failed" ? explain(groups.error) : grouped ? null : failed;
406
+ const morePiles = groups.bringsGroups(null);
403
407
  const grouping = grouped
404
408
  ? {
405
409
  group: {
@@ -414,10 +418,22 @@ export function EntityList({ listing, api, columns: askedColumns, cells, yesNo,
414
418
  if (bucket !== undefined)
415
419
  groups.more(bucket);
416
420
  },
421
+ // «Ver N grupos más» after the last group of a level: the first level, or the one
422
+ // under an open group — counted by the server (`groups_count`).
423
+ ...(groups.groupsCount === null ? {} : { pilesCount: groups.groupsCount }),
424
+ ...(morePiles === undefined ? {} : { morePiles }),
425
+ onMorePiles: (parent) => {
426
+ if (parent === null)
427
+ return groups.moreGroups(null);
428
+ const bucket = bucketAt.get(pathKey(parent.path));
429
+ if (bucket !== undefined)
430
+ groups.moreGroups(bucket);
431
+ },
417
432
  },
418
433
  }
419
434
  : {};
420
- const records = groups.buckets.reduce((sum, bucket) => sum + bucket.count, 0);
435
+ // How many groups and records the SERVER counted — never the sum of the groups in hand.
436
+ const records = groups.records ?? groups.buckets.reduce((sum, bucket) => sum + bucket.count, 0);
421
437
  // The foot adds up what the model says adds up (`total`) — over the rows in hand, never a
422
438
  // grouped set (each group says its own, counted by the server). While the rows are not the
423
439
  // whole set the list says the figures are this page's (`pageTotals`): the server's total over
@@ -456,9 +472,7 @@ export function EntityList({ listing, api, columns: askedColumns, cells, yesNo,
456
472
  // The way through the set. Inside a record or a panel, only while there is more than what is
457
473
  // on screen: «1–5 / 5» repeats the rows.
458
474
  const fits = embedded && !partial;
459
- const through = grouped ? (groups.status !== "ready" ? null : (_jsx("span", { className: "text-meta text-muted", children: groups.capped
460
- ? copy.groupsCapped(groups.buckets.length)
461
- : copy.groups(groups.buckets.length, records) }))) : fits ? null : listing.paging === "pages" ? (page.from === 0 ? null : (_jsx(Pagination, { from: page.from, to: page.to, total: count?.value ?? page.to,
475
+ const through = grouped ? (groups.status !== "ready" ? null : (_jsx("span", { className: "text-meta text-muted", children: copy.groups(groups.groupsCount ?? groups.buckets.length, records) }))) : fits ? null : listing.paging === "pages" ? (page.from === 0 ? null : (_jsx(Pagination, { from: page.from, to: page.to, total: count?.value ?? page.to,
462
476
  /* The range is touched to choose how many rows fit — in both styles. Without these two
463
477
  the modern pill and the plain range drew a size nobody could change. */
464
478
  pageSize: page.size, onPageSizeChange: listing.resize, ...(page.hasPrev ? { onPrev: listing.prev } : {}), ...(page.hasNext ? { onNext: listing.next } : {}) }))) : (_jsxs(_Fragment, { children: [count === null ? null : (_jsx("span", { className: "text-meta text-muted", children: copy.shown(listing.rows.length, count.value, count.exact) })), listing.capped ? (_jsx("span", { className: "text-meta text-muted", children: copy.capped(listing.rows.length) })) : listing.hasMore ? (_jsx(Button, { size: "sm", role: "secondary", disabled: listing.status === "loadingMore", onClick: listing.more, children: listing.status === "loadingMore" ? copy.loading : copy.loadMore })) : null] }));
@@ -496,11 +510,23 @@ export function EntityList({ listing, api, columns: askedColumns, cells, yesNo,
496
510
  // Emptied (or cleared with ×): the whole set again, at once.
497
511
  if (next === "" && listing.text !== "")
498
512
  listing.search("", { now: true });
499
- }, onSubmit: (text) => listing.search(text, { now: true }), placeholder: copy.search, "aria-label": copy.search }) })) : null, started.drawn === null ? null : (_jsxs(List.Actions, { children: [started.drawn, creating === undefined ? null : (_jsx(Button, { role: "primary", size: "sm", onClick: creating, children: frameworkCopy().record.create }))] })), startDock.length === 0 && forChosen.dock.length === 0 ? null : (_jsx(List.Dock, { ...(startDock.length === 0 ? {} : { actions: startDock }), ...(forChosen.dock.length === 0 ? {} : { selection: forChosen.dock }) })), paging === null ? null : _jsx(List.Pagination, { children: paging })] }), views.includes("table") ? (_jsx(List.Table, { columns: shown, ...(totalled ? { totals: true } : {}), ...(rowActions === undefined ? {} : { rowActions }), ...(reorder.move === undefined ? {} : { onReorder: reorder.move }) })) : null, _jsx(List.Rows, { row: rowOf }), views.includes("sheet") ? (_jsx(List.Sheet, { columns: sheetColumns, cell: (row, column) => {
513
+ }, onSubmit: (text) => listing.search(text, { now: true }), placeholder: copy.search, "aria-label": copy.search }) })) : null, started.drawn === null ? null : (_jsxs(List.Actions, { children: [started.drawn, creating === undefined ? null : (_jsx(Button, { role: "primary", size: "sm", onClick: creating, children: frameworkCopy().record.create }))] })), startDock.length === 0 && forChosen.dock.length === 0 ? null : (_jsx(List.Dock, { ...(startDock.length === 0 ? {} : { actions: startDock }), ...(forChosen.dock.length === 0 ? {} : { selection: forChosen.dock }) })), paging === null ? null : _jsx(List.Pagination, { children: paging })] }), views.includes("table") ? (_jsx(List.Table, { columns: shown, ...(totalled ? { totals: true } : {}), ...(rowActions === undefined ? {} : { rowActions }), ...(reorder.move === undefined ? {} : { onReorder: reorder.move }) })) : null, _jsx(List.Rows, { row: rowOf }), views.includes("sheet") ? (_jsx(List.Sheet, {
514
+ // The set comes in pages (50 by default): the sheet grows with its page, as the table
515
+ // does, instead of web-ui's fixed box — which suits a sheet of thousands, not a page.
516
+ height: "auto", columns: sheetColumns, cell: (row, column) => {
500
517
  const value = row[column.id];
501
518
  return value === null || value === undefined
502
519
  ? null
503
520
  : (textOf(meta, column.id, value, locale) ?? String(value));
521
+ },
522
+ // The tones the application gave its choices (`presented(entity, { tones })`): the
523
+ // same colour a state has in the table, the record and its tag.
524
+ tone: (row, column) => {
525
+ const tones = look.tones?.[column.id];
526
+ const value = row[column.id];
527
+ return tones === undefined || value === null || value === undefined
528
+ ? undefined
529
+ : (tones[String(value)] ?? "neutral");
504
530
  } })) : null, views.includes("pivot") ? (_jsx(List.Pivot, { folded: folded ??
505
531
  pivotOf({
506
532
  crossed: [],