@oxog/scrollex 1.0.0 → 1.1.0

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.
package/dist/index.cjs CHANGED
@@ -1,10 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ var chunkND5PV5MU_cjs = require('./chunk-ND5PV5MU.cjs');
3
4
  var react = require('react');
4
5
  var jsxRuntime = require('react/jsx-runtime');
5
6
 
6
- // src/react/components/virtual-list.tsx
7
-
8
7
  // src/kernel/event-bus.ts
9
8
  var EventBus = class {
10
9
  constructor() {
@@ -99,9 +98,11 @@ var EventBus = class {
99
98
  */
100
99
  dispatchEvent(event) {
101
100
  const eventType = event.type;
101
+ const onceSnapshot = Array.from(this.onceHandlers.get(eventType) ?? []);
102
102
  const handlers = this.handlers.get(eventType);
103
103
  if (handlers) {
104
- for (const handler of handlers) {
104
+ for (const handler of Array.from(handlers)) {
105
+ if (!handlers.has(handler)) continue;
105
106
  try {
106
107
  handler(event);
107
108
  } catch (error) {
@@ -109,20 +110,17 @@ var EventBus = class {
109
110
  }
110
111
  }
111
112
  }
112
- const onceHandlers = this.onceHandlers.get(eventType);
113
- if (onceHandlers) {
114
- const handlersToCall = Array.from(onceHandlers);
115
- onceHandlers.clear();
116
- for (const handler of handlersToCall) {
117
- try {
118
- handler(event);
119
- } catch (error) {
120
- console.error(`[Scrollex] Error in once handler for "${eventType}":`, error);
121
- }
122
- }
113
+ for (const handler of onceSnapshot) {
114
+ const onceHandlers = this.onceHandlers.get(eventType);
115
+ if (!onceHandlers || !onceHandlers.delete(handler)) continue;
123
116
  if (onceHandlers.size === 0) {
124
117
  this.onceHandlers.delete(eventType);
125
118
  }
119
+ try {
120
+ handler(event);
121
+ } catch (error) {
122
+ console.error(`[Scrollex] Error in once handler for "${eventType}":`, error);
123
+ }
126
124
  }
127
125
  }
128
126
  /**
@@ -151,6 +149,7 @@ var EventBus = class {
151
149
  * Remove all handlers.
152
150
  */
153
151
  clear() {
152
+ for (const handlers of this.handlers.values()) handlers.clear();
154
153
  this.handlers.clear();
155
154
  this.onceHandlers.clear();
156
155
  this.pendingEvents = [];
@@ -162,6 +161,7 @@ var EventBus = class {
162
161
  * @param eventType - Type of event to clear handlers for
163
162
  */
164
163
  clearEvent(eventType) {
164
+ this.handlers.get(eventType)?.clear();
165
165
  this.handlers.delete(eventType);
166
166
  this.onceHandlers.delete(eventType);
167
167
  }
@@ -210,7 +210,7 @@ function setScrollPosition(element, position) {
210
210
  function getScrollDirection(current, previous) {
211
211
  const deltaY = current.scrollTop - previous.scrollTop;
212
212
  const deltaX = current.scrollLeft - previous.scrollLeft;
213
- if (Math.abs(deltaY) > Math.abs(deltaX)) {
213
+ if (Math.abs(deltaY) >= Math.abs(deltaX)) {
214
214
  if (deltaY > 0) return "down";
215
215
  if (deltaY < 0) return "up";
216
216
  } else {
@@ -220,21 +220,6 @@ function getScrollDirection(current, previous) {
220
220
  return "none";
221
221
  }
222
222
 
223
- // src/utils/raf.ts
224
- function raf(callback) {
225
- if (typeof requestAnimationFrame !== "undefined") {
226
- return requestAnimationFrame(callback);
227
- }
228
- return setTimeout(() => callback(Date.now()), 16);
229
- }
230
- function cancelRaf(id) {
231
- if (typeof cancelAnimationFrame !== "undefined") {
232
- cancelAnimationFrame(id);
233
- } else {
234
- clearTimeout(id);
235
- }
236
- }
237
-
238
223
  // src/kernel/scroll-engine.ts
239
224
  var easings = {
240
225
  linear: (t) => t,
@@ -250,11 +235,15 @@ var ScrollEngine = class {
250
235
  this.container = null;
251
236
  this.scrollPosition = { scrollTop: 0, scrollLeft: 0 };
252
237
  this.previousScrollPosition = { scrollTop: 0, scrollLeft: 0 };
238
+ // The position the last scroll event reported (scrollPosition is also updated by programmatic scrolls, ahead of the
239
+ // event the browser fires for them, and a delta against it would always be 0)
240
+ this.reportedPosition = { scrollTop: 0, scrollLeft: 0 };
253
241
  this.scrolling = false;
254
242
  this.scrollDirection = "none";
255
243
  this.lastScrollTime = 0;
256
244
  this.scrollEndTimer = null;
257
245
  this.scrollEndDelay = 150;
246
+ this.horizontal = false;
258
247
  // Animation state
259
248
  this.animationId = null;
260
249
  this.animationStartTime = 0;
@@ -280,6 +269,7 @@ var ScrollEngine = class {
280
269
  this.container = container;
281
270
  this.scrollPosition = getScrollPosition(container);
282
271
  this.previousScrollPosition = { ...this.scrollPosition };
272
+ this.reportedPosition = { ...this.scrollPosition };
283
273
  this.throttledHandleScroll = throttleRAF(this.processScroll.bind(this));
284
274
  this.boundHandleScroll = () => this.throttledHandleScroll?.();
285
275
  container.addEventListener("scroll", this.boundHandleScroll, { passive: true });
@@ -288,6 +278,15 @@ var ScrollEngine = class {
288
278
  * Detach from the current container.
289
279
  */
290
280
  detach() {
281
+ if (this.scrolling) {
282
+ this.scrolling = false;
283
+ this.onScrollEndCallback?.({
284
+ type: "scroll-end",
285
+ scrollTop: this.scrollPosition.scrollTop,
286
+ scrollLeft: this.scrollPosition.scrollLeft,
287
+ timestamp: performance.now()
288
+ });
289
+ }
291
290
  if (this.container && this.boundHandleScroll) {
292
291
  this.container.removeEventListener("scroll", this.boundHandleScroll);
293
292
  }
@@ -300,7 +299,7 @@ var ScrollEngine = class {
300
299
  this.scrollEndTimer = null;
301
300
  }
302
301
  if (this.animationId) {
303
- cancelRaf(this.animationId);
302
+ chunkND5PV5MU_cjs.cancelRaf(this.animationId);
304
303
  this.animationId = null;
305
304
  }
306
305
  this.boundHandleScroll = null;
@@ -312,8 +311,9 @@ var ScrollEngine = class {
312
311
  processScroll() {
313
312
  if (!this.container) return;
314
313
  const now = performance.now();
315
- this.previousScrollPosition = { ...this.scrollPosition };
314
+ this.previousScrollPosition = { ...this.reportedPosition };
316
315
  this.scrollPosition = getScrollPosition(this.container);
316
+ this.reportedPosition = { ...this.scrollPosition };
317
317
  this.scrollDirection = getScrollDirection(this.scrollPosition, this.previousScrollPosition);
318
318
  if (!this.scrolling) {
319
319
  this.scrolling = true;
@@ -370,15 +370,16 @@ var ScrollEngine = class {
370
370
  setScrollPosition(position) {
371
371
  if (!this.container) return;
372
372
  if (this.animationId) {
373
- cancelRaf(this.animationId);
373
+ chunkND5PV5MU_cjs.cancelRaf(this.animationId);
374
374
  this.animationId = null;
375
375
  }
376
376
  setScrollPosition(this.container, position);
377
+ const actual = getScrollPosition(this.container);
377
378
  if (position.scrollTop !== void 0) {
378
- this.scrollPosition.scrollTop = position.scrollTop;
379
+ this.scrollPosition.scrollTop = actual.scrollTop;
379
380
  }
380
381
  if (position.scrollLeft !== void 0) {
381
- this.scrollPosition.scrollLeft = position.scrollLeft;
382
+ this.scrollPosition.scrollLeft = actual.scrollLeft;
382
383
  }
383
384
  }
384
385
  /**
@@ -390,8 +391,8 @@ var ScrollEngine = class {
390
391
  scrollTo(offset, options = {}) {
391
392
  if (!this.container) return;
392
393
  const { behavior = "auto", duration = 300, easing = easings.easeInOut } = options;
393
- if (behavior === "auto" || behavior === "smooth" && duration === 0) {
394
- this.setScrollPosition({ scrollTop: offset });
394
+ if (behavior === "auto" || !(duration > 0)) {
395
+ this.setScrollPosition(this.horizontal ? { scrollLeft: offset } : { scrollTop: offset });
395
396
  } else {
396
397
  this.animateScroll(offset, duration, easing);
397
398
  }
@@ -401,26 +402,26 @@ var ScrollEngine = class {
401
402
  */
402
403
  animateScroll(targetOffset, duration, easing) {
403
404
  if (this.animationId) {
404
- cancelRaf(this.animationId);
405
+ chunkND5PV5MU_cjs.cancelRaf(this.animationId);
405
406
  }
406
407
  this.animationStartTime = performance.now();
407
- this.animationStartOffset = this.scrollPosition.scrollTop;
408
+ this.animationStartOffset = this.horizontal ? this.scrollPosition.scrollLeft : this.scrollPosition.scrollTop;
408
409
  this.animationTargetOffset = targetOffset;
409
410
  this.animationDuration = duration;
410
411
  this.animationEasing = easing;
411
412
  const animate = (currentTime) => {
412
413
  const elapsed = currentTime - this.animationStartTime;
413
- const progress = Math.min(elapsed / this.animationDuration, 1);
414
+ const progress = Math.max(0, Math.min(elapsed / this.animationDuration, 1));
414
415
  const easedProgress = this.animationEasing(progress);
415
416
  const currentOffset = this.animationStartOffset + (this.animationTargetOffset - this.animationStartOffset) * easedProgress;
416
- this.setScrollPosition({ scrollTop: currentOffset });
417
+ this.setScrollPosition(this.horizontal ? { scrollLeft: currentOffset } : { scrollTop: currentOffset });
417
418
  if (progress < 1) {
418
- this.animationId = raf(animate);
419
+ this.animationId = chunkND5PV5MU_cjs.raf(animate);
419
420
  } else {
420
421
  this.animationId = null;
421
422
  }
422
423
  };
423
- this.animationId = raf(animate);
424
+ this.animationId = chunkND5PV5MU_cjs.raf(animate);
424
425
  }
425
426
  /**
426
427
  * Check if currently scrolling.
@@ -451,6 +452,14 @@ var ScrollEngine = class {
451
452
  *
452
453
  * @param delay - Delay in ms
453
454
  */
455
+ /**
456
+ * Set the axis that scrollTo() and its animation drive.
457
+ *
458
+ * @param direction - Scroll direction
459
+ */
460
+ setDirection(direction) {
461
+ this.horizontal = direction === "horizontal";
462
+ }
454
463
  setScrollEndDelay(delay) {
455
464
  this.scrollEndDelay = delay;
456
465
  }
@@ -499,7 +508,7 @@ var ScrollEngine = class {
499
508
  */
500
509
  stopAnimation() {
501
510
  if (this.animationId) {
502
- cancelRaf(this.animationId);
511
+ chunkND5PV5MU_cjs.cancelRaf(this.animationId);
503
512
  this.animationId = null;
504
513
  }
505
514
  }
@@ -514,6 +523,11 @@ function getViewport(element) {
514
523
  scrollHeight: element.scrollHeight
515
524
  };
516
525
  }
526
+ function getContentWidth(element) {
527
+ const style = typeof getComputedStyle === "function" ? getComputedStyle(element) : null;
528
+ const padding = style ? (parseFloat(style.paddingLeft) || 0) + (parseFloat(style.paddingRight) || 0) : 0;
529
+ return Math.max(0, element.clientWidth - padding);
530
+ }
517
531
 
518
532
  // src/kernel/viewport.ts
519
533
  var ViewportManager = class {
@@ -685,11 +699,6 @@ function binarySearch(length, predicate) {
685
699
  return low;
686
700
  }
687
701
 
688
- // src/utils/array.ts
689
- function clamp(value, min, max) {
690
- return Math.min(Math.max(value, min), max);
691
- }
692
-
693
702
  // src/kernel/measurement-cache.ts
694
703
  var MeasurementCache = class {
695
704
  /**
@@ -839,19 +848,17 @@ var MeasurementCache = class {
839
848
  if (offset === 0) return;
840
849
  const newCache = /* @__PURE__ */ new Map();
841
850
  for (const [index, height] of this.cache) {
842
- if (index >= startIndex) {
843
- const newIndex = index + offset;
844
- if (newIndex >= 0) {
845
- newCache.set(newIndex, height);
846
- } else {
847
- this.totalMeasured--;
848
- this.sumOfHeights -= height;
849
- }
850
- } else {
851
- newCache.set(index, height);
851
+ const newIndex = index >= startIndex ? index + offset : index;
852
+ if (newIndex >= 0) {
853
+ newCache.set(newIndex, height);
852
854
  }
853
855
  }
854
856
  this.cache = newCache;
857
+ this.totalMeasured = newCache.size;
858
+ this.sumOfHeights = 0;
859
+ for (const height of newCache.values()) {
860
+ this.sumOfHeights += height;
861
+ }
855
862
  }
856
863
  /**
857
864
  * Get the internal cache map.
@@ -884,13 +891,13 @@ var RangeCalculator = class {
884
891
  * @param options - Configuration options
885
892
  */
886
893
  constructor(options) {
887
- this.offsetCache = [];
888
- this.dirtyFromIndex = 0;
889
- this.totalSize = 0;
894
+ // Fenwick trees (1-based) over the measured items with index < itemCount
895
+ this.countTree = new Float64Array(1);
896
+ this.sumTree = new Float64Array(1);
897
+ this.treesValid = false;
890
898
  this.itemCount = options.itemCount;
891
899
  this.overscan = options.overscan;
892
900
  this.measurementCache = new MeasurementCache(options.estimatedItemHeight);
893
- this.rebuildOffsetCache();
894
901
  }
895
902
  /**
896
903
  * Get the visible range of items.
@@ -908,7 +915,6 @@ var RangeCalculator = class {
908
915
  overscanEndIndex: 0
909
916
  };
910
917
  }
911
- this.ensureOffsetCacheValid(this.itemCount - 1);
912
918
  const startIndex = this.findStartIndex(scrollOffset);
913
919
  const scrollEnd = scrollOffset + viewportSize;
914
920
  const endIndex = this.findEndIndex(scrollEnd, startIndex);
@@ -930,22 +936,18 @@ var RangeCalculator = class {
930
936
  const itemEnd = this.getItemEnd(mid);
931
937
  return itemEnd > scrollOffset;
932
938
  });
933
- return clamp(index, 0, this.itemCount - 1);
939
+ return chunkND5PV5MU_cjs.clamp(index, 0, this.itemCount - 1);
934
940
  }
935
941
  /**
936
942
  * Find the end index for a given scroll end position.
937
943
  */
938
944
  findEndIndex(scrollEnd, startIndex) {
939
- if (scrollEnd >= this.totalSize) return this.itemCount - 1;
945
+ if (scrollEnd >= this.getTotalSize()) return this.itemCount - 1;
940
946
  let index = startIndex;
941
- while (index < this.itemCount - 1) {
942
- const itemStart = this.getItemOffset(index);
943
- if (itemStart >= scrollEnd) {
944
- break;
945
- }
947
+ while (index < this.itemCount - 1 && this.getItemOffset(index + 1) < scrollEnd) {
946
948
  index++;
947
949
  }
948
- return clamp(index, startIndex, this.itemCount - 1);
950
+ return chunkND5PV5MU_cjs.clamp(index, startIndex, this.itemCount - 1);
949
951
  }
950
952
  /**
951
953
  * Get the offset (start position) of an item.
@@ -955,9 +957,8 @@ var RangeCalculator = class {
955
957
  */
956
958
  getItemOffset(index) {
957
959
  if (index < 0 || this.itemCount === 0) return 0;
958
- if (index >= this.itemCount) return this.totalSize;
959
- this.ensureOffsetCacheValid(index);
960
- return this.offsetCache[index] ?? 0;
960
+ if (index >= this.itemCount) return this.getTotalSize();
961
+ return this.offsetBefore(Math.floor(index));
961
962
  }
962
963
  /**
963
964
  * Get the end position of an item.
@@ -983,8 +984,7 @@ var RangeCalculator = class {
983
984
  * @returns Total size
984
985
  */
985
986
  getTotalSize() {
986
- this.ensureOffsetCacheValid(this.itemCount - 1);
987
- return this.totalSize;
987
+ return this.offsetBefore(this.itemCount);
988
988
  }
989
989
  /**
990
990
  * Set the height for an item.
@@ -995,7 +995,7 @@ var RangeCalculator = class {
995
995
  */
996
996
  setItemHeight(index, height) {
997
997
  const previousHeight = this.measurementCache.set(index, height);
998
- this.invalidateFrom(index);
998
+ this.track(index, previousHeight === void 0 ? 1 : 0, height - (previousHeight ?? 0));
999
999
  return previousHeight;
1000
1000
  }
1001
1001
  /**
@@ -1013,8 +1013,9 @@ var RangeCalculator = class {
1013
1013
  * @param index - Item index
1014
1014
  */
1015
1015
  invalidate(index) {
1016
+ const previousHeight = this.measurementCache.get(index);
1016
1017
  if (this.measurementCache.delete(index)) {
1017
- this.invalidateFrom(index);
1018
+ this.track(index, -1, -(previousHeight ?? 0));
1018
1019
  }
1019
1020
  }
1020
1021
  /**
@@ -1022,41 +1023,7 @@ var RangeCalculator = class {
1022
1023
  */
1023
1024
  invalidateAll() {
1024
1025
  this.measurementCache.clear();
1025
- this.dirtyFromIndex = 0;
1026
- this.rebuildOffsetCache();
1027
- }
1028
- /**
1029
- * Mark offset cache as dirty from a specific index.
1030
- */
1031
- invalidateFrom(index) {
1032
- this.dirtyFromIndex = Math.min(this.dirtyFromIndex, index);
1033
- }
1034
- /**
1035
- * Ensure offset cache is valid up to the given index.
1036
- */
1037
- ensureOffsetCacheValid(upToIndex) {
1038
- if (this.dirtyFromIndex > upToIndex) return;
1039
- let offset = this.dirtyFromIndex === 0 ? 0 : (this.offsetCache[this.dirtyFromIndex - 1] ?? 0) + this.getItemSize(this.dirtyFromIndex - 1);
1040
- for (let i = this.dirtyFromIndex; i <= upToIndex && i < this.itemCount; i++) {
1041
- this.offsetCache[i] = offset;
1042
- offset += this.getItemSize(i);
1043
- }
1044
- if (upToIndex >= this.itemCount - 1) {
1045
- this.totalSize = offset;
1046
- }
1047
- this.dirtyFromIndex = upToIndex + 1;
1048
- }
1049
- /**
1050
- * Rebuild the entire offset cache.
1051
- */
1052
- rebuildOffsetCache() {
1053
- this.offsetCache = new Array(this.itemCount);
1054
- this.dirtyFromIndex = 0;
1055
- if (this.itemCount > 0) {
1056
- this.ensureOffsetCacheValid(this.itemCount - 1);
1057
- } else {
1058
- this.totalSize = 0;
1059
- }
1026
+ this.treesValid = false;
1060
1027
  }
1061
1028
  /**
1062
1029
  * Update item count.
@@ -1068,20 +1035,11 @@ var RangeCalculator = class {
1068
1035
  const previousCount = this.itemCount;
1069
1036
  this.itemCount = count;
1070
1037
  if (count < previousCount) {
1071
- this.offsetCache.length = count;
1072
- if (count > 0) {
1073
- const lastIndex = count - 1;
1074
- this.dirtyFromIndex = Math.min(this.dirtyFromIndex, lastIndex);
1075
- this.ensureOffsetCacheValid(lastIndex);
1076
- } else {
1077
- this.totalSize = 0;
1078
- }
1079
- } else {
1080
- this.offsetCache.length = count;
1081
- if (this.dirtyFromIndex > previousCount) {
1082
- this.dirtyFromIndex = previousCount;
1038
+ for (const measured of this.measurementCache.getMeasuredIndices()) {
1039
+ if (measured >= count) this.measurementCache.delete(measured);
1083
1040
  }
1084
1041
  }
1042
+ this.treesValid = false;
1085
1043
  }
1086
1044
  /**
1087
1045
  * Update overscan amount.
@@ -1098,7 +1056,6 @@ var RangeCalculator = class {
1098
1056
  */
1099
1057
  setEstimatedHeight(height) {
1100
1058
  this.measurementCache.setEstimatedHeight(height);
1101
- this.dirtyFromIndex = 0;
1102
1059
  }
1103
1060
  /**
1104
1061
  * Get the estimated item height.
@@ -1116,8 +1073,7 @@ var RangeCalculator = class {
1116
1073
  */
1117
1074
  getItemAtOffset(offset) {
1118
1075
  if (offset <= 0 || this.itemCount === 0) return 0;
1119
- if (offset >= this.totalSize) return this.itemCount - 1;
1120
- this.ensureOffsetCacheValid(this.itemCount - 1);
1076
+ if (offset >= this.getTotalSize()) return this.itemCount - 1;
1121
1077
  return binarySearch(this.itemCount, (mid) => {
1122
1078
  const itemEnd = this.getItemEnd(mid);
1123
1079
  return itemEnd > offset;
@@ -1139,6 +1095,51 @@ var RangeCalculator = class {
1139
1095
  getItemCount() {
1140
1096
  return this.itemCount;
1141
1097
  }
1098
+ /**
1099
+ * Position where item `index` starts (index === itemCount gives the total size).
1100
+ */
1101
+ offsetBefore(index) {
1102
+ this.ensureTrees();
1103
+ let measuredCount = 0;
1104
+ let measuredSum = 0;
1105
+ for (let i = index; i > 0; i -= i & -i) {
1106
+ measuredCount += this.countTree[i];
1107
+ measuredSum += this.sumTree[i];
1108
+ }
1109
+ return measuredSum + (index - measuredCount) * this.measurementCache.getEstimatedHeight();
1110
+ }
1111
+ /**
1112
+ * Record that the measured set changed at `index` (a no-op until the trees are built).
1113
+ */
1114
+ track(index, countDelta, sumDelta) {
1115
+ if (!this.treesValid || index < 0 || index >= this.itemCount || !Number.isInteger(index)) return;
1116
+ for (let i = index + 1; i <= this.itemCount; i += i & -i) {
1117
+ this.countTree[i] += countDelta;
1118
+ this.sumTree[i] += sumDelta;
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Build the Fenwick trees from the measurement cache (linear time).
1123
+ */
1124
+ ensureTrees() {
1125
+ if (this.treesValid) return;
1126
+ const size = this.itemCount;
1127
+ this.countTree = new Float64Array(size + 1);
1128
+ this.sumTree = new Float64Array(size + 1);
1129
+ for (const index of this.measurementCache.getMeasuredIndices()) {
1130
+ if (index < 0 || index >= size || !Number.isInteger(index)) continue;
1131
+ this.countTree[index + 1] = 1;
1132
+ this.sumTree[index + 1] = this.measurementCache.get(index) ?? 0;
1133
+ }
1134
+ for (let i = 1; i <= size; i++) {
1135
+ const parent = i + (i & -i);
1136
+ if (parent <= size) {
1137
+ this.countTree[parent] += this.countTree[i];
1138
+ this.sumTree[parent] += this.sumTree[i];
1139
+ }
1140
+ }
1141
+ this.treesValid = true;
1142
+ }
1142
1143
  };
1143
1144
 
1144
1145
  // src/kernel/plugin-registry.ts
@@ -1171,7 +1172,12 @@ var PluginRegistry = class {
1171
1172
  }
1172
1173
  this.plugins.set(plugin.name, plugin);
1173
1174
  if (this.kernel && plugin.install) {
1174
- plugin.install(this.kernel);
1175
+ try {
1176
+ plugin.install(this.kernel);
1177
+ } catch (error) {
1178
+ this.plugins.delete(plugin.name);
1179
+ throw error;
1180
+ }
1175
1181
  this.setupHooks(plugin);
1176
1182
  }
1177
1183
  }
@@ -1187,8 +1193,11 @@ var PluginRegistry = class {
1187
1193
  return false;
1188
1194
  }
1189
1195
  this.teardownHooks(plugin);
1190
- plugin.uninstall?.();
1191
- this.plugins.delete(name);
1196
+ try {
1197
+ plugin.uninstall?.();
1198
+ } finally {
1199
+ this.plugins.delete(name);
1200
+ }
1192
1201
  return true;
1193
1202
  }
1194
1203
  /**
@@ -1375,7 +1384,11 @@ var PluginRegistry = class {
1375
1384
  clear() {
1376
1385
  const names = Array.from(this.plugins.keys()).reverse();
1377
1386
  for (const name of names) {
1378
- this.unregister(name);
1387
+ try {
1388
+ this.unregister(name);
1389
+ } catch (error) {
1390
+ console.error(`[Scrollex] Error uninstalling plugin "${name}":`, error);
1391
+ }
1379
1392
  }
1380
1393
  }
1381
1394
  /**
@@ -1398,8 +1411,10 @@ var DEFAULT_OPTIONS = {
1398
1411
  };
1399
1412
  function createKernel(options = {}) {
1400
1413
  const config = { ...DEFAULT_OPTIONS, ...options };
1414
+ config.overscan = chunkND5PV5MU_cjs.normalizeOverscan(config.overscan);
1401
1415
  const eventBus = new EventBus();
1402
1416
  const scrollEngine = new ScrollEngine();
1417
+ scrollEngine.setDirection(config.direction);
1403
1418
  const viewportManager = new ViewportManager();
1404
1419
  const rangeCalculator = new RangeCalculator({
1405
1420
  itemCount: config.itemCount,
@@ -1407,6 +1422,8 @@ function createKernel(options = {}) {
1407
1422
  overscan: config.overscan
1408
1423
  });
1409
1424
  const pluginRegistry = new PluginRegistry();
1425
+ const startPadding = () => config.paddingStart ?? 0;
1426
+ let rangeAnnounced = false;
1410
1427
  let currentRange = {
1411
1428
  startIndex: 0,
1412
1429
  endIndex: 0,
@@ -1430,7 +1447,13 @@ function createKernel(options = {}) {
1430
1447
  },
1431
1448
  // Scroll Control
1432
1449
  getScrollPosition() {
1433
- return scrollEngine.getScrollPosition();
1450
+ const position = scrollEngine.getScrollPosition();
1451
+ const horizontal = config.direction === "horizontal";
1452
+ const offset = horizontal ? position.scrollLeft : position.scrollTop;
1453
+ const viewport = viewportManager.getViewport();
1454
+ const maxScroll = rangeCalculator.getTotalSize() + startPadding() - (horizontal ? viewport.width : viewport.height);
1455
+ const percentage = maxScroll > 0 ? Math.min(1, Math.max(0, offset / maxScroll)) : 0;
1456
+ return { ...position, offset, percentage };
1434
1457
  },
1435
1458
  setScrollPosition(position) {
1436
1459
  scrollEngine.setScrollPosition(position);
@@ -1440,37 +1463,39 @@ function createKernel(options = {}) {
1440
1463
  },
1441
1464
  scrollToIndex(index, options2 = {}) {
1442
1465
  const { align = "auto", offset: additionalOffset = 0, ...scrollOptions } = options2;
1443
- const itemOffset = rangeCalculator.getItemOffset(index);
1466
+ const itemOffset = rangeCalculator.getItemOffset(index) + startPadding();
1444
1467
  const itemSize = rangeCalculator.getItemSize(index);
1445
1468
  const viewport = viewportManager.getViewport();
1469
+ const horizontal = config.direction === "horizontal";
1470
+ const viewportSize = horizontal ? viewport.width : viewport.height;
1446
1471
  let targetOffset;
1447
1472
  switch (align) {
1448
1473
  case "start":
1449
1474
  targetOffset = itemOffset;
1450
1475
  break;
1451
1476
  case "center":
1452
- targetOffset = itemOffset - viewport.height / 2 + itemSize / 2;
1477
+ targetOffset = itemOffset - viewportSize / 2 + itemSize / 2;
1453
1478
  break;
1454
1479
  case "end":
1455
- targetOffset = itemOffset - viewport.height + itemSize;
1480
+ targetOffset = itemOffset - viewportSize + itemSize;
1456
1481
  break;
1457
1482
  case "auto":
1458
1483
  default: {
1459
1484
  const scrollPosition = scrollEngine.getScrollPosition();
1460
- const visibleStart = scrollPosition.scrollTop;
1461
- const visibleEnd = visibleStart + viewport.height;
1485
+ const visibleStart = horizontal ? scrollPosition.scrollLeft : scrollPosition.scrollTop;
1486
+ const visibleEnd = visibleStart + viewportSize;
1462
1487
  const itemEnd = itemOffset + itemSize;
1463
1488
  if (itemOffset < visibleStart) {
1464
1489
  targetOffset = itemOffset;
1465
1490
  } else if (itemEnd > visibleEnd) {
1466
- targetOffset = itemEnd - viewport.height;
1491
+ targetOffset = itemEnd - viewportSize;
1467
1492
  } else {
1468
1493
  return;
1469
1494
  }
1470
1495
  break;
1471
1496
  }
1472
1497
  }
1473
- const maxScroll = Math.max(0, rangeCalculator.getTotalSize() - viewport.height);
1498
+ const maxScroll = Math.max(0, rangeCalculator.getTotalSize() + startPadding() - viewportSize);
1474
1499
  targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
1475
1500
  scrollEngine.scrollTo(targetOffset, scrollOptions);
1476
1501
  },
@@ -1493,6 +1518,8 @@ function createKernel(options = {}) {
1493
1518
  },
1494
1519
  // Measurement
1495
1520
  measureItem(index, size) {
1521
+ if (!Number.isFinite(size) || size < 0) return;
1522
+ if (!Number.isInteger(index) || index < 0 || index >= rangeCalculator.getItemCount()) return;
1496
1523
  const previousHeight = rangeCalculator.setItemHeight(index, size);
1497
1524
  eventBus.emit({
1498
1525
  type: "item-measured",
@@ -1506,18 +1533,19 @@ function createKernel(options = {}) {
1506
1533
  return rangeCalculator.getCachedHeight(index);
1507
1534
  },
1508
1535
  invalidateMeasurement(index) {
1536
+ const wasMeasured = rangeCalculator.getCachedHeight(index) !== void 0;
1509
1537
  rangeCalculator.invalidate(index);
1510
- updateVisibleRange();
1538
+ updateVisibleRange(wasMeasured);
1511
1539
  },
1512
1540
  invalidateAllMeasurements() {
1513
1541
  rangeCalculator.invalidateAll();
1514
- updateVisibleRange();
1542
+ updateVisibleRange(true);
1515
1543
  },
1516
1544
  getEstimatedHeight() {
1517
1545
  return rangeCalculator.getEstimatedHeight();
1518
1546
  },
1519
1547
  getItemOffset(index) {
1520
- return rangeCalculator.getItemOffset(index);
1548
+ return rangeCalculator.getItemOffset(index) + startPadding();
1521
1549
  },
1522
1550
  // Events
1523
1551
  emit(event) {
@@ -1543,21 +1571,28 @@ function createKernel(options = {}) {
1543
1571
  });
1544
1572
  }
1545
1573
  }
1574
+ let layoutChanged = false;
1575
+ if (newOptions.paddingStart !== void 0) {
1576
+ layoutChanged = newOptions.paddingStart !== startPadding();
1577
+ config.paddingStart = newOptions.paddingStart;
1578
+ }
1546
1579
  if (newOptions.estimatedItemHeight !== void 0) {
1580
+ layoutChanged = layoutChanged || newOptions.estimatedItemHeight !== config.estimatedItemHeight;
1547
1581
  config.estimatedItemHeight = newOptions.estimatedItemHeight;
1548
1582
  rangeCalculator.setEstimatedHeight(newOptions.estimatedItemHeight);
1549
1583
  }
1550
1584
  if (newOptions.overscan !== void 0) {
1551
- config.overscan = newOptions.overscan;
1552
- rangeCalculator.setOverscan(newOptions.overscan);
1585
+ config.overscan = chunkND5PV5MU_cjs.normalizeOverscan(newOptions.overscan);
1586
+ rangeCalculator.setOverscan(config.overscan);
1553
1587
  }
1554
1588
  if (newOptions.direction !== void 0) {
1555
1589
  config.direction = newOptions.direction;
1590
+ scrollEngine.setDirection(newOptions.direction);
1556
1591
  }
1557
1592
  if (newOptions.getItemKey !== void 0) {
1558
1593
  config.getItemKey = newOptions.getItemKey;
1559
1594
  }
1560
- updateVisibleRange();
1595
+ updateVisibleRange(layoutChanged);
1561
1596
  },
1562
1597
  getOptions() {
1563
1598
  return { ...config };
@@ -1570,13 +1605,14 @@ function createKernel(options = {}) {
1570
1605
  return config.itemCount;
1571
1606
  },
1572
1607
  getTotalSize() {
1573
- return rangeCalculator.getTotalSize();
1608
+ return rangeCalculator.getTotalSize() + startPadding();
1574
1609
  },
1575
1610
  // Lifecycle
1576
1611
  attach(container) {
1577
1612
  if (attached) {
1578
1613
  kernel.detach();
1579
1614
  }
1615
+ const previousViewport = viewportManager.getViewport();
1580
1616
  scrollEngine.attach(container);
1581
1617
  viewportManager.attach(container);
1582
1618
  attached = true;
@@ -1594,6 +1630,10 @@ function createKernel(options = {}) {
1594
1630
  eventBus.emit(event);
1595
1631
  updateVisibleRange();
1596
1632
  });
1633
+ const viewport = viewportManager.getViewport();
1634
+ if (viewport.width !== previousViewport.width || viewport.height !== previousViewport.height || viewport.scrollWidth !== previousViewport.scrollWidth || viewport.scrollHeight !== previousViewport.scrollHeight) {
1635
+ eventBus.emit({ type: "resize", viewport, previousViewport });
1636
+ }
1597
1637
  updateVisibleRange();
1598
1638
  },
1599
1639
  detach() {
@@ -1608,15 +1648,16 @@ function createKernel(options = {}) {
1608
1648
  }
1609
1649
  };
1610
1650
  pluginRegistry.setKernel(kernel);
1611
- function updateVisibleRange() {
1651
+ function updateVisibleRange(layoutChanged = false) {
1612
1652
  if (!attached) return;
1613
1653
  const viewport = viewportManager.getViewport();
1614
1654
  const scrollPosition = scrollEngine.getScrollPosition();
1615
- const scrollOffset = config.direction === "vertical" ? scrollPosition.scrollTop : scrollPosition.scrollLeft;
1655
+ const scrollOffset = (config.direction === "vertical" ? scrollPosition.scrollTop : scrollPosition.scrollLeft) - startPadding();
1616
1656
  const viewportSize = config.direction === "vertical" ? viewport.height : viewport.width;
1617
1657
  const previousRange = { ...currentRange };
1618
1658
  currentRange = rangeCalculator.getVisibleRange(scrollOffset, viewportSize);
1619
- if (currentRange.startIndex !== previousRange.startIndex || currentRange.endIndex !== previousRange.endIndex || currentRange.overscanStartIndex !== previousRange.overscanStartIndex || currentRange.overscanEndIndex !== previousRange.overscanEndIndex) {
1659
+ if (layoutChanged || !rangeAnnounced || currentRange.startIndex !== previousRange.startIndex || currentRange.endIndex !== previousRange.endIndex || currentRange.overscanStartIndex !== previousRange.overscanStartIndex || currentRange.overscanEndIndex !== previousRange.overscanEndIndex) {
1660
+ rangeAnnounced = true;
1620
1661
  eventBus.emit({
1621
1662
  type: "visible-range-change",
1622
1663
  range: currentRange,
@@ -1642,118 +1683,56 @@ function createPlugin(config) {
1642
1683
  };
1643
1684
  }
1644
1685
 
1645
- // src/plugins/core/list-renderer.ts
1646
- var VirtualItemPool = class {
1647
- constructor() {
1648
- this.pool = [];
1649
- }
1650
- acquire() {
1651
- const item = this.pool.pop();
1652
- if (item) {
1653
- return item;
1654
- }
1655
- return { index: 0, key: 0, start: 0, end: 0, size: 0, lane: 0 };
1656
- }
1657
- release(item) {
1658
- item.index = 0;
1659
- item.key = 0;
1660
- item.start = 0;
1661
- item.end = 0;
1662
- item.size = 0;
1663
- item.lane = 0;
1664
- this.pool.push(item);
1665
- }
1666
- releaseAll(items) {
1667
- for (const item of items) {
1668
- this.release(item);
1669
- }
1670
- }
1671
- };
1672
- function listRendererPlugin(options = {}) {
1673
- const { getItemKey = (index) => index } = options;
1674
- let kernel = null;
1675
- let virtualItems = [];
1676
- let currentRange = {
1677
- startIndex: 0,
1678
- endIndex: 0,
1679
- overscanStartIndex: 0,
1680
- overscanEndIndex: 0
1681
- };
1682
- const itemPool = new VirtualItemPool();
1683
- function buildVirtualItems(range) {
1684
- if (!kernel) return [];
1685
- itemPool.releaseAll(virtualItems);
1686
- const items = [];
1687
- range.startIndex;
1688
- range.endIndex;
1689
- for (let i = range.overscanStartIndex; i <= range.overscanEndIndex; i++) {
1690
- const item = itemPool.acquire();
1691
- const offset = kernel.getItemOffset(i);
1692
- const size = kernel.getCachedHeight(i) ?? kernel.getEstimatedHeight();
1693
- item.index = i;
1694
- item.key = getItemKey(i);
1695
- item.start = offset;
1696
- item.end = offset + size;
1697
- item.size = size;
1698
- item.lane = 0;
1699
- items.push(item);
1686
+ // src/react/hooks/items-range.ts
1687
+ function getItemsRange(items, scrollTop, viewportHeight) {
1688
+ if (items.length === 0) {
1689
+ return { startIndex: 0, endIndex: 0, overscanStartIndex: 0, overscanEndIndex: 0 };
1690
+ }
1691
+ const overscanStartIndex = items[0].index;
1692
+ const overscanEndIndex = items[items.length - 1].index;
1693
+ const viewEnd = scrollTop + viewportHeight;
1694
+ let startIndex = -1;
1695
+ let endIndex = -1;
1696
+ for (const item of items) {
1697
+ if (item.end > scrollTop && item.start < viewEnd) {
1698
+ if (startIndex === -1) startIndex = item.index;
1699
+ endIndex = item.index;
1700
+ }
1701
+ }
1702
+ return startIndex === -1 ? { startIndex: overscanStartIndex, endIndex: overscanEndIndex, overscanStartIndex, overscanEndIndex } : { startIndex, endIndex, overscanStartIndex, overscanEndIndex };
1703
+ }
1704
+ function rekeyItems(items, count, getItemKey) {
1705
+ let changed = false;
1706
+ const next = [];
1707
+ for (const item of items) {
1708
+ if (item.index >= count) {
1709
+ changed = true;
1710
+ continue;
1711
+ }
1712
+ const key = getItemKey(item.index);
1713
+ if (key === item.key) {
1714
+ next.push(item);
1715
+ } else {
1716
+ changed = true;
1717
+ next.push({ ...item, key });
1700
1718
  }
1701
- return items;
1702
- }
1703
- function recalculate() {
1704
- if (!kernel) return;
1705
- currentRange = kernel.getVisibleRange();
1706
- virtualItems = buildVirtualItems(currentRange);
1707
1719
  }
1708
- const api = {
1709
- getVirtualItems() {
1710
- return virtualItems;
1711
- },
1712
- getTotalHeight() {
1713
- return kernel?.getTotalSize() ?? 0;
1714
- },
1715
- getStartOffset() {
1716
- if (virtualItems.length === 0) return 0;
1717
- return virtualItems[0]?.start ?? 0;
1718
- },
1719
- getEndOffset() {
1720
- if (virtualItems.length === 0) return 0;
1721
- const lastItem = virtualItems[virtualItems.length - 1];
1722
- return lastItem?.end ?? 0;
1723
- },
1724
- isItemVisible(index) {
1725
- return index >= currentRange.startIndex && index <= currentRange.endIndex;
1726
- },
1727
- recalculate
1728
- };
1729
- return {
1730
- name: "list-renderer",
1731
- version: "1.0.0",
1732
- type: "core",
1733
- install(k) {
1734
- kernel = k;
1735
- recalculate();
1736
- },
1737
- uninstall() {
1738
- itemPool.releaseAll(virtualItems);
1739
- virtualItems = [];
1740
- kernel = null;
1741
- },
1742
- hooks: {
1743
- onScroll: () => recalculate(),
1744
- onResize: () => recalculate(),
1745
- onItemMeasured: () => recalculate(),
1746
- onVisibleRangeChange: (range) => {
1747
- currentRange = range;
1748
- virtualItems = buildVirtualItems(range);
1749
- },
1750
- onItemsChange: () => recalculate()
1751
- },
1752
- api
1753
- };
1720
+ return changed ? next : items;
1754
1721
  }
1755
1722
 
1756
1723
  // src/react/hooks/use-virtual-list.ts
1724
+ function sameItems(a, b) {
1725
+ if (a === b) return true;
1726
+ if (a.length !== b.length) return false;
1727
+ for (let i = 0; i < a.length; i++) {
1728
+ const x = a[i];
1729
+ const y = b[i];
1730
+ if (x.index !== y.index || x.key !== y.key || x.start !== y.start || x.size !== y.size || x.lane !== y.lane) {
1731
+ return false;
1732
+ }
1733
+ }
1734
+ return true;
1735
+ }
1757
1736
  function useVirtualList(options) {
1758
1737
  const {
1759
1738
  count,
@@ -1767,17 +1746,21 @@ function useVirtualList(options) {
1767
1746
  horizontal = false,
1768
1747
  containerRef
1769
1748
  } = options;
1749
+ const getItemKeyRef = react.useRef(getItemKey);
1750
+ getItemKeyRef.current = getItemKey;
1770
1751
  const kernelRef = react.useRef(
1771
1752
  createKernel({
1772
1753
  itemCount: count,
1773
1754
  estimatedItemHeight,
1774
1755
  overscan,
1775
1756
  direction: horizontal ? "horizontal" : "vertical",
1776
- getItemKey
1757
+ getItemKey,
1758
+ paddingStart
1777
1759
  })
1778
1760
  );
1779
1761
  const [virtualItems, setVirtualItems] = react.useState([]);
1780
1762
  const [isScrolling, setIsScrolling] = react.useState(false);
1763
+ const [kernelTotalSize, setKernelTotalSize] = react.useState(() => kernelRef.current.getTotalSize());
1781
1764
  const [scrollOffset, setScrollOffset] = react.useState(initialOffset);
1782
1765
  const [range, setRange] = react.useState({
1783
1766
  startIndex: 0,
@@ -1790,12 +1773,12 @@ function useVirtualList(options) {
1790
1773
  const resizeObserverRef = react.useRef(null);
1791
1774
  const kernel = kernelRef.current;
1792
1775
  react.useEffect(() => {
1793
- const plugin = listRendererPlugin({ getItemKey });
1776
+ const plugin = chunkND5PV5MU_cjs.listRendererPlugin({ getItemKey: (index) => getItemKeyRef.current(index) });
1794
1777
  kernel.register(plugin);
1795
1778
  listRendererRef.current = plugin.api;
1796
1779
  const unsubScroll = kernel.on("scroll", (event) => {
1797
1780
  const e = event;
1798
- setScrollOffset(horizontal ? e.scrollLeft : e.scrollTop);
1781
+ setScrollOffset(kernel.getOptions().direction === "horizontal" ? e.scrollLeft : e.scrollTop);
1799
1782
  });
1800
1783
  const unsubScrollStart = kernel.on("scroll-start", () => {
1801
1784
  setIsScrolling(true);
@@ -1807,40 +1790,70 @@ function useVirtualList(options) {
1807
1790
  const e = event;
1808
1791
  setRange(e.range);
1809
1792
  setVirtualItems(listRendererRef.current?.getVirtualItems() ?? []);
1793
+ setKernelTotalSize(kernel.getTotalSize());
1810
1794
  });
1795
+ const syncLayout = () => {
1796
+ const next = listRendererRef.current?.getVirtualItems() ?? [];
1797
+ setVirtualItems((previous) => sameItems(previous, next) ? previous : next);
1798
+ setKernelTotalSize(kernel.getTotalSize());
1799
+ };
1800
+ const unsubItemsChange = kernel.on("items-change", syncLayout);
1801
+ const unsubItemMeasured = kernel.on("item-measured", syncLayout);
1811
1802
  return () => {
1812
1803
  unsubScroll();
1813
1804
  unsubScrollStart();
1814
1805
  unsubScrollEnd();
1815
1806
  unsubRangeChange();
1807
+ unsubItemsChange();
1808
+ unsubItemMeasured();
1816
1809
  kernel.destroy();
1817
1810
  };
1818
1811
  }, []);
1812
+ const initialOffsetAppliedRef = react.useRef(false);
1819
1813
  react.useEffect(() => {
1820
1814
  const container = containerRef.current;
1821
1815
  if (!container) return;
1822
1816
  kernel.attach(container);
1823
- if (initialOffset > 0) {
1824
- kernel.scrollTo(initialOffset);
1825
- }
1826
1817
  return () => {
1827
1818
  kernel.detach();
1828
1819
  };
1829
- }, [containerRef, kernel, initialOffset]);
1820
+ }, [containerRef, kernel]);
1821
+ const hasRows = virtualItems.length > 0;
1822
+ react.useEffect(() => {
1823
+ if (initialOffset > 0 && hasRows && !initialOffsetAppliedRef.current && containerRef.current) {
1824
+ initialOffsetAppliedRef.current = true;
1825
+ kernel.scrollTo(initialOffset);
1826
+ }
1827
+ }, [initialOffset, hasRows, kernel, containerRef]);
1830
1828
  react.useEffect(() => {
1831
1829
  kernel.configure({ itemCount: count });
1832
1830
  }, [count, kernel]);
1833
1831
  react.useEffect(() => {
1834
1832
  kernel.configure({ overscan });
1835
1833
  }, [overscan, kernel]);
1834
+ react.useEffect(() => {
1835
+ kernel.configure({ estimatedItemHeight });
1836
+ }, [estimatedItemHeight, kernel]);
1837
+ react.useEffect(() => {
1838
+ kernel.configure({ paddingStart });
1839
+ }, [paddingStart, kernel]);
1840
+ react.useEffect(() => {
1841
+ kernel.configure({ direction: horizontal ? "horizontal" : "vertical" });
1842
+ }, [horizontal, kernel]);
1836
1843
  react.useEffect(() => {
1837
1844
  const observer = new ResizeObserver((entries) => {
1838
1845
  for (const entry of entries) {
1839
1846
  const element = entry.target;
1840
1847
  const index = parseInt(element.dataset["virtualIndex"] ?? "", 10);
1841
1848
  if (!isNaN(index)) {
1842
- const rect = entry.contentRect;
1843
- const size = horizontal ? rect.width : rect.height;
1849
+ const horizontalList = kernel.getOptions().direction === "horizontal";
1850
+ const borderBox = entry.borderBoxSize?.[0];
1851
+ let size = borderBox ? horizontalList ? borderBox.inlineSize : borderBox.blockSize : 0;
1852
+ if (!(size > 0)) {
1853
+ const box = element.getBoundingClientRect();
1854
+ size = horizontalList ? box.width : box.height;
1855
+ }
1856
+ if (!(size > 0)) size = horizontalList ? entry.contentRect.width : entry.contentRect.height;
1844
1857
  if (size > 0) {
1845
1858
  kernel.measureItem(index, size);
1846
1859
  }
@@ -1851,7 +1864,7 @@ function useVirtualList(options) {
1851
1864
  return () => {
1852
1865
  observer.disconnect();
1853
1866
  };
1854
- }, [kernel, horizontal]);
1867
+ }, [kernel]);
1855
1868
  const measureElement = react.useCallback(
1856
1869
  (index, element) => {
1857
1870
  const observer = resizeObserverRef.current;
@@ -1903,11 +1916,13 @@ function useVirtualList(options) {
1903
1916
  () => kernel.invalidateAllMeasurements(),
1904
1917
  [kernel]
1905
1918
  );
1906
- const totalSize = react.useMemo(() => {
1907
- return paddingStart + kernel.getTotalSize() + paddingEnd;
1908
- }, [kernel, paddingStart, paddingEnd, virtualItems]);
1919
+ const totalSize = kernelTotalSize + paddingEnd;
1920
+ const keyedItems = react.useMemo(
1921
+ () => rekeyItems(virtualItems, count, getItemKey),
1922
+ [virtualItems, count, getItemKey]
1923
+ );
1909
1924
  return {
1910
- virtualItems,
1925
+ virtualItems: keyedItems,
1911
1926
  totalSize,
1912
1927
  scrollOffset,
1913
1928
  isScrolling,
@@ -1917,9 +1932,60 @@ function useVirtualList(options) {
1917
1932
  range,
1918
1933
  getMeasurement,
1919
1934
  invalidateMeasurement,
1920
- invalidateAllMeasurements
1935
+ invalidateAllMeasurements,
1936
+ kernel
1921
1937
  };
1922
1938
  }
1939
+ function useKernelPlugins(kernel, plugins) {
1940
+ const registeredRef = react.useRef([]);
1941
+ react.useEffect(() => {
1942
+ const previous = registeredRef.current;
1943
+ if (previous.length === plugins.length && previous.every((plugin, i) => plugin === plugins[i])) {
1944
+ return;
1945
+ }
1946
+ for (const plugin of previous) {
1947
+ kernel.unregister(plugin.name);
1948
+ }
1949
+ for (const plugin of plugins) {
1950
+ kernel.register(plugin);
1951
+ }
1952
+ registeredRef.current = plugins;
1953
+ });
1954
+ react.useEffect(() => () => {
1955
+ for (const plugin of registeredRef.current) {
1956
+ kernel.unregister(plugin.name);
1957
+ }
1958
+ registeredRef.current = [];
1959
+ }, [kernel]);
1960
+ }
1961
+ function callLoadMore(onLoadMore) {
1962
+ try {
1963
+ const pending = onLoadMore();
1964
+ if (pending && typeof pending.then === "function") {
1965
+ Promise.resolve(pending).catch((error) => {
1966
+ console.error("[Scrollex] Error in onLoadMore:", error);
1967
+ });
1968
+ }
1969
+ } catch (error) {
1970
+ console.error("[Scrollex] Error in onLoadMore:", error);
1971
+ }
1972
+ }
1973
+ function useLoadMoreWhenShort(containerRef, { count, totalSize, hasMore, isLoading, threshold, horizontal = false, onLoadMore }) {
1974
+ const requestedCount = react.useRef(-1);
1975
+ react.useEffect(() => {
1976
+ if (!hasMore) {
1977
+ requestedCount.current = -1;
1978
+ return;
1979
+ }
1980
+ const element = containerRef.current;
1981
+ if (!element || !onLoadMore || isLoading || requestedCount.current === count) return;
1982
+ const distanceToEnd = horizontal ? element.scrollWidth - element.scrollLeft - element.clientWidth : element.scrollHeight - element.scrollTop - element.clientHeight;
1983
+ if (distanceToEnd < threshold) {
1984
+ requestedCount.current = count;
1985
+ callLoadMore(onLoadMore);
1986
+ }
1987
+ }, [count, totalSize, hasMore, isLoading, threshold, horizontal, !!onLoadMore]);
1988
+ }
1923
1989
  var ScrollexContext = react.createContext(null);
1924
1990
  function useScrollex() {
1925
1991
  const context = react.useContext(ScrollexContext);
@@ -1974,7 +2040,8 @@ function VirtualListInner(props, ref) {
1974
2040
  scrollToIndex,
1975
2041
  measureElement,
1976
2042
  isScrolling,
1977
- range
2043
+ range,
2044
+ kernel
1978
2045
  } = useVirtualList({
1979
2046
  count: data.length,
1980
2047
  getItemHeight: itemHeight === "auto" ? void 0 : () => itemHeight,
@@ -1985,12 +2052,16 @@ function VirtualListInner(props, ref) {
1985
2052
  horizontal: direction === "horizontal",
1986
2053
  containerRef
1987
2054
  });
1988
- const kernelRef = react.useRef(createKernel({
1989
- itemCount: data.length,
1990
- estimatedItemHeight: itemHeight === "auto" ? estimatedItemHeight : itemHeight,
1991
- overscan,
1992
- direction
1993
- }));
2055
+ react.useEffect(() => {
2056
+ if (virtualItems.length === 0) return;
2057
+ onVisibleRangeChange?.(range);
2058
+ onItemsRendered?.({
2059
+ overscanStartIndex: range.overscanStartIndex,
2060
+ overscanEndIndex: range.overscanEndIndex,
2061
+ visibleStartIndex: range.startIndex,
2062
+ visibleEndIndex: range.endIndex
2063
+ });
2064
+ }, [range.startIndex, range.endIndex, range.overscanStartIndex, range.overscanEndIndex]);
1994
2065
  react.useImperativeHandle(ref, () => ({
1995
2066
  scrollTo: (offset, options) => scrollTo(offset, options),
1996
2067
  scrollToIndex: (index, options) => scrollToIndex(index, options),
@@ -2008,11 +2079,11 @@ function VirtualListInner(props, ref) {
2008
2079
  const handleScrollForInfinite = react.useCallback((event) => {
2009
2080
  if (!onLoadMore || !hasMore || isLoading) return;
2010
2081
  const target = event.currentTarget;
2011
- const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2012
- if (scrollBottom < threshold) {
2013
- onLoadMore();
2082
+ const distanceToEnd = direction === "horizontal" ? target.scrollWidth - target.scrollLeft - target.clientWidth : target.scrollHeight - target.scrollTop - target.clientHeight;
2083
+ if (distanceToEnd < threshold) {
2084
+ callLoadMore(onLoadMore);
2014
2085
  }
2015
- }, [onLoadMore, hasMore, isLoading, threshold]);
2086
+ }, [onLoadMore, hasMore, isLoading, threshold, direction]);
2016
2087
  const containerStyles = react.useMemo(() => ({
2017
2088
  height,
2018
2089
  width,
@@ -2030,10 +2101,10 @@ function VirtualListInner(props, ref) {
2030
2101
  }), [totalSize, direction, innerStyle]);
2031
2102
  const createRenderProps = react.useCallback(
2032
2103
  (index) => {
2033
- const item = data[index];
2034
- if (item === void 0) {
2035
- throw new Error(`[Scrollex] Item at index ${index} is undefined`);
2104
+ if (index >= data.length) {
2105
+ throw new Error(`[Scrollex] Item at index ${index} is out of range`);
2036
2106
  }
2107
+ const item = data[index];
2037
2108
  const virtualItem = virtualItems.find((vi) => vi.index === index);
2038
2109
  const itemOffset = virtualItem?.start ?? 0;
2039
2110
  const itemSize = virtualItem?.size ?? estimatedItemHeight;
@@ -2041,8 +2112,10 @@ function VirtualListInner(props, ref) {
2041
2112
  position: "absolute",
2042
2113
  top: 0,
2043
2114
  left: 0,
2044
- width: direction === "vertical" ? "100%" : itemSize,
2045
- height: direction === "vertical" ? itemSize : "100%",
2115
+ // Rows that are measured take the size of their content: a fixed size on the measured element would only
2116
+ // measure itself (the estimate until it is measured) and never grow
2117
+ width: direction === "vertical" ? "100%" : itemHeight === "auto" ? "auto" : itemSize,
2118
+ height: direction === "vertical" ? itemHeight === "auto" ? "auto" : itemSize : "100%",
2046
2119
  transform: direction === "vertical" ? `translateY(${itemOffset}px)` : `translateX(${itemOffset}px)`,
2047
2120
  willChange: "transform",
2048
2121
  contain: "layout style",
@@ -2057,11 +2130,13 @@ function VirtualListInner(props, ref) {
2057
2130
  isScrolling
2058
2131
  };
2059
2132
  },
2060
- [data, virtualItems, estimatedItemHeight, direction, itemStyle, measureElement, range, isScrolling]
2133
+ [data, virtualItems, estimatedItemHeight, itemHeight, direction, itemStyle, measureElement, range, isScrolling]
2061
2134
  );
2135
+ useKernelPlugins(kernel, plugins);
2136
+ useLoadMoreWhenShort(containerRef, { count: data.length, totalSize, hasMore, isLoading, threshold, horizontal: direction === "horizontal", onLoadMore });
2062
2137
  const contextValue = react.useMemo(() => ({
2063
- kernel: kernelRef.current
2064
- }), []);
2138
+ kernel
2139
+ }), [kernel]);
2065
2140
  return /* @__PURE__ */ jsxRuntime.jsx(ScrollexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxRuntime.jsxs(
2066
2141
  "div",
2067
2142
  {
@@ -2074,21 +2149,21 @@ function VirtualListInner(props, ref) {
2074
2149
  },
2075
2150
  role,
2076
2151
  "aria-label": ariaLabel,
2077
- "aria-rowcount": data.length,
2152
+ "aria-orientation": direction,
2078
2153
  tabIndex,
2079
2154
  ...restProps,
2080
2155
  children: [
2081
2156
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: innerClassName, style: innerContainerStyles, children: virtualItems.map((virtualItem) => {
2082
2157
  const index = virtualItem.index;
2083
- const item = data[index];
2084
- if (item === void 0) return null;
2158
+ if (index >= data.length) return null;
2085
2159
  return /* @__PURE__ */ jsxRuntime.jsx(
2086
2160
  "div",
2087
2161
  {
2088
2162
  className: itemClassName,
2089
2163
  "data-index": index,
2090
2164
  role: "option",
2091
- "aria-rowindex": index + 1,
2165
+ "aria-setsize": data.length,
2166
+ "aria-posinset": index + 1,
2092
2167
  children: renderItem(createRenderProps(index))
2093
2168
  },
2094
2169
  virtualItem.key
@@ -2100,117 +2175,11 @@ function VirtualListInner(props, ref) {
2100
2175
  ) });
2101
2176
  }
2102
2177
  var VirtualList = react.forwardRef(VirtualListInner);
2103
-
2104
- // src/plugins/core/grid-renderer.ts
2105
- function gridRendererPlugin(options) {
2106
- const {
2107
- columns,
2108
- minColumnWidth = 100,
2109
- rowHeight,
2110
- gap = 0,
2111
- getItemKey = (index) => index
2112
- } = options;
2113
- let kernel = null;
2114
- let virtualItems = [];
2115
- let columnCount = typeof columns === "number" ? columns : 1;
2116
- let columnWidth = 0;
2117
- let gapX = typeof gap === "number" ? gap : gap.x;
2118
- let gapY = typeof gap === "number" ? gap : gap.y;
2119
- function calculateColumns(containerWidth) {
2120
- if (typeof columns === "number") {
2121
- columnCount = columns;
2122
- } else {
2123
- columnCount = Math.max(1, Math.floor((containerWidth + gapX) / (minColumnWidth + gapX)));
2124
- }
2125
- columnWidth = (containerWidth - (columnCount - 1) * gapX) / columnCount;
2126
- }
2127
- function getRowCount() {
2128
- if (!kernel) return 0;
2129
- return Math.ceil(kernel.getItemCount() / columnCount);
2130
- }
2131
- function buildVirtualItems() {
2132
- if (!kernel) return [];
2133
- const viewport = kernel.getViewport();
2134
- const scrollPosition = kernel.getScrollPosition();
2135
- const scrollTop = scrollPosition.scrollTop;
2136
- const effectiveRowHeight = rowHeight + gapY;
2137
- const startRow = Math.max(0, Math.floor(scrollTop / effectiveRowHeight));
2138
- const visibleRows = Math.ceil(viewport.height / effectiveRowHeight);
2139
- const overscan = kernel.getOptions().overscan;
2140
- const endRow = Math.min(getRowCount() - 1, startRow + visibleRows + overscan);
2141
- const overscanStartRow = Math.max(0, startRow - overscan);
2142
- const items = [];
2143
- const itemCount = kernel.getItemCount();
2144
- for (let row = overscanStartRow; row <= endRow; row++) {
2145
- for (let col = 0; col < columnCount; col++) {
2146
- const index = row * columnCount + col;
2147
- if (index >= itemCount) break;
2148
- const top = row * effectiveRowHeight;
2149
- items.push({
2150
- index,
2151
- key: getItemKey(index),
2152
- start: top,
2153
- end: top + rowHeight,
2154
- size: rowHeight,
2155
- lane: col
2156
- });
2157
- }
2158
- }
2159
- return items;
2160
- }
2161
- function recalculate() {
2162
- if (!kernel) return;
2163
- const viewport = kernel.getViewport();
2164
- calculateColumns(viewport.width);
2165
- virtualItems = buildVirtualItems();
2166
- }
2167
- const api = {
2168
- getVirtualItems() {
2169
- return virtualItems;
2170
- },
2171
- getTotalHeight() {
2172
- return getRowCount() * (rowHeight + gapY) - gapY;
2173
- },
2174
- getColumnCount() {
2175
- return columnCount;
2176
- },
2177
- getColumnWidth() {
2178
- return columnWidth;
2179
- },
2180
- getItemsPerRow() {
2181
- return columnCount;
2182
- },
2183
- getRowCount,
2184
- recalculate
2185
- };
2186
- return {
2187
- name: "grid-renderer",
2188
- version: "1.0.0",
2189
- type: "core",
2190
- install(k) {
2191
- kernel = k;
2192
- recalculate();
2193
- },
2194
- uninstall() {
2195
- virtualItems = [];
2196
- kernel = null;
2197
- },
2198
- hooks: {
2199
- onScroll: () => {
2200
- virtualItems = buildVirtualItems();
2201
- },
2202
- onResize: () => recalculate(),
2203
- onItemsChange: () => recalculate()
2204
- },
2205
- api
2206
- };
2207
- }
2208
-
2209
- // src/react/hooks/use-virtual-grid.ts
2210
2178
  function useVirtualGrid(options) {
2211
2179
  const {
2212
2180
  count,
2213
2181
  columns,
2182
+ minColumnWidth,
2214
2183
  rowHeight,
2215
2184
  gap = 0,
2216
2185
  overscan = 2,
@@ -2220,6 +2189,8 @@ function useVirtualGrid(options) {
2220
2189
  } = options;
2221
2190
  const gapX = typeof gap === "number" ? gap : gap.x;
2222
2191
  const gapY = typeof gap === "number" ? gap : gap.y;
2192
+ const getItemKeyRef = react.useRef(getItemKey);
2193
+ getItemKeyRef.current = getItemKey;
2223
2194
  const kernelRef = react.useRef(
2224
2195
  createKernel({
2225
2196
  itemCount: count,
@@ -2238,23 +2209,49 @@ function useVirtualGrid(options) {
2238
2209
  overscanStartIndex: 0,
2239
2210
  overscanEndIndex: 0
2240
2211
  });
2241
- const [columnCount, setColumnCount] = react.useState(typeof columns === "number" ? columns : 1);
2212
+ const [columnCount, setColumnCount] = react.useState(typeof columns === "number" ? chunkND5PV5MU_cjs.normalizeColumnCount(columns) : 1);
2242
2213
  const [columnWidth, setColumnWidth] = react.useState(0);
2243
2214
  const gridRendererRef = react.useRef(null);
2244
2215
  const kernel = kernelRef.current;
2216
+ const publishItems = react.useCallback((items) => {
2217
+ setVirtualItems(items);
2218
+ setRange(getItemsRange(items, kernel.getScrollPosition().scrollTop, kernel.getViewport().height));
2219
+ const api = gridRendererRef.current;
2220
+ const itemCount = kernel.getItemCount();
2221
+ if (api && itemCount > 0) kernel.configure({ estimatedItemHeight: api.getTotalHeight() / itemCount });
2222
+ }, [kernel]);
2245
2223
  react.useEffect(() => {
2246
- const plugin = gridRendererPlugin({
2224
+ const plugin = chunkND5PV5MU_cjs.gridRendererPlugin({
2247
2225
  columns,
2226
+ minColumnWidth,
2248
2227
  rowHeight,
2249
2228
  gap: { x: gapX, y: gapY },
2250
- getItemKey
2229
+ getItemKey: (index) => getItemKeyRef.current(index),
2230
+ getContainerWidth: () => containerRef.current ? getContentWidth(containerRef.current) : void 0
2251
2231
  });
2252
2232
  kernel.register(plugin);
2253
- gridRendererRef.current = plugin.api;
2233
+ const api = plugin.api;
2234
+ gridRendererRef.current = api;
2235
+ if (containerRef.current) {
2236
+ api.recalculate();
2237
+ setColumnCount(api.getColumnCount());
2238
+ setColumnWidth(api.getColumnWidth());
2239
+ publishItems(api.getVirtualItems());
2240
+ }
2241
+ return () => {
2242
+ kernel.unregister(plugin.name);
2243
+ gridRendererRef.current = null;
2244
+ };
2245
+ }, [kernel, columns, minColumnWidth, rowHeight, gapX, gapY]);
2246
+ react.useEffect(() => {
2254
2247
  const unsubScroll = kernel.on("scroll", (event) => {
2255
2248
  const e = event;
2256
2249
  setScrollOffset(e.scrollTop);
2257
- setVirtualItems(gridRendererRef.current?.getVirtualItems() ?? []);
2250
+ const api = gridRendererRef.current;
2251
+ if (api) {
2252
+ api.recalculate();
2253
+ publishItems(api.getVirtualItems());
2254
+ }
2258
2255
  });
2259
2256
  const unsubScrollStart = kernel.on("scroll-start", () => {
2260
2257
  setIsScrolling(true);
@@ -2268,22 +2265,18 @@ function useVirtualGrid(options) {
2268
2265
  api.recalculate();
2269
2266
  setColumnCount(api.getColumnCount());
2270
2267
  setColumnWidth(api.getColumnWidth());
2271
- setVirtualItems(api.getVirtualItems());
2268
+ publishItems(api.getVirtualItems());
2272
2269
  }
2273
2270
  });
2274
- const unsubRangeChange = kernel.on("visible-range-change", (event) => {
2275
- const e = event;
2276
- setRange(e.range);
2277
- });
2278
2271
  return () => {
2279
2272
  unsubScroll();
2280
2273
  unsubScrollStart();
2281
2274
  unsubScrollEnd();
2282
2275
  unsubResize();
2283
- unsubRangeChange();
2284
2276
  kernel.destroy();
2285
2277
  };
2286
2278
  }, []);
2279
+ const initialOffsetAppliedRef = react.useRef(false);
2287
2280
  react.useEffect(() => {
2288
2281
  const container = containerRef.current;
2289
2282
  if (!container) return;
@@ -2293,23 +2286,28 @@ function useVirtualGrid(options) {
2293
2286
  api.recalculate();
2294
2287
  setColumnCount(api.getColumnCount());
2295
2288
  setColumnWidth(api.getColumnWidth());
2296
- setVirtualItems(api.getVirtualItems());
2297
- }
2298
- if (initialOffset > 0) {
2299
- kernel.scrollTo(initialOffset);
2289
+ publishItems(api.getVirtualItems());
2300
2290
  }
2301
2291
  return () => {
2302
2292
  kernel.detach();
2303
2293
  };
2304
- }, [containerRef, kernel, initialOffset]);
2294
+ }, [containerRef, kernel]);
2305
2295
  react.useEffect(() => {
2306
2296
  kernel.configure({ itemCount: count });
2307
2297
  const api = gridRendererRef.current;
2308
2298
  if (api) {
2309
2299
  api.recalculate();
2310
- setVirtualItems(api.getVirtualItems());
2300
+ publishItems(api.getVirtualItems());
2311
2301
  }
2312
- }, [count, kernel]);
2302
+ }, [count, kernel, publishItems]);
2303
+ react.useEffect(() => {
2304
+ kernel.configure({ overscan });
2305
+ const api = gridRendererRef.current;
2306
+ if (api && containerRef.current) {
2307
+ api.recalculate();
2308
+ publishItems(api.getVirtualItems());
2309
+ }
2310
+ }, [overscan, kernel, publishItems]);
2313
2311
  const scrollTo = react.useCallback(
2314
2312
  (offset, scrollOptions) => {
2315
2313
  kernel.scrollTo(offset, scrollOptions);
@@ -2317,12 +2315,42 @@ function useVirtualGrid(options) {
2317
2315
  [kernel]
2318
2316
  );
2319
2317
  const scrollToIndex = react.useCallback(
2320
- (index, scrollOptions) => {
2318
+ (index, scrollOptions = {}) => {
2321
2319
  const row = Math.floor(index / columnCount);
2322
2320
  const rowOffset = row * (rowHeight + gapY);
2323
- kernel.scrollTo(rowOffset, scrollOptions);
2321
+ const container = containerRef.current;
2322
+ if (!container) return;
2323
+ const { align = "auto", offset: additionalOffset = 0, ...options2 } = scrollOptions;
2324
+ const viewportHeight = container.clientHeight;
2325
+ const rowEnd = rowOffset + rowHeight;
2326
+ let targetOffset;
2327
+ switch (align) {
2328
+ case "start":
2329
+ targetOffset = rowOffset;
2330
+ break;
2331
+ case "center":
2332
+ targetOffset = rowOffset - viewportHeight / 2 + rowHeight / 2;
2333
+ break;
2334
+ case "end":
2335
+ targetOffset = rowEnd - viewportHeight;
2336
+ break;
2337
+ case "auto":
2338
+ default: {
2339
+ const visibleStart = container.scrollTop;
2340
+ if (rowOffset < visibleStart) {
2341
+ targetOffset = rowOffset;
2342
+ } else if (rowEnd > visibleStart + viewportHeight) {
2343
+ targetOffset = rowEnd - viewportHeight;
2344
+ } else {
2345
+ return;
2346
+ }
2347
+ break;
2348
+ }
2349
+ }
2350
+ const maxScroll = Math.max(0, container.scrollHeight - viewportHeight);
2351
+ kernel.scrollTo(Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll)), options2);
2324
2352
  },
2325
- [kernel, columnCount, rowHeight, gapY]
2353
+ [kernel, containerRef, columnCount, rowHeight, gapY]
2326
2354
  );
2327
2355
  const measureElement = react.useCallback(
2328
2356
  (_index, _element) => {
@@ -2343,11 +2371,19 @@ function useVirtualGrid(options) {
2343
2371
  const totalSize = react.useMemo(() => {
2344
2372
  return gridRendererRef.current?.getTotalHeight() ?? 0;
2345
2373
  }, [virtualItems]);
2346
- const rowCount = react.useMemo(() => {
2347
- return gridRendererRef.current?.getRowCount() ?? 0;
2348
- }, [count, columnCount]);
2374
+ react.useEffect(() => {
2375
+ if (initialOffset > 0 && totalSize > 0 && !initialOffsetAppliedRef.current && containerRef.current) {
2376
+ initialOffsetAppliedRef.current = true;
2377
+ kernel.scrollTo(initialOffset);
2378
+ }
2379
+ }, [initialOffset, totalSize, kernel, containerRef]);
2380
+ const rowCount = react.useMemo(() => Math.ceil(count / Math.max(1, columnCount)), [count, columnCount]);
2381
+ const keyedItems = react.useMemo(
2382
+ () => rekeyItems(virtualItems, count, getItemKey),
2383
+ [virtualItems, count, getItemKey]
2384
+ );
2349
2385
  return {
2350
- virtualItems,
2386
+ virtualItems: keyedItems,
2351
2387
  totalSize,
2352
2388
  scrollOffset,
2353
2389
  isScrolling,
@@ -2358,6 +2394,7 @@ function useVirtualGrid(options) {
2358
2394
  getMeasurement,
2359
2395
  invalidateMeasurement,
2360
2396
  invalidateAllMeasurements,
2397
+ kernel,
2361
2398
  columnCount,
2362
2399
  columnWidth,
2363
2400
  rowCount
@@ -2408,11 +2445,12 @@ function VirtualGridInner(props, ref) {
2408
2445
  range,
2409
2446
  columnCount,
2410
2447
  columnWidth,
2411
- rowCount
2448
+ rowCount,
2449
+ kernel
2412
2450
  } = useVirtualGrid({
2413
2451
  count: data.length,
2414
- columns: typeof columns === "number" ? columns : 1,
2415
- // TODO: handle auto
2452
+ columns,
2453
+ minColumnWidth,
2416
2454
  rowHeight: itemHeight,
2417
2455
  gap: { x: gapX, y: gapY },
2418
2456
  overscan,
@@ -2420,12 +2458,16 @@ function VirtualGridInner(props, ref) {
2420
2458
  getItemKey: getItemKey ? (index) => getItemKey(index, data) : void 0,
2421
2459
  containerRef
2422
2460
  });
2423
- const kernelRef = react.useRef(createKernel({
2424
- itemCount: data.length,
2425
- estimatedItemHeight: itemHeight,
2426
- overscan,
2427
- direction: "vertical"
2428
- }));
2461
+ react.useEffect(() => {
2462
+ if (virtualItems.length === 0) return;
2463
+ onVisibleRangeChange?.(range);
2464
+ onItemsRendered?.({
2465
+ overscanStartIndex: range.overscanStartIndex,
2466
+ overscanEndIndex: range.overscanEndIndex,
2467
+ visibleStartIndex: range.startIndex,
2468
+ visibleEndIndex: range.endIndex
2469
+ });
2470
+ }, [range.startIndex, range.endIndex, range.overscanStartIndex, range.overscanEndIndex]);
2429
2471
  react.useImperativeHandle(ref, () => ({
2430
2472
  scrollTo: (offset, options) => scrollTo(offset, options),
2431
2473
  scrollToIndex: (index, options) => scrollToIndex(index, options),
@@ -2445,7 +2487,7 @@ function VirtualGridInner(props, ref) {
2445
2487
  const target = event.currentTarget;
2446
2488
  const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2447
2489
  if (scrollBottom < threshold) {
2448
- onLoadMore();
2490
+ callLoadMore(onLoadMore);
2449
2491
  }
2450
2492
  }, [onLoadMore, hasMore, isLoading, threshold]);
2451
2493
  const containerStyles = react.useMemo(() => ({
@@ -2465,10 +2507,10 @@ function VirtualGridInner(props, ref) {
2465
2507
  }), [totalSize, innerStyle]);
2466
2508
  const createRenderProps = react.useCallback(
2467
2509
  (index, virtualItem) => {
2468
- const item = data[index];
2469
- if (item === void 0) {
2470
- throw new Error(`[Scrollex] Item at index ${index} is undefined`);
2510
+ if (index >= data.length) {
2511
+ throw new Error(`[Scrollex] Item at index ${index} is out of range`);
2471
2512
  }
2513
+ const item = data[index];
2472
2514
  const columnIndex = virtualItem.lane;
2473
2515
  const rowIndex = Math.floor(index / columnCount);
2474
2516
  const left = columnIndex * (columnWidth + gapX);
@@ -2499,9 +2541,11 @@ function VirtualGridInner(props, ref) {
2499
2541
  },
2500
2542
  [data, columnCount, columnWidth, gapX, itemStyle, range, isScrolling]
2501
2543
  );
2544
+ useKernelPlugins(kernel, plugins);
2545
+ useLoadMoreWhenShort(containerRef, { count: data.length, totalSize, hasMore, isLoading, threshold, onLoadMore });
2502
2546
  const contextValue = react.useMemo(() => ({
2503
- kernel: kernelRef.current
2504
- }), []);
2547
+ kernel
2548
+ }), [kernel]);
2505
2549
  return /* @__PURE__ */ jsxRuntime.jsx(ScrollexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxRuntime.jsxs(
2506
2550
  "div",
2507
2551
  {
@@ -2521,8 +2565,7 @@ function VirtualGridInner(props, ref) {
2521
2565
  children: [
2522
2566
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: innerClassName, style: innerContainerStyles, children: virtualItems.map((virtualItem) => {
2523
2567
  const index = virtualItem.index;
2524
- const item = data[index];
2525
- if (item === void 0) return null;
2568
+ if (index >= data.length) return null;
2526
2569
  const rowIndex = Math.floor(index / columnCount);
2527
2570
  const columnIndex = virtualItem.lane;
2528
2571
  return /* @__PURE__ */ jsxRuntime.jsx(
@@ -2548,11 +2591,16 @@ function useVirtualMasonry(options) {
2548
2591
  const {
2549
2592
  count,
2550
2593
  columns,
2594
+ minColumnWidth = 200,
2551
2595
  getItemHeight,
2552
2596
  gap = 0,
2553
2597
  overscan = 5,
2598
+ initialOffset = 0,
2599
+ getItemKey = (index) => index,
2554
2600
  containerRef
2555
2601
  } = options;
2602
+ const gapX = typeof gap === "number" ? gap : gap.x;
2603
+ const gapY = typeof gap === "number" ? gap : gap.y;
2556
2604
  const kernelRef = react.useRef(
2557
2605
  createKernel({
2558
2606
  itemCount: count,
@@ -2570,42 +2618,57 @@ function useVirtualMasonry(options) {
2570
2618
  overscanStartIndex: 0,
2571
2619
  overscanEndIndex: 0
2572
2620
  });
2621
+ const [columnCount, setColumnCount] = react.useState(typeof columns === "number" ? chunkND5PV5MU_cjs.normalizeColumnCount(columns) : 1);
2573
2622
  const [columnWidth, setColumnWidth] = react.useState(0);
2574
2623
  const [columnHeights, setColumnHeights] = react.useState([]);
2575
2624
  const [totalSize, setTotalSize] = react.useState(0);
2576
2625
  const layoutCacheRef = react.useRef(/* @__PURE__ */ new Map());
2626
+ const getItemHeightRef = react.useRef(getItemHeight);
2627
+ getItemHeightRef.current = getItemHeight;
2628
+ const getItemKeyRef = react.useRef(getItemKey);
2629
+ getItemKeyRef.current = getItemKey;
2630
+ const initialOffsetAppliedRef = react.useRef(false);
2577
2631
  const kernel = kernelRef.current;
2578
2632
  const calculateLayout = react.useCallback((containerWidth) => {
2633
+ kernel.configure({ itemCount: count });
2579
2634
  if (containerWidth === 0 || count === 0) {
2580
2635
  setVirtualItems([]);
2581
2636
  setColumnHeights([]);
2582
2637
  setTotalSize(0);
2583
2638
  return;
2584
2639
  }
2585
- const newColumnWidth = (containerWidth - (columns - 1) * gap) / columns;
2640
+ const columnTotal = columns === "auto" ? chunkND5PV5MU_cjs.autoColumnCount(containerWidth, minColumnWidth, gapX) : chunkND5PV5MU_cjs.normalizeColumnCount(columns);
2641
+ const newColumnWidth = (containerWidth - (columnTotal - 1) * gapX) / columnTotal;
2642
+ setColumnCount(columnTotal);
2586
2643
  setColumnWidth(newColumnWidth);
2587
- const heights = new Array(columns).fill(0);
2644
+ const heights = new Array(columnTotal).fill(0);
2645
+ const itemsInColumn = new Array(columnTotal).fill(0);
2588
2646
  const cache = /* @__PURE__ */ new Map();
2589
2647
  for (let i = 0; i < count; i++) {
2590
2648
  let shortestCol = 0;
2591
- for (let j = 1; j < columns; j++) {
2649
+ for (let j = 1; j < columnTotal; j++) {
2592
2650
  if ((heights[j] ?? 0) < (heights[shortestCol] ?? 0)) {
2593
2651
  shortestCol = j;
2594
2652
  }
2595
2653
  }
2596
- const itemHeight = getItemHeight(i, newColumnWidth);
2654
+ const measured = getItemHeightRef.current(i, newColumnWidth);
2655
+ const itemHeight = Number.isFinite(measured) && measured > 0 ? measured : 0;
2597
2656
  const top = heights[shortestCol] ?? 0;
2598
2657
  cache.set(i, { top, lane: shortestCol, height: itemHeight });
2599
- heights[shortestCol] = top + itemHeight + gap;
2658
+ heights[shortestCol] = top + itemHeight + gapY;
2659
+ itemsInColumn[shortestCol] = (itemsInColumn[shortestCol] ?? 0) + 1;
2600
2660
  }
2601
2661
  layoutCacheRef.current = cache;
2602
- setColumnHeights(heights);
2603
- setTotalSize(Math.max(...heights) - gap);
2604
- }, [count, columns, gap, getItemHeight]);
2662
+ const extents = heights.map((height, column) => (itemsInColumn[column] ?? 0) > 0 ? height - gapY : 0);
2663
+ setColumnHeights(extents);
2664
+ const total = Math.max(...extents);
2665
+ setTotalSize(total);
2666
+ kernel.configure({ estimatedItemHeight: total / count });
2667
+ }, [kernel, count, columns, minColumnWidth, gapX, gapY]);
2605
2668
  const getVisibleItems = react.useCallback((scrollTop, viewportHeight) => {
2606
2669
  const cache = layoutCacheRef.current;
2607
2670
  const items = [];
2608
- const overscanAmount = overscan * 100;
2671
+ const overscanAmount = chunkND5PV5MU_cjs.normalizeOverscan(overscan) * 100;
2609
2672
  const viewStart = Math.max(0, scrollTop - overscanAmount);
2610
2673
  const viewEnd = scrollTop + viewportHeight + overscanAmount;
2611
2674
  for (let i = 0; i < count; i++) {
@@ -2615,7 +2678,7 @@ function useVirtualMasonry(options) {
2615
2678
  if (itemEnd >= viewStart && layout.top <= viewEnd) {
2616
2679
  items.push({
2617
2680
  index: i,
2618
- key: i,
2681
+ key: getItemKeyRef.current(i),
2619
2682
  start: layout.top,
2620
2683
  end: itemEnd,
2621
2684
  size: layout.height,
@@ -2625,6 +2688,11 @@ function useVirtualMasonry(options) {
2625
2688
  }
2626
2689
  return items;
2627
2690
  }, [count, overscan]);
2691
+ const updateVisibleItems = react.useCallback((scrollTop, viewportHeight) => {
2692
+ const items = getVisibleItems(scrollTop, viewportHeight);
2693
+ setVirtualItems(items);
2694
+ setRange(getItemsRange(items, scrollTop, viewportHeight));
2695
+ }, [getVisibleItems]);
2628
2696
  react.useEffect(() => {
2629
2697
  const unsubScrollStart = kernel.on("scroll-start", () => {
2630
2698
  setIsScrolling(true);
@@ -2642,16 +2710,23 @@ function useVirtualMasonry(options) {
2642
2710
  const container = containerRef.current;
2643
2711
  if (!container) return;
2644
2712
  kernel.attach(container);
2645
- calculateLayout(container.clientWidth);
2713
+ return () => {
2714
+ kernel.detach();
2715
+ };
2716
+ }, [containerRef, kernel]);
2717
+ react.useEffect(() => {
2718
+ const container = containerRef.current;
2719
+ if (!container) return;
2720
+ calculateLayout(getContentWidth(container));
2646
2721
  const handleScroll = () => {
2647
2722
  const scrollTop = container.scrollTop;
2648
2723
  setScrollOffset(scrollTop);
2649
- setVirtualItems(getVisibleItems(scrollTop, container.clientHeight));
2724
+ updateVisibleItems(scrollTop, container.clientHeight);
2650
2725
  };
2651
2726
  const resizeObserver = new ResizeObserver((entries) => {
2652
2727
  for (const entry of entries) {
2653
2728
  calculateLayout(entry.contentRect.width);
2654
- setVirtualItems(getVisibleItems(container.scrollTop, entry.contentRect.height));
2729
+ updateVisibleItems(container.scrollTop, entry.contentRect.height);
2655
2730
  }
2656
2731
  });
2657
2732
  container.addEventListener("scroll", handleScroll, { passive: true });
@@ -2660,15 +2735,20 @@ function useVirtualMasonry(options) {
2660
2735
  return () => {
2661
2736
  container.removeEventListener("scroll", handleScroll);
2662
2737
  resizeObserver.disconnect();
2663
- kernel.detach();
2664
2738
  };
2665
- }, [containerRef, kernel, calculateLayout, getVisibleItems]);
2739
+ }, [containerRef, kernel, calculateLayout, updateVisibleItems]);
2740
+ react.useEffect(() => {
2741
+ if (initialOffset > 0 && totalSize > 0 && !initialOffsetAppliedRef.current && containerRef.current) {
2742
+ initialOffsetAppliedRef.current = true;
2743
+ kernel.scrollTo(initialOffset);
2744
+ }
2745
+ }, [initialOffset, totalSize, kernel, containerRef]);
2666
2746
  react.useEffect(() => {
2667
2747
  const container = containerRef.current;
2668
2748
  if (!container) return;
2669
- calculateLayout(container.clientWidth);
2670
- setVirtualItems(getVisibleItems(container.scrollTop, container.clientHeight));
2671
- }, [count, containerRef, calculateLayout, getVisibleItems]);
2749
+ calculateLayout(getContentWidth(container));
2750
+ updateVisibleItems(container.scrollTop, container.clientHeight);
2751
+ }, [count, containerRef, calculateLayout, updateVisibleItems]);
2672
2752
  const scrollTo = react.useCallback(
2673
2753
  (offset, scrollOptions) => {
2674
2754
  kernel.scrollTo(offset, scrollOptions);
@@ -2676,13 +2756,41 @@ function useVirtualMasonry(options) {
2676
2756
  [kernel]
2677
2757
  );
2678
2758
  const scrollToIndex = react.useCallback(
2679
- (index, _scrollOptions) => {
2759
+ (index, scrollOptions = {}) => {
2680
2760
  const layout = layoutCacheRef.current.get(index);
2681
- if (layout) {
2682
- kernel.scrollTo(layout.top);
2761
+ const container = containerRef.current;
2762
+ if (!layout || !container) return;
2763
+ const { align = "auto", offset: additionalOffset = 0, ...options2 } = scrollOptions;
2764
+ const viewportHeight = container.clientHeight;
2765
+ const itemEnd = layout.top + layout.height;
2766
+ let targetOffset;
2767
+ switch (align) {
2768
+ case "start":
2769
+ targetOffset = layout.top;
2770
+ break;
2771
+ case "center":
2772
+ targetOffset = layout.top - viewportHeight / 2 + layout.height / 2;
2773
+ break;
2774
+ case "end":
2775
+ targetOffset = itemEnd - viewportHeight;
2776
+ break;
2777
+ case "auto":
2778
+ default: {
2779
+ const visibleStart = container.scrollTop;
2780
+ if (layout.top < visibleStart) {
2781
+ targetOffset = layout.top;
2782
+ } else if (itemEnd > visibleStart + viewportHeight) {
2783
+ targetOffset = itemEnd - viewportHeight;
2784
+ } else {
2785
+ return;
2786
+ }
2787
+ break;
2788
+ }
2683
2789
  }
2790
+ const maxScroll = Math.max(0, container.scrollHeight - viewportHeight);
2791
+ kernel.scrollTo(Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll)), options2);
2684
2792
  },
2685
- [kernel]
2793
+ [kernel, containerRef]
2686
2794
  );
2687
2795
  const measureElement = react.useCallback(
2688
2796
  (_index, _element) => {
@@ -2698,17 +2806,23 @@ function useVirtualMasonry(options) {
2698
2806
  const invalidateMeasurement = react.useCallback((_index) => {
2699
2807
  const container = containerRef.current;
2700
2808
  if (container) {
2701
- calculateLayout(container.clientWidth);
2809
+ calculateLayout(getContentWidth(container));
2810
+ updateVisibleItems(container.scrollTop, container.clientHeight);
2702
2811
  }
2703
- }, [containerRef, calculateLayout]);
2812
+ }, [containerRef, calculateLayout, updateVisibleItems]);
2704
2813
  const invalidateAllMeasurements = react.useCallback(() => {
2705
2814
  const container = containerRef.current;
2706
2815
  if (container) {
2707
- calculateLayout(container.clientWidth);
2816
+ calculateLayout(getContentWidth(container));
2817
+ updateVisibleItems(container.scrollTop, container.clientHeight);
2708
2818
  }
2709
- }, [containerRef, calculateLayout]);
2819
+ }, [containerRef, calculateLayout, updateVisibleItems]);
2820
+ const currentItems = react.useMemo(
2821
+ () => virtualItems.some((item) => item.index >= count) ? virtualItems.filter((item) => item.index < count) : virtualItems,
2822
+ [virtualItems, count]
2823
+ );
2710
2824
  return {
2711
- virtualItems,
2825
+ virtualItems: currentItems,
2712
2826
  totalSize,
2713
2827
  scrollOffset,
2714
2828
  isScrolling,
@@ -2719,7 +2833,8 @@ function useVirtualMasonry(options) {
2719
2833
  getMeasurement,
2720
2834
  invalidateMeasurement,
2721
2835
  invalidateAllMeasurements,
2722
- columnCount: columns,
2836
+ kernel,
2837
+ columnCount,
2723
2838
  columnWidth,
2724
2839
  columnHeights
2725
2840
  };
@@ -2765,29 +2880,39 @@ function VirtualMasonryInner(props, ref) {
2765
2880
  scrollTo,
2766
2881
  scrollToIndex,
2767
2882
  isScrolling,
2883
+ scrollOffset,
2768
2884
  range,
2769
2885
  columnCount,
2770
2886
  columnWidth,
2771
- columnHeights
2887
+ invalidateAllMeasurements,
2888
+ kernel
2772
2889
  } = useVirtualMasonry({
2773
2890
  count: data.length,
2774
- columns: typeof columns === "number" ? columns : 3,
2775
- // TODO: handle auto
2891
+ columns,
2892
+ minColumnWidth,
2776
2893
  getItemHeight: (index, colWidth) => {
2777
- const item = data[index];
2778
- if (item === void 0) return 100;
2779
- return getItemHeight(item, colWidth);
2894
+ if (index >= data.length) return 100;
2895
+ return getItemHeight(data[index], colWidth);
2780
2896
  },
2781
- gap: gapValue,
2897
+ gap,
2782
2898
  overscan,
2899
+ initialOffset: initialScrollOffset,
2900
+ getItemKey: getItemKey ? (index) => getItemKey(index, data) : void 0,
2783
2901
  containerRef
2784
2902
  });
2785
- const kernelRef = react.useRef(createKernel({
2786
- itemCount: data.length,
2787
- estimatedItemHeight: 200,
2788
- overscan,
2789
- direction: "vertical"
2790
- }));
2903
+ react.useEffect(() => {
2904
+ invalidateAllMeasurements();
2905
+ }, [data, invalidateAllMeasurements]);
2906
+ react.useEffect(() => {
2907
+ if (virtualItems.length === 0) return;
2908
+ onVisibleRangeChange?.(range);
2909
+ onItemsRendered?.({
2910
+ overscanStartIndex: range.overscanStartIndex,
2911
+ overscanEndIndex: range.overscanEndIndex,
2912
+ visibleStartIndex: range.startIndex,
2913
+ visibleEndIndex: range.endIndex
2914
+ });
2915
+ }, [range.startIndex, range.endIndex, range.overscanStartIndex, range.overscanEndIndex]);
2791
2916
  react.useImperativeHandle(ref, () => ({
2792
2917
  scrollTo: (offset, options) => scrollTo(offset, options),
2793
2918
  scrollToIndex: (index, options) => scrollToIndex(index, options),
@@ -2807,7 +2932,7 @@ function VirtualMasonryInner(props, ref) {
2807
2932
  const target = event.currentTarget;
2808
2933
  const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2809
2934
  if (scrollBottom < threshold) {
2810
- onLoadMore();
2935
+ callLoadMore(onLoadMore);
2811
2936
  }
2812
2937
  }, [onLoadMore, hasMore, isLoading, threshold]);
2813
2938
  const containerStyles = react.useMemo(() => ({
@@ -2827,12 +2952,13 @@ function VirtualMasonryInner(props, ref) {
2827
2952
  }), [totalSize, innerStyle]);
2828
2953
  const createRenderProps = react.useCallback(
2829
2954
  (index, virtualItem) => {
2830
- const item = data[index];
2831
- if (item === void 0) {
2832
- throw new Error(`[Scrollex] Item at index ${index} is undefined`);
2955
+ if (index >= data.length) {
2956
+ throw new Error(`[Scrollex] Item at index ${index} is out of range`);
2833
2957
  }
2958
+ const item = data[index];
2834
2959
  const columnIndex = virtualItem.lane;
2835
2960
  const left = columnIndex * (columnWidth + gapValue);
2961
+ const viewportHeight = kernel.getViewport().height;
2836
2962
  const itemStyles = {
2837
2963
  position: "absolute",
2838
2964
  top: 0,
@@ -2851,8 +2977,7 @@ function VirtualMasonryInner(props, ref) {
2851
2977
  measureRef: () => {
2852
2978
  },
2853
2979
  // Masonry uses calculated heights
2854
- isVisible: true,
2855
- // All virtual items are considered visible
2980
+ isVisible: virtualItem.end > scrollOffset && virtualItem.start < scrollOffset + viewportHeight,
2856
2981
  isScrolling,
2857
2982
  columnIndex,
2858
2983
  rowIndex: 0,
@@ -2861,11 +2986,13 @@ function VirtualMasonryInner(props, ref) {
2861
2986
  width: columnWidth
2862
2987
  };
2863
2988
  },
2864
- [data, columnWidth, gapValue, itemStyle, isScrolling]
2989
+ [data, columnWidth, gapValue, itemStyle, isScrolling, scrollOffset, kernel]
2865
2990
  );
2991
+ useKernelPlugins(kernel, plugins);
2992
+ useLoadMoreWhenShort(containerRef, { count: data.length, totalSize, hasMore, isLoading, threshold, onLoadMore });
2866
2993
  const contextValue = react.useMemo(() => ({
2867
- kernel: kernelRef.current
2868
- }), []);
2994
+ kernel
2995
+ }), [kernel]);
2869
2996
  return /* @__PURE__ */ jsxRuntime.jsx(ScrollexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxRuntime.jsxs(
2870
2997
  "div",
2871
2998
  {
@@ -2884,8 +3011,7 @@ function VirtualMasonryInner(props, ref) {
2884
3011
  children: [
2885
3012
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: innerClassName, style: innerContainerStyles, children: virtualItems.map((virtualItem) => {
2886
3013
  const index = virtualItem.index;
2887
- const item = data[index];
2888
- if (item === void 0) return null;
3014
+ if (index >= data.length) return null;
2889
3015
  return /* @__PURE__ */ jsxRuntime.jsx(
2890
3016
  "div",
2891
3017
  {
@@ -2904,38 +3030,52 @@ function VirtualMasonryInner(props, ref) {
2904
3030
  ) });
2905
3031
  }
2906
3032
  var VirtualMasonry = react.forwardRef(VirtualMasonryInner);
3033
+ function boxOf(entry) {
3034
+ const borderBox = entry.borderBoxSize?.[0];
3035
+ if (borderBox && (borderBox.inlineSize > 0 || borderBox.blockSize > 0)) {
3036
+ return { width: borderBox.inlineSize, height: borderBox.blockSize };
3037
+ }
3038
+ return { width: entry.contentRect.width, height: entry.contentRect.height };
3039
+ }
2907
3040
  function useMeasure(options = {}) {
2908
- const { onResize, debounce: debounce2 = 0 } = options;
3041
+ const { onResize, debounce = 0 } = options;
2909
3042
  const elementRef = react.useRef(null);
2910
3043
  const observerRef = react.useRef(null);
2911
- const dimensionsRef = react.useRef({ width: 0, height: 0 });
3044
+ const [dimensions, setDimensions] = react.useState({ width: 0, height: 0 });
2912
3045
  const debounceTimerRef = react.useRef(null);
3046
+ const onResizeRef = react.useRef(onResize);
3047
+ onResizeRef.current = onResize;
2913
3048
  const handleResize = react.useCallback(
2914
3049
  (width, height) => {
2915
- dimensionsRef.current = { width, height };
2916
- if (onResize) {
2917
- if (debounce2 > 0) {
3050
+ setDimensions(
3051
+ (previous) => previous.width === width && previous.height === height ? previous : { width, height }
3052
+ );
3053
+ const onResize2 = onResizeRef.current;
3054
+ if (onResize2) {
3055
+ if (debounce > 0) {
2918
3056
  if (debounceTimerRef.current) {
2919
3057
  clearTimeout(debounceTimerRef.current);
2920
3058
  }
2921
3059
  debounceTimerRef.current = setTimeout(() => {
2922
- onResize(width, height);
2923
- }, debounce2);
3060
+ onResize2(width, height);
3061
+ }, debounce);
2924
3062
  } else {
2925
- onResize(width, height);
3063
+ onResize2(width, height);
2926
3064
  }
2927
3065
  }
2928
3066
  },
2929
- [onResize, debounce2]
3067
+ [debounce]
2930
3068
  );
2931
3069
  react.useEffect(() => {
2932
3070
  observerRef.current = new ResizeObserver((entries) => {
2933
3071
  for (const entry of entries) {
2934
- const { width, height } = entry.contentRect;
3072
+ const { width, height } = boxOf(entry);
2935
3073
  handleResize(width, height);
2936
3074
  }
2937
3075
  });
2938
3076
  if (elementRef.current) {
3077
+ const rect = elementRef.current.getBoundingClientRect();
3078
+ handleResize(rect.width, rect.height);
2939
3079
  observerRef.current.observe(elementRef.current);
2940
3080
  }
2941
3081
  return () => {
@@ -2958,12 +3098,13 @@ function useMeasure(options = {}) {
2958
3098
  }, [handleResize]);
2959
3099
  return {
2960
3100
  measureRef,
2961
- width: dimensionsRef.current.width,
2962
- height: dimensionsRef.current.height
3101
+ width: dimensions.width,
3102
+ height: dimensions.height
2963
3103
  };
2964
3104
  }
2965
3105
  function useMeasureMany() {
2966
3106
  const elementsRef = react.useRef(/* @__PURE__ */ new Map());
3107
+ const keysRef = react.useRef(/* @__PURE__ */ new WeakMap());
2967
3108
  const observerRef = react.useRef(null);
2968
3109
  const measurementsRef = react.useRef(/* @__PURE__ */ new Map());
2969
3110
  const callbackRef = react.useRef(null);
@@ -2971,14 +3112,17 @@ function useMeasureMany() {
2971
3112
  observerRef.current = new ResizeObserver((entries) => {
2972
3113
  for (const entry of entries) {
2973
3114
  const element = entry.target;
2974
- const key = element.dataset["measureKey"];
3115
+ const key = element.dataset["measureKey"] !== void 0 ? keysRef.current.get(element) : void 0;
2975
3116
  if (key !== void 0) {
2976
- const { width, height } = entry.contentRect;
3117
+ const { width, height } = boxOf(entry);
2977
3118
  measurementsRef.current.set(key, { width, height });
2978
3119
  callbackRef.current?.(key, width, height);
2979
3120
  }
2980
3121
  }
2981
3122
  });
3123
+ for (const element of elementsRef.current.values()) {
3124
+ observerRef.current.observe(element);
3125
+ }
2982
3126
  return () => {
2983
3127
  observerRef.current?.disconnect();
2984
3128
  };
@@ -2991,9 +3135,11 @@ function useMeasureMany() {
2991
3135
  if (oldElement && oldElement !== element) {
2992
3136
  observer?.unobserve(oldElement);
2993
3137
  elements.delete(key);
3138
+ keysRef.current.delete(oldElement);
2994
3139
  }
2995
3140
  if (element) {
2996
3141
  element.dataset["measureKey"] = String(key);
3142
+ keysRef.current.set(element, key);
2997
3143
  elements.set(key, element);
2998
3144
  observer?.observe(element);
2999
3145
  const rect = element.getBoundingClientRect();
@@ -3027,462 +3173,32 @@ function useMeasureMany() {
3027
3173
  };
3028
3174
  }
3029
3175
 
3030
- // src/utils/debounce.ts
3031
- function debounce(fn, wait) {
3032
- let timeoutId = null;
3033
- let lastArgs = null;
3034
- let lastThis = null;
3035
- const debounced = function(...args) {
3036
- lastArgs = args;
3037
- lastThis = this;
3038
- if (timeoutId) {
3039
- clearTimeout(timeoutId);
3040
- }
3041
- timeoutId = setTimeout(() => {
3042
- timeoutId = null;
3043
- if (lastArgs) {
3044
- fn.apply(lastThis, lastArgs);
3045
- lastArgs = null;
3046
- lastThis = null;
3047
- }
3048
- }, wait);
3049
- };
3050
- debounced.cancel = () => {
3051
- if (timeoutId) {
3052
- clearTimeout(timeoutId);
3053
- timeoutId = null;
3054
- }
3055
- lastArgs = null;
3056
- lastThis = null;
3057
- };
3058
- debounced.flush = () => {
3059
- if (timeoutId) {
3060
- clearTimeout(timeoutId);
3061
- timeoutId = null;
3062
- if (lastArgs) {
3063
- fn.apply(lastThis, lastArgs);
3064
- lastArgs = null;
3065
- lastThis = null;
3066
- }
3067
- }
3068
- };
3069
- return debounced;
3070
- }
3071
-
3072
- // src/plugins/core/auto-measurer.ts
3073
- function autoMeasurerPlugin(options = {}) {
3074
- const {
3075
- estimatedItemHeight = 50,
3076
- measureOnResize = true,
3077
- debounceMs = 100
3078
- } = options;
3079
- let kernel = null;
3080
- let resizeObserver = null;
3081
- const observedElements = /* @__PURE__ */ new WeakMap();
3082
- const elementsByIndex = /* @__PURE__ */ new Map();
3083
- let measureQueue = /* @__PURE__ */ new Set();
3084
- let flushScheduled = false;
3085
- const debouncedFlush = debounce(() => {
3086
- flush();
3087
- }, debounceMs);
3088
- function flush() {
3089
- if (!kernel || measureQueue.size === 0) {
3090
- flushScheduled = false;
3091
- return;
3092
- }
3093
- const indicesToMeasure = Array.from(measureQueue);
3094
- measureQueue = /* @__PURE__ */ new Set();
3095
- flushScheduled = false;
3096
- const measurements = [];
3097
- for (const index of indicesToMeasure) {
3098
- const ref = elementsByIndex.get(index);
3099
- const element = ref?.deref();
3100
- if (element) {
3101
- const rect = element.getBoundingClientRect();
3102
- measurements.push({ index, height: rect.height });
3103
- }
3104
- }
3105
- for (const { index, height } of measurements) {
3106
- if (height > 0) {
3107
- kernel.measureItem(index, height);
3108
- }
3109
- }
3110
- }
3111
- function scheduleFlush() {
3112
- if (!flushScheduled) {
3113
- flushScheduled = true;
3114
- requestAnimationFrame(() => {
3115
- flush();
3116
- });
3117
- }
3118
- }
3119
- function handleResize(entries) {
3120
- for (const entry of entries) {
3121
- const index = observedElements.get(entry.target);
3122
- if (index !== void 0) {
3123
- measureQueue.add(index);
3124
- }
3125
- }
3126
- if (measureOnResize && measureQueue.size > 0) {
3127
- debouncedFlush();
3128
- }
3129
- }
3130
- const api = {
3131
- measureElement(index, element) {
3132
- const rect = element.getBoundingClientRect();
3133
- const height = rect.height;
3134
- if (height > 0 && kernel) {
3135
- kernel.measureItem(index, height);
3136
- }
3137
- return height;
3138
- },
3139
- getCachedSize(index) {
3140
- return kernel?.getCachedHeight(index);
3141
- },
3142
- invalidate(index) {
3143
- kernel?.invalidateMeasurement(index);
3144
- },
3145
- invalidateAll() {
3146
- kernel?.invalidateAllMeasurements();
3147
- },
3148
- getMeasurementCache() {
3149
- const cache = /* @__PURE__ */ new Map();
3150
- if (!kernel) return cache;
3151
- const itemCount = kernel.getItemCount();
3152
- for (let i = 0; i < itemCount; i++) {
3153
- const height = kernel.getCachedHeight(i);
3154
- if (height !== void 0) {
3155
- cache.set(i, height);
3156
- }
3157
- }
3158
- return cache;
3159
- },
3160
- observe(index, element) {
3161
- if (!resizeObserver) return;
3162
- const existingRef = elementsByIndex.get(index);
3163
- const existingElement = existingRef?.deref();
3164
- if (existingElement && existingElement !== element) {
3165
- resizeObserver.unobserve(existingElement);
3166
- observedElements.delete(existingElement);
3167
- }
3168
- observedElements.set(element, index);
3169
- elementsByIndex.set(index, new WeakRef(element));
3170
- resizeObserver.observe(element);
3171
- measureQueue.add(index);
3172
- scheduleFlush();
3173
- },
3174
- unobserve(element) {
3175
- if (!resizeObserver) return;
3176
- const index = observedElements.get(element);
3177
- if (index !== void 0) {
3178
- resizeObserver.unobserve(element);
3179
- observedElements.delete(element);
3180
- elementsByIndex.delete(index);
3181
- measureQueue.delete(index);
3182
- }
3183
- }
3184
- };
3185
- return {
3186
- name: "auto-measurer",
3187
- version: "1.0.0",
3188
- type: "core",
3189
- install(k) {
3190
- kernel = k;
3191
- kernel.configure({ estimatedItemHeight });
3192
- if (measureOnResize && typeof ResizeObserver !== "undefined") {
3193
- resizeObserver = new ResizeObserver(handleResize);
3194
- }
3195
- },
3196
- uninstall() {
3197
- if (resizeObserver) {
3198
- resizeObserver.disconnect();
3199
- resizeObserver = null;
3200
- }
3201
- debouncedFlush.cancel();
3202
- measureQueue.clear();
3203
- elementsByIndex.clear();
3204
- flushScheduled = false;
3205
- kernel = null;
3206
- },
3207
- api
3208
- };
3209
- }
3210
-
3211
- // src/plugins/core/infinite-loader.ts
3212
- function infiniteLoaderPlugin(options) {
3213
- const {
3214
- threshold = 200,
3215
- thresholdItems = 5,
3216
- direction = "forward",
3217
- onLoadMore
3218
- } = options;
3219
- let kernel = null;
3220
- let loading = false;
3221
- let hasMoreForward = true;
3222
- let hasMoreBackward = direction === "backward" || direction === "both";
3223
- let lastCheckTime = 0;
3224
- const checkDebounceMs = 100;
3225
- function checkLoadMore(event) {
3226
- if (loading || !kernel) return;
3227
- const now = performance.now();
3228
- if (now - lastCheckTime < checkDebounceMs) return;
3229
- lastCheckTime = now;
3230
- const viewport = kernel.getViewport();
3231
- const totalSize = kernel.getTotalSize();
3232
- const { scrollTop } = event;
3233
- if ((direction === "forward" || direction === "both") && hasMoreForward) {
3234
- const distanceFromBottom = totalSize - scrollTop - viewport.height;
3235
- if (distanceFromBottom < threshold) {
3236
- triggerLoad("forward");
3237
- return;
3238
- }
3239
- }
3240
- if ((direction === "backward" || direction === "both") && hasMoreBackward) {
3241
- if (scrollTop < threshold) {
3242
- triggerLoad("backward");
3243
- return;
3244
- }
3245
- }
3246
- }
3247
- function checkLoadMoreByRange(range) {
3248
- if (loading || !kernel) return;
3249
- const itemCount = kernel.getItemCount();
3250
- if ((direction === "forward" || direction === "both") && hasMoreForward) {
3251
- const itemsFromEnd = itemCount - 1 - range.endIndex;
3252
- if (itemsFromEnd <= thresholdItems) {
3253
- triggerLoad("forward");
3254
- return;
3255
- }
3256
- }
3257
- if ((direction === "backward" || direction === "both") && hasMoreBackward) {
3258
- if (range.startIndex <= thresholdItems) {
3259
- triggerLoad("backward");
3260
- return;
3261
- }
3262
- }
3263
- }
3264
- async function triggerLoad(loadDirection) {
3265
- if (loading || !kernel) return;
3266
- if (loadDirection === "forward" && !hasMoreForward) return;
3267
- if (loadDirection === "backward" && !hasMoreBackward) return;
3268
- loading = true;
3269
- kernel.emit({
3270
- type: "load-more",
3271
- direction: loadDirection
3272
- });
3273
- try {
3274
- await onLoadMore(loadDirection);
3275
- } catch (error) {
3276
- console.error("[Scrollex] Error in onLoadMore:", error);
3277
- } finally {
3278
- loading = false;
3279
- }
3280
- }
3281
- const api = {
3282
- isLoading() {
3283
- return loading;
3284
- },
3285
- setLoading(l) {
3286
- loading = l;
3287
- },
3288
- hasMore() {
3289
- return hasMoreForward || hasMoreBackward;
3290
- },
3291
- setHasMore(hasMore) {
3292
- hasMoreForward = hasMore;
3293
- hasMoreBackward = hasMore;
3294
- },
3295
- hasMoreForward() {
3296
- return hasMoreForward;
3297
- },
3298
- setHasMoreForward(hasMore) {
3299
- hasMoreForward = hasMore;
3300
- },
3301
- hasMoreBackward() {
3302
- return hasMoreBackward;
3303
- },
3304
- setHasMoreBackward(hasMore) {
3305
- hasMoreBackward = hasMore;
3306
- },
3307
- reset() {
3308
- loading = false;
3309
- hasMoreForward = true;
3310
- hasMoreBackward = direction === "backward" || direction === "both";
3311
- },
3312
- triggerLoad(loadDirection) {
3313
- triggerLoad(loadDirection);
3314
- }
3315
- };
3316
- return {
3317
- name: "infinite-loader",
3318
- version: "1.0.0",
3319
- type: "core",
3320
- install(k) {
3321
- kernel = k;
3322
- },
3323
- uninstall() {
3324
- kernel = null;
3325
- loading = false;
3326
- },
3327
- hooks: {
3328
- onScroll: checkLoadMore,
3329
- onVisibleRangeChange: (range) => checkLoadMoreByRange(range)
3330
- },
3331
- api
3332
- };
3333
- }
3334
-
3335
- // src/plugins/core/scroll-controller.ts
3336
- var easings2 = {
3337
- easeInOut: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t};
3338
- function scrollControllerPlugin(options = {}) {
3339
- const {
3340
- defaultDuration = 300,
3341
- defaultEasing = easings2.easeInOut
3342
- } = options;
3343
- let kernel = null;
3344
- let animationId = null;
3345
- let animating = false;
3346
- function animateScroll(targetOffset, duration, easing) {
3347
- if (!kernel) return;
3348
- stopAnimation();
3349
- const startTime = performance.now();
3350
- const startOffset = kernel.getScrollPosition().scrollTop;
3351
- const distance = targetOffset - startOffset;
3352
- if (distance === 0 || duration === 0) {
3353
- kernel.setScrollPosition({ scrollTop: targetOffset, scrollLeft: 0 });
3354
- return;
3355
- }
3356
- animating = true;
3357
- function animate(currentTime) {
3358
- if (!kernel) {
3359
- animating = false;
3360
- return;
3361
- }
3362
- const elapsed = currentTime - startTime;
3363
- const progress = Math.min(elapsed / duration, 1);
3364
- const easedProgress = easing(progress);
3365
- const currentOffset = startOffset + distance * easedProgress;
3366
- kernel.setScrollPosition({ scrollTop: currentOffset, scrollLeft: 0 });
3367
- if (progress < 1) {
3368
- animationId = raf(animate);
3369
- } else {
3370
- animationId = null;
3371
- animating = false;
3372
- }
3373
- }
3374
- animationId = raf(animate);
3375
- }
3376
- function stopAnimation() {
3377
- if (animationId !== null) {
3378
- cancelRaf(animationId);
3379
- animationId = null;
3380
- }
3381
- animating = false;
3382
- }
3383
- const api = {
3384
- scrollTo(offset, options2 = {}) {
3385
- if (!kernel) return;
3386
- const {
3387
- behavior = "auto",
3388
- duration = defaultDuration,
3389
- easing = defaultEasing
3390
- } = options2;
3391
- if (behavior === "auto") {
3392
- stopAnimation();
3393
- kernel.setScrollPosition({ scrollTop: offset, scrollLeft: 0 });
3394
- } else {
3395
- animateScroll(offset, duration, easing);
3396
- }
3397
- },
3398
- scrollToIndex(index, options2 = {}) {
3399
- if (!kernel) return;
3400
- const {
3401
- align = "auto",
3402
- offset: additionalOffset = 0,
3403
- ...scrollOptions
3404
- } = options2;
3405
- const itemOffset = kernel.getItemOffset(index);
3406
- const itemSize = kernel.getCachedHeight(index) ?? kernel.getEstimatedHeight();
3407
- const viewport = kernel.getViewport();
3408
- let targetOffset;
3409
- switch (align) {
3410
- case "start":
3411
- targetOffset = itemOffset;
3412
- break;
3413
- case "center":
3414
- targetOffset = itemOffset - viewport.height / 2 + itemSize / 2;
3415
- break;
3416
- case "end":
3417
- targetOffset = itemOffset - viewport.height + itemSize;
3418
- break;
3419
- case "auto":
3420
- default: {
3421
- const scrollPosition = kernel.getScrollPosition();
3422
- const visibleStart = scrollPosition.scrollTop;
3423
- const visibleEnd = visibleStart + viewport.height;
3424
- const itemEnd = itemOffset + itemSize;
3425
- if (itemOffset < visibleStart) {
3426
- targetOffset = itemOffset;
3427
- } else if (itemEnd > visibleEnd) {
3428
- targetOffset = itemEnd - viewport.height;
3429
- } else {
3430
- return;
3431
- }
3432
- break;
3433
- }
3434
- }
3435
- const maxScroll = Math.max(0, kernel.getTotalSize() - viewport.height);
3436
- targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
3437
- api.scrollTo(targetOffset, scrollOptions);
3438
- },
3439
- scrollToTop(options2 = {}) {
3440
- api.scrollTo(0, options2);
3441
- },
3442
- scrollToBottom(options2 = {}) {
3443
- if (!kernel) return;
3444
- const viewport = kernel.getViewport();
3445
- const totalSize = kernel.getTotalSize();
3446
- const maxScroll = Math.max(0, totalSize - viewport.height);
3447
- api.scrollTo(maxScroll, options2);
3448
- },
3449
- getScrollPosition() {
3450
- return kernel?.getScrollPosition() ?? { scrollTop: 0, scrollLeft: 0 };
3451
- },
3452
- isScrolling() {
3453
- return kernel?.isScrolling() ?? false;
3454
- },
3455
- isAnimating() {
3456
- return animating;
3457
- },
3458
- stopAnimation
3459
- };
3460
- return {
3461
- name: "scroll-controller",
3462
- version: "1.0.0",
3463
- type: "core",
3464
- install(k) {
3465
- kernel = k;
3466
- },
3467
- uninstall() {
3468
- stopAnimation();
3469
- kernel = null;
3470
- },
3471
- api
3472
- };
3473
- }
3474
-
3176
+ Object.defineProperty(exports, "autoMeasurerPlugin", {
3177
+ enumerable: true,
3178
+ get: function () { return chunkND5PV5MU_cjs.autoMeasurerPlugin; }
3179
+ });
3180
+ Object.defineProperty(exports, "gridRendererPlugin", {
3181
+ enumerable: true,
3182
+ get: function () { return chunkND5PV5MU_cjs.gridRendererPlugin; }
3183
+ });
3184
+ Object.defineProperty(exports, "infiniteLoaderPlugin", {
3185
+ enumerable: true,
3186
+ get: function () { return chunkND5PV5MU_cjs.infiniteLoaderPlugin; }
3187
+ });
3188
+ Object.defineProperty(exports, "listRendererPlugin", {
3189
+ enumerable: true,
3190
+ get: function () { return chunkND5PV5MU_cjs.listRendererPlugin; }
3191
+ });
3192
+ Object.defineProperty(exports, "scrollControllerPlugin", {
3193
+ enumerable: true,
3194
+ get: function () { return chunkND5PV5MU_cjs.scrollControllerPlugin; }
3195
+ });
3475
3196
  exports.VirtualGrid = VirtualGrid;
3476
3197
  exports.VirtualList = VirtualList;
3477
3198
  exports.VirtualMasonry = VirtualMasonry;
3478
- exports.autoMeasurerPlugin = autoMeasurerPlugin;
3479
3199
  exports.createKernel = createKernel;
3480
3200
  exports.createPlugin = createPlugin;
3481
3201
  exports.easings = easings;
3482
- exports.gridRendererPlugin = gridRendererPlugin;
3483
- exports.infiniteLoaderPlugin = infiniteLoaderPlugin;
3484
- exports.listRendererPlugin = listRendererPlugin;
3485
- exports.scrollControllerPlugin = scrollControllerPlugin;
3486
3202
  exports.useMeasure = useMeasure;
3487
3203
  exports.useMeasureMany = useMeasureMany;
3488
3204
  exports.useScrollex = useScrollex;