@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.js CHANGED
@@ -1,8 +1,8 @@
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';
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
  /**
@@ -1710,91 +1682,6 @@ function createPlugin(config) {
1710
1682
  };
1711
1683
  }
1712
1684
 
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
1685
  // src/react/hooks/items-range.ts
1799
1686
  function getItemsRange(items, scrollTop, viewportHeight) {
1800
1687
  if (items.length === 0) {
@@ -2070,6 +1957,18 @@ function useKernelPlugins(kernel, plugins) {
2070
1957
  registeredRef.current = [];
2071
1958
  }, [kernel]);
2072
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
+ }
2073
1972
  function useLoadMoreWhenShort(containerRef, { count, totalSize, hasMore, isLoading, threshold, horizontal = false, onLoadMore }) {
2074
1973
  const requestedCount = useRef(-1);
2075
1974
  useEffect(() => {
@@ -2082,16 +1981,7 @@ function useLoadMoreWhenShort(containerRef, { count, totalSize, hasMore, isLoadi
2082
1981
  const distanceToEnd = horizontal ? element.scrollWidth - element.scrollLeft - element.clientWidth : element.scrollHeight - element.scrollTop - element.clientHeight;
2083
1982
  if (distanceToEnd < threshold) {
2084
1983
  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
- }
1984
+ callLoadMore(onLoadMore);
2095
1985
  }
2096
1986
  }, [count, totalSize, hasMore, isLoading, threshold, horizontal, !!onLoadMore]);
2097
1987
  }
@@ -2190,7 +2080,7 @@ function VirtualListInner(props, ref) {
2190
2080
  const target = event.currentTarget;
2191
2081
  const distanceToEnd = direction === "horizontal" ? target.scrollWidth - target.scrollLeft - target.clientWidth : target.scrollHeight - target.scrollTop - target.clientHeight;
2192
2082
  if (distanceToEnd < threshold) {
2193
- onLoadMore();
2083
+ callLoadMore(onLoadMore);
2194
2084
  }
2195
2085
  }, [onLoadMore, hasMore, isLoading, threshold, direction]);
2196
2086
  const containerStyles = useMemo(() => ({
@@ -2284,115 +2174,6 @@ function VirtualListInner(props, ref) {
2284
2174
  ) });
2285
2175
  }
2286
2176
  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
2177
  function useVirtualGrid(options) {
2397
2178
  const {
2398
2179
  count,
@@ -2705,7 +2486,7 @@ function VirtualGridInner(props, ref) {
2705
2486
  const target = event.currentTarget;
2706
2487
  const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2707
2488
  if (scrollBottom < threshold) {
2708
- onLoadMore();
2489
+ callLoadMore(onLoadMore);
2709
2490
  }
2710
2491
  }, [onLoadMore, hasMore, isLoading, threshold]);
2711
2492
  const containerStyles = useMemo(() => ({
@@ -3102,7 +2883,6 @@ function VirtualMasonryInner(props, ref) {
3102
2883
  range,
3103
2884
  columnCount,
3104
2885
  columnWidth,
3105
- columnHeights,
3106
2886
  invalidateAllMeasurements,
3107
2887
  kernel
3108
2888
  } = useVirtualMasonry({
@@ -3151,7 +2931,7 @@ function VirtualMasonryInner(props, ref) {
3151
2931
  const target = event.currentTarget;
3152
2932
  const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
3153
2933
  if (scrollBottom < threshold) {
3154
- onLoadMore();
2934
+ callLoadMore(onLoadMore);
3155
2935
  }
3156
2936
  }, [onLoadMore, hasMore, isLoading, threshold]);
3157
2937
  const containerStyles = useMemo(() => ({
@@ -3257,7 +3037,7 @@ function boxOf(entry) {
3257
3037
  return { width: entry.contentRect.width, height: entry.contentRect.height };
3258
3038
  }
3259
3039
  function useMeasure(options = {}) {
3260
- const { onResize, debounce: debounce2 = 0 } = options;
3040
+ const { onResize, debounce = 0 } = options;
3261
3041
  const elementRef = useRef(null);
3262
3042
  const observerRef = useRef(null);
3263
3043
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
@@ -3271,19 +3051,19 @@ function useMeasure(options = {}) {
3271
3051
  );
3272
3052
  const onResize2 = onResizeRef.current;
3273
3053
  if (onResize2) {
3274
- if (debounce2 > 0) {
3054
+ if (debounce > 0) {
3275
3055
  if (debounceTimerRef.current) {
3276
3056
  clearTimeout(debounceTimerRef.current);
3277
3057
  }
3278
3058
  debounceTimerRef.current = setTimeout(() => {
3279
3059
  onResize2(width, height);
3280
- }, debounce2);
3060
+ }, debounce);
3281
3061
  } else {
3282
3062
  onResize2(width, height);
3283
3063
  }
3284
3064
  }
3285
3065
  },
3286
- [debounce2]
3066
+ [debounce]
3287
3067
  );
3288
3068
  useEffect(() => {
3289
3069
  observerRef.current = new ResizeObserver((entries) => {
@@ -3392,517 +3172,6 @@ function useMeasureMany() {
3392
3172
  };
3393
3173
  }
3394
3174
 
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 };
3175
+ export { VirtualGrid, VirtualList, VirtualMasonry, createKernel, createPlugin, easings, useMeasure, useMeasureMany, useScrollex, useScrollexRequired, useVirtualGrid, useVirtualList, useVirtualMasonry };
3907
3176
  //# sourceMappingURL=index.js.map
3908
3177
  //# sourceMappingURL=index.js.map