@svgrid/grid 3.0.4 → 3.0.5

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.
Files changed (77) hide show
  1. package/README.md +4 -4
  2. package/dist/SvGrid.controller.svelte.d.ts +12 -2
  3. package/dist/SvGrid.controller.svelte.js +192 -8
  4. package/dist/SvGrid.css +73 -0
  5. package/dist/SvGrid.svelte +128 -3
  6. package/dist/SvGrid.types.d.ts +356 -3
  7. package/dist/build-api.js +11 -6
  8. package/dist/cdn/{GridMenus-BL7ZgQvU.js → GridMenus-CID62rlI.js} +11 -11
  9. package/dist/cdn/{GridMenus-7kbpnnBW.js → GridMenus-DLL-qZeu.js} +11 -11
  10. package/dist/cdn/server-block-cache-CGoWz-87.js +237 -0
  11. package/dist/cdn/{src-BKhZ6eXd.js → src-Bklofsad.js} +8818 -8798
  12. package/dist/cdn/{src-V1uu8iE9.js → src-jcFMkBnN.js} +4282 -4262
  13. package/dist/cdn/svgrid.js +27 -26
  14. package/dist/cdn/svgrid.svelte-external.js +27 -26
  15. package/dist/cdn/validate-C7Rn_Bns.js +76 -0
  16. package/dist/core.js +36 -13
  17. package/dist/editing.js +10 -0
  18. package/dist/gantt-view.svelte.d.ts +24 -0
  19. package/dist/gantt-view.svelte.js +13 -0
  20. package/dist/grid-icons.d.ts +2 -2
  21. package/dist/grid-icons.js +2 -2
  22. package/dist/grid-messages.d.ts +6 -0
  23. package/dist/grid-messages.js +5 -0
  24. package/dist/index.d.ts +5 -4
  25. package/dist/index.js +3 -3
  26. package/dist/row-model.d.ts +133 -0
  27. package/dist/row-model.js +16 -0
  28. package/dist/selection.d.ts +2 -1
  29. package/dist/selection.js +30 -2
  30. package/dist/server-block-cache.d.ts +214 -0
  31. package/dist/server-block-cache.js +531 -0
  32. package/dist/server-data-source.d.ts +240 -6
  33. package/dist/server-data-source.js +220 -20
  34. package/dist/server.d.ts +13 -0
  35. package/dist/server.js +13 -0
  36. package/dist/validate.d.ts +4 -0
  37. package/dist/validate.js +21 -3
  38. package/package.json +6 -1
  39. package/src/SvGrid.controller.svelte.ts +191 -8
  40. package/src/SvGrid.css +73 -0
  41. package/src/SvGrid.svelte +128 -3
  42. package/src/SvGrid.types.ts +376 -3
  43. package/src/build-api.ts +11 -4
  44. package/src/core.rowmodel-cache.test.ts +51 -0
  45. package/src/core.ts +33 -12
  46. package/src/editing.ts +8 -0
  47. package/src/gantt-stub.test.svelte +38 -0
  48. package/src/gantt-view.svelte.ts +35 -0
  49. package/src/grid-icons.ts +2 -2
  50. package/src/grid-messages.ts +12 -0
  51. package/src/icon-seam.test.ts +2 -4
  52. package/src/index.ts +36 -10
  53. package/src/row-model.ts +146 -0
  54. package/src/selection.test.ts +3 -0
  55. package/src/selection.ts +32 -2
  56. package/src/server-block-cache.test.ts +645 -0
  57. package/src/server-block-cache.ts +677 -0
  58. package/src/server-data-source.infinite.test.ts +343 -0
  59. package/src/server-data-source.ts +450 -27
  60. package/src/server.ts +47 -0
  61. package/src/svgrid.gantt-seam.test.ts +199 -0
  62. package/src/svgrid.row-model-prop.svelte.test.ts +352 -0
  63. package/src/svgrid.row-model-seam.svelte.test.ts +289 -0
  64. package/src/svgrid.upsell-license.test.ts +7 -4
  65. package/src/validate.test.ts +29 -0
  66. package/src/validate.ts +28 -3
  67. package/dist/SvGroupCell.svelte +0 -141
  68. package/dist/SvGroupCell.svelte.d.ts +0 -49
  69. package/dist/SvRowGroupPanel.svelte +0 -186
  70. package/dist/SvRowGroupPanel.svelte.d.ts +0 -25
  71. package/dist/cdn/validate-_CDJzgIo.js +0 -75
  72. package/dist/server-group-model.d.ts +0 -98
  73. package/dist/server-group-model.js +0 -263
  74. package/src/SvGroupCell.svelte +0 -141
  75. package/src/SvRowGroupPanel.svelte +0 -186
  76. package/src/server-group-model.test.ts +0 -294
  77. package/src/server-group-model.ts +0 -370
