@oxog/scrollex 1.0.0 → 1.0.3

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.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, forwardRef, useRef, useImperativeHandle, useCallback, useMemo, useState, useEffect, useContext } from 'react';
1
+ import { createContext, forwardRef, useRef, useEffect, useImperativeHandle, useCallback, useMemo, useState, useContext } from 'react';
2
2
  import { jsx, jsxs } from 'react/jsx-runtime';
3
3
 
4
4
  // src/react/components/virtual-list.tsx
@@ -97,9 +97,11 @@ var EventBus = class {
97
97
  */
98
98
  dispatchEvent(event) {
99
99
  const eventType = event.type;
100
+ const onceSnapshot = Array.from(this.onceHandlers.get(eventType) ?? []);
100
101
  const handlers = this.handlers.get(eventType);
101
102
  if (handlers) {
102
- for (const handler of handlers) {
103
+ for (const handler of Array.from(handlers)) {
104
+ if (!handlers.has(handler)) continue;
103
105
  try {
104
106
  handler(event);
105
107
  } catch (error) {
@@ -107,20 +109,17 @@ var EventBus = class {
107
109
  }
108
110
  }
109
111
  }
110
- const onceHandlers = this.onceHandlers.get(eventType);
111
- if (onceHandlers) {
112
- const handlersToCall = Array.from(onceHandlers);
113
- onceHandlers.clear();
114
- for (const handler of handlersToCall) {
115
- try {
116
- handler(event);
117
- } catch (error) {
118
- console.error(`[Scrollex] Error in once handler for "${eventType}":`, error);
119
- }
120
- }
112
+ for (const handler of onceSnapshot) {
113
+ const onceHandlers = this.onceHandlers.get(eventType);
114
+ if (!onceHandlers || !onceHandlers.delete(handler)) continue;
121
115
  if (onceHandlers.size === 0) {
122
116
  this.onceHandlers.delete(eventType);
123
117
  }
118
+ try {
119
+ handler(event);
120
+ } catch (error) {
121
+ console.error(`[Scrollex] Error in once handler for "${eventType}":`, error);
122
+ }
124
123
  }
125
124
  }
126
125
  /**
@@ -208,7 +207,7 @@ function setScrollPosition(element, position) {
208
207
  function getScrollDirection(current, previous) {
209
208
  const deltaY = current.scrollTop - previous.scrollTop;
210
209
  const deltaX = current.scrollLeft - previous.scrollLeft;
211
- if (Math.abs(deltaY) > Math.abs(deltaX)) {
210
+ if (Math.abs(deltaY) >= Math.abs(deltaX)) {
212
211
  if (deltaY > 0) return "down";
213
212
  if (deltaY < 0) return "up";
214
213
  } else {
@@ -223,7 +222,7 @@ function raf(callback) {
223
222
  if (typeof requestAnimationFrame !== "undefined") {
224
223
  return requestAnimationFrame(callback);
225
224
  }
226
- return setTimeout(() => callback(Date.now()), 16);
225
+ return setTimeout(() => callback(performance.now()), 16);
227
226
  }
228
227
  function cancelRaf(id) {
229
228
  if (typeof cancelAnimationFrame !== "undefined") {
@@ -248,11 +247,15 @@ var ScrollEngine = class {
248
247
  this.container = null;
249
248
  this.scrollPosition = { scrollTop: 0, scrollLeft: 0 };
250
249
  this.previousScrollPosition = { scrollTop: 0, scrollLeft: 0 };
250
+ // The position the last scroll event reported (scrollPosition is also updated by programmatic scrolls, ahead of the
251
+ // event the browser fires for them, and a delta against it would always be 0)
252
+ this.reportedPosition = { scrollTop: 0, scrollLeft: 0 };
251
253
  this.scrolling = false;
252
254
  this.scrollDirection = "none";
253
255
  this.lastScrollTime = 0;
254
256
  this.scrollEndTimer = null;
255
257
  this.scrollEndDelay = 150;
258
+ this.horizontal = false;
256
259
  // Animation state
257
260
  this.animationId = null;
258
261
  this.animationStartTime = 0;
@@ -278,6 +281,7 @@ var ScrollEngine = class {
278
281
  this.container = container;
279
282
  this.scrollPosition = getScrollPosition(container);
280
283
  this.previousScrollPosition = { ...this.scrollPosition };
284
+ this.reportedPosition = { ...this.scrollPosition };
281
285
  this.throttledHandleScroll = throttleRAF(this.processScroll.bind(this));
282
286
  this.boundHandleScroll = () => this.throttledHandleScroll?.();
283
287
  container.addEventListener("scroll", this.boundHandleScroll, { passive: true });
@@ -286,6 +290,15 @@ var ScrollEngine = class {
286
290
  * Detach from the current container.
287
291
  */
288
292
  detach() {
293
+ if (this.scrolling) {
294
+ this.scrolling = false;
295
+ this.onScrollEndCallback?.({
296
+ type: "scroll-end",
297
+ scrollTop: this.scrollPosition.scrollTop,
298
+ scrollLeft: this.scrollPosition.scrollLeft,
299
+ timestamp: performance.now()
300
+ });
301
+ }
289
302
  if (this.container && this.boundHandleScroll) {
290
303
  this.container.removeEventListener("scroll", this.boundHandleScroll);
291
304
  }
@@ -310,8 +323,9 @@ var ScrollEngine = class {
310
323
  processScroll() {
311
324
  if (!this.container) return;
312
325
  const now = performance.now();
313
- this.previousScrollPosition = { ...this.scrollPosition };
326
+ this.previousScrollPosition = { ...this.reportedPosition };
314
327
  this.scrollPosition = getScrollPosition(this.container);
328
+ this.reportedPosition = { ...this.scrollPosition };
315
329
  this.scrollDirection = getScrollDirection(this.scrollPosition, this.previousScrollPosition);
316
330
  if (!this.scrolling) {
317
331
  this.scrolling = true;
@@ -372,11 +386,12 @@ var ScrollEngine = class {
372
386
  this.animationId = null;
373
387
  }
374
388
  setScrollPosition(this.container, position);
389
+ const actual = getScrollPosition(this.container);
375
390
  if (position.scrollTop !== void 0) {
376
- this.scrollPosition.scrollTop = position.scrollTop;
391
+ this.scrollPosition.scrollTop = actual.scrollTop;
377
392
  }
378
393
  if (position.scrollLeft !== void 0) {
379
- this.scrollPosition.scrollLeft = position.scrollLeft;
394
+ this.scrollPosition.scrollLeft = actual.scrollLeft;
380
395
  }
381
396
  }
382
397
  /**
@@ -388,8 +403,8 @@ var ScrollEngine = class {
388
403
  scrollTo(offset, options = {}) {
389
404
  if (!this.container) return;
390
405
  const { behavior = "auto", duration = 300, easing = easings.easeInOut } = options;
391
- if (behavior === "auto" || behavior === "smooth" && duration === 0) {
392
- this.setScrollPosition({ scrollTop: offset });
406
+ if (behavior === "auto" || !(duration > 0)) {
407
+ this.setScrollPosition(this.horizontal ? { scrollLeft: offset } : { scrollTop: offset });
393
408
  } else {
394
409
  this.animateScroll(offset, duration, easing);
395
410
  }
@@ -402,16 +417,16 @@ var ScrollEngine = class {
402
417
  cancelRaf(this.animationId);
403
418
  }
404
419
  this.animationStartTime = performance.now();
405
- this.animationStartOffset = this.scrollPosition.scrollTop;
420
+ this.animationStartOffset = this.horizontal ? this.scrollPosition.scrollLeft : this.scrollPosition.scrollTop;
406
421
  this.animationTargetOffset = targetOffset;
407
422
  this.animationDuration = duration;
408
423
  this.animationEasing = easing;
409
424
  const animate = (currentTime) => {
410
425
  const elapsed = currentTime - this.animationStartTime;
411
- const progress = Math.min(elapsed / this.animationDuration, 1);
426
+ const progress = Math.max(0, Math.min(elapsed / this.animationDuration, 1));
412
427
  const easedProgress = this.animationEasing(progress);
413
428
  const currentOffset = this.animationStartOffset + (this.animationTargetOffset - this.animationStartOffset) * easedProgress;
414
- this.setScrollPosition({ scrollTop: currentOffset });
429
+ this.setScrollPosition(this.horizontal ? { scrollLeft: currentOffset } : { scrollTop: currentOffset });
415
430
  if (progress < 1) {
416
431
  this.animationId = raf(animate);
417
432
  } else {
@@ -449,6 +464,14 @@ var ScrollEngine = class {
449
464
  *
450
465
  * @param delay - Delay in ms
451
466
  */
467
+ /**
468
+ * Set the axis that scrollTo() and its animation drive.
469
+ *
470
+ * @param direction - Scroll direction
471
+ */
472
+ setDirection(direction) {
473
+ this.horizontal = direction === "horizontal";
474
+ }
452
475
  setScrollEndDelay(delay) {
453
476
  this.scrollEndDelay = delay;
454
477
  }
@@ -512,6 +535,11 @@ function getViewport(element) {
512
535
  scrollHeight: element.scrollHeight
513
536
  };
514
537
  }
538
+ function getContentWidth(element) {
539
+ const style = typeof getComputedStyle === "function" ? getComputedStyle(element) : null;
540
+ const padding = style ? (parseFloat(style.paddingLeft) || 0) + (parseFloat(style.paddingRight) || 0) : 0;
541
+ return Math.max(0, element.clientWidth - padding);
542
+ }
515
543
 
516
544
  // src/kernel/viewport.ts
517
545
  var ViewportManager = class {
@@ -687,6 +715,16 @@ function binarySearch(length, predicate) {
687
715
  function clamp(value, min, max) {
688
716
  return Math.min(Math.max(value, min), max);
689
717
  }
718
+ function normalizeColumnCount(columns) {
719
+ return Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 1;
720
+ }
721
+ function autoColumnCount(containerWidth, minColumnWidth, gap) {
722
+ const slot = minColumnWidth + gap;
723
+ return slot > 0 ? normalizeColumnCount(Math.floor((containerWidth + gap) / slot)) : 1;
724
+ }
725
+ function normalizeOverscan(overscan) {
726
+ return Number.isNaN(overscan) ? 0 : Math.max(0, Math.floor(overscan));
727
+ }
690
728
 
691
729
  // src/kernel/measurement-cache.ts
692
730
  var MeasurementCache = class {
@@ -837,19 +875,17 @@ var MeasurementCache = class {
837
875
  if (offset === 0) return;
838
876
  const newCache = /* @__PURE__ */ new Map();
839
877
  for (const [index, height] of this.cache) {
840
- if (index >= startIndex) {
841
- const newIndex = index + offset;
842
- if (newIndex >= 0) {
843
- newCache.set(newIndex, height);
844
- } else {
845
- this.totalMeasured--;
846
- this.sumOfHeights -= height;
847
- }
848
- } else {
849
- newCache.set(index, height);
878
+ const newIndex = index >= startIndex ? index + offset : index;
879
+ if (newIndex >= 0) {
880
+ newCache.set(newIndex, height);
850
881
  }
851
882
  }
852
883
  this.cache = newCache;
884
+ this.totalMeasured = newCache.size;
885
+ this.sumOfHeights = 0;
886
+ for (const height of newCache.values()) {
887
+ this.sumOfHeights += height;
888
+ }
853
889
  }
854
890
  /**
855
891
  * Get the internal cache map.
@@ -882,13 +918,13 @@ var RangeCalculator = class {
882
918
  * @param options - Configuration options
883
919
  */
884
920
  constructor(options) {
885
- this.offsetCache = [];
886
- this.dirtyFromIndex = 0;
887
- this.totalSize = 0;
921
+ // Fenwick trees (1-based) over the measured items with index < itemCount
922
+ this.countTree = new Float64Array(1);
923
+ this.sumTree = new Float64Array(1);
924
+ this.treesValid = false;
888
925
  this.itemCount = options.itemCount;
889
926
  this.overscan = options.overscan;
890
927
  this.measurementCache = new MeasurementCache(options.estimatedItemHeight);
891
- this.rebuildOffsetCache();
892
928
  }
893
929
  /**
894
930
  * Get the visible range of items.
@@ -906,7 +942,6 @@ var RangeCalculator = class {
906
942
  overscanEndIndex: 0
907
943
  };
908
944
  }
909
- this.ensureOffsetCacheValid(this.itemCount - 1);
910
945
  const startIndex = this.findStartIndex(scrollOffset);
911
946
  const scrollEnd = scrollOffset + viewportSize;
912
947
  const endIndex = this.findEndIndex(scrollEnd, startIndex);
@@ -934,13 +969,9 @@ var RangeCalculator = class {
934
969
  * Find the end index for a given scroll end position.
935
970
  */
936
971
  findEndIndex(scrollEnd, startIndex) {
937
- if (scrollEnd >= this.totalSize) return this.itemCount - 1;
972
+ if (scrollEnd >= this.getTotalSize()) return this.itemCount - 1;
938
973
  let index = startIndex;
939
- while (index < this.itemCount - 1) {
940
- const itemStart = this.getItemOffset(index);
941
- if (itemStart >= scrollEnd) {
942
- break;
943
- }
974
+ while (index < this.itemCount - 1 && this.getItemOffset(index + 1) < scrollEnd) {
944
975
  index++;
945
976
  }
946
977
  return clamp(index, startIndex, this.itemCount - 1);
@@ -953,9 +984,8 @@ var RangeCalculator = class {
953
984
  */
954
985
  getItemOffset(index) {
955
986
  if (index < 0 || this.itemCount === 0) return 0;
956
- if (index >= this.itemCount) return this.totalSize;
957
- this.ensureOffsetCacheValid(index);
958
- return this.offsetCache[index] ?? 0;
987
+ if (index >= this.itemCount) return this.getTotalSize();
988
+ return this.offsetBefore(Math.floor(index));
959
989
  }
960
990
  /**
961
991
  * Get the end position of an item.
@@ -981,8 +1011,7 @@ var RangeCalculator = class {
981
1011
  * @returns Total size
982
1012
  */
983
1013
  getTotalSize() {
984
- this.ensureOffsetCacheValid(this.itemCount - 1);
985
- return this.totalSize;
1014
+ return this.offsetBefore(this.itemCount);
986
1015
  }
987
1016
  /**
988
1017
  * Set the height for an item.
@@ -993,7 +1022,7 @@ var RangeCalculator = class {
993
1022
  */
994
1023
  setItemHeight(index, height) {
995
1024
  const previousHeight = this.measurementCache.set(index, height);
996
- this.invalidateFrom(index);
1025
+ this.track(index, previousHeight === void 0 ? 1 : 0, height - (previousHeight ?? 0));
997
1026
  return previousHeight;
998
1027
  }
999
1028
  /**
@@ -1011,8 +1040,9 @@ var RangeCalculator = class {
1011
1040
  * @param index - Item index
1012
1041
  */
1013
1042
  invalidate(index) {
1043
+ const previousHeight = this.measurementCache.get(index);
1014
1044
  if (this.measurementCache.delete(index)) {
1015
- this.invalidateFrom(index);
1045
+ this.track(index, -1, -(previousHeight ?? 0));
1016
1046
  }
1017
1047
  }
1018
1048
  /**
@@ -1020,41 +1050,7 @@ var RangeCalculator = class {
1020
1050
  */
1021
1051
  invalidateAll() {
1022
1052
  this.measurementCache.clear();
1023
- this.dirtyFromIndex = 0;
1024
- this.rebuildOffsetCache();
1025
- }
1026
- /**
1027
- * Mark offset cache as dirty from a specific index.
1028
- */
1029
- invalidateFrom(index) {
1030
- this.dirtyFromIndex = Math.min(this.dirtyFromIndex, index);
1031
- }
1032
- /**
1033
- * Ensure offset cache is valid up to the given index.
1034
- */
1035
- ensureOffsetCacheValid(upToIndex) {
1036
- if (this.dirtyFromIndex > upToIndex) return;
1037
- let offset = this.dirtyFromIndex === 0 ? 0 : (this.offsetCache[this.dirtyFromIndex - 1] ?? 0) + this.getItemSize(this.dirtyFromIndex - 1);
1038
- for (let i = this.dirtyFromIndex; i <= upToIndex && i < this.itemCount; i++) {
1039
- this.offsetCache[i] = offset;
1040
- offset += this.getItemSize(i);
1041
- }
1042
- if (upToIndex >= this.itemCount - 1) {
1043
- this.totalSize = offset;
1044
- }
1045
- this.dirtyFromIndex = upToIndex + 1;
1046
- }
1047
- /**
1048
- * Rebuild the entire offset cache.
1049
- */
1050
- rebuildOffsetCache() {
1051
- this.offsetCache = new Array(this.itemCount);
1052
- this.dirtyFromIndex = 0;
1053
- if (this.itemCount > 0) {
1054
- this.ensureOffsetCacheValid(this.itemCount - 1);
1055
- } else {
1056
- this.totalSize = 0;
1057
- }
1053
+ this.treesValid = false;
1058
1054
  }
1059
1055
  /**
1060
1056
  * Update item count.
@@ -1066,20 +1062,11 @@ var RangeCalculator = class {
1066
1062
  const previousCount = this.itemCount;
1067
1063
  this.itemCount = count;
1068
1064
  if (count < previousCount) {
1069
- this.offsetCache.length = count;
1070
- if (count > 0) {
1071
- const lastIndex = count - 1;
1072
- this.dirtyFromIndex = Math.min(this.dirtyFromIndex, lastIndex);
1073
- this.ensureOffsetCacheValid(lastIndex);
1074
- } else {
1075
- this.totalSize = 0;
1076
- }
1077
- } else {
1078
- this.offsetCache.length = count;
1079
- if (this.dirtyFromIndex > previousCount) {
1080
- this.dirtyFromIndex = previousCount;
1065
+ for (const measured of this.measurementCache.getMeasuredIndices()) {
1066
+ if (measured >= count) this.measurementCache.delete(measured);
1081
1067
  }
1082
1068
  }
1069
+ this.treesValid = false;
1083
1070
  }
1084
1071
  /**
1085
1072
  * Update overscan amount.
@@ -1096,7 +1083,6 @@ var RangeCalculator = class {
1096
1083
  */
1097
1084
  setEstimatedHeight(height) {
1098
1085
  this.measurementCache.setEstimatedHeight(height);
1099
- this.dirtyFromIndex = 0;
1100
1086
  }
1101
1087
  /**
1102
1088
  * Get the estimated item height.
@@ -1114,8 +1100,7 @@ var RangeCalculator = class {
1114
1100
  */
1115
1101
  getItemAtOffset(offset) {
1116
1102
  if (offset <= 0 || this.itemCount === 0) return 0;
1117
- if (offset >= this.totalSize) return this.itemCount - 1;
1118
- this.ensureOffsetCacheValid(this.itemCount - 1);
1103
+ if (offset >= this.getTotalSize()) return this.itemCount - 1;
1119
1104
  return binarySearch(this.itemCount, (mid) => {
1120
1105
  const itemEnd = this.getItemEnd(mid);
1121
1106
  return itemEnd > offset;
@@ -1137,6 +1122,51 @@ var RangeCalculator = class {
1137
1122
  getItemCount() {
1138
1123
  return this.itemCount;
1139
1124
  }
1125
+ /**
1126
+ * Position where item `index` starts (index === itemCount gives the total size).
1127
+ */
1128
+ offsetBefore(index) {
1129
+ this.ensureTrees();
1130
+ let measuredCount = 0;
1131
+ let measuredSum = 0;
1132
+ for (let i = index; i > 0; i -= i & -i) {
1133
+ measuredCount += this.countTree[i];
1134
+ measuredSum += this.sumTree[i];
1135
+ }
1136
+ return measuredSum + (index - measuredCount) * this.measurementCache.getEstimatedHeight();
1137
+ }
1138
+ /**
1139
+ * Record that the measured set changed at `index` (a no-op until the trees are built).
1140
+ */
1141
+ track(index, countDelta, sumDelta) {
1142
+ if (!this.treesValid || index < 0 || index >= this.itemCount || !Number.isInteger(index)) return;
1143
+ for (let i = index + 1; i <= this.itemCount; i += i & -i) {
1144
+ this.countTree[i] += countDelta;
1145
+ this.sumTree[i] += sumDelta;
1146
+ }
1147
+ }
1148
+ /**
1149
+ * Build the Fenwick trees from the measurement cache (linear time).
1150
+ */
1151
+ ensureTrees() {
1152
+ if (this.treesValid) return;
1153
+ const size = this.itemCount;
1154
+ this.countTree = new Float64Array(size + 1);
1155
+ this.sumTree = new Float64Array(size + 1);
1156
+ for (const index of this.measurementCache.getMeasuredIndices()) {
1157
+ if (index < 0 || index >= size || !Number.isInteger(index)) continue;
1158
+ this.countTree[index + 1] = 1;
1159
+ this.sumTree[index + 1] = this.measurementCache.get(index) ?? 0;
1160
+ }
1161
+ for (let i = 1; i <= size; i++) {
1162
+ const parent = i + (i & -i);
1163
+ if (parent <= size) {
1164
+ this.countTree[parent] += this.countTree[i];
1165
+ this.sumTree[parent] += this.sumTree[i];
1166
+ }
1167
+ }
1168
+ this.treesValid = true;
1169
+ }
1140
1170
  };
1141
1171
 
1142
1172
  // src/kernel/plugin-registry.ts
@@ -1169,7 +1199,12 @@ var PluginRegistry = class {
1169
1199
  }
1170
1200
  this.plugins.set(plugin.name, plugin);
1171
1201
  if (this.kernel && plugin.install) {
1172
- plugin.install(this.kernel);
1202
+ try {
1203
+ plugin.install(this.kernel);
1204
+ } catch (error) {
1205
+ this.plugins.delete(plugin.name);
1206
+ throw error;
1207
+ }
1173
1208
  this.setupHooks(plugin);
1174
1209
  }
1175
1210
  }
@@ -1185,8 +1220,11 @@ var PluginRegistry = class {
1185
1220
  return false;
1186
1221
  }
1187
1222
  this.teardownHooks(plugin);
1188
- plugin.uninstall?.();
1189
- this.plugins.delete(name);
1223
+ try {
1224
+ plugin.uninstall?.();
1225
+ } finally {
1226
+ this.plugins.delete(name);
1227
+ }
1190
1228
  return true;
1191
1229
  }
1192
1230
  /**
@@ -1373,7 +1411,11 @@ var PluginRegistry = class {
1373
1411
  clear() {
1374
1412
  const names = Array.from(this.plugins.keys()).reverse();
1375
1413
  for (const name of names) {
1376
- this.unregister(name);
1414
+ try {
1415
+ this.unregister(name);
1416
+ } catch (error) {
1417
+ console.error(`[Scrollex] Error uninstalling plugin "${name}":`, error);
1418
+ }
1377
1419
  }
1378
1420
  }
1379
1421
  /**
@@ -1396,8 +1438,10 @@ var DEFAULT_OPTIONS = {
1396
1438
  };
1397
1439
  function createKernel(options = {}) {
1398
1440
  const config = { ...DEFAULT_OPTIONS, ...options };
1441
+ config.overscan = normalizeOverscan(config.overscan);
1399
1442
  const eventBus = new EventBus();
1400
1443
  const scrollEngine = new ScrollEngine();
1444
+ scrollEngine.setDirection(config.direction);
1401
1445
  const viewportManager = new ViewportManager();
1402
1446
  const rangeCalculator = new RangeCalculator({
1403
1447
  itemCount: config.itemCount,
@@ -1405,6 +1449,8 @@ function createKernel(options = {}) {
1405
1449
  overscan: config.overscan
1406
1450
  });
1407
1451
  const pluginRegistry = new PluginRegistry();
1452
+ const startPadding = () => config.paddingStart ?? 0;
1453
+ let rangeAnnounced = false;
1408
1454
  let currentRange = {
1409
1455
  startIndex: 0,
1410
1456
  endIndex: 0,
@@ -1428,7 +1474,13 @@ function createKernel(options = {}) {
1428
1474
  },
1429
1475
  // Scroll Control
1430
1476
  getScrollPosition() {
1431
- return scrollEngine.getScrollPosition();
1477
+ const position = scrollEngine.getScrollPosition();
1478
+ const horizontal = config.direction === "horizontal";
1479
+ const offset = horizontal ? position.scrollLeft : position.scrollTop;
1480
+ const viewport = viewportManager.getViewport();
1481
+ const maxScroll = rangeCalculator.getTotalSize() + startPadding() - (horizontal ? viewport.width : viewport.height);
1482
+ const percentage = maxScroll > 0 ? Math.min(1, Math.max(0, offset / maxScroll)) : 0;
1483
+ return { ...position, offset, percentage };
1432
1484
  },
1433
1485
  setScrollPosition(position) {
1434
1486
  scrollEngine.setScrollPosition(position);
@@ -1438,37 +1490,39 @@ function createKernel(options = {}) {
1438
1490
  },
1439
1491
  scrollToIndex(index, options2 = {}) {
1440
1492
  const { align = "auto", offset: additionalOffset = 0, ...scrollOptions } = options2;
1441
- const itemOffset = rangeCalculator.getItemOffset(index);
1493
+ const itemOffset = rangeCalculator.getItemOffset(index) + startPadding();
1442
1494
  const itemSize = rangeCalculator.getItemSize(index);
1443
1495
  const viewport = viewportManager.getViewport();
1496
+ const horizontal = config.direction === "horizontal";
1497
+ const viewportSize = horizontal ? viewport.width : viewport.height;
1444
1498
  let targetOffset;
1445
1499
  switch (align) {
1446
1500
  case "start":
1447
1501
  targetOffset = itemOffset;
1448
1502
  break;
1449
1503
  case "center":
1450
- targetOffset = itemOffset - viewport.height / 2 + itemSize / 2;
1504
+ targetOffset = itemOffset - viewportSize / 2 + itemSize / 2;
1451
1505
  break;
1452
1506
  case "end":
1453
- targetOffset = itemOffset - viewport.height + itemSize;
1507
+ targetOffset = itemOffset - viewportSize + itemSize;
1454
1508
  break;
1455
1509
  case "auto":
1456
1510
  default: {
1457
1511
  const scrollPosition = scrollEngine.getScrollPosition();
1458
- const visibleStart = scrollPosition.scrollTop;
1459
- const visibleEnd = visibleStart + viewport.height;
1512
+ const visibleStart = horizontal ? scrollPosition.scrollLeft : scrollPosition.scrollTop;
1513
+ const visibleEnd = visibleStart + viewportSize;
1460
1514
  const itemEnd = itemOffset + itemSize;
1461
1515
  if (itemOffset < visibleStart) {
1462
1516
  targetOffset = itemOffset;
1463
1517
  } else if (itemEnd > visibleEnd) {
1464
- targetOffset = itemEnd - viewport.height;
1518
+ targetOffset = itemEnd - viewportSize;
1465
1519
  } else {
1466
1520
  return;
1467
1521
  }
1468
1522
  break;
1469
1523
  }
1470
1524
  }
1471
- const maxScroll = Math.max(0, rangeCalculator.getTotalSize() - viewport.height);
1525
+ const maxScroll = Math.max(0, rangeCalculator.getTotalSize() + startPadding() - viewportSize);
1472
1526
  targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
1473
1527
  scrollEngine.scrollTo(targetOffset, scrollOptions);
1474
1528
  },
@@ -1491,6 +1545,8 @@ function createKernel(options = {}) {
1491
1545
  },
1492
1546
  // Measurement
1493
1547
  measureItem(index, size) {
1548
+ if (!Number.isFinite(size) || size < 0) return;
1549
+ if (!Number.isInteger(index) || index < 0 || index >= rangeCalculator.getItemCount()) return;
1494
1550
  const previousHeight = rangeCalculator.setItemHeight(index, size);
1495
1551
  eventBus.emit({
1496
1552
  type: "item-measured",
@@ -1504,18 +1560,19 @@ function createKernel(options = {}) {
1504
1560
  return rangeCalculator.getCachedHeight(index);
1505
1561
  },
1506
1562
  invalidateMeasurement(index) {
1563
+ const wasMeasured = rangeCalculator.getCachedHeight(index) !== void 0;
1507
1564
  rangeCalculator.invalidate(index);
1508
- updateVisibleRange();
1565
+ updateVisibleRange(wasMeasured);
1509
1566
  },
1510
1567
  invalidateAllMeasurements() {
1511
1568
  rangeCalculator.invalidateAll();
1512
- updateVisibleRange();
1569
+ updateVisibleRange(true);
1513
1570
  },
1514
1571
  getEstimatedHeight() {
1515
1572
  return rangeCalculator.getEstimatedHeight();
1516
1573
  },
1517
1574
  getItemOffset(index) {
1518
- return rangeCalculator.getItemOffset(index);
1575
+ return rangeCalculator.getItemOffset(index) + startPadding();
1519
1576
  },
1520
1577
  // Events
1521
1578
  emit(event) {
@@ -1541,21 +1598,28 @@ function createKernel(options = {}) {
1541
1598
  });
1542
1599
  }
1543
1600
  }
1601
+ let layoutChanged = false;
1602
+ if (newOptions.paddingStart !== void 0) {
1603
+ layoutChanged = newOptions.paddingStart !== startPadding();
1604
+ config.paddingStart = newOptions.paddingStart;
1605
+ }
1544
1606
  if (newOptions.estimatedItemHeight !== void 0) {
1607
+ layoutChanged = layoutChanged || newOptions.estimatedItemHeight !== config.estimatedItemHeight;
1545
1608
  config.estimatedItemHeight = newOptions.estimatedItemHeight;
1546
1609
  rangeCalculator.setEstimatedHeight(newOptions.estimatedItemHeight);
1547
1610
  }
1548
1611
  if (newOptions.overscan !== void 0) {
1549
- config.overscan = newOptions.overscan;
1550
- rangeCalculator.setOverscan(newOptions.overscan);
1612
+ config.overscan = normalizeOverscan(newOptions.overscan);
1613
+ rangeCalculator.setOverscan(config.overscan);
1551
1614
  }
1552
1615
  if (newOptions.direction !== void 0) {
1553
1616
  config.direction = newOptions.direction;
1617
+ scrollEngine.setDirection(newOptions.direction);
1554
1618
  }
1555
1619
  if (newOptions.getItemKey !== void 0) {
1556
1620
  config.getItemKey = newOptions.getItemKey;
1557
1621
  }
1558
- updateVisibleRange();
1622
+ updateVisibleRange(layoutChanged);
1559
1623
  },
1560
1624
  getOptions() {
1561
1625
  return { ...config };
@@ -1568,13 +1632,14 @@ function createKernel(options = {}) {
1568
1632
  return config.itemCount;
1569
1633
  },
1570
1634
  getTotalSize() {
1571
- return rangeCalculator.getTotalSize();
1635
+ return rangeCalculator.getTotalSize() + startPadding();
1572
1636
  },
1573
1637
  // Lifecycle
1574
1638
  attach(container) {
1575
1639
  if (attached) {
1576
1640
  kernel.detach();
1577
1641
  }
1642
+ const previousViewport = viewportManager.getViewport();
1578
1643
  scrollEngine.attach(container);
1579
1644
  viewportManager.attach(container);
1580
1645
  attached = true;
@@ -1592,6 +1657,10 @@ function createKernel(options = {}) {
1592
1657
  eventBus.emit(event);
1593
1658
  updateVisibleRange();
1594
1659
  });
1660
+ const viewport = viewportManager.getViewport();
1661
+ if (viewport.width !== previousViewport.width || viewport.height !== previousViewport.height || viewport.scrollWidth !== previousViewport.scrollWidth || viewport.scrollHeight !== previousViewport.scrollHeight) {
1662
+ eventBus.emit({ type: "resize", viewport, previousViewport });
1663
+ }
1595
1664
  updateVisibleRange();
1596
1665
  },
1597
1666
  detach() {
@@ -1606,15 +1675,16 @@ function createKernel(options = {}) {
1606
1675
  }
1607
1676
  };
1608
1677
  pluginRegistry.setKernel(kernel);
1609
- function updateVisibleRange() {
1678
+ function updateVisibleRange(layoutChanged = false) {
1610
1679
  if (!attached) return;
1611
1680
  const viewport = viewportManager.getViewport();
1612
1681
  const scrollPosition = scrollEngine.getScrollPosition();
1613
- const scrollOffset = config.direction === "vertical" ? scrollPosition.scrollTop : scrollPosition.scrollLeft;
1682
+ const scrollOffset = (config.direction === "vertical" ? scrollPosition.scrollTop : scrollPosition.scrollLeft) - startPadding();
1614
1683
  const viewportSize = config.direction === "vertical" ? viewport.height : viewport.width;
1615
1684
  const previousRange = { ...currentRange };
1616
1685
  currentRange = rangeCalculator.getVisibleRange(scrollOffset, viewportSize);
1617
- if (currentRange.startIndex !== previousRange.startIndex || currentRange.endIndex !== previousRange.endIndex || currentRange.overscanStartIndex !== previousRange.overscanStartIndex || currentRange.overscanEndIndex !== previousRange.overscanEndIndex) {
1686
+ if (layoutChanged || !rangeAnnounced || currentRange.startIndex !== previousRange.startIndex || currentRange.endIndex !== previousRange.endIndex || currentRange.overscanStartIndex !== previousRange.overscanStartIndex || currentRange.overscanEndIndex !== previousRange.overscanEndIndex) {
1687
+ rangeAnnounced = true;
1618
1688
  eventBus.emit({
1619
1689
  type: "visible-range-change",
1620
1690
  range: currentRange,
@@ -1641,32 +1711,6 @@ function createPlugin(config) {
1641
1711
  }
1642
1712
 
1643
1713
  // src/plugins/core/list-renderer.ts
1644
- var VirtualItemPool = class {
1645
- constructor() {
1646
- this.pool = [];
1647
- }
1648
- acquire() {
1649
- const item = this.pool.pop();
1650
- if (item) {
1651
- return item;
1652
- }
1653
- return { index: 0, key: 0, start: 0, end: 0, size: 0, lane: 0 };
1654
- }
1655
- release(item) {
1656
- item.index = 0;
1657
- item.key = 0;
1658
- item.start = 0;
1659
- item.end = 0;
1660
- item.size = 0;
1661
- item.lane = 0;
1662
- this.pool.push(item);
1663
- }
1664
- releaseAll(items) {
1665
- for (const item of items) {
1666
- this.release(item);
1667
- }
1668
- }
1669
- };
1670
1714
  function listRendererPlugin(options = {}) {
1671
1715
  const { getItemKey = (index) => index } = options;
1672
1716
  let kernel = null;
@@ -1677,24 +1721,24 @@ function listRendererPlugin(options = {}) {
1677
1721
  overscanStartIndex: 0,
1678
1722
  overscanEndIndex: 0
1679
1723
  };
1680
- const itemPool = new VirtualItemPool();
1681
1724
  function buildVirtualItems(range) {
1682
1725
  if (!kernel) return [];
1683
- itemPool.releaseAll(virtualItems);
1684
1726
  const items = [];
1685
1727
  range.startIndex;
1686
1728
  range.endIndex;
1687
- for (let i = range.overscanStartIndex; i <= range.overscanEndIndex; i++) {
1688
- const item = itemPool.acquire();
1729
+ const lastIndex = Math.min(range.overscanEndIndex, kernel.getItemCount() - 1);
1730
+ for (let i = range.overscanStartIndex; i <= lastIndex; i++) {
1689
1731
  const offset = kernel.getItemOffset(i);
1690
1732
  const size = kernel.getCachedHeight(i) ?? kernel.getEstimatedHeight();
1691
- item.index = i;
1692
- item.key = getItemKey(i);
1693
- item.start = offset;
1694
- item.end = offset + size;
1695
- item.size = size;
1696
- item.lane = 0;
1697
- items.push(item);
1733
+ items.push({
1734
+ index: i,
1735
+ key: getItemKey(i),
1736
+ start: offset,
1737
+ end: offset + size,
1738
+ size,
1739
+ lane: 0
1740
+ // For list, always lane 0
1741
+ });
1698
1742
  }
1699
1743
  return items;
1700
1744
  }
@@ -1720,6 +1764,7 @@ function listRendererPlugin(options = {}) {
1720
1764
  return lastItem?.end ?? 0;
1721
1765
  },
1722
1766
  isItemVisible(index) {
1767
+ if (!kernel || index >= kernel.getItemCount()) return false;
1723
1768
  return index >= currentRange.startIndex && index <= currentRange.endIndex;
1724
1769
  },
1725
1770
  recalculate
@@ -1733,7 +1778,6 @@ function listRendererPlugin(options = {}) {
1733
1778
  recalculate();
1734
1779
  },
1735
1780
  uninstall() {
1736
- itemPool.releaseAll(virtualItems);
1737
1781
  virtualItems = [];
1738
1782
  kernel = null;
1739
1783
  },
@@ -1751,7 +1795,56 @@ function listRendererPlugin(options = {}) {
1751
1795
  };
1752
1796
  }
1753
1797
 
1798
+ // src/react/hooks/items-range.ts
1799
+ function getItemsRange(items, scrollTop, viewportHeight) {
1800
+ if (items.length === 0) {
1801
+ return { startIndex: 0, endIndex: 0, overscanStartIndex: 0, overscanEndIndex: 0 };
1802
+ }
1803
+ const overscanStartIndex = items[0].index;
1804
+ const overscanEndIndex = items[items.length - 1].index;
1805
+ const viewEnd = scrollTop + viewportHeight;
1806
+ let startIndex = -1;
1807
+ let endIndex = -1;
1808
+ for (const item of items) {
1809
+ if (item.end > scrollTop && item.start < viewEnd) {
1810
+ if (startIndex === -1) startIndex = item.index;
1811
+ endIndex = item.index;
1812
+ }
1813
+ }
1814
+ return startIndex === -1 ? { startIndex: overscanStartIndex, endIndex: overscanEndIndex, overscanStartIndex, overscanEndIndex } : { startIndex, endIndex, overscanStartIndex, overscanEndIndex };
1815
+ }
1816
+ function rekeyItems(items, count, getItemKey) {
1817
+ let changed = false;
1818
+ const next = [];
1819
+ for (const item of items) {
1820
+ if (item.index >= count) {
1821
+ changed = true;
1822
+ continue;
1823
+ }
1824
+ const key = getItemKey(item.index);
1825
+ if (key === item.key) {
1826
+ next.push(item);
1827
+ } else {
1828
+ changed = true;
1829
+ next.push({ ...item, key });
1830
+ }
1831
+ }
1832
+ return changed ? next : items;
1833
+ }
1834
+
1754
1835
  // src/react/hooks/use-virtual-list.ts
1836
+ function sameItems(a, b) {
1837
+ if (a === b) return true;
1838
+ if (a.length !== b.length) return false;
1839
+ for (let i = 0; i < a.length; i++) {
1840
+ const x = a[i];
1841
+ const y = b[i];
1842
+ if (x.index !== y.index || x.key !== y.key || x.start !== y.start || x.size !== y.size || x.lane !== y.lane) {
1843
+ return false;
1844
+ }
1845
+ }
1846
+ return true;
1847
+ }
1755
1848
  function useVirtualList(options) {
1756
1849
  const {
1757
1850
  count,
@@ -1765,17 +1858,21 @@ function useVirtualList(options) {
1765
1858
  horizontal = false,
1766
1859
  containerRef
1767
1860
  } = options;
1861
+ const getItemKeyRef = useRef(getItemKey);
1862
+ getItemKeyRef.current = getItemKey;
1768
1863
  const kernelRef = useRef(
1769
1864
  createKernel({
1770
1865
  itemCount: count,
1771
1866
  estimatedItemHeight,
1772
1867
  overscan,
1773
1868
  direction: horizontal ? "horizontal" : "vertical",
1774
- getItemKey
1869
+ getItemKey,
1870
+ paddingStart
1775
1871
  })
1776
1872
  );
1777
1873
  const [virtualItems, setVirtualItems] = useState([]);
1778
1874
  const [isScrolling, setIsScrolling] = useState(false);
1875
+ const [kernelTotalSize, setKernelTotalSize] = useState(() => kernelRef.current.getTotalSize());
1779
1876
  const [scrollOffset, setScrollOffset] = useState(initialOffset);
1780
1877
  const [range, setRange] = useState({
1781
1878
  startIndex: 0,
@@ -1788,12 +1885,12 @@ function useVirtualList(options) {
1788
1885
  const resizeObserverRef = useRef(null);
1789
1886
  const kernel = kernelRef.current;
1790
1887
  useEffect(() => {
1791
- const plugin = listRendererPlugin({ getItemKey });
1888
+ const plugin = listRendererPlugin({ getItemKey: (index) => getItemKeyRef.current(index) });
1792
1889
  kernel.register(plugin);
1793
1890
  listRendererRef.current = plugin.api;
1794
1891
  const unsubScroll = kernel.on("scroll", (event) => {
1795
1892
  const e = event;
1796
- setScrollOffset(horizontal ? e.scrollLeft : e.scrollTop);
1893
+ setScrollOffset(kernel.getOptions().direction === "horizontal" ? e.scrollLeft : e.scrollTop);
1797
1894
  });
1798
1895
  const unsubScrollStart = kernel.on("scroll-start", () => {
1799
1896
  setIsScrolling(true);
@@ -1805,40 +1902,70 @@ function useVirtualList(options) {
1805
1902
  const e = event;
1806
1903
  setRange(e.range);
1807
1904
  setVirtualItems(listRendererRef.current?.getVirtualItems() ?? []);
1905
+ setKernelTotalSize(kernel.getTotalSize());
1808
1906
  });
1907
+ const syncLayout = () => {
1908
+ const next = listRendererRef.current?.getVirtualItems() ?? [];
1909
+ setVirtualItems((previous) => sameItems(previous, next) ? previous : next);
1910
+ setKernelTotalSize(kernel.getTotalSize());
1911
+ };
1912
+ const unsubItemsChange = kernel.on("items-change", syncLayout);
1913
+ const unsubItemMeasured = kernel.on("item-measured", syncLayout);
1809
1914
  return () => {
1810
1915
  unsubScroll();
1811
1916
  unsubScrollStart();
1812
1917
  unsubScrollEnd();
1813
1918
  unsubRangeChange();
1919
+ unsubItemsChange();
1920
+ unsubItemMeasured();
1814
1921
  kernel.destroy();
1815
1922
  };
1816
1923
  }, []);
1924
+ const initialOffsetAppliedRef = useRef(false);
1817
1925
  useEffect(() => {
1818
1926
  const container = containerRef.current;
1819
1927
  if (!container) return;
1820
1928
  kernel.attach(container);
1821
- if (initialOffset > 0) {
1822
- kernel.scrollTo(initialOffset);
1823
- }
1824
1929
  return () => {
1825
1930
  kernel.detach();
1826
1931
  };
1827
- }, [containerRef, kernel, initialOffset]);
1932
+ }, [containerRef, kernel]);
1933
+ const hasRows = virtualItems.length > 0;
1934
+ useEffect(() => {
1935
+ if (initialOffset > 0 && hasRows && !initialOffsetAppliedRef.current && containerRef.current) {
1936
+ initialOffsetAppliedRef.current = true;
1937
+ kernel.scrollTo(initialOffset);
1938
+ }
1939
+ }, [initialOffset, hasRows, kernel, containerRef]);
1828
1940
  useEffect(() => {
1829
1941
  kernel.configure({ itemCount: count });
1830
1942
  }, [count, kernel]);
1831
1943
  useEffect(() => {
1832
1944
  kernel.configure({ overscan });
1833
1945
  }, [overscan, kernel]);
1946
+ useEffect(() => {
1947
+ kernel.configure({ estimatedItemHeight });
1948
+ }, [estimatedItemHeight, kernel]);
1949
+ useEffect(() => {
1950
+ kernel.configure({ paddingStart });
1951
+ }, [paddingStart, kernel]);
1952
+ useEffect(() => {
1953
+ kernel.configure({ direction: horizontal ? "horizontal" : "vertical" });
1954
+ }, [horizontal, kernel]);
1834
1955
  useEffect(() => {
1835
1956
  const observer = new ResizeObserver((entries) => {
1836
1957
  for (const entry of entries) {
1837
1958
  const element = entry.target;
1838
1959
  const index = parseInt(element.dataset["virtualIndex"] ?? "", 10);
1839
1960
  if (!isNaN(index)) {
1840
- const rect = entry.contentRect;
1841
- const size = horizontal ? rect.width : rect.height;
1961
+ const horizontalList = kernel.getOptions().direction === "horizontal";
1962
+ const borderBox = entry.borderBoxSize?.[0];
1963
+ let size = borderBox ? horizontalList ? borderBox.inlineSize : borderBox.blockSize : 0;
1964
+ if (!(size > 0)) {
1965
+ const box = element.getBoundingClientRect();
1966
+ size = horizontalList ? box.width : box.height;
1967
+ }
1968
+ if (!(size > 0)) size = horizontalList ? entry.contentRect.width : entry.contentRect.height;
1842
1969
  if (size > 0) {
1843
1970
  kernel.measureItem(index, size);
1844
1971
  }
@@ -1849,7 +1976,7 @@ function useVirtualList(options) {
1849
1976
  return () => {
1850
1977
  observer.disconnect();
1851
1978
  };
1852
- }, [kernel, horizontal]);
1979
+ }, [kernel]);
1853
1980
  const measureElement = useCallback(
1854
1981
  (index, element) => {
1855
1982
  const observer = resizeObserverRef.current;
@@ -1901,11 +2028,13 @@ function useVirtualList(options) {
1901
2028
  () => kernel.invalidateAllMeasurements(),
1902
2029
  [kernel]
1903
2030
  );
1904
- const totalSize = useMemo(() => {
1905
- return paddingStart + kernel.getTotalSize() + paddingEnd;
1906
- }, [kernel, paddingStart, paddingEnd, virtualItems]);
2031
+ const totalSize = kernelTotalSize + paddingEnd;
2032
+ const keyedItems = useMemo(
2033
+ () => rekeyItems(virtualItems, count, getItemKey),
2034
+ [virtualItems, count, getItemKey]
2035
+ );
1907
2036
  return {
1908
- virtualItems,
2037
+ virtualItems: keyedItems,
1909
2038
  totalSize,
1910
2039
  scrollOffset,
1911
2040
  isScrolling,
@@ -1915,9 +2044,57 @@ function useVirtualList(options) {
1915
2044
  range,
1916
2045
  getMeasurement,
1917
2046
  invalidateMeasurement,
1918
- invalidateAllMeasurements
2047
+ invalidateAllMeasurements,
2048
+ kernel
1919
2049
  };
1920
2050
  }
2051
+ function useKernelPlugins(kernel, plugins) {
2052
+ const registeredRef = useRef([]);
2053
+ useEffect(() => {
2054
+ const previous = registeredRef.current;
2055
+ if (previous.length === plugins.length && previous.every((plugin, i) => plugin === plugins[i])) {
2056
+ return;
2057
+ }
2058
+ for (const plugin of previous) {
2059
+ kernel.unregister(plugin.name);
2060
+ }
2061
+ for (const plugin of plugins) {
2062
+ kernel.register(plugin);
2063
+ }
2064
+ registeredRef.current = plugins;
2065
+ });
2066
+ useEffect(() => () => {
2067
+ for (const plugin of registeredRef.current) {
2068
+ kernel.unregister(plugin.name);
2069
+ }
2070
+ registeredRef.current = [];
2071
+ }, [kernel]);
2072
+ }
2073
+ function useLoadMoreWhenShort(containerRef, { count, totalSize, hasMore, isLoading, threshold, horizontal = false, onLoadMore }) {
2074
+ const requestedCount = useRef(-1);
2075
+ useEffect(() => {
2076
+ if (!hasMore) {
2077
+ requestedCount.current = -1;
2078
+ return;
2079
+ }
2080
+ const element = containerRef.current;
2081
+ if (!element || !onLoadMore || isLoading || requestedCount.current === count) return;
2082
+ const distanceToEnd = horizontal ? element.scrollWidth - element.scrollLeft - element.clientWidth : element.scrollHeight - element.scrollTop - element.clientHeight;
2083
+ if (distanceToEnd < threshold) {
2084
+ requestedCount.current = count;
2085
+ try {
2086
+ const pending = onLoadMore();
2087
+ if (pending && typeof pending.then === "function") {
2088
+ Promise.resolve(pending).catch((error) => {
2089
+ console.error("[Scrollex] Error in onLoadMore:", error);
2090
+ });
2091
+ }
2092
+ } catch (error) {
2093
+ console.error("[Scrollex] Error in onLoadMore:", error);
2094
+ }
2095
+ }
2096
+ }, [count, totalSize, hasMore, isLoading, threshold, horizontal, !!onLoadMore]);
2097
+ }
1921
2098
  var ScrollexContext = createContext(null);
1922
2099
  function useScrollex() {
1923
2100
  const context = useContext(ScrollexContext);
@@ -1972,7 +2149,8 @@ function VirtualListInner(props, ref) {
1972
2149
  scrollToIndex,
1973
2150
  measureElement,
1974
2151
  isScrolling,
1975
- range
2152
+ range,
2153
+ kernel
1976
2154
  } = useVirtualList({
1977
2155
  count: data.length,
1978
2156
  getItemHeight: itemHeight === "auto" ? void 0 : () => itemHeight,
@@ -1983,12 +2161,16 @@ function VirtualListInner(props, ref) {
1983
2161
  horizontal: direction === "horizontal",
1984
2162
  containerRef
1985
2163
  });
1986
- const kernelRef = useRef(createKernel({
1987
- itemCount: data.length,
1988
- estimatedItemHeight: itemHeight === "auto" ? estimatedItemHeight : itemHeight,
1989
- overscan,
1990
- direction
1991
- }));
2164
+ useEffect(() => {
2165
+ if (virtualItems.length === 0) return;
2166
+ onVisibleRangeChange?.(range);
2167
+ onItemsRendered?.({
2168
+ overscanStartIndex: range.overscanStartIndex,
2169
+ overscanEndIndex: range.overscanEndIndex,
2170
+ visibleStartIndex: range.startIndex,
2171
+ visibleEndIndex: range.endIndex
2172
+ });
2173
+ }, [range.startIndex, range.endIndex, range.overscanStartIndex, range.overscanEndIndex]);
1992
2174
  useImperativeHandle(ref, () => ({
1993
2175
  scrollTo: (offset, options) => scrollTo(offset, options),
1994
2176
  scrollToIndex: (index, options) => scrollToIndex(index, options),
@@ -2006,11 +2188,11 @@ function VirtualListInner(props, ref) {
2006
2188
  const handleScrollForInfinite = useCallback((event) => {
2007
2189
  if (!onLoadMore || !hasMore || isLoading) return;
2008
2190
  const target = event.currentTarget;
2009
- const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2010
- if (scrollBottom < threshold) {
2191
+ const distanceToEnd = direction === "horizontal" ? target.scrollWidth - target.scrollLeft - target.clientWidth : target.scrollHeight - target.scrollTop - target.clientHeight;
2192
+ if (distanceToEnd < threshold) {
2011
2193
  onLoadMore();
2012
2194
  }
2013
- }, [onLoadMore, hasMore, isLoading, threshold]);
2195
+ }, [onLoadMore, hasMore, isLoading, threshold, direction]);
2014
2196
  const containerStyles = useMemo(() => ({
2015
2197
  height,
2016
2198
  width,
@@ -2028,10 +2210,10 @@ function VirtualListInner(props, ref) {
2028
2210
  }), [totalSize, direction, innerStyle]);
2029
2211
  const createRenderProps = useCallback(
2030
2212
  (index) => {
2031
- const item = data[index];
2032
- if (item === void 0) {
2033
- throw new Error(`[Scrollex] Item at index ${index} is undefined`);
2213
+ if (index >= data.length) {
2214
+ throw new Error(`[Scrollex] Item at index ${index} is out of range`);
2034
2215
  }
2216
+ const item = data[index];
2035
2217
  const virtualItem = virtualItems.find((vi) => vi.index === index);
2036
2218
  const itemOffset = virtualItem?.start ?? 0;
2037
2219
  const itemSize = virtualItem?.size ?? estimatedItemHeight;
@@ -2039,8 +2221,10 @@ function VirtualListInner(props, ref) {
2039
2221
  position: "absolute",
2040
2222
  top: 0,
2041
2223
  left: 0,
2042
- width: direction === "vertical" ? "100%" : itemSize,
2043
- height: direction === "vertical" ? itemSize : "100%",
2224
+ // Rows that are measured take the size of their content: a fixed size on the measured element would only
2225
+ // measure itself (the estimate until it is measured) and never grow
2226
+ width: direction === "vertical" ? "100%" : itemHeight === "auto" ? "auto" : itemSize,
2227
+ height: direction === "vertical" ? itemHeight === "auto" ? "auto" : itemSize : "100%",
2044
2228
  transform: direction === "vertical" ? `translateY(${itemOffset}px)` : `translateX(${itemOffset}px)`,
2045
2229
  willChange: "transform",
2046
2230
  contain: "layout style",
@@ -2055,11 +2239,13 @@ function VirtualListInner(props, ref) {
2055
2239
  isScrolling
2056
2240
  };
2057
2241
  },
2058
- [data, virtualItems, estimatedItemHeight, direction, itemStyle, measureElement, range, isScrolling]
2242
+ [data, virtualItems, estimatedItemHeight, itemHeight, direction, itemStyle, measureElement, range, isScrolling]
2059
2243
  );
2244
+ useKernelPlugins(kernel, plugins);
2245
+ useLoadMoreWhenShort(containerRef, { count: data.length, totalSize, hasMore, isLoading, threshold, horizontal: direction === "horizontal", onLoadMore });
2060
2246
  const contextValue = useMemo(() => ({
2061
- kernel: kernelRef.current
2062
- }), []);
2247
+ kernel
2248
+ }), [kernel]);
2063
2249
  return /* @__PURE__ */ jsx(ScrollexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(
2064
2250
  "div",
2065
2251
  {
@@ -2072,21 +2258,21 @@ function VirtualListInner(props, ref) {
2072
2258
  },
2073
2259
  role,
2074
2260
  "aria-label": ariaLabel,
2075
- "aria-rowcount": data.length,
2261
+ "aria-orientation": direction,
2076
2262
  tabIndex,
2077
2263
  ...restProps,
2078
2264
  children: [
2079
2265
  /* @__PURE__ */ jsx("div", { className: innerClassName, style: innerContainerStyles, children: virtualItems.map((virtualItem) => {
2080
2266
  const index = virtualItem.index;
2081
- const item = data[index];
2082
- if (item === void 0) return null;
2267
+ if (index >= data.length) return null;
2083
2268
  return /* @__PURE__ */ jsx(
2084
2269
  "div",
2085
2270
  {
2086
2271
  className: itemClassName,
2087
2272
  "data-index": index,
2088
2273
  role: "option",
2089
- "aria-rowindex": index + 1,
2274
+ "aria-setsize": data.length,
2275
+ "aria-posinset": index + 1,
2090
2276
  children: renderItem(createRenderProps(index))
2091
2277
  },
2092
2278
  virtualItem.key
@@ -2106,19 +2292,20 @@ function gridRendererPlugin(options) {
2106
2292
  minColumnWidth = 100,
2107
2293
  rowHeight,
2108
2294
  gap = 0,
2109
- getItemKey = (index) => index
2295
+ getItemKey = (index) => index,
2296
+ getContainerWidth
2110
2297
  } = options;
2111
2298
  let kernel = null;
2112
2299
  let virtualItems = [];
2113
- let columnCount = typeof columns === "number" ? columns : 1;
2300
+ let columnCount = typeof columns === "number" ? normalizeColumnCount(columns) : 1;
2114
2301
  let columnWidth = 0;
2115
2302
  let gapX = typeof gap === "number" ? gap : gap.x;
2116
2303
  let gapY = typeof gap === "number" ? gap : gap.y;
2117
2304
  function calculateColumns(containerWidth) {
2118
2305
  if (typeof columns === "number") {
2119
- columnCount = columns;
2306
+ columnCount = normalizeColumnCount(columns);
2120
2307
  } else {
2121
- columnCount = Math.max(1, Math.floor((containerWidth + gapX) / (minColumnWidth + gapX)));
2308
+ columnCount = autoColumnCount(containerWidth, minColumnWidth, gapX);
2122
2309
  }
2123
2310
  columnWidth = (containerWidth - (columnCount - 1) * gapX) / columnCount;
2124
2311
  }
@@ -2159,7 +2346,7 @@ function gridRendererPlugin(options) {
2159
2346
  function recalculate() {
2160
2347
  if (!kernel) return;
2161
2348
  const viewport = kernel.getViewport();
2162
- calculateColumns(viewport.width);
2349
+ calculateColumns(getContainerWidth?.() ?? viewport.width);
2163
2350
  virtualItems = buildVirtualItems();
2164
2351
  }
2165
2352
  const api = {
@@ -2167,7 +2354,8 @@ function gridRendererPlugin(options) {
2167
2354
  return virtualItems;
2168
2355
  },
2169
2356
  getTotalHeight() {
2170
- return getRowCount() * (rowHeight + gapY) - gapY;
2357
+ const rowCount = getRowCount();
2358
+ return rowCount === 0 ? 0 : rowCount * (rowHeight + gapY) - gapY;
2171
2359
  },
2172
2360
  getColumnCount() {
2173
2361
  return columnCount;
@@ -2209,6 +2397,7 @@ function useVirtualGrid(options) {
2209
2397
  const {
2210
2398
  count,
2211
2399
  columns,
2400
+ minColumnWidth,
2212
2401
  rowHeight,
2213
2402
  gap = 0,
2214
2403
  overscan = 2,
@@ -2218,6 +2407,8 @@ function useVirtualGrid(options) {
2218
2407
  } = options;
2219
2408
  const gapX = typeof gap === "number" ? gap : gap.x;
2220
2409
  const gapY = typeof gap === "number" ? gap : gap.y;
2410
+ const getItemKeyRef = useRef(getItemKey);
2411
+ getItemKeyRef.current = getItemKey;
2221
2412
  const kernelRef = useRef(
2222
2413
  createKernel({
2223
2414
  itemCount: count,
@@ -2236,23 +2427,49 @@ function useVirtualGrid(options) {
2236
2427
  overscanStartIndex: 0,
2237
2428
  overscanEndIndex: 0
2238
2429
  });
2239
- const [columnCount, setColumnCount] = useState(typeof columns === "number" ? columns : 1);
2430
+ const [columnCount, setColumnCount] = useState(typeof columns === "number" ? normalizeColumnCount(columns) : 1);
2240
2431
  const [columnWidth, setColumnWidth] = useState(0);
2241
2432
  const gridRendererRef = useRef(null);
2242
2433
  const kernel = kernelRef.current;
2434
+ const publishItems = useCallback((items) => {
2435
+ setVirtualItems(items);
2436
+ setRange(getItemsRange(items, kernel.getScrollPosition().scrollTop, kernel.getViewport().height));
2437
+ const api = gridRendererRef.current;
2438
+ const itemCount = kernel.getItemCount();
2439
+ if (api && itemCount > 0) kernel.configure({ estimatedItemHeight: api.getTotalHeight() / itemCount });
2440
+ }, [kernel]);
2243
2441
  useEffect(() => {
2244
2442
  const plugin = gridRendererPlugin({
2245
2443
  columns,
2444
+ minColumnWidth,
2246
2445
  rowHeight,
2247
2446
  gap: { x: gapX, y: gapY },
2248
- getItemKey
2447
+ getItemKey: (index) => getItemKeyRef.current(index),
2448
+ getContainerWidth: () => containerRef.current ? getContentWidth(containerRef.current) : void 0
2249
2449
  });
2250
2450
  kernel.register(plugin);
2251
- gridRendererRef.current = plugin.api;
2451
+ const api = plugin.api;
2452
+ gridRendererRef.current = api;
2453
+ if (containerRef.current) {
2454
+ api.recalculate();
2455
+ setColumnCount(api.getColumnCount());
2456
+ setColumnWidth(api.getColumnWidth());
2457
+ publishItems(api.getVirtualItems());
2458
+ }
2459
+ return () => {
2460
+ kernel.unregister(plugin.name);
2461
+ gridRendererRef.current = null;
2462
+ };
2463
+ }, [kernel, columns, minColumnWidth, rowHeight, gapX, gapY]);
2464
+ useEffect(() => {
2252
2465
  const unsubScroll = kernel.on("scroll", (event) => {
2253
2466
  const e = event;
2254
2467
  setScrollOffset(e.scrollTop);
2255
- setVirtualItems(gridRendererRef.current?.getVirtualItems() ?? []);
2468
+ const api = gridRendererRef.current;
2469
+ if (api) {
2470
+ api.recalculate();
2471
+ publishItems(api.getVirtualItems());
2472
+ }
2256
2473
  });
2257
2474
  const unsubScrollStart = kernel.on("scroll-start", () => {
2258
2475
  setIsScrolling(true);
@@ -2266,22 +2483,18 @@ function useVirtualGrid(options) {
2266
2483
  api.recalculate();
2267
2484
  setColumnCount(api.getColumnCount());
2268
2485
  setColumnWidth(api.getColumnWidth());
2269
- setVirtualItems(api.getVirtualItems());
2486
+ publishItems(api.getVirtualItems());
2270
2487
  }
2271
2488
  });
2272
- const unsubRangeChange = kernel.on("visible-range-change", (event) => {
2273
- const e = event;
2274
- setRange(e.range);
2275
- });
2276
2489
  return () => {
2277
2490
  unsubScroll();
2278
2491
  unsubScrollStart();
2279
2492
  unsubScrollEnd();
2280
2493
  unsubResize();
2281
- unsubRangeChange();
2282
2494
  kernel.destroy();
2283
2495
  };
2284
2496
  }, []);
2497
+ const initialOffsetAppliedRef = useRef(false);
2285
2498
  useEffect(() => {
2286
2499
  const container = containerRef.current;
2287
2500
  if (!container) return;
@@ -2291,23 +2504,28 @@ function useVirtualGrid(options) {
2291
2504
  api.recalculate();
2292
2505
  setColumnCount(api.getColumnCount());
2293
2506
  setColumnWidth(api.getColumnWidth());
2294
- setVirtualItems(api.getVirtualItems());
2295
- }
2296
- if (initialOffset > 0) {
2297
- kernel.scrollTo(initialOffset);
2507
+ publishItems(api.getVirtualItems());
2298
2508
  }
2299
2509
  return () => {
2300
2510
  kernel.detach();
2301
2511
  };
2302
- }, [containerRef, kernel, initialOffset]);
2512
+ }, [containerRef, kernel]);
2303
2513
  useEffect(() => {
2304
2514
  kernel.configure({ itemCount: count });
2305
2515
  const api = gridRendererRef.current;
2306
2516
  if (api) {
2307
2517
  api.recalculate();
2308
- setVirtualItems(api.getVirtualItems());
2518
+ publishItems(api.getVirtualItems());
2309
2519
  }
2310
- }, [count, kernel]);
2520
+ }, [count, kernel, publishItems]);
2521
+ useEffect(() => {
2522
+ kernel.configure({ overscan });
2523
+ const api = gridRendererRef.current;
2524
+ if (api && containerRef.current) {
2525
+ api.recalculate();
2526
+ publishItems(api.getVirtualItems());
2527
+ }
2528
+ }, [overscan, kernel, publishItems]);
2311
2529
  const scrollTo = useCallback(
2312
2530
  (offset, scrollOptions) => {
2313
2531
  kernel.scrollTo(offset, scrollOptions);
@@ -2315,12 +2533,42 @@ function useVirtualGrid(options) {
2315
2533
  [kernel]
2316
2534
  );
2317
2535
  const scrollToIndex = useCallback(
2318
- (index, scrollOptions) => {
2536
+ (index, scrollOptions = {}) => {
2319
2537
  const row = Math.floor(index / columnCount);
2320
2538
  const rowOffset = row * (rowHeight + gapY);
2321
- kernel.scrollTo(rowOffset, scrollOptions);
2539
+ const container = containerRef.current;
2540
+ if (!container) return;
2541
+ const { align = "auto", offset: additionalOffset = 0, ...options2 } = scrollOptions;
2542
+ const viewportHeight = container.clientHeight;
2543
+ const rowEnd = rowOffset + rowHeight;
2544
+ let targetOffset;
2545
+ switch (align) {
2546
+ case "start":
2547
+ targetOffset = rowOffset;
2548
+ break;
2549
+ case "center":
2550
+ targetOffset = rowOffset - viewportHeight / 2 + rowHeight / 2;
2551
+ break;
2552
+ case "end":
2553
+ targetOffset = rowEnd - viewportHeight;
2554
+ break;
2555
+ case "auto":
2556
+ default: {
2557
+ const visibleStart = container.scrollTop;
2558
+ if (rowOffset < visibleStart) {
2559
+ targetOffset = rowOffset;
2560
+ } else if (rowEnd > visibleStart + viewportHeight) {
2561
+ targetOffset = rowEnd - viewportHeight;
2562
+ } else {
2563
+ return;
2564
+ }
2565
+ break;
2566
+ }
2567
+ }
2568
+ const maxScroll = Math.max(0, container.scrollHeight - viewportHeight);
2569
+ kernel.scrollTo(Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll)), options2);
2322
2570
  },
2323
- [kernel, columnCount, rowHeight, gapY]
2571
+ [kernel, containerRef, columnCount, rowHeight, gapY]
2324
2572
  );
2325
2573
  const measureElement = useCallback(
2326
2574
  (_index, _element) => {
@@ -2341,11 +2589,19 @@ function useVirtualGrid(options) {
2341
2589
  const totalSize = useMemo(() => {
2342
2590
  return gridRendererRef.current?.getTotalHeight() ?? 0;
2343
2591
  }, [virtualItems]);
2344
- const rowCount = useMemo(() => {
2345
- return gridRendererRef.current?.getRowCount() ?? 0;
2346
- }, [count, columnCount]);
2592
+ useEffect(() => {
2593
+ if (initialOffset > 0 && totalSize > 0 && !initialOffsetAppliedRef.current && containerRef.current) {
2594
+ initialOffsetAppliedRef.current = true;
2595
+ kernel.scrollTo(initialOffset);
2596
+ }
2597
+ }, [initialOffset, totalSize, kernel, containerRef]);
2598
+ const rowCount = useMemo(() => Math.ceil(count / Math.max(1, columnCount)), [count, columnCount]);
2599
+ const keyedItems = useMemo(
2600
+ () => rekeyItems(virtualItems, count, getItemKey),
2601
+ [virtualItems, count, getItemKey]
2602
+ );
2347
2603
  return {
2348
- virtualItems,
2604
+ virtualItems: keyedItems,
2349
2605
  totalSize,
2350
2606
  scrollOffset,
2351
2607
  isScrolling,
@@ -2356,6 +2612,7 @@ function useVirtualGrid(options) {
2356
2612
  getMeasurement,
2357
2613
  invalidateMeasurement,
2358
2614
  invalidateAllMeasurements,
2615
+ kernel,
2359
2616
  columnCount,
2360
2617
  columnWidth,
2361
2618
  rowCount
@@ -2406,11 +2663,12 @@ function VirtualGridInner(props, ref) {
2406
2663
  range,
2407
2664
  columnCount,
2408
2665
  columnWidth,
2409
- rowCount
2666
+ rowCount,
2667
+ kernel
2410
2668
  } = useVirtualGrid({
2411
2669
  count: data.length,
2412
- columns: typeof columns === "number" ? columns : 1,
2413
- // TODO: handle auto
2670
+ columns,
2671
+ minColumnWidth,
2414
2672
  rowHeight: itemHeight,
2415
2673
  gap: { x: gapX, y: gapY },
2416
2674
  overscan,
@@ -2418,12 +2676,16 @@ function VirtualGridInner(props, ref) {
2418
2676
  getItemKey: getItemKey ? (index) => getItemKey(index, data) : void 0,
2419
2677
  containerRef
2420
2678
  });
2421
- const kernelRef = useRef(createKernel({
2422
- itemCount: data.length,
2423
- estimatedItemHeight: itemHeight,
2424
- overscan,
2425
- direction: "vertical"
2426
- }));
2679
+ useEffect(() => {
2680
+ if (virtualItems.length === 0) return;
2681
+ onVisibleRangeChange?.(range);
2682
+ onItemsRendered?.({
2683
+ overscanStartIndex: range.overscanStartIndex,
2684
+ overscanEndIndex: range.overscanEndIndex,
2685
+ visibleStartIndex: range.startIndex,
2686
+ visibleEndIndex: range.endIndex
2687
+ });
2688
+ }, [range.startIndex, range.endIndex, range.overscanStartIndex, range.overscanEndIndex]);
2427
2689
  useImperativeHandle(ref, () => ({
2428
2690
  scrollTo: (offset, options) => scrollTo(offset, options),
2429
2691
  scrollToIndex: (index, options) => scrollToIndex(index, options),
@@ -2463,10 +2725,10 @@ function VirtualGridInner(props, ref) {
2463
2725
  }), [totalSize, innerStyle]);
2464
2726
  const createRenderProps = useCallback(
2465
2727
  (index, virtualItem) => {
2466
- const item = data[index];
2467
- if (item === void 0) {
2468
- throw new Error(`[Scrollex] Item at index ${index} is undefined`);
2728
+ if (index >= data.length) {
2729
+ throw new Error(`[Scrollex] Item at index ${index} is out of range`);
2469
2730
  }
2731
+ const item = data[index];
2470
2732
  const columnIndex = virtualItem.lane;
2471
2733
  const rowIndex = Math.floor(index / columnCount);
2472
2734
  const left = columnIndex * (columnWidth + gapX);
@@ -2497,9 +2759,11 @@ function VirtualGridInner(props, ref) {
2497
2759
  },
2498
2760
  [data, columnCount, columnWidth, gapX, itemStyle, range, isScrolling]
2499
2761
  );
2762
+ useKernelPlugins(kernel, plugins);
2763
+ useLoadMoreWhenShort(containerRef, { count: data.length, totalSize, hasMore, isLoading, threshold, onLoadMore });
2500
2764
  const contextValue = useMemo(() => ({
2501
- kernel: kernelRef.current
2502
- }), []);
2765
+ kernel
2766
+ }), [kernel]);
2503
2767
  return /* @__PURE__ */ jsx(ScrollexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(
2504
2768
  "div",
2505
2769
  {
@@ -2519,8 +2783,7 @@ function VirtualGridInner(props, ref) {
2519
2783
  children: [
2520
2784
  /* @__PURE__ */ jsx("div", { className: innerClassName, style: innerContainerStyles, children: virtualItems.map((virtualItem) => {
2521
2785
  const index = virtualItem.index;
2522
- const item = data[index];
2523
- if (item === void 0) return null;
2786
+ if (index >= data.length) return null;
2524
2787
  const rowIndex = Math.floor(index / columnCount);
2525
2788
  const columnIndex = virtualItem.lane;
2526
2789
  return /* @__PURE__ */ jsx(
@@ -2546,11 +2809,16 @@ function useVirtualMasonry(options) {
2546
2809
  const {
2547
2810
  count,
2548
2811
  columns,
2812
+ minColumnWidth = 200,
2549
2813
  getItemHeight,
2550
2814
  gap = 0,
2551
2815
  overscan = 5,
2816
+ initialOffset = 0,
2817
+ getItemKey = (index) => index,
2552
2818
  containerRef
2553
2819
  } = options;
2820
+ const gapX = typeof gap === "number" ? gap : gap.x;
2821
+ const gapY = typeof gap === "number" ? gap : gap.y;
2554
2822
  const kernelRef = useRef(
2555
2823
  createKernel({
2556
2824
  itemCount: count,
@@ -2568,42 +2836,57 @@ function useVirtualMasonry(options) {
2568
2836
  overscanStartIndex: 0,
2569
2837
  overscanEndIndex: 0
2570
2838
  });
2839
+ const [columnCount, setColumnCount] = useState(typeof columns === "number" ? normalizeColumnCount(columns) : 1);
2571
2840
  const [columnWidth, setColumnWidth] = useState(0);
2572
2841
  const [columnHeights, setColumnHeights] = useState([]);
2573
2842
  const [totalSize, setTotalSize] = useState(0);
2574
2843
  const layoutCacheRef = useRef(/* @__PURE__ */ new Map());
2844
+ const getItemHeightRef = useRef(getItemHeight);
2845
+ getItemHeightRef.current = getItemHeight;
2846
+ const getItemKeyRef = useRef(getItemKey);
2847
+ getItemKeyRef.current = getItemKey;
2848
+ const initialOffsetAppliedRef = useRef(false);
2575
2849
  const kernel = kernelRef.current;
2576
2850
  const calculateLayout = useCallback((containerWidth) => {
2851
+ kernel.configure({ itemCount: count });
2577
2852
  if (containerWidth === 0 || count === 0) {
2578
2853
  setVirtualItems([]);
2579
2854
  setColumnHeights([]);
2580
2855
  setTotalSize(0);
2581
2856
  return;
2582
2857
  }
2583
- const newColumnWidth = (containerWidth - (columns - 1) * gap) / columns;
2858
+ const columnTotal = columns === "auto" ? autoColumnCount(containerWidth, minColumnWidth, gapX) : normalizeColumnCount(columns);
2859
+ const newColumnWidth = (containerWidth - (columnTotal - 1) * gapX) / columnTotal;
2860
+ setColumnCount(columnTotal);
2584
2861
  setColumnWidth(newColumnWidth);
2585
- const heights = new Array(columns).fill(0);
2862
+ const heights = new Array(columnTotal).fill(0);
2863
+ const itemsInColumn = new Array(columnTotal).fill(0);
2586
2864
  const cache = /* @__PURE__ */ new Map();
2587
2865
  for (let i = 0; i < count; i++) {
2588
2866
  let shortestCol = 0;
2589
- for (let j = 1; j < columns; j++) {
2867
+ for (let j = 1; j < columnTotal; j++) {
2590
2868
  if ((heights[j] ?? 0) < (heights[shortestCol] ?? 0)) {
2591
2869
  shortestCol = j;
2592
2870
  }
2593
2871
  }
2594
- const itemHeight = getItemHeight(i, newColumnWidth);
2872
+ const measured = getItemHeightRef.current(i, newColumnWidth);
2873
+ const itemHeight = Number.isFinite(measured) && measured > 0 ? measured : 0;
2595
2874
  const top = heights[shortestCol] ?? 0;
2596
2875
  cache.set(i, { top, lane: shortestCol, height: itemHeight });
2597
- heights[shortestCol] = top + itemHeight + gap;
2876
+ heights[shortestCol] = top + itemHeight + gapY;
2877
+ itemsInColumn[shortestCol] = (itemsInColumn[shortestCol] ?? 0) + 1;
2598
2878
  }
2599
2879
  layoutCacheRef.current = cache;
2600
- setColumnHeights(heights);
2601
- setTotalSize(Math.max(...heights) - gap);
2602
- }, [count, columns, gap, getItemHeight]);
2880
+ const extents = heights.map((height, column) => (itemsInColumn[column] ?? 0) > 0 ? height - gapY : 0);
2881
+ setColumnHeights(extents);
2882
+ const total = Math.max(...extents);
2883
+ setTotalSize(total);
2884
+ kernel.configure({ estimatedItemHeight: total / count });
2885
+ }, [kernel, count, columns, minColumnWidth, gapX, gapY]);
2603
2886
  const getVisibleItems = useCallback((scrollTop, viewportHeight) => {
2604
2887
  const cache = layoutCacheRef.current;
2605
2888
  const items = [];
2606
- const overscanAmount = overscan * 100;
2889
+ const overscanAmount = normalizeOverscan(overscan) * 100;
2607
2890
  const viewStart = Math.max(0, scrollTop - overscanAmount);
2608
2891
  const viewEnd = scrollTop + viewportHeight + overscanAmount;
2609
2892
  for (let i = 0; i < count; i++) {
@@ -2613,7 +2896,7 @@ function useVirtualMasonry(options) {
2613
2896
  if (itemEnd >= viewStart && layout.top <= viewEnd) {
2614
2897
  items.push({
2615
2898
  index: i,
2616
- key: i,
2899
+ key: getItemKeyRef.current(i),
2617
2900
  start: layout.top,
2618
2901
  end: itemEnd,
2619
2902
  size: layout.height,
@@ -2623,6 +2906,11 @@ function useVirtualMasonry(options) {
2623
2906
  }
2624
2907
  return items;
2625
2908
  }, [count, overscan]);
2909
+ const updateVisibleItems = useCallback((scrollTop, viewportHeight) => {
2910
+ const items = getVisibleItems(scrollTop, viewportHeight);
2911
+ setVirtualItems(items);
2912
+ setRange(getItemsRange(items, scrollTop, viewportHeight));
2913
+ }, [getVisibleItems]);
2626
2914
  useEffect(() => {
2627
2915
  const unsubScrollStart = kernel.on("scroll-start", () => {
2628
2916
  setIsScrolling(true);
@@ -2640,16 +2928,23 @@ function useVirtualMasonry(options) {
2640
2928
  const container = containerRef.current;
2641
2929
  if (!container) return;
2642
2930
  kernel.attach(container);
2643
- calculateLayout(container.clientWidth);
2931
+ return () => {
2932
+ kernel.detach();
2933
+ };
2934
+ }, [containerRef, kernel]);
2935
+ useEffect(() => {
2936
+ const container = containerRef.current;
2937
+ if (!container) return;
2938
+ calculateLayout(getContentWidth(container));
2644
2939
  const handleScroll = () => {
2645
2940
  const scrollTop = container.scrollTop;
2646
2941
  setScrollOffset(scrollTop);
2647
- setVirtualItems(getVisibleItems(scrollTop, container.clientHeight));
2942
+ updateVisibleItems(scrollTop, container.clientHeight);
2648
2943
  };
2649
2944
  const resizeObserver = new ResizeObserver((entries) => {
2650
2945
  for (const entry of entries) {
2651
2946
  calculateLayout(entry.contentRect.width);
2652
- setVirtualItems(getVisibleItems(container.scrollTop, entry.contentRect.height));
2947
+ updateVisibleItems(container.scrollTop, entry.contentRect.height);
2653
2948
  }
2654
2949
  });
2655
2950
  container.addEventListener("scroll", handleScroll, { passive: true });
@@ -2658,15 +2953,20 @@ function useVirtualMasonry(options) {
2658
2953
  return () => {
2659
2954
  container.removeEventListener("scroll", handleScroll);
2660
2955
  resizeObserver.disconnect();
2661
- kernel.detach();
2662
2956
  };
2663
- }, [containerRef, kernel, calculateLayout, getVisibleItems]);
2957
+ }, [containerRef, kernel, calculateLayout, updateVisibleItems]);
2958
+ useEffect(() => {
2959
+ if (initialOffset > 0 && totalSize > 0 && !initialOffsetAppliedRef.current && containerRef.current) {
2960
+ initialOffsetAppliedRef.current = true;
2961
+ kernel.scrollTo(initialOffset);
2962
+ }
2963
+ }, [initialOffset, totalSize, kernel, containerRef]);
2664
2964
  useEffect(() => {
2665
2965
  const container = containerRef.current;
2666
2966
  if (!container) return;
2667
- calculateLayout(container.clientWidth);
2668
- setVirtualItems(getVisibleItems(container.scrollTop, container.clientHeight));
2669
- }, [count, containerRef, calculateLayout, getVisibleItems]);
2967
+ calculateLayout(getContentWidth(container));
2968
+ updateVisibleItems(container.scrollTop, container.clientHeight);
2969
+ }, [count, containerRef, calculateLayout, updateVisibleItems]);
2670
2970
  const scrollTo = useCallback(
2671
2971
  (offset, scrollOptions) => {
2672
2972
  kernel.scrollTo(offset, scrollOptions);
@@ -2674,13 +2974,41 @@ function useVirtualMasonry(options) {
2674
2974
  [kernel]
2675
2975
  );
2676
2976
  const scrollToIndex = useCallback(
2677
- (index, _scrollOptions) => {
2977
+ (index, scrollOptions = {}) => {
2678
2978
  const layout = layoutCacheRef.current.get(index);
2679
- if (layout) {
2680
- kernel.scrollTo(layout.top);
2979
+ const container = containerRef.current;
2980
+ if (!layout || !container) return;
2981
+ const { align = "auto", offset: additionalOffset = 0, ...options2 } = scrollOptions;
2982
+ const viewportHeight = container.clientHeight;
2983
+ const itemEnd = layout.top + layout.height;
2984
+ let targetOffset;
2985
+ switch (align) {
2986
+ case "start":
2987
+ targetOffset = layout.top;
2988
+ break;
2989
+ case "center":
2990
+ targetOffset = layout.top - viewportHeight / 2 + layout.height / 2;
2991
+ break;
2992
+ case "end":
2993
+ targetOffset = itemEnd - viewportHeight;
2994
+ break;
2995
+ case "auto":
2996
+ default: {
2997
+ const visibleStart = container.scrollTop;
2998
+ if (layout.top < visibleStart) {
2999
+ targetOffset = layout.top;
3000
+ } else if (itemEnd > visibleStart + viewportHeight) {
3001
+ targetOffset = itemEnd - viewportHeight;
3002
+ } else {
3003
+ return;
3004
+ }
3005
+ break;
3006
+ }
2681
3007
  }
3008
+ const maxScroll = Math.max(0, container.scrollHeight - viewportHeight);
3009
+ kernel.scrollTo(Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll)), options2);
2682
3010
  },
2683
- [kernel]
3011
+ [kernel, containerRef]
2684
3012
  );
2685
3013
  const measureElement = useCallback(
2686
3014
  (_index, _element) => {
@@ -2696,17 +3024,23 @@ function useVirtualMasonry(options) {
2696
3024
  const invalidateMeasurement = useCallback((_index) => {
2697
3025
  const container = containerRef.current;
2698
3026
  if (container) {
2699
- calculateLayout(container.clientWidth);
3027
+ calculateLayout(getContentWidth(container));
3028
+ updateVisibleItems(container.scrollTop, container.clientHeight);
2700
3029
  }
2701
- }, [containerRef, calculateLayout]);
3030
+ }, [containerRef, calculateLayout, updateVisibleItems]);
2702
3031
  const invalidateAllMeasurements = useCallback(() => {
2703
3032
  const container = containerRef.current;
2704
3033
  if (container) {
2705
- calculateLayout(container.clientWidth);
3034
+ calculateLayout(getContentWidth(container));
3035
+ updateVisibleItems(container.scrollTop, container.clientHeight);
2706
3036
  }
2707
- }, [containerRef, calculateLayout]);
3037
+ }, [containerRef, calculateLayout, updateVisibleItems]);
3038
+ const currentItems = useMemo(
3039
+ () => virtualItems.some((item) => item.index >= count) ? virtualItems.filter((item) => item.index < count) : virtualItems,
3040
+ [virtualItems, count]
3041
+ );
2708
3042
  return {
2709
- virtualItems,
3043
+ virtualItems: currentItems,
2710
3044
  totalSize,
2711
3045
  scrollOffset,
2712
3046
  isScrolling,
@@ -2717,7 +3051,8 @@ function useVirtualMasonry(options) {
2717
3051
  getMeasurement,
2718
3052
  invalidateMeasurement,
2719
3053
  invalidateAllMeasurements,
2720
- columnCount: columns,
3054
+ kernel,
3055
+ columnCount,
2721
3056
  columnWidth,
2722
3057
  columnHeights
2723
3058
  };
@@ -2763,29 +3098,40 @@ function VirtualMasonryInner(props, ref) {
2763
3098
  scrollTo,
2764
3099
  scrollToIndex,
2765
3100
  isScrolling,
3101
+ scrollOffset,
2766
3102
  range,
2767
3103
  columnCount,
2768
3104
  columnWidth,
2769
- columnHeights
3105
+ columnHeights,
3106
+ invalidateAllMeasurements,
3107
+ kernel
2770
3108
  } = useVirtualMasonry({
2771
3109
  count: data.length,
2772
- columns: typeof columns === "number" ? columns : 3,
2773
- // TODO: handle auto
3110
+ columns,
3111
+ minColumnWidth,
2774
3112
  getItemHeight: (index, colWidth) => {
2775
- const item = data[index];
2776
- if (item === void 0) return 100;
2777
- return getItemHeight(item, colWidth);
3113
+ if (index >= data.length) return 100;
3114
+ return getItemHeight(data[index], colWidth);
2778
3115
  },
2779
- gap: gapValue,
3116
+ gap,
2780
3117
  overscan,
3118
+ initialOffset: initialScrollOffset,
3119
+ getItemKey: getItemKey ? (index) => getItemKey(index, data) : void 0,
2781
3120
  containerRef
2782
3121
  });
2783
- const kernelRef = useRef(createKernel({
2784
- itemCount: data.length,
2785
- estimatedItemHeight: 200,
2786
- overscan,
2787
- direction: "vertical"
2788
- }));
3122
+ useEffect(() => {
3123
+ invalidateAllMeasurements();
3124
+ }, [data, invalidateAllMeasurements]);
3125
+ useEffect(() => {
3126
+ if (virtualItems.length === 0) return;
3127
+ onVisibleRangeChange?.(range);
3128
+ onItemsRendered?.({
3129
+ overscanStartIndex: range.overscanStartIndex,
3130
+ overscanEndIndex: range.overscanEndIndex,
3131
+ visibleStartIndex: range.startIndex,
3132
+ visibleEndIndex: range.endIndex
3133
+ });
3134
+ }, [range.startIndex, range.endIndex, range.overscanStartIndex, range.overscanEndIndex]);
2789
3135
  useImperativeHandle(ref, () => ({
2790
3136
  scrollTo: (offset, options) => scrollTo(offset, options),
2791
3137
  scrollToIndex: (index, options) => scrollToIndex(index, options),
@@ -2825,12 +3171,13 @@ function VirtualMasonryInner(props, ref) {
2825
3171
  }), [totalSize, innerStyle]);
2826
3172
  const createRenderProps = useCallback(
2827
3173
  (index, virtualItem) => {
2828
- const item = data[index];
2829
- if (item === void 0) {
2830
- throw new Error(`[Scrollex] Item at index ${index} is undefined`);
3174
+ if (index >= data.length) {
3175
+ throw new Error(`[Scrollex] Item at index ${index} is out of range`);
2831
3176
  }
3177
+ const item = data[index];
2832
3178
  const columnIndex = virtualItem.lane;
2833
3179
  const left = columnIndex * (columnWidth + gapValue);
3180
+ const viewportHeight = kernel.getViewport().height;
2834
3181
  const itemStyles = {
2835
3182
  position: "absolute",
2836
3183
  top: 0,
@@ -2849,8 +3196,7 @@ function VirtualMasonryInner(props, ref) {
2849
3196
  measureRef: () => {
2850
3197
  },
2851
3198
  // Masonry uses calculated heights
2852
- isVisible: true,
2853
- // All virtual items are considered visible
3199
+ isVisible: virtualItem.end > scrollOffset && virtualItem.start < scrollOffset + viewportHeight,
2854
3200
  isScrolling,
2855
3201
  columnIndex,
2856
3202
  rowIndex: 0,
@@ -2859,11 +3205,13 @@ function VirtualMasonryInner(props, ref) {
2859
3205
  width: columnWidth
2860
3206
  };
2861
3207
  },
2862
- [data, columnWidth, gapValue, itemStyle, isScrolling]
3208
+ [data, columnWidth, gapValue, itemStyle, isScrolling, scrollOffset, kernel]
2863
3209
  );
3210
+ useKernelPlugins(kernel, plugins);
3211
+ useLoadMoreWhenShort(containerRef, { count: data.length, totalSize, hasMore, isLoading, threshold, onLoadMore });
2864
3212
  const contextValue = useMemo(() => ({
2865
- kernel: kernelRef.current
2866
- }), []);
3213
+ kernel
3214
+ }), [kernel]);
2867
3215
  return /* @__PURE__ */ jsx(ScrollexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(
2868
3216
  "div",
2869
3217
  {
@@ -2882,8 +3230,7 @@ function VirtualMasonryInner(props, ref) {
2882
3230
  children: [
2883
3231
  /* @__PURE__ */ jsx("div", { className: innerClassName, style: innerContainerStyles, children: virtualItems.map((virtualItem) => {
2884
3232
  const index = virtualItem.index;
2885
- const item = data[index];
2886
- if (item === void 0) return null;
3233
+ if (index >= data.length) return null;
2887
3234
  return /* @__PURE__ */ jsx(
2888
3235
  "div",
2889
3236
  {
@@ -2902,38 +3249,52 @@ function VirtualMasonryInner(props, ref) {
2902
3249
  ) });
2903
3250
  }
2904
3251
  var VirtualMasonry = forwardRef(VirtualMasonryInner);
3252
+ function boxOf(entry) {
3253
+ const borderBox = entry.borderBoxSize?.[0];
3254
+ if (borderBox && (borderBox.inlineSize > 0 || borderBox.blockSize > 0)) {
3255
+ return { width: borderBox.inlineSize, height: borderBox.blockSize };
3256
+ }
3257
+ return { width: entry.contentRect.width, height: entry.contentRect.height };
3258
+ }
2905
3259
  function useMeasure(options = {}) {
2906
3260
  const { onResize, debounce: debounce2 = 0 } = options;
2907
3261
  const elementRef = useRef(null);
2908
3262
  const observerRef = useRef(null);
2909
- const dimensionsRef = useRef({ width: 0, height: 0 });
3263
+ const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
2910
3264
  const debounceTimerRef = useRef(null);
3265
+ const onResizeRef = useRef(onResize);
3266
+ onResizeRef.current = onResize;
2911
3267
  const handleResize = useCallback(
2912
3268
  (width, height) => {
2913
- dimensionsRef.current = { width, height };
2914
- if (onResize) {
3269
+ setDimensions(
3270
+ (previous) => previous.width === width && previous.height === height ? previous : { width, height }
3271
+ );
3272
+ const onResize2 = onResizeRef.current;
3273
+ if (onResize2) {
2915
3274
  if (debounce2 > 0) {
2916
3275
  if (debounceTimerRef.current) {
2917
3276
  clearTimeout(debounceTimerRef.current);
2918
3277
  }
2919
3278
  debounceTimerRef.current = setTimeout(() => {
2920
- onResize(width, height);
3279
+ onResize2(width, height);
2921
3280
  }, debounce2);
2922
3281
  } else {
2923
- onResize(width, height);
3282
+ onResize2(width, height);
2924
3283
  }
2925
3284
  }
2926
3285
  },
2927
- [onResize, debounce2]
3286
+ [debounce2]
2928
3287
  );
2929
3288
  useEffect(() => {
2930
3289
  observerRef.current = new ResizeObserver((entries) => {
2931
3290
  for (const entry of entries) {
2932
- const { width, height } = entry.contentRect;
3291
+ const { width, height } = boxOf(entry);
2933
3292
  handleResize(width, height);
2934
3293
  }
2935
3294
  });
2936
3295
  if (elementRef.current) {
3296
+ const rect = elementRef.current.getBoundingClientRect();
3297
+ handleResize(rect.width, rect.height);
2937
3298
  observerRef.current.observe(elementRef.current);
2938
3299
  }
2939
3300
  return () => {
@@ -2956,12 +3317,13 @@ function useMeasure(options = {}) {
2956
3317
  }, [handleResize]);
2957
3318
  return {
2958
3319
  measureRef,
2959
- width: dimensionsRef.current.width,
2960
- height: dimensionsRef.current.height
3320
+ width: dimensions.width,
3321
+ height: dimensions.height
2961
3322
  };
2962
3323
  }
2963
3324
  function useMeasureMany() {
2964
3325
  const elementsRef = useRef(/* @__PURE__ */ new Map());
3326
+ const keysRef = useRef(/* @__PURE__ */ new WeakMap());
2965
3327
  const observerRef = useRef(null);
2966
3328
  const measurementsRef = useRef(/* @__PURE__ */ new Map());
2967
3329
  const callbackRef = useRef(null);
@@ -2969,14 +3331,17 @@ function useMeasureMany() {
2969
3331
  observerRef.current = new ResizeObserver((entries) => {
2970
3332
  for (const entry of entries) {
2971
3333
  const element = entry.target;
2972
- const key = element.dataset["measureKey"];
3334
+ const key = element.dataset["measureKey"] !== void 0 ? keysRef.current.get(element) : void 0;
2973
3335
  if (key !== void 0) {
2974
- const { width, height } = entry.contentRect;
3336
+ const { width, height } = boxOf(entry);
2975
3337
  measurementsRef.current.set(key, { width, height });
2976
3338
  callbackRef.current?.(key, width, height);
2977
3339
  }
2978
3340
  }
2979
3341
  });
3342
+ for (const element of elementsRef.current.values()) {
3343
+ observerRef.current.observe(element);
3344
+ }
2980
3345
  return () => {
2981
3346
  observerRef.current?.disconnect();
2982
3347
  };
@@ -2989,9 +3354,11 @@ function useMeasureMany() {
2989
3354
  if (oldElement && oldElement !== element) {
2990
3355
  observer?.unobserve(oldElement);
2991
3356
  elements.delete(key);
3357
+ keysRef.current.delete(oldElement);
2992
3358
  }
2993
3359
  if (element) {
2994
3360
  element.dataset["measureKey"] = String(key);
3361
+ keysRef.current.set(element, key);
2995
3362
  elements.set(key, element);
2996
3363
  observer?.observe(element);
2997
3364
  const rect = element.getBoundingClientRect();
@@ -3070,7 +3437,7 @@ function debounce(fn, wait) {
3070
3437
  // src/plugins/core/auto-measurer.ts
3071
3438
  function autoMeasurerPlugin(options = {}) {
3072
3439
  const {
3073
- estimatedItemHeight = 50,
3440
+ estimatedItemHeight,
3074
3441
  measureOnResize = true,
3075
3442
  debounceMs = 100
3076
3443
  } = options;
@@ -3080,6 +3447,9 @@ function autoMeasurerPlugin(options = {}) {
3080
3447
  const elementsByIndex = /* @__PURE__ */ new Map();
3081
3448
  let measureQueue = /* @__PURE__ */ new Set();
3082
3449
  let flushScheduled = false;
3450
+ function sizeAlongAxis(rect) {
3451
+ return kernel?.getOptions().direction === "horizontal" ? rect.width : rect.height;
3452
+ }
3083
3453
  const debouncedFlush = debounce(() => {
3084
3454
  flush();
3085
3455
  }, debounceMs);
@@ -3097,7 +3467,7 @@ function autoMeasurerPlugin(options = {}) {
3097
3467
  const element = ref?.deref();
3098
3468
  if (element) {
3099
3469
  const rect = element.getBoundingClientRect();
3100
- measurements.push({ index, height: rect.height });
3470
+ measurements.push({ index, height: sizeAlongAxis(rect) });
3101
3471
  }
3102
3472
  }
3103
3473
  for (const { index, height } of measurements) {
@@ -3128,7 +3498,7 @@ function autoMeasurerPlugin(options = {}) {
3128
3498
  const api = {
3129
3499
  measureElement(index, element) {
3130
3500
  const rect = element.getBoundingClientRect();
3131
- const height = rect.height;
3501
+ const height = sizeAlongAxis(rect);
3132
3502
  if (height > 0 && kernel) {
3133
3503
  kernel.measureItem(index, height);
3134
3504
  }
@@ -3156,24 +3526,27 @@ function autoMeasurerPlugin(options = {}) {
3156
3526
  return cache;
3157
3527
  },
3158
3528
  observe(index, element) {
3159
- if (!resizeObserver) return;
3160
3529
  const existingRef = elementsByIndex.get(index);
3161
3530
  const existingElement = existingRef?.deref();
3162
3531
  if (existingElement && existingElement !== element) {
3163
- resizeObserver.unobserve(existingElement);
3532
+ resizeObserver?.unobserve(existingElement);
3164
3533
  observedElements.delete(existingElement);
3165
3534
  }
3535
+ const previousIndex = observedElements.get(element);
3536
+ if (previousIndex !== void 0 && previousIndex !== index) {
3537
+ elementsByIndex.delete(previousIndex);
3538
+ measureQueue.delete(previousIndex);
3539
+ }
3166
3540
  observedElements.set(element, index);
3167
- elementsByIndex.set(index, new WeakRef(element));
3168
- resizeObserver.observe(element);
3541
+ elementsByIndex.set(index, typeof WeakRef === "function" ? new WeakRef(element) : { deref: () => element });
3542
+ resizeObserver?.observe(element);
3169
3543
  measureQueue.add(index);
3170
3544
  scheduleFlush();
3171
3545
  },
3172
3546
  unobserve(element) {
3173
- if (!resizeObserver) return;
3174
3547
  const index = observedElements.get(element);
3175
3548
  if (index !== void 0) {
3176
- resizeObserver.unobserve(element);
3549
+ resizeObserver?.unobserve(element);
3177
3550
  observedElements.delete(element);
3178
3551
  elementsByIndex.delete(index);
3179
3552
  measureQueue.delete(index);
@@ -3186,7 +3559,9 @@ function autoMeasurerPlugin(options = {}) {
3186
3559
  type: "core",
3187
3560
  install(k) {
3188
3561
  kernel = k;
3189
- kernel.configure({ estimatedItemHeight });
3562
+ if (estimatedItemHeight !== void 0) {
3563
+ kernel.configure({ estimatedItemHeight });
3564
+ }
3190
3565
  if (measureOnResize && typeof ResizeObserver !== "undefined") {
3191
3566
  resizeObserver = new ResizeObserver(handleResize);
3192
3567
  }
@@ -3207,6 +3582,10 @@ function autoMeasurerPlugin(options = {}) {
3207
3582
  }
3208
3583
 
3209
3584
  // src/plugins/core/infinite-loader.ts
3585
+ function initialLoaderState(direction) {
3586
+ return { loading: false, loadGeneration: 0, hasMoreForward: true, hasMoreBackward: direction === "backward" || direction === "both" };
3587
+ }
3588
+ var sharedLoaderStates = /* @__PURE__ */ new WeakMap();
3210
3589
  function infiniteLoaderPlugin(options) {
3211
3590
  const {
3212
3591
  threshold = 200,
@@ -3215,44 +3594,61 @@ function infiniteLoaderPlugin(options) {
3215
3594
  onLoadMore
3216
3595
  } = options;
3217
3596
  let kernel = null;
3218
- let loading = false;
3219
- let hasMoreForward = true;
3220
- let hasMoreBackward = direction === "backward" || direction === "both";
3597
+ let state = initialLoaderState(direction);
3221
3598
  let lastCheckTime = 0;
3222
3599
  const checkDebounceMs = 100;
3600
+ let pendingEvent = null;
3601
+ let trailingTimer = null;
3223
3602
  function checkLoadMore(event) {
3224
- if (loading || !kernel) return;
3603
+ if (state.loading || !kernel) return;
3225
3604
  const now = performance.now();
3226
- if (now - lastCheckTime < checkDebounceMs) return;
3227
- lastCheckTime = now;
3605
+ if (now - lastCheckTime < checkDebounceMs) {
3606
+ pendingEvent = event;
3607
+ if (trailingTimer === null) {
3608
+ trailingTimer = setTimeout(() => {
3609
+ trailingTimer = null;
3610
+ const latest = pendingEvent;
3611
+ pendingEvent = null;
3612
+ if (latest) runCheck(latest);
3613
+ }, Math.max(0, checkDebounceMs - (now - lastCheckTime)));
3614
+ }
3615
+ return;
3616
+ }
3617
+ runCheck(event);
3618
+ }
3619
+ function runCheck(event) {
3620
+ if (state.loading || !kernel) return;
3621
+ lastCheckTime = performance.now();
3228
3622
  const viewport = kernel.getViewport();
3229
3623
  const totalSize = kernel.getTotalSize();
3230
- const { scrollTop } = event;
3231
- if ((direction === "forward" || direction === "both") && hasMoreForward) {
3232
- const distanceFromBottom = totalSize - scrollTop - viewport.height;
3624
+ const horizontal = kernel.getOptions().direction === "horizontal";
3625
+ const scrollTop = horizontal ? event.scrollLeft : event.scrollTop;
3626
+ const viewportSize = horizontal ? viewport.width : viewport.height;
3627
+ if ((direction === "forward" || direction === "both") && state.hasMoreForward) {
3628
+ const distanceFromBottom = totalSize - scrollTop - viewportSize;
3233
3629
  if (distanceFromBottom < threshold) {
3234
3630
  triggerLoad("forward");
3235
3631
  return;
3236
3632
  }
3237
3633
  }
3238
- if ((direction === "backward" || direction === "both") && hasMoreBackward) {
3634
+ if ((direction === "backward" || direction === "both") && state.hasMoreBackward) {
3239
3635
  if (scrollTop < threshold) {
3240
3636
  triggerLoad("backward");
3241
3637
  return;
3242
3638
  }
3243
3639
  }
3244
3640
  }
3245
- function checkLoadMoreByRange(range) {
3246
- if (loading || !kernel) return;
3641
+ function checkLoadMoreByRange(range, forwardOnly = false) {
3642
+ if (state.loading || !kernel) return;
3247
3643
  const itemCount = kernel.getItemCount();
3248
- if ((direction === "forward" || direction === "both") && hasMoreForward) {
3644
+ if ((direction === "forward" || direction === "both") && state.hasMoreForward) {
3249
3645
  const itemsFromEnd = itemCount - 1 - range.endIndex;
3250
3646
  if (itemsFromEnd <= thresholdItems) {
3251
3647
  triggerLoad("forward");
3252
3648
  return;
3253
3649
  }
3254
3650
  }
3255
- if ((direction === "backward" || direction === "both") && hasMoreBackward) {
3651
+ if (!forwardOnly && (direction === "backward" || direction === "both") && state.hasMoreBackward) {
3256
3652
  if (range.startIndex <= thresholdItems) {
3257
3653
  triggerLoad("backward");
3258
3654
  return;
@@ -3260,10 +3656,11 @@ function infiniteLoaderPlugin(options) {
3260
3656
  }
3261
3657
  }
3262
3658
  async function triggerLoad(loadDirection) {
3263
- if (loading || !kernel) return;
3264
- if (loadDirection === "forward" && !hasMoreForward) return;
3265
- if (loadDirection === "backward" && !hasMoreBackward) return;
3266
- loading = true;
3659
+ if (state.loading || !kernel) return;
3660
+ if (loadDirection === "forward" && !state.hasMoreForward) return;
3661
+ if (loadDirection === "backward" && !state.hasMoreBackward) return;
3662
+ state.loading = true;
3663
+ const generation = ++state.loadGeneration;
3267
3664
  kernel.emit({
3268
3665
  type: "load-more",
3269
3666
  direction: loadDirection
@@ -3273,39 +3670,47 @@ function infiniteLoaderPlugin(options) {
3273
3670
  } catch (error) {
3274
3671
  console.error("[Scrollex] Error in onLoadMore:", error);
3275
3672
  } finally {
3276
- loading = false;
3673
+ if (generation === state.loadGeneration) {
3674
+ state.loading = false;
3675
+ }
3277
3676
  }
3278
3677
  }
3279
3678
  const api = {
3280
3679
  isLoading() {
3281
- return loading;
3680
+ return state.loading;
3282
3681
  },
3283
3682
  setLoading(l) {
3284
- loading = l;
3683
+ state.loading = l;
3285
3684
  },
3286
3685
  hasMore() {
3287
- return hasMoreForward || hasMoreBackward;
3686
+ return state.hasMoreForward || state.hasMoreBackward;
3288
3687
  },
3289
3688
  setHasMore(hasMore) {
3290
- hasMoreForward = hasMore;
3291
- hasMoreBackward = hasMore;
3689
+ state.hasMoreForward = hasMore;
3690
+ state.hasMoreBackward = hasMore;
3292
3691
  },
3293
3692
  hasMoreForward() {
3294
- return hasMoreForward;
3693
+ return state.hasMoreForward;
3295
3694
  },
3296
3695
  setHasMoreForward(hasMore) {
3297
- hasMoreForward = hasMore;
3696
+ state.hasMoreForward = hasMore;
3298
3697
  },
3299
3698
  hasMoreBackward() {
3300
- return hasMoreBackward;
3699
+ return state.hasMoreBackward;
3301
3700
  },
3302
3701
  setHasMoreBackward(hasMore) {
3303
- hasMoreBackward = hasMore;
3702
+ state.hasMoreBackward = hasMore;
3304
3703
  },
3305
3704
  reset() {
3306
- loading = false;
3307
- hasMoreForward = true;
3308
- hasMoreBackward = direction === "backward" || direction === "both";
3705
+ state.loadGeneration++;
3706
+ state.loading = false;
3707
+ state.hasMoreForward = true;
3708
+ state.hasMoreBackward = direction === "backward" || direction === "both";
3709
+ if (trailingTimer !== null) {
3710
+ clearTimeout(trailingTimer);
3711
+ trailingTimer = null;
3712
+ }
3713
+ pendingEvent = null;
3309
3714
  },
3310
3715
  triggerLoad(loadDirection) {
3311
3716
  triggerLoad(loadDirection);
@@ -3317,10 +3722,21 @@ function infiniteLoaderPlugin(options) {
3317
3722
  type: "core",
3318
3723
  install(k) {
3319
3724
  kernel = k;
3725
+ const shared = sharedLoaderStates.get(k);
3726
+ if (shared) {
3727
+ state = shared;
3728
+ } else {
3729
+ sharedLoaderStates.set(k, state);
3730
+ checkLoadMoreByRange(k.getVisibleRange(), true);
3731
+ }
3320
3732
  },
3321
3733
  uninstall() {
3734
+ if (trailingTimer !== null) {
3735
+ clearTimeout(trailingTimer);
3736
+ trailingTimer = null;
3737
+ }
3738
+ pendingEvent = null;
3322
3739
  kernel = null;
3323
- loading = false;
3324
3740
  },
3325
3741
  hooks: {
3326
3742
  onScroll: checkLoadMore,
@@ -3341,14 +3757,30 @@ function scrollControllerPlugin(options = {}) {
3341
3757
  let kernel = null;
3342
3758
  let animationId = null;
3343
3759
  let animating = false;
3760
+ let animationGeneration = 0;
3761
+ function isHorizontal(k) {
3762
+ return k.getOptions().direction === "horizontal";
3763
+ }
3764
+ function getOffset(k) {
3765
+ const position = k.getScrollPosition();
3766
+ return isHorizontal(k) ? position.scrollLeft : position.scrollTop;
3767
+ }
3768
+ function setOffset(k, offset) {
3769
+ k.setScrollPosition(isHorizontal(k) ? { scrollLeft: offset } : { scrollTop: offset });
3770
+ }
3771
+ function getViewportSize(k) {
3772
+ const viewport = k.getViewport();
3773
+ return isHorizontal(k) ? viewport.width : viewport.height;
3774
+ }
3344
3775
  function animateScroll(targetOffset, duration, easing) {
3345
3776
  if (!kernel) return;
3346
3777
  stopAnimation();
3778
+ const generation = animationGeneration;
3347
3779
  const startTime = performance.now();
3348
- const startOffset = kernel.getScrollPosition().scrollTop;
3780
+ const startOffset = getOffset(kernel);
3349
3781
  const distance = targetOffset - startOffset;
3350
- if (distance === 0 || duration === 0) {
3351
- kernel.setScrollPosition({ scrollTop: targetOffset, scrollLeft: 0 });
3782
+ if (distance === 0 || !(duration > 0)) {
3783
+ setOffset(kernel, targetOffset);
3352
3784
  return;
3353
3785
  }
3354
3786
  animating = true;
@@ -3357,11 +3789,13 @@ function scrollControllerPlugin(options = {}) {
3357
3789
  animating = false;
3358
3790
  return;
3359
3791
  }
3792
+ if (generation !== animationGeneration) return;
3360
3793
  const elapsed = currentTime - startTime;
3361
- const progress = Math.min(elapsed / duration, 1);
3794
+ const progress = Math.max(0, Math.min(elapsed / duration, 1));
3362
3795
  const easedProgress = easing(progress);
3363
3796
  const currentOffset = startOffset + distance * easedProgress;
3364
- kernel.setScrollPosition({ scrollTop: currentOffset, scrollLeft: 0 });
3797
+ setOffset(kernel, currentOffset);
3798
+ if (generation !== animationGeneration) return;
3365
3799
  if (progress < 1) {
3366
3800
  animationId = raf(animate);
3367
3801
  } else {
@@ -3372,6 +3806,7 @@ function scrollControllerPlugin(options = {}) {
3372
3806
  animationId = raf(animate);
3373
3807
  }
3374
3808
  function stopAnimation() {
3809
+ animationGeneration++;
3375
3810
  if (animationId !== null) {
3376
3811
  cancelRaf(animationId);
3377
3812
  animationId = null;
@@ -3388,7 +3823,7 @@ function scrollControllerPlugin(options = {}) {
3388
3823
  } = options2;
3389
3824
  if (behavior === "auto") {
3390
3825
  stopAnimation();
3391
- kernel.setScrollPosition({ scrollTop: offset, scrollLeft: 0 });
3826
+ setOffset(kernel, offset);
3392
3827
  } else {
3393
3828
  animateScroll(offset, duration, easing);
3394
3829
  }
@@ -3402,35 +3837,34 @@ function scrollControllerPlugin(options = {}) {
3402
3837
  } = options2;
3403
3838
  const itemOffset = kernel.getItemOffset(index);
3404
3839
  const itemSize = kernel.getCachedHeight(index) ?? kernel.getEstimatedHeight();
3405
- const viewport = kernel.getViewport();
3840
+ const viewportSize = getViewportSize(kernel);
3406
3841
  let targetOffset;
3407
3842
  switch (align) {
3408
3843
  case "start":
3409
3844
  targetOffset = itemOffset;
3410
3845
  break;
3411
3846
  case "center":
3412
- targetOffset = itemOffset - viewport.height / 2 + itemSize / 2;
3847
+ targetOffset = itemOffset - viewportSize / 2 + itemSize / 2;
3413
3848
  break;
3414
3849
  case "end":
3415
- targetOffset = itemOffset - viewport.height + itemSize;
3850
+ targetOffset = itemOffset - viewportSize + itemSize;
3416
3851
  break;
3417
3852
  case "auto":
3418
3853
  default: {
3419
- const scrollPosition = kernel.getScrollPosition();
3420
- const visibleStart = scrollPosition.scrollTop;
3421
- const visibleEnd = visibleStart + viewport.height;
3854
+ const visibleStart = getOffset(kernel);
3855
+ const visibleEnd = visibleStart + viewportSize;
3422
3856
  const itemEnd = itemOffset + itemSize;
3423
3857
  if (itemOffset < visibleStart) {
3424
3858
  targetOffset = itemOffset;
3425
3859
  } else if (itemEnd > visibleEnd) {
3426
- targetOffset = itemEnd - viewport.height;
3860
+ targetOffset = itemEnd - viewportSize;
3427
3861
  } else {
3428
3862
  return;
3429
3863
  }
3430
3864
  break;
3431
3865
  }
3432
3866
  }
3433
- const maxScroll = Math.max(0, kernel.getTotalSize() - viewport.height);
3867
+ const maxScroll = Math.max(0, kernel.getTotalSize() - viewportSize);
3434
3868
  targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
3435
3869
  api.scrollTo(targetOffset, scrollOptions);
3436
3870
  },
@@ -3439,9 +3873,8 @@ function scrollControllerPlugin(options = {}) {
3439
3873
  },
3440
3874
  scrollToBottom(options2 = {}) {
3441
3875
  if (!kernel) return;
3442
- const viewport = kernel.getViewport();
3443
3876
  const totalSize = kernel.getTotalSize();
3444
- const maxScroll = Math.max(0, totalSize - viewport.height);
3877
+ const maxScroll = Math.max(0, totalSize - getViewportSize(kernel));
3445
3878
  api.scrollTo(maxScroll, options2);
3446
3879
  },
3447
3880
  getScrollPosition() {