@tanstack/solid-virtual 3.0.0-beta.9 → 3.0.1

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