@@ -1,141 +0,0 @@
1
- <!--
2
- Built-in group cell for the server-side group/tree model. Drop it into the
3
- grouping column and it draws the expander + indentation for group rows (and an
4
- indented leaf value) - no hand-written cell recipe. Pair with `serverGroupRows`
5
- to feed `<SvGrid data>`, and wire `onToggle` to the controller's `toggleGroup`.
6
-
7
- cell: (ctx) => renderComponent(SvGroupCell, {
8
- row: ctx.row.original, onToggle: ctl.toggleGroup, leafField: 'name',
9
- })
10
- -->
11
- <script lang="ts" generics="TData">
12
- import type { ServerDisplayRow } from './server-data-source'
13
- import type { GridIcons } from './grid-icons'
14
-
15
- type GroupGridRow = { __group?: ServerDisplayRow<TData> } & Record<string, unknown>
16
- type Props = {
17
- /** The grid row from `serverGroupRows` (carries the `__group` marker). */
18
- row: GroupGridRow
19
- /**
20
- * Expand / collapse a group, or load more children. Receives the grid row;
21
- * wire to `serverGroupNav(ctl).onToggle` (which drives clicks and keyboard).
22
- */
23
- onToggle: (row: GroupGridRow) => void
24
- /** Field to show for leaf rows in the group column (blank if omitted). */
25
- leafField?: string
26
- /** Pixels of indentation per level. Default 18. */
27
- indent?: number
28
- /**
29
- * Icon overrides, the same map `<SvGrid icons>` takes. Only
30
- * `chevron-right` is drawn here. You mount this component yourself, so it
31
- * cannot inherit the grid's icons - pass the same object to both to keep
32
- * the expander consistent with the rest of the chrome.
33
- */
34
- icons?: GridIcons
35
- }
36
-
37
- let { row, onToggle, leafField, indent = 18, icons }: Props = $props()
38
- const chevron = $derived(icons?.['chevron-right'])
39
- const meta = $derived(row.__group)
40
- </script>
41
-
42
- {#if meta && meta.kind === 'group'}
43
- <button
44
- type="button"
45
- class="sv-group-cell"
46
- style={`padding-inline-start: ${meta.level * indent}px`}
47
- aria-expanded={meta.expanded}
48
- aria-label={meta.expanded ? 'Collapse group' : 'Expand group'}
49
- onclick={() => onToggle(row)}
50
- >
51
- <!-- Same chevron the grid's own expanders and SvTree draw, so every
52
- expander in the library looks identical. -->
53
- <span class="sv-group-chev" class:open={meta.expanded} aria-hidden="true">
54
- {#if chevron}
55
- {@render chevron()}
56
- {:else}
57
- <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor"
58
- stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6" /></svg>
59
- {/if}
60
- </span>
61
- <span class="sv-group-key">{meta.key}</span>
62
- {#if meta.loading}<span class="sv-group-load" aria-hidden="true">…</span>{/if}
63
- </button>
64
- {:else if meta && meta.kind === 'more'}
65
- <button
66
- type="button"
67
- class="sv-group-more"
68
- style={`padding-inline-start: ${meta.level * indent}px`}
69
- disabled={meta.loading}
70
- onclick={() => onToggle(row)}
71
- >
72
- {meta.loading ? 'Loading...' : `Load ${meta.remaining} more`}
73
- </button>
74
- {:else if meta && meta.kind === 'footer'}
75
- <span class="sv-group-footer" style={`padding-inline-start: ${meta.level * indent}px`}>Total</span>
76
- {:else if meta && meta.kind === 'skeleton'}
77
- <span class="sv-group-skeleton" style={`margin-inline-start: ${meta.level * indent}px`} aria-hidden="true"></span>
78
- {:else if meta}
79
- <span class="sv-group-leaf" style={`padding-inline-start: ${(meta.level + 1) * indent}px`}>
80
- {leafField ? (row[leafField] ?? '') : ''}
81
- </span>
82
- {/if}
83
-
84
- <style>
85
- .sv-group-cell {
86
- display: inline-flex;
87
- align-items: center;
88
- gap: 6px;
89
- background: none;
90
- border: 0;
91
- padding: 0;
92
- font: inherit;
93
- color: inherit;
94
- cursor: pointer;
95
- }
96
- .sv-group-chev {
97
- display: inline-flex;
98
- align-items: center;
99
- justify-content: center;
100
- width: 12px;
101
- height: 12px;
102
- transition: transform 0.15s;
103
- color: var(--sg-muted, #64748b);
104
- }
105
- /* An `icons` override renders inside this wrapper, and this style block is
106
- scoped, so its markup needs :global() to be reached. Sizing it here means
107
- a custom chevron lands in the same box as the built-in and rotates with
108
- the wrapper rather than needing to know the rule exists. */
109
- .sv-group-chev :global(svg),
110
- .sv-group-chev :global(img) {
111
- width: 100%;
112
- height: 100%;
113
- display: block;
114
- }
115
- .sv-group-chev.open { transform: rotate(90deg); }
116
- .sv-group-key { font-weight: 600; }
117
- .sv-group-load { color: var(--sg-muted, #64748b); font-size: 12px; }
118
- .sv-group-leaf { color: var(--sg-muted, #475569); }
119
- .sv-group-more {
120
- background: none;
121
- border: 0;
122
- padding: 0;
123
- font: inherit;
124
- font-size: 13px;
125
- color: var(--sg-accent, #2563eb);
126
- cursor: pointer;
127
- }
128
- .sv-group-more:disabled { color: var(--sg-muted, #64748b); cursor: default; }
129
- .sv-group-footer { font-weight: 600; color: var(--sg-muted, #64748b); font-size: 12px; text-transform: uppercase; letter-spacing: 0.03em; }
130
- .sv-group-skeleton {
131
- display: inline-block;
132
- width: 60%;
133
- height: 10px;
134
- border-radius: 5px;
135
- background: linear-gradient(90deg, var(--sg-border, #e2e8f0) 25%, var(--sg-header-bg, #f1f5f9) 50%, var(--sg-border, #e2e8f0) 75%);
136
- background-size: 200% 100%;
137
- animation: sv-group-shimmer 1.2s infinite;
138
- }
139
- @keyframes sv-group-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
140
- @media (prefers-reduced-motion: reduce) { .sv-group-skeleton { animation: none; } }
141
- </style>
@@ -1,186 +0,0 @@
1
- <!--
2
- A row-group panel (like the "drag columns to group" bar in enterprise grids).
3
- Shows the current group-by columns as chips you can remove or drag to reorder,
4
- plus a "+ Group by" menu to add one. It is also a drop target: a column drag
5
- that carries `text/sv-column` (its column id) adds that column. Wire `onChange`
6
- to a server group model's `setGroupBy`, or to client grouping.
7
-
8
- <SvRowGroupPanel
9
- columns={[{ id: 'region', label: 'Region' }, { id: 'country', label: 'Country' }]}
10
- groupBy={view.groupBy}
11
- onChange={(g) => ctl.setGroupBy(g)}
12
- />
13
- -->
14
- <script lang="ts">
15
- import { GRID_ICON_GLYPHS, type GridIconName, type GridIcons } from './grid-icons'
16
-
17
- type Col = { id: string; label: string }
18
- type Props = {
19
- /** Columns that can be grouped on. */
20
- columns: Col[]
21
- /** Current group-by column ids, outer to inner. */
22
- groupBy: string[]
23
- /** Called with the new group-by order. */
24
- onChange: (groupBy: string[]) => void
25
- /** Text shown when nothing is grouped. */
26
- placeholder?: string
27
- /**
28
- * Icon overrides, the same map `<SvGrid icons>` takes. This panel draws
29
- * `drag-handle`, `remove` and `breadcrumb-separator`. You mount it
30
- * yourself, so pass the same object you gave the grid to keep them
31
- * consistent.
32
- */
33
- icons?: GridIcons
34
- }
35
- let { columns, groupBy, onChange, placeholder = 'Drag a column here to group by it', icons }: Props = $props()
36
-
37
- const labelOf = (id: string) => columns.find((c) => c.id === id)?.label ?? id
38
- const available = $derived(columns.filter((c) => !groupBy.includes(c.id)))
39
-
40
- let dragIndex = $state<number | null>(null)
41
-
42
- function remove(id: string) {
43
- onChange(groupBy.filter((g) => g !== id))
44
- }
45
- function add(id: string) {
46
- if (id && !groupBy.includes(id)) onChange([...groupBy, id])
47
- }
48
- function reorder(to: number) {
49
- if (dragIndex === null || dragIndex === to) return
50
- const next = [...groupBy]
51
- const [moved] = next.splice(dragIndex, 1)
52
- next.splice(to, 0, moved!)
53
- dragIndex = null
54
- onChange(next)
55
- }
56
- function onPanelDrop(e: DragEvent) {
57
- const id = e.dataTransfer?.getData('text/sv-column')
58
- if (id) add(id)
59
- }
60
- /** Keyboard equivalent of dragging a chip: moves the chip at `i` one slot earlier/later,
61
- * reusing `reorder()` (via `dragIndex`) so there is a single source of truth for the move. */
62
- function moveByKeyboard(i: number, delta: number) {
63
- const to = i + delta
64
- if (to < 0 || to >= groupBy.length) return
65
- dragIndex = i
66
- reorder(to)
67
- }
68
- function onChipKeydown(e: KeyboardEvent, i: number) {
69
- if (!e.altKey) return
70
- if (e.key === 'ArrowLeft') {
71
- e.preventDefault()
72
- moveByKeyboard(i, -1)
73
- } else if (e.key === 'ArrowRight') {
74
- e.preventDefault()
75
- moveByKeyboard(i, 1)
76
- }
77
- }
78
- </script>
79
-
80
- <!-- Same override-or-default resolution SvGrid uses, kept local because this
81
- component is mounted by the consumer and never sees the grid's snippet. -->
82
- {#snippet ic(name: GridIconName)}
83
- {@const override = icons?.[name]}
84
- {#if override}{@render override()}{:else}{GRID_ICON_GLYPHS[name]}{/if}
85
- {/snippet}
86
-
87
- <div
88
- class="sv-rowgroup-panel"
89
- role="group"
90
- aria-label="Row groups"
91
- ondragover={(e) => e.preventDefault()}
92
- ondrop={onPanelDrop}
93
- >
94
- <span class="sv-rgp-label" aria-hidden="true">Group by:</span>
95
- {#if groupBy.length === 0}
96
- <span class="sv-rgp-empty">{placeholder}</span>
97
- {:else}
98
- {#each groupBy as id, i (id)}
99
- {#if i > 0}<span class="sv-rgp-sep" aria-hidden="true">{@render ic('breadcrumb-separator')}</span>{/if}
100
- <!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
101
- <span
102
- class="sv-rgp-chip"
103
- class:sv-rgp-chip-drag={dragIndex === i}
104
- role="group"
105
- tabindex="0"
106
- aria-label={`Grouped by ${labelOf(id)}, position ${i + 1} of ${groupBy.length}. Press Alt+Arrow keys to reorder.`}
107
- draggable="true"
108
- ondragstart={() => (dragIndex = i)}
109
- ondragend={() => (dragIndex = null)}
110
- ondragover={(e) => e.preventDefault()}
111
- ondrop={() => reorder(i)}
112
- onkeydown={(e) => onChipKeydown(e, i)}
113
- >
114
- <span class="sv-rgp-grip" aria-hidden="true">{@render ic('drag-handle')}</span>
115
- {labelOf(id)}
116
- <button type="button" class="sv-rgp-x" onclick={() => remove(id)} aria-label={`Stop grouping by ${labelOf(id)}`}>{@render ic('remove')}</button>
117
- </span>
118
- {/each}
119
- {/if}
120
- {#if available.length}
121
- <select
122
- class="sv-rgp-add"
123
- aria-label="Add a group column"
124
- onchange={(e) => { add(e.currentTarget.value); e.currentTarget.value = '' }}
125
- >
126
- <option value="">+ Group by</option>
127
- {#each available as c (c.id)}<option value={c.id}>{c.label}</option>{/each}
128
- </select>
129
- {/if}
130
- </div>
131
-
132
- <style>
133
- .sv-rowgroup-panel {
134
- display: flex;
135
- align-items: center;
136
- flex-wrap: wrap;
137
- gap: 6px;
138
- padding: 8px 10px;
139
- border: 1px dashed var(--sg-border, #cbd5e1);
140
- border-radius: 10px;
141
- background: var(--sg-header-bg, #f8fafc);
142
- font-size: 13px;
143
- }
144
- .sv-rgp-label { color: var(--sg-muted, #64748b); font-weight: 600; }
145
- .sv-rgp-empty { color: var(--sg-muted, #94a3b8); font-style: italic; }
146
- .sv-rgp-sep { color: var(--sg-muted, #94a3b8); }
147
- .sv-rgp-chip {
148
- display: inline-flex;
149
- align-items: center;
150
- gap: 6px;
151
- padding: 3px 6px 3px 8px;
152
- border-radius: 999px;
153
- background: var(--sg-bg, #fff);
154
- border: 1px solid var(--sg-border, #e2e8f0);
155
- cursor: grab;
156
- user-select: none;
157
- font-weight: 600;
158
- }
159
- .sv-rgp-chip-drag { opacity: 0.5; }
160
- .sv-rgp-grip { color: var(--sg-muted, #94a3b8); cursor: grab; }
161
- .sv-rgp-x {
162
- display: inline-flex;
163
- align-items: center;
164
- justify-content: center;
165
- width: 16px;
166
- height: 16px;
167
- border: 0;
168
- border-radius: 50%;
169
- background: none;
170
- color: var(--sg-muted, #64748b);
171
- cursor: pointer;
172
- font-size: 14px;
173
- line-height: 1;
174
- }
175
- .sv-rgp-x:hover { background: var(--sg-header-bg, #f1f5f9); color: var(--sg-fg, #0f172a); }
176
- .sv-rgp-add {
177
- font: inherit;
178
- font-size: 13px;
179
- padding: 4px 8px;
180
- border-radius: 8px;
181
- border: 1px solid var(--sg-border, #e2e8f0);
182
- background: var(--sg-bg, #fff);
183
- color: var(--sg-accent, #2563eb);
184
- cursor: pointer;
185
- }
186
- </style>
@@ -1,294 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
- import { createServerGroupModel } from './server-group-model'
3
- import type { ServerDataSource, ServerDisplayRow, ServerGroupRow } from './server-data-source'
4
-
5
- type Row = { country: string; city: string; amount: number }
6
-
7
- const DATA: Row[] = [
8
- { country: 'DE', city: 'Berlin', amount: 10 },
9
- { country: 'DE', city: 'Berlin', amount: 5 },
10
- { country: 'DE', city: 'Munich', amount: 7 },
11
- { country: 'FR', city: 'Paris', amount: 3 },
12
- ]
13
-
14
- /**
15
- * A fake backend that groups + aggregates DATA per the request's groupBy /
16
- * groupKeys, exactly as a real SQL GROUP BY would - returns group rows for a
17
- * group level and leaf rows at the bottom.
18
- */
19
- function makeGroupSource(data: Row[], delay = 0): ServerDataSource<Row> & { calls: number } {
20
- return {
21
- calls: 0,
22
- async getRows(req) {
23
- this.calls += 1
24
- if (delay) await new Promise((r) => setTimeout(r, delay))
25
- const subset = data.filter((r) =>
26
- req.groupKeys!.every((k, i) => String((r as Record<string, unknown>)[req.groupBy![i]!]) === k),
27
- )
28
- const level = req.groupKeys!.length
29
- if (level < req.groupBy!.length) {
30
- const field = req.groupBy![level]!
31
- const map = new Map<string, Record<string, unknown>>()
32
- for (const r of subset) {
33
- const key = String((r as Record<string, unknown>)[field])
34
- const agg = map.get(key) ?? { [field]: (r as Record<string, unknown>)[field] }
35
- for (const a of req.aggregations!) {
36
- const cur = (agg[a.col] as number) ?? 0
37
- agg[a.col] = a.fn === 'count' ? cur + 1 : cur + ((r as Record<string, unknown>)[a.col] as number)
38
- }
39
- map.set(key, agg)
40
- }
41
- const groups = [...map.values()]
42
- return { rows: groups.slice(req.startRow, req.endRow) as unknown as Row[], rowCount: groups.length }
43
- }
44
- return { rows: subset.slice(req.startRow, req.endRow), rowCount: subset.length }
45
- },
46
- }
47
- }
48
-
49
- const flush = () => new Promise((r) => setTimeout(r, 0))
50
- const groups = (rows: ServerDisplayRow<Row>[]) => rows.filter((r): r is ServerGroupRow<Row> => r.kind === 'group')
51
-
52
- describe('createServerGroupModel', () => {
53
- it('refresh() loads the top-level groups with aggregates', async () => {
54
- const src = makeGroupSource(DATA)
55
- let state = createServerGroupModel<Row>(src, {
56
- groupBy: ['country', 'city'],
57
- aggregations: [{ col: 'amount', fn: 'sum' }],
58
- onChange: (s) => (state = s as never),
59
- }).getState()
60
- const ctl = createServerGroupModel<Row>(src, {
61
- groupBy: ['country', 'city'],
62
- aggregations: [{ col: 'amount', fn: 'sum' }],
63
- onChange: (s) => (state = s as never),
64
- })
65
- ctl.refresh()
66
- await flush()
67
- const g = groups(state.displayRows)
68
- expect(g.map((r) => r.key)).toEqual(['DE', 'FR'])
69
- expect(g.every((r) => r.level === 0 && !r.expanded)).toBe(true)
70
- expect(g[0]!.aggregates.amount).toBe(22) // 10 + 5 + 7
71
- expect(g[1]!.aggregates.amount).toBe(3)
72
- })
73
-
74
- it('expanding a group lazily fetches and splices its child groups', async () => {
75
- const src = makeGroupSource(DATA)
76
- let state = { displayRows: [] as ServerDisplayRow<Row>[] } as never
77
- const ctl = createServerGroupModel<Row>(src, {
78
- groupBy: ['country', 'city'],
79
- aggregations: [{ col: 'amount', fn: 'sum' }],
80
- onChange: (s) => (state = s as never),
81
- })
82
- ctl.refresh()
83
- await flush()
84
- const callsBefore = src.calls
85
- ctl.expandGroup(['DE'])
86
- await flush()
87
- expect(src.calls).toBe(callsBefore + 1) // one fetch for DE's children
88
- const rows = (state as { displayRows: ServerDisplayRow<Row>[] }).displayRows
89
- // DE (expanded), Berlin, Munich, FR
90
- expect(rows.map((r) => (r.kind === 'group' ? r.key : 'leaf'))).toEqual(['DE', 'Berlin', 'Munich', 'FR'])
91
- const berlin = rows.find((r) => r.kind === 'group' && r.key === 'Berlin') as ServerGroupRow<Row>
92
- expect(berlin.level).toBe(1)
93
- expect(berlin.aggregates.amount).toBe(15) // 10 + 5
94
- })
95
-
96
- it('expanding a bottom-level group returns leaf rows', async () => {
97
- const src = makeGroupSource(DATA)
98
- let state = { displayRows: [] as ServerDisplayRow<Row>[] } as never
99
- const ctl = createServerGroupModel<Row>(src, {
100
- groupBy: ['country', 'city'],
101
- onChange: (s) => (state = s as never),
102
- })
103
- ctl.refresh()
104
- await flush()
105
- ctl.expandGroup(['DE'])
106
- await flush()
107
- ctl.expandGroup(['DE', 'Berlin'])
108
- await flush()
109
- const rows = (state as { displayRows: ServerDisplayRow<Row>[] }).displayRows
110
- const leaves = rows.filter((r) => r.kind === 'leaf')
111
- expect(leaves).toHaveLength(2) // the two Berlin rows
112
- expect(leaves.every((r) => r.level === 2)).toBe(true)
113
- })
114
-
115
- it('collapse removes the children again', async () => {
116
- const src = makeGroupSource(DATA)
117
- // Reads go through ctl.getState() below, so the change callback is a no-op.
118
- const ctl = createServerGroupModel<Row>(src, {
119
- groupBy: ['country', 'city'],
120
- onChange: () => {},
121
- })
122
- ctl.refresh()
123
- await flush()
124
- ctl.expandGroup(['DE'])
125
- await flush()
126
- ctl.collapseGroup(['DE'])
127
- const rows = ctl.getState().displayRows
128
- expect(rows.map((r) => (r.kind === 'group' ? r.key : 'leaf'))).toEqual(['DE', 'FR'])
129
- expect(ctl.isExpanded(['DE'])).toBe(false)
130
- })
131
-
132
- it('setFilter resets the tree and refetches from the top', async () => {
133
- const src = makeGroupSource(DATA)
134
- const ctl = createServerGroupModel<Row>(src, { groupBy: ['country'], onChange: () => {} })
135
- ctl.refresh()
136
- await flush()
137
- const before = src.calls
138
- ctl.setFilter({ global: 'x' })
139
- await flush()
140
- expect(src.calls).toBeGreaterThan(before)
141
- expect(ctl.getState().filterModel).toEqual({ global: 'x' })
142
- })
143
-
144
- it('a stale expand response is dropped after a reset (race safety)', async () => {
145
- const src = makeGroupSource(DATA, 20) // slow
146
- let state = { displayRows: [] as ServerDisplayRow<Row>[] } as never
147
- const ctl = createServerGroupModel<Row>(src, {
148
- groupBy: ['country', 'city'],
149
- onChange: (s) => (state = s as never),
150
- })
151
- ctl.refresh()
152
- await new Promise((r) => setTimeout(r, 30))
153
- ctl.expandGroup(['DE']) // in-flight, slow
154
- ctl.setGroupBy(['city']) // reset (bumps generation) before DE's children land
155
- await new Promise((r) => setTimeout(r, 60))
156
- const rows = (state as { displayRows: ServerDisplayRow<Row>[] }).displayRows
157
- // Regrouped by city at the top; no stale DE subtree leaked in.
158
- expect(rows.every((r) => r.level === 0)).toBe(true)
159
- expect(rows.some((r) => r.kind === 'group' && r.key === 'DE')).toBe(false)
160
- })
161
-
162
- it('pages a group\'s children in blocks (load more)', async () => {
163
- const data: Row[] = [
164
- { country: 'DE', city: 'B', amount: 1 },
165
- { country: 'DE', city: 'M', amount: 2 },
166
- { country: 'DE', city: 'H', amount: 3 },
167
- { country: 'DE', city: 'K', amount: 4 },
168
- ]
169
- const src = makeGroupSource(data)
170
- let state = { displayRows: [] as ServerDisplayRow<Row>[] } as never
171
- const ctl = createServerGroupModel<Row>(src, {
172
- groupBy: ['country'],
173
- pageSize: 2,
174
- onChange: (s) => (state = s as never),
175
- })
176
- ctl.refresh()
177
- await flush()
178
- ctl.expandGroup(['DE'])
179
- await flush()
180
- let rows = (state as { displayRows: ServerDisplayRow<Row>[] }).displayRows
181
- expect(rows.filter((r) => r.kind === 'leaf')).toHaveLength(2) // first block
182
- const more = rows.find((r) => r.kind === 'more')
183
- expect(more && more.kind === 'more' && more.remaining).toBe(2)
184
-
185
- ctl.loadMoreChildren(['DE'])
186
- await flush()
187
- rows = (state as { displayRows: ServerDisplayRow<Row>[] }).displayRows
188
- expect(rows.filter((r) => r.kind === 'leaf')).toHaveLength(4) // all loaded
189
- expect(rows.some((r) => r.kind === 'more')).toBe(false) // no more affordance
190
- })
191
-
192
- it('emits a subtotal footer row after an expanded group when groupFooters is on', async () => {
193
- const src = makeGroupSource(DATA)
194
- let state = { displayRows: [] as ServerDisplayRow<Row>[] } as never
195
- const ctl = createServerGroupModel<Row>(src, {
196
- groupBy: ['country', 'city'],
197
- aggregations: [{ col: 'amount', fn: 'sum' }],
198
- groupFooters: true,
199
- onChange: (s) => (state = s as never),
200
- })
201
- ctl.refresh()
202
- await flush()
203
- ctl.expandGroup(['DE'])
204
- await flush()
205
- const rows = (state as { displayRows: ServerDisplayRow<Row>[] }).displayRows
206
- const footers = rows.filter((r) => r.kind === 'footer')
207
- expect(footers).toHaveLength(1)
208
- expect(footers[0]!.kind === 'footer' && footers[0]!.key).toBe('DE')
209
- })
210
-
211
- it('shows skeleton rows while a group\'s first block is loading', async () => {
212
- const src = makeGroupSource(DATA, 20) // slow
213
- let state = { displayRows: [] as ServerDisplayRow<Row>[] } as never
214
- const ctl = createServerGroupModel<Row>(src, {
215
- groupBy: ['country', 'city'],
216
- skeletonRows: 3,
217
- onChange: (s) => (state = s as never),
218
- })
219
- ctl.refresh()
220
- await new Promise((r) => setTimeout(r, 35)) // root loaded
221
- ctl.expandGroup(['DE']) // fetch in flight -> synchronous emit with skeletons
222
- const loading = (state as { displayRows: ServerDisplayRow<Row>[] }).displayRows
223
- expect(loading.filter((r) => r.kind === 'skeleton')).toHaveLength(3)
224
- await new Promise((r) => setTimeout(r, 40)) // DE loads
225
- expect((state as { displayRows: ServerDisplayRow<Row>[] }).displayRows.some((r) => r.kind === 'skeleton')).toBe(false)
226
- })
227
- })
228
-
229
- type Node = { id: string; parentId: string | null; name: string; kids: boolean }
230
- const TREE: Node[] = [
231
- { id: '1', parentId: null, name: 'Root A', kids: true },
232
- { id: '2', parentId: null, name: 'Root B', kids: false },
233
- { id: '1a', parentId: '1', name: 'Child A1', kids: true },
234
- { id: '1b', parentId: '1', name: 'Child A2', kids: false },
235
- { id: '1a1', parentId: '1a', name: 'Leaf A1a', kids: false },
236
- ]
237
-
238
- /** A fake self-referential tree backend: return the children of the node at the end of groupKeys. */
239
- function makeTreeSource(nodes: Node[]): ServerDataSource<Node> & { calls: number } {
240
- return {
241
- calls: 0,
242
- async getRows(req) {
243
- this.calls += 1
244
- const parent = req.groupKeys!.length ? req.groupKeys![req.groupKeys!.length - 1] : null
245
- const children = nodes.filter((n) => (n.parentId ?? null) === (parent ?? null))
246
- return { rows: children, rowCount: children.length }
247
- },
248
- }
249
- }
250
-
251
- describe('createServerGroupModel - treeData', () => {
252
- const opts = (onChange: (s: unknown) => void) => ({
253
- treeData: true,
254
- getRowId: (n: Node) => n.id,
255
- hasChildren: (n: Node) => n.kids,
256
- onChange: onChange as never,
257
- })
258
- const nameOf = (r: ServerDisplayRow<Node>) => ('data' in r ? r.data.name : `(${r.kind})`)
259
-
260
- it('throws without getRowId/hasChildren', () => {
261
- expect(() => createServerGroupModel<Node>(makeTreeSource(TREE), { treeData: true, onChange: () => {} })).toThrow()
262
- })
263
-
264
- it('loads roots, marking expandable nodes as groups and leaves as leaves', async () => {
265
- const src = makeTreeSource(TREE)
266
- let state = { displayRows: [] as ServerDisplayRow<Node>[] } as never
267
- const ctl = createServerGroupModel<Node>(src, opts((s) => (state = s as never)))
268
- ctl.refresh()
269
- await flush()
270
- const rows = (state as { displayRows: ServerDisplayRow<Node>[] }).displayRows
271
- expect(rows.map((r) => [r.kind, nameOf(r)])).toEqual([
272
- ['group', 'Root A'], // kids: true
273
- ['leaf', 'Root B'], // kids: false
274
- ])
275
- })
276
-
277
- it('expanding a node fetches and splices its children by id path', async () => {
278
- const src = makeTreeSource(TREE)
279
- let state = { displayRows: [] as ServerDisplayRow<Node>[] } as never
280
- const ctl = createServerGroupModel<Node>(src, opts((s) => (state = s as never)))
281
- ctl.refresh()
282
- await flush()
283
- ctl.expandGroup(['1'])
284
- await flush()
285
- let rows = (state as { displayRows: ServerDisplayRow<Node>[] }).displayRows
286
- expect(rows.map(nameOf)).toEqual(['Root A', 'Child A1', 'Child A2', 'Root B'])
287
- // drill one more level: Child A1 -> Leaf A1a
288
- ctl.expandGroup(['1', '1a'])
289
- await flush()
290
- rows = (state as { displayRows: ServerDisplayRow<Node>[] }).displayRows
291
- expect(rows.map(nameOf)).toEqual(['Root A', 'Child A1', 'Leaf A1a', 'Child A2', 'Root B'])
292
- expect(rows.find((r) => nameOf(r) === 'Leaf A1a')!.level).toBe(2)
293
- })
294
- })