@oxog/scrollex 1.0.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 ADDED
@@ -0,0 +1,3475 @@
1
+ import { createContext, forwardRef, useRef, useImperativeHandle, useCallback, useMemo, useState, useEffect, useContext } from 'react';
2
+ import { jsx, jsxs } from 'react/jsx-runtime';
3
+
4
+ // src/react/components/virtual-list.tsx
5
+
6
+ // src/kernel/event-bus.ts
7
+ var EventBus = class {
8
+ constructor() {
9
+ this.handlers = /* @__PURE__ */ new Map();
10
+ this.onceHandlers = /* @__PURE__ */ new Map();
11
+ this.emitting = false;
12
+ this.pendingEvents = [];
13
+ }
14
+ /**
15
+ * Subscribe to an event type.
16
+ *
17
+ * @param eventType - Type of event to subscribe to
18
+ * @param handler - Handler function to call when event is emitted
19
+ * @returns Unsubscribe function
20
+ */
21
+ on(eventType, handler) {
22
+ let handlers = this.handlers.get(eventType);
23
+ if (!handlers) {
24
+ handlers = /* @__PURE__ */ new Set();
25
+ this.handlers.set(eventType, handlers);
26
+ }
27
+ handlers.add(handler);
28
+ return () => {
29
+ this.off(eventType, handler);
30
+ };
31
+ }
32
+ /**
33
+ * Unsubscribe from an event type.
34
+ *
35
+ * @param eventType - Type of event to unsubscribe from
36
+ * @param handler - Handler function to remove
37
+ */
38
+ off(eventType, handler) {
39
+ const handlers = this.handlers.get(eventType);
40
+ if (handlers) {
41
+ handlers.delete(handler);
42
+ if (handlers.size === 0) {
43
+ this.handlers.delete(eventType);
44
+ }
45
+ }
46
+ const onceHandlers = this.onceHandlers.get(eventType);
47
+ if (onceHandlers) {
48
+ onceHandlers.delete(handler);
49
+ if (onceHandlers.size === 0) {
50
+ this.onceHandlers.delete(eventType);
51
+ }
52
+ }
53
+ }
54
+ /**
55
+ * Subscribe to an event type, but only fire once.
56
+ *
57
+ * @param eventType - Type of event to subscribe to
58
+ * @param handler - Handler function to call when event is emitted
59
+ * @returns Unsubscribe function
60
+ */
61
+ once(eventType, handler) {
62
+ let onceHandlers = this.onceHandlers.get(eventType);
63
+ if (!onceHandlers) {
64
+ onceHandlers = /* @__PURE__ */ new Set();
65
+ this.onceHandlers.set(eventType, onceHandlers);
66
+ }
67
+ onceHandlers.add(handler);
68
+ return () => {
69
+ this.off(eventType, handler);
70
+ };
71
+ }
72
+ /**
73
+ * Emit an event to all subscribers.
74
+ *
75
+ * @param event - Event to emit
76
+ */
77
+ emit(event) {
78
+ if (this.emitting) {
79
+ this.pendingEvents.push(event);
80
+ return;
81
+ }
82
+ this.emitting = true;
83
+ try {
84
+ this.dispatchEvent(event);
85
+ while (this.pendingEvents.length > 0) {
86
+ const pendingEvent = this.pendingEvents.shift();
87
+ if (pendingEvent) {
88
+ this.dispatchEvent(pendingEvent);
89
+ }
90
+ }
91
+ } finally {
92
+ this.emitting = false;
93
+ }
94
+ }
95
+ /**
96
+ * Dispatch a single event to handlers.
97
+ */
98
+ dispatchEvent(event) {
99
+ const eventType = event.type;
100
+ const handlers = this.handlers.get(eventType);
101
+ if (handlers) {
102
+ for (const handler of handlers) {
103
+ try {
104
+ handler(event);
105
+ } catch (error) {
106
+ console.error(`[Scrollex] Error in event handler for "${eventType}":`, error);
107
+ }
108
+ }
109
+ }
110
+ const onceHandlers = this.onceHandlers.get(eventType);
111
+ if (onceHandlers) {
112
+ const handlersToCall = Array.from(onceHandlers);
113
+ onceHandlers.clear();
114
+ for (const handler of handlersToCall) {
115
+ try {
116
+ handler(event);
117
+ } catch (error) {
118
+ console.error(`[Scrollex] Error in once handler for "${eventType}":`, error);
119
+ }
120
+ }
121
+ if (onceHandlers.size === 0) {
122
+ this.onceHandlers.delete(eventType);
123
+ }
124
+ }
125
+ }
126
+ /**
127
+ * Check if there are any handlers for an event type.
128
+ *
129
+ * @param eventType - Type of event to check
130
+ * @returns Whether there are handlers
131
+ */
132
+ hasHandlers(eventType) {
133
+ const handlers = this.handlers.get(eventType);
134
+ const onceHandlers = this.onceHandlers.get(eventType);
135
+ return (handlers?.size ?? 0) > 0 || (onceHandlers?.size ?? 0) > 0;
136
+ }
137
+ /**
138
+ * Get the number of handlers for an event type.
139
+ *
140
+ * @param eventType - Type of event to check
141
+ * @returns Number of handlers
142
+ */
143
+ handlerCount(eventType) {
144
+ const handlers = this.handlers.get(eventType);
145
+ const onceHandlers = this.onceHandlers.get(eventType);
146
+ return (handlers?.size ?? 0) + (onceHandlers?.size ?? 0);
147
+ }
148
+ /**
149
+ * Remove all handlers.
150
+ */
151
+ clear() {
152
+ this.handlers.clear();
153
+ this.onceHandlers.clear();
154
+ this.pendingEvents = [];
155
+ this.emitting = false;
156
+ }
157
+ /**
158
+ * Remove all handlers for a specific event type.
159
+ *
160
+ * @param eventType - Type of event to clear handlers for
161
+ */
162
+ clearEvent(eventType) {
163
+ this.handlers.delete(eventType);
164
+ this.onceHandlers.delete(eventType);
165
+ }
166
+ };
167
+
168
+ // src/utils/throttle.ts
169
+ function throttleRAF(fn) {
170
+ let rafId = null;
171
+ let lastArgs = null;
172
+ const throttled = function(...args) {
173
+ lastArgs = args;
174
+ if (rafId === null) {
175
+ rafId = requestAnimationFrame(() => {
176
+ rafId = null;
177
+ if (lastArgs) {
178
+ fn.apply(this, lastArgs);
179
+ }
180
+ });
181
+ }
182
+ };
183
+ throttled.cancel = () => {
184
+ if (rafId !== null) {
185
+ cancelAnimationFrame(rafId);
186
+ rafId = null;
187
+ }
188
+ lastArgs = null;
189
+ };
190
+ return throttled;
191
+ }
192
+
193
+ // src/utils/scroll.ts
194
+ function getScrollPosition(element) {
195
+ return {
196
+ scrollTop: element.scrollTop,
197
+ scrollLeft: element.scrollLeft
198
+ };
199
+ }
200
+ function setScrollPosition(element, position) {
201
+ if (position.scrollTop !== void 0) {
202
+ element.scrollTop = position.scrollTop;
203
+ }
204
+ if (position.scrollLeft !== void 0) {
205
+ element.scrollLeft = position.scrollLeft;
206
+ }
207
+ }
208
+ function getScrollDirection(current, previous) {
209
+ const deltaY = current.scrollTop - previous.scrollTop;
210
+ const deltaX = current.scrollLeft - previous.scrollLeft;
211
+ if (Math.abs(deltaY) > Math.abs(deltaX)) {
212
+ if (deltaY > 0) return "down";
213
+ if (deltaY < 0) return "up";
214
+ } else {
215
+ if (deltaX > 0) return "right";
216
+ if (deltaX < 0) return "left";
217
+ }
218
+ return "none";
219
+ }
220
+
221
+ // src/utils/raf.ts
222
+ function raf(callback) {
223
+ if (typeof requestAnimationFrame !== "undefined") {
224
+ return requestAnimationFrame(callback);
225
+ }
226
+ return setTimeout(() => callback(Date.now()), 16);
227
+ }
228
+ function cancelRaf(id) {
229
+ if (typeof cancelAnimationFrame !== "undefined") {
230
+ cancelAnimationFrame(id);
231
+ } else {
232
+ clearTimeout(id);
233
+ }
234
+ }
235
+
236
+ // src/kernel/scroll-engine.ts
237
+ var easings = {
238
+ linear: (t) => t,
239
+ easeIn: (t) => t * t,
240
+ easeOut: (t) => t * (2 - t),
241
+ easeInOut: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
242
+ easeInCubic: (t) => t * t * t,
243
+ easeOutCubic: (t) => 1 - Math.pow(1 - t, 3),
244
+ easeInOutCubic: (t) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2
245
+ };
246
+ var ScrollEngine = class {
247
+ constructor() {
248
+ this.container = null;
249
+ this.scrollPosition = { scrollTop: 0, scrollLeft: 0 };
250
+ this.previousScrollPosition = { scrollTop: 0, scrollLeft: 0 };
251
+ this.scrolling = false;
252
+ this.scrollDirection = "none";
253
+ this.lastScrollTime = 0;
254
+ this.scrollEndTimer = null;
255
+ this.scrollEndDelay = 150;
256
+ // Animation state
257
+ this.animationId = null;
258
+ this.animationStartTime = 0;
259
+ this.animationStartOffset = 0;
260
+ this.animationTargetOffset = 0;
261
+ this.animationDuration = 0;
262
+ this.animationEasing = easings.easeInOut;
263
+ // Callbacks
264
+ this.onScrollCallback = null;
265
+ this.onScrollStartCallback = null;
266
+ this.onScrollEndCallback = null;
267
+ // Throttled handler
268
+ this.throttledHandleScroll = null;
269
+ this.boundHandleScroll = null;
270
+ }
271
+ /**
272
+ * Attach to a container element.
273
+ *
274
+ * @param container - Container element to observe
275
+ */
276
+ attach(container) {
277
+ this.detach();
278
+ this.container = container;
279
+ this.scrollPosition = getScrollPosition(container);
280
+ this.previousScrollPosition = { ...this.scrollPosition };
281
+ this.throttledHandleScroll = throttleRAF(this.processScroll.bind(this));
282
+ this.boundHandleScroll = () => this.throttledHandleScroll?.();
283
+ container.addEventListener("scroll", this.boundHandleScroll, { passive: true });
284
+ }
285
+ /**
286
+ * Detach from the current container.
287
+ */
288
+ detach() {
289
+ if (this.container && this.boundHandleScroll) {
290
+ this.container.removeEventListener("scroll", this.boundHandleScroll);
291
+ }
292
+ if (this.throttledHandleScroll) {
293
+ this.throttledHandleScroll.cancel();
294
+ this.throttledHandleScroll = null;
295
+ }
296
+ if (this.scrollEndTimer) {
297
+ clearTimeout(this.scrollEndTimer);
298
+ this.scrollEndTimer = null;
299
+ }
300
+ if (this.animationId) {
301
+ cancelRaf(this.animationId);
302
+ this.animationId = null;
303
+ }
304
+ this.boundHandleScroll = null;
305
+ this.container = null;
306
+ }
307
+ /**
308
+ * Process scroll event.
309
+ */
310
+ processScroll() {
311
+ if (!this.container) return;
312
+ const now = performance.now();
313
+ this.previousScrollPosition = { ...this.scrollPosition };
314
+ this.scrollPosition = getScrollPosition(this.container);
315
+ this.scrollDirection = getScrollDirection(this.scrollPosition, this.previousScrollPosition);
316
+ if (!this.scrolling) {
317
+ this.scrolling = true;
318
+ this.onScrollStartCallback?.({
319
+ type: "scroll-start",
320
+ scrollTop: this.scrollPosition.scrollTop,
321
+ scrollLeft: this.scrollPosition.scrollLeft,
322
+ timestamp: now
323
+ });
324
+ }
325
+ this.onScrollCallback?.({
326
+ type: "scroll",
327
+ scrollTop: this.scrollPosition.scrollTop,
328
+ scrollLeft: this.scrollPosition.scrollLeft,
329
+ deltaY: this.scrollPosition.scrollTop - this.previousScrollPosition.scrollTop,
330
+ deltaX: this.scrollPosition.scrollLeft - this.previousScrollPosition.scrollLeft,
331
+ direction: this.scrollDirection,
332
+ timestamp: now
333
+ });
334
+ this.lastScrollTime = now;
335
+ this.scheduleScrollEnd();
336
+ }
337
+ /**
338
+ * Schedule scroll end detection.
339
+ */
340
+ scheduleScrollEnd() {
341
+ if (this.scrollEndTimer) {
342
+ clearTimeout(this.scrollEndTimer);
343
+ }
344
+ this.scrollEndTimer = setTimeout(() => {
345
+ this.scrolling = false;
346
+ this.scrollEndTimer = null;
347
+ this.onScrollEndCallback?.({
348
+ type: "scroll-end",
349
+ scrollTop: this.scrollPosition.scrollTop,
350
+ scrollLeft: this.scrollPosition.scrollLeft,
351
+ timestamp: performance.now()
352
+ });
353
+ }, this.scrollEndDelay);
354
+ }
355
+ /**
356
+ * Get the current scroll position.
357
+ *
358
+ * @returns Current scroll position
359
+ */
360
+ getScrollPosition() {
361
+ return { ...this.scrollPosition };
362
+ }
363
+ /**
364
+ * Set the scroll position directly.
365
+ *
366
+ * @param position - New scroll position
367
+ */
368
+ setScrollPosition(position) {
369
+ if (!this.container) return;
370
+ if (this.animationId) {
371
+ cancelRaf(this.animationId);
372
+ this.animationId = null;
373
+ }
374
+ setScrollPosition(this.container, position);
375
+ if (position.scrollTop !== void 0) {
376
+ this.scrollPosition.scrollTop = position.scrollTop;
377
+ }
378
+ if (position.scrollLeft !== void 0) {
379
+ this.scrollPosition.scrollLeft = position.scrollLeft;
380
+ }
381
+ }
382
+ /**
383
+ * Scroll to an offset with optional animation.
384
+ *
385
+ * @param offset - Target scroll offset
386
+ * @param options - Scroll options
387
+ */
388
+ scrollTo(offset, options = {}) {
389
+ if (!this.container) return;
390
+ const { behavior = "auto", duration = 300, easing = easings.easeInOut } = options;
391
+ if (behavior === "auto" || behavior === "smooth" && duration === 0) {
392
+ this.setScrollPosition({ scrollTop: offset });
393
+ } else {
394
+ this.animateScroll(offset, duration, easing);
395
+ }
396
+ }
397
+ /**
398
+ * Animate scroll to a target offset.
399
+ */
400
+ animateScroll(targetOffset, duration, easing) {
401
+ if (this.animationId) {
402
+ cancelRaf(this.animationId);
403
+ }
404
+ this.animationStartTime = performance.now();
405
+ this.animationStartOffset = this.scrollPosition.scrollTop;
406
+ this.animationTargetOffset = targetOffset;
407
+ this.animationDuration = duration;
408
+ this.animationEasing = easing;
409
+ const animate = (currentTime) => {
410
+ const elapsed = currentTime - this.animationStartTime;
411
+ const progress = Math.min(elapsed / this.animationDuration, 1);
412
+ const easedProgress = this.animationEasing(progress);
413
+ const currentOffset = this.animationStartOffset + (this.animationTargetOffset - this.animationStartOffset) * easedProgress;
414
+ this.setScrollPosition({ scrollTop: currentOffset });
415
+ if (progress < 1) {
416
+ this.animationId = raf(animate);
417
+ } else {
418
+ this.animationId = null;
419
+ }
420
+ };
421
+ this.animationId = raf(animate);
422
+ }
423
+ /**
424
+ * Check if currently scrolling.
425
+ *
426
+ * @returns Whether scrolling
427
+ */
428
+ isScrolling() {
429
+ return this.scrolling;
430
+ }
431
+ /**
432
+ * Check if an animation is in progress.
433
+ *
434
+ * @returns Whether animating
435
+ */
436
+ isAnimating() {
437
+ return this.animationId !== null;
438
+ }
439
+ /**
440
+ * Get the current scroll direction.
441
+ *
442
+ * @returns Scroll direction
443
+ */
444
+ getScrollDirection() {
445
+ return this.scrollDirection;
446
+ }
447
+ /**
448
+ * Set scroll end delay.
449
+ *
450
+ * @param delay - Delay in ms
451
+ */
452
+ setScrollEndDelay(delay) {
453
+ this.scrollEndDelay = delay;
454
+ }
455
+ /**
456
+ * Set callback for scroll events.
457
+ *
458
+ * @param callback - Callback function
459
+ */
460
+ onScroll(callback) {
461
+ this.onScrollCallback = callback;
462
+ }
463
+ /**
464
+ * Set callback for scroll start events.
465
+ *
466
+ * @param callback - Callback function
467
+ */
468
+ onScrollStart(callback) {
469
+ this.onScrollStartCallback = callback;
470
+ }
471
+ /**
472
+ * Set callback for scroll end events.
473
+ *
474
+ * @param callback - Callback function
475
+ */
476
+ onScrollEnd(callback) {
477
+ this.onScrollEndCallback = callback;
478
+ }
479
+ /**
480
+ * Get the container element.
481
+ *
482
+ * @returns Container element, or null if not attached
483
+ */
484
+ getContainer() {
485
+ return this.container;
486
+ }
487
+ /**
488
+ * Check if attached to a container.
489
+ *
490
+ * @returns Whether attached
491
+ */
492
+ isAttached() {
493
+ return this.container !== null;
494
+ }
495
+ /**
496
+ * Stop any ongoing scroll animation.
497
+ */
498
+ stopAnimation() {
499
+ if (this.animationId) {
500
+ cancelRaf(this.animationId);
501
+ this.animationId = null;
502
+ }
503
+ }
504
+ };
505
+
506
+ // src/utils/rect.ts
507
+ function getViewport(element) {
508
+ return {
509
+ width: element.clientWidth,
510
+ height: element.clientHeight,
511
+ scrollWidth: element.scrollWidth,
512
+ scrollHeight: element.scrollHeight
513
+ };
514
+ }
515
+
516
+ // src/kernel/viewport.ts
517
+ var ViewportManager = class {
518
+ constructor() {
519
+ this.viewport = {
520
+ width: 0,
521
+ height: 0,
522
+ scrollWidth: 0,
523
+ scrollHeight: 0
524
+ };
525
+ this.container = null;
526
+ this.resizeObserver = null;
527
+ this.onChangeCallback = null;
528
+ this.throttledHandleResize = null;
529
+ }
530
+ /**
531
+ * Attach to a container element.
532
+ *
533
+ * @param container - Container element to observe
534
+ */
535
+ attach(container) {
536
+ this.detach();
537
+ this.container = container;
538
+ this.viewport = getViewport(container);
539
+ this.throttledHandleResize = throttleRAF(this.handleResize.bind(this));
540
+ this.resizeObserver = new ResizeObserver(this.throttledHandleResize);
541
+ this.resizeObserver.observe(container);
542
+ }
543
+ /**
544
+ * Detach from the current container.
545
+ */
546
+ detach() {
547
+ if (this.resizeObserver) {
548
+ this.resizeObserver.disconnect();
549
+ this.resizeObserver = null;
550
+ }
551
+ if (this.throttledHandleResize) {
552
+ this.throttledHandleResize.cancel();
553
+ this.throttledHandleResize = null;
554
+ }
555
+ this.container = null;
556
+ }
557
+ /**
558
+ * Handle resize observer callback.
559
+ */
560
+ handleResize() {
561
+ if (!this.container) return;
562
+ const previousViewport = { ...this.viewport };
563
+ this.viewport = getViewport(this.container);
564
+ if (previousViewport.width === this.viewport.width && previousViewport.height === this.viewport.height && previousViewport.scrollWidth === this.viewport.scrollWidth && previousViewport.scrollHeight === this.viewport.scrollHeight) {
565
+ return;
566
+ }
567
+ if (this.onChangeCallback) {
568
+ this.onChangeCallback({
569
+ type: "resize",
570
+ viewport: this.viewport,
571
+ previousViewport
572
+ });
573
+ }
574
+ }
575
+ /**
576
+ * Get the current viewport dimensions.
577
+ *
578
+ * @returns Current viewport
579
+ */
580
+ getViewport() {
581
+ return { ...this.viewport };
582
+ }
583
+ /**
584
+ * Force a measurement update.
585
+ *
586
+ * @returns Updated viewport
587
+ */
588
+ measure() {
589
+ if (this.container) {
590
+ const previousViewport = { ...this.viewport };
591
+ this.viewport = getViewport(this.container);
592
+ if ((previousViewport.width !== this.viewport.width || previousViewport.height !== this.viewport.height || previousViewport.scrollWidth !== this.viewport.scrollWidth || previousViewport.scrollHeight !== this.viewport.scrollHeight) && this.onChangeCallback) {
593
+ this.onChangeCallback({
594
+ type: "resize",
595
+ viewport: this.viewport,
596
+ previousViewport
597
+ });
598
+ }
599
+ }
600
+ return { ...this.viewport };
601
+ }
602
+ /**
603
+ * Update the scroll dimensions without triggering a resize event.
604
+ * Used when the content size changes but container size stays the same.
605
+ *
606
+ * @param scrollWidth - New scroll width
607
+ * @param scrollHeight - New scroll height
608
+ */
609
+ updateScrollDimensions(scrollWidth, scrollHeight) {
610
+ this.viewport.scrollWidth = scrollWidth;
611
+ this.viewport.scrollHeight = scrollHeight;
612
+ }
613
+ /**
614
+ * Set callback for viewport changes.
615
+ *
616
+ * @param callback - Callback function
617
+ */
618
+ onChange(callback) {
619
+ this.onChangeCallback = callback;
620
+ }
621
+ /**
622
+ * Get the container element.
623
+ *
624
+ * @returns Container element, or null if not attached
625
+ */
626
+ getContainer() {
627
+ return this.container;
628
+ }
629
+ /**
630
+ * Check if attached to a container.
631
+ *
632
+ * @returns Whether attached
633
+ */
634
+ isAttached() {
635
+ return this.container !== null;
636
+ }
637
+ /**
638
+ * Get the visible width.
639
+ *
640
+ * @returns Visible width
641
+ */
642
+ getWidth() {
643
+ return this.viewport.width;
644
+ }
645
+ /**
646
+ * Get the visible height.
647
+ *
648
+ * @returns Visible height
649
+ */
650
+ getHeight() {
651
+ return this.viewport.height;
652
+ }
653
+ /**
654
+ * Get the total scrollable width.
655
+ *
656
+ * @returns Scroll width
657
+ */
658
+ getScrollWidth() {
659
+ return this.viewport.scrollWidth;
660
+ }
661
+ /**
662
+ * Get the total scrollable height.
663
+ *
664
+ * @returns Scroll height
665
+ */
666
+ getScrollHeight() {
667
+ return this.viewport.scrollHeight;
668
+ }
669
+ };
670
+
671
+ // src/utils/binary-search.ts
672
+ function binarySearch(length, predicate) {
673
+ let low = 0;
674
+ let high = length - 1;
675
+ while (low <= high) {
676
+ const mid = Math.floor((low + high) / 2);
677
+ if (predicate(mid)) {
678
+ high = mid - 1;
679
+ } else {
680
+ low = mid + 1;
681
+ }
682
+ }
683
+ return low;
684
+ }
685
+
686
+ // src/utils/array.ts
687
+ function clamp(value, min, max) {
688
+ return Math.min(Math.max(value, min), max);
689
+ }
690
+
691
+ // src/kernel/measurement-cache.ts
692
+ var MeasurementCache = class {
693
+ /**
694
+ * Create a new measurement cache.
695
+ *
696
+ * @param estimatedHeight - Default estimated height for unmeasured items
697
+ */
698
+ constructor(estimatedHeight) {
699
+ this.cache = /* @__PURE__ */ new Map();
700
+ this.totalMeasured = 0;
701
+ this.sumOfHeights = 0;
702
+ this.estimatedHeight = estimatedHeight;
703
+ }
704
+ /**
705
+ * Get the cached height for an index.
706
+ *
707
+ * @param index - Item index
708
+ * @returns Cached height, or undefined if not measured
709
+ */
710
+ get(index) {
711
+ return this.cache.get(index);
712
+ }
713
+ /**
714
+ * Set the height for an index.
715
+ *
716
+ * @param index - Item index
717
+ * @param height - Measured height
718
+ * @returns Previous height, or undefined if not previously measured
719
+ */
720
+ set(index, height) {
721
+ const previousHeight = this.cache.get(index);
722
+ if (previousHeight !== void 0) {
723
+ this.sumOfHeights = this.sumOfHeights - previousHeight + height;
724
+ } else {
725
+ this.totalMeasured++;
726
+ this.sumOfHeights += height;
727
+ }
728
+ this.cache.set(index, height);
729
+ return previousHeight;
730
+ }
731
+ /**
732
+ * Check if an index has been measured.
733
+ *
734
+ * @param index - Item index
735
+ * @returns Whether the index has a cached measurement
736
+ */
737
+ has(index) {
738
+ return this.cache.has(index);
739
+ }
740
+ /**
741
+ * Delete a cached measurement.
742
+ *
743
+ * @param index - Item index
744
+ * @returns Whether a measurement was deleted
745
+ */
746
+ delete(index) {
747
+ const height = this.cache.get(index);
748
+ if (height !== void 0) {
749
+ this.cache.delete(index);
750
+ this.totalMeasured--;
751
+ this.sumOfHeights -= height;
752
+ return true;
753
+ }
754
+ return false;
755
+ }
756
+ /**
757
+ * Clear all cached measurements.
758
+ */
759
+ clear() {
760
+ this.cache.clear();
761
+ this.totalMeasured = 0;
762
+ this.sumOfHeights = 0;
763
+ }
764
+ /**
765
+ * Get the height for an index, using estimated height if not measured.
766
+ *
767
+ * @param index - Item index
768
+ * @returns Height (measured or estimated)
769
+ */
770
+ getOrEstimate(index) {
771
+ return this.cache.get(index) ?? this.getEstimatedHeight();
772
+ }
773
+ /**
774
+ * Get the average height of measured items.
775
+ * Falls back to estimated height if no measurements.
776
+ *
777
+ * @returns Average height
778
+ */
779
+ getAverageHeight() {
780
+ if (this.totalMeasured === 0) {
781
+ return this.estimatedHeight;
782
+ }
783
+ return this.sumOfHeights / this.totalMeasured;
784
+ }
785
+ /**
786
+ * Get the estimated height.
787
+ * Uses average of measured items if available, otherwise initial estimate.
788
+ *
789
+ * @returns Estimated height
790
+ */
791
+ getEstimatedHeight() {
792
+ if (this.totalMeasured > 0) {
793
+ return this.getAverageHeight();
794
+ }
795
+ return this.estimatedHeight;
796
+ }
797
+ /**
798
+ * Set the base estimated height.
799
+ *
800
+ * @param height - New estimated height
801
+ */
802
+ setEstimatedHeight(height) {
803
+ this.estimatedHeight = height;
804
+ }
805
+ /**
806
+ * Get the number of measured items.
807
+ *
808
+ * @returns Number of measured items
809
+ */
810
+ getMeasuredCount() {
811
+ return this.totalMeasured;
812
+ }
813
+ /**
814
+ * Get all measured indices.
815
+ *
816
+ * @returns Array of measured indices
817
+ */
818
+ getMeasuredIndices() {
819
+ return Array.from(this.cache.keys());
820
+ }
821
+ /**
822
+ * Get the total size (sum of all measured heights).
823
+ *
824
+ * @returns Total measured size
825
+ */
826
+ getTotalMeasuredSize() {
827
+ return this.sumOfHeights;
828
+ }
829
+ /**
830
+ * Shift all indices by an offset.
831
+ * Used when items are added or removed before the measured items.
832
+ *
833
+ * @param startIndex - Index from which to start shifting
834
+ * @param offset - Amount to shift (positive = shift right, negative = shift left)
835
+ */
836
+ shiftIndices(startIndex, offset) {
837
+ if (offset === 0) return;
838
+ const newCache = /* @__PURE__ */ new Map();
839
+ for (const [index, height] of this.cache) {
840
+ if (index >= startIndex) {
841
+ const newIndex = index + offset;
842
+ if (newIndex >= 0) {
843
+ newCache.set(newIndex, height);
844
+ } else {
845
+ this.totalMeasured--;
846
+ this.sumOfHeights -= height;
847
+ }
848
+ } else {
849
+ newCache.set(index, height);
850
+ }
851
+ }
852
+ this.cache = newCache;
853
+ }
854
+ /**
855
+ * Get the internal cache map.
856
+ * Useful for debugging or serialization.
857
+ *
858
+ * @returns The cache map
859
+ */
860
+ getCache() {
861
+ return new Map(this.cache);
862
+ }
863
+ /**
864
+ * Restore cache from a map.
865
+ * Useful for deserialization or restoration.
866
+ *
867
+ * @param cache - Cache map to restore
868
+ */
869
+ restoreCache(cache) {
870
+ this.clear();
871
+ for (const [index, height] of cache) {
872
+ this.set(index, height);
873
+ }
874
+ }
875
+ };
876
+
877
+ // src/kernel/range-calculator.ts
878
+ var RangeCalculator = class {
879
+ /**
880
+ * Create a new range calculator.
881
+ *
882
+ * @param options - Configuration options
883
+ */
884
+ constructor(options) {
885
+ this.offsetCache = [];
886
+ this.dirtyFromIndex = 0;
887
+ this.totalSize = 0;
888
+ this.itemCount = options.itemCount;
889
+ this.overscan = options.overscan;
890
+ this.measurementCache = new MeasurementCache(options.estimatedItemHeight);
891
+ this.rebuildOffsetCache();
892
+ }
893
+ /**
894
+ * Get the visible range of items.
895
+ *
896
+ * @param scrollOffset - Current scroll position
897
+ * @param viewportSize - Size of the visible viewport
898
+ * @returns Visible range with overscan
899
+ */
900
+ getVisibleRange(scrollOffset, viewportSize) {
901
+ if (this.itemCount === 0) {
902
+ return {
903
+ startIndex: 0,
904
+ endIndex: 0,
905
+ overscanStartIndex: 0,
906
+ overscanEndIndex: 0
907
+ };
908
+ }
909
+ this.ensureOffsetCacheValid(this.itemCount - 1);
910
+ const startIndex = this.findStartIndex(scrollOffset);
911
+ const scrollEnd = scrollOffset + viewportSize;
912
+ const endIndex = this.findEndIndex(scrollEnd, startIndex);
913
+ const overscanStartIndex = Math.max(0, startIndex - this.overscan);
914
+ const overscanEndIndex = Math.min(this.itemCount - 1, endIndex + this.overscan);
915
+ return {
916
+ startIndex,
917
+ endIndex,
918
+ overscanStartIndex,
919
+ overscanEndIndex
920
+ };
921
+ }
922
+ /**
923
+ * Find the start index for a given scroll offset.
924
+ */
925
+ findStartIndex(scrollOffset) {
926
+ if (scrollOffset <= 0) return 0;
927
+ const index = binarySearch(this.itemCount, (mid) => {
928
+ const itemEnd = this.getItemEnd(mid);
929
+ return itemEnd > scrollOffset;
930
+ });
931
+ return clamp(index, 0, this.itemCount - 1);
932
+ }
933
+ /**
934
+ * Find the end index for a given scroll end position.
935
+ */
936
+ findEndIndex(scrollEnd, startIndex) {
937
+ if (scrollEnd >= this.totalSize) return this.itemCount - 1;
938
+ let index = startIndex;
939
+ while (index < this.itemCount - 1) {
940
+ const itemStart = this.getItemOffset(index);
941
+ if (itemStart >= scrollEnd) {
942
+ break;
943
+ }
944
+ index++;
945
+ }
946
+ return clamp(index, startIndex, this.itemCount - 1);
947
+ }
948
+ /**
949
+ * Get the offset (start position) of an item.
950
+ *
951
+ * @param index - Item index
952
+ * @returns Offset from start
953
+ */
954
+ getItemOffset(index) {
955
+ if (index < 0 || this.itemCount === 0) return 0;
956
+ if (index >= this.itemCount) return this.totalSize;
957
+ this.ensureOffsetCacheValid(index);
958
+ return this.offsetCache[index] ?? 0;
959
+ }
960
+ /**
961
+ * Get the end position of an item.
962
+ *
963
+ * @param index - Item index
964
+ * @returns End position (offset + size)
965
+ */
966
+ getItemEnd(index) {
967
+ return this.getItemOffset(index) + this.getItemSize(index);
968
+ }
969
+ /**
970
+ * Get the size of an item.
971
+ *
972
+ * @param index - Item index
973
+ * @returns Item size
974
+ */
975
+ getItemSize(index) {
976
+ return this.measurementCache.getOrEstimate(index);
977
+ }
978
+ /**
979
+ * Get the total size of all items.
980
+ *
981
+ * @returns Total size
982
+ */
983
+ getTotalSize() {
984
+ this.ensureOffsetCacheValid(this.itemCount - 1);
985
+ return this.totalSize;
986
+ }
987
+ /**
988
+ * Set the height for an item.
989
+ *
990
+ * @param index - Item index
991
+ * @param height - Item height
992
+ * @returns Previous height, or undefined if not measured
993
+ */
994
+ setItemHeight(index, height) {
995
+ const previousHeight = this.measurementCache.set(index, height);
996
+ this.invalidateFrom(index);
997
+ return previousHeight;
998
+ }
999
+ /**
1000
+ * Get the cached height for an item.
1001
+ *
1002
+ * @param index - Item index
1003
+ * @returns Cached height, or undefined if not measured
1004
+ */
1005
+ getCachedHeight(index) {
1006
+ return this.measurementCache.get(index);
1007
+ }
1008
+ /**
1009
+ * Invalidate measurement for an item.
1010
+ *
1011
+ * @param index - Item index
1012
+ */
1013
+ invalidate(index) {
1014
+ if (this.measurementCache.delete(index)) {
1015
+ this.invalidateFrom(index);
1016
+ }
1017
+ }
1018
+ /**
1019
+ * Invalidate all measurements.
1020
+ */
1021
+ invalidateAll() {
1022
+ this.measurementCache.clear();
1023
+ this.dirtyFromIndex = 0;
1024
+ this.rebuildOffsetCache();
1025
+ }
1026
+ /**
1027
+ * Mark offset cache as dirty from a specific index.
1028
+ */
1029
+ invalidateFrom(index) {
1030
+ this.dirtyFromIndex = Math.min(this.dirtyFromIndex, index);
1031
+ }
1032
+ /**
1033
+ * Ensure offset cache is valid up to the given index.
1034
+ */
1035
+ ensureOffsetCacheValid(upToIndex) {
1036
+ if (this.dirtyFromIndex > upToIndex) return;
1037
+ let offset = this.dirtyFromIndex === 0 ? 0 : (this.offsetCache[this.dirtyFromIndex - 1] ?? 0) + this.getItemSize(this.dirtyFromIndex - 1);
1038
+ for (let i = this.dirtyFromIndex; i <= upToIndex && i < this.itemCount; i++) {
1039
+ this.offsetCache[i] = offset;
1040
+ offset += this.getItemSize(i);
1041
+ }
1042
+ if (upToIndex >= this.itemCount - 1) {
1043
+ this.totalSize = offset;
1044
+ }
1045
+ this.dirtyFromIndex = upToIndex + 1;
1046
+ }
1047
+ /**
1048
+ * Rebuild the entire offset cache.
1049
+ */
1050
+ rebuildOffsetCache() {
1051
+ this.offsetCache = new Array(this.itemCount);
1052
+ this.dirtyFromIndex = 0;
1053
+ if (this.itemCount > 0) {
1054
+ this.ensureOffsetCacheValid(this.itemCount - 1);
1055
+ } else {
1056
+ this.totalSize = 0;
1057
+ }
1058
+ }
1059
+ /**
1060
+ * Update item count.
1061
+ *
1062
+ * @param count - New item count
1063
+ */
1064
+ setItemCount(count) {
1065
+ if (count === this.itemCount) return;
1066
+ const previousCount = this.itemCount;
1067
+ this.itemCount = count;
1068
+ if (count < previousCount) {
1069
+ this.offsetCache.length = count;
1070
+ if (count > 0) {
1071
+ const lastIndex = count - 1;
1072
+ this.dirtyFromIndex = Math.min(this.dirtyFromIndex, lastIndex);
1073
+ this.ensureOffsetCacheValid(lastIndex);
1074
+ } else {
1075
+ this.totalSize = 0;
1076
+ }
1077
+ } else {
1078
+ this.offsetCache.length = count;
1079
+ if (this.dirtyFromIndex > previousCount) {
1080
+ this.dirtyFromIndex = previousCount;
1081
+ }
1082
+ }
1083
+ }
1084
+ /**
1085
+ * Update overscan amount.
1086
+ *
1087
+ * @param overscan - New overscan value
1088
+ */
1089
+ setOverscan(overscan) {
1090
+ this.overscan = overscan;
1091
+ }
1092
+ /**
1093
+ * Update estimated item height.
1094
+ *
1095
+ * @param height - New estimated height
1096
+ */
1097
+ setEstimatedHeight(height) {
1098
+ this.measurementCache.setEstimatedHeight(height);
1099
+ this.dirtyFromIndex = 0;
1100
+ }
1101
+ /**
1102
+ * Get the estimated item height.
1103
+ *
1104
+ * @returns Estimated height
1105
+ */
1106
+ getEstimatedHeight() {
1107
+ return this.measurementCache.getEstimatedHeight();
1108
+ }
1109
+ /**
1110
+ * Get the item index at a given offset.
1111
+ *
1112
+ * @param offset - Offset position
1113
+ * @returns Item index at that offset
1114
+ */
1115
+ getItemAtOffset(offset) {
1116
+ if (offset <= 0 || this.itemCount === 0) return 0;
1117
+ if (offset >= this.totalSize) return this.itemCount - 1;
1118
+ this.ensureOffsetCacheValid(this.itemCount - 1);
1119
+ return binarySearch(this.itemCount, (mid) => {
1120
+ const itemEnd = this.getItemEnd(mid);
1121
+ return itemEnd > offset;
1122
+ });
1123
+ }
1124
+ /**
1125
+ * Get the measurement cache.
1126
+ *
1127
+ * @returns Measurement cache
1128
+ */
1129
+ getMeasurementCache() {
1130
+ return this.measurementCache;
1131
+ }
1132
+ /**
1133
+ * Get current item count.
1134
+ *
1135
+ * @returns Item count
1136
+ */
1137
+ getItemCount() {
1138
+ return this.itemCount;
1139
+ }
1140
+ };
1141
+
1142
+ // src/kernel/plugin-registry.ts
1143
+ var PluginRegistry = class {
1144
+ constructor() {
1145
+ this.plugins = /* @__PURE__ */ new Map();
1146
+ this.kernel = null;
1147
+ this.hookSubscriptions = /* @__PURE__ */ new Map();
1148
+ }
1149
+ /**
1150
+ * Set the kernel instance.
1151
+ *
1152
+ * @param kernel - Kernel instance
1153
+ */
1154
+ setKernel(kernel) {
1155
+ this.kernel = kernel;
1156
+ }
1157
+ /**
1158
+ * Register a plugin.
1159
+ *
1160
+ * @param plugin - Plugin to register
1161
+ * @throws Error if plugin with same name already registered
1162
+ */
1163
+ register(plugin) {
1164
+ this.validatePlugin(plugin);
1165
+ if (this.plugins.has(plugin.name)) {
1166
+ throw new Error(
1167
+ `[Scrollex] Plugin "${plugin.name}" is already registered. Unregister the existing plugin first.`
1168
+ );
1169
+ }
1170
+ this.plugins.set(plugin.name, plugin);
1171
+ if (this.kernel && plugin.install) {
1172
+ plugin.install(this.kernel);
1173
+ this.setupHooks(plugin);
1174
+ }
1175
+ }
1176
+ /**
1177
+ * Unregister a plugin by name.
1178
+ *
1179
+ * @param name - Plugin name to unregister
1180
+ * @returns Whether a plugin was unregistered
1181
+ */
1182
+ unregister(name) {
1183
+ const plugin = this.plugins.get(name);
1184
+ if (!plugin) {
1185
+ return false;
1186
+ }
1187
+ this.teardownHooks(plugin);
1188
+ plugin.uninstall?.();
1189
+ this.plugins.delete(name);
1190
+ return true;
1191
+ }
1192
+ /**
1193
+ * Get a plugin by name.
1194
+ *
1195
+ * @param name - Plugin name
1196
+ * @returns Plugin instance, or undefined if not found
1197
+ */
1198
+ get(name) {
1199
+ return this.plugins.get(name);
1200
+ }
1201
+ /**
1202
+ * Check if a plugin is registered.
1203
+ *
1204
+ * @param name - Plugin name
1205
+ * @returns Whether plugin is registered
1206
+ */
1207
+ has(name) {
1208
+ return this.plugins.has(name);
1209
+ }
1210
+ /**
1211
+ * List all registered plugins.
1212
+ *
1213
+ * @returns Array of plugin info
1214
+ */
1215
+ list() {
1216
+ return Array.from(this.plugins.values()).map((plugin) => ({
1217
+ name: plugin.name,
1218
+ version: plugin.version,
1219
+ type: plugin.type,
1220
+ enabled: true
1221
+ }));
1222
+ }
1223
+ /**
1224
+ * Get all registered plugins.
1225
+ *
1226
+ * @returns Array of plugins
1227
+ */
1228
+ getAll() {
1229
+ return Array.from(this.plugins.values());
1230
+ }
1231
+ /**
1232
+ * Validate a plugin before registration.
1233
+ */
1234
+ validatePlugin(plugin) {
1235
+ if (!plugin.name || typeof plugin.name !== "string") {
1236
+ throw new Error("[Scrollex] Plugin must have a name");
1237
+ }
1238
+ if (!plugin.version || typeof plugin.version !== "string") {
1239
+ throw new Error(`[Scrollex] Plugin "${plugin.name}" must have a version`);
1240
+ }
1241
+ if (plugin.type !== "core" && plugin.type !== "optional") {
1242
+ throw new Error(
1243
+ `[Scrollex] Plugin "${plugin.name}" type must be "core" or "optional"`
1244
+ );
1245
+ }
1246
+ if (typeof plugin.install !== "function") {
1247
+ throw new Error(`[Scrollex] Plugin "${plugin.name}" must have an install method`);
1248
+ }
1249
+ if (typeof plugin.uninstall !== "function") {
1250
+ throw new Error(`[Scrollex] Plugin "${plugin.name}" must have an uninstall method`);
1251
+ }
1252
+ }
1253
+ /**
1254
+ * Set up hooks for a plugin.
1255
+ */
1256
+ setupHooks(plugin) {
1257
+ if (!plugin.hooks || !this.kernel) return;
1258
+ const subscriptions = [];
1259
+ const hooks = plugin.hooks;
1260
+ const k = this.kernel;
1261
+ if (hooks.onScroll) {
1262
+ const handler = hooks.onScroll;
1263
+ const unsub = k.on("scroll", ((event) => {
1264
+ if (event.type === "scroll") handler(event);
1265
+ }));
1266
+ subscriptions.push(unsub);
1267
+ }
1268
+ if (hooks.onScrollStart) {
1269
+ const handler = hooks.onScrollStart;
1270
+ const unsub = k.on("scroll-start", ((event) => {
1271
+ if (event.type === "scroll-start") handler(event);
1272
+ }));
1273
+ subscriptions.push(unsub);
1274
+ }
1275
+ if (hooks.onScrollEnd) {
1276
+ const handler = hooks.onScrollEnd;
1277
+ const unsub = k.on("scroll-end", ((event) => {
1278
+ if (event.type === "scroll-end") handler(event);
1279
+ }));
1280
+ subscriptions.push(unsub);
1281
+ }
1282
+ if (hooks.onVisibleRangeChange) {
1283
+ const handler = hooks.onVisibleRangeChange;
1284
+ const unsub = k.on("visible-range-change", ((event) => {
1285
+ if (event.type === "visible-range-change") {
1286
+ const e = event;
1287
+ handler(e.range, e.previousRange);
1288
+ }
1289
+ }));
1290
+ subscriptions.push(unsub);
1291
+ }
1292
+ if (hooks.onItemMeasured) {
1293
+ const handler = hooks.onItemMeasured;
1294
+ const unsub = k.on("item-measured", ((event) => {
1295
+ if (event.type === "item-measured") {
1296
+ const e = event;
1297
+ handler(e.index, e.height);
1298
+ }
1299
+ }));
1300
+ subscriptions.push(unsub);
1301
+ }
1302
+ if (hooks.onResize) {
1303
+ const handler = hooks.onResize;
1304
+ const unsub = k.on("resize", ((event) => {
1305
+ if (event.type === "resize") {
1306
+ const e = event;
1307
+ handler(e.viewport);
1308
+ }
1309
+ }));
1310
+ subscriptions.push(unsub);
1311
+ }
1312
+ if (hooks.onLoadMore) {
1313
+ const handler = hooks.onLoadMore;
1314
+ const unsub = k.on("load-more", ((event) => {
1315
+ if (event.type === "load-more") {
1316
+ const e = event;
1317
+ handler(e.direction);
1318
+ }
1319
+ }));
1320
+ subscriptions.push(unsub);
1321
+ }
1322
+ if (hooks.onItemsChange) {
1323
+ const handler = hooks.onItemsChange;
1324
+ const unsub = k.on("items-change", ((event) => {
1325
+ if (event.type === "items-change") {
1326
+ const e = event;
1327
+ handler(e.count, e.previousCount);
1328
+ }
1329
+ }));
1330
+ subscriptions.push(unsub);
1331
+ }
1332
+ if (subscriptions.length > 0) {
1333
+ this.hookSubscriptions.set(plugin.name, subscriptions);
1334
+ }
1335
+ }
1336
+ /**
1337
+ * Tear down hooks for a plugin.
1338
+ */
1339
+ teardownHooks(plugin) {
1340
+ const subscriptions = this.hookSubscriptions.get(plugin.name);
1341
+ if (subscriptions) {
1342
+ for (const unsub of subscriptions) {
1343
+ unsub();
1344
+ }
1345
+ this.hookSubscriptions.delete(plugin.name);
1346
+ }
1347
+ }
1348
+ /**
1349
+ * Dispatch a hook to all plugins that implement it.
1350
+ *
1351
+ * @param hookName - Name of the hook
1352
+ * @param args - Arguments to pass to the hook
1353
+ */
1354
+ dispatchHook(hookName, ...args) {
1355
+ for (const plugin of this.plugins.values()) {
1356
+ const hook = plugin.hooks?.[hookName];
1357
+ if (hook) {
1358
+ try {
1359
+ ;
1360
+ hook(...args);
1361
+ } catch (error) {
1362
+ console.error(
1363
+ `[Scrollex] Error in plugin "${plugin.name}" hook "${String(hookName)}":`,
1364
+ error
1365
+ );
1366
+ }
1367
+ }
1368
+ }
1369
+ }
1370
+ /**
1371
+ * Unregister all plugins.
1372
+ */
1373
+ clear() {
1374
+ const names = Array.from(this.plugins.keys()).reverse();
1375
+ for (const name of names) {
1376
+ this.unregister(name);
1377
+ }
1378
+ }
1379
+ /**
1380
+ * Get the number of registered plugins.
1381
+ *
1382
+ * @returns Number of plugins
1383
+ */
1384
+ size() {
1385
+ return this.plugins.size;
1386
+ }
1387
+ };
1388
+
1389
+ // src/kernel/kernel.ts
1390
+ var DEFAULT_OPTIONS = {
1391
+ itemCount: 0,
1392
+ estimatedItemHeight: 50,
1393
+ overscan: 5,
1394
+ direction: "vertical",
1395
+ getItemKey: (index) => index
1396
+ };
1397
+ function createKernel(options = {}) {
1398
+ const config = { ...DEFAULT_OPTIONS, ...options };
1399
+ const eventBus = new EventBus();
1400
+ const scrollEngine = new ScrollEngine();
1401
+ const viewportManager = new ViewportManager();
1402
+ const rangeCalculator = new RangeCalculator({
1403
+ itemCount: config.itemCount,
1404
+ estimatedItemHeight: config.estimatedItemHeight,
1405
+ overscan: config.overscan
1406
+ });
1407
+ const pluginRegistry = new PluginRegistry();
1408
+ let currentRange = {
1409
+ startIndex: 0,
1410
+ endIndex: 0,
1411
+ overscanStartIndex: 0,
1412
+ overscanEndIndex: 0
1413
+ };
1414
+ let attached = false;
1415
+ const kernel = {
1416
+ // Plugin Management
1417
+ register(plugin) {
1418
+ pluginRegistry.register(plugin);
1419
+ },
1420
+ unregister(pluginName) {
1421
+ pluginRegistry.unregister(pluginName);
1422
+ },
1423
+ getPlugin(name) {
1424
+ return pluginRegistry.get(name);
1425
+ },
1426
+ listPlugins() {
1427
+ return pluginRegistry.list();
1428
+ },
1429
+ // Scroll Control
1430
+ getScrollPosition() {
1431
+ return scrollEngine.getScrollPosition();
1432
+ },
1433
+ setScrollPosition(position) {
1434
+ scrollEngine.setScrollPosition(position);
1435
+ },
1436
+ scrollTo(offset, options2) {
1437
+ scrollEngine.scrollTo(offset, options2);
1438
+ },
1439
+ scrollToIndex(index, options2 = {}) {
1440
+ const { align = "auto", offset: additionalOffset = 0, ...scrollOptions } = options2;
1441
+ const itemOffset = rangeCalculator.getItemOffset(index);
1442
+ const itemSize = rangeCalculator.getItemSize(index);
1443
+ const viewport = viewportManager.getViewport();
1444
+ let targetOffset;
1445
+ switch (align) {
1446
+ case "start":
1447
+ targetOffset = itemOffset;
1448
+ break;
1449
+ case "center":
1450
+ targetOffset = itemOffset - viewport.height / 2 + itemSize / 2;
1451
+ break;
1452
+ case "end":
1453
+ targetOffset = itemOffset - viewport.height + itemSize;
1454
+ break;
1455
+ case "auto":
1456
+ default: {
1457
+ const scrollPosition = scrollEngine.getScrollPosition();
1458
+ const visibleStart = scrollPosition.scrollTop;
1459
+ const visibleEnd = visibleStart + viewport.height;
1460
+ const itemEnd = itemOffset + itemSize;
1461
+ if (itemOffset < visibleStart) {
1462
+ targetOffset = itemOffset;
1463
+ } else if (itemEnd > visibleEnd) {
1464
+ targetOffset = itemEnd - viewport.height;
1465
+ } else {
1466
+ return;
1467
+ }
1468
+ break;
1469
+ }
1470
+ }
1471
+ const maxScroll = Math.max(0, rangeCalculator.getTotalSize() - viewport.height);
1472
+ targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
1473
+ scrollEngine.scrollTo(targetOffset, scrollOptions);
1474
+ },
1475
+ // Viewport
1476
+ getViewport() {
1477
+ return viewportManager.getViewport();
1478
+ },
1479
+ getVisibleRange() {
1480
+ return { ...currentRange };
1481
+ },
1482
+ getRenderRange() {
1483
+ return {
1484
+ startIndex: currentRange.overscanStartIndex,
1485
+ endIndex: currentRange.overscanEndIndex,
1486
+ overscanStartIndex: currentRange.overscanStartIndex,
1487
+ overscanEndIndex: currentRange.overscanEndIndex,
1488
+ start: currentRange.overscanStartIndex,
1489
+ end: currentRange.overscanEndIndex
1490
+ };
1491
+ },
1492
+ // Measurement
1493
+ measureItem(index, size) {
1494
+ const previousHeight = rangeCalculator.setItemHeight(index, size);
1495
+ eventBus.emit({
1496
+ type: "item-measured",
1497
+ index,
1498
+ height: size,
1499
+ previousHeight
1500
+ });
1501
+ updateVisibleRange();
1502
+ },
1503
+ getCachedHeight(index) {
1504
+ return rangeCalculator.getCachedHeight(index);
1505
+ },
1506
+ invalidateMeasurement(index) {
1507
+ rangeCalculator.invalidate(index);
1508
+ updateVisibleRange();
1509
+ },
1510
+ invalidateAllMeasurements() {
1511
+ rangeCalculator.invalidateAll();
1512
+ updateVisibleRange();
1513
+ },
1514
+ getEstimatedHeight() {
1515
+ return rangeCalculator.getEstimatedHeight();
1516
+ },
1517
+ getItemOffset(index) {
1518
+ return rangeCalculator.getItemOffset(index);
1519
+ },
1520
+ // Events
1521
+ emit(event) {
1522
+ eventBus.emit(event);
1523
+ },
1524
+ on(eventType, handler) {
1525
+ return eventBus.on(eventType, handler);
1526
+ },
1527
+ off(eventType, handler) {
1528
+ eventBus.off(eventType, handler);
1529
+ },
1530
+ // Configuration
1531
+ configure(newOptions) {
1532
+ const previousCount = config.itemCount;
1533
+ if (newOptions.itemCount !== void 0) {
1534
+ config.itemCount = newOptions.itemCount;
1535
+ rangeCalculator.setItemCount(newOptions.itemCount);
1536
+ if (newOptions.itemCount !== previousCount) {
1537
+ eventBus.emit({
1538
+ type: "items-change",
1539
+ count: newOptions.itemCount,
1540
+ previousCount
1541
+ });
1542
+ }
1543
+ }
1544
+ if (newOptions.estimatedItemHeight !== void 0) {
1545
+ config.estimatedItemHeight = newOptions.estimatedItemHeight;
1546
+ rangeCalculator.setEstimatedHeight(newOptions.estimatedItemHeight);
1547
+ }
1548
+ if (newOptions.overscan !== void 0) {
1549
+ config.overscan = newOptions.overscan;
1550
+ rangeCalculator.setOverscan(newOptions.overscan);
1551
+ }
1552
+ if (newOptions.direction !== void 0) {
1553
+ config.direction = newOptions.direction;
1554
+ }
1555
+ if (newOptions.getItemKey !== void 0) {
1556
+ config.getItemKey = newOptions.getItemKey;
1557
+ }
1558
+ updateVisibleRange();
1559
+ },
1560
+ getOptions() {
1561
+ return { ...config };
1562
+ },
1563
+ // State
1564
+ isScrolling() {
1565
+ return scrollEngine.isScrolling();
1566
+ },
1567
+ getItemCount() {
1568
+ return config.itemCount;
1569
+ },
1570
+ getTotalSize() {
1571
+ return rangeCalculator.getTotalSize();
1572
+ },
1573
+ // Lifecycle
1574
+ attach(container) {
1575
+ if (attached) {
1576
+ kernel.detach();
1577
+ }
1578
+ scrollEngine.attach(container);
1579
+ viewportManager.attach(container);
1580
+ attached = true;
1581
+ scrollEngine.onScroll((event) => {
1582
+ eventBus.emit(event);
1583
+ updateVisibleRange();
1584
+ });
1585
+ scrollEngine.onScrollStart((event) => {
1586
+ eventBus.emit(event);
1587
+ });
1588
+ scrollEngine.onScrollEnd((event) => {
1589
+ eventBus.emit(event);
1590
+ });
1591
+ viewportManager.onChange((event) => {
1592
+ eventBus.emit(event);
1593
+ updateVisibleRange();
1594
+ });
1595
+ updateVisibleRange();
1596
+ },
1597
+ detach() {
1598
+ scrollEngine.detach();
1599
+ viewportManager.detach();
1600
+ attached = false;
1601
+ },
1602
+ destroy() {
1603
+ kernel.detach();
1604
+ pluginRegistry.clear();
1605
+ eventBus.clear();
1606
+ }
1607
+ };
1608
+ pluginRegistry.setKernel(kernel);
1609
+ function updateVisibleRange() {
1610
+ if (!attached) return;
1611
+ const viewport = viewportManager.getViewport();
1612
+ const scrollPosition = scrollEngine.getScrollPosition();
1613
+ const scrollOffset = config.direction === "vertical" ? scrollPosition.scrollTop : scrollPosition.scrollLeft;
1614
+ const viewportSize = config.direction === "vertical" ? viewport.height : viewport.width;
1615
+ const previousRange = { ...currentRange };
1616
+ currentRange = rangeCalculator.getVisibleRange(scrollOffset, viewportSize);
1617
+ if (currentRange.startIndex !== previousRange.startIndex || currentRange.endIndex !== previousRange.endIndex || currentRange.overscanStartIndex !== previousRange.overscanStartIndex || currentRange.overscanEndIndex !== previousRange.overscanEndIndex) {
1618
+ eventBus.emit({
1619
+ type: "visible-range-change",
1620
+ range: currentRange,
1621
+ previousRange
1622
+ });
1623
+ }
1624
+ }
1625
+ return kernel;
1626
+ }
1627
+ function createPlugin(config) {
1628
+ return {
1629
+ name: config.name,
1630
+ version: config.version,
1631
+ type: config.type,
1632
+ hooks: config.hooks,
1633
+ api: config.api,
1634
+ install(kernel) {
1635
+ config.install(kernel);
1636
+ },
1637
+ uninstall() {
1638
+ config.uninstall?.();
1639
+ }
1640
+ };
1641
+ }
1642
+
1643
+ // src/plugins/core/list-renderer.ts
1644
+ var VirtualItemPool = class {
1645
+ constructor() {
1646
+ this.pool = [];
1647
+ }
1648
+ acquire() {
1649
+ const item = this.pool.pop();
1650
+ if (item) {
1651
+ return item;
1652
+ }
1653
+ return { index: 0, key: 0, start: 0, end: 0, size: 0, lane: 0 };
1654
+ }
1655
+ release(item) {
1656
+ item.index = 0;
1657
+ item.key = 0;
1658
+ item.start = 0;
1659
+ item.end = 0;
1660
+ item.size = 0;
1661
+ item.lane = 0;
1662
+ this.pool.push(item);
1663
+ }
1664
+ releaseAll(items) {
1665
+ for (const item of items) {
1666
+ this.release(item);
1667
+ }
1668
+ }
1669
+ };
1670
+ function listRendererPlugin(options = {}) {
1671
+ const { getItemKey = (index) => index } = options;
1672
+ let kernel = null;
1673
+ let virtualItems = [];
1674
+ let currentRange = {
1675
+ startIndex: 0,
1676
+ endIndex: 0,
1677
+ overscanStartIndex: 0,
1678
+ overscanEndIndex: 0
1679
+ };
1680
+ const itemPool = new VirtualItemPool();
1681
+ function buildVirtualItems(range) {
1682
+ if (!kernel) return [];
1683
+ itemPool.releaseAll(virtualItems);
1684
+ const items = [];
1685
+ range.startIndex;
1686
+ range.endIndex;
1687
+ for (let i = range.overscanStartIndex; i <= range.overscanEndIndex; i++) {
1688
+ const item = itemPool.acquire();
1689
+ const offset = kernel.getItemOffset(i);
1690
+ const size = kernel.getCachedHeight(i) ?? kernel.getEstimatedHeight();
1691
+ item.index = i;
1692
+ item.key = getItemKey(i);
1693
+ item.start = offset;
1694
+ item.end = offset + size;
1695
+ item.size = size;
1696
+ item.lane = 0;
1697
+ items.push(item);
1698
+ }
1699
+ return items;
1700
+ }
1701
+ function recalculate() {
1702
+ if (!kernel) return;
1703
+ currentRange = kernel.getVisibleRange();
1704
+ virtualItems = buildVirtualItems(currentRange);
1705
+ }
1706
+ const api = {
1707
+ getVirtualItems() {
1708
+ return virtualItems;
1709
+ },
1710
+ getTotalHeight() {
1711
+ return kernel?.getTotalSize() ?? 0;
1712
+ },
1713
+ getStartOffset() {
1714
+ if (virtualItems.length === 0) return 0;
1715
+ return virtualItems[0]?.start ?? 0;
1716
+ },
1717
+ getEndOffset() {
1718
+ if (virtualItems.length === 0) return 0;
1719
+ const lastItem = virtualItems[virtualItems.length - 1];
1720
+ return lastItem?.end ?? 0;
1721
+ },
1722
+ isItemVisible(index) {
1723
+ return index >= currentRange.startIndex && index <= currentRange.endIndex;
1724
+ },
1725
+ recalculate
1726
+ };
1727
+ return {
1728
+ name: "list-renderer",
1729
+ version: "1.0.0",
1730
+ type: "core",
1731
+ install(k) {
1732
+ kernel = k;
1733
+ recalculate();
1734
+ },
1735
+ uninstall() {
1736
+ itemPool.releaseAll(virtualItems);
1737
+ virtualItems = [];
1738
+ kernel = null;
1739
+ },
1740
+ hooks: {
1741
+ onScroll: () => recalculate(),
1742
+ onResize: () => recalculate(),
1743
+ onItemMeasured: () => recalculate(),
1744
+ onVisibleRangeChange: (range) => {
1745
+ currentRange = range;
1746
+ virtualItems = buildVirtualItems(range);
1747
+ },
1748
+ onItemsChange: () => recalculate()
1749
+ },
1750
+ api
1751
+ };
1752
+ }
1753
+
1754
+ // src/react/hooks/use-virtual-list.ts
1755
+ function useVirtualList(options) {
1756
+ const {
1757
+ count,
1758
+ getItemHeight,
1759
+ estimatedItemHeight = 50,
1760
+ overscan = 5,
1761
+ paddingStart = 0,
1762
+ paddingEnd = 0,
1763
+ initialOffset = 0,
1764
+ getItemKey = (index) => index,
1765
+ horizontal = false,
1766
+ containerRef
1767
+ } = options;
1768
+ const kernelRef = useRef(
1769
+ createKernel({
1770
+ itemCount: count,
1771
+ estimatedItemHeight,
1772
+ overscan,
1773
+ direction: horizontal ? "horizontal" : "vertical",
1774
+ getItemKey
1775
+ })
1776
+ );
1777
+ const [virtualItems, setVirtualItems] = useState([]);
1778
+ const [isScrolling, setIsScrolling] = useState(false);
1779
+ const [scrollOffset, setScrollOffset] = useState(initialOffset);
1780
+ const [range, setRange] = useState({
1781
+ startIndex: 0,
1782
+ endIndex: 0,
1783
+ overscanStartIndex: 0,
1784
+ overscanEndIndex: 0
1785
+ });
1786
+ const listRendererRef = useRef(null);
1787
+ const measurementRefs = useRef(/* @__PURE__ */ new Map());
1788
+ const resizeObserverRef = useRef(null);
1789
+ const kernel = kernelRef.current;
1790
+ useEffect(() => {
1791
+ const plugin = listRendererPlugin({ getItemKey });
1792
+ kernel.register(plugin);
1793
+ listRendererRef.current = plugin.api;
1794
+ const unsubScroll = kernel.on("scroll", (event) => {
1795
+ const e = event;
1796
+ setScrollOffset(horizontal ? e.scrollLeft : e.scrollTop);
1797
+ });
1798
+ const unsubScrollStart = kernel.on("scroll-start", () => {
1799
+ setIsScrolling(true);
1800
+ });
1801
+ const unsubScrollEnd = kernel.on("scroll-end", () => {
1802
+ setIsScrolling(false);
1803
+ });
1804
+ const unsubRangeChange = kernel.on("visible-range-change", (event) => {
1805
+ const e = event;
1806
+ setRange(e.range);
1807
+ setVirtualItems(listRendererRef.current?.getVirtualItems() ?? []);
1808
+ });
1809
+ return () => {
1810
+ unsubScroll();
1811
+ unsubScrollStart();
1812
+ unsubScrollEnd();
1813
+ unsubRangeChange();
1814
+ kernel.destroy();
1815
+ };
1816
+ }, []);
1817
+ useEffect(() => {
1818
+ const container = containerRef.current;
1819
+ if (!container) return;
1820
+ kernel.attach(container);
1821
+ if (initialOffset > 0) {
1822
+ kernel.scrollTo(initialOffset);
1823
+ }
1824
+ return () => {
1825
+ kernel.detach();
1826
+ };
1827
+ }, [containerRef, kernel, initialOffset]);
1828
+ useEffect(() => {
1829
+ kernel.configure({ itemCount: count });
1830
+ }, [count, kernel]);
1831
+ useEffect(() => {
1832
+ kernel.configure({ overscan });
1833
+ }, [overscan, kernel]);
1834
+ useEffect(() => {
1835
+ const observer = new ResizeObserver((entries) => {
1836
+ for (const entry of entries) {
1837
+ const element = entry.target;
1838
+ const index = parseInt(element.dataset["virtualIndex"] ?? "", 10);
1839
+ if (!isNaN(index)) {
1840
+ const rect = entry.contentRect;
1841
+ const size = horizontal ? rect.width : rect.height;
1842
+ if (size > 0) {
1843
+ kernel.measureItem(index, size);
1844
+ }
1845
+ }
1846
+ }
1847
+ });
1848
+ resizeObserverRef.current = observer;
1849
+ return () => {
1850
+ observer.disconnect();
1851
+ };
1852
+ }, [kernel, horizontal]);
1853
+ const measureElement = useCallback(
1854
+ (index, element) => {
1855
+ const observer = resizeObserverRef.current;
1856
+ const refs = measurementRefs.current;
1857
+ const oldElement = refs.get(index);
1858
+ if (oldElement && oldElement !== element) {
1859
+ observer?.unobserve(oldElement);
1860
+ refs.delete(index);
1861
+ }
1862
+ if (element) {
1863
+ element.dataset["virtualIndex"] = String(index);
1864
+ refs.set(index, element);
1865
+ observer?.observe(element);
1866
+ if (getItemHeight) {
1867
+ const size = getItemHeight(index);
1868
+ kernel.measureItem(index, size);
1869
+ } else {
1870
+ const rect = element.getBoundingClientRect();
1871
+ const size = horizontal ? rect.width : rect.height;
1872
+ if (size > 0) {
1873
+ kernel.measureItem(index, size);
1874
+ }
1875
+ }
1876
+ }
1877
+ },
1878
+ [kernel, horizontal, getItemHeight]
1879
+ );
1880
+ const scrollTo = useCallback(
1881
+ (offset, scrollOptions) => {
1882
+ kernel.scrollTo(offset, scrollOptions);
1883
+ },
1884
+ [kernel]
1885
+ );
1886
+ const scrollToIndex = useCallback(
1887
+ (index, scrollOptions) => {
1888
+ kernel.scrollToIndex(index, scrollOptions);
1889
+ },
1890
+ [kernel]
1891
+ );
1892
+ const getMeasurement = useCallback(
1893
+ (index) => kernel.getCachedHeight(index),
1894
+ [kernel]
1895
+ );
1896
+ const invalidateMeasurement = useCallback(
1897
+ (index) => kernel.invalidateMeasurement(index),
1898
+ [kernel]
1899
+ );
1900
+ const invalidateAllMeasurements = useCallback(
1901
+ () => kernel.invalidateAllMeasurements(),
1902
+ [kernel]
1903
+ );
1904
+ const totalSize = useMemo(() => {
1905
+ return paddingStart + kernel.getTotalSize() + paddingEnd;
1906
+ }, [kernel, paddingStart, paddingEnd, virtualItems]);
1907
+ return {
1908
+ virtualItems,
1909
+ totalSize,
1910
+ scrollOffset,
1911
+ isScrolling,
1912
+ scrollTo,
1913
+ scrollToIndex,
1914
+ measureElement,
1915
+ range,
1916
+ getMeasurement,
1917
+ invalidateMeasurement,
1918
+ invalidateAllMeasurements
1919
+ };
1920
+ }
1921
+ var ScrollexContext = createContext(null);
1922
+ function useScrollex() {
1923
+ const context = useContext(ScrollexContext);
1924
+ return context?.kernel ?? null;
1925
+ }
1926
+ function useScrollexRequired() {
1927
+ const context = useContext(ScrollexContext);
1928
+ if (!context) {
1929
+ throw new Error(
1930
+ "[Scrollex] useScrollexRequired must be used within a Scrollex component. Make sure you are rendering this component inside VirtualList, VirtualGrid, or VirtualMasonry."
1931
+ );
1932
+ }
1933
+ return context.kernel;
1934
+ }
1935
+ function VirtualListInner(props, ref) {
1936
+ const {
1937
+ data,
1938
+ renderItem,
1939
+ itemHeight,
1940
+ estimatedItemHeight = 50,
1941
+ height = "100%",
1942
+ width = "100%",
1943
+ direction = "vertical",
1944
+ overscan = 5,
1945
+ initialScrollOffset = 0,
1946
+ getItemKey,
1947
+ onLoadMore,
1948
+ hasMore = false,
1949
+ isLoading = false,
1950
+ loadingIndicator,
1951
+ threshold = 200,
1952
+ onScroll,
1953
+ onVisibleRangeChange,
1954
+ onItemsRendered,
1955
+ plugins = [],
1956
+ className,
1957
+ style,
1958
+ innerClassName,
1959
+ innerStyle,
1960
+ itemClassName,
1961
+ itemStyle,
1962
+ role = "listbox",
1963
+ ariaLabel,
1964
+ tabIndex,
1965
+ ...restProps
1966
+ } = props;
1967
+ const containerRef = useRef(null);
1968
+ const {
1969
+ virtualItems,
1970
+ totalSize,
1971
+ scrollTo,
1972
+ scrollToIndex,
1973
+ measureElement,
1974
+ isScrolling,
1975
+ range
1976
+ } = useVirtualList({
1977
+ count: data.length,
1978
+ getItemHeight: itemHeight === "auto" ? void 0 : () => itemHeight,
1979
+ estimatedItemHeight: itemHeight === "auto" ? estimatedItemHeight : itemHeight,
1980
+ overscan,
1981
+ initialOffset: initialScrollOffset,
1982
+ getItemKey: getItemKey ? (index) => getItemKey(index, data) : void 0,
1983
+ horizontal: direction === "horizontal",
1984
+ containerRef
1985
+ });
1986
+ const kernelRef = useRef(createKernel({
1987
+ itemCount: data.length,
1988
+ estimatedItemHeight: itemHeight === "auto" ? estimatedItemHeight : itemHeight,
1989
+ overscan,
1990
+ direction
1991
+ }));
1992
+ useImperativeHandle(ref, () => ({
1993
+ scrollTo: (offset, options) => scrollTo(offset, options),
1994
+ scrollToIndex: (index, options) => scrollToIndex(index, options),
1995
+ scrollToTop: (options) => scrollTo(0, options),
1996
+ scrollToBottom: (options) => scrollTo(totalSize, options),
1997
+ getScrollPosition: () => ({
1998
+ scrollTop: containerRef.current?.scrollTop ?? 0,
1999
+ scrollLeft: containerRef.current?.scrollLeft ?? 0
2000
+ })
2001
+ }), [scrollTo, scrollToIndex, totalSize]);
2002
+ const handleScroll = useCallback((event) => {
2003
+ const target = event.currentTarget;
2004
+ onScroll?.(target.scrollTop, target.scrollLeft);
2005
+ }, [onScroll]);
2006
+ const handleScrollForInfinite = useCallback((event) => {
2007
+ if (!onLoadMore || !hasMore || isLoading) return;
2008
+ const target = event.currentTarget;
2009
+ const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2010
+ if (scrollBottom < threshold) {
2011
+ onLoadMore();
2012
+ }
2013
+ }, [onLoadMore, hasMore, isLoading, threshold]);
2014
+ const containerStyles = useMemo(() => ({
2015
+ height,
2016
+ width,
2017
+ overflow: "auto",
2018
+ position: "relative",
2019
+ contain: "strict",
2020
+ ...style
2021
+ }), [height, width, style]);
2022
+ const innerContainerStyles = useMemo(() => ({
2023
+ height: direction === "vertical" ? totalSize : "100%",
2024
+ width: direction === "horizontal" ? totalSize : "100%",
2025
+ position: "relative",
2026
+ contain: "size layout",
2027
+ ...innerStyle
2028
+ }), [totalSize, direction, innerStyle]);
2029
+ const createRenderProps = useCallback(
2030
+ (index) => {
2031
+ const item = data[index];
2032
+ if (item === void 0) {
2033
+ throw new Error(`[Scrollex] Item at index ${index} is undefined`);
2034
+ }
2035
+ const virtualItem = virtualItems.find((vi) => vi.index === index);
2036
+ const itemOffset = virtualItem?.start ?? 0;
2037
+ const itemSize = virtualItem?.size ?? estimatedItemHeight;
2038
+ const itemStyles = {
2039
+ position: "absolute",
2040
+ top: 0,
2041
+ left: 0,
2042
+ width: direction === "vertical" ? "100%" : itemSize,
2043
+ height: direction === "vertical" ? itemSize : "100%",
2044
+ transform: direction === "vertical" ? `translateY(${itemOffset}px)` : `translateX(${itemOffset}px)`,
2045
+ willChange: "transform",
2046
+ contain: "layout style",
2047
+ ...itemStyle
2048
+ };
2049
+ return {
2050
+ item,
2051
+ index,
2052
+ style: itemStyles,
2053
+ measureRef: (el) => measureElement(index, el),
2054
+ isVisible: index >= range.startIndex && index <= range.endIndex,
2055
+ isScrolling
2056
+ };
2057
+ },
2058
+ [data, virtualItems, estimatedItemHeight, direction, itemStyle, measureElement, range, isScrolling]
2059
+ );
2060
+ const contextValue = useMemo(() => ({
2061
+ kernel: kernelRef.current
2062
+ }), []);
2063
+ return /* @__PURE__ */ jsx(ScrollexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(
2064
+ "div",
2065
+ {
2066
+ ref: containerRef,
2067
+ className,
2068
+ style: containerStyles,
2069
+ onScroll: (e) => {
2070
+ handleScroll(e);
2071
+ handleScrollForInfinite(e);
2072
+ },
2073
+ role,
2074
+ "aria-label": ariaLabel,
2075
+ "aria-rowcount": data.length,
2076
+ tabIndex,
2077
+ ...restProps,
2078
+ children: [
2079
+ /* @__PURE__ */ jsx("div", { className: innerClassName, style: innerContainerStyles, children: virtualItems.map((virtualItem) => {
2080
+ const index = virtualItem.index;
2081
+ const item = data[index];
2082
+ if (item === void 0) return null;
2083
+ return /* @__PURE__ */ jsx(
2084
+ "div",
2085
+ {
2086
+ className: itemClassName,
2087
+ "data-index": index,
2088
+ role: "option",
2089
+ "aria-rowindex": index + 1,
2090
+ children: renderItem(createRenderProps(index))
2091
+ },
2092
+ virtualItem.key
2093
+ );
2094
+ }) }),
2095
+ isLoading && loadingIndicator
2096
+ ]
2097
+ }
2098
+ ) });
2099
+ }
2100
+ var VirtualList = forwardRef(VirtualListInner);
2101
+
2102
+ // src/plugins/core/grid-renderer.ts
2103
+ function gridRendererPlugin(options) {
2104
+ const {
2105
+ columns,
2106
+ minColumnWidth = 100,
2107
+ rowHeight,
2108
+ gap = 0,
2109
+ getItemKey = (index) => index
2110
+ } = options;
2111
+ let kernel = null;
2112
+ let virtualItems = [];
2113
+ let columnCount = typeof columns === "number" ? columns : 1;
2114
+ let columnWidth = 0;
2115
+ let gapX = typeof gap === "number" ? gap : gap.x;
2116
+ let gapY = typeof gap === "number" ? gap : gap.y;
2117
+ function calculateColumns(containerWidth) {
2118
+ if (typeof columns === "number") {
2119
+ columnCount = columns;
2120
+ } else {
2121
+ columnCount = Math.max(1, Math.floor((containerWidth + gapX) / (minColumnWidth + gapX)));
2122
+ }
2123
+ columnWidth = (containerWidth - (columnCount - 1) * gapX) / columnCount;
2124
+ }
2125
+ function getRowCount() {
2126
+ if (!kernel) return 0;
2127
+ return Math.ceil(kernel.getItemCount() / columnCount);
2128
+ }
2129
+ function buildVirtualItems() {
2130
+ if (!kernel) return [];
2131
+ const viewport = kernel.getViewport();
2132
+ const scrollPosition = kernel.getScrollPosition();
2133
+ const scrollTop = scrollPosition.scrollTop;
2134
+ const effectiveRowHeight = rowHeight + gapY;
2135
+ const startRow = Math.max(0, Math.floor(scrollTop / effectiveRowHeight));
2136
+ const visibleRows = Math.ceil(viewport.height / effectiveRowHeight);
2137
+ const overscan = kernel.getOptions().overscan;
2138
+ const endRow = Math.min(getRowCount() - 1, startRow + visibleRows + overscan);
2139
+ const overscanStartRow = Math.max(0, startRow - overscan);
2140
+ const items = [];
2141
+ const itemCount = kernel.getItemCount();
2142
+ for (let row = overscanStartRow; row <= endRow; row++) {
2143
+ for (let col = 0; col < columnCount; col++) {
2144
+ const index = row * columnCount + col;
2145
+ if (index >= itemCount) break;
2146
+ const top = row * effectiveRowHeight;
2147
+ items.push({
2148
+ index,
2149
+ key: getItemKey(index),
2150
+ start: top,
2151
+ end: top + rowHeight,
2152
+ size: rowHeight,
2153
+ lane: col
2154
+ });
2155
+ }
2156
+ }
2157
+ return items;
2158
+ }
2159
+ function recalculate() {
2160
+ if (!kernel) return;
2161
+ const viewport = kernel.getViewport();
2162
+ calculateColumns(viewport.width);
2163
+ virtualItems = buildVirtualItems();
2164
+ }
2165
+ const api = {
2166
+ getVirtualItems() {
2167
+ return virtualItems;
2168
+ },
2169
+ getTotalHeight() {
2170
+ return getRowCount() * (rowHeight + gapY) - gapY;
2171
+ },
2172
+ getColumnCount() {
2173
+ return columnCount;
2174
+ },
2175
+ getColumnWidth() {
2176
+ return columnWidth;
2177
+ },
2178
+ getItemsPerRow() {
2179
+ return columnCount;
2180
+ },
2181
+ getRowCount,
2182
+ recalculate
2183
+ };
2184
+ return {
2185
+ name: "grid-renderer",
2186
+ version: "1.0.0",
2187
+ type: "core",
2188
+ install(k) {
2189
+ kernel = k;
2190
+ recalculate();
2191
+ },
2192
+ uninstall() {
2193
+ virtualItems = [];
2194
+ kernel = null;
2195
+ },
2196
+ hooks: {
2197
+ onScroll: () => {
2198
+ virtualItems = buildVirtualItems();
2199
+ },
2200
+ onResize: () => recalculate(),
2201
+ onItemsChange: () => recalculate()
2202
+ },
2203
+ api
2204
+ };
2205
+ }
2206
+
2207
+ // src/react/hooks/use-virtual-grid.ts
2208
+ function useVirtualGrid(options) {
2209
+ const {
2210
+ count,
2211
+ columns,
2212
+ rowHeight,
2213
+ gap = 0,
2214
+ overscan = 2,
2215
+ initialOffset = 0,
2216
+ getItemKey = (index) => index,
2217
+ containerRef
2218
+ } = options;
2219
+ const gapX = typeof gap === "number" ? gap : gap.x;
2220
+ const gapY = typeof gap === "number" ? gap : gap.y;
2221
+ const kernelRef = useRef(
2222
+ createKernel({
2223
+ itemCount: count,
2224
+ estimatedItemHeight: rowHeight,
2225
+ overscan,
2226
+ direction: "vertical",
2227
+ getItemKey
2228
+ })
2229
+ );
2230
+ const [virtualItems, setVirtualItems] = useState([]);
2231
+ const [isScrolling, setIsScrolling] = useState(false);
2232
+ const [scrollOffset, setScrollOffset] = useState(initialOffset);
2233
+ const [range, setRange] = useState({
2234
+ startIndex: 0,
2235
+ endIndex: 0,
2236
+ overscanStartIndex: 0,
2237
+ overscanEndIndex: 0
2238
+ });
2239
+ const [columnCount, setColumnCount] = useState(typeof columns === "number" ? columns : 1);
2240
+ const [columnWidth, setColumnWidth] = useState(0);
2241
+ const gridRendererRef = useRef(null);
2242
+ const kernel = kernelRef.current;
2243
+ useEffect(() => {
2244
+ const plugin = gridRendererPlugin({
2245
+ columns,
2246
+ rowHeight,
2247
+ gap: { x: gapX, y: gapY },
2248
+ getItemKey
2249
+ });
2250
+ kernel.register(plugin);
2251
+ gridRendererRef.current = plugin.api;
2252
+ const unsubScroll = kernel.on("scroll", (event) => {
2253
+ const e = event;
2254
+ setScrollOffset(e.scrollTop);
2255
+ setVirtualItems(gridRendererRef.current?.getVirtualItems() ?? []);
2256
+ });
2257
+ const unsubScrollStart = kernel.on("scroll-start", () => {
2258
+ setIsScrolling(true);
2259
+ });
2260
+ const unsubScrollEnd = kernel.on("scroll-end", () => {
2261
+ setIsScrolling(false);
2262
+ });
2263
+ const unsubResize = kernel.on("resize", () => {
2264
+ const api = gridRendererRef.current;
2265
+ if (api) {
2266
+ api.recalculate();
2267
+ setColumnCount(api.getColumnCount());
2268
+ setColumnWidth(api.getColumnWidth());
2269
+ setVirtualItems(api.getVirtualItems());
2270
+ }
2271
+ });
2272
+ const unsubRangeChange = kernel.on("visible-range-change", (event) => {
2273
+ const e = event;
2274
+ setRange(e.range);
2275
+ });
2276
+ return () => {
2277
+ unsubScroll();
2278
+ unsubScrollStart();
2279
+ unsubScrollEnd();
2280
+ unsubResize();
2281
+ unsubRangeChange();
2282
+ kernel.destroy();
2283
+ };
2284
+ }, []);
2285
+ useEffect(() => {
2286
+ const container = containerRef.current;
2287
+ if (!container) return;
2288
+ kernel.attach(container);
2289
+ const api = gridRendererRef.current;
2290
+ if (api) {
2291
+ api.recalculate();
2292
+ setColumnCount(api.getColumnCount());
2293
+ setColumnWidth(api.getColumnWidth());
2294
+ setVirtualItems(api.getVirtualItems());
2295
+ }
2296
+ if (initialOffset > 0) {
2297
+ kernel.scrollTo(initialOffset);
2298
+ }
2299
+ return () => {
2300
+ kernel.detach();
2301
+ };
2302
+ }, [containerRef, kernel, initialOffset]);
2303
+ useEffect(() => {
2304
+ kernel.configure({ itemCount: count });
2305
+ const api = gridRendererRef.current;
2306
+ if (api) {
2307
+ api.recalculate();
2308
+ setVirtualItems(api.getVirtualItems());
2309
+ }
2310
+ }, [count, kernel]);
2311
+ const scrollTo = useCallback(
2312
+ (offset, scrollOptions) => {
2313
+ kernel.scrollTo(offset, scrollOptions);
2314
+ },
2315
+ [kernel]
2316
+ );
2317
+ const scrollToIndex = useCallback(
2318
+ (index, scrollOptions) => {
2319
+ const row = Math.floor(index / columnCount);
2320
+ const rowOffset = row * (rowHeight + gapY);
2321
+ kernel.scrollTo(rowOffset, scrollOptions);
2322
+ },
2323
+ [kernel, columnCount, rowHeight, gapY]
2324
+ );
2325
+ const measureElement = useCallback(
2326
+ (_index, _element) => {
2327
+ },
2328
+ []
2329
+ );
2330
+ const getMeasurement = useCallback(
2331
+ (_index) => rowHeight,
2332
+ [rowHeight]
2333
+ );
2334
+ const invalidateMeasurement = useCallback(
2335
+ (_index) => {
2336
+ },
2337
+ []
2338
+ );
2339
+ const invalidateAllMeasurements = useCallback(() => {
2340
+ }, []);
2341
+ const totalSize = useMemo(() => {
2342
+ return gridRendererRef.current?.getTotalHeight() ?? 0;
2343
+ }, [virtualItems]);
2344
+ const rowCount = useMemo(() => {
2345
+ return gridRendererRef.current?.getRowCount() ?? 0;
2346
+ }, [count, columnCount]);
2347
+ return {
2348
+ virtualItems,
2349
+ totalSize,
2350
+ scrollOffset,
2351
+ isScrolling,
2352
+ scrollTo,
2353
+ scrollToIndex,
2354
+ measureElement,
2355
+ range,
2356
+ getMeasurement,
2357
+ invalidateMeasurement,
2358
+ invalidateAllMeasurements,
2359
+ columnCount,
2360
+ columnWidth,
2361
+ rowCount
2362
+ };
2363
+ }
2364
+ function VirtualGridInner(props, ref) {
2365
+ const {
2366
+ data,
2367
+ renderItem,
2368
+ itemHeight,
2369
+ columns,
2370
+ minColumnWidth = 100,
2371
+ gap = 0,
2372
+ height = "100%",
2373
+ width = "100%",
2374
+ overscan = 2,
2375
+ initialScrollOffset = 0,
2376
+ getItemKey,
2377
+ onLoadMore,
2378
+ hasMore = false,
2379
+ isLoading = false,
2380
+ loadingIndicator,
2381
+ threshold = 200,
2382
+ onScroll,
2383
+ onVisibleRangeChange,
2384
+ onItemsRendered,
2385
+ plugins = [],
2386
+ className,
2387
+ style,
2388
+ innerClassName,
2389
+ innerStyle,
2390
+ itemClassName,
2391
+ itemStyle,
2392
+ role = "grid",
2393
+ ariaLabel,
2394
+ tabIndex,
2395
+ ...restProps
2396
+ } = props;
2397
+ const containerRef = useRef(null);
2398
+ const gapX = typeof gap === "number" ? gap : gap.x;
2399
+ const gapY = typeof gap === "number" ? gap : gap.y;
2400
+ const {
2401
+ virtualItems,
2402
+ totalSize,
2403
+ scrollTo,
2404
+ scrollToIndex,
2405
+ isScrolling,
2406
+ range,
2407
+ columnCount,
2408
+ columnWidth,
2409
+ rowCount
2410
+ } = useVirtualGrid({
2411
+ count: data.length,
2412
+ columns: typeof columns === "number" ? columns : 1,
2413
+ // TODO: handle auto
2414
+ rowHeight: itemHeight,
2415
+ gap: { x: gapX, y: gapY },
2416
+ overscan,
2417
+ initialOffset: initialScrollOffset,
2418
+ getItemKey: getItemKey ? (index) => getItemKey(index, data) : void 0,
2419
+ containerRef
2420
+ });
2421
+ const kernelRef = useRef(createKernel({
2422
+ itemCount: data.length,
2423
+ estimatedItemHeight: itemHeight,
2424
+ overscan,
2425
+ direction: "vertical"
2426
+ }));
2427
+ useImperativeHandle(ref, () => ({
2428
+ scrollTo: (offset, options) => scrollTo(offset, options),
2429
+ scrollToIndex: (index, options) => scrollToIndex(index, options),
2430
+ scrollToTop: (options) => scrollTo(0, options),
2431
+ scrollToBottom: (options) => scrollTo(totalSize, options),
2432
+ getScrollPosition: () => ({
2433
+ scrollTop: containerRef.current?.scrollTop ?? 0,
2434
+ scrollLeft: containerRef.current?.scrollLeft ?? 0
2435
+ })
2436
+ }), [scrollTo, scrollToIndex, totalSize]);
2437
+ const handleScroll = useCallback((event) => {
2438
+ const target = event.currentTarget;
2439
+ onScroll?.(target.scrollTop, target.scrollLeft);
2440
+ }, [onScroll]);
2441
+ const handleScrollForInfinite = useCallback((event) => {
2442
+ if (!onLoadMore || !hasMore || isLoading) return;
2443
+ const target = event.currentTarget;
2444
+ const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2445
+ if (scrollBottom < threshold) {
2446
+ onLoadMore();
2447
+ }
2448
+ }, [onLoadMore, hasMore, isLoading, threshold]);
2449
+ const containerStyles = useMemo(() => ({
2450
+ height,
2451
+ width,
2452
+ overflow: "auto",
2453
+ position: "relative",
2454
+ contain: "strict",
2455
+ ...style
2456
+ }), [height, width, style]);
2457
+ const innerContainerStyles = useMemo(() => ({
2458
+ height: totalSize,
2459
+ width: "100%",
2460
+ position: "relative",
2461
+ contain: "size layout",
2462
+ ...innerStyle
2463
+ }), [totalSize, innerStyle]);
2464
+ const createRenderProps = useCallback(
2465
+ (index, virtualItem) => {
2466
+ const item = data[index];
2467
+ if (item === void 0) {
2468
+ throw new Error(`[Scrollex] Item at index ${index} is undefined`);
2469
+ }
2470
+ const columnIndex = virtualItem.lane;
2471
+ const rowIndex = Math.floor(index / columnCount);
2472
+ const left = columnIndex * (columnWidth + gapX);
2473
+ const itemStyles = {
2474
+ position: "absolute",
2475
+ top: 0,
2476
+ left: 0,
2477
+ width: columnWidth,
2478
+ height: virtualItem.size,
2479
+ transform: `translate(${left}px, ${virtualItem.start}px)`,
2480
+ willChange: "transform",
2481
+ contain: "layout style",
2482
+ ...itemStyle
2483
+ };
2484
+ return {
2485
+ item,
2486
+ index,
2487
+ style: itemStyles,
2488
+ measureRef: () => {
2489
+ },
2490
+ // Grid uses fixed heights
2491
+ isVisible: index >= range.startIndex && index <= range.endIndex,
2492
+ isScrolling,
2493
+ columnIndex,
2494
+ rowIndex,
2495
+ columnWidth
2496
+ };
2497
+ },
2498
+ [data, columnCount, columnWidth, gapX, itemStyle, range, isScrolling]
2499
+ );
2500
+ const contextValue = useMemo(() => ({
2501
+ kernel: kernelRef.current
2502
+ }), []);
2503
+ return /* @__PURE__ */ jsx(ScrollexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(
2504
+ "div",
2505
+ {
2506
+ ref: containerRef,
2507
+ className,
2508
+ style: containerStyles,
2509
+ onScroll: (e) => {
2510
+ handleScroll(e);
2511
+ handleScrollForInfinite(e);
2512
+ },
2513
+ role,
2514
+ "aria-label": ariaLabel,
2515
+ "aria-rowcount": rowCount,
2516
+ "aria-colcount": columnCount,
2517
+ tabIndex,
2518
+ ...restProps,
2519
+ children: [
2520
+ /* @__PURE__ */ jsx("div", { className: innerClassName, style: innerContainerStyles, children: virtualItems.map((virtualItem) => {
2521
+ const index = virtualItem.index;
2522
+ const item = data[index];
2523
+ if (item === void 0) return null;
2524
+ const rowIndex = Math.floor(index / columnCount);
2525
+ const columnIndex = virtualItem.lane;
2526
+ return /* @__PURE__ */ jsx(
2527
+ "div",
2528
+ {
2529
+ className: itemClassName,
2530
+ "data-index": index,
2531
+ role: "gridcell",
2532
+ "aria-rowindex": rowIndex + 1,
2533
+ "aria-colindex": columnIndex + 1,
2534
+ children: renderItem(createRenderProps(index, virtualItem))
2535
+ },
2536
+ virtualItem.key
2537
+ );
2538
+ }) }),
2539
+ isLoading && loadingIndicator
2540
+ ]
2541
+ }
2542
+ ) });
2543
+ }
2544
+ var VirtualGrid = forwardRef(VirtualGridInner);
2545
+ function useVirtualMasonry(options) {
2546
+ const {
2547
+ count,
2548
+ columns,
2549
+ getItemHeight,
2550
+ gap = 0,
2551
+ overscan = 5,
2552
+ containerRef
2553
+ } = options;
2554
+ const kernelRef = useRef(
2555
+ createKernel({
2556
+ itemCount: count,
2557
+ estimatedItemHeight: 200,
2558
+ overscan,
2559
+ direction: "vertical"
2560
+ })
2561
+ );
2562
+ const [virtualItems, setVirtualItems] = useState([]);
2563
+ const [isScrolling, setIsScrolling] = useState(false);
2564
+ const [scrollOffset, setScrollOffset] = useState(0);
2565
+ const [range, setRange] = useState({
2566
+ startIndex: 0,
2567
+ endIndex: 0,
2568
+ overscanStartIndex: 0,
2569
+ overscanEndIndex: 0
2570
+ });
2571
+ const [columnWidth, setColumnWidth] = useState(0);
2572
+ const [columnHeights, setColumnHeights] = useState([]);
2573
+ const [totalSize, setTotalSize] = useState(0);
2574
+ const layoutCacheRef = useRef(/* @__PURE__ */ new Map());
2575
+ const kernel = kernelRef.current;
2576
+ const calculateLayout = useCallback((containerWidth) => {
2577
+ if (containerWidth === 0 || count === 0) {
2578
+ setVirtualItems([]);
2579
+ setColumnHeights([]);
2580
+ setTotalSize(0);
2581
+ return;
2582
+ }
2583
+ const newColumnWidth = (containerWidth - (columns - 1) * gap) / columns;
2584
+ setColumnWidth(newColumnWidth);
2585
+ const heights = new Array(columns).fill(0);
2586
+ const cache = /* @__PURE__ */ new Map();
2587
+ for (let i = 0; i < count; i++) {
2588
+ let shortestCol = 0;
2589
+ for (let j = 1; j < columns; j++) {
2590
+ if ((heights[j] ?? 0) < (heights[shortestCol] ?? 0)) {
2591
+ shortestCol = j;
2592
+ }
2593
+ }
2594
+ const itemHeight = getItemHeight(i, newColumnWidth);
2595
+ const top = heights[shortestCol] ?? 0;
2596
+ cache.set(i, { top, lane: shortestCol, height: itemHeight });
2597
+ heights[shortestCol] = top + itemHeight + gap;
2598
+ }
2599
+ layoutCacheRef.current = cache;
2600
+ setColumnHeights(heights);
2601
+ setTotalSize(Math.max(...heights) - gap);
2602
+ }, [count, columns, gap, getItemHeight]);
2603
+ const getVisibleItems = useCallback((scrollTop, viewportHeight) => {
2604
+ const cache = layoutCacheRef.current;
2605
+ const items = [];
2606
+ const overscanAmount = overscan * 100;
2607
+ const viewStart = Math.max(0, scrollTop - overscanAmount);
2608
+ const viewEnd = scrollTop + viewportHeight + overscanAmount;
2609
+ for (let i = 0; i < count; i++) {
2610
+ const layout = cache.get(i);
2611
+ if (!layout) continue;
2612
+ const itemEnd = layout.top + layout.height;
2613
+ if (itemEnd >= viewStart && layout.top <= viewEnd) {
2614
+ items.push({
2615
+ index: i,
2616
+ key: i,
2617
+ start: layout.top,
2618
+ end: itemEnd,
2619
+ size: layout.height,
2620
+ lane: layout.lane
2621
+ });
2622
+ }
2623
+ }
2624
+ return items;
2625
+ }, [count, overscan]);
2626
+ useEffect(() => {
2627
+ const unsubScrollStart = kernel.on("scroll-start", () => {
2628
+ setIsScrolling(true);
2629
+ });
2630
+ const unsubScrollEnd = kernel.on("scroll-end", () => {
2631
+ setIsScrolling(false);
2632
+ });
2633
+ return () => {
2634
+ unsubScrollStart();
2635
+ unsubScrollEnd();
2636
+ kernel.destroy();
2637
+ };
2638
+ }, [kernel]);
2639
+ useEffect(() => {
2640
+ const container = containerRef.current;
2641
+ if (!container) return;
2642
+ kernel.attach(container);
2643
+ calculateLayout(container.clientWidth);
2644
+ const handleScroll = () => {
2645
+ const scrollTop = container.scrollTop;
2646
+ setScrollOffset(scrollTop);
2647
+ setVirtualItems(getVisibleItems(scrollTop, container.clientHeight));
2648
+ };
2649
+ const resizeObserver = new ResizeObserver((entries) => {
2650
+ for (const entry of entries) {
2651
+ calculateLayout(entry.contentRect.width);
2652
+ setVirtualItems(getVisibleItems(container.scrollTop, entry.contentRect.height));
2653
+ }
2654
+ });
2655
+ container.addEventListener("scroll", handleScroll, { passive: true });
2656
+ resizeObserver.observe(container);
2657
+ handleScroll();
2658
+ return () => {
2659
+ container.removeEventListener("scroll", handleScroll);
2660
+ resizeObserver.disconnect();
2661
+ kernel.detach();
2662
+ };
2663
+ }, [containerRef, kernel, calculateLayout, getVisibleItems]);
2664
+ useEffect(() => {
2665
+ const container = containerRef.current;
2666
+ if (!container) return;
2667
+ calculateLayout(container.clientWidth);
2668
+ setVirtualItems(getVisibleItems(container.scrollTop, container.clientHeight));
2669
+ }, [count, containerRef, calculateLayout, getVisibleItems]);
2670
+ const scrollTo = useCallback(
2671
+ (offset, scrollOptions) => {
2672
+ kernel.scrollTo(offset, scrollOptions);
2673
+ },
2674
+ [kernel]
2675
+ );
2676
+ const scrollToIndex = useCallback(
2677
+ (index, _scrollOptions) => {
2678
+ const layout = layoutCacheRef.current.get(index);
2679
+ if (layout) {
2680
+ kernel.scrollTo(layout.top);
2681
+ }
2682
+ },
2683
+ [kernel]
2684
+ );
2685
+ const measureElement = useCallback(
2686
+ (_index, _element) => {
2687
+ },
2688
+ []
2689
+ );
2690
+ const getMeasurement = useCallback(
2691
+ (index) => {
2692
+ return layoutCacheRef.current.get(index)?.height;
2693
+ },
2694
+ []
2695
+ );
2696
+ const invalidateMeasurement = useCallback((_index) => {
2697
+ const container = containerRef.current;
2698
+ if (container) {
2699
+ calculateLayout(container.clientWidth);
2700
+ }
2701
+ }, [containerRef, calculateLayout]);
2702
+ const invalidateAllMeasurements = useCallback(() => {
2703
+ const container = containerRef.current;
2704
+ if (container) {
2705
+ calculateLayout(container.clientWidth);
2706
+ }
2707
+ }, [containerRef, calculateLayout]);
2708
+ return {
2709
+ virtualItems,
2710
+ totalSize,
2711
+ scrollOffset,
2712
+ isScrolling,
2713
+ scrollTo,
2714
+ scrollToIndex,
2715
+ measureElement,
2716
+ range,
2717
+ getMeasurement,
2718
+ invalidateMeasurement,
2719
+ invalidateAllMeasurements,
2720
+ columnCount: columns,
2721
+ columnWidth,
2722
+ columnHeights
2723
+ };
2724
+ }
2725
+ function VirtualMasonryInner(props, ref) {
2726
+ const {
2727
+ data,
2728
+ renderItem,
2729
+ getItemHeight,
2730
+ columns,
2731
+ minColumnWidth = 200,
2732
+ gap = 0,
2733
+ height = "100%",
2734
+ width = "100%",
2735
+ overscan = 5,
2736
+ initialScrollOffset = 0,
2737
+ getItemKey,
2738
+ onLoadMore,
2739
+ hasMore = false,
2740
+ isLoading = false,
2741
+ loadingIndicator,
2742
+ threshold = 200,
2743
+ onScroll,
2744
+ onVisibleRangeChange,
2745
+ onItemsRendered,
2746
+ plugins = [],
2747
+ className,
2748
+ style,
2749
+ innerClassName,
2750
+ innerStyle,
2751
+ itemClassName,
2752
+ itemStyle,
2753
+ role = "grid",
2754
+ ariaLabel,
2755
+ tabIndex,
2756
+ ...restProps
2757
+ } = props;
2758
+ const containerRef = useRef(null);
2759
+ const gapValue = typeof gap === "number" ? gap : gap.x;
2760
+ const {
2761
+ virtualItems,
2762
+ totalSize,
2763
+ scrollTo,
2764
+ scrollToIndex,
2765
+ isScrolling,
2766
+ range,
2767
+ columnCount,
2768
+ columnWidth,
2769
+ columnHeights
2770
+ } = useVirtualMasonry({
2771
+ count: data.length,
2772
+ columns: typeof columns === "number" ? columns : 3,
2773
+ // TODO: handle auto
2774
+ getItemHeight: (index, colWidth) => {
2775
+ const item = data[index];
2776
+ if (item === void 0) return 100;
2777
+ return getItemHeight(item, colWidth);
2778
+ },
2779
+ gap: gapValue,
2780
+ overscan,
2781
+ containerRef
2782
+ });
2783
+ const kernelRef = useRef(createKernel({
2784
+ itemCount: data.length,
2785
+ estimatedItemHeight: 200,
2786
+ overscan,
2787
+ direction: "vertical"
2788
+ }));
2789
+ useImperativeHandle(ref, () => ({
2790
+ scrollTo: (offset, options) => scrollTo(offset, options),
2791
+ scrollToIndex: (index, options) => scrollToIndex(index, options),
2792
+ scrollToTop: (options) => scrollTo(0, options),
2793
+ scrollToBottom: (options) => scrollTo(totalSize, options),
2794
+ getScrollPosition: () => ({
2795
+ scrollTop: containerRef.current?.scrollTop ?? 0,
2796
+ scrollLeft: containerRef.current?.scrollLeft ?? 0
2797
+ })
2798
+ }), [scrollTo, scrollToIndex, totalSize]);
2799
+ const handleScroll = useCallback((event) => {
2800
+ const target = event.currentTarget;
2801
+ onScroll?.(target.scrollTop, target.scrollLeft);
2802
+ }, [onScroll]);
2803
+ const handleScrollForInfinite = useCallback((event) => {
2804
+ if (!onLoadMore || !hasMore || isLoading) return;
2805
+ const target = event.currentTarget;
2806
+ const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
2807
+ if (scrollBottom < threshold) {
2808
+ onLoadMore();
2809
+ }
2810
+ }, [onLoadMore, hasMore, isLoading, threshold]);
2811
+ const containerStyles = useMemo(() => ({
2812
+ height,
2813
+ width,
2814
+ overflow: "auto",
2815
+ position: "relative",
2816
+ contain: "strict",
2817
+ ...style
2818
+ }), [height, width, style]);
2819
+ const innerContainerStyles = useMemo(() => ({
2820
+ height: totalSize,
2821
+ width: "100%",
2822
+ position: "relative",
2823
+ contain: "size layout",
2824
+ ...innerStyle
2825
+ }), [totalSize, innerStyle]);
2826
+ const createRenderProps = useCallback(
2827
+ (index, virtualItem) => {
2828
+ const item = data[index];
2829
+ if (item === void 0) {
2830
+ throw new Error(`[Scrollex] Item at index ${index} is undefined`);
2831
+ }
2832
+ const columnIndex = virtualItem.lane;
2833
+ const left = columnIndex * (columnWidth + gapValue);
2834
+ const itemStyles = {
2835
+ position: "absolute",
2836
+ top: 0,
2837
+ left: 0,
2838
+ width: columnWidth,
2839
+ height: virtualItem.size,
2840
+ transform: `translate(${left}px, ${virtualItem.start}px)`,
2841
+ willChange: "transform",
2842
+ contain: "layout style",
2843
+ ...itemStyle
2844
+ };
2845
+ return {
2846
+ item,
2847
+ index,
2848
+ style: itemStyles,
2849
+ measureRef: () => {
2850
+ },
2851
+ // Masonry uses calculated heights
2852
+ isVisible: true,
2853
+ // All virtual items are considered visible
2854
+ isScrolling,
2855
+ columnIndex,
2856
+ rowIndex: 0,
2857
+ // Not meaningful for masonry
2858
+ columnWidth,
2859
+ width: columnWidth
2860
+ };
2861
+ },
2862
+ [data, columnWidth, gapValue, itemStyle, isScrolling]
2863
+ );
2864
+ const contextValue = useMemo(() => ({
2865
+ kernel: kernelRef.current
2866
+ }), []);
2867
+ return /* @__PURE__ */ jsx(ScrollexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(
2868
+ "div",
2869
+ {
2870
+ ref: containerRef,
2871
+ className,
2872
+ style: containerStyles,
2873
+ onScroll: (e) => {
2874
+ handleScroll(e);
2875
+ handleScrollForInfinite(e);
2876
+ },
2877
+ role,
2878
+ "aria-label": ariaLabel,
2879
+ "aria-colcount": columnCount,
2880
+ tabIndex,
2881
+ ...restProps,
2882
+ children: [
2883
+ /* @__PURE__ */ jsx("div", { className: innerClassName, style: innerContainerStyles, children: virtualItems.map((virtualItem) => {
2884
+ const index = virtualItem.index;
2885
+ const item = data[index];
2886
+ if (item === void 0) return null;
2887
+ return /* @__PURE__ */ jsx(
2888
+ "div",
2889
+ {
2890
+ className: itemClassName,
2891
+ "data-index": index,
2892
+ role: "gridcell",
2893
+ "aria-colindex": virtualItem.lane + 1,
2894
+ children: renderItem(createRenderProps(index, virtualItem))
2895
+ },
2896
+ virtualItem.key
2897
+ );
2898
+ }) }),
2899
+ isLoading && loadingIndicator
2900
+ ]
2901
+ }
2902
+ ) });
2903
+ }
2904
+ var VirtualMasonry = forwardRef(VirtualMasonryInner);
2905
+ function useMeasure(options = {}) {
2906
+ const { onResize, debounce: debounce2 = 0 } = options;
2907
+ const elementRef = useRef(null);
2908
+ const observerRef = useRef(null);
2909
+ const dimensionsRef = useRef({ width: 0, height: 0 });
2910
+ const debounceTimerRef = useRef(null);
2911
+ const handleResize = useCallback(
2912
+ (width, height) => {
2913
+ dimensionsRef.current = { width, height };
2914
+ if (onResize) {
2915
+ if (debounce2 > 0) {
2916
+ if (debounceTimerRef.current) {
2917
+ clearTimeout(debounceTimerRef.current);
2918
+ }
2919
+ debounceTimerRef.current = setTimeout(() => {
2920
+ onResize(width, height);
2921
+ }, debounce2);
2922
+ } else {
2923
+ onResize(width, height);
2924
+ }
2925
+ }
2926
+ },
2927
+ [onResize, debounce2]
2928
+ );
2929
+ useEffect(() => {
2930
+ observerRef.current = new ResizeObserver((entries) => {
2931
+ for (const entry of entries) {
2932
+ const { width, height } = entry.contentRect;
2933
+ handleResize(width, height);
2934
+ }
2935
+ });
2936
+ if (elementRef.current) {
2937
+ observerRef.current.observe(elementRef.current);
2938
+ }
2939
+ return () => {
2940
+ observerRef.current?.disconnect();
2941
+ if (debounceTimerRef.current) {
2942
+ clearTimeout(debounceTimerRef.current);
2943
+ }
2944
+ };
2945
+ }, [handleResize]);
2946
+ const measureRef = useCallback((element) => {
2947
+ if (elementRef.current && observerRef.current) {
2948
+ observerRef.current.unobserve(elementRef.current);
2949
+ }
2950
+ elementRef.current = element;
2951
+ if (element && observerRef.current) {
2952
+ observerRef.current.observe(element);
2953
+ const rect = element.getBoundingClientRect();
2954
+ handleResize(rect.width, rect.height);
2955
+ }
2956
+ }, [handleResize]);
2957
+ return {
2958
+ measureRef,
2959
+ width: dimensionsRef.current.width,
2960
+ height: dimensionsRef.current.height
2961
+ };
2962
+ }
2963
+ function useMeasureMany() {
2964
+ const elementsRef = useRef(/* @__PURE__ */ new Map());
2965
+ const observerRef = useRef(null);
2966
+ const measurementsRef = useRef(/* @__PURE__ */ new Map());
2967
+ const callbackRef = useRef(null);
2968
+ useEffect(() => {
2969
+ observerRef.current = new ResizeObserver((entries) => {
2970
+ for (const entry of entries) {
2971
+ const element = entry.target;
2972
+ const key = element.dataset["measureKey"];
2973
+ if (key !== void 0) {
2974
+ const { width, height } = entry.contentRect;
2975
+ measurementsRef.current.set(key, { width, height });
2976
+ callbackRef.current?.(key, width, height);
2977
+ }
2978
+ }
2979
+ });
2980
+ return () => {
2981
+ observerRef.current?.disconnect();
2982
+ };
2983
+ }, []);
2984
+ const createMeasureRef = useCallback(
2985
+ (key) => (element) => {
2986
+ const elements = elementsRef.current;
2987
+ const observer = observerRef.current;
2988
+ const oldElement = elements.get(key);
2989
+ if (oldElement && oldElement !== element) {
2990
+ observer?.unobserve(oldElement);
2991
+ elements.delete(key);
2992
+ }
2993
+ if (element) {
2994
+ element.dataset["measureKey"] = String(key);
2995
+ elements.set(key, element);
2996
+ observer?.observe(element);
2997
+ const rect = element.getBoundingClientRect();
2998
+ measurementsRef.current.set(key, { width: rect.width, height: rect.height });
2999
+ }
3000
+ },
3001
+ []
3002
+ );
3003
+ const getMeasurement = useCallback((key) => {
3004
+ return measurementsRef.current.get(key);
3005
+ }, []);
3006
+ const onMeasure = useCallback(
3007
+ (callback) => {
3008
+ callbackRef.current = callback;
3009
+ },
3010
+ []
3011
+ );
3012
+ const clear = useCallback(() => {
3013
+ const observer = observerRef.current;
3014
+ for (const element of elementsRef.current.values()) {
3015
+ observer?.unobserve(element);
3016
+ }
3017
+ elementsRef.current.clear();
3018
+ measurementsRef.current.clear();
3019
+ }, []);
3020
+ return {
3021
+ createMeasureRef,
3022
+ getMeasurement,
3023
+ onMeasure,
3024
+ clear
3025
+ };
3026
+ }
3027
+
3028
+ // src/utils/debounce.ts
3029
+ function debounce(fn, wait) {
3030
+ let timeoutId = null;
3031
+ let lastArgs = null;
3032
+ let lastThis = null;
3033
+ const debounced = function(...args) {
3034
+ lastArgs = args;
3035
+ lastThis = this;
3036
+ if (timeoutId) {
3037
+ clearTimeout(timeoutId);
3038
+ }
3039
+ timeoutId = setTimeout(() => {
3040
+ timeoutId = null;
3041
+ if (lastArgs) {
3042
+ fn.apply(lastThis, lastArgs);
3043
+ lastArgs = null;
3044
+ lastThis = null;
3045
+ }
3046
+ }, wait);
3047
+ };
3048
+ debounced.cancel = () => {
3049
+ if (timeoutId) {
3050
+ clearTimeout(timeoutId);
3051
+ timeoutId = null;
3052
+ }
3053
+ lastArgs = null;
3054
+ lastThis = null;
3055
+ };
3056
+ debounced.flush = () => {
3057
+ if (timeoutId) {
3058
+ clearTimeout(timeoutId);
3059
+ timeoutId = null;
3060
+ if (lastArgs) {
3061
+ fn.apply(lastThis, lastArgs);
3062
+ lastArgs = null;
3063
+ lastThis = null;
3064
+ }
3065
+ }
3066
+ };
3067
+ return debounced;
3068
+ }
3069
+
3070
+ // src/plugins/core/auto-measurer.ts
3071
+ function autoMeasurerPlugin(options = {}) {
3072
+ const {
3073
+ estimatedItemHeight = 50,
3074
+ measureOnResize = true,
3075
+ debounceMs = 100
3076
+ } = options;
3077
+ let kernel = null;
3078
+ let resizeObserver = null;
3079
+ const observedElements = /* @__PURE__ */ new WeakMap();
3080
+ const elementsByIndex = /* @__PURE__ */ new Map();
3081
+ let measureQueue = /* @__PURE__ */ new Set();
3082
+ let flushScheduled = false;
3083
+ const debouncedFlush = debounce(() => {
3084
+ flush();
3085
+ }, debounceMs);
3086
+ function flush() {
3087
+ if (!kernel || measureQueue.size === 0) {
3088
+ flushScheduled = false;
3089
+ return;
3090
+ }
3091
+ const indicesToMeasure = Array.from(measureQueue);
3092
+ measureQueue = /* @__PURE__ */ new Set();
3093
+ flushScheduled = false;
3094
+ const measurements = [];
3095
+ for (const index of indicesToMeasure) {
3096
+ const ref = elementsByIndex.get(index);
3097
+ const element = ref?.deref();
3098
+ if (element) {
3099
+ const rect = element.getBoundingClientRect();
3100
+ measurements.push({ index, height: rect.height });
3101
+ }
3102
+ }
3103
+ for (const { index, height } of measurements) {
3104
+ if (height > 0) {
3105
+ kernel.measureItem(index, height);
3106
+ }
3107
+ }
3108
+ }
3109
+ function scheduleFlush() {
3110
+ if (!flushScheduled) {
3111
+ flushScheduled = true;
3112
+ requestAnimationFrame(() => {
3113
+ flush();
3114
+ });
3115
+ }
3116
+ }
3117
+ function handleResize(entries) {
3118
+ for (const entry of entries) {
3119
+ const index = observedElements.get(entry.target);
3120
+ if (index !== void 0) {
3121
+ measureQueue.add(index);
3122
+ }
3123
+ }
3124
+ if (measureOnResize && measureQueue.size > 0) {
3125
+ debouncedFlush();
3126
+ }
3127
+ }
3128
+ const api = {
3129
+ measureElement(index, element) {
3130
+ const rect = element.getBoundingClientRect();
3131
+ const height = rect.height;
3132
+ if (height > 0 && kernel) {
3133
+ kernel.measureItem(index, height);
3134
+ }
3135
+ return height;
3136
+ },
3137
+ getCachedSize(index) {
3138
+ return kernel?.getCachedHeight(index);
3139
+ },
3140
+ invalidate(index) {
3141
+ kernel?.invalidateMeasurement(index);
3142
+ },
3143
+ invalidateAll() {
3144
+ kernel?.invalidateAllMeasurements();
3145
+ },
3146
+ getMeasurementCache() {
3147
+ const cache = /* @__PURE__ */ new Map();
3148
+ if (!kernel) return cache;
3149
+ const itemCount = kernel.getItemCount();
3150
+ for (let i = 0; i < itemCount; i++) {
3151
+ const height = kernel.getCachedHeight(i);
3152
+ if (height !== void 0) {
3153
+ cache.set(i, height);
3154
+ }
3155
+ }
3156
+ return cache;
3157
+ },
3158
+ observe(index, element) {
3159
+ if (!resizeObserver) return;
3160
+ const existingRef = elementsByIndex.get(index);
3161
+ const existingElement = existingRef?.deref();
3162
+ if (existingElement && existingElement !== element) {
3163
+ resizeObserver.unobserve(existingElement);
3164
+ observedElements.delete(existingElement);
3165
+ }
3166
+ observedElements.set(element, index);
3167
+ elementsByIndex.set(index, new WeakRef(element));
3168
+ resizeObserver.observe(element);
3169
+ measureQueue.add(index);
3170
+ scheduleFlush();
3171
+ },
3172
+ unobserve(element) {
3173
+ if (!resizeObserver) return;
3174
+ const index = observedElements.get(element);
3175
+ if (index !== void 0) {
3176
+ resizeObserver.unobserve(element);
3177
+ observedElements.delete(element);
3178
+ elementsByIndex.delete(index);
3179
+ measureQueue.delete(index);
3180
+ }
3181
+ }
3182
+ };
3183
+ return {
3184
+ name: "auto-measurer",
3185
+ version: "1.0.0",
3186
+ type: "core",
3187
+ install(k) {
3188
+ kernel = k;
3189
+ kernel.configure({ estimatedItemHeight });
3190
+ if (measureOnResize && typeof ResizeObserver !== "undefined") {
3191
+ resizeObserver = new ResizeObserver(handleResize);
3192
+ }
3193
+ },
3194
+ uninstall() {
3195
+ if (resizeObserver) {
3196
+ resizeObserver.disconnect();
3197
+ resizeObserver = null;
3198
+ }
3199
+ debouncedFlush.cancel();
3200
+ measureQueue.clear();
3201
+ elementsByIndex.clear();
3202
+ flushScheduled = false;
3203
+ kernel = null;
3204
+ },
3205
+ api
3206
+ };
3207
+ }
3208
+
3209
+ // src/plugins/core/infinite-loader.ts
3210
+ function infiniteLoaderPlugin(options) {
3211
+ const {
3212
+ threshold = 200,
3213
+ thresholdItems = 5,
3214
+ direction = "forward",
3215
+ onLoadMore
3216
+ } = options;
3217
+ let kernel = null;
3218
+ let loading = false;
3219
+ let hasMoreForward = true;
3220
+ let hasMoreBackward = direction === "backward" || direction === "both";
3221
+ let lastCheckTime = 0;
3222
+ const checkDebounceMs = 100;
3223
+ function checkLoadMore(event) {
3224
+ if (loading || !kernel) return;
3225
+ const now = performance.now();
3226
+ if (now - lastCheckTime < checkDebounceMs) return;
3227
+ lastCheckTime = now;
3228
+ const viewport = kernel.getViewport();
3229
+ const totalSize = kernel.getTotalSize();
3230
+ const { scrollTop } = event;
3231
+ if ((direction === "forward" || direction === "both") && hasMoreForward) {
3232
+ const distanceFromBottom = totalSize - scrollTop - viewport.height;
3233
+ if (distanceFromBottom < threshold) {
3234
+ triggerLoad("forward");
3235
+ return;
3236
+ }
3237
+ }
3238
+ if ((direction === "backward" || direction === "both") && hasMoreBackward) {
3239
+ if (scrollTop < threshold) {
3240
+ triggerLoad("backward");
3241
+ return;
3242
+ }
3243
+ }
3244
+ }
3245
+ function checkLoadMoreByRange(range) {
3246
+ if (loading || !kernel) return;
3247
+ const itemCount = kernel.getItemCount();
3248
+ if ((direction === "forward" || direction === "both") && hasMoreForward) {
3249
+ const itemsFromEnd = itemCount - 1 - range.endIndex;
3250
+ if (itemsFromEnd <= thresholdItems) {
3251
+ triggerLoad("forward");
3252
+ return;
3253
+ }
3254
+ }
3255
+ if ((direction === "backward" || direction === "both") && hasMoreBackward) {
3256
+ if (range.startIndex <= thresholdItems) {
3257
+ triggerLoad("backward");
3258
+ return;
3259
+ }
3260
+ }
3261
+ }
3262
+ async function triggerLoad(loadDirection) {
3263
+ if (loading || !kernel) return;
3264
+ if (loadDirection === "forward" && !hasMoreForward) return;
3265
+ if (loadDirection === "backward" && !hasMoreBackward) return;
3266
+ loading = true;
3267
+ kernel.emit({
3268
+ type: "load-more",
3269
+ direction: loadDirection
3270
+ });
3271
+ try {
3272
+ await onLoadMore(loadDirection);
3273
+ } catch (error) {
3274
+ console.error("[Scrollex] Error in onLoadMore:", error);
3275
+ } finally {
3276
+ loading = false;
3277
+ }
3278
+ }
3279
+ const api = {
3280
+ isLoading() {
3281
+ return loading;
3282
+ },
3283
+ setLoading(l) {
3284
+ loading = l;
3285
+ },
3286
+ hasMore() {
3287
+ return hasMoreForward || hasMoreBackward;
3288
+ },
3289
+ setHasMore(hasMore) {
3290
+ hasMoreForward = hasMore;
3291
+ hasMoreBackward = hasMore;
3292
+ },
3293
+ hasMoreForward() {
3294
+ return hasMoreForward;
3295
+ },
3296
+ setHasMoreForward(hasMore) {
3297
+ hasMoreForward = hasMore;
3298
+ },
3299
+ hasMoreBackward() {
3300
+ return hasMoreBackward;
3301
+ },
3302
+ setHasMoreBackward(hasMore) {
3303
+ hasMoreBackward = hasMore;
3304
+ },
3305
+ reset() {
3306
+ loading = false;
3307
+ hasMoreForward = true;
3308
+ hasMoreBackward = direction === "backward" || direction === "both";
3309
+ },
3310
+ triggerLoad(loadDirection) {
3311
+ triggerLoad(loadDirection);
3312
+ }
3313
+ };
3314
+ return {
3315
+ name: "infinite-loader",
3316
+ version: "1.0.0",
3317
+ type: "core",
3318
+ install(k) {
3319
+ kernel = k;
3320
+ },
3321
+ uninstall() {
3322
+ kernel = null;
3323
+ loading = false;
3324
+ },
3325
+ hooks: {
3326
+ onScroll: checkLoadMore,
3327
+ onVisibleRangeChange: (range) => checkLoadMoreByRange(range)
3328
+ },
3329
+ api
3330
+ };
3331
+ }
3332
+
3333
+ // src/plugins/core/scroll-controller.ts
3334
+ var easings2 = {
3335
+ easeInOut: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t};
3336
+ function scrollControllerPlugin(options = {}) {
3337
+ const {
3338
+ defaultDuration = 300,
3339
+ defaultEasing = easings2.easeInOut
3340
+ } = options;
3341
+ let kernel = null;
3342
+ let animationId = null;
3343
+ let animating = false;
3344
+ function animateScroll(targetOffset, duration, easing) {
3345
+ if (!kernel) return;
3346
+ stopAnimation();
3347
+ const startTime = performance.now();
3348
+ const startOffset = kernel.getScrollPosition().scrollTop;
3349
+ const distance = targetOffset - startOffset;
3350
+ if (distance === 0 || duration === 0) {
3351
+ kernel.setScrollPosition({ scrollTop: targetOffset, scrollLeft: 0 });
3352
+ return;
3353
+ }
3354
+ animating = true;
3355
+ function animate(currentTime) {
3356
+ if (!kernel) {
3357
+ animating = false;
3358
+ return;
3359
+ }
3360
+ const elapsed = currentTime - startTime;
3361
+ const progress = Math.min(elapsed / duration, 1);
3362
+ const easedProgress = easing(progress);
3363
+ const currentOffset = startOffset + distance * easedProgress;
3364
+ kernel.setScrollPosition({ scrollTop: currentOffset, scrollLeft: 0 });
3365
+ if (progress < 1) {
3366
+ animationId = raf(animate);
3367
+ } else {
3368
+ animationId = null;
3369
+ animating = false;
3370
+ }
3371
+ }
3372
+ animationId = raf(animate);
3373
+ }
3374
+ function stopAnimation() {
3375
+ if (animationId !== null) {
3376
+ cancelRaf(animationId);
3377
+ animationId = null;
3378
+ }
3379
+ animating = false;
3380
+ }
3381
+ const api = {
3382
+ scrollTo(offset, options2 = {}) {
3383
+ if (!kernel) return;
3384
+ const {
3385
+ behavior = "auto",
3386
+ duration = defaultDuration,
3387
+ easing = defaultEasing
3388
+ } = options2;
3389
+ if (behavior === "auto") {
3390
+ stopAnimation();
3391
+ kernel.setScrollPosition({ scrollTop: offset, scrollLeft: 0 });
3392
+ } else {
3393
+ animateScroll(offset, duration, easing);
3394
+ }
3395
+ },
3396
+ scrollToIndex(index, options2 = {}) {
3397
+ if (!kernel) return;
3398
+ const {
3399
+ align = "auto",
3400
+ offset: additionalOffset = 0,
3401
+ ...scrollOptions
3402
+ } = options2;
3403
+ const itemOffset = kernel.getItemOffset(index);
3404
+ const itemSize = kernel.getCachedHeight(index) ?? kernel.getEstimatedHeight();
3405
+ const viewport = kernel.getViewport();
3406
+ let targetOffset;
3407
+ switch (align) {
3408
+ case "start":
3409
+ targetOffset = itemOffset;
3410
+ break;
3411
+ case "center":
3412
+ targetOffset = itemOffset - viewport.height / 2 + itemSize / 2;
3413
+ break;
3414
+ case "end":
3415
+ targetOffset = itemOffset - viewport.height + itemSize;
3416
+ break;
3417
+ case "auto":
3418
+ default: {
3419
+ const scrollPosition = kernel.getScrollPosition();
3420
+ const visibleStart = scrollPosition.scrollTop;
3421
+ const visibleEnd = visibleStart + viewport.height;
3422
+ const itemEnd = itemOffset + itemSize;
3423
+ if (itemOffset < visibleStart) {
3424
+ targetOffset = itemOffset;
3425
+ } else if (itemEnd > visibleEnd) {
3426
+ targetOffset = itemEnd - viewport.height;
3427
+ } else {
3428
+ return;
3429
+ }
3430
+ break;
3431
+ }
3432
+ }
3433
+ const maxScroll = Math.max(0, kernel.getTotalSize() - viewport.height);
3434
+ targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
3435
+ api.scrollTo(targetOffset, scrollOptions);
3436
+ },
3437
+ scrollToTop(options2 = {}) {
3438
+ api.scrollTo(0, options2);
3439
+ },
3440
+ scrollToBottom(options2 = {}) {
3441
+ if (!kernel) return;
3442
+ const viewport = kernel.getViewport();
3443
+ const totalSize = kernel.getTotalSize();
3444
+ const maxScroll = Math.max(0, totalSize - viewport.height);
3445
+ api.scrollTo(maxScroll, options2);
3446
+ },
3447
+ getScrollPosition() {
3448
+ return kernel?.getScrollPosition() ?? { scrollTop: 0, scrollLeft: 0 };
3449
+ },
3450
+ isScrolling() {
3451
+ return kernel?.isScrolling() ?? false;
3452
+ },
3453
+ isAnimating() {
3454
+ return animating;
3455
+ },
3456
+ stopAnimation
3457
+ };
3458
+ return {
3459
+ name: "scroll-controller",
3460
+ version: "1.0.0",
3461
+ type: "core",
3462
+ install(k) {
3463
+ kernel = k;
3464
+ },
3465
+ uninstall() {
3466
+ stopAnimation();
3467
+ kernel = null;
3468
+ },
3469
+ api
3470
+ };
3471
+ }
3472
+
3473
+ export { VirtualGrid, VirtualList, VirtualMasonry, autoMeasurerPlugin, createKernel, createPlugin, easings, gridRendererPlugin, infiniteLoaderPlugin, listRendererPlugin, scrollControllerPlugin, useMeasure, useMeasureMany, useScrollex, useScrollexRequired, useVirtualGrid, useVirtualList, useVirtualMasonry };
3474
+ //# sourceMappingURL=index.js.map
3475
+ //# sourceMappingURL=index.js.map