@svgrid/grid 3.0.4 → 3.0.6

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 (176) hide show
  1. package/README.md +32 -11
  2. package/dist/GridMenus.svelte +34 -4
  3. package/dist/SvGrid.controller.svelte.d.ts +33 -5
  4. package/dist/SvGrid.controller.svelte.js +397 -58
  5. package/dist/SvGrid.css +200 -2
  6. package/dist/SvGrid.svelte +350 -40
  7. package/dist/SvGrid.types.d.ts +433 -7
  8. package/dist/SvGridDropdown.svelte +20 -0
  9. package/dist/SvGridDropdown.svelte.d.ts +12 -0
  10. package/dist/SvModal.svelte +22 -0
  11. package/dist/SvModal.svelte.d.ts +7 -0
  12. package/dist/a11y/dismissable.d.ts +10 -0
  13. package/dist/a11y/dismissable.js +24 -2
  14. package/dist/build-api.js +92 -37
  15. package/dist/cdn/{GridMenus-BL7ZgQvU.js → GridMenus-C-NtjlrJ.js} +155 -146
  16. package/dist/cdn/GridMenus-TssHej3q.js +644 -0
  17. package/dist/cdn/{SvChartMenu-FBSMINA6.js → SvChartMenu-BFSTpvB-.js} +1 -1
  18. package/dist/cdn/{SvChartMenu-Bl6PBbkT.js → SvChartMenu-BZ1Iwv0y.js} +1 -1
  19. package/dist/cdn/{SvDateTimePicker-DQwt4UAs.js → SvDateTimePicker-D9u_cOf8.js} +1 -1
  20. package/dist/cdn/{SvDateTimePicker-vNU6bZ-q.js → SvDateTimePicker-s_6IUpI7.js} +1 -1
  21. package/dist/cdn/{SvGridCellEditor-B1p-vCK5.js → SvGridCellEditor-BlyCSp0q.js} +1 -1
  22. package/dist/cdn/{SvGridCellEditor-D_0q4xAu.js → SvGridCellEditor-ClRRA9lW.js} +1 -1
  23. package/dist/cdn/{SvGridChart-DzLkSwCH.js → SvGridChart-B4EV8U6t.js} +4 -4
  24. package/dist/cdn/{SvGridChart-C3EWAZaM.js → SvGridChart-DsmwTyZF.js} +4 -4
  25. package/dist/cdn/{SvGridChartBuilder-CfII62sZ.js → SvGridChartBuilder-cHloHobN.js} +4 -4
  26. package/dist/cdn/{SvGridChartBuilder-BE2T1ykB.js → SvGridChartBuilder-vOl7C0Za.js} +4 -4
  27. package/dist/cdn/{SvGridChartPanel-xf4sWVTo.js → SvGridChartPanel-AcqF-Ll5.js} +5 -5
  28. package/dist/cdn/{SvGridChartPanel-CCX5_Wgd.js → SvGridChartPanel-biMtSBPA.js} +5 -5
  29. package/dist/cdn/{SvGridChartView-DYwabQWj.js → SvGridChartView-Dx_GmZuL.js} +2 -2
  30. package/dist/cdn/{SvGridChartView-CfuXmY5I.js → SvGridChartView-I3rDHXAq.js} +2 -2
  31. package/dist/cdn/{SvGridDropdown-D0VdjeR8.js → SvGridDropdown-BWeM3lMe.js} +46 -46
  32. package/dist/cdn/{SvGridDropdown-D13MtJ2j.js → SvGridDropdown-CJ6QqTxu.js} +67 -67
  33. package/dist/cdn/{SvModal-CIZWCcad.js → SvModal-ClxGmpAc.js} +187 -186
  34. package/dist/cdn/{SvModal-BAE-pjZX.js → SvModal-DhB_VMFR.js} +148 -147
  35. package/dist/cdn/{cell-formatting-C2Hf5gqd.js → cell-formatting-DVVKOSI9.js} +1 -1
  36. package/dist/cdn/{chart-Dz7SqMXH.js → chart-DEZxwC0i.js} +1 -1
  37. package/dist/cdn/{chart-panel-messages-CUbf2R4i.js → chart-panel-messages-D12XcTZJ.js} +1 -1
  38. package/dist/cdn/{chart-panel-messages-CmNrMdsr.js → chart-panel-messages-DguS7gC5.js} +1 -1
  39. package/dist/cdn/{chart-summary-BJW_tg_X.js → chart-summary-CMAXBGY-.js} +1 -1
  40. package/dist/cdn/{chart-trend-CaN9mDEV.js → chart-trend-BkEp61Gj.js} +1 -1
  41. package/dist/cdn/{dismissable-DAHetSNk.js → dismissable-Brc4EZU1.js} +5 -1
  42. package/dist/cdn/{export-format-CUDLy2yn.js → export-format-YzdwBww2.js} +1 -1
  43. package/dist/cdn/{row-resize-niQCp040.js → row-resize-DtOS1KG6.js} +41 -32
  44. package/dist/cdn/server-block-cache-DIqb3VZn.js +241 -0
  45. package/dist/cdn/{src-V1uu8iE9.js → src-CgoeSM8k.js} +5339 -4753
  46. package/dist/cdn/{src-BKhZ6eXd.js → src-DfwxB1TH.js} +9817 -9231
  47. package/dist/cdn/svgrid.js +28 -27
  48. package/dist/cdn/svgrid.svelte-external.js +28 -27
  49. package/dist/cdn/validate-AZoD8BoR.js +80 -0
  50. package/dist/cell-formatting.js +18 -1
  51. package/dist/cell-render.js +25 -6
  52. package/dist/clipboard.d.ts +2 -2
  53. package/dist/clipboard.js +72 -23
  54. package/dist/columns.js +7 -2
  55. package/dist/conditional-formatting.d.ts +2 -0
  56. package/dist/conditional-formatting.js +2 -0
  57. package/dist/core.d.ts +22 -6
  58. package/dist/core.js +401 -38
  59. package/dist/editing.js +34 -0
  60. package/dist/gantt-view.svelte.d.ts +24 -0
  61. package/dist/gantt-view.svelte.js +13 -0
  62. package/dist/grid-icons.d.ts +2 -2
  63. package/dist/grid-icons.js +2 -2
  64. package/dist/grid-messages.d.ts +10 -0
  65. package/dist/grid-messages.js +9 -0
  66. package/dist/headless.d.ts +5 -0
  67. package/dist/headless.js +12 -0
  68. package/dist/history.d.ts +21 -0
  69. package/dist/history.js +34 -4
  70. package/dist/index.d.ts +5 -4
  71. package/dist/index.js +3 -3
  72. package/dist/keyboard-handlers.js +24 -1
  73. package/dist/keyboard.js +4 -0
  74. package/dist/row-drag-touch.d.ts +1 -1
  75. package/dist/row-drag.js +35 -1
  76. package/dist/row-model.d.ts +139 -0
  77. package/dist/row-model.js +16 -0
  78. package/dist/row-resize.js +22 -1
  79. package/dist/selection.d.ts +2 -1
  80. package/dist/selection.js +31 -3
  81. package/dist/server-block-cache.d.ts +219 -0
  82. package/dist/server-block-cache.js +539 -0
  83. package/dist/server-data-source.d.ts +274 -8
  84. package/dist/server-data-source.js +229 -20
  85. package/dist/server.d.ts +13 -0
  86. package/dist/server.js +13 -0
  87. package/dist/sparkline.js +7 -5
  88. package/dist/svgrid-wrapper.types.d.ts +33 -0
  89. package/dist/validate.d.ts +4 -0
  90. package/dist/validate.js +29 -3
  91. package/package.json +11 -1
  92. package/src/GridMenus.svelte +34 -4
  93. package/src/SvGrid.controller.svelte.ts +397 -61
  94. package/src/SvGrid.css +200 -2
  95. package/src/SvGrid.svelte +350 -40
  96. package/src/SvGrid.types.ts +453 -7
  97. package/src/SvGridDropdown.svelte +20 -0
  98. package/src/SvModal.svelte +22 -0
  99. package/src/SvModal.test.ts +30 -1
  100. package/src/a11y/dismissable.test.ts +10 -1
  101. package/src/a11y/dismissable.ts +22 -2
  102. package/src/build-api.ts +96 -31
  103. package/src/cell-formatting.test.ts +17 -0
  104. package/src/cell-formatting.ts +18 -1
  105. package/src/cell-render.test.ts +24 -2
  106. package/src/cell-render.ts +24 -8
  107. package/src/clipboard.test.ts +107 -0
  108. package/src/clipboard.ts +62 -23
  109. package/src/columns.test.ts +4 -4
  110. package/src/columns.ts +7 -2
  111. package/src/conditional-formatting.test.ts +8 -0
  112. package/src/conditional-formatting.ts +3 -0
  113. package/src/core.rowmodel-cache.test.ts +51 -0
  114. package/src/core.tick-repair.test.ts +287 -0
  115. package/src/core.ts +407 -38
  116. package/src/editing.test.ts +52 -0
  117. package/src/editing.ts +33 -0
  118. package/src/gantt-stub.test.svelte +38 -0
  119. package/src/gantt-view.svelte.ts +35 -0
  120. package/src/grid-icons.ts +2 -2
  121. package/src/grid-messages.test.ts +7 -0
  122. package/src/grid-messages.ts +22 -0
  123. package/src/headless.ts +24 -0
  124. package/src/history.test.ts +49 -1
  125. package/src/history.ts +48 -2
  126. package/src/icon-seam.test.ts +2 -4
  127. package/src/index.ts +38 -10
  128. package/src/keyboard-handlers.coverage.test.ts +65 -0
  129. package/src/keyboard-handlers.ts +26 -1
  130. package/src/keyboard.ts +3 -0
  131. package/src/row-drag-touch.ts +2 -2
  132. package/src/row-drag.test.ts +51 -0
  133. package/src/row-drag.ts +35 -2
  134. package/src/row-model.ts +152 -0
  135. package/src/row-resize.ts +24 -1
  136. package/src/selection.test.ts +3 -0
  137. package/src/selection.ts +33 -3
  138. package/src/server-block-cache.test.ts +672 -0
  139. package/src/server-block-cache.ts +690 -0
  140. package/src/server-data-source.infinite.test.ts +405 -0
  141. package/src/server-data-source.test.ts +19 -0
  142. package/src/server-data-source.ts +496 -29
  143. package/src/server.ts +49 -0
  144. package/src/sparkline.test.ts +7 -0
  145. package/src/sparkline.ts +6 -4
  146. package/src/svgrid-wrapper.types.ts +32 -0
  147. package/src/svgrid.api.test.ts +21 -0
  148. package/src/svgrid.charting.test.ts +12 -4
  149. package/src/svgrid.context-menu.test.ts +12 -0
  150. package/src/svgrid.detail-rows.svelte.test.ts +187 -0
  151. package/src/svgrid.filter-menu-scroll.test.ts +9 -0
  152. package/src/svgrid.gantt-seam.test.ts +199 -0
  153. package/src/svgrid.live-update-paths.svelte.test.ts +184 -0
  154. package/src/svgrid.menu-scroll-close.test.ts +10 -0
  155. package/src/svgrid.row-model-prop.svelte.test.ts +352 -0
  156. package/src/svgrid.row-model-seam.svelte.test.ts +305 -0
  157. package/src/svgrid.row-pinning.test.ts +15 -1
  158. package/src/svgrid.selection-bar-seam.test.ts +1 -1
  159. package/src/svgrid.sticky-groups.svelte.test.ts +145 -0
  160. package/src/svgrid.upsell-license.test.ts +8 -5
  161. package/src/test-setup.ts +12 -0
  162. package/src/transaction.test.ts +58 -0
  163. package/src/validate.test.ts +29 -0
  164. package/src/validate.ts +34 -3
  165. package/dist/SvGroupCell.svelte +0 -141
  166. package/dist/SvGroupCell.svelte.d.ts +0 -49
  167. package/dist/SvRowGroupPanel.svelte +0 -186
  168. package/dist/SvRowGroupPanel.svelte.d.ts +0 -25
  169. package/dist/cdn/GridMenus-7kbpnnBW.js +0 -635
  170. package/dist/cdn/validate-_CDJzgIo.js +0 -75
  171. package/dist/server-group-model.d.ts +0 -98
  172. package/dist/server-group-model.js +0 -263
  173. package/src/SvGroupCell.svelte +0 -141
  174. package/src/SvRowGroupPanel.svelte +0 -186
  175. package/src/server-group-model.test.ts +0 -294
  176. package/src/server-group-model.ts +0 -370
