@tanstack/solid-virtual 3.0.0-beta.6 → 3.0.0-beta.61

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