@oxog/scrollex 1.0.3 → 1.1.1

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 { listRendererPlugin, normalizeColumnCount, gridRendererPlugin, autoColumnCount, normalizeOverscan, cancelRaf, raf, clamp } from './chunk-VLA5K5HH.js';
2
+ export { autoMeasurerPlugin, gridRendererPlugin, infiniteLoaderPlugin, listRendererPlugin, scrollControllerPlugin } from './chunk-VLA5K5HH.js';
1
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() {
@@ -148,6 +148,7 @@ var EventBus = class {
148
148
  * Remove all handlers.
149
149
  */
150
150
  clear() {
151
+ for (const handlers of this.handlers.values()) handlers.clear();
151
152
  this.handlers.clear();
152
153
  this.onceHandlers.clear();
153
154
  this.pendingEvents = [];
@@ -159,6 +160,7 @@ var EventBus = class {
159
160
  * @param eventType - Type of event to clear handlers for
160
161
  */
161
162
  clearEvent(eventType) {
163
+ this.handlers.get(eventType)?.clear();
162
164
  this.handlers.delete(eventType);
163
165
  this.onceHandlers.delete(eventType);
164
166
  }
@@ -217,21 +219,6 @@ function getScrollDirection(current, previous) {
217
219
  return "none";
218
220
  }
219
221
 
220
- // src/utils/raf.ts
221
- function raf(callback) {
222
- if (typeof requestAnimationFrame !== "undefined") {
223
- return requestAnimationFrame(callback);
224
- }
225
- return setTimeout(() => callback(performance.now()), 16);
226
- }
227
- function cancelRaf(id) {
228
- if (typeof cancelAnimationFrame !== "undefined") {
229
- cancelAnimationFrame(id);
230
- } else {
231
- clearTimeout(id);
232
- }
233
- }
234
-
235
222
  // src/kernel/scroll-engine.ts
236
223
  var easings = {
237
224
  linear: (t) => t,
@@ -711,21 +698,6 @@ function binarySearch(length, predicate) {
711
698
  return low;
712
699
  }
713
700
 
714
- // src/utils/array.ts
715
- function clamp(value, min, max) {
716
- return Math.min(Math.max(value, min), max);
717
- }
718
- function normalizeColumnCount(columns) {
719
- return Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 1;
720
- }
721
- function autoColumnCount(containerWidth, minColumnWidth, gap) {
722
- const slot = minColumnWidth + gap;
723
- return slot > 0 ? normalizeColumnCount(Math.floor((containerWidth + gap) / slot)) : 1;
724
- }
725
- function normalizeOverscan(overscan) {
726
- return Number.isNaN(overscan) ? 0 : Math.max(0, Math.floor(overscan));
727
- }
728
-
729
701
  // src/kernel/measurement-cache.ts
730
702
  var MeasurementCache = class {
731
703
  /**
@@ -922,9 +894,59 @@ var RangeCalculator = class {
922
894
  this.countTree = new Float64Array(1);
923
895
  this.sumTree = new Float64Array(1);
924
896
  this.treesValid = false;
897
+ // Items whose size came from sizeGetter (not from a measurement): a new getter sizes them again
898
+ this.sized = /* @__PURE__ */ new Set();
925
899
  this.itemCount = options.itemCount;
926
900
  this.overscan = options.overscan;
927
901
  this.measurementCache = new MeasurementCache(options.estimatedItemHeight);
902
+ this.sizeGetter = options.getItemSize;
903
+ }
904
+ /**
905
+ * Set (or clear) the function that gives the known size of an item. Unmeasured items take that size
906
+ * up front; measurements already taken are kept, and the items sized by the previous function are sized
907
+ * again by the new one.
908
+ *
909
+ * @param getItemSize - Size of an item, or undefined to size unmeasured items with the estimate
910
+ * @returns Whether any item size (or the total size) changed
911
+ */
912
+ setSizeGetter(getItemSize) {
913
+ if (getItemSize === this.sizeGetter) return false;
914
+ const hadGetter = this.sizeGetter !== void 0;
915
+ this.sizeGetter = getItemSize;
916
+ let changed = hadGetter !== (getItemSize !== void 0);
917
+ for (let index = 0; index < this.itemCount; index++) {
918
+ if (this.measurementCache.has(index) && !this.sized.has(index)) continue;
919
+ const size = getItemSize ? getItemSize(index) : NaN;
920
+ const previous = this.measurementCache.get(index);
921
+ if (Number.isFinite(size) && size >= 0) {
922
+ if (size !== previous) {
923
+ this.measurementCache.set(index, size);
924
+ this.sized.add(index);
925
+ changed = true;
926
+ }
927
+ } else if (previous !== void 0) {
928
+ this.measurementCache.delete(index);
929
+ this.sized.delete(index);
930
+ changed = true;
931
+ }
932
+ }
933
+ if (changed) this.treesValid = false;
934
+ return changed;
935
+ }
936
+ /**
937
+ * Size the unmeasured items with the known-size function.
938
+ */
939
+ applyKnownSizes() {
940
+ const getItemSize = this.sizeGetter;
941
+ if (!getItemSize) return;
942
+ for (let index = 0; index < this.itemCount; index++) {
943
+ if (this.measurementCache.has(index)) continue;
944
+ const size = getItemSize(index);
945
+ if (Number.isFinite(size) && size >= 0) {
946
+ this.measurementCache.set(index, size);
947
+ this.sized.add(index);
948
+ }
949
+ }
928
950
  }
929
951
  /**
930
952
  * Get the visible range of items.
@@ -1003,6 +1025,7 @@ var RangeCalculator = class {
1003
1025
  * @returns Item size
1004
1026
  */
1005
1027
  getItemSize(index) {
1028
+ if (this.sizeGetter) this.ensureTrees();
1006
1029
  return this.measurementCache.getOrEstimate(index);
1007
1030
  }
1008
1031
  /**
@@ -1021,6 +1044,7 @@ var RangeCalculator = class {
1021
1044
  * @returns Previous height, or undefined if not measured
1022
1045
  */
1023
1046
  setItemHeight(index, height) {
1047
+ this.sized.delete(index);
1024
1048
  const previousHeight = this.measurementCache.set(index, height);
1025
1049
  this.track(index, previousHeight === void 0 ? 1 : 0, height - (previousHeight ?? 0));
1026
1050
  return previousHeight;
@@ -1032,6 +1056,7 @@ var RangeCalculator = class {
1032
1056
  * @returns Cached height, or undefined if not measured
1033
1057
  */
1034
1058
  getCachedHeight(index) {
1059
+ if (this.sizeGetter) this.ensureTrees();
1035
1060
  return this.measurementCache.get(index);
1036
1061
  }
1037
1062
  /**
@@ -1041,15 +1066,24 @@ var RangeCalculator = class {
1041
1066
  */
1042
1067
  invalidate(index) {
1043
1068
  const previousHeight = this.measurementCache.get(index);
1069
+ this.sized.delete(index);
1044
1070
  if (this.measurementCache.delete(index)) {
1045
1071
  this.track(index, -1, -(previousHeight ?? 0));
1046
1072
  }
1073
+ if (this.sizeGetter && Number.isInteger(index) && index >= 0 && index < this.itemCount) {
1074
+ const size = this.sizeGetter(index);
1075
+ if (Number.isFinite(size) && size >= 0) {
1076
+ this.setItemHeight(index, size);
1077
+ this.sized.add(index);
1078
+ }
1079
+ }
1047
1080
  }
1048
1081
  /**
1049
1082
  * Invalidate all measurements.
1050
1083
  */
1051
1084
  invalidateAll() {
1052
1085
  this.measurementCache.clear();
1086
+ this.sized.clear();
1053
1087
  this.treesValid = false;
1054
1088
  }
1055
1089
  /**
@@ -1065,6 +1099,9 @@ var RangeCalculator = class {
1065
1099
  for (const measured of this.measurementCache.getMeasuredIndices()) {
1066
1100
  if (measured >= count) this.measurementCache.delete(measured);
1067
1101
  }
1102
+ for (const index of this.sized) {
1103
+ if (index >= count) this.sized.delete(index);
1104
+ }
1068
1105
  }
1069
1106
  this.treesValid = false;
1070
1107
  }
@@ -1090,6 +1127,7 @@ var RangeCalculator = class {
1090
1127
  * @returns Estimated height
1091
1128
  */
1092
1129
  getEstimatedHeight() {
1130
+ if (this.sizeGetter) this.ensureTrees();
1093
1131
  return this.measurementCache.getEstimatedHeight();
1094
1132
  }
1095
1133
  /**
@@ -1151,6 +1189,7 @@ var RangeCalculator = class {
1151
1189
  ensureTrees() {
1152
1190
  if (this.treesValid) return;
1153
1191
  const size = this.itemCount;
1192
+ this.applyKnownSizes();
1154
1193
  this.countTree = new Float64Array(size + 1);
1155
1194
  this.sumTree = new Float64Array(size + 1);
1156
1195
  for (const index of this.measurementCache.getMeasuredIndices()) {
@@ -1446,10 +1485,12 @@ function createKernel(options = {}) {
1446
1485
  const rangeCalculator = new RangeCalculator({
1447
1486
  itemCount: config.itemCount,
1448
1487
  estimatedItemHeight: config.estimatedItemHeight,
1449
- overscan: config.overscan
1488
+ overscan: config.overscan,
1489
+ getItemSize: config.getItemSize
1450
1490
  });
1451
1491
  const pluginRegistry = new PluginRegistry();
1452
1492
  const startPadding = () => config.paddingStart ?? 0;
1493
+ const listStart = () => (config.scrollMargin ?? 0) + startPadding();
1453
1494
  let rangeAnnounced = false;
1454
1495
  let currentRange = {
1455
1496
  startIndex: 0,
@@ -1478,7 +1519,7 @@ function createKernel(options = {}) {
1478
1519
  const horizontal = config.direction === "horizontal";
1479
1520
  const offset = horizontal ? position.scrollLeft : position.scrollTop;
1480
1521
  const viewport = viewportManager.getViewport();
1481
- const maxScroll = rangeCalculator.getTotalSize() + startPadding() - (horizontal ? viewport.width : viewport.height);
1522
+ const maxScroll = rangeCalculator.getTotalSize() + listStart() - (horizontal ? viewport.width : viewport.height);
1482
1523
  const percentage = maxScroll > 0 ? Math.min(1, Math.max(0, offset / maxScroll)) : 0;
1483
1524
  return { ...position, offset, percentage };
1484
1525
  },
@@ -1490,7 +1531,7 @@ function createKernel(options = {}) {
1490
1531
  },
1491
1532
  scrollToIndex(index, options2 = {}) {
1492
1533
  const { align = "auto", offset: additionalOffset = 0, ...scrollOptions } = options2;
1493
- const itemOffset = rangeCalculator.getItemOffset(index) + startPadding();
1534
+ const itemOffset = rangeCalculator.getItemOffset(index) + listStart();
1494
1535
  const itemSize = rangeCalculator.getItemSize(index);
1495
1536
  const viewport = viewportManager.getViewport();
1496
1537
  const horizontal = config.direction === "horizontal";
@@ -1522,7 +1563,7 @@ function createKernel(options = {}) {
1522
1563
  break;
1523
1564
  }
1524
1565
  }
1525
- const maxScroll = Math.max(0, rangeCalculator.getTotalSize() + startPadding() - viewportSize);
1566
+ const maxScroll = Math.max(0, rangeCalculator.getTotalSize() + listStart() - viewportSize);
1526
1567
  targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
1527
1568
  scrollEngine.scrollTo(targetOffset, scrollOptions);
1528
1569
  },
@@ -1572,7 +1613,7 @@ function createKernel(options = {}) {
1572
1613
  return rangeCalculator.getEstimatedHeight();
1573
1614
  },
1574
1615
  getItemOffset(index) {
1575
- return rangeCalculator.getItemOffset(index) + startPadding();
1616
+ return rangeCalculator.getItemOffset(index) + listStart();
1576
1617
  },
1577
1618
  // Events
1578
1619
  emit(event) {
@@ -1603,6 +1644,14 @@ function createKernel(options = {}) {
1603
1644
  layoutChanged = newOptions.paddingStart !== startPadding();
1604
1645
  config.paddingStart = newOptions.paddingStart;
1605
1646
  }
1647
+ if (newOptions.scrollMargin !== void 0) {
1648
+ layoutChanged = layoutChanged || newOptions.scrollMargin !== (config.scrollMargin ?? 0);
1649
+ config.scrollMargin = newOptions.scrollMargin;
1650
+ }
1651
+ if ("getItemSize" in newOptions && newOptions.getItemSize !== config.getItemSize) {
1652
+ config.getItemSize = newOptions.getItemSize;
1653
+ layoutChanged = rangeCalculator.setSizeGetter(newOptions.getItemSize) || layoutChanged;
1654
+ }
1606
1655
  if (newOptions.estimatedItemHeight !== void 0) {
1607
1656
  layoutChanged = layoutChanged || newOptions.estimatedItemHeight !== config.estimatedItemHeight;
1608
1657
  config.estimatedItemHeight = newOptions.estimatedItemHeight;
@@ -1679,7 +1728,7 @@ function createKernel(options = {}) {
1679
1728
  if (!attached) return;
1680
1729
  const viewport = viewportManager.getViewport();
1681
1730
  const scrollPosition = scrollEngine.getScrollPosition();
1682
- const scrollOffset = (config.direction === "vertical" ? scrollPosition.scrollTop : scrollPosition.scrollLeft) - startPadding();
1731
+ const scrollOffset = (config.direction === "vertical" ? scrollPosition.scrollTop : scrollPosition.scrollLeft) - listStart();
1683
1732
  const viewportSize = config.direction === "vertical" ? viewport.height : viewport.width;
1684
1733
  const previousRange = { ...currentRange };
1685
1734
  currentRange = rangeCalculator.getVisibleRange(scrollOffset, viewportSize);
@@ -1710,91 +1759,6 @@ function createPlugin(config) {
1710
1759
  };
1711
1760
  }
1712
1761
 
1713
- // src/plugins/core/list-renderer.ts
1714
- function listRendererPlugin(options = {}) {
1715
- const { getItemKey = (index) => index } = options;
1716
- let kernel = null;
1717
- let virtualItems = [];
1718
- let currentRange = {
1719
- startIndex: 0,
1720
- endIndex: 0,
1721
- overscanStartIndex: 0,
1722
- overscanEndIndex: 0
1723
- };
1724
- function buildVirtualItems(range) {
1725
- if (!kernel) return [];
1726
- const items = [];
1727
- range.startIndex;
1728
- range.endIndex;
1729
- const lastIndex = Math.min(range.overscanEndIndex, kernel.getItemCount() - 1);
1730
- for (let i = range.overscanStartIndex; i <= lastIndex; i++) {
1731
- const offset = kernel.getItemOffset(i);
1732
- const size = kernel.getCachedHeight(i) ?? kernel.getEstimatedHeight();
1733
- items.push({
1734
- index: i,
1735
- key: getItemKey(i),
1736
- start: offset,
1737
- end: offset + size,
1738
- size,
1739
- lane: 0
1740
- // For list, always lane 0
1741
- });
1742
- }
1743
- return items;
1744
- }
1745
- function recalculate() {
1746
- if (!kernel) return;
1747
- currentRange = kernel.getVisibleRange();
1748
- virtualItems = buildVirtualItems(currentRange);
1749
- }
1750
- const api = {
1751
- getVirtualItems() {
1752
- return virtualItems;
1753
- },
1754
- getTotalHeight() {
1755
- return kernel?.getTotalSize() ?? 0;
1756
- },
1757
- getStartOffset() {
1758
- if (virtualItems.length === 0) return 0;
1759
- return virtualItems[0]?.start ?? 0;
1760
- },
1761
- getEndOffset() {
1762
- if (virtualItems.length === 0) return 0;
1763
- const lastItem = virtualItems[virtualItems.length - 1];
1764
- return lastItem?.end ?? 0;
1765
- },
1766
- isItemVisible(index) {
1767
- if (!kernel || index >= kernel.getItemCount()) return false;
1768
- return index >= currentRange.startIndex && index <= currentRange.endIndex;
1769
- },
1770
- recalculate
1771
- };
1772
- return {
1773
- name: "list-renderer",
1774
- version: "1.0.0",
1775
- type: "core",
1776
- install(k) {
1777
- kernel = k;
1778
- recalculate();
1779
- },
1780
- uninstall() {
1781
- virtualItems = [];
1782
- kernel = null;
1783
- },
1784
- hooks: {
1785
- onScroll: () => recalculate(),
1786
- onResize: () => recalculate(),
1787
- onItemMeasured: () => recalculate(),
1788
- onVisibleRangeChange: (range) => {
1789
- currentRange = range;
1790
- virtualItems = buildVirtualItems(range);
1791
- },
1792
- onItemsChange: () => recalculate()
1793
- },
1794
- api
1795
- };
1796
- }
1797
-
1798
1762
  // src/react/hooks/items-range.ts
1799
1763
  function getItemsRange(items, scrollTop, viewportHeight) {
1800
1764
  if (items.length === 0) {
@@ -1853,6 +1817,7 @@ function useVirtualList(options) {
1853
1817
  overscan = 5,
1854
1818
  paddingStart = 0,
1855
1819
  paddingEnd = 0,
1820
+ scrollMargin = 0,
1856
1821
  initialOffset = 0,
1857
1822
  getItemKey = (index) => index,
1858
1823
  horizontal = false,
@@ -1867,7 +1832,10 @@ function useVirtualList(options) {
1867
1832
  overscan,
1868
1833
  direction: horizontal ? "horizontal" : "vertical",
1869
1834
  getItemKey,
1870
- paddingStart
1835
+ paddingStart,
1836
+ scrollMargin,
1837
+ // Known heights lay out every item up front, not only the rows attached with measureElement
1838
+ getItemSize: getItemHeight
1871
1839
  })
1872
1840
  );
1873
1841
  const [virtualItems, setVirtualItems] = useState([]);
@@ -1949,6 +1917,12 @@ function useVirtualList(options) {
1949
1917
  useEffect(() => {
1950
1918
  kernel.configure({ paddingStart });
1951
1919
  }, [paddingStart, kernel]);
1920
+ useEffect(() => {
1921
+ kernel.configure({ scrollMargin });
1922
+ }, [scrollMargin, kernel]);
1923
+ useEffect(() => {
1924
+ kernel.configure({ getItemSize: getItemHeight });
1925
+ }, [getItemHeight, kernel]);
1952
1926
  useEffect(() => {
1953
1927
  kernel.configure({ direction: horizontal ? "horizontal" : "vertical" });
1954
1928
  }, [horizontal, kernel]);
@@ -1992,7 +1966,7 @@ function useVirtualList(options) {
1992
1966
  observer?.observe(element);
1993
1967
  if (getItemHeight) {
1994
1968
  const size = getItemHeight(index);
1995
- kernel.measureItem(index, size);
1969
+ if (kernel.getCachedHeight(index) !== size) kernel.measureItem(index, size);
1996
1970
  } else {
1997
1971
  const rect = element.getBoundingClientRect();
1998
1972
  const size = horizontal ? rect.width : rect.height;
@@ -2070,6 +2044,18 @@ function useKernelPlugins(kernel, plugins) {
2070
2044
  registeredRef.current = [];
2071
2045
  }, [kernel]);
2072
2046
  }
2047
+ function callLoadMore(onLoadMore) {
2048
+ try {
2049
+ const pending = onLoadMore();
2050
+ if (pending && typeof pending.then === "function") {
2051
+ Promise.resolve(pending).catch((error) => {
2052
+ console.error("[Scrollex] Error in onLoadMore:", error);
2053
+ });
2054
+ }
2055
+ } catch (error) {
2056
+ console.error("[Scrollex] Error in onLoadMore:", error);
2057
+ }
2058
+ }
2073
2059
  function useLoadMoreWhenShort(containerRef, { count, totalSize, hasMore, isLoading, threshold, horizontal = false, onLoadMore }) {
2074
2060
  const requestedCount = useRef(-1);
2075
2061
  useEffect(() => {
@@ -2082,16 +2068,7 @@ function useLoadMoreWhenShort(containerRef, { count, totalSize, hasMore, isLoadi
2082
2068
  const distanceToEnd = horizontal ? element.scrollWidth - element.scrollLeft - element.clientWidth : element.scrollHeight - element.scrollTop - element.clientHeight;
2083
2069
  if (distanceToEnd < threshold) {
2084
2070
  requestedCount.current = count;
2085
- try {
2086
- const pending = onLoadMore();
2087
- if (pending && typeof pending.then === "function") {
2088
- Promise.resolve(pending).catch((error) => {
2089
- console.error("[Scrollex] Error in onLoadMore:", error);
2090
- });
2091
- }
2092
- } catch (error) {
2093
- console.error("[Scrollex] Error in onLoadMore:", error);
2094
- }
2071
+ callLoadMore(onLoadMore);
2095
2072
  }
2096
2073
  }, [count, totalSize, hasMore, isLoading, threshold, horizontal, !!onLoadMore]);
2097
2074
  }
@@ -2190,7 +2167,7 @@ function VirtualListInner(props, ref) {
2190
2167
  const target = event.currentTarget;
2191
2168
  const distanceToEnd = direction === "horizontal" ? target.scrollWidth - target.scrollLeft - target.clientWidth : target.scrollHeight - target.scrollTop - target.clientHeight;
2192
2169
  if (distanceToEnd < threshold) {
2193
- onLoadMore();
2170
+ callLoadMore(onLoadMore);
2194
2171
  }
2195
2172
  }, [onLoadMore, hasMore, isLoading, threshold, direction]);
2196
2173
  const containerStyles = useMemo(() => ({
@@ -2284,115 +2261,6 @@ function VirtualListInner(props, ref) {
2284
2261
  ) });
2285
2262
  }
2286
2263
  var VirtualList = forwardRef(VirtualListInner);
2287
-
2288
- // src/plugins/core/grid-renderer.ts
2289
- function gridRendererPlugin(options) {
2290
- const {
2291
- columns,
2292
- minColumnWidth = 100,
2293
- rowHeight,
2294
- gap = 0,
2295
- getItemKey = (index) => index,
2296
- getContainerWidth
2297
- } = options;
2298
- let kernel = null;
2299
- let virtualItems = [];
2300
- let columnCount = typeof columns === "number" ? normalizeColumnCount(columns) : 1;
2301
- let columnWidth = 0;
2302
- let gapX = typeof gap === "number" ? gap : gap.x;
2303
- let gapY = typeof gap === "number" ? gap : gap.y;
2304
- function calculateColumns(containerWidth) {
2305
- if (typeof columns === "number") {
2306
- columnCount = normalizeColumnCount(columns);
2307
- } else {
2308
- columnCount = autoColumnCount(containerWidth, minColumnWidth, gapX);
2309
- }
2310
- columnWidth = (containerWidth - (columnCount - 1) * gapX) / columnCount;
2311
- }
2312
- function getRowCount() {
2313
- if (!kernel) return 0;
2314
- return Math.ceil(kernel.getItemCount() / columnCount);
2315
- }
2316
- function buildVirtualItems() {
2317
- if (!kernel) return [];
2318
- const viewport = kernel.getViewport();
2319
- const scrollPosition = kernel.getScrollPosition();
2320
- const scrollTop = scrollPosition.scrollTop;
2321
- const effectiveRowHeight = rowHeight + gapY;
2322
- const startRow = Math.max(0, Math.floor(scrollTop / effectiveRowHeight));
2323
- const visibleRows = Math.ceil(viewport.height / effectiveRowHeight);
2324
- const overscan = kernel.getOptions().overscan;
2325
- const endRow = Math.min(getRowCount() - 1, startRow + visibleRows + overscan);
2326
- const overscanStartRow = Math.max(0, startRow - overscan);
2327
- const items = [];
2328
- const itemCount = kernel.getItemCount();
2329
- for (let row = overscanStartRow; row <= endRow; row++) {
2330
- for (let col = 0; col < columnCount; col++) {
2331
- const index = row * columnCount + col;
2332
- if (index >= itemCount) break;
2333
- const top = row * effectiveRowHeight;
2334
- items.push({
2335
- index,
2336
- key: getItemKey(index),
2337
- start: top,
2338
- end: top + rowHeight,
2339
- size: rowHeight,
2340
- lane: col
2341
- });
2342
- }
2343
- }
2344
- return items;
2345
- }
2346
- function recalculate() {
2347
- if (!kernel) return;
2348
- const viewport = kernel.getViewport();
2349
- calculateColumns(getContainerWidth?.() ?? viewport.width);
2350
- virtualItems = buildVirtualItems();
2351
- }
2352
- const api = {
2353
- getVirtualItems() {
2354
- return virtualItems;
2355
- },
2356
- getTotalHeight() {
2357
- const rowCount = getRowCount();
2358
- return rowCount === 0 ? 0 : rowCount * (rowHeight + gapY) - gapY;
2359
- },
2360
- getColumnCount() {
2361
- return columnCount;
2362
- },
2363
- getColumnWidth() {
2364
- return columnWidth;
2365
- },
2366
- getItemsPerRow() {
2367
- return columnCount;
2368
- },
2369
- getRowCount,
2370
- recalculate
2371
- };
2372
- return {
2373
- name: "grid-renderer",
2374
- version: "1.0.0",
2375
- type: "core",
2376
- install(k) {
2377
- kernel = k;
2378
- recalculate();
2379
- },
2380
- uninstall() {
2381
- virtualItems = [];
2382
- kernel = null;
2383
- },
2384
- hooks: {
2385
- onScroll: () => {
2386
- virtualItems = buildVirtualItems();
2387
- },
2388
- onResize: () => recalculate(),
2389
- onItemsChange: () => recalculate()
2390
- },
2391
- api
2392
- };
2393
- }
2394
-
2395
- // src/react/hooks/use-virtual-grid.ts
2396
2264
  function useVirtualGrid(options) {
2397
2265
  const {
2398
2266
  count,
@@ -2705,7 +2573,7 @@ function VirtualGridInner(props, ref) {
2705
2573
  const target = event.currentTarget;
2706
2574
  const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2707
2575
  if (scrollBottom < threshold) {
2708
- onLoadMore();
2576
+ callLoadMore(onLoadMore);
2709
2577
  }
2710
2578
  }, [onLoadMore, hasMore, isLoading, threshold]);
2711
2579
  const containerStyles = useMemo(() => ({
@@ -3102,7 +2970,6 @@ function VirtualMasonryInner(props, ref) {
3102
2970
  range,
3103
2971
  columnCount,
3104
2972
  columnWidth,
3105
- columnHeights,
3106
2973
  invalidateAllMeasurements,
3107
2974
  kernel
3108
2975
  } = useVirtualMasonry({
@@ -3151,7 +3018,7 @@ function VirtualMasonryInner(props, ref) {
3151
3018
  const target = event.currentTarget;
3152
3019
  const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
3153
3020
  if (scrollBottom < threshold) {
3154
- onLoadMore();
3021
+ callLoadMore(onLoadMore);
3155
3022
  }
3156
3023
  }, [onLoadMore, hasMore, isLoading, threshold]);
3157
3024
  const containerStyles = useMemo(() => ({
@@ -3257,7 +3124,7 @@ function boxOf(entry) {
3257
3124
  return { width: entry.contentRect.width, height: entry.contentRect.height };
3258
3125
  }
3259
3126
  function useMeasure(options = {}) {
3260
- const { onResize, debounce: debounce2 = 0 } = options;
3127
+ const { onResize, debounce = 0 } = options;
3261
3128
  const elementRef = useRef(null);
3262
3129
  const observerRef = useRef(null);
3263
3130
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
@@ -3271,19 +3138,19 @@ function useMeasure(options = {}) {
3271
3138
  );
3272
3139
  const onResize2 = onResizeRef.current;
3273
3140
  if (onResize2) {
3274
- if (debounce2 > 0) {
3141
+ if (debounce > 0) {
3275
3142
  if (debounceTimerRef.current) {
3276
3143
  clearTimeout(debounceTimerRef.current);
3277
3144
  }
3278
3145
  debounceTimerRef.current = setTimeout(() => {
3279
3146
  onResize2(width, height);
3280
- }, debounce2);
3147
+ }, debounce);
3281
3148
  } else {
3282
3149
  onResize2(width, height);
3283
3150
  }
3284
3151
  }
3285
3152
  },
3286
- [debounce2]
3153
+ [debounce]
3287
3154
  );
3288
3155
  useEffect(() => {
3289
3156
  observerRef.current = new ResizeObserver((entries) => {
@@ -3392,517 +3259,6 @@ function useMeasureMany() {
3392
3259
  };
3393
3260
  }
3394
3261
 
3395
- // src/utils/debounce.ts
3396
- function debounce(fn, wait) {
3397
- let timeoutId = null;
3398
- let lastArgs = null;
3399
- let lastThis = null;
3400
- const debounced = function(...args) {
3401
- lastArgs = args;
3402
- lastThis = this;
3403
- if (timeoutId) {
3404
- clearTimeout(timeoutId);
3405
- }
3406
- timeoutId = setTimeout(() => {
3407
- timeoutId = null;
3408
- if (lastArgs) {
3409
- fn.apply(lastThis, lastArgs);
3410
- lastArgs = null;
3411
- lastThis = null;
3412
- }
3413
- }, wait);
3414
- };
3415
- debounced.cancel = () => {
3416
- if (timeoutId) {
3417
- clearTimeout(timeoutId);
3418
- timeoutId = null;
3419
- }
3420
- lastArgs = null;
3421
- lastThis = null;
3422
- };
3423
- debounced.flush = () => {
3424
- if (timeoutId) {
3425
- clearTimeout(timeoutId);
3426
- timeoutId = null;
3427
- if (lastArgs) {
3428
- fn.apply(lastThis, lastArgs);
3429
- lastArgs = null;
3430
- lastThis = null;
3431
- }
3432
- }
3433
- };
3434
- return debounced;
3435
- }
3436
-
3437
- // src/plugins/core/auto-measurer.ts
3438
- function autoMeasurerPlugin(options = {}) {
3439
- const {
3440
- estimatedItemHeight,
3441
- measureOnResize = true,
3442
- debounceMs = 100
3443
- } = options;
3444
- let kernel = null;
3445
- let resizeObserver = null;
3446
- const observedElements = /* @__PURE__ */ new WeakMap();
3447
- const elementsByIndex = /* @__PURE__ */ new Map();
3448
- let measureQueue = /* @__PURE__ */ new Set();
3449
- let flushScheduled = false;
3450
- function sizeAlongAxis(rect) {
3451
- return kernel?.getOptions().direction === "horizontal" ? rect.width : rect.height;
3452
- }
3453
- const debouncedFlush = debounce(() => {
3454
- flush();
3455
- }, debounceMs);
3456
- function flush() {
3457
- if (!kernel || measureQueue.size === 0) {
3458
- flushScheduled = false;
3459
- return;
3460
- }
3461
- const indicesToMeasure = Array.from(measureQueue);
3462
- measureQueue = /* @__PURE__ */ new Set();
3463
- flushScheduled = false;
3464
- const measurements = [];
3465
- for (const index of indicesToMeasure) {
3466
- const ref = elementsByIndex.get(index);
3467
- const element = ref?.deref();
3468
- if (element) {
3469
- const rect = element.getBoundingClientRect();
3470
- measurements.push({ index, height: sizeAlongAxis(rect) });
3471
- }
3472
- }
3473
- for (const { index, height } of measurements) {
3474
- if (height > 0) {
3475
- kernel.measureItem(index, height);
3476
- }
3477
- }
3478
- }
3479
- function scheduleFlush() {
3480
- if (!flushScheduled) {
3481
- flushScheduled = true;
3482
- requestAnimationFrame(() => {
3483
- flush();
3484
- });
3485
- }
3486
- }
3487
- function handleResize(entries) {
3488
- for (const entry of entries) {
3489
- const index = observedElements.get(entry.target);
3490
- if (index !== void 0) {
3491
- measureQueue.add(index);
3492
- }
3493
- }
3494
- if (measureOnResize && measureQueue.size > 0) {
3495
- debouncedFlush();
3496
- }
3497
- }
3498
- const api = {
3499
- measureElement(index, element) {
3500
- const rect = element.getBoundingClientRect();
3501
- const height = sizeAlongAxis(rect);
3502
- if (height > 0 && kernel) {
3503
- kernel.measureItem(index, height);
3504
- }
3505
- return height;
3506
- },
3507
- getCachedSize(index) {
3508
- return kernel?.getCachedHeight(index);
3509
- },
3510
- invalidate(index) {
3511
- kernel?.invalidateMeasurement(index);
3512
- },
3513
- invalidateAll() {
3514
- kernel?.invalidateAllMeasurements();
3515
- },
3516
- getMeasurementCache() {
3517
- const cache = /* @__PURE__ */ new Map();
3518
- if (!kernel) return cache;
3519
- const itemCount = kernel.getItemCount();
3520
- for (let i = 0; i < itemCount; i++) {
3521
- const height = kernel.getCachedHeight(i);
3522
- if (height !== void 0) {
3523
- cache.set(i, height);
3524
- }
3525
- }
3526
- return cache;
3527
- },
3528
- observe(index, element) {
3529
- const existingRef = elementsByIndex.get(index);
3530
- const existingElement = existingRef?.deref();
3531
- if (existingElement && existingElement !== element) {
3532
- resizeObserver?.unobserve(existingElement);
3533
- observedElements.delete(existingElement);
3534
- }
3535
- const previousIndex = observedElements.get(element);
3536
- if (previousIndex !== void 0 && previousIndex !== index) {
3537
- elementsByIndex.delete(previousIndex);
3538
- measureQueue.delete(previousIndex);
3539
- }
3540
- observedElements.set(element, index);
3541
- elementsByIndex.set(index, typeof WeakRef === "function" ? new WeakRef(element) : { deref: () => element });
3542
- resizeObserver?.observe(element);
3543
- measureQueue.add(index);
3544
- scheduleFlush();
3545
- },
3546
- unobserve(element) {
3547
- const index = observedElements.get(element);
3548
- if (index !== void 0) {
3549
- resizeObserver?.unobserve(element);
3550
- observedElements.delete(element);
3551
- elementsByIndex.delete(index);
3552
- measureQueue.delete(index);
3553
- }
3554
- }
3555
- };
3556
- return {
3557
- name: "auto-measurer",
3558
- version: "1.0.0",
3559
- type: "core",
3560
- install(k) {
3561
- kernel = k;
3562
- if (estimatedItemHeight !== void 0) {
3563
- kernel.configure({ estimatedItemHeight });
3564
- }
3565
- if (measureOnResize && typeof ResizeObserver !== "undefined") {
3566
- resizeObserver = new ResizeObserver(handleResize);
3567
- }
3568
- },
3569
- uninstall() {
3570
- if (resizeObserver) {
3571
- resizeObserver.disconnect();
3572
- resizeObserver = null;
3573
- }
3574
- debouncedFlush.cancel();
3575
- measureQueue.clear();
3576
- elementsByIndex.clear();
3577
- flushScheduled = false;
3578
- kernel = null;
3579
- },
3580
- api
3581
- };
3582
- }
3583
-
3584
- // src/plugins/core/infinite-loader.ts
3585
- function initialLoaderState(direction) {
3586
- return { loading: false, loadGeneration: 0, hasMoreForward: true, hasMoreBackward: direction === "backward" || direction === "both" };
3587
- }
3588
- var sharedLoaderStates = /* @__PURE__ */ new WeakMap();
3589
- function infiniteLoaderPlugin(options) {
3590
- const {
3591
- threshold = 200,
3592
- thresholdItems = 5,
3593
- direction = "forward",
3594
- onLoadMore
3595
- } = options;
3596
- let kernel = null;
3597
- let state = initialLoaderState(direction);
3598
- let lastCheckTime = 0;
3599
- const checkDebounceMs = 100;
3600
- let pendingEvent = null;
3601
- let trailingTimer = null;
3602
- function checkLoadMore(event) {
3603
- if (state.loading || !kernel) return;
3604
- const now = performance.now();
3605
- if (now - lastCheckTime < checkDebounceMs) {
3606
- pendingEvent = event;
3607
- if (trailingTimer === null) {
3608
- trailingTimer = setTimeout(() => {
3609
- trailingTimer = null;
3610
- const latest = pendingEvent;
3611
- pendingEvent = null;
3612
- if (latest) runCheck(latest);
3613
- }, Math.max(0, checkDebounceMs - (now - lastCheckTime)));
3614
- }
3615
- return;
3616
- }
3617
- runCheck(event);
3618
- }
3619
- function runCheck(event) {
3620
- if (state.loading || !kernel) return;
3621
- lastCheckTime = performance.now();
3622
- const viewport = kernel.getViewport();
3623
- const totalSize = kernel.getTotalSize();
3624
- const horizontal = kernel.getOptions().direction === "horizontal";
3625
- const scrollTop = horizontal ? event.scrollLeft : event.scrollTop;
3626
- const viewportSize = horizontal ? viewport.width : viewport.height;
3627
- if ((direction === "forward" || direction === "both") && state.hasMoreForward) {
3628
- const distanceFromBottom = totalSize - scrollTop - viewportSize;
3629
- if (distanceFromBottom < threshold) {
3630
- triggerLoad("forward");
3631
- return;
3632
- }
3633
- }
3634
- if ((direction === "backward" || direction === "both") && state.hasMoreBackward) {
3635
- if (scrollTop < threshold) {
3636
- triggerLoad("backward");
3637
- return;
3638
- }
3639
- }
3640
- }
3641
- function checkLoadMoreByRange(range, forwardOnly = false) {
3642
- if (state.loading || !kernel) return;
3643
- const itemCount = kernel.getItemCount();
3644
- if ((direction === "forward" || direction === "both") && state.hasMoreForward) {
3645
- const itemsFromEnd = itemCount - 1 - range.endIndex;
3646
- if (itemsFromEnd <= thresholdItems) {
3647
- triggerLoad("forward");
3648
- return;
3649
- }
3650
- }
3651
- if (!forwardOnly && (direction === "backward" || direction === "both") && state.hasMoreBackward) {
3652
- if (range.startIndex <= thresholdItems) {
3653
- triggerLoad("backward");
3654
- return;
3655
- }
3656
- }
3657
- }
3658
- async function triggerLoad(loadDirection) {
3659
- if (state.loading || !kernel) return;
3660
- if (loadDirection === "forward" && !state.hasMoreForward) return;
3661
- if (loadDirection === "backward" && !state.hasMoreBackward) return;
3662
- state.loading = true;
3663
- const generation = ++state.loadGeneration;
3664
- kernel.emit({
3665
- type: "load-more",
3666
- direction: loadDirection
3667
- });
3668
- try {
3669
- await onLoadMore(loadDirection);
3670
- } catch (error) {
3671
- console.error("[Scrollex] Error in onLoadMore:", error);
3672
- } finally {
3673
- if (generation === state.loadGeneration) {
3674
- state.loading = false;
3675
- }
3676
- }
3677
- }
3678
- const api = {
3679
- isLoading() {
3680
- return state.loading;
3681
- },
3682
- setLoading(l) {
3683
- state.loading = l;
3684
- },
3685
- hasMore() {
3686
- return state.hasMoreForward || state.hasMoreBackward;
3687
- },
3688
- setHasMore(hasMore) {
3689
- state.hasMoreForward = hasMore;
3690
- state.hasMoreBackward = hasMore;
3691
- },
3692
- hasMoreForward() {
3693
- return state.hasMoreForward;
3694
- },
3695
- setHasMoreForward(hasMore) {
3696
- state.hasMoreForward = hasMore;
3697
- },
3698
- hasMoreBackward() {
3699
- return state.hasMoreBackward;
3700
- },
3701
- setHasMoreBackward(hasMore) {
3702
- state.hasMoreBackward = hasMore;
3703
- },
3704
- reset() {
3705
- state.loadGeneration++;
3706
- state.loading = false;
3707
- state.hasMoreForward = true;
3708
- state.hasMoreBackward = direction === "backward" || direction === "both";
3709
- if (trailingTimer !== null) {
3710
- clearTimeout(trailingTimer);
3711
- trailingTimer = null;
3712
- }
3713
- pendingEvent = null;
3714
- },
3715
- triggerLoad(loadDirection) {
3716
- triggerLoad(loadDirection);
3717
- }
3718
- };
3719
- return {
3720
- name: "infinite-loader",
3721
- version: "1.0.0",
3722
- type: "core",
3723
- install(k) {
3724
- kernel = k;
3725
- const shared = sharedLoaderStates.get(k);
3726
- if (shared) {
3727
- state = shared;
3728
- } else {
3729
- sharedLoaderStates.set(k, state);
3730
- checkLoadMoreByRange(k.getVisibleRange(), true);
3731
- }
3732
- },
3733
- uninstall() {
3734
- if (trailingTimer !== null) {
3735
- clearTimeout(trailingTimer);
3736
- trailingTimer = null;
3737
- }
3738
- pendingEvent = null;
3739
- kernel = null;
3740
- },
3741
- hooks: {
3742
- onScroll: checkLoadMore,
3743
- onVisibleRangeChange: (range) => checkLoadMoreByRange(range)
3744
- },
3745
- api
3746
- };
3747
- }
3748
-
3749
- // src/plugins/core/scroll-controller.ts
3750
- var easings2 = {
3751
- easeInOut: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t};
3752
- function scrollControllerPlugin(options = {}) {
3753
- const {
3754
- defaultDuration = 300,
3755
- defaultEasing = easings2.easeInOut
3756
- } = options;
3757
- let kernel = null;
3758
- let animationId = null;
3759
- let animating = false;
3760
- let animationGeneration = 0;
3761
- function isHorizontal(k) {
3762
- return k.getOptions().direction === "horizontal";
3763
- }
3764
- function getOffset(k) {
3765
- const position = k.getScrollPosition();
3766
- return isHorizontal(k) ? position.scrollLeft : position.scrollTop;
3767
- }
3768
- function setOffset(k, offset) {
3769
- k.setScrollPosition(isHorizontal(k) ? { scrollLeft: offset } : { scrollTop: offset });
3770
- }
3771
- function getViewportSize(k) {
3772
- const viewport = k.getViewport();
3773
- return isHorizontal(k) ? viewport.width : viewport.height;
3774
- }
3775
- function animateScroll(targetOffset, duration, easing) {
3776
- if (!kernel) return;
3777
- stopAnimation();
3778
- const generation = animationGeneration;
3779
- const startTime = performance.now();
3780
- const startOffset = getOffset(kernel);
3781
- const distance = targetOffset - startOffset;
3782
- if (distance === 0 || !(duration > 0)) {
3783
- setOffset(kernel, targetOffset);
3784
- return;
3785
- }
3786
- animating = true;
3787
- function animate(currentTime) {
3788
- if (!kernel) {
3789
- animating = false;
3790
- return;
3791
- }
3792
- if (generation !== animationGeneration) return;
3793
- const elapsed = currentTime - startTime;
3794
- const progress = Math.max(0, Math.min(elapsed / duration, 1));
3795
- const easedProgress = easing(progress);
3796
- const currentOffset = startOffset + distance * easedProgress;
3797
- setOffset(kernel, currentOffset);
3798
- if (generation !== animationGeneration) return;
3799
- if (progress < 1) {
3800
- animationId = raf(animate);
3801
- } else {
3802
- animationId = null;
3803
- animating = false;
3804
- }
3805
- }
3806
- animationId = raf(animate);
3807
- }
3808
- function stopAnimation() {
3809
- animationGeneration++;
3810
- if (animationId !== null) {
3811
- cancelRaf(animationId);
3812
- animationId = null;
3813
- }
3814
- animating = false;
3815
- }
3816
- const api = {
3817
- scrollTo(offset, options2 = {}) {
3818
- if (!kernel) return;
3819
- const {
3820
- behavior = "auto",
3821
- duration = defaultDuration,
3822
- easing = defaultEasing
3823
- } = options2;
3824
- if (behavior === "auto") {
3825
- stopAnimation();
3826
- setOffset(kernel, offset);
3827
- } else {
3828
- animateScroll(offset, duration, easing);
3829
- }
3830
- },
3831
- scrollToIndex(index, options2 = {}) {
3832
- if (!kernel) return;
3833
- const {
3834
- align = "auto",
3835
- offset: additionalOffset = 0,
3836
- ...scrollOptions
3837
- } = options2;
3838
- const itemOffset = kernel.getItemOffset(index);
3839
- const itemSize = kernel.getCachedHeight(index) ?? kernel.getEstimatedHeight();
3840
- const viewportSize = getViewportSize(kernel);
3841
- let targetOffset;
3842
- switch (align) {
3843
- case "start":
3844
- targetOffset = itemOffset;
3845
- break;
3846
- case "center":
3847
- targetOffset = itemOffset - viewportSize / 2 + itemSize / 2;
3848
- break;
3849
- case "end":
3850
- targetOffset = itemOffset - viewportSize + itemSize;
3851
- break;
3852
- case "auto":
3853
- default: {
3854
- const visibleStart = getOffset(kernel);
3855
- const visibleEnd = visibleStart + viewportSize;
3856
- const itemEnd = itemOffset + itemSize;
3857
- if (itemOffset < visibleStart) {
3858
- targetOffset = itemOffset;
3859
- } else if (itemEnd > visibleEnd) {
3860
- targetOffset = itemEnd - viewportSize;
3861
- } else {
3862
- return;
3863
- }
3864
- break;
3865
- }
3866
- }
3867
- const maxScroll = Math.max(0, kernel.getTotalSize() - viewportSize);
3868
- targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
3869
- api.scrollTo(targetOffset, scrollOptions);
3870
- },
3871
- scrollToTop(options2 = {}) {
3872
- api.scrollTo(0, options2);
3873
- },
3874
- scrollToBottom(options2 = {}) {
3875
- if (!kernel) return;
3876
- const totalSize = kernel.getTotalSize();
3877
- const maxScroll = Math.max(0, totalSize - getViewportSize(kernel));
3878
- api.scrollTo(maxScroll, options2);
3879
- },
3880
- getScrollPosition() {
3881
- return kernel?.getScrollPosition() ?? { scrollTop: 0, scrollLeft: 0 };
3882
- },
3883
- isScrolling() {
3884
- return kernel?.isScrolling() ?? false;
3885
- },
3886
- isAnimating() {
3887
- return animating;
3888
- },
3889
- stopAnimation
3890
- };
3891
- return {
3892
- name: "scroll-controller",
3893
- version: "1.0.0",
3894
- type: "core",
3895
- install(k) {
3896
- kernel = k;
3897
- },
3898
- uninstall() {
3899
- stopAnimation();
3900
- kernel = null;
3901
- },
3902
- api
3903
- };
3904
- }
3905
-
3906
- export { VirtualGrid, VirtualList, VirtualMasonry, autoMeasurerPlugin, createKernel, createPlugin, easings, gridRendererPlugin, infiniteLoaderPlugin, listRendererPlugin, scrollControllerPlugin, useMeasure, useMeasureMany, useScrollex, useScrollexRequired, useVirtualGrid, useVirtualList, useVirtualMasonry };
3262
+ export { VirtualGrid, VirtualList, VirtualMasonry, createKernel, createPlugin, easings, useMeasure, useMeasureMany, useScrollex, useScrollexRequired, useVirtualGrid, useVirtualList, useVirtualMasonry };
3907
3263
  //# sourceMappingURL=index.js.map
3908
3264
  //# sourceMappingURL=index.js.map