@@ -0,0 +1,539 @@
1
+ /**
2
+ * Block cache for server-backed rows - the engine behind infinite scrolling.
3
+ *
4
+ * Paging asks for "page 3". Infinite scrolling asks a different question: the
5
+ * user is looking at rows 4,000 to 4,020 of a table with a million rows, so
6
+ * fetch the block that covers them, keep a bounded number of recently-seen
7
+ * blocks, and render something sensible for every row nobody has fetched yet.
8
+ * That is all this module does, in plain TypeScript with no Svelte and no DOM.
9
+ *
10
+ * The shape of the problem (and most of the vocabulary) is the same one every
11
+ * grid with a server row model solves, so the options here are deliberately
12
+ * recognisable: `blockSize`, `maxBlocksInCache`, `maxConcurrentRequests`,
13
+ * `blockLoadDebounceMs`, `initialRowCount`, `overflowRows`.
14
+ *
15
+ * Three things it takes seriously:
16
+ *
17
+ * - **Unloaded rows still have to render.** `rows()` always returns a dense
18
+ * array, with a shared sentinel object in every slot that has no data. The
19
+ * grid recognises those (see {@link rowPlaceholderState}) and draws a
20
+ * skeleton or a retry affordance instead of an empty row, so the scrollbar
21
+ * never lies and scrolling never leaves a hole.
22
+ * - **The row count may be unknown.** A backend that cannot cheaply count
23
+ * says so (omit `rowCount`, or send `-1`) and the list grows by a block at
24
+ * a time until a short block proves where the end is.
25
+ * - **Requests are not free.** In-flight blocks are deduplicated, at most
26
+ * `maxConcurrentRequests` are open at once, a fast scroll debounces rather
27
+ * than firing a request per frame, and blocks abandoned by eviction or
28
+ * purge are aborted.
29
+ *
30
+ * Enterprise's server row model runs one of these per group level; the free
31
+ * flat controller runs exactly one.
32
+ */
33
+ /**
34
+ * The mark that says "this row is not data yet".
35
+ *
36
+ * A symbol, for two reasons. It cannot collide with a field in anyone's row
37
+ * data, which a string key like `__svPlaceholder` eventually would. And
38
+ * `Symbol.for` puts it in the global registry, so a placeholder still reads as
39
+ * one after it has crossed a module boundary - two copies of this file loaded
40
+ * through different specifiers would otherwise mint different symbols.
41
+ */
42
+ const PLACEHOLDER = Symbol.for('svgrid.rowPlaceholder');
43
+ /** Rows the cache has not loaded. One shared object per state, not per row. */
44
+ const LOADING_ROW = Object.freeze({ [PLACEHOLDER]: 'loading' });
45
+ const FAILED_ROW = Object.freeze({ [PLACEHOLDER]: 'failed' });
46
+ /**
47
+ * Why a row is not real data, or `null` when it is.
48
+ *
49
+ * Deliberately NOT an identity check. The sentinels are shared objects, so
50
+ * `row === LOADING_ROW` looks like the obvious test - but rows routinely
51
+ * arrive here through something that wrapped them. Svelte is the everyday
52
+ * case: assigning the controller state into `$state` makes the row array
53
+ * deeply reactive, and every row read back out is a proxy of the original.
54
+ * Identity fails, every placeholder reads as real data, and the grid renders
55
+ * a screen of blank rows instead of skeletons. Reading the mark works through
56
+ * any wrapper that forwards property access, which is all of them.
57
+ */
58
+ export function rowPlaceholderState(row) {
59
+ if (row == null || typeof row !== 'object')
60
+ return null;
61
+ const mark = row[PLACEHOLDER];
62
+ return mark === 'loading' || mark === 'failed' ? mark : null;
63
+ }
64
+ /**
65
+ * Mint a frozen placeholder the grid will recognise, carrying whatever
66
+ * other fields the caller wants on it. The row model uses this to give its
67
+ * placeholders a `kind`, so code reading display rows and code reading grid
68
+ * rows agree on what they are looking at.
69
+ */
70
+ export function createRowPlaceholder(state, fields) {
71
+ return Object.freeze({ ...fields, [PLACEHOLDER]: state });
72
+ }
73
+ const defaultSchedule = (flush) => {
74
+ void Promise.resolve().then(flush);
75
+ };
76
+ /**
77
+ * Build a block cache over a `fetch(startRow, endRow, signal)`. The free
78
+ * infinite row model and the Enterprise server-side row model both run on
79
+ * it, one per level.
80
+ */
81
+ export function createBlockCache(options) {
82
+ const blockSize = Math.max(1, options.blockSize ?? 100);
83
+ const maxBlocks = options.maxBlocksInCache ?? Infinity;
84
+ const maxConcurrent = Math.max(1, options.maxConcurrentRequests ?? 2);
85
+ const debounceMs = Math.max(0, options.blockLoadDebounceMs ?? 0);
86
+ const initialRowCount = Math.max(0, options.initialRowCount ?? 1);
87
+ const overflowRows = Math.max(0, options.overflowRows ?? 1);
88
+ const schedule = options.schedule ?? defaultSchedule;
89
+ const blocks = new Map();
90
+ /** Block indices waiting for a slot, in the order the viewport asked for them. */
91
+ const queue = [];
92
+ let inFlight = 0;
93
+ let touchClock = 0;
94
+ let count = null;
95
+ let countKnown = false;
96
+ let disposed = false;
97
+ let viewStart = 0;
98
+ let viewEnd = 0;
99
+ let debounceTimer = null;
100
+ let emitScheduled = false;
101
+ let rowsCache = null;
102
+ const blockOf = (rowIndex) => Math.floor(rowIndex / blockSize);
103
+ const startOf = (blockIndex) => blockIndex * blockSize;
104
+ /**
105
+ * How many rows to claim we have.
106
+ *
107
+ * With a known count that is simply the count. Without one it is the last row
108
+ * we have touched plus `overflowRows`, so there is always somewhere to scroll
109
+ * that will ask for the next block - this is what makes the list grow as you
110
+ * go rather than ending at the first unloaded row.
111
+ */
112
+ function currentLength() {
113
+ if (countKnown && count != null)
114
+ return count;
115
+ let highestEnd = 0;
116
+ let anySettled = false;
117
+ for (const b of blocks.values())
118
+ if (b.status !== 'loading')
119
+ anySettled = true;
120
+ for (const [index, block] of blocks) {
121
+ // A block in flight extends the list only once some block has settled.
122
+ // Before that the list is `initialRowCount` long: the few skeleton
123
+ // rows a level shows while it waits, not a hundred of them. The first
124
+ // block failing says nothing about how long the list is either, so it
125
+ // keeps those few rows (its Retry sits on them); a failed block further
126
+ // in was scrolled to, so its slots stay and the scrollbar holds still.
127
+ const end = block.status === 'loaded'
128
+ ? startOf(index) + block.rows.length
129
+ : block.status === 'failed'
130
+ ? index === 0 ? 0 : startOf(index) + blockSize
131
+ : anySettled
132
+ ? startOf(index) + blockSize
133
+ : 0;
134
+ if (end > highestEnd)
135
+ highestEnd = end;
136
+ }
137
+ if (!anySettled)
138
+ return initialRowCount;
139
+ return Math.max(initialRowCount, highestEnd + overflowRows);
140
+ }
141
+ function state() {
142
+ const failed = [];
143
+ for (const [index, block] of blocks)
144
+ if (block.status === 'failed')
145
+ failed.push(index);
146
+ return {
147
+ rowCount: countKnown ? count : null,
148
+ lastRowKnown: countKnown,
149
+ loading: inFlight > 0,
150
+ failedBlocks: failed.sort((a, b) => a - b),
151
+ };
152
+ }
153
+ /**
154
+ * Something changed: forget the row array NOW, so a synchronous read after
155
+ * a mutation sees the new state, and notify on the next tick, so a burst of
156
+ * mutations notifies once. Every mutating path ends here.
157
+ */
158
+ function emit() {
159
+ rowsCache = null; // rebuilt lazily, on the next read
160
+ if (disposed || emitScheduled)
161
+ return;
162
+ emitScheduled = true;
163
+ schedule(() => {
164
+ emitScheduled = false;
165
+ if (disposed)
166
+ return;
167
+ options.onChange(state());
168
+ });
169
+ }
170
+ function ensureBlock(blockIndex) {
171
+ if (disposed)
172
+ return;
173
+ const existing = blocks.get(blockIndex);
174
+ // Loading or loaded blocks are left alone; a failed one only retries when
175
+ // asked, so a broken backend is not hammered once per scroll frame.
176
+ if (existing)
177
+ return;
178
+ if (queue.includes(blockIndex))
179
+ return;
180
+ queue.push(blockIndex);
181
+ pump();
182
+ }
183
+ function pump() {
184
+ while (!disposed && inFlight < maxConcurrent && queue.length > 0) {
185
+ const blockIndex = queue.shift();
186
+ if (blocks.has(blockIndex))
187
+ continue;
188
+ void load(blockIndex);
189
+ }
190
+ }
191
+ async function load(blockIndex) {
192
+ const controller = new AbortController();
193
+ const block = {
194
+ status: 'loading',
195
+ rows: [],
196
+ lastTouched: (touchClock += 1),
197
+ controller,
198
+ };
199
+ blocks.set(blockIndex, block);
200
+ inFlight += 1;
201
+ emit();
202
+ const startRow = startOf(blockIndex);
203
+ const endRow = startRow + blockSize;
204
+ try {
205
+ const result = await options.fetch(startRow, endRow, controller.signal);
206
+ if (disposed || controller.signal.aborted || blocks.get(blockIndex) !== block)
207
+ return;
208
+ block.rows = [...result.rows];
209
+ block.status = 'loaded';
210
+ block.controller = null;
211
+ applyCountFrom(blockIndex, block.rows.length, result.rowCount);
212
+ evictIfNeeded();
213
+ }
214
+ catch {
215
+ if (disposed || controller.signal.aborted || blocks.get(blockIndex) !== block)
216
+ return;
217
+ block.status = 'failed';
218
+ block.rows = [];
219
+ block.controller = null;
220
+ }
221
+ finally {
222
+ if (!disposed && !controller.signal.aborted) {
223
+ inFlight -= 1;
224
+ emit();
225
+ pump();
226
+ }
227
+ }
228
+ }
229
+ /**
230
+ * Learn the total from a block that just landed.
231
+ *
232
+ * An explicit non-negative `rowCount` settles it. Otherwise a SHORT block is
233
+ * the proof that we hit the end: fewer rows came back than were asked for, so
234
+ * the data stops where they stop.
235
+ */
236
+ function applyCountFrom(blockIndex, received, reported) {
237
+ if (typeof reported === 'number' && reported >= 0) {
238
+ count = reported;
239
+ countKnown = true;
240
+ return;
241
+ }
242
+ if (received < blockSize) {
243
+ count = startOf(blockIndex) + received;
244
+ countKnown = true;
245
+ }
246
+ }
247
+ /**
248
+ * Evict loaded blocks over the limit, least-recently-seen first, never one
249
+ * the viewport is currently on - dropping a visible block would swap real
250
+ * rows for skeletons under the user's eyes and immediately re-fetch them.
251
+ */
252
+ function evictIfNeeded() {
253
+ if (!Number.isFinite(maxBlocks))
254
+ return;
255
+ const firstVisible = blockOf(viewStart);
256
+ const lastVisible = blockOf(Math.max(viewStart, viewEnd));
257
+ const evictable = [...blocks.entries()]
258
+ .filter(([index, b]) => b.status === 'loaded' && (index < firstVisible || index > lastVisible))
259
+ .sort((a, b) => a[1].lastTouched - b[1].lastTouched);
260
+ let loaded = 0;
261
+ for (const b of blocks.values())
262
+ if (b.status === 'loaded')
263
+ loaded += 1;
264
+ for (const [index] of evictable) {
265
+ if (loaded <= maxBlocks)
266
+ break;
267
+ blocks.delete(index);
268
+ loaded -= 1;
269
+ }
270
+ }
271
+ function fetchViewport() {
272
+ if (disposed)
273
+ return;
274
+ const first = blockOf(viewStart);
275
+ const last = blockOf(Math.max(viewStart, viewEnd));
276
+ for (let i = first; i <= last; i += 1) {
277
+ const block = blocks.get(i);
278
+ if (block)
279
+ block.lastTouched = touchClock += 1;
280
+ else
281
+ ensureBlock(i);
282
+ }
283
+ }
284
+ function abortAll() {
285
+ for (const block of blocks.values())
286
+ block.controller?.abort();
287
+ inFlight = 0;
288
+ queue.length = 0;
289
+ }
290
+ return {
291
+ setViewport(startIndex, endIndex) {
292
+ if (disposed)
293
+ return;
294
+ viewStart = Math.max(0, startIndex);
295
+ viewEnd = Math.max(viewStart, endIndex);
296
+ if (debounceMs === 0) {
297
+ fetchViewport();
298
+ return;
299
+ }
300
+ if (debounceTimer)
301
+ clearTimeout(debounceTimer);
302
+ debounceTimer = setTimeout(() => {
303
+ debounceTimer = null;
304
+ fetchViewport();
305
+ }, debounceMs);
306
+ },
307
+ rows() {
308
+ if (rowsCache)
309
+ return rowsCache;
310
+ const length = currentLength();
311
+ const out = new Array(length);
312
+ // Fill from the blocks we have, then pad the rest with placeholders. One
313
+ // pass per block beats one lookup per row: at a million rows the
314
+ // difference is the frame budget.
315
+ out.fill(LOADING_ROW);
316
+ for (const [index, block] of blocks) {
317
+ const start = startOf(index);
318
+ if (start >= length)
319
+ continue;
320
+ if (block.status === 'failed') {
321
+ const end = Math.min(start + blockSize, length);
322
+ for (let i = start; i < end; i += 1)
323
+ out[i] = FAILED_ROW;
324
+ continue;
325
+ }
326
+ for (let i = 0; i < block.rows.length && start + i < length; i += 1) {
327
+ out[start + i] = block.rows[i];
328
+ }
329
+ }
330
+ rowsCache = out;
331
+ return out;
332
+ },
333
+ getRow(index) {
334
+ const block = blocks.get(blockOf(index));
335
+ if (!block)
336
+ return LOADING_ROW;
337
+ if (block.status === 'failed')
338
+ return FAILED_ROW;
339
+ const row = block.rows[index - startOf(blockOf(index))];
340
+ return row ?? LOADING_ROW;
341
+ },
342
+ rowCount: () => (countKnown ? count : null),
343
+ lastRowKnown: () => countKnown,
344
+ retryFailed() {
345
+ let any = false;
346
+ for (const [index, block] of [...blocks]) {
347
+ if (block.status !== 'failed')
348
+ continue;
349
+ blocks.delete(index);
350
+ ensureBlock(index);
351
+ any = true;
352
+ }
353
+ if (any)
354
+ emit();
355
+ },
356
+ retryFailedAt(rowIndex) {
357
+ const index = blockOf(Math.max(0, rowIndex));
358
+ if (blocks.get(index)?.status !== 'failed')
359
+ return;
360
+ blocks.delete(index);
361
+ ensureBlock(index);
362
+ emit();
363
+ },
364
+ refresh() {
365
+ // Keep the count and the scroll position: drop the DATA, re-request the
366
+ // same blocks. The user sees skeletons where they were, not a jump home.
367
+ for (const [index, block] of [...blocks]) {
368
+ block.controller?.abort();
369
+ blocks.delete(index);
370
+ ensureBlock(index);
371
+ }
372
+ emit();
373
+ },
374
+ purge() {
375
+ abortAll();
376
+ blocks.clear();
377
+ count = null;
378
+ countKnown = false;
379
+ rowsCache = null;
380
+ fetchViewport();
381
+ emit();
382
+ },
383
+ setRowCount(next, known = next != null) {
384
+ count = next;
385
+ countKnown = known && next != null;
386
+ emit();
387
+ },
388
+ applyRows(startRow, rows, rowCount) {
389
+ if (startRow % blockSize !== 0) {
390
+ throw new Error(`createBlockCache.applyRows: startRow ${startRow} is not a multiple of blockSize ${blockSize}`);
391
+ }
392
+ const firstBlock = blockOf(startRow);
393
+ const blockCount = Math.ceil(rows.length / blockSize);
394
+ for (let i = 0; i < blockCount; i += 1) {
395
+ const index = firstBlock + i;
396
+ blocks.get(index)?.controller?.abort(); // ours now, whatever was in flight
397
+ blocks.set(index, {
398
+ status: 'loaded',
399
+ rows: rows.slice(i * blockSize, (i + 1) * blockSize),
400
+ lastTouched: (touchClock += 1),
401
+ controller: null,
402
+ });
403
+ }
404
+ const lastBlock = blocks.get(firstBlock + blockCount - 1);
405
+ if (lastBlock)
406
+ applyCountFrom(firstBlock + blockCount - 1, lastBlock.rows.length, rowCount);
407
+ else if (typeof rowCount === 'number' && rowCount >= 0) {
408
+ count = rowCount;
409
+ countKnown = true;
410
+ }
411
+ emit();
412
+ },
413
+ patch(index, row) {
414
+ const block = blocks.get(blockOf(index));
415
+ if (!block || block.status !== 'loaded')
416
+ return false;
417
+ const offset = index - startOf(blockOf(index));
418
+ if (offset < 0 || offset >= block.rows.length)
419
+ return false;
420
+ block.rows[offset] = row;
421
+ emit();
422
+ return true;
423
+ },
424
+ findIndex(predicate) {
425
+ for (const [blockIndex, block] of blocks) {
426
+ if (block.status !== 'loaded')
427
+ continue;
428
+ const start = startOf(blockIndex);
429
+ for (let i = 0; i < block.rows.length; i += 1) {
430
+ if (predicate(block.rows[i], start + i))
431
+ return start + i;
432
+ }
433
+ }
434
+ return -1;
435
+ },
436
+ insert(index, rows) {
437
+ if (rows.length === 0)
438
+ return false;
439
+ const clamped = Math.max(0, Math.min(index, currentLength()));
440
+ const run = loadedRunAt(clamped);
441
+ if (run) {
442
+ // Rows shift across block boundaries, so re-slice the run from its
443
+ // first block; everything loaded past it is dropped (offsets moved).
444
+ run.flat.splice(clamped - startOf(run.startBlock), 0, ...rows);
445
+ reseat(run.startBlock, run.flat);
446
+ }
447
+ else {
448
+ dropLoadedFrom(blockOf(clamped));
449
+ }
450
+ if (countKnown && count != null)
451
+ count += rows.length;
452
+ emit();
453
+ return run != null;
454
+ },
455
+ remove(index, removeCount = 1) {
456
+ if (removeCount <= 0)
457
+ return 0;
458
+ const run = loadedRunAt(index);
459
+ if (!run)
460
+ return 0;
461
+ const removed = run.flat.splice(index - startOf(run.startBlock), removeCount).length;
462
+ reseat(run.startBlock, run.flat);
463
+ if (countKnown && count != null)
464
+ count = Math.max(0, count - removed);
465
+ emit();
466
+ return removed;
467
+ },
468
+ getCacheState() {
469
+ return [...blocks.entries()]
470
+ .map(([blockIndex, block]) => ({
471
+ blockIndex,
472
+ startRow: startOf(blockIndex),
473
+ endRow: startOf(blockIndex) + blockSize,
474
+ status: block.status,
475
+ lastTouched: block.lastTouched,
476
+ }))
477
+ .sort((a, b) => a.blockIndex - b.blockIndex);
478
+ },
479
+ dispose() {
480
+ disposed = true;
481
+ if (debounceTimer)
482
+ clearTimeout(debounceTimer);
483
+ debounceTimer = null;
484
+ abortAll();
485
+ blocks.clear();
486
+ },
487
+ };
488
+ /**
489
+ * The run of consecutive loaded blocks containing `index`, flattened, with
490
+ * the block it starts at. Null when the block at `index` is not loaded -
491
+ * an index-shifting edit there would have nothing to shift.
492
+ */
493
+ function loadedRunAt(index) {
494
+ const at = blockOf(index);
495
+ if (blocks.get(at)?.status !== 'loaded')
496
+ return null;
497
+ let startBlock = at;
498
+ while (blocks.get(startBlock - 1)?.status === 'loaded')
499
+ startBlock -= 1;
500
+ const flat = [];
501
+ for (let i = startBlock;; i += 1) {
502
+ const block = blocks.get(i);
503
+ if (!block || block.status !== 'loaded')
504
+ break;
505
+ flat.push(...block.rows);
506
+ if (block.rows.length < blockSize)
507
+ break; // the last block, by definition
508
+ }
509
+ return { startBlock, flat };
510
+ }
511
+ /**
512
+ * Lay a flat run back out into blocks from `startBlock`, and drop every
513
+ * block after the run: their rows have shifted, and re-fetching them at
514
+ * the new offsets is the honest outcome. Blocks before it are untouched.
515
+ */
516
+ function reseat(startBlock, flat) {
517
+ const blockCount = Math.ceil(flat.length / blockSize);
518
+ dropLoadedFrom(startBlock);
519
+ for (let i = 0; i < blockCount; i += 1) {
520
+ blocks.set(startBlock + i, {
521
+ status: 'loaded',
522
+ rows: flat.slice(i * blockSize, (i + 1) * blockSize),
523
+ lastTouched: (touchClock += 1),
524
+ controller: null,
525
+ });
526
+ }
527
+ rowsCache = null;
528
+ }
529
+ /** Forget every block from `fromBlock` on, aborting any in flight. */
530
+ function dropLoadedFrom(fromBlock) {
531
+ for (const [index, block] of [...blocks]) {
532
+ if (index < fromBlock)
533
+ continue;
534
+ block.controller?.abort();
535
+ blocks.delete(index);
536
+ }
537
+ rowsCache = null;
538
+ }
539
+ }