@ember-lattice/data 0.0.0-stage → 1.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,1474 @@
1
+ import { evaluate, FILTER_OPS, LIMITS, GROUP_COUNT_KEY } from '@ember-lattice/protocol';
2
+ import is from '@sindresorhus/is';
3
+ import { tracked, cached } from '@glimmer/tracking';
4
+ import { State, Machine, transition } from '@switchyard-ts/core';
5
+ import { n, g, i } from 'decorator-transforms/runtime';
6
+ import { constructRow } from '@ember-lattice/core';
7
+
8
+ // `arrayDataSource`: a DataSource over rows in memory, for tests and demos. The protocol's
9
+ // `evaluate` answers each request, so it acts the same as a conforming server.
10
+ /** A new row list with the transaction applied: remove, then update in place, then add. */
11
+ function applyTransaction(rows, tx, getRowId) {
12
+ const removed = new Set(tx.remove ?? []);
13
+ const updates = new Map((tx.update ?? []).map(row => [getRowId(row), row]));
14
+ const next = rows.filter(row => !removed.has(getRowId(row))).map(row => updates.get(getRowId(row)) ?? row);
15
+ const add = tx.add ?? [];
16
+ next.splice(Math.min(tx.addIndex ?? next.length, next.length), 0, ...add);
17
+ return next;
18
+ }
19
+ const abortError = () => new DOMException('The request was aborted.', 'AbortError');
20
+ function arrayDataSource(initial, allowList) {
21
+ const key = allowList.find(c => c.key === true)?.name;
22
+ if (!key) throw new Error('arrayDataSource: the allow-list needs one key column');
23
+ let rows = [...initial];
24
+ const listeners = new Set();
25
+ const getRowId = row => String(Reflect.get(row, key));
26
+ const push = tx => {
27
+ rows = applyTransaction(rows, tx, getRowId);
28
+ for (const listener of listeners) listener(tx);
29
+ };
30
+ return {
31
+ capabilities: {
32
+ sort: true,
33
+ filter: true,
34
+ group: true,
35
+ aggregate: true,
36
+ pivot: true,
37
+ tree: allowList.some(c => c.parent === true || c.path === true),
38
+ count: true,
39
+ transactions: true,
40
+ push: true
41
+ },
42
+ get rows() {
43
+ return rows;
44
+ },
45
+ getRowId,
46
+ push,
47
+ getRows(request, signal) {
48
+ if (signal.aborted) return Promise.reject(abortError());
49
+ try {
50
+ // Rows are plain objects, so the protocol's row type fits them.
51
+ const response = evaluate(request, rows, allowList);
52
+ return Promise.resolve({
53
+ ...response,
54
+ rows: response.rows
55
+ });
56
+ } catch (error) {
57
+ return Promise.reject(error);
58
+ }
59
+ },
60
+ subscribe(onChange) {
61
+ listeners.add(onChange);
62
+ return () => listeners.delete(onChange);
63
+ },
64
+ mutate(ops) {
65
+ const results = [];
66
+ const tx = {
67
+ v: 1
68
+ };
69
+ const byId = new Map(rows.map(row => [getRowId(row), row]));
70
+ for (const op of ops) {
71
+ if (op.type === 'add') {
72
+ (tx.add ??= []).push(op.row);
73
+ results.push({
74
+ status: 'ok',
75
+ id: getRowId(op.row),
76
+ row: op.row
77
+ });
78
+ continue;
79
+ }
80
+ const row = byId.get(op.id);
81
+ if (!row) {
82
+ results.push({
83
+ status: 'error',
84
+ id: op.id,
85
+ message: `no row with id ${op.id}`
86
+ });
87
+ continue;
88
+ }
89
+ if (op.type === 'remove') {
90
+ (tx.remove ??= []).push(op.id);
91
+ results.push({
92
+ status: 'ok',
93
+ id: op.id
94
+ });
95
+ } else {
96
+ const next = {
97
+ ...row,
98
+ ...op.changes
99
+ };
100
+ byId.set(op.id, next);
101
+ (tx.update ??= []).push(next);
102
+ results.push({
103
+ status: 'ok',
104
+ id: op.id,
105
+ row: next
106
+ });
107
+ }
108
+ }
109
+ push(tx);
110
+ const result = {
111
+ results,
112
+ transaction: tx
113
+ };
114
+ return Promise.resolve(result);
115
+ }
116
+ };
117
+ }
118
+
119
+ // The engine state to a protocol RowsRequest. The server row models run the engine in manual
120
+ // mode (manualSorting, manualFiltering, manualGrouping, manualPagination): the engine keeps the
121
+ // state, and the server does the work.
122
+
123
+ /** The parts of the engine state (`table.store.state`) that change the rows of the server. */
124
+
125
+ const isScalar = value => is.string(value) || is.number(value) || is.boolean(value);
126
+ const isOp = value => is.string(value) && FILTER_OPS.includes(value);
127
+
128
+ /**
129
+ * One column filter value to one filter leaf. The convention (ADR 0010):
130
+ * a string is `contains`, a number or a boolean is `eq`, an array is `in`, and
131
+ * `{ op, value? }` is that op. An empty value is no filter.
132
+ */
133
+ function columnFilterNode(column, value) {
134
+ if (is.string(value)) return value === '' ? null : {
135
+ column,
136
+ op: 'contains',
137
+ value
138
+ };
139
+ if (is.number(value) || is.boolean(value)) return {
140
+ column,
141
+ op: 'eq',
142
+ value
143
+ };
144
+ if (is.array(value)) {
145
+ const list = value.filter(isScalar);
146
+ return list.length === 0 ? null : {
147
+ column,
148
+ op: 'in',
149
+ value: list
150
+ };
151
+ }
152
+ if (is.plainObject(value) && isOp(value['op'])) {
153
+ const op = value['op'];
154
+ const v = value['value'];
155
+ if (op === 'blank' || op === 'notBlank') return {
156
+ column,
157
+ op
158
+ };
159
+ if (op === 'in' || op === 'notIn') return is.array(v) ? {
160
+ column,
161
+ op,
162
+ value: v.filter(isScalar)
163
+ } : null;
164
+ if (op === 'between' || op === 'inRange') {
165
+ return is.array(v) && v.length === 2 && isScalar(v[0]) && isScalar(v[1]) ? {
166
+ column,
167
+ op,
168
+ value: [v[0], v[1]]
169
+ } : null;
170
+ }
171
+ return isScalar(v) ? {
172
+ column,
173
+ op,
174
+ value: v
175
+ } : null;
176
+ }
177
+ return null;
178
+ }
179
+ function toRowsRequest(state, options) {
180
+ const page = state.pagination;
181
+ const range = options.range ?? (page ? {
182
+ start: page.pageIndex * page.pageSize,
183
+ end: (page.pageIndex + 1) * page.pageSize
184
+ } : {
185
+ start: 0,
186
+ end: 100
187
+ });
188
+ const leaves = (state.columnFilters ?? []).map(f => columnFilterNode(f.id, f.value)).filter(is.truthy);
189
+ const request = {
190
+ v: 1,
191
+ range,
192
+ sort: (state.sorting ?? []).map(s => ({
193
+ column: s.id,
194
+ dir: s.desc ? 'desc' : 'asc'
195
+ })),
196
+ filter: leaves.length === 0 ? null : leaves.length === 1 ? leaves[0] : {
197
+ op: 'and',
198
+ nodes: leaves
199
+ },
200
+ group: options.tree ? {
201
+ by: [],
202
+ keys: []
203
+ } : {
204
+ by: [...(state.grouping ?? [])],
205
+ keys: options.keys ?? []
206
+ },
207
+ aggregate: (options.aggregate ?? []).map(a => ({
208
+ ...a,
209
+ as: a.column
210
+ }))
211
+ };
212
+ // The parser rejects a key with no value, so an optional key is set only with a value.
213
+ if (is.string(state.globalFilter) && state.globalFilter !== '') request.search = state.globalFilter;
214
+ if (options.pivot) request.pivot = options.pivot;
215
+ if (options.columns) request.columns = options.columns;
216
+ if (options.count) request.count = true;
217
+ if (options.tree) request.tree = {
218
+ keys: options.tree
219
+ };
220
+ return request;
221
+ }
222
+
223
+ /**
224
+ * A map that keeps its entries in use order. `evict` removes the oldest entries above the limit;
225
+ * the caller calls it after it marks the keys in use.
226
+ */
227
+ class LruMap {
228
+ map = new Map();
229
+ max;
230
+ onEvict;
231
+ constructor(max, onEvict) {
232
+ this.max = max;
233
+ this.onEvict = onEvict;
234
+ }
235
+ get size() {
236
+ return this.map.size;
237
+ }
238
+ get(key) {
239
+ return this.map.get(key);
240
+ }
241
+ has(key) {
242
+ return this.map.has(key);
243
+ }
244
+ keys() {
245
+ return this.map.keys();
246
+ }
247
+ values() {
248
+ return this.map.values();
249
+ }
250
+
251
+ /** Make the entry the most recently used. */
252
+ touch(key) {
253
+ const value = this.map.get(key);
254
+ if (value === undefined) return;
255
+ this.map.delete(key);
256
+ this.map.set(key, value);
257
+ }
258
+ set(key, value) {
259
+ this.map.delete(key);
260
+ this.map.set(key, value);
261
+ }
262
+ delete(key) {
263
+ const value = this.map.get(key);
264
+ if (value === undefined) return;
265
+ this.map.delete(key);
266
+ this.onEvict?.(key, value);
267
+ }
268
+ clear() {
269
+ for (const key of [...this.map.keys()]) this.delete(key);
270
+ }
271
+
272
+ /** Evict the oldest entries above the limit. Pinned keys stay, also above the limit. */
273
+ evict(pinned = new Set()) {
274
+ for (const key of [...this.map.keys()]) {
275
+ if (this.map.size <= this.max) return;
276
+ if (!pinned.has(key)) this.delete(key);
277
+ }
278
+ }
279
+ }
280
+
281
+ /** Call `callback` on the next animation frame, or on the next task where no frame exists. */
282
+ const nextFrame = callback => {
283
+ if (is.function(globalThis.requestAnimationFrame)) requestAnimationFrame(() => callback());else setTimeout(callback, 0);
284
+ };
285
+
286
+ /** Collects the items of one frame and applies them in one call (`applyTransactionAsync`). */
287
+ class TransactionBatcher {
288
+ queue = [];
289
+ waiting = [];
290
+ apply;
291
+ schedule;
292
+ constructor(apply, schedule = nextFrame) {
293
+ this.apply = apply;
294
+ this.schedule = schedule;
295
+ }
296
+
297
+ /** Resolves when the frame applied the item. */
298
+ add(item) {
299
+ if (this.queue.length === 0) this.schedule(this.flush);
300
+ this.queue.push(item);
301
+ return new Promise(resolve => this.waiting.push(resolve));
302
+ }
303
+ flush = () => {
304
+ const items = this.queue;
305
+ const waiting = this.waiting;
306
+ this.queue = [];
307
+ this.waiting = [];
308
+ if (items.length > 0) this.apply(items);
309
+ for (const resolve of waiting) resolve();
310
+ };
311
+ }
312
+
313
+ // One block of rows and the Switchyard machine that runs its loading state (plan 5.2,
314
+ // decision 20). Only the load path goes through the machine. Scroll and render read the tracked
315
+ // `rows` and `state` fields of the block, never the machine.
316
+ class BlockState extends State {
317
+ static Idle = BlockState.of('idle');
318
+ static Loading = BlockState.of('loading');
319
+ static Loaded = BlockState.of('loaded');
320
+ static Stale = BlockState.of('stale');
321
+ static Reloading = BlockState.of('reloading');
322
+ static Failed = BlockState.of('failed');
323
+ }
324
+ class BlockMachine extends Machine {
325
+ static strict = true;
326
+ load() {}
327
+ static {
328
+ n(this.prototype, "load", [transition({
329
+ from: BlockState.Idle,
330
+ to: BlockState.Loading
331
+ })]);
332
+ }
333
+ resolve() {}
334
+ static {
335
+ n(this.prototype, "resolve", [transition({
336
+ from: [BlockState.Loading, BlockState.Reloading],
337
+ to: BlockState.Loaded
338
+ })]);
339
+ }
340
+ fail() {}
341
+ static {
342
+ n(this.prototype, "fail", [transition({
343
+ from: [BlockState.Loading, BlockState.Reloading],
344
+ to: BlockState.Failed
345
+ })]);
346
+ }
347
+ invalidate() {}
348
+ static {
349
+ n(this.prototype, "invalidate", [transition({
350
+ from: BlockState.Loaded,
351
+ to: BlockState.Stale
352
+ })]);
353
+ }
354
+ reload() {}
355
+ static {
356
+ n(this.prototype, "reload", [transition({
357
+ from: BlockState.Stale,
358
+ to: BlockState.Reloading
359
+ })]);
360
+ }
361
+ retry() {}
362
+
363
+ /** An aborted load. A block with rows keeps them and stays stale. */
364
+ static {
365
+ n(this.prototype, "retry", [transition({
366
+ from: BlockState.Failed,
367
+ to: BlockState.Loading
368
+ })]);
369
+ }
370
+ cancel() {}
371
+ static {
372
+ n(this.prototype, "cancel", [transition({
373
+ from: BlockState.Loading,
374
+ to: BlockState.Idle
375
+ })]);
376
+ }
377
+ cancelReload() {}
378
+ static {
379
+ n(this.prototype, "cancelReload", [transition({
380
+ from: BlockState.Reloading,
381
+ to: BlockState.Stale
382
+ })]);
383
+ }
384
+ }
385
+
386
+ /** The states in which a block has a request in flight. */
387
+ const isBusy = state => state === BlockState.Loading || state === BlockState.Reloading;
388
+ class Block {
389
+ static {
390
+ g(this.prototype, "state", [tracked], function () {
391
+ return BlockState.Idle;
392
+ });
393
+ }
394
+ #state = (i(this, "state"), void 0);
395
+ /** The mirror of the machine state, for render. */
396
+ static {
397
+ g(this.prototype, "rows", [tracked], function () {
398
+ return [];
399
+ });
400
+ }
401
+ #rows = (i(this, "rows"), void 0);
402
+ error = null;
403
+ response = null;
404
+ machine = new BlockMachine();
405
+ controller = null;
406
+ index;
407
+ /** The first row of the block in its level. */
408
+ start;
409
+ constructor(index, start) {
410
+ this.index = index;
411
+ this.start = start;
412
+ this.machine.subscribe(m => {
413
+ if (m.state !== this.state) this.state = m.state;
414
+ });
415
+ }
416
+ get busy() {
417
+ return isBusy(this.state);
418
+ }
419
+
420
+ /** Start a load (from idle, stale or failed) and give its signal. Null: no load to start. */
421
+ begin() {
422
+ const m = this.machine;
423
+ if (m.can.load) m.load();else if (m.can.reload) m.reload();else if (m.can.retry) m.retry();else return null;
424
+ this.controller = new AbortController();
425
+ return this.controller.signal;
426
+ }
427
+ finish(response) {
428
+ this.controller = null;
429
+ this.response = response;
430
+ this.rows = response.rows;
431
+ this.error = null;
432
+ this.machine.resolve();
433
+ }
434
+ failWith(error) {
435
+ this.controller = null;
436
+ this.error = error;
437
+ this.machine.fail();
438
+ }
439
+
440
+ /** Abort the request in flight. */
441
+ abort() {
442
+ this.controller?.abort();
443
+ this.controller = null;
444
+ if (this.machine.can.cancel) this.machine.cancel();else if (this.machine.can.cancelReload) this.machine.cancelReload();
445
+ }
446
+ invalidate() {
447
+ if (this.machine.can.invalidate) this.machine.invalidate();
448
+ }
449
+
450
+ /** Replace the rows in place (a live update). */
451
+ replaceRows(rows) {
452
+ this.rows = rows;
453
+ }
454
+ }
455
+
456
+ // A block cache for one level of rows: blocks of `blockSize` rows, LRU eviction above
457
+ // `maxBlocks`, and abort of the blocks that leave the view while they load.
458
+ function checkBlockOptions(blockSize, maxBlocks) {
459
+ if (!Number.isInteger(blockSize) || blockSize < 1 || blockSize > LIMITS.maxPage) {
460
+ throw new Error(`blockSize must be an integer from 1 to ${LIMITS.maxPage}`);
461
+ }
462
+ if (!Number.isInteger(maxBlocks) || maxBlocks < 1) {
463
+ throw new Error('maxBlocks must be a positive integer');
464
+ }
465
+ }
466
+ class BlockCache {
467
+ blocks;
468
+ options;
469
+ constructor(options) {
470
+ this.options = options;
471
+ this.blocks = new LruMap(options.maxBlocks, (_, block) => block.abort());
472
+ }
473
+ get blockSize() {
474
+ return this.options.blockSize;
475
+ }
476
+
477
+ /** The block of a row, if the cache has it. It does not change the use order (render path). */
478
+ blockOf(index) {
479
+ return this.blocks.get(Math.floor(index / this.options.blockSize));
480
+ }
481
+ rowAt(index) {
482
+ const block = this.blockOf(index);
483
+ return block?.rows[index - block.start];
484
+ }
485
+
486
+ /**
487
+ * Make the rows `start` to `end` (exclusive) loaded: load the missing blocks, abort the
488
+ * blocks in flight outside the range, and evict the oldest blocks above `maxBlocks`.
489
+ */
490
+ ensure(start, end) {
491
+ const size = this.options.blockSize;
492
+ const wanted = new Set();
493
+ for (let b = Math.floor(start / size); b * size < Math.max(end, start + 1); b++) wanted.add(b);
494
+ for (const block of [...this.blocks.values()]) {
495
+ if (block.busy && !wanted.has(block.index)) this.blocks.delete(block.index);
496
+ }
497
+ for (const b of wanted) {
498
+ let block = this.blocks.get(b);
499
+ if (!block) {
500
+ block = new Block(b, b * size);
501
+ this.blocks.set(b, block);
502
+ } else this.blocks.touch(b);
503
+ if (block.state === BlockState.Idle || block.state === BlockState.Stale) this.load(block);
504
+ }
505
+ this.blocks.evict(wanted);
506
+ }
507
+ load(block) {
508
+ const signal = block.begin();
509
+ if (!signal) return;
510
+ const request = this.options.request(block);
511
+ this.options.onPending?.(1);
512
+ this.options.fetch(request, signal).then(response => {
513
+ if (signal.aborted) return;
514
+ block.finish(response);
515
+ this.options.onLoad?.(block, response);
516
+ }, error => {
517
+ if (!signal.aborted) block.failWith(error);
518
+ }).finally(() => this.options.onPending?.(-1));
519
+ }
520
+
521
+ /** Mark every loaded block stale. With `purge`, drop them all. */
522
+ refresh(purge) {
523
+ if (purge) {
524
+ this.blocks.clear();
525
+ return;
526
+ }
527
+ for (const block of this.blocks.values()) block.invalidate();
528
+ }
529
+
530
+ /** Load the failed blocks again. */
531
+ retryFailed() {
532
+ for (const block of this.blocks.values()) {
533
+ if (block.state === BlockState.Failed) this.load(block);
534
+ }
535
+ }
536
+
537
+ /** Update the rows with these ids in place. Returns the ids it found. */
538
+ update(rows, getRowId) {
539
+ const byId = new Map(rows.map(row => [getRowId(row), row]));
540
+ const found = new Set();
541
+ for (const block of this.blocks.values()) {
542
+ let changed = false;
543
+ const next = block.rows.map(row => {
544
+ const id = getRowId(row);
545
+ const update = byId.get(id);
546
+ if (!update) return row;
547
+ found.add(id);
548
+ changed = true;
549
+ return update;
550
+ });
551
+ if (changed) block.replaceRows(next);
552
+ }
553
+ return found;
554
+ }
555
+ }
556
+
557
+ // The parts that every row model shares: the table binding, engine rows for loaded data, the
558
+ // query key, the pending count and the visible range from the grid.
559
+ class BaseRowModel {
560
+ static {
561
+ g(this.prototype, "pending", [tracked], function () {
562
+ return 0;
563
+ });
564
+ }
565
+ #pending = (i(this, "pending"), void 0);
566
+ /** The number of requests in flight. */
567
+ source;
568
+ table;
569
+ range = [0, 0];
570
+ rows = new WeakMap();
571
+ scheduled = false;
572
+ batcher = new TransactionBatcher(list => {
573
+ for (const tx of list) this.applyTransaction(tx);
574
+ });
575
+ constructor(options) {
576
+ this.source = options.source;
577
+ // The same cast as the core row models: the public table is the internal table.
578
+ this.table = options.table;
579
+ }
580
+
581
+ /** True when no request is in flight. */
582
+ get idle() {
583
+ return this.pending === 0;
584
+ }
585
+
586
+ /** The engine state that changes the rows of the server. */
587
+ get query() {
588
+ const state = this.table.store.state;
589
+ return {
590
+ sorting: state.sorting,
591
+ columnFilters: state.columnFilters,
592
+ globalFilter: state.globalFilter,
593
+ grouping: state.grouping
594
+ };
595
+ }
596
+
597
+ /** A string that changes when the query changes. The grid passes it to its range modifier. */
598
+ get queryKey() {
599
+ return JSON.stringify(this.query);
600
+ }
601
+ onPending = delta => {
602
+ this.pending += delta;
603
+ };
604
+
605
+ /** The engine row of a data row: the table's columns read its values. */
606
+ engineRow(original, index, depth = 0) {
607
+ let row = this.rows.get(original);
608
+ if (!row) {
609
+ row = constructRow(this.table, this.rowId(original), original, index, depth);
610
+ this.rows.set(original, row);
611
+ }
612
+ return row;
613
+ }
614
+ rowId(original) {
615
+ return this.source.getRowId(original);
616
+ }
617
+
618
+ /**
619
+ * The grid calls this after each render with the rows in view (`end` is exclusive). The
620
+ * work runs in a microtask: never during render, and once for many calls.
621
+ */
622
+ setRange(start, end) {
623
+ this.range = [start, end];
624
+ this.schedule();
625
+ }
626
+ schedule() {
627
+ if (this.scheduled) return;
628
+ this.scheduled = true;
629
+ queueMicrotask(() => {
630
+ this.scheduled = false;
631
+ this.flush();
632
+ });
633
+ }
634
+ /** Apply the transaction with the other transactions of this frame, in one update. */
635
+ applyTransactionAsync(tx) {
636
+ return this.batcher.add(tx);
637
+ }
638
+ }
639
+
640
+ // The infinite row model (plan 5.2): blocks of `blockSize` rows, an LRU block cache, and the
641
+ // sort and filter on the server.
642
+ class InfiniteRowModel extends BaseRowModel {
643
+ blockSize;
644
+ cache;
645
+ /** The total from the server, or null when it is not known. */
646
+ static {
647
+ g(this.prototype, "count", [tracked], function () {
648
+ return null;
649
+ });
650
+ }
651
+ #count = (i(this, "count"), void 0);
652
+ static {
653
+ g(this.prototype, "seen", [tracked], function () {
654
+ return 0;
655
+ });
656
+ }
657
+ #seen = (i(this, "seen"), void 0);
658
+ /** The rows known to exist, when the count is not known. */
659
+ key = null;
660
+ constructor(options) {
661
+ super(options);
662
+ this.blockSize = options.blockSize ?? 100;
663
+ const maxBlocks = options.maxBlocks ?? 10;
664
+ checkBlockOptions(this.blockSize, maxBlocks);
665
+ const aggregate = options.aggregate;
666
+ this.cache = new BlockCache({
667
+ blockSize: this.blockSize,
668
+ maxBlocks,
669
+ request: block => toRowsRequest(this.query, {
670
+ range: {
671
+ start: block.start,
672
+ end: block.start + this.blockSize
673
+ },
674
+ ...(aggregate && {
675
+ aggregate
676
+ }),
677
+ count: block.index === 0 && this.source.capabilities.count
678
+ }),
679
+ fetch: (request, signal) => this.source.getRows(request, signal),
680
+ onLoad: (block, response) => this.onLoad(block, response.rows.length, response.count),
681
+ onPending: this.onPending
682
+ });
683
+ }
684
+ get rowCount() {
685
+ return this.count;
686
+ }
687
+
688
+ /** The rows the grid shows: all rows, or the known rows and one block of skeleton rows. */
689
+ get displayCount() {
690
+ return this.count ?? this.seen + this.blockSize;
691
+ }
692
+ rowAt(index) {
693
+ const row = this.cache.rowAt(index);
694
+ return row === undefined ? undefined : this.engineRow(row, index);
695
+ }
696
+
697
+ /** The state of the block of a row, or undefined when the cache has no block for it. */
698
+ stateAt(index) {
699
+ return this.cache.blockOf(index)?.state;
700
+ }
701
+ failedAt(index) {
702
+ return this.cache.blockOf(index)?.state === BlockState.Failed;
703
+ }
704
+ onLoad(block, length, count) {
705
+ if (count !== undefined) this.count = count;else if (length < this.blockSize) this.count = block.start + length;else if (block.start + length > this.seen) this.seen = block.start + length;
706
+ }
707
+ flush() {
708
+ const key = this.queryKey;
709
+ if (key !== this.key) {
710
+ // A new sort or filter: the cached rows are of the old query.
711
+ if (this.key !== null) this.reset();
712
+ this.key = key;
713
+ }
714
+ this.cache.ensure(...this.range);
715
+ }
716
+ reset() {
717
+ this.cache.refresh(true);
718
+ this.count = null;
719
+ this.seen = 0;
720
+ }
721
+
722
+ /** Load the rows again. Without `purge` the old rows stay on screen until the new rows come. */
723
+ refresh({
724
+ purge = false
725
+ } = {}) {
726
+ if (purge) this.reset();else this.cache.refresh(false);
727
+ this.schedule();
728
+ }
729
+ retryFailed() {
730
+ this.cache.retryFailed();
731
+ }
732
+
733
+ /**
734
+ * Updates change the loaded rows in place. Adds and removes move rows between blocks, so
735
+ * they make the blocks stale: the blocks load again and keep their rows until then.
736
+ */
737
+ applyTransaction(tx) {
738
+ if (tx.update?.length) this.cache.update(tx.update, row => this.rowId(row));
739
+ if (tx.add?.length || tx.remove?.length) this.refresh();
740
+ }
741
+ }
742
+
743
+ // The server row model (plan 5.2): lazy group levels, a block cache for each group node, server
744
+ // group, aggregate and pivot, the grand total and transactions by route (group path).
745
+ /** One level of rows: the root, or the children of one group row. */
746
+ class GroupNode {
747
+ route;
748
+ /** The index of the group row in the parent node. It moves when the parent loads again. */
749
+ index;
750
+ cache;
751
+ /** The rows of the level, or null before the first block loads. */
752
+ static {
753
+ g(this.prototype, "count", [tracked], function () {
754
+ return null;
755
+ });
756
+ }
757
+ #count = (i(this, "count"), void 0);
758
+ static {
759
+ g(this.prototype, "groups", [tracked], function () {
760
+ return new Map();
761
+ });
762
+ }
763
+ #groups = (i(this, "groups"), void 0);
764
+ /** The loaded group rows of the level, by group row ID. */
765
+ childrenOf;
766
+ constructor(route, index, cache, childrenOf) {
767
+ this.route = route;
768
+ this.index = index;
769
+ this.cache = cache(this);
770
+ this.childrenOf = childrenOf;
771
+ }
772
+ get level() {
773
+ return this.route.length;
774
+ }
775
+
776
+ /** The expanded child nodes, in index order. They come from the table expanded state. */
777
+ get children() {
778
+ return this.childrenOf(this);
779
+ }
780
+ static {
781
+ n(this.prototype, "children", [cached]);
782
+ }
783
+ }
784
+
785
+ /** A plain column def fits each feature set: the feature options of a def are all optional. */
786
+ const asColumnDef = def => def;
787
+ const groupId = route => `group:${JSON.stringify(route)}`;
788
+ const sameRoute = (a, b) => a.length === b.length && a.every((k, i) => k === b[i]);
789
+ class ServerRowModel extends BaseRowModel {
790
+ blockSize;
791
+ maxBlocks;
792
+ options;
793
+ static {
794
+ g(this.prototype, "root", [tracked]);
795
+ }
796
+ #root = (i(this, "root"), void 0);
797
+ static {
798
+ g(this.prototype, "grandTotal", [tracked], function () {
799
+ return undefined;
800
+ });
801
+ }
802
+ #grandTotal = (i(this, "grandTotal"), void 0);
803
+ /** The aggregates over all rows (the grand total row). */
804
+ static {
805
+ g(this.prototype, "pivotColumns", [tracked], function () {
806
+ return undefined;
807
+ });
808
+ }
809
+ #pivotColumns = (i(this, "pivotColumns"), void 0);
810
+ groupIds = new WeakMap();
811
+ key = null;
812
+ /** The node of each expanded group row that rendered, by group row ID. */
813
+ childNodes = new Map();
814
+ /** The expanded state when the table has no row expanding feature. */
815
+ static {
816
+ g(this.prototype, "ownExpanded", [tracked], function () {
817
+ return {};
818
+ });
819
+ }
820
+ #ownExpanded = (i(this, "ownExpanded"), void 0);
821
+ /**
822
+ * The column defs of the table before the pivot columns.
823
+ * shortcut: read once; an app `setOptions` that changes the columns is lost at the next pivot change. Read them per change if apps do that.
824
+ */
825
+ baseColumns;
826
+ constructor(options) {
827
+ super(options);
828
+ this.options = options;
829
+ this.blockSize = options.blockSize ?? 100;
830
+ this.maxBlocks = options.maxBlocks ?? 10;
831
+ checkBlockOptions(this.blockSize, this.maxBlocks);
832
+ this.baseColumns = this.table.options.columns;
833
+ this.root = this.node([], 0);
834
+ }
835
+
836
+ /** The expanded group rows: `table.state.expanded` when the table has the feature. */
837
+ get expanded() {
838
+ if (!this.hasExpanding) return this.ownExpanded;
839
+ return this.table.store.state.expanded ?? {};
840
+ }
841
+ get hasExpanding() {
842
+ return is.function(Reflect.get(this.table, 'setExpanded'));
843
+ }
844
+ isExpanded(id) {
845
+ const expanded = this.expanded;
846
+ return expanded === true || expanded[id] === true;
847
+ }
848
+ setExpanded(id, open) {
849
+ const next = old => {
850
+ // shortcut: `true` (all expanded) becomes the loaded group rows; rows not loaded collapse.
851
+ const all = old === true ? this.loadedGroupIds() : {
852
+ ...old
853
+ };
854
+ if (open) all[id] = true;else delete all[id];
855
+ return all;
856
+ };
857
+ if (this.hasExpanding) {
858
+ const set = Reflect.get(this.table, 'setExpanded');
859
+ set.call(this.table, next);
860
+ } else this.ownExpanded = next(this.ownExpanded);
861
+ }
862
+ loadedGroupIds() {
863
+ const ids = {};
864
+ for (const node of this.nodes()) for (const id of node.groups.keys()) ids[id] = true;
865
+ return ids;
866
+ }
867
+
868
+ /** The child nodes of the expanded group rows that `node` has loaded. */
869
+ childrenOf = node => {
870
+ const children = [];
871
+ for (const [id, group] of node.groups) {
872
+ if (!this.isExpanded(id)) continue;
873
+ let child = this.childNodes.get(id);
874
+ if (!child) {
875
+ child = this.node([...node.route, group.key], group.index);
876
+ this.childNodes.set(id, child);
877
+ }
878
+ child.index = group.index;
879
+ children.push(child);
880
+ }
881
+ return children.sort((a, b) => a.index - b.index);
882
+ };
883
+ get groupBy() {
884
+ return this.query.grouping ?? [];
885
+ }
886
+ get tree() {
887
+ return this.groupBy.length > 0 || this.options.tree !== undefined;
888
+ }
889
+
890
+ /** The group key and label of a row that can expand, or undefined. */
891
+ groupOf(node, row) {
892
+ const tree = this.options.tree;
893
+ if (tree) {
894
+ const count = Reflect.get(row, GROUP_COUNT_KEY);
895
+ if (!is.number(count) || count <= 0) return undefined;
896
+ return {
897
+ key: Reflect.get(row, tree.key),
898
+ label: Reflect.get(row, tree.label)
899
+ };
900
+ }
901
+ const column = this.groupBy[node.level];
902
+ if (column === undefined) return undefined;
903
+ const key = Reflect.get(row, column);
904
+ return {
905
+ key,
906
+ label: key
907
+ };
908
+ }
909
+ node(route, index) {
910
+ const make = node => {
911
+ const {
912
+ aggregate,
913
+ pivot
914
+ } = this.options;
915
+ return new BlockCache({
916
+ blockSize: this.blockSize,
917
+ maxBlocks: this.maxBlocks,
918
+ request: block => toRowsRequest(this.query, {
919
+ range: {
920
+ start: block.start,
921
+ end: block.start + this.blockSize
922
+ },
923
+ keys: node.route,
924
+ // A tree route holds row keys, and a row key is never null.
925
+ ...(this.options.tree && {
926
+ tree: node.route
927
+ }),
928
+ ...(aggregate && {
929
+ aggregate
930
+ }),
931
+ ...(pivot && {
932
+ pivot
933
+ }),
934
+ count: block.index === 0
935
+ }),
936
+ fetch: (request, signal) => this.source.getRows(request, signal),
937
+ onLoad: (block, response) => {
938
+ if (response.count !== undefined) node.count = response.count;else if (response.rows.length < this.blockSize) node.count = block.start + response.rows.length;
939
+ if (this.options.tree || node.level < this.groupBy.length) {
940
+ const groups = new Map(node.groups);
941
+ response.rows.forEach((row, i) => {
942
+ const group = this.groupOf(node, row);
943
+ if (!group) return;
944
+ // A tree row keeps its own row ID, so the expanded state names the row.
945
+ const id = this.options.tree ? this.rowId(row) : groupId([...node.route, group.key]);
946
+ if (!this.options.tree) this.groupIds.set(row, id);
947
+ groups.set(id, {
948
+ index: block.start + i,
949
+ key: group.key
950
+ });
951
+ });
952
+ node.groups = groups;
953
+ }
954
+ if (node === this.root && block.index === 0) {
955
+ this.grandTotal = response.total;
956
+ if (response.total) this.groupIds.set(response.total, 'total');
957
+ this.setPivotColumns(response.pivotColumns);
958
+ }
959
+ },
960
+ onPending: this.onPending
961
+ });
962
+ };
963
+ return new GroupNode(route, index, make, this.childrenOf);
964
+ }
965
+
966
+ /** The grand total as an engine row, so the columns of the table read and format it. */
967
+ get totalRow() {
968
+ const total = this.grandTotal;
969
+ return total ? this.engineRow(total, -1) : undefined;
970
+ }
971
+
972
+ /**
973
+ * The pivot result columns become leaf columns of the table, after its own columns: one
974
+ * header group for each pivot key, with a leaf for each value. The leaf ID is the field.
975
+ */
976
+ setPivotColumns(columns) {
977
+ if (JSON.stringify(columns) === JSON.stringify(this.pivotColumns)) return;
978
+ this.pivotColumns = columns;
979
+ const groups = new Map();
980
+ for (const column of columns ?? []) {
981
+ const header = column.keys.map(k => k === null ? '(blank)' : String(k)).join(' / ');
982
+ const leaves = groups.get(header) ?? [];
983
+ leaves.push(asColumnDef({
984
+ id: column.field,
985
+ header: column.value,
986
+ accessorFn: row => Reflect.get(row, column.field)
987
+ }));
988
+ groups.set(header, leaves);
989
+ }
990
+ const pivot = [...groups].map(([header, leaves], i) => asColumnDef({
991
+ id: `pivot:${i}`,
992
+ header,
993
+ columns: leaves
994
+ }));
995
+ this.table.setOptions(old => ({
996
+ ...old,
997
+ columns: [...this.baseColumns, ...pivot]
998
+ }));
999
+ }
1000
+
1001
+ /** The display rows of a node: its own rows and the rows of its expanded children. */
1002
+ lengthOf(node) {
1003
+ let length = node.count ?? 1;
1004
+ for (const child of node.children) length += this.lengthOf(child);
1005
+ return length;
1006
+ }
1007
+ countsKnown(node) {
1008
+ return node.count !== null && node.children.every(c => this.countsKnown(c));
1009
+ }
1010
+
1011
+ /** The node and the index in the node of a display row. */
1012
+ locate(index, node = this.root) {
1013
+ let pos = index;
1014
+ for (const child of node.children) {
1015
+ if (pos <= child.index) return {
1016
+ node,
1017
+ local: pos
1018
+ };
1019
+ const rel = pos - child.index - 1;
1020
+ const length = this.lengthOf(child);
1021
+ if (rel < length) return this.locate(rel, child);
1022
+ pos -= length;
1023
+ }
1024
+ return {
1025
+ node,
1026
+ local: pos
1027
+ };
1028
+ }
1029
+ get displayCount() {
1030
+ return this.lengthOf(this.root);
1031
+ }
1032
+ get rowCount() {
1033
+ return this.countsKnown(this.root) ? this.displayCount : null;
1034
+ }
1035
+ rowAt(index) {
1036
+ const {
1037
+ node,
1038
+ local
1039
+ } = this.locate(index);
1040
+ const row = node.cache.rowAt(local);
1041
+ return row === undefined ? undefined : this.engineRow(row, index, node.level);
1042
+ }
1043
+ rowId(original) {
1044
+ return this.groupIds.get(original) ?? this.source.getRowId(original);
1045
+ }
1046
+ failedAt(index) {
1047
+ const {
1048
+ node,
1049
+ local
1050
+ } = this.locate(index);
1051
+ return node.cache.blockOf(local)?.state === BlockState.Failed;
1052
+ }
1053
+ levelAt(index) {
1054
+ return this.locate(index).node.level + 1;
1055
+ }
1056
+ groupAt(index) {
1057
+ const {
1058
+ node,
1059
+ local
1060
+ } = this.locate(index);
1061
+ const row = node.cache.rowAt(local);
1062
+ const group = row === undefined ? undefined : this.groupOf(node, row);
1063
+ if (row === undefined || !group) return undefined;
1064
+ const count = Reflect.get(row, GROUP_COUNT_KEY);
1065
+ return {
1066
+ level: node.level + 1,
1067
+ expanded: this.isExpanded(this.rowId(row)),
1068
+ label: `${group.label === null ? '(blank)' : String(group.label)} (${String(count)})`
1069
+ };
1070
+ }
1071
+
1072
+ /** Expand or collapse the group row at a display index. Its rows load when they come in view. */
1073
+ toggleGroup(index) {
1074
+ const {
1075
+ node,
1076
+ local
1077
+ } = this.locate(index);
1078
+ const row = node.cache.rowAt(local);
1079
+ if (row === undefined || !this.groupOf(node, row)) return;
1080
+ const id = this.rowId(row);
1081
+ const open = this.isExpanded(id);
1082
+ if (open) {
1083
+ // A group that opens again loads its rows again.
1084
+ this.childNodes.get(id)?.cache.refresh(true);
1085
+ this.childNodes.delete(id);
1086
+ }
1087
+ this.setExpanded(id, !open);
1088
+ this.schedule();
1089
+ }
1090
+ flush() {
1091
+ const key = this.queryKey;
1092
+ if (key !== this.key) {
1093
+ if (this.key !== null) this.reset();
1094
+ this.key = key;
1095
+ }
1096
+ // The local range of each node in view.
1097
+ const ranges = new Map();
1098
+ const [start, end] = this.range;
1099
+ for (let i = start; i < Math.max(end, start + 1); i++) {
1100
+ const {
1101
+ node,
1102
+ local
1103
+ } = this.locate(i);
1104
+ const r = ranges.get(node);
1105
+ ranges.set(node, r ? [Math.min(r[0], local), Math.max(r[1], local + 1)] : [local, local + 1]);
1106
+ }
1107
+ for (const [node, [from, to]] of ranges) node.cache.ensure(from, to);
1108
+ }
1109
+ reset() {
1110
+ this.clear(this.root);
1111
+ this.childNodes.clear();
1112
+ this.root = this.node([], 0);
1113
+ this.grandTotal = undefined;
1114
+ }
1115
+ clear(node) {
1116
+ node.cache.refresh(true);
1117
+ for (const child of node.children) this.clear(child);
1118
+ }
1119
+ nodes(node = this.root) {
1120
+ return [node, ...node.children.flatMap(c => this.nodes(c))];
1121
+ }
1122
+
1123
+ /** Load the rows again. Without `purge` the old rows stay on screen until the new rows come. */
1124
+ refresh({
1125
+ purge = false
1126
+ } = {}) {
1127
+ if (purge) this.reset();else for (const node of this.nodes()) node.cache.refresh(false);
1128
+ this.schedule();
1129
+ }
1130
+ retryFailed() {
1131
+ for (const node of this.nodes()) node.cache.retryFailed();
1132
+ }
1133
+
1134
+ /** Apply a transaction to the node of its route. Adds and removes reload that node. */
1135
+ applyTransaction(tx) {
1136
+ const route = tx.route ?? [];
1137
+ const node = this.nodes().find(n => sameRoute(n.route, route));
1138
+ if (!node) return;
1139
+ if (tx.update?.length) node.cache.update(tx.update, row => this.rowId(row));
1140
+ if (tx.add?.length || tx.remove?.length) {
1141
+ node.cache.refresh(false);
1142
+ this.schedule();
1143
+ }
1144
+ }
1145
+ }
1146
+
1147
+ // The viewport row model (plan 5.2): the grid reports the rows in view, the source sends only
1148
+ // those rows, and it pushes their changes. For live data at a high rate.
1149
+ class RowSlot {
1150
+ static {
1151
+ g(this.prototype, "row", [tracked]);
1152
+ }
1153
+ #row = (i(this, "row"), void 0);
1154
+ constructor(row) {
1155
+ this.row = row;
1156
+ }
1157
+ }
1158
+ class ViewportRowModel extends BaseRowModel {
1159
+ static {
1160
+ g(this.prototype, "count", [tracked], function () {
1161
+ return null;
1162
+ });
1163
+ }
1164
+ #count = (i(this, "count"), void 0);
1165
+ static {
1166
+ g(this.prototype, "slots", [tracked], function () {
1167
+ return new Map();
1168
+ });
1169
+ }
1170
+ #slots = (i(this, "slots"), void 0);
1171
+ /** The rows of the last response, by display index. */
1172
+ ids = new Map();
1173
+ controller = null;
1174
+ loaded = '';
1175
+ key = null;
1176
+ overscan;
1177
+ stop;
1178
+ constructor(options) {
1179
+ super(options);
1180
+ this.overscan = options.overscan ?? 10;
1181
+ // Live changes are batched: all the changes of one frame render once.
1182
+ this.stop = this.source.subscribe?.(tx => void this.applyTransactionAsync(tx)) ?? (() => {});
1183
+ }
1184
+
1185
+ /** Stop the live updates and abort the request in flight. */
1186
+ disconnect() {
1187
+ this.stop();
1188
+ this.controller?.abort();
1189
+ }
1190
+ get rowCount() {
1191
+ return this.count;
1192
+ }
1193
+ get displayCount() {
1194
+ return this.count ?? Math.max(this.range[1], 1);
1195
+ }
1196
+ rowAt(index) {
1197
+ const row = this.slots.get(index)?.row;
1198
+ return row === undefined ? undefined : this.engineRow(row, index);
1199
+ }
1200
+ flush() {
1201
+ const key = this.queryKey;
1202
+ if (key !== this.key) {
1203
+ this.key = key;
1204
+ this.loaded = '';
1205
+ this.count = null;
1206
+ }
1207
+ const start = Math.max(this.range[0] - this.overscan, 0);
1208
+ const end = this.range[1] + this.overscan;
1209
+ const want = `${key}:${start}:${end}`;
1210
+ if (want === this.loaded) return;
1211
+ this.loaded = want;
1212
+ this.controller?.abort();
1213
+ const controller = new AbortController();
1214
+ this.controller = controller;
1215
+ const request = toRowsRequest(this.query, {
1216
+ range: {
1217
+ start,
1218
+ end
1219
+ },
1220
+ count: true
1221
+ });
1222
+ this.onPending(1);
1223
+ this.source.getRows(request, controller.signal).then(response => {
1224
+ if (controller.signal.aborted) return;
1225
+ const slots = new Map();
1226
+ this.ids.clear();
1227
+ response.rows.forEach((row, i) => {
1228
+ slots.set(start + i, new RowSlot(row));
1229
+ this.ids.set(this.rowId(row), start + i);
1230
+ });
1231
+ this.slots = slots;
1232
+ if (response.count !== undefined) this.count = response.count;
1233
+ }, () => {
1234
+ // A failed or aborted range keeps the old rows. The next range asks again.
1235
+ if (!controller.signal.aborted) this.loaded = '';
1236
+ }).finally(() => this.onPending(-1));
1237
+ }
1238
+
1239
+ /** Updates change the rows in view in place. Adds and removes ask for the range again. */
1240
+ applyTransaction(tx) {
1241
+ for (const row of tx.update ?? []) {
1242
+ const index = this.ids.get(this.rowId(row));
1243
+ const slot = index === undefined ? undefined : this.slots.get(index);
1244
+ if (slot) slot.row = row;
1245
+ }
1246
+ if (tx.add?.length || tx.remove?.length) {
1247
+ this.loaded = '';
1248
+ this.schedule();
1249
+ }
1250
+ }
1251
+ refresh() {
1252
+ this.loaded = '';
1253
+ this.schedule();
1254
+ }
1255
+ }
1256
+
1257
+ // The client row model adapter: load every row of a DataSource, then give the rows to the
1258
+ // engine (`constructTable({ data })`). The engine sorts, filters and groups on the client.
1259
+ /** Ask for pages until a page is short. The rows come in the order of the key column. */
1260
+ async function loadAllRows(source, {
1261
+ pageSize = LIMITS.maxPage,
1262
+ signal = new AbortController().signal
1263
+ } = {}) {
1264
+ const size = Math.min(Math.max(Math.floor(pageSize), 1), LIMITS.maxPage);
1265
+ const rows = [];
1266
+ for (;;) {
1267
+ const request = {
1268
+ v: 1,
1269
+ range: {
1270
+ start: rows.length,
1271
+ end: rows.length + size
1272
+ },
1273
+ sort: [],
1274
+ filter: null,
1275
+ group: {
1276
+ by: [],
1277
+ keys: []
1278
+ },
1279
+ aggregate: []
1280
+ };
1281
+ const page = await source.getRows(request, signal);
1282
+ rows.push(...page.rows);
1283
+ if (page.rows.length < size || page.count !== undefined && rows.length >= page.count) {
1284
+ return rows;
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ // Cursor (keyset) paging in two directions (plan 5.2): blocks load after the last block and
1290
+ // before the first block, from an optional anchor cursor. For lists, deep scroll and chats.
1291
+ // shortcut: cursor mode keeps every loaded block (no eviction); evict at the front with a scroll anchor when lists need it.
1292
+ class CursorRowModel extends BaseRowModel {
1293
+ blockSize;
1294
+ start;
1295
+ /** The loaded blocks, in row order. */
1296
+ static {
1297
+ g(this.prototype, "blocks", [tracked], function () {
1298
+ return [];
1299
+ });
1300
+ }
1301
+ #blocks = (i(this, "blocks"), void 0);
1302
+ static {
1303
+ g(this.prototype, "edge", [tracked], function () {
1304
+ return {};
1305
+ });
1306
+ }
1307
+ #edge = (i(this, "edge"), void 0);
1308
+ /** The block that loads (or failed) at each end. */
1309
+ static {
1310
+ g(this.prototype, "more", [tracked], function () {
1311
+ return {
1312
+ after: true,
1313
+ before: false
1314
+ };
1315
+ });
1316
+ }
1317
+ #more = (i(this, "more"), void 0);
1318
+ static {
1319
+ g(this.prototype, "prepended", [tracked], function () {
1320
+ return 0;
1321
+ });
1322
+ }
1323
+ #prepended = (i(this, "prepended"), void 0);
1324
+ /** The number of rows added before the first row. A list keeps its scroll anchor with it. */
1325
+ cursors = {};
1326
+ key = null;
1327
+ nextIndex = 0;
1328
+ constructor(options) {
1329
+ super(options);
1330
+ this.blockSize = options.blockSize ?? 100;
1331
+ checkBlockOptions(this.blockSize, options.maxBlocks ?? 20);
1332
+ this.start = options.start ?? {};
1333
+ }
1334
+ get loadedCount() {
1335
+ return this.blocks.reduce((n, b) => n + b.rows.length, 0);
1336
+ }
1337
+ get rowCount() {
1338
+ return this.more.after || this.more.before ? null : this.loadedCount;
1339
+ }
1340
+
1341
+ /** The loaded rows and one skeleton row at the end while more rows can come. */
1342
+ get displayCount() {
1343
+ return this.loadedCount + (this.more.after ? 1 : 0);
1344
+ }
1345
+ rowAt(index) {
1346
+ let at = index;
1347
+ for (const block of this.blocks) {
1348
+ if (at < block.rows.length) return this.engineRow(block.rows[at], index);
1349
+ at -= block.rows.length;
1350
+ }
1351
+ return undefined;
1352
+ }
1353
+ failedAt(index) {
1354
+ return index >= this.loadedCount && this.edge.after?.state === BlockState.Failed;
1355
+ }
1356
+ flush() {
1357
+ const key = this.queryKey;
1358
+ if (key !== this.key) {
1359
+ if (this.key !== null) this.reset();
1360
+ this.key = key;
1361
+ }
1362
+ const [first, end] = this.range;
1363
+ const near = Math.ceil(this.blockSize / 2);
1364
+ if (this.blocks.length === 0) this.load('after');else {
1365
+ if (this.more.after && end >= this.loadedCount - near) this.load('after');
1366
+ if (this.more.before && first <= near) this.load('before');
1367
+ }
1368
+ }
1369
+ load(direction, retry = false) {
1370
+ const pending = this.edge[direction];
1371
+ if (pending && !(retry && pending.state === BlockState.Failed)) return;
1372
+ const initial = this.blocks.length === 0;
1373
+ const block = pending ?? new Block(this.nextIndex++, 0);
1374
+ const signal = block.begin();
1375
+ if (!signal) return;
1376
+ this.edge = {
1377
+ ...this.edge,
1378
+ [direction]: block
1379
+ };
1380
+ const cursor = initial ? this.start : {
1381
+ [direction]: this.cursors[direction]
1382
+ };
1383
+ const range = {
1384
+ limit: this.blockSize
1385
+ };
1386
+ if (cursor.after !== undefined) range.after = cursor.after;
1387
+ if (cursor.before !== undefined) range.before = cursor.before;
1388
+ this.onPending(1);
1389
+ this.source.getRows(toRowsRequest(this.query, {
1390
+ range
1391
+ }), signal).then(response => {
1392
+ if (signal.aborted) return;
1393
+ block.finish(response);
1394
+ const next = response.cursor?.next;
1395
+ const prev = response.cursor?.prev;
1396
+ const {
1397
+ [direction]: _done,
1398
+ ...rest
1399
+ } = this.edge;
1400
+ this.edge = rest;
1401
+ if (direction === 'after' || initial) {
1402
+ this.cursors.after = next;
1403
+ this.more = {
1404
+ ...this.more,
1405
+ after: next !== undefined
1406
+ };
1407
+ }
1408
+ if (direction === 'before' || initial) {
1409
+ this.cursors.before = prev;
1410
+ this.more = {
1411
+ ...this.more,
1412
+ before: prev !== undefined
1413
+ };
1414
+ }
1415
+ if (direction === 'before' && !initial) {
1416
+ this.blocks = [block, ...this.blocks];
1417
+ this.prepended += response.rows.length;
1418
+ } else {
1419
+ this.blocks = [...this.blocks, block];
1420
+ }
1421
+ this.schedule();
1422
+ }, error => {
1423
+ if (!signal.aborted) block.failWith(error);
1424
+ }).finally(() => this.onPending(-1));
1425
+ }
1426
+ reset() {
1427
+ for (const block of Object.values(this.edge)) block.abort();
1428
+ this.blocks = [];
1429
+ this.edge = {};
1430
+ this.more = {
1431
+ after: true,
1432
+ before: false
1433
+ };
1434
+ this.cursors = {};
1435
+ this.prepended = 0;
1436
+ }
1437
+
1438
+ /** Cursor blocks depend on each other, so a refresh always purges and starts at the anchor. */
1439
+ refresh() {
1440
+ this.reset();
1441
+ this.schedule();
1442
+ }
1443
+ retryFailed() {
1444
+ for (const direction of ['after', 'before']) {
1445
+ if (this.edge[direction]?.state === BlockState.Failed) this.load(direction, true);
1446
+ }
1447
+ }
1448
+
1449
+ /**
1450
+ * Updates change rows in place. A remove drops the row. An add goes at the end (or, with
1451
+ * `addIndex: 0`, at the start) only when that end is loaded; else the paging brings it.
1452
+ */
1453
+ applyTransaction(tx) {
1454
+ const updates = new Map((tx.update ?? []).map(row => [this.rowId(row), row]));
1455
+ const removed = new Set(tx.remove ?? []);
1456
+ for (const block of this.blocks) {
1457
+ if (!block.rows.some(r => updates.has(this.rowId(r)) || removed.has(this.rowId(r)))) continue;
1458
+ block.replaceRows(block.rows.filter(r => !removed.has(this.rowId(r))).map(r => updates.get(this.rowId(r)) ?? r));
1459
+ }
1460
+ const add = tx.add ?? [];
1461
+ if (add.length === 0) return;
1462
+ const first = this.blocks[0];
1463
+ const last = this.blocks[this.blocks.length - 1];
1464
+ if (tx.addIndex === 0 && first && !this.more.before) {
1465
+ first.replaceRows([...add, ...first.rows]);
1466
+ this.prepended += add.length;
1467
+ } else if (tx.addIndex === undefined && last && !this.more.after) {
1468
+ last.replaceRows([...last.rows, ...add]);
1469
+ }
1470
+ }
1471
+ }
1472
+
1473
+ export { BaseRowModel, Block, BlockCache, BlockMachine, BlockState, CursorRowModel, InfiniteRowModel, LruMap, ServerRowModel, TransactionBatcher, ViewportRowModel, applyTransaction, arrayDataSource, columnFilterNode, loadAllRows, toRowsRequest };
1474
+ //# sourceMappingURL=index.js.map