@oxog/scrollex 1.0.0 → 1.1.0

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