@tanstack/solid-virtual 3.0.0-beta.22 → 3.0.0-beta.26

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