@tanstack/react-virtual 3.0.0-beta.6 → 3.0.0-beta.60

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