@tanstack/solid-virtual 3.0.0-beta.10

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.
@@ -0,0 +1,685 @@
1
+ /**
2
+ * solid-virtual
3
+ *
4
+ * Copyright (c) TanStack
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE.md file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ (function (global, factory) {
12
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('solid-js'), require('solid-js/store')) :
13
+ typeof define === 'function' && define.amd ? define(['exports', 'solid-js', 'solid-js/store'], factory) :
14
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.SolidVirtual = {}, global.Solid, global["Solid/Store"]));
15
+ })(this, (function (exports, solidJs, store) { 'use strict';
16
+
17
+ /**
18
+ * virtual-core
19
+ *
20
+ * Copyright (c) TanStack
21
+ *
22
+ * This source code is licensed under the MIT license found in the
23
+ * LICENSE.md file in the root directory of this source tree.
24
+ *
25
+ * @license MIT
26
+ */
27
+ var props = ["bottom", "height", "left", "right", "top", "width"];
28
+
29
+ var rectChanged = function rectChanged(a, b) {
30
+ if (a === void 0) {
31
+ a = {};
32
+ }
33
+
34
+ if (b === void 0) {
35
+ b = {};
36
+ }
37
+
38
+ return props.some(function (prop) {
39
+ return a[prop] !== b[prop];
40
+ });
41
+ };
42
+
43
+ var observedNodes = /*#__PURE__*/new Map();
44
+ var rafId;
45
+
46
+ var run = function run() {
47
+ var changedStates = [];
48
+ observedNodes.forEach(function (state, node) {
49
+ var newRect = node.getBoundingClientRect();
50
+
51
+ if (rectChanged(newRect, state.rect)) {
52
+ state.rect = newRect;
53
+ changedStates.push(state);
54
+ }
55
+ });
56
+ changedStates.forEach(function (state) {
57
+ state.callbacks.forEach(function (cb) {
58
+ return cb(state.rect);
59
+ });
60
+ });
61
+ rafId = window.requestAnimationFrame(run);
62
+ };
63
+
64
+ function observeRect(node, cb) {
65
+ return {
66
+ observe: function observe() {
67
+ var wasEmpty = observedNodes.size === 0;
68
+
69
+ if (observedNodes.has(node)) {
70
+ observedNodes.get(node).callbacks.push(cb);
71
+ } else {
72
+ observedNodes.set(node, {
73
+ rect: undefined,
74
+ hasRectChanged: false,
75
+ callbacks: [cb]
76
+ });
77
+ }
78
+
79
+ if (wasEmpty) run();
80
+ },
81
+ unobserve: function unobserve() {
82
+ var state = observedNodes.get(node);
83
+
84
+ if (state) {
85
+ // Remove the callback
86
+ var index = state.callbacks.indexOf(cb);
87
+ if (index >= 0) state.callbacks.splice(index, 1); // Remove the node reference
88
+
89
+ if (!state.callbacks.length) observedNodes["delete"](node); // Stop the loop
90
+
91
+ if (!observedNodes.size) cancelAnimationFrame(rafId);
92
+ }
93
+ }
94
+ };
95
+ }
96
+
97
+ function memo(getDeps, fn, opts) {
98
+ let deps = [];
99
+ let result;
100
+ return () => {
101
+ let depTime;
102
+ if (opts.key && opts.debug != null && opts.debug()) depTime = Date.now();
103
+ const newDeps = getDeps();
104
+ const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep);
105
+
106
+ if (!depsChanged) {
107
+ return result;
108
+ }
109
+
110
+ deps = newDeps;
111
+ let resultTime;
112
+ if (opts.key && opts.debug != null && opts.debug()) resultTime = Date.now();
113
+ result = fn(...newDeps);
114
+ opts == null ? void 0 : opts.onChange == null ? void 0 : opts.onChange(result);
115
+
116
+ if (opts.key && opts.debug != null && opts.debug()) {
117
+ const depEndTime = Math.round((Date.now() - depTime) * 100) / 100;
118
+ const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100;
119
+ const resultFpsPercentage = resultEndTime / 16;
120
+
121
+ const pad = (str, num) => {
122
+ str = String(str);
123
+
124
+ while (str.length < num) {
125
+ str = ' ' + str;
126
+ }
127
+
128
+ return str;
129
+ };
130
+
131
+ console.info("%c\u23F1 " + pad(resultEndTime, 5) + " /" + pad(depEndTime, 5) + " ms", "\n font-size: .6rem;\n font-weight: bold;\n color: hsl(" + Math.max(0, Math.min(120 - 120 * resultFpsPercentage, 120)) + "deg 100% 31%);", opts == null ? void 0 : opts.key);
132
+ }
133
+
134
+ return result;
135
+ };
136
+ }
137
+
138
+ //
139
+ const defaultKeyExtractor = index => index;
140
+ const defaultRangeExtractor = range => {
141
+ const start = Math.max(range.startIndex - range.overscan, 0);
142
+ const end = Math.min(range.endIndex + range.overscan, range.count - 1);
143
+ const arr = [];
144
+
145
+ for (let i = start; i <= end; i++) {
146
+ arr.push(i);
147
+ }
148
+
149
+ return arr;
150
+ };
151
+
152
+ const memoRectCallback = (instance, cb) => {
153
+ let prev = {
154
+ height: -1,
155
+ width: -1
156
+ };
157
+ return rect => {
158
+ if (instance.options.horizontal ? rect.width !== prev.width : rect.height !== prev.height) {
159
+ cb(rect);
160
+ }
161
+
162
+ prev = rect;
163
+ };
164
+ };
165
+
166
+ const observeElementRect = (instance, cb) => {
167
+ const onResize = memoRectCallback(instance, cb);
168
+ const observer = observeRect(instance.scrollElement, rect => {
169
+ onResize(rect);
170
+ });
171
+
172
+ if (!instance.scrollElement) {
173
+ return;
174
+ }
175
+
176
+ onResize(instance.scrollElement.getBoundingClientRect());
177
+ observer.observe();
178
+ return () => {
179
+ observer.unobserve();
180
+ };
181
+ };
182
+ const observeWindowRect = (instance, cb) => {
183
+ const memoizedCallback = memoRectCallback(instance, cb);
184
+
185
+ const onResize = () => memoizedCallback({
186
+ width: instance.scrollElement.innerWidth,
187
+ height: instance.scrollElement.innerHeight
188
+ });
189
+
190
+ if (!instance.scrollElement) {
191
+ return;
192
+ }
193
+
194
+ onResize();
195
+ instance.scrollElement.addEventListener('resize', onResize, {
196
+ capture: false,
197
+ passive: true
198
+ });
199
+ return () => {
200
+ instance.scrollElement.removeEventListener('resize', onResize);
201
+ };
202
+ };
203
+ const scrollProps = {
204
+ element: ['scrollLeft', 'scrollTop'],
205
+ window: ['scrollX', 'scrollY']
206
+ };
207
+
208
+ const createOffsetObserver = mode => {
209
+ return (instance, cb) => {
210
+ if (!instance.scrollElement) {
211
+ return;
212
+ }
213
+
214
+ const propX = scrollProps[mode][0];
215
+ const propY = scrollProps[mode][1];
216
+ let prevX = instance.scrollElement[propX];
217
+ let prevY = instance.scrollElement[propY];
218
+
219
+ const scroll = () => {
220
+ cb(instance.scrollElement[instance.options.horizontal ? propX : propY]);
221
+ };
222
+
223
+ scroll();
224
+
225
+ const onScroll = e => {
226
+ const target = e.currentTarget;
227
+ const scrollX = target[propX];
228
+ const scrollY = target[propY];
229
+
230
+ if (instance.options.horizontal ? prevX - scrollX : prevY - scrollY) {
231
+ scroll();
232
+ }
233
+
234
+ prevX = scrollX;
235
+ prevY = scrollY;
236
+ };
237
+
238
+ instance.scrollElement.addEventListener('scroll', onScroll, {
239
+ capture: false,
240
+ passive: true
241
+ });
242
+ return () => {
243
+ instance.scrollElement.removeEventListener('scroll', onScroll);
244
+ };
245
+ };
246
+ };
247
+
248
+ const observeElementOffset = createOffsetObserver('element');
249
+ const observeWindowOffset = createOffsetObserver('window');
250
+ const measureElement = (element, instance) => {
251
+ return element.getBoundingClientRect()[instance.options.horizontal ? 'width' : 'height'];
252
+ };
253
+ const windowScroll = (offset, canSmooth, instance) => {
254
+ var _instance$scrollEleme;
255
+ (_instance$scrollEleme = instance.scrollElement) == null ? void 0 : _instance$scrollEleme.scrollTo({
256
+ [instance.options.horizontal ? 'left' : 'top']: offset,
257
+ behavior: canSmooth ? 'smooth' : undefined
258
+ });
259
+ };
260
+ const elementScroll = (offset, canSmooth, instance) => {
261
+ var _instance$scrollEleme2;
262
+ (_instance$scrollEleme2 = instance.scrollElement) == null ? void 0 : _instance$scrollEleme2.scrollTo({
263
+ [instance.options.horizontal ? 'left' : 'top']: offset,
264
+ behavior: canSmooth ? 'smooth' : undefined
265
+ });
266
+ };
267
+ class Virtualizer {
268
+ constructor(_opts) {
269
+ var _this = this;
270
+
271
+ this.unsubs = [];
272
+ this.scrollElement = null;
273
+ this.measurementsCache = [];
274
+ this.itemMeasurementsCache = {};
275
+ this.pendingMeasuredCacheIndexes = [];
276
+ this.measureElementCache = {};
277
+
278
+ this.setOptions = opts => {
279
+ Object.entries(opts).forEach(_ref => {
280
+ let [key, value] = _ref;
281
+ if (typeof value === 'undefined') delete opts[key];
282
+ });
283
+ this.options = {
284
+ debug: false,
285
+ initialOffset: 0,
286
+ overscan: 1,
287
+ paddingStart: 0,
288
+ paddingEnd: 0,
289
+ scrollPaddingStart: 0,
290
+ scrollPaddingEnd: 0,
291
+ horizontal: false,
292
+ getItemKey: defaultKeyExtractor,
293
+ rangeExtractor: defaultRangeExtractor,
294
+ enableSmoothScroll: true,
295
+ onChange: () => {},
296
+ measureElement,
297
+ initialRect: {
298
+ width: 0,
299
+ height: 0
300
+ },
301
+ ...opts
302
+ };
303
+ };
304
+
305
+ this.notify = () => {
306
+ var _this$options$onChang, _this$options;
307
+
308
+ (_this$options$onChang = (_this$options = this.options).onChange) == null ? void 0 : _this$options$onChang.call(_this$options, this);
309
+ };
310
+
311
+ this.cleanup = () => {
312
+ this.unsubs.filter(Boolean).forEach(d => d());
313
+ this.unsubs = [];
314
+ this.scrollElement = null;
315
+ };
316
+
317
+ this._didMount = () => {
318
+ return () => {
319
+ this.cleanup();
320
+ };
321
+ };
322
+
323
+ this._willUpdate = () => {
324
+ const scrollElement = this.options.getScrollElement();
325
+
326
+ if (this.scrollElement !== scrollElement) {
327
+ this.cleanup();
328
+ this.scrollElement = scrollElement;
329
+ this.unsubs.push(this.options.observeElementRect(this, rect => {
330
+ this.scrollRect = rect;
331
+ this.notify();
332
+ }));
333
+ this.unsubs.push(this.options.observeElementOffset(this, offset => {
334
+ this.scrollOffset = offset;
335
+ this.notify();
336
+ }));
337
+ }
338
+ };
339
+
340
+ this.getSize = () => {
341
+ return this.scrollRect[this.options.horizontal ? 'width' : 'height'];
342
+ };
343
+
344
+ this.getMeasurements = memo(() => [this.options.count, this.options.paddingStart, this.options.getItemKey, this.itemMeasurementsCache], (count, paddingStart, getItemKey, measurementsCache) => {
345
+ const min = this.pendingMeasuredCacheIndexes.length > 0 ? Math.min(...this.pendingMeasuredCacheIndexes) : 0;
346
+ this.pendingMeasuredCacheIndexes = [];
347
+ const measurements = this.measurementsCache.slice(0, min);
348
+
349
+ for (let i = min; i < count; i++) {
350
+ const key = getItemKey(i);
351
+ const measuredSize = measurementsCache[key];
352
+ const start = measurements[i - 1] ? measurements[i - 1].end : paddingStart;
353
+ const size = typeof measuredSize === 'number' ? measuredSize : this.options.estimateSize(i);
354
+ const end = start + size;
355
+ measurements[i] = {
356
+ index: i,
357
+ start,
358
+ size,
359
+ end,
360
+ key
361
+ };
362
+ }
363
+
364
+ this.measurementsCache = measurements;
365
+ return measurements;
366
+ }, {
367
+ key: 'getMeasurements',
368
+ debug: () => this.options.debug
369
+ });
370
+ this.calculateRange = memo(() => [this.getMeasurements(), this.getSize(), this.scrollOffset], (measurements, outerSize, scrollOffset) => {
371
+ return calculateRange({
372
+ measurements,
373
+ outerSize,
374
+ scrollOffset
375
+ });
376
+ }, {
377
+ key: 'calculateRange',
378
+ debug: () => this.options.debug
379
+ });
380
+ this.getIndexes = memo(() => [this.options.rangeExtractor, this.calculateRange(), this.options.overscan, this.options.count], (rangeExtractor, range, overscan, count) => {
381
+ return rangeExtractor({ ...range,
382
+ overscan,
383
+ count: count
384
+ });
385
+ }, {
386
+ key: 'getIndexes'
387
+ });
388
+ this.getVirtualItems = memo(() => [this.getIndexes(), this.getMeasurements(), this.options.measureElement], (indexes, measurements, measureElement) => {
389
+ const makeMeasureElement = index => measurableItem => {
390
+ var _this$itemMeasurement;
391
+
392
+ const item = this.measurementsCache[index];
393
+
394
+ if (!measurableItem) {
395
+ return;
396
+ }
397
+
398
+ const measuredItemSize = measureElement(measurableItem, this);
399
+ const itemSize = (_this$itemMeasurement = this.itemMeasurementsCache[item.key]) != null ? _this$itemMeasurement : item.size;
400
+
401
+ if (measuredItemSize !== itemSize) {
402
+ if (item.start < this.scrollOffset) {
403
+ if (this.options.debug) {
404
+ console.info('correction', measuredItemSize - itemSize);
405
+ }
406
+
407
+ if (!this.destinationOffset) {
408
+ this._scrollToOffset(this.scrollOffset + (measuredItemSize - itemSize), false);
409
+ }
410
+ }
411
+
412
+ this.pendingMeasuredCacheIndexes.push(index);
413
+ this.itemMeasurementsCache = { ...this.itemMeasurementsCache,
414
+ [item.key]: measuredItemSize
415
+ };
416
+ this.notify();
417
+ }
418
+ };
419
+
420
+ const virtualItems = [];
421
+ const currentMeasureElements = {};
422
+
423
+ for (let k = 0, len = indexes.length; k < len; k++) {
424
+ var _this$measureElementC;
425
+
426
+ const i = indexes[k];
427
+ const measurement = measurements[i];
428
+ const item = { ...measurement,
429
+ measureElement: currentMeasureElements[i] = (_this$measureElementC = this.measureElementCache[i]) != null ? _this$measureElementC : makeMeasureElement(i)
430
+ };
431
+ virtualItems.push(item);
432
+ }
433
+
434
+ this.measureElementCache = currentMeasureElements;
435
+ return virtualItems;
436
+ }, {
437
+ key: 'getIndexes'
438
+ });
439
+
440
+ this.scrollToOffset = function (toOffset, _temp) {
441
+ let {
442
+ align
443
+ } = _temp === void 0 ? {
444
+ align: 'start'
445
+ } : _temp;
446
+
447
+ const attempt = () => {
448
+ const offset = _this.scrollOffset;
449
+
450
+ const size = _this.getSize();
451
+
452
+ if (align === 'auto') {
453
+ if (toOffset <= offset) {
454
+ align = 'start';
455
+ } else if (toOffset >= offset + size) {
456
+ align = 'end';
457
+ } else {
458
+ align = 'start';
459
+ }
460
+ }
461
+
462
+ if (align === 'start') {
463
+ _this._scrollToOffset(toOffset, true);
464
+ } else if (align === 'end') {
465
+ _this._scrollToOffset(toOffset - size, true);
466
+ } else if (align === 'center') {
467
+ _this._scrollToOffset(toOffset - size / 2, true);
468
+ }
469
+ };
470
+
471
+ attempt();
472
+ requestAnimationFrame(() => {
473
+ attempt();
474
+ });
475
+ };
476
+
477
+ this.scrollToIndex = function (index, _temp2) {
478
+ let {
479
+ align,
480
+ ...rest
481
+ } = _temp2 === void 0 ? {
482
+ align: 'auto'
483
+ } : _temp2;
484
+
485
+ const measurements = _this.getMeasurements();
486
+
487
+ const offset = _this.scrollOffset;
488
+
489
+ const size = _this.getSize();
490
+
491
+ const {
492
+ count
493
+ } = _this.options;
494
+ const measurement = measurements[Math.max(0, Math.min(index, count - 1))];
495
+
496
+ if (!measurement) {
497
+ return;
498
+ }
499
+
500
+ if (align === 'auto') {
501
+ if (measurement.end >= offset + size - _this.options.scrollPaddingEnd) {
502
+ align = 'end';
503
+ } else if (measurement.start <= offset + _this.options.scrollPaddingStart) {
504
+ align = 'start';
505
+ } else {
506
+ return;
507
+ }
508
+ }
509
+
510
+ const toOffset = align === 'end' ? measurement.end + _this.options.scrollPaddingEnd : measurement.start - _this.options.scrollPaddingStart;
511
+
512
+ _this.scrollToOffset(toOffset, {
513
+ align,
514
+ ...rest
515
+ });
516
+ };
517
+
518
+ this.getTotalSize = () => {
519
+ var _this$getMeasurements;
520
+
521
+ return (((_this$getMeasurements = this.getMeasurements()[this.options.count - 1]) == null ? void 0 : _this$getMeasurements.end) || this.options.paddingStart) + this.options.paddingEnd;
522
+ };
523
+
524
+ this._scrollToOffset = (offset, canSmooth) => {
525
+ clearTimeout(this.scrollCheckFrame);
526
+ this.destinationOffset = offset;
527
+ this.options.scrollToFn(offset, this.options.enableSmoothScroll && canSmooth, this);
528
+ let scrollCheckFrame;
529
+
530
+ const check = () => {
531
+ let lastOffset = this.scrollOffset;
532
+ this.scrollCheckFrame = scrollCheckFrame = setTimeout(() => {
533
+ if (this.scrollCheckFrame !== scrollCheckFrame) {
534
+ return;
535
+ }
536
+
537
+ if (this.scrollOffset === lastOffset) {
538
+ this.destinationOffset = undefined;
539
+ return;
540
+ }
541
+
542
+ lastOffset = this.scrollOffset;
543
+ check();
544
+ }, 100);
545
+ };
546
+
547
+ check();
548
+ };
549
+
550
+ this.measure = () => {
551
+ this.itemMeasurementsCache = {};
552
+ this.notify();
553
+ };
554
+
555
+ this.setOptions(_opts);
556
+ this.scrollRect = this.options.initialRect;
557
+ this.scrollOffset = this.options.initialOffset;
558
+ }
559
+
560
+ }
561
+
562
+ const findNearestBinarySearch = (low, high, getCurrentValue, value) => {
563
+ while (low <= high) {
564
+ const middle = (low + high) / 2 | 0;
565
+ const currentValue = getCurrentValue(middle);
566
+
567
+ if (currentValue < value) {
568
+ low = middle + 1;
569
+ } else if (currentValue > value) {
570
+ high = middle - 1;
571
+ } else {
572
+ return middle;
573
+ }
574
+ }
575
+
576
+ if (low > 0) {
577
+ return low - 1;
578
+ } else {
579
+ return 0;
580
+ }
581
+ };
582
+
583
+ function calculateRange(_ref2) {
584
+ let {
585
+ measurements,
586
+ outerSize,
587
+ scrollOffset
588
+ } = _ref2;
589
+ const count = measurements.length - 1;
590
+
591
+ const getOffset = index => measurements[index].start;
592
+
593
+ const startIndex = findNearestBinarySearch(0, count, getOffset, scrollOffset);
594
+ let endIndex = startIndex;
595
+
596
+ while (endIndex < count && measurements[endIndex].end < scrollOffset + outerSize) {
597
+ endIndex++;
598
+ }
599
+
600
+ return {
601
+ startIndex,
602
+ endIndex
603
+ };
604
+ }
605
+
606
+ function createVirtualizerBase(options) {
607
+ const resolvedOptions = solidJs.mergeProps(options);
608
+ const instance = new Virtualizer(resolvedOptions);
609
+ const [virtualItems, setVirtualItems] = store.createStore(instance.getVirtualItems());
610
+ const [totalSize, setTotalSize] = solidJs.createSignal(instance.getTotalSize());
611
+ const handler = {
612
+ get(target, prop) {
613
+ switch (prop) {
614
+ case 'getVirtualItems':
615
+ return () => virtualItems;
616
+
617
+ case 'getTotalSize':
618
+ return () => totalSize();
619
+
620
+ default:
621
+ return Reflect.get(target, prop);
622
+ }
623
+ }
624
+
625
+ };
626
+ const virtualizer = new Proxy(instance, handler);
627
+ virtualizer.setOptions(resolvedOptions);
628
+ solidJs.onMount(() => {
629
+ const cleanup = virtualizer._didMount();
630
+
631
+ virtualizer._willUpdate();
632
+
633
+ solidJs.onCleanup(cleanup);
634
+ });
635
+ solidJs.createComputed(() => {
636
+ virtualizer.setOptions(solidJs.mergeProps(resolvedOptions, options, {
637
+ onChange: instance => {
638
+ instance._willUpdate();
639
+
640
+ setVirtualItems(store.reconcile(instance.getVirtualItems(), {
641
+ key: 'index'
642
+ }));
643
+ setTotalSize(instance.getTotalSize());
644
+ options.onChange == null ? void 0 : options.onChange(instance);
645
+ }
646
+ }));
647
+ virtualizer.measure();
648
+ });
649
+ return virtualizer;
650
+ }
651
+
652
+ function createVirtualizer(options) {
653
+ return createVirtualizerBase(solidJs.mergeProps({
654
+ observeElementRect: observeElementRect,
655
+ observeElementOffset: observeElementOffset,
656
+ scrollToFn: elementScroll
657
+ }, options));
658
+ }
659
+ function createWindowVirtualizer(options) {
660
+ return createVirtualizerBase(solidJs.mergeProps({
661
+ getScrollElement: () => typeof window !== 'undefined' ? window : null,
662
+ observeElementRect: observeWindowRect,
663
+ observeElementOffset: observeWindowOffset,
664
+ scrollToFn: windowScroll
665
+ }, options));
666
+ }
667
+
668
+ exports.Virtualizer = Virtualizer;
669
+ exports.createVirtualizer = createVirtualizer;
670
+ exports.createWindowVirtualizer = createWindowVirtualizer;
671
+ exports.defaultKeyExtractor = defaultKeyExtractor;
672
+ exports.defaultRangeExtractor = defaultRangeExtractor;
673
+ exports.elementScroll = elementScroll;
674
+ exports.measureElement = measureElement;
675
+ exports.memo = memo;
676
+ exports.observeElementOffset = observeElementOffset;
677
+ exports.observeElementRect = observeElementRect;
678
+ exports.observeWindowOffset = observeWindowOffset;
679
+ exports.observeWindowRect = observeWindowRect;
680
+ exports.windowScroll = windowScroll;
681
+
682
+ Object.defineProperty(exports, '__esModule', { value: true });
683
+
684
+ }));
685
+ //# sourceMappingURL=index.development.js.map