@tanstack/solid-virtual 3.0.0-beta.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.
@@ -0,0 +1,653 @@
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
+ const observeElementRect = (instance, cb) => {
152
+ const observer = observeRect(instance.scrollElement, rect => {
153
+ cb(rect);
154
+ });
155
+
156
+ if (!instance.scrollElement) {
157
+ return;
158
+ }
159
+
160
+ cb(instance.scrollElement.getBoundingClientRect());
161
+ observer.observe();
162
+ return () => {
163
+ observer.unobserve();
164
+ };
165
+ };
166
+ const observeWindowRect = (instance, cb) => {
167
+ const onResize = () => {
168
+ cb({
169
+ width: instance.scrollElement.innerWidth,
170
+ height: instance.scrollElement.innerHeight
171
+ });
172
+ };
173
+
174
+ if (!instance.scrollElement) {
175
+ return;
176
+ }
177
+
178
+ onResize();
179
+ instance.scrollElement.addEventListener('resize', onResize, {
180
+ capture: false,
181
+ passive: true
182
+ });
183
+ return () => {
184
+ instance.scrollElement.removeEventListener('resize', onResize);
185
+ };
186
+ };
187
+ const observeElementOffset = (instance, cb) => {
188
+ const onScroll = () => cb(instance.scrollElement[instance.options.horizontal ? 'scrollLeft' : 'scrollTop']);
189
+
190
+ if (!instance.scrollElement) {
191
+ return;
192
+ }
193
+
194
+ onScroll();
195
+ instance.scrollElement.addEventListener('scroll', onScroll, {
196
+ capture: false,
197
+ passive: true
198
+ });
199
+ return () => {
200
+ instance.scrollElement.removeEventListener('scroll', onScroll);
201
+ };
202
+ };
203
+ const observeWindowOffset = (instance, cb) => {
204
+ const onScroll = () => cb(instance.scrollElement[instance.options.horizontal ? 'scrollX' : 'scrollY']);
205
+
206
+ if (!instance.scrollElement) {
207
+ return;
208
+ }
209
+
210
+ onScroll();
211
+ instance.scrollElement.addEventListener('scroll', onScroll, {
212
+ capture: false,
213
+ passive: true
214
+ });
215
+ return () => {
216
+ instance.scrollElement.removeEventListener('scroll', onScroll);
217
+ };
218
+ };
219
+ const measureElement = (element, instance) => {
220
+ return element.getBoundingClientRect()[instance.options.horizontal ? 'width' : 'height'];
221
+ };
222
+ const windowScroll = (offset, canSmooth, instance) => {
223
+ var _instance$scrollEleme;
224
+ (_instance$scrollEleme = instance.scrollElement) == null ? void 0 : _instance$scrollEleme.scrollTo({
225
+ [instance.options.horizontal ? 'left' : 'top']: offset,
226
+ behavior: canSmooth ? 'smooth' : undefined
227
+ });
228
+ };
229
+ const elementScroll = (offset, canSmooth, instance) => {
230
+ var _instance$scrollEleme2;
231
+ (_instance$scrollEleme2 = instance.scrollElement) == null ? void 0 : _instance$scrollEleme2.scrollTo({
232
+ [instance.options.horizontal ? 'left' : 'top']: offset,
233
+ behavior: canSmooth ? 'smooth' : undefined
234
+ });
235
+ };
236
+ class Virtualizer {
237
+ constructor(_opts) {
238
+ var _this = this;
239
+
240
+ this.unsubs = [];
241
+ this.scrollElement = null;
242
+ this.measurementsCache = [];
243
+ this.itemMeasurementsCache = {};
244
+ this.pendingMeasuredCacheIndexes = [];
245
+ this.measureElementCache = {};
246
+
247
+ this.setOptions = opts => {
248
+ Object.entries(opts).forEach(_ref => {
249
+ let [key, value] = _ref;
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
+ ...opts
271
+ };
272
+ };
273
+
274
+ this.notify = () => {
275
+ var _this$options$onChang, _this$options;
276
+
277
+ (_this$options$onChang = (_this$options = this.options).onChange) == null ? void 0 : _this$options$onChang.call(_this$options, this);
278
+ };
279
+
280
+ this.cleanup = () => {
281
+ this.unsubs.filter(Boolean).forEach(d => d());
282
+ this.unsubs = [];
283
+ };
284
+
285
+ this._didMount = () => {
286
+ return () => {
287
+ this.cleanup();
288
+ };
289
+ };
290
+
291
+ this._willUpdate = () => {
292
+ const scrollElement = this.options.getScrollElement();
293
+
294
+ if (this.scrollElement !== scrollElement) {
295
+ this.cleanup();
296
+ this.scrollElement = scrollElement;
297
+ this.unsubs.push(this.options.observeElementRect(this, rect => {
298
+ this.scrollRect = rect;
299
+ this.notify();
300
+ }));
301
+ this.unsubs.push(this.options.observeElementOffset(this, offset => {
302
+ this.scrollOffset = offset;
303
+ this.notify();
304
+ }));
305
+ }
306
+ };
307
+
308
+ this.getSize = () => {
309
+ return this.scrollRect[this.options.horizontal ? 'width' : 'height'];
310
+ };
311
+
312
+ this.getMeasurements = memo(() => [this.options.count, this.options.paddingStart, this.options.getItemKey, this.itemMeasurementsCache], (count, paddingStart, getItemKey, measurementsCache) => {
313
+ const min = this.pendingMeasuredCacheIndexes.length > 0 ? Math.min(...this.pendingMeasuredCacheIndexes) : 0;
314
+ this.pendingMeasuredCacheIndexes = [];
315
+ const measurements = this.measurementsCache.slice(0, min);
316
+
317
+ for (let i = min; i < count; i++) {
318
+ const key = getItemKey(i);
319
+ const measuredSize = measurementsCache[key];
320
+ const start = measurements[i - 1] ? measurements[i - 1].end : paddingStart;
321
+ const size = typeof measuredSize === 'number' ? measuredSize : this.options.estimateSize(i);
322
+ const end = start + size;
323
+ measurements[i] = {
324
+ index: i,
325
+ start,
326
+ size,
327
+ end,
328
+ key
329
+ };
330
+ }
331
+
332
+ this.measurementsCache = measurements;
333
+ return measurements;
334
+ }, {
335
+ key: 'getMeasurements',
336
+ debug: () => this.options.debug
337
+ });
338
+ this.calculateRange = memo(() => [this.getMeasurements(), this.getSize(), this.scrollOffset], (measurements, outerSize, scrollOffset) => {
339
+ return calculateRange({
340
+ measurements,
341
+ outerSize,
342
+ scrollOffset
343
+ });
344
+ }, {
345
+ key: 'calculateRange',
346
+ debug: () => this.options.debug
347
+ });
348
+ this.getIndexes = memo(() => [this.options.rangeExtractor, this.calculateRange(), this.options.overscan, this.options.count], (rangeExtractor, range, overscan, count) => {
349
+ return rangeExtractor({ ...range,
350
+ overscan,
351
+ count: count
352
+ });
353
+ }, {
354
+ key: 'getIndexes'
355
+ });
356
+ this.getVirtualItems = memo(() => [this.getIndexes(), this.getMeasurements(), this.options.measureElement], (indexes, measurements, measureElement) => {
357
+ const makeMeasureElement = index => measurableItem => {
358
+ var _this$itemMeasurement;
359
+
360
+ const item = this.measurementsCache[index];
361
+
362
+ if (!measurableItem) {
363
+ return;
364
+ }
365
+
366
+ const measuredItemSize = measureElement(measurableItem, this);
367
+ const itemSize = (_this$itemMeasurement = this.itemMeasurementsCache[item.key]) != null ? _this$itemMeasurement : item.size;
368
+
369
+ if (measuredItemSize !== itemSize) {
370
+ if (item.start < this.scrollOffset) {
371
+ if (this.options.debug) {
372
+ console.info('correction', measuredItemSize - itemSize);
373
+ }
374
+
375
+ if (!this.destinationOffset) {
376
+ this._scrollToOffset(this.scrollOffset + (measuredItemSize - itemSize), false);
377
+ }
378
+ }
379
+
380
+ this.pendingMeasuredCacheIndexes.push(index);
381
+ this.itemMeasurementsCache = { ...this.itemMeasurementsCache,
382
+ [item.key]: measuredItemSize
383
+ };
384
+ this.notify();
385
+ }
386
+ };
387
+
388
+ const virtualItems = [];
389
+ const currentMeasureElements = {};
390
+
391
+ for (let k = 0, len = indexes.length; k < len; k++) {
392
+ var _this$measureElementC;
393
+
394
+ const i = indexes[k];
395
+ const measurement = measurements[i];
396
+ const item = { ...measurement,
397
+ measureElement: currentMeasureElements[i] = (_this$measureElementC = this.measureElementCache[i]) != null ? _this$measureElementC : makeMeasureElement(i)
398
+ };
399
+ virtualItems.push(item);
400
+ }
401
+
402
+ this.measureElementCache = currentMeasureElements;
403
+ return virtualItems;
404
+ }, {
405
+ key: 'getIndexes'
406
+ });
407
+
408
+ this.scrollToOffset = function (toOffset, _temp) {
409
+ let {
410
+ align
411
+ } = _temp === void 0 ? {
412
+ align: 'start'
413
+ } : _temp;
414
+
415
+ const attempt = () => {
416
+ const offset = _this.scrollOffset;
417
+
418
+ const size = _this.getSize();
419
+
420
+ if (align === 'auto') {
421
+ if (toOffset <= offset) {
422
+ align = 'start';
423
+ } else if (toOffset >= offset + size) {
424
+ align = 'end';
425
+ } else {
426
+ align = 'start';
427
+ }
428
+ }
429
+
430
+ if (align === 'start') {
431
+ _this._scrollToOffset(toOffset, true);
432
+ } else if (align === 'end') {
433
+ _this._scrollToOffset(toOffset - size, true);
434
+ } else if (align === 'center') {
435
+ _this._scrollToOffset(toOffset - size / 2, true);
436
+ }
437
+ };
438
+
439
+ attempt();
440
+ requestAnimationFrame(() => {
441
+ attempt();
442
+ });
443
+ };
444
+
445
+ this.scrollToIndex = function (index, _temp2) {
446
+ let {
447
+ align,
448
+ ...rest
449
+ } = _temp2 === void 0 ? {
450
+ align: 'auto'
451
+ } : _temp2;
452
+
453
+ const measurements = _this.getMeasurements();
454
+
455
+ const offset = _this.scrollOffset;
456
+
457
+ const size = _this.getSize();
458
+
459
+ const {
460
+ count
461
+ } = _this.options;
462
+ const measurement = measurements[Math.max(0, Math.min(index, count - 1))];
463
+
464
+ if (!measurement) {
465
+ return;
466
+ }
467
+
468
+ if (align === 'auto') {
469
+ if (measurement.end >= offset + size - _this.options.scrollPaddingEnd) {
470
+ align = 'end';
471
+ } else if (measurement.start <= offset + _this.options.scrollPaddingStart) {
472
+ align = 'start';
473
+ } else {
474
+ return;
475
+ }
476
+ }
477
+
478
+ const toOffset = align === 'end' ? measurement.end + _this.options.scrollPaddingEnd : measurement.start - _this.options.scrollPaddingStart;
479
+
480
+ _this.scrollToOffset(toOffset, {
481
+ align,
482
+ ...rest
483
+ });
484
+ };
485
+
486
+ this.getTotalSize = () => {
487
+ var _this$getMeasurements;
488
+
489
+ return (((_this$getMeasurements = this.getMeasurements()[this.options.count - 1]) == null ? void 0 : _this$getMeasurements.end) || this.options.paddingStart) + this.options.paddingEnd;
490
+ };
491
+
492
+ this._scrollToOffset = (offset, canSmooth) => {
493
+ clearTimeout(this.scrollCheckFrame);
494
+ this.destinationOffset = offset;
495
+ this.options.scrollToFn(offset, this.options.enableSmoothScroll && canSmooth, this);
496
+ let scrollCheckFrame;
497
+
498
+ const check = () => {
499
+ let lastOffset = this.scrollOffset;
500
+ this.scrollCheckFrame = scrollCheckFrame = setTimeout(() => {
501
+ if (this.scrollCheckFrame !== scrollCheckFrame) {
502
+ return;
503
+ }
504
+
505
+ if (this.scrollOffset === lastOffset) {
506
+ this.destinationOffset = undefined;
507
+ return;
508
+ }
509
+
510
+ lastOffset = this.scrollOffset;
511
+ check();
512
+ }, 100);
513
+ };
514
+
515
+ check();
516
+ };
517
+
518
+ this.measure = () => {
519
+ this.itemMeasurementsCache = {};
520
+ this.notify();
521
+ };
522
+
523
+ this.setOptions(_opts);
524
+ this.scrollRect = this.options.initialRect;
525
+ this.scrollOffset = this.options.initialOffset;
526
+ }
527
+
528
+ }
529
+
530
+ const findNearestBinarySearch = (low, high, getCurrentValue, value) => {
531
+ while (low <= high) {
532
+ const middle = (low + high) / 2 | 0;
533
+ const currentValue = getCurrentValue(middle);
534
+
535
+ if (currentValue < value) {
536
+ low = middle + 1;
537
+ } else if (currentValue > value) {
538
+ high = middle - 1;
539
+ } else {
540
+ return middle;
541
+ }
542
+ }
543
+
544
+ if (low > 0) {
545
+ return low - 1;
546
+ } else {
547
+ return 0;
548
+ }
549
+ };
550
+
551
+ function calculateRange(_ref2) {
552
+ let {
553
+ measurements,
554
+ outerSize,
555
+ scrollOffset
556
+ } = _ref2;
557
+ const count = measurements.length - 1;
558
+
559
+ const getOffset = index => measurements[index].start;
560
+
561
+ const startIndex = findNearestBinarySearch(0, count, getOffset, scrollOffset);
562
+ let endIndex = startIndex;
563
+
564
+ while (endIndex < count && measurements[endIndex].end < scrollOffset + outerSize) {
565
+ endIndex++;
566
+ }
567
+
568
+ return {
569
+ startIndex,
570
+ endIndex
571
+ };
572
+ }
573
+
574
+ function createVirtualizerBase(options) {
575
+ const resolvedOptions = solidJs.mergeProps(options);
576
+ const instance = new Virtualizer(resolvedOptions);
577
+ const [virtualItems, setVirtualItems] = store.createStore(instance.getVirtualItems());
578
+ const [totalSize, setTotalSize] = solidJs.createSignal(instance.getTotalSize());
579
+ const handler = {
580
+ get(target, prop) {
581
+ switch (prop) {
582
+ case 'getVirtualItems':
583
+ return () => virtualItems;
584
+
585
+ case 'getTotalSize':
586
+ return () => totalSize();
587
+
588
+ default:
589
+ return Reflect.get(target, prop);
590
+ }
591
+ }
592
+
593
+ };
594
+ const virtualizer = new Proxy(instance, handler);
595
+ virtualizer.setOptions(resolvedOptions);
596
+ solidJs.onMount(() => {
597
+ const cleanup = virtualizer._didMount();
598
+
599
+ virtualizer._willUpdate();
600
+
601
+ solidJs.onCleanup(cleanup);
602
+ });
603
+ solidJs.createComputed(() => {
604
+ virtualizer.setOptions(solidJs.mergeProps(resolvedOptions, options, {
605
+ onChange: instance => {
606
+ instance._willUpdate();
607
+
608
+ setVirtualItems(store.reconcile(instance.getVirtualItems(), {
609
+ key: 'index'
610
+ }));
611
+ setTotalSize(instance.getTotalSize());
612
+ options.onChange == null ? void 0 : options.onChange(instance);
613
+ }
614
+ }));
615
+ virtualizer.measure();
616
+ });
617
+ return virtualizer;
618
+ }
619
+
620
+ function createVirtualizer(options) {
621
+ return createVirtualizerBase(solidJs.mergeProps({
622
+ observeElementRect: observeElementRect,
623
+ observeElementOffset: observeElementOffset,
624
+ scrollToFn: elementScroll
625
+ }, options));
626
+ }
627
+ function createWindowVirtualizer(options) {
628
+ return createVirtualizerBase(solidJs.mergeProps({
629
+ getScrollElement: () => typeof window !== 'undefined' ? window : null,
630
+ observeElementRect: observeWindowRect,
631
+ observeElementOffset: observeWindowOffset,
632
+ scrollToFn: windowScroll
633
+ }, options));
634
+ }
635
+
636
+ exports.Virtualizer = Virtualizer;
637
+ exports.createVirtualizer = createVirtualizer;
638
+ exports.createWindowVirtualizer = createWindowVirtualizer;
639
+ exports.defaultKeyExtractor = defaultKeyExtractor;
640
+ exports.defaultRangeExtractor = defaultRangeExtractor;
641
+ exports.elementScroll = elementScroll;
642
+ exports.measureElement = measureElement;
643
+ exports.memo = memo;
644
+ exports.observeElementOffset = observeElementOffset;
645
+ exports.observeElementRect = observeElementRect;
646
+ exports.observeWindowOffset = observeWindowOffset;
647
+ exports.observeWindowRect = observeWindowRect;
648
+ exports.windowScroll = windowScroll;
649
+
650
+ Object.defineProperty(exports, '__esModule', { value: true });
651
+
652
+ }));
653
+ //# sourceMappingURL=index.development.js.map