@oxog/scrollex 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ var chunkND5PV5MU_cjs = require('./chunk-ND5PV5MU.cjs');
3
4
  var react = require('react');
4
5
  var jsxRuntime = require('react/jsx-runtime');
5
6
 
6
- // src/react/components/virtual-list.tsx
7
-
8
7
  // src/kernel/event-bus.ts
9
8
  var EventBus = class {
10
9
  constructor() {
@@ -150,6 +149,7 @@ var EventBus = class {
150
149
  * Remove all handlers.
151
150
  */
152
151
  clear() {
152
+ for (const handlers of this.handlers.values()) handlers.clear();
153
153
  this.handlers.clear();
154
154
  this.onceHandlers.clear();
155
155
  this.pendingEvents = [];
@@ -161,6 +161,7 @@ var EventBus = class {
161
161
  * @param eventType - Type of event to clear handlers for
162
162
  */
163
163
  clearEvent(eventType) {
164
+ this.handlers.get(eventType)?.clear();
164
165
  this.handlers.delete(eventType);
165
166
  this.onceHandlers.delete(eventType);
166
167
  }
@@ -219,21 +220,6 @@ function getScrollDirection(current, previous) {
219
220
  return "none";
220
221
  }
221
222
 
222
- // src/utils/raf.ts
223
- function raf(callback) {
224
- if (typeof requestAnimationFrame !== "undefined") {
225
- return requestAnimationFrame(callback);
226
- }
227
- return setTimeout(() => callback(performance.now()), 16);
228
- }
229
- function cancelRaf(id) {
230
- if (typeof cancelAnimationFrame !== "undefined") {
231
- cancelAnimationFrame(id);
232
- } else {
233
- clearTimeout(id);
234
- }
235
- }
236
-
237
223
  // src/kernel/scroll-engine.ts
238
224
  var easings = {
239
225
  linear: (t) => t,
@@ -313,7 +299,7 @@ var ScrollEngine = class {
313
299
  this.scrollEndTimer = null;
314
300
  }
315
301
  if (this.animationId) {
316
- cancelRaf(this.animationId);
302
+ chunkND5PV5MU_cjs.cancelRaf(this.animationId);
317
303
  this.animationId = null;
318
304
  }
319
305
  this.boundHandleScroll = null;
@@ -384,7 +370,7 @@ var ScrollEngine = class {
384
370
  setScrollPosition(position) {
385
371
  if (!this.container) return;
386
372
  if (this.animationId) {
387
- cancelRaf(this.animationId);
373
+ chunkND5PV5MU_cjs.cancelRaf(this.animationId);
388
374
  this.animationId = null;
389
375
  }
390
376
  setScrollPosition(this.container, position);
@@ -416,7 +402,7 @@ var ScrollEngine = class {
416
402
  */
417
403
  animateScroll(targetOffset, duration, easing) {
418
404
  if (this.animationId) {
419
- cancelRaf(this.animationId);
405
+ chunkND5PV5MU_cjs.cancelRaf(this.animationId);
420
406
  }
421
407
  this.animationStartTime = performance.now();
422
408
  this.animationStartOffset = this.horizontal ? this.scrollPosition.scrollLeft : this.scrollPosition.scrollTop;
@@ -430,12 +416,12 @@ var ScrollEngine = class {
430
416
  const currentOffset = this.animationStartOffset + (this.animationTargetOffset - this.animationStartOffset) * easedProgress;
431
417
  this.setScrollPosition(this.horizontal ? { scrollLeft: currentOffset } : { scrollTop: currentOffset });
432
418
  if (progress < 1) {
433
- this.animationId = raf(animate);
419
+ this.animationId = chunkND5PV5MU_cjs.raf(animate);
434
420
  } else {
435
421
  this.animationId = null;
436
422
  }
437
423
  };
438
- this.animationId = raf(animate);
424
+ this.animationId = chunkND5PV5MU_cjs.raf(animate);
439
425
  }
440
426
  /**
441
427
  * Check if currently scrolling.
@@ -522,7 +508,7 @@ var ScrollEngine = class {
522
508
  */
523
509
  stopAnimation() {
524
510
  if (this.animationId) {
525
- cancelRaf(this.animationId);
511
+ chunkND5PV5MU_cjs.cancelRaf(this.animationId);
526
512
  this.animationId = null;
527
513
  }
528
514
  }
@@ -713,21 +699,6 @@ function binarySearch(length, predicate) {
713
699
  return low;
714
700
  }
715
701
 
716
- // src/utils/array.ts
717
- function clamp(value, min, max) {
718
- return Math.min(Math.max(value, min), max);
719
- }
720
- function normalizeColumnCount(columns) {
721
- return Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 1;
722
- }
723
- function autoColumnCount(containerWidth, minColumnWidth, gap) {
724
- const slot = minColumnWidth + gap;
725
- return slot > 0 ? normalizeColumnCount(Math.floor((containerWidth + gap) / slot)) : 1;
726
- }
727
- function normalizeOverscan(overscan) {
728
- return Number.isNaN(overscan) ? 0 : Math.max(0, Math.floor(overscan));
729
- }
730
-
731
702
  // src/kernel/measurement-cache.ts
732
703
  var MeasurementCache = class {
733
704
  /**
@@ -965,7 +936,7 @@ var RangeCalculator = class {
965
936
  const itemEnd = this.getItemEnd(mid);
966
937
  return itemEnd > scrollOffset;
967
938
  });
968
- return clamp(index, 0, this.itemCount - 1);
939
+ return chunkND5PV5MU_cjs.clamp(index, 0, this.itemCount - 1);
969
940
  }
970
941
  /**
971
942
  * Find the end index for a given scroll end position.
@@ -976,7 +947,7 @@ var RangeCalculator = class {
976
947
  while (index < this.itemCount - 1 && this.getItemOffset(index + 1) < scrollEnd) {
977
948
  index++;
978
949
  }
979
- return clamp(index, startIndex, this.itemCount - 1);
950
+ return chunkND5PV5MU_cjs.clamp(index, startIndex, this.itemCount - 1);
980
951
  }
981
952
  /**
982
953
  * Get the offset (start position) of an item.
@@ -1440,7 +1411,7 @@ var DEFAULT_OPTIONS = {
1440
1411
  };
1441
1412
  function createKernel(options = {}) {
1442
1413
  const config = { ...DEFAULT_OPTIONS, ...options };
1443
- config.overscan = normalizeOverscan(config.overscan);
1414
+ config.overscan = chunkND5PV5MU_cjs.normalizeOverscan(config.overscan);
1444
1415
  const eventBus = new EventBus();
1445
1416
  const scrollEngine = new ScrollEngine();
1446
1417
  scrollEngine.setDirection(config.direction);
@@ -1611,7 +1582,7 @@ function createKernel(options = {}) {
1611
1582
  rangeCalculator.setEstimatedHeight(newOptions.estimatedItemHeight);
1612
1583
  }
1613
1584
  if (newOptions.overscan !== void 0) {
1614
- config.overscan = normalizeOverscan(newOptions.overscan);
1585
+ config.overscan = chunkND5PV5MU_cjs.normalizeOverscan(newOptions.overscan);
1615
1586
  rangeCalculator.setOverscan(config.overscan);
1616
1587
  }
1617
1588
  if (newOptions.direction !== void 0) {
@@ -1712,91 +1683,6 @@ function createPlugin(config) {
1712
1683
  };
1713
1684
  }
1714
1685
 
1715
- // src/plugins/core/list-renderer.ts
1716
- function listRendererPlugin(options = {}) {
1717
- const { getItemKey = (index) => index } = options;
1718
- let kernel = null;
1719
- let virtualItems = [];
1720
- let currentRange = {
1721
- startIndex: 0,
1722
- endIndex: 0,
1723
- overscanStartIndex: 0,
1724
- overscanEndIndex: 0
1725
- };
1726
- function buildVirtualItems(range) {
1727
- if (!kernel) return [];
1728
- const items = [];
1729
- range.startIndex;
1730
- range.endIndex;
1731
- const lastIndex = Math.min(range.overscanEndIndex, kernel.getItemCount() - 1);
1732
- for (let i = range.overscanStartIndex; i <= lastIndex; i++) {
1733
- const offset = kernel.getItemOffset(i);
1734
- const size = kernel.getCachedHeight(i) ?? kernel.getEstimatedHeight();
1735
- items.push({
1736
- index: i,
1737
- key: getItemKey(i),
1738
- start: offset,
1739
- end: offset + size,
1740
- size,
1741
- lane: 0
1742
- // For list, always lane 0
1743
- });
1744
- }
1745
- return items;
1746
- }
1747
- function recalculate() {
1748
- if (!kernel) return;
1749
- currentRange = kernel.getVisibleRange();
1750
- virtualItems = buildVirtualItems(currentRange);
1751
- }
1752
- const api = {
1753
- getVirtualItems() {
1754
- return virtualItems;
1755
- },
1756
- getTotalHeight() {
1757
- return kernel?.getTotalSize() ?? 0;
1758
- },
1759
- getStartOffset() {
1760
- if (virtualItems.length === 0) return 0;
1761
- return virtualItems[0]?.start ?? 0;
1762
- },
1763
- getEndOffset() {
1764
- if (virtualItems.length === 0) return 0;
1765
- const lastItem = virtualItems[virtualItems.length - 1];
1766
- return lastItem?.end ?? 0;
1767
- },
1768
- isItemVisible(index) {
1769
- if (!kernel || index >= kernel.getItemCount()) return false;
1770
- return index >= currentRange.startIndex && index <= currentRange.endIndex;
1771
- },
1772
- recalculate
1773
- };
1774
- return {
1775
- name: "list-renderer",
1776
- version: "1.0.0",
1777
- type: "core",
1778
- install(k) {
1779
- kernel = k;
1780
- recalculate();
1781
- },
1782
- uninstall() {
1783
- virtualItems = [];
1784
- kernel = null;
1785
- },
1786
- hooks: {
1787
- onScroll: () => recalculate(),
1788
- onResize: () => recalculate(),
1789
- onItemMeasured: () => recalculate(),
1790
- onVisibleRangeChange: (range) => {
1791
- currentRange = range;
1792
- virtualItems = buildVirtualItems(range);
1793
- },
1794
- onItemsChange: () => recalculate()
1795
- },
1796
- api
1797
- };
1798
- }
1799
-
1800
1686
  // src/react/hooks/items-range.ts
1801
1687
  function getItemsRange(items, scrollTop, viewportHeight) {
1802
1688
  if (items.length === 0) {
@@ -1887,7 +1773,7 @@ function useVirtualList(options) {
1887
1773
  const resizeObserverRef = react.useRef(null);
1888
1774
  const kernel = kernelRef.current;
1889
1775
  react.useEffect(() => {
1890
- const plugin = listRendererPlugin({ getItemKey: (index) => getItemKeyRef.current(index) });
1776
+ const plugin = chunkND5PV5MU_cjs.listRendererPlugin({ getItemKey: (index) => getItemKeyRef.current(index) });
1891
1777
  kernel.register(plugin);
1892
1778
  listRendererRef.current = plugin.api;
1893
1779
  const unsubScroll = kernel.on("scroll", (event) => {
@@ -2072,6 +1958,18 @@ function useKernelPlugins(kernel, plugins) {
2072
1958
  registeredRef.current = [];
2073
1959
  }, [kernel]);
2074
1960
  }
1961
+ function callLoadMore(onLoadMore) {
1962
+ try {
1963
+ const pending = onLoadMore();
1964
+ if (pending && typeof pending.then === "function") {
1965
+ Promise.resolve(pending).catch((error) => {
1966
+ console.error("[Scrollex] Error in onLoadMore:", error);
1967
+ });
1968
+ }
1969
+ } catch (error) {
1970
+ console.error("[Scrollex] Error in onLoadMore:", error);
1971
+ }
1972
+ }
2075
1973
  function useLoadMoreWhenShort(containerRef, { count, totalSize, hasMore, isLoading, threshold, horizontal = false, onLoadMore }) {
2076
1974
  const requestedCount = react.useRef(-1);
2077
1975
  react.useEffect(() => {
@@ -2084,16 +1982,7 @@ function useLoadMoreWhenShort(containerRef, { count, totalSize, hasMore, isLoadi
2084
1982
  const distanceToEnd = horizontal ? element.scrollWidth - element.scrollLeft - element.clientWidth : element.scrollHeight - element.scrollTop - element.clientHeight;
2085
1983
  if (distanceToEnd < threshold) {
2086
1984
  requestedCount.current = count;
2087
- try {
2088
- const pending = onLoadMore();
2089
- if (pending && typeof pending.then === "function") {
2090
- Promise.resolve(pending).catch((error) => {
2091
- console.error("[Scrollex] Error in onLoadMore:", error);
2092
- });
2093
- }
2094
- } catch (error) {
2095
- console.error("[Scrollex] Error in onLoadMore:", error);
2096
- }
1985
+ callLoadMore(onLoadMore);
2097
1986
  }
2098
1987
  }, [count, totalSize, hasMore, isLoading, threshold, horizontal, !!onLoadMore]);
2099
1988
  }
@@ -2192,7 +2081,7 @@ function VirtualListInner(props, ref) {
2192
2081
  const target = event.currentTarget;
2193
2082
  const distanceToEnd = direction === "horizontal" ? target.scrollWidth - target.scrollLeft - target.clientWidth : target.scrollHeight - target.scrollTop - target.clientHeight;
2194
2083
  if (distanceToEnd < threshold) {
2195
- onLoadMore();
2084
+ callLoadMore(onLoadMore);
2196
2085
  }
2197
2086
  }, [onLoadMore, hasMore, isLoading, threshold, direction]);
2198
2087
  const containerStyles = react.useMemo(() => ({
@@ -2286,115 +2175,6 @@ function VirtualListInner(props, ref) {
2286
2175
  ) });
2287
2176
  }
2288
2177
  var VirtualList = react.forwardRef(VirtualListInner);
2289
-
2290
- // src/plugins/core/grid-renderer.ts
2291
- function gridRendererPlugin(options) {
2292
- const {
2293
- columns,
2294
- minColumnWidth = 100,
2295
- rowHeight,
2296
- gap = 0,
2297
- getItemKey = (index) => index,
2298
- getContainerWidth
2299
- } = options;
2300
- let kernel = null;
2301
- let virtualItems = [];
2302
- let columnCount = typeof columns === "number" ? normalizeColumnCount(columns) : 1;
2303
- let columnWidth = 0;
2304
- let gapX = typeof gap === "number" ? gap : gap.x;
2305
- let gapY = typeof gap === "number" ? gap : gap.y;
2306
- function calculateColumns(containerWidth) {
2307
- if (typeof columns === "number") {
2308
- columnCount = normalizeColumnCount(columns);
2309
- } else {
2310
- columnCount = autoColumnCount(containerWidth, minColumnWidth, gapX);
2311
- }
2312
- columnWidth = (containerWidth - (columnCount - 1) * gapX) / columnCount;
2313
- }
2314
- function getRowCount() {
2315
- if (!kernel) return 0;
2316
- return Math.ceil(kernel.getItemCount() / columnCount);
2317
- }
2318
- function buildVirtualItems() {
2319
- if (!kernel) return [];
2320
- const viewport = kernel.getViewport();
2321
- const scrollPosition = kernel.getScrollPosition();
2322
- const scrollTop = scrollPosition.scrollTop;
2323
- const effectiveRowHeight = rowHeight + gapY;
2324
- const startRow = Math.max(0, Math.floor(scrollTop / effectiveRowHeight));
2325
- const visibleRows = Math.ceil(viewport.height / effectiveRowHeight);
2326
- const overscan = kernel.getOptions().overscan;
2327
- const endRow = Math.min(getRowCount() - 1, startRow + visibleRows + overscan);
2328
- const overscanStartRow = Math.max(0, startRow - overscan);
2329
- const items = [];
2330
- const itemCount = kernel.getItemCount();
2331
- for (let row = overscanStartRow; row <= endRow; row++) {
2332
- for (let col = 0; col < columnCount; col++) {
2333
- const index = row * columnCount + col;
2334
- if (index >= itemCount) break;
2335
- const top = row * effectiveRowHeight;
2336
- items.push({
2337
- index,
2338
- key: getItemKey(index),
2339
- start: top,
2340
- end: top + rowHeight,
2341
- size: rowHeight,
2342
- lane: col
2343
- });
2344
- }
2345
- }
2346
- return items;
2347
- }
2348
- function recalculate() {
2349
- if (!kernel) return;
2350
- const viewport = kernel.getViewport();
2351
- calculateColumns(getContainerWidth?.() ?? viewport.width);
2352
- virtualItems = buildVirtualItems();
2353
- }
2354
- const api = {
2355
- getVirtualItems() {
2356
- return virtualItems;
2357
- },
2358
- getTotalHeight() {
2359
- const rowCount = getRowCount();
2360
- return rowCount === 0 ? 0 : rowCount * (rowHeight + gapY) - gapY;
2361
- },
2362
- getColumnCount() {
2363
- return columnCount;
2364
- },
2365
- getColumnWidth() {
2366
- return columnWidth;
2367
- },
2368
- getItemsPerRow() {
2369
- return columnCount;
2370
- },
2371
- getRowCount,
2372
- recalculate
2373
- };
2374
- return {
2375
- name: "grid-renderer",
2376
- version: "1.0.0",
2377
- type: "core",
2378
- install(k) {
2379
- kernel = k;
2380
- recalculate();
2381
- },
2382
- uninstall() {
2383
- virtualItems = [];
2384
- kernel = null;
2385
- },
2386
- hooks: {
2387
- onScroll: () => {
2388
- virtualItems = buildVirtualItems();
2389
- },
2390
- onResize: () => recalculate(),
2391
- onItemsChange: () => recalculate()
2392
- },
2393
- api
2394
- };
2395
- }
2396
-
2397
- // src/react/hooks/use-virtual-grid.ts
2398
2178
  function useVirtualGrid(options) {
2399
2179
  const {
2400
2180
  count,
@@ -2429,7 +2209,7 @@ function useVirtualGrid(options) {
2429
2209
  overscanStartIndex: 0,
2430
2210
  overscanEndIndex: 0
2431
2211
  });
2432
- const [columnCount, setColumnCount] = react.useState(typeof columns === "number" ? normalizeColumnCount(columns) : 1);
2212
+ const [columnCount, setColumnCount] = react.useState(typeof columns === "number" ? chunkND5PV5MU_cjs.normalizeColumnCount(columns) : 1);
2433
2213
  const [columnWidth, setColumnWidth] = react.useState(0);
2434
2214
  const gridRendererRef = react.useRef(null);
2435
2215
  const kernel = kernelRef.current;
@@ -2441,7 +2221,7 @@ function useVirtualGrid(options) {
2441
2221
  if (api && itemCount > 0) kernel.configure({ estimatedItemHeight: api.getTotalHeight() / itemCount });
2442
2222
  }, [kernel]);
2443
2223
  react.useEffect(() => {
2444
- const plugin = gridRendererPlugin({
2224
+ const plugin = chunkND5PV5MU_cjs.gridRendererPlugin({
2445
2225
  columns,
2446
2226
  minColumnWidth,
2447
2227
  rowHeight,
@@ -2707,7 +2487,7 @@ function VirtualGridInner(props, ref) {
2707
2487
  const target = event.currentTarget;
2708
2488
  const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2709
2489
  if (scrollBottom < threshold) {
2710
- onLoadMore();
2490
+ callLoadMore(onLoadMore);
2711
2491
  }
2712
2492
  }, [onLoadMore, hasMore, isLoading, threshold]);
2713
2493
  const containerStyles = react.useMemo(() => ({
@@ -2838,7 +2618,7 @@ function useVirtualMasonry(options) {
2838
2618
  overscanStartIndex: 0,
2839
2619
  overscanEndIndex: 0
2840
2620
  });
2841
- const [columnCount, setColumnCount] = react.useState(typeof columns === "number" ? normalizeColumnCount(columns) : 1);
2621
+ const [columnCount, setColumnCount] = react.useState(typeof columns === "number" ? chunkND5PV5MU_cjs.normalizeColumnCount(columns) : 1);
2842
2622
  const [columnWidth, setColumnWidth] = react.useState(0);
2843
2623
  const [columnHeights, setColumnHeights] = react.useState([]);
2844
2624
  const [totalSize, setTotalSize] = react.useState(0);
@@ -2857,7 +2637,7 @@ function useVirtualMasonry(options) {
2857
2637
  setTotalSize(0);
2858
2638
  return;
2859
2639
  }
2860
- const columnTotal = columns === "auto" ? autoColumnCount(containerWidth, minColumnWidth, gapX) : normalizeColumnCount(columns);
2640
+ const columnTotal = columns === "auto" ? chunkND5PV5MU_cjs.autoColumnCount(containerWidth, minColumnWidth, gapX) : chunkND5PV5MU_cjs.normalizeColumnCount(columns);
2861
2641
  const newColumnWidth = (containerWidth - (columnTotal - 1) * gapX) / columnTotal;
2862
2642
  setColumnCount(columnTotal);
2863
2643
  setColumnWidth(newColumnWidth);
@@ -2888,7 +2668,7 @@ function useVirtualMasonry(options) {
2888
2668
  const getVisibleItems = react.useCallback((scrollTop, viewportHeight) => {
2889
2669
  const cache = layoutCacheRef.current;
2890
2670
  const items = [];
2891
- const overscanAmount = normalizeOverscan(overscan) * 100;
2671
+ const overscanAmount = chunkND5PV5MU_cjs.normalizeOverscan(overscan) * 100;
2892
2672
  const viewStart = Math.max(0, scrollTop - overscanAmount);
2893
2673
  const viewEnd = scrollTop + viewportHeight + overscanAmount;
2894
2674
  for (let i = 0; i < count; i++) {
@@ -3104,7 +2884,6 @@ function VirtualMasonryInner(props, ref) {
3104
2884
  range,
3105
2885
  columnCount,
3106
2886
  columnWidth,
3107
- columnHeights,
3108
2887
  invalidateAllMeasurements,
3109
2888
  kernel
3110
2889
  } = useVirtualMasonry({
@@ -3153,7 +2932,7 @@ function VirtualMasonryInner(props, ref) {
3153
2932
  const target = event.currentTarget;
3154
2933
  const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
3155
2934
  if (scrollBottom < threshold) {
3156
- onLoadMore();
2935
+ callLoadMore(onLoadMore);
3157
2936
  }
3158
2937
  }, [onLoadMore, hasMore, isLoading, threshold]);
3159
2938
  const containerStyles = react.useMemo(() => ({
@@ -3259,7 +3038,7 @@ function boxOf(entry) {
3259
3038
  return { width: entry.contentRect.width, height: entry.contentRect.height };
3260
3039
  }
3261
3040
  function useMeasure(options = {}) {
3262
- const { onResize, debounce: debounce2 = 0 } = options;
3041
+ const { onResize, debounce = 0 } = options;
3263
3042
  const elementRef = react.useRef(null);
3264
3043
  const observerRef = react.useRef(null);
3265
3044
  const [dimensions, setDimensions] = react.useState({ width: 0, height: 0 });
@@ -3273,19 +3052,19 @@ function useMeasure(options = {}) {
3273
3052
  );
3274
3053
  const onResize2 = onResizeRef.current;
3275
3054
  if (onResize2) {
3276
- if (debounce2 > 0) {
3055
+ if (debounce > 0) {
3277
3056
  if (debounceTimerRef.current) {
3278
3057
  clearTimeout(debounceTimerRef.current);
3279
3058
  }
3280
3059
  debounceTimerRef.current = setTimeout(() => {
3281
3060
  onResize2(width, height);
3282
- }, debounce2);
3061
+ }, debounce);
3283
3062
  } else {
3284
3063
  onResize2(width, height);
3285
3064
  }
3286
3065
  }
3287
3066
  },
3288
- [debounce2]
3067
+ [debounce]
3289
3068
  );
3290
3069
  react.useEffect(() => {
3291
3070
  observerRef.current = new ResizeObserver((entries) => {
@@ -3394,528 +3173,32 @@ function useMeasureMany() {
3394
3173
  };
3395
3174
  }
3396
3175
 
3397
- // src/utils/debounce.ts
3398
- function debounce(fn, wait) {
3399
- let timeoutId = null;
3400
- let lastArgs = null;
3401
- let lastThis = null;
3402
- const debounced = function(...args) {
3403
- lastArgs = args;
3404
- lastThis = this;
3405
- if (timeoutId) {
3406
- clearTimeout(timeoutId);
3407
- }
3408
- timeoutId = setTimeout(() => {
3409
- timeoutId = null;
3410
- if (lastArgs) {
3411
- fn.apply(lastThis, lastArgs);
3412
- lastArgs = null;
3413
- lastThis = null;
3414
- }
3415
- }, wait);
3416
- };
3417
- debounced.cancel = () => {
3418
- if (timeoutId) {
3419
- clearTimeout(timeoutId);
3420
- timeoutId = null;
3421
- }
3422
- lastArgs = null;
3423
- lastThis = null;
3424
- };
3425
- debounced.flush = () => {
3426
- if (timeoutId) {
3427
- clearTimeout(timeoutId);
3428
- timeoutId = null;
3429
- if (lastArgs) {
3430
- fn.apply(lastThis, lastArgs);
3431
- lastArgs = null;
3432
- lastThis = null;
3433
- }
3434
- }
3435
- };
3436
- return debounced;
3437
- }
3438
-
3439
- // src/plugins/core/auto-measurer.ts
3440
- function autoMeasurerPlugin(options = {}) {
3441
- const {
3442
- estimatedItemHeight,
3443
- measureOnResize = true,
3444
- debounceMs = 100
3445
- } = options;
3446
- let kernel = null;
3447
- let resizeObserver = null;
3448
- const observedElements = /* @__PURE__ */ new WeakMap();
3449
- const elementsByIndex = /* @__PURE__ */ new Map();
3450
- let measureQueue = /* @__PURE__ */ new Set();
3451
- let flushScheduled = false;
3452
- function sizeAlongAxis(rect) {
3453
- return kernel?.getOptions().direction === "horizontal" ? rect.width : rect.height;
3454
- }
3455
- const debouncedFlush = debounce(() => {
3456
- flush();
3457
- }, debounceMs);
3458
- function flush() {
3459
- if (!kernel || measureQueue.size === 0) {
3460
- flushScheduled = false;
3461
- return;
3462
- }
3463
- const indicesToMeasure = Array.from(measureQueue);
3464
- measureQueue = /* @__PURE__ */ new Set();
3465
- flushScheduled = false;
3466
- const measurements = [];
3467
- for (const index of indicesToMeasure) {
3468
- const ref = elementsByIndex.get(index);
3469
- const element = ref?.deref();
3470
- if (element) {
3471
- const rect = element.getBoundingClientRect();
3472
- measurements.push({ index, height: sizeAlongAxis(rect) });
3473
- }
3474
- }
3475
- for (const { index, height } of measurements) {
3476
- if (height > 0) {
3477
- kernel.measureItem(index, height);
3478
- }
3479
- }
3480
- }
3481
- function scheduleFlush() {
3482
- if (!flushScheduled) {
3483
- flushScheduled = true;
3484
- requestAnimationFrame(() => {
3485
- flush();
3486
- });
3487
- }
3488
- }
3489
- function handleResize(entries) {
3490
- for (const entry of entries) {
3491
- const index = observedElements.get(entry.target);
3492
- if (index !== void 0) {
3493
- measureQueue.add(index);
3494
- }
3495
- }
3496
- if (measureOnResize && measureQueue.size > 0) {
3497
- debouncedFlush();
3498
- }
3499
- }
3500
- const api = {
3501
- measureElement(index, element) {
3502
- const rect = element.getBoundingClientRect();
3503
- const height = sizeAlongAxis(rect);
3504
- if (height > 0 && kernel) {
3505
- kernel.measureItem(index, height);
3506
- }
3507
- return height;
3508
- },
3509
- getCachedSize(index) {
3510
- return kernel?.getCachedHeight(index);
3511
- },
3512
- invalidate(index) {
3513
- kernel?.invalidateMeasurement(index);
3514
- },
3515
- invalidateAll() {
3516
- kernel?.invalidateAllMeasurements();
3517
- },
3518
- getMeasurementCache() {
3519
- const cache = /* @__PURE__ */ new Map();
3520
- if (!kernel) return cache;
3521
- const itemCount = kernel.getItemCount();
3522
- for (let i = 0; i < itemCount; i++) {
3523
- const height = kernel.getCachedHeight(i);
3524
- if (height !== void 0) {
3525
- cache.set(i, height);
3526
- }
3527
- }
3528
- return cache;
3529
- },
3530
- observe(index, element) {
3531
- const existingRef = elementsByIndex.get(index);
3532
- const existingElement = existingRef?.deref();
3533
- if (existingElement && existingElement !== element) {
3534
- resizeObserver?.unobserve(existingElement);
3535
- observedElements.delete(existingElement);
3536
- }
3537
- const previousIndex = observedElements.get(element);
3538
- if (previousIndex !== void 0 && previousIndex !== index) {
3539
- elementsByIndex.delete(previousIndex);
3540
- measureQueue.delete(previousIndex);
3541
- }
3542
- observedElements.set(element, index);
3543
- elementsByIndex.set(index, typeof WeakRef === "function" ? new WeakRef(element) : { deref: () => element });
3544
- resizeObserver?.observe(element);
3545
- measureQueue.add(index);
3546
- scheduleFlush();
3547
- },
3548
- unobserve(element) {
3549
- const index = observedElements.get(element);
3550
- if (index !== void 0) {
3551
- resizeObserver?.unobserve(element);
3552
- observedElements.delete(element);
3553
- elementsByIndex.delete(index);
3554
- measureQueue.delete(index);
3555
- }
3556
- }
3557
- };
3558
- return {
3559
- name: "auto-measurer",
3560
- version: "1.0.0",
3561
- type: "core",
3562
- install(k) {
3563
- kernel = k;
3564
- if (estimatedItemHeight !== void 0) {
3565
- kernel.configure({ estimatedItemHeight });
3566
- }
3567
- if (measureOnResize && typeof ResizeObserver !== "undefined") {
3568
- resizeObserver = new ResizeObserver(handleResize);
3569
- }
3570
- },
3571
- uninstall() {
3572
- if (resizeObserver) {
3573
- resizeObserver.disconnect();
3574
- resizeObserver = null;
3575
- }
3576
- debouncedFlush.cancel();
3577
- measureQueue.clear();
3578
- elementsByIndex.clear();
3579
- flushScheduled = false;
3580
- kernel = null;
3581
- },
3582
- api
3583
- };
3584
- }
3585
-
3586
- // src/plugins/core/infinite-loader.ts
3587
- function initialLoaderState(direction) {
3588
- return { loading: false, loadGeneration: 0, hasMoreForward: true, hasMoreBackward: direction === "backward" || direction === "both" };
3589
- }
3590
- var sharedLoaderStates = /* @__PURE__ */ new WeakMap();
3591
- function infiniteLoaderPlugin(options) {
3592
- const {
3593
- threshold = 200,
3594
- thresholdItems = 5,
3595
- direction = "forward",
3596
- onLoadMore
3597
- } = options;
3598
- let kernel = null;
3599
- let state = initialLoaderState(direction);
3600
- let lastCheckTime = 0;
3601
- const checkDebounceMs = 100;
3602
- let pendingEvent = null;
3603
- let trailingTimer = null;
3604
- function checkLoadMore(event) {
3605
- if (state.loading || !kernel) return;
3606
- const now = performance.now();
3607
- if (now - lastCheckTime < checkDebounceMs) {
3608
- pendingEvent = event;
3609
- if (trailingTimer === null) {
3610
- trailingTimer = setTimeout(() => {
3611
- trailingTimer = null;
3612
- const latest = pendingEvent;
3613
- pendingEvent = null;
3614
- if (latest) runCheck(latest);
3615
- }, Math.max(0, checkDebounceMs - (now - lastCheckTime)));
3616
- }
3617
- return;
3618
- }
3619
- runCheck(event);
3620
- }
3621
- function runCheck(event) {
3622
- if (state.loading || !kernel) return;
3623
- lastCheckTime = performance.now();
3624
- const viewport = kernel.getViewport();
3625
- const totalSize = kernel.getTotalSize();
3626
- const horizontal = kernel.getOptions().direction === "horizontal";
3627
- const scrollTop = horizontal ? event.scrollLeft : event.scrollTop;
3628
- const viewportSize = horizontal ? viewport.width : viewport.height;
3629
- if ((direction === "forward" || direction === "both") && state.hasMoreForward) {
3630
- const distanceFromBottom = totalSize - scrollTop - viewportSize;
3631
- if (distanceFromBottom < threshold) {
3632
- triggerLoad("forward");
3633
- return;
3634
- }
3635
- }
3636
- if ((direction === "backward" || direction === "both") && state.hasMoreBackward) {
3637
- if (scrollTop < threshold) {
3638
- triggerLoad("backward");
3639
- return;
3640
- }
3641
- }
3642
- }
3643
- function checkLoadMoreByRange(range, forwardOnly = false) {
3644
- if (state.loading || !kernel) return;
3645
- const itemCount = kernel.getItemCount();
3646
- if ((direction === "forward" || direction === "both") && state.hasMoreForward) {
3647
- const itemsFromEnd = itemCount - 1 - range.endIndex;
3648
- if (itemsFromEnd <= thresholdItems) {
3649
- triggerLoad("forward");
3650
- return;
3651
- }
3652
- }
3653
- if (!forwardOnly && (direction === "backward" || direction === "both") && state.hasMoreBackward) {
3654
- if (range.startIndex <= thresholdItems) {
3655
- triggerLoad("backward");
3656
- return;
3657
- }
3658
- }
3659
- }
3660
- async function triggerLoad(loadDirection) {
3661
- if (state.loading || !kernel) return;
3662
- if (loadDirection === "forward" && !state.hasMoreForward) return;
3663
- if (loadDirection === "backward" && !state.hasMoreBackward) return;
3664
- state.loading = true;
3665
- const generation = ++state.loadGeneration;
3666
- kernel.emit({
3667
- type: "load-more",
3668
- direction: loadDirection
3669
- });
3670
- try {
3671
- await onLoadMore(loadDirection);
3672
- } catch (error) {
3673
- console.error("[Scrollex] Error in onLoadMore:", error);
3674
- } finally {
3675
- if (generation === state.loadGeneration) {
3676
- state.loading = false;
3677
- }
3678
- }
3679
- }
3680
- const api = {
3681
- isLoading() {
3682
- return state.loading;
3683
- },
3684
- setLoading(l) {
3685
- state.loading = l;
3686
- },
3687
- hasMore() {
3688
- return state.hasMoreForward || state.hasMoreBackward;
3689
- },
3690
- setHasMore(hasMore) {
3691
- state.hasMoreForward = hasMore;
3692
- state.hasMoreBackward = hasMore;
3693
- },
3694
- hasMoreForward() {
3695
- return state.hasMoreForward;
3696
- },
3697
- setHasMoreForward(hasMore) {
3698
- state.hasMoreForward = hasMore;
3699
- },
3700
- hasMoreBackward() {
3701
- return state.hasMoreBackward;
3702
- },
3703
- setHasMoreBackward(hasMore) {
3704
- state.hasMoreBackward = hasMore;
3705
- },
3706
- reset() {
3707
- state.loadGeneration++;
3708
- state.loading = false;
3709
- state.hasMoreForward = true;
3710
- state.hasMoreBackward = direction === "backward" || direction === "both";
3711
- if (trailingTimer !== null) {
3712
- clearTimeout(trailingTimer);
3713
- trailingTimer = null;
3714
- }
3715
- pendingEvent = null;
3716
- },
3717
- triggerLoad(loadDirection) {
3718
- triggerLoad(loadDirection);
3719
- }
3720
- };
3721
- return {
3722
- name: "infinite-loader",
3723
- version: "1.0.0",
3724
- type: "core",
3725
- install(k) {
3726
- kernel = k;
3727
- const shared = sharedLoaderStates.get(k);
3728
- if (shared) {
3729
- state = shared;
3730
- } else {
3731
- sharedLoaderStates.set(k, state);
3732
- checkLoadMoreByRange(k.getVisibleRange(), true);
3733
- }
3734
- },
3735
- uninstall() {
3736
- if (trailingTimer !== null) {
3737
- clearTimeout(trailingTimer);
3738
- trailingTimer = null;
3739
- }
3740
- pendingEvent = null;
3741
- kernel = null;
3742
- },
3743
- hooks: {
3744
- onScroll: checkLoadMore,
3745
- onVisibleRangeChange: (range) => checkLoadMoreByRange(range)
3746
- },
3747
- api
3748
- };
3749
- }
3750
-
3751
- // src/plugins/core/scroll-controller.ts
3752
- var easings2 = {
3753
- easeInOut: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t};
3754
- function scrollControllerPlugin(options = {}) {
3755
- const {
3756
- defaultDuration = 300,
3757
- defaultEasing = easings2.easeInOut
3758
- } = options;
3759
- let kernel = null;
3760
- let animationId = null;
3761
- let animating = false;
3762
- let animationGeneration = 0;
3763
- function isHorizontal(k) {
3764
- return k.getOptions().direction === "horizontal";
3765
- }
3766
- function getOffset(k) {
3767
- const position = k.getScrollPosition();
3768
- return isHorizontal(k) ? position.scrollLeft : position.scrollTop;
3769
- }
3770
- function setOffset(k, offset) {
3771
- k.setScrollPosition(isHorizontal(k) ? { scrollLeft: offset } : { scrollTop: offset });
3772
- }
3773
- function getViewportSize(k) {
3774
- const viewport = k.getViewport();
3775
- return isHorizontal(k) ? viewport.width : viewport.height;
3776
- }
3777
- function animateScroll(targetOffset, duration, easing) {
3778
- if (!kernel) return;
3779
- stopAnimation();
3780
- const generation = animationGeneration;
3781
- const startTime = performance.now();
3782
- const startOffset = getOffset(kernel);
3783
- const distance = targetOffset - startOffset;
3784
- if (distance === 0 || !(duration > 0)) {
3785
- setOffset(kernel, targetOffset);
3786
- return;
3787
- }
3788
- animating = true;
3789
- function animate(currentTime) {
3790
- if (!kernel) {
3791
- animating = false;
3792
- return;
3793
- }
3794
- if (generation !== animationGeneration) return;
3795
- const elapsed = currentTime - startTime;
3796
- const progress = Math.max(0, Math.min(elapsed / duration, 1));
3797
- const easedProgress = easing(progress);
3798
- const currentOffset = startOffset + distance * easedProgress;
3799
- setOffset(kernel, currentOffset);
3800
- if (generation !== animationGeneration) return;
3801
- if (progress < 1) {
3802
- animationId = raf(animate);
3803
- } else {
3804
- animationId = null;
3805
- animating = false;
3806
- }
3807
- }
3808
- animationId = raf(animate);
3809
- }
3810
- function stopAnimation() {
3811
- animationGeneration++;
3812
- if (animationId !== null) {
3813
- cancelRaf(animationId);
3814
- animationId = null;
3815
- }
3816
- animating = false;
3817
- }
3818
- const api = {
3819
- scrollTo(offset, options2 = {}) {
3820
- if (!kernel) return;
3821
- const {
3822
- behavior = "auto",
3823
- duration = defaultDuration,
3824
- easing = defaultEasing
3825
- } = options2;
3826
- if (behavior === "auto") {
3827
- stopAnimation();
3828
- setOffset(kernel, offset);
3829
- } else {
3830
- animateScroll(offset, duration, easing);
3831
- }
3832
- },
3833
- scrollToIndex(index, options2 = {}) {
3834
- if (!kernel) return;
3835
- const {
3836
- align = "auto",
3837
- offset: additionalOffset = 0,
3838
- ...scrollOptions
3839
- } = options2;
3840
- const itemOffset = kernel.getItemOffset(index);
3841
- const itemSize = kernel.getCachedHeight(index) ?? kernel.getEstimatedHeight();
3842
- const viewportSize = getViewportSize(kernel);
3843
- let targetOffset;
3844
- switch (align) {
3845
- case "start":
3846
- targetOffset = itemOffset;
3847
- break;
3848
- case "center":
3849
- targetOffset = itemOffset - viewportSize / 2 + itemSize / 2;
3850
- break;
3851
- case "end":
3852
- targetOffset = itemOffset - viewportSize + itemSize;
3853
- break;
3854
- case "auto":
3855
- default: {
3856
- const visibleStart = getOffset(kernel);
3857
- const visibleEnd = visibleStart + viewportSize;
3858
- const itemEnd = itemOffset + itemSize;
3859
- if (itemOffset < visibleStart) {
3860
- targetOffset = itemOffset;
3861
- } else if (itemEnd > visibleEnd) {
3862
- targetOffset = itemEnd - viewportSize;
3863
- } else {
3864
- return;
3865
- }
3866
- break;
3867
- }
3868
- }
3869
- const maxScroll = Math.max(0, kernel.getTotalSize() - viewportSize);
3870
- targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
3871
- api.scrollTo(targetOffset, scrollOptions);
3872
- },
3873
- scrollToTop(options2 = {}) {
3874
- api.scrollTo(0, options2);
3875
- },
3876
- scrollToBottom(options2 = {}) {
3877
- if (!kernel) return;
3878
- const totalSize = kernel.getTotalSize();
3879
- const maxScroll = Math.max(0, totalSize - getViewportSize(kernel));
3880
- api.scrollTo(maxScroll, options2);
3881
- },
3882
- getScrollPosition() {
3883
- return kernel?.getScrollPosition() ?? { scrollTop: 0, scrollLeft: 0 };
3884
- },
3885
- isScrolling() {
3886
- return kernel?.isScrolling() ?? false;
3887
- },
3888
- isAnimating() {
3889
- return animating;
3890
- },
3891
- stopAnimation
3892
- };
3893
- return {
3894
- name: "scroll-controller",
3895
- version: "1.0.0",
3896
- type: "core",
3897
- install(k) {
3898
- kernel = k;
3899
- },
3900
- uninstall() {
3901
- stopAnimation();
3902
- kernel = null;
3903
- },
3904
- api
3905
- };
3906
- }
3907
-
3176
+ Object.defineProperty(exports, "autoMeasurerPlugin", {
3177
+ enumerable: true,
3178
+ get: function () { return chunkND5PV5MU_cjs.autoMeasurerPlugin; }
3179
+ });
3180
+ Object.defineProperty(exports, "gridRendererPlugin", {
3181
+ enumerable: true,
3182
+ get: function () { return chunkND5PV5MU_cjs.gridRendererPlugin; }
3183
+ });
3184
+ Object.defineProperty(exports, "infiniteLoaderPlugin", {
3185
+ enumerable: true,
3186
+ get: function () { return chunkND5PV5MU_cjs.infiniteLoaderPlugin; }
3187
+ });
3188
+ Object.defineProperty(exports, "listRendererPlugin", {
3189
+ enumerable: true,
3190
+ get: function () { return chunkND5PV5MU_cjs.listRendererPlugin; }
3191
+ });
3192
+ Object.defineProperty(exports, "scrollControllerPlugin", {
3193
+ enumerable: true,
3194
+ get: function () { return chunkND5PV5MU_cjs.scrollControllerPlugin; }
3195
+ });
3908
3196
  exports.VirtualGrid = VirtualGrid;
3909
3197
  exports.VirtualList = VirtualList;
3910
3198
  exports.VirtualMasonry = VirtualMasonry;
3911
- exports.autoMeasurerPlugin = autoMeasurerPlugin;
3912
3199
  exports.createKernel = createKernel;
3913
3200
  exports.createPlugin = createPlugin;
3914
3201
  exports.easings = easings;
3915
- exports.gridRendererPlugin = gridRendererPlugin;
3916
- exports.infiniteLoaderPlugin = infiniteLoaderPlugin;
3917
- exports.listRendererPlugin = listRendererPlugin;
3918
- exports.scrollControllerPlugin = scrollControllerPlugin;
3919
3202
  exports.useMeasure = useMeasure;
3920
3203
  exports.useMeasureMany = useMeasureMany;
3921
3204
  exports.useScrollex = useScrollex;