@oxog/scrollex 1.0.0 → 1.0.3

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.
@@ -4,32 +4,6 @@ var react = require('react');
4
4
  var jsxRuntime = require('react/jsx-runtime');
5
5
 
6
6
  // src/plugins/core/list-renderer.ts
7
- var VirtualItemPool = class {
8
- constructor() {
9
- this.pool = [];
10
- }
11
- acquire() {
12
- const item = this.pool.pop();
13
- if (item) {
14
- return item;
15
- }
16
- return { index: 0, key: 0, start: 0, end: 0, size: 0, lane: 0 };
17
- }
18
- release(item) {
19
- item.index = 0;
20
- item.key = 0;
21
- item.start = 0;
22
- item.end = 0;
23
- item.size = 0;
24
- item.lane = 0;
25
- this.pool.push(item);
26
- }
27
- releaseAll(items) {
28
- for (const item of items) {
29
- this.release(item);
30
- }
31
- }
32
- };
33
7
  function listRendererPlugin(options = {}) {
34
8
  const { getItemKey = (index) => index } = options;
35
9
  let kernel = null;
@@ -40,24 +14,24 @@ function listRendererPlugin(options = {}) {
40
14
  overscanStartIndex: 0,
41
15
  overscanEndIndex: 0
42
16
  };
43
- const itemPool = new VirtualItemPool();
44
17
  function buildVirtualItems(range) {
45
18
  if (!kernel) return [];
46
- itemPool.releaseAll(virtualItems);
47
19
  const items = [];
48
20
  range.startIndex;
49
21
  range.endIndex;
50
- for (let i = range.overscanStartIndex; i <= range.overscanEndIndex; i++) {
51
- const item = itemPool.acquire();
22
+ const lastIndex = Math.min(range.overscanEndIndex, kernel.getItemCount() - 1);
23
+ for (let i = range.overscanStartIndex; i <= lastIndex; i++) {
52
24
  const offset = kernel.getItemOffset(i);
53
25
  const size = kernel.getCachedHeight(i) ?? kernel.getEstimatedHeight();
54
- item.index = i;
55
- item.key = getItemKey(i);
56
- item.start = offset;
57
- item.end = offset + size;
58
- item.size = size;
59
- item.lane = 0;
60
- items.push(item);
26
+ items.push({
27
+ index: i,
28
+ key: getItemKey(i),
29
+ start: offset,
30
+ end: offset + size,
31
+ size,
32
+ lane: 0
33
+ // For list, always lane 0
34
+ });
61
35
  }
62
36
  return items;
63
37
  }
@@ -83,6 +57,7 @@ function listRendererPlugin(options = {}) {
83
57
  return lastItem?.end ?? 0;
84
58
  },
85
59
  isItemVisible(index) {
60
+ if (!kernel || index >= kernel.getItemCount()) return false;
86
61
  return index >= currentRange.startIndex && index <= currentRange.endIndex;
87
62
  },
88
63
  recalculate
@@ -96,7 +71,6 @@ function listRendererPlugin(options = {}) {
96
71
  recalculate();
97
72
  },
98
73
  uninstall() {
99
- itemPool.releaseAll(virtualItems);
100
74
  virtualItems = [];
101
75
  kernel = null;
102
76
  },
@@ -114,6 +88,15 @@ function listRendererPlugin(options = {}) {
114
88
  };
115
89
  }
116
90
 
91
+ // src/utils/array.ts
92
+ function normalizeColumnCount(columns) {
93
+ return Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 1;
94
+ }
95
+ function autoColumnCount(containerWidth, minColumnWidth, gap) {
96
+ const slot = minColumnWidth + gap;
97
+ return slot > 0 ? normalizeColumnCount(Math.floor((containerWidth + gap) / slot)) : 1;
98
+ }
99
+
117
100
  // src/plugins/core/grid-renderer.ts
118
101
  function gridRendererPlugin(options) {
119
102
  const {
@@ -121,19 +104,20 @@ function gridRendererPlugin(options) {
121
104
  minColumnWidth = 100,
122
105
  rowHeight,
123
106
  gap = 0,
124
- getItemKey = (index) => index
107
+ getItemKey = (index) => index,
108
+ getContainerWidth
125
109
  } = options;
126
110
  let kernel = null;
127
111
  let virtualItems = [];
128
- let columnCount = typeof columns === "number" ? columns : 1;
112
+ let columnCount = typeof columns === "number" ? normalizeColumnCount(columns) : 1;
129
113
  let columnWidth = 0;
130
114
  let gapX = typeof gap === "number" ? gap : gap.x;
131
115
  let gapY = typeof gap === "number" ? gap : gap.y;
132
116
  function calculateColumns(containerWidth) {
133
117
  if (typeof columns === "number") {
134
- columnCount = columns;
118
+ columnCount = normalizeColumnCount(columns);
135
119
  } else {
136
- columnCount = Math.max(1, Math.floor((containerWidth + gapX) / (minColumnWidth + gapX)));
120
+ columnCount = autoColumnCount(containerWidth, minColumnWidth, gapX);
137
121
  }
138
122
  columnWidth = (containerWidth - (columnCount - 1) * gapX) / columnCount;
139
123
  }
@@ -174,7 +158,7 @@ function gridRendererPlugin(options) {
174
158
  function recalculate() {
175
159
  if (!kernel) return;
176
160
  const viewport = kernel.getViewport();
177
- calculateColumns(viewport.width);
161
+ calculateColumns(getContainerWidth?.() ?? viewport.width);
178
162
  virtualItems = buildVirtualItems();
179
163
  }
180
164
  const api = {
@@ -182,7 +166,8 @@ function gridRendererPlugin(options) {
182
166
  return virtualItems;
183
167
  },
184
168
  getTotalHeight() {
185
- return getRowCount() * (rowHeight + gapY) - gapY;
169
+ const rowCount = getRowCount();
170
+ return rowCount === 0 ? 0 : rowCount * (rowHeight + gapY) - gapY;
186
171
  },
187
172
  getColumnCount() {
188
173
  return columnCount;
@@ -264,7 +249,7 @@ function debounce(fn, wait) {
264
249
  // src/plugins/core/auto-measurer.ts
265
250
  function autoMeasurerPlugin(options = {}) {
266
251
  const {
267
- estimatedItemHeight = 50,
252
+ estimatedItemHeight,
268
253
  measureOnResize = true,
269
254
  debounceMs = 100
270
255
  } = options;
@@ -274,6 +259,9 @@ function autoMeasurerPlugin(options = {}) {
274
259
  const elementsByIndex = /* @__PURE__ */ new Map();
275
260
  let measureQueue = /* @__PURE__ */ new Set();
276
261
  let flushScheduled = false;
262
+ function sizeAlongAxis(rect) {
263
+ return kernel?.getOptions().direction === "horizontal" ? rect.width : rect.height;
264
+ }
277
265
  const debouncedFlush = debounce(() => {
278
266
  flush();
279
267
  }, debounceMs);
@@ -291,7 +279,7 @@ function autoMeasurerPlugin(options = {}) {
291
279
  const element = ref?.deref();
292
280
  if (element) {
293
281
  const rect = element.getBoundingClientRect();
294
- measurements.push({ index, height: rect.height });
282
+ measurements.push({ index, height: sizeAlongAxis(rect) });
295
283
  }
296
284
  }
297
285
  for (const { index, height } of measurements) {
@@ -322,7 +310,7 @@ function autoMeasurerPlugin(options = {}) {
322
310
  const api = {
323
311
  measureElement(index, element) {
324
312
  const rect = element.getBoundingClientRect();
325
- const height = rect.height;
313
+ const height = sizeAlongAxis(rect);
326
314
  if (height > 0 && kernel) {
327
315
  kernel.measureItem(index, height);
328
316
  }
@@ -350,24 +338,27 @@ function autoMeasurerPlugin(options = {}) {
350
338
  return cache;
351
339
  },
352
340
  observe(index, element) {
353
- if (!resizeObserver) return;
354
341
  const existingRef = elementsByIndex.get(index);
355
342
  const existingElement = existingRef?.deref();
356
343
  if (existingElement && existingElement !== element) {
357
- resizeObserver.unobserve(existingElement);
344
+ resizeObserver?.unobserve(existingElement);
358
345
  observedElements.delete(existingElement);
359
346
  }
347
+ const previousIndex = observedElements.get(element);
348
+ if (previousIndex !== void 0 && previousIndex !== index) {
349
+ elementsByIndex.delete(previousIndex);
350
+ measureQueue.delete(previousIndex);
351
+ }
360
352
  observedElements.set(element, index);
361
- elementsByIndex.set(index, new WeakRef(element));
362
- resizeObserver.observe(element);
353
+ elementsByIndex.set(index, typeof WeakRef === "function" ? new WeakRef(element) : { deref: () => element });
354
+ resizeObserver?.observe(element);
363
355
  measureQueue.add(index);
364
356
  scheduleFlush();
365
357
  },
366
358
  unobserve(element) {
367
- if (!resizeObserver) return;
368
359
  const index = observedElements.get(element);
369
360
  if (index !== void 0) {
370
- resizeObserver.unobserve(element);
361
+ resizeObserver?.unobserve(element);
371
362
  observedElements.delete(element);
372
363
  elementsByIndex.delete(index);
373
364
  measureQueue.delete(index);
@@ -380,7 +371,9 @@ function autoMeasurerPlugin(options = {}) {
380
371
  type: "core",
381
372
  install(k) {
382
373
  kernel = k;
383
- kernel.configure({ estimatedItemHeight });
374
+ if (estimatedItemHeight !== void 0) {
375
+ kernel.configure({ estimatedItemHeight });
376
+ }
384
377
  if (measureOnResize && typeof ResizeObserver !== "undefined") {
385
378
  resizeObserver = new ResizeObserver(handleResize);
386
379
  }
@@ -401,6 +394,10 @@ function autoMeasurerPlugin(options = {}) {
401
394
  }
402
395
 
403
396
  // src/plugins/core/infinite-loader.ts
397
+ function initialLoaderState(direction) {
398
+ return { loading: false, loadGeneration: 0, hasMoreForward: true, hasMoreBackward: direction === "backward" || direction === "both" };
399
+ }
400
+ var sharedLoaderStates = /* @__PURE__ */ new WeakMap();
404
401
  function infiniteLoaderPlugin(options) {
405
402
  const {
406
403
  threshold = 200,
@@ -409,44 +406,61 @@ function infiniteLoaderPlugin(options) {
409
406
  onLoadMore
410
407
  } = options;
411
408
  let kernel = null;
412
- let loading = false;
413
- let hasMoreForward = true;
414
- let hasMoreBackward = direction === "backward" || direction === "both";
409
+ let state = initialLoaderState(direction);
415
410
  let lastCheckTime = 0;
416
411
  const checkDebounceMs = 100;
412
+ let pendingEvent = null;
413
+ let trailingTimer = null;
417
414
  function checkLoadMore(event) {
418
- if (loading || !kernel) return;
415
+ if (state.loading || !kernel) return;
419
416
  const now = performance.now();
420
- if (now - lastCheckTime < checkDebounceMs) return;
421
- lastCheckTime = now;
417
+ if (now - lastCheckTime < checkDebounceMs) {
418
+ pendingEvent = event;
419
+ if (trailingTimer === null) {
420
+ trailingTimer = setTimeout(() => {
421
+ trailingTimer = null;
422
+ const latest = pendingEvent;
423
+ pendingEvent = null;
424
+ if (latest) runCheck(latest);
425
+ }, Math.max(0, checkDebounceMs - (now - lastCheckTime)));
426
+ }
427
+ return;
428
+ }
429
+ runCheck(event);
430
+ }
431
+ function runCheck(event) {
432
+ if (state.loading || !kernel) return;
433
+ lastCheckTime = performance.now();
422
434
  const viewport = kernel.getViewport();
423
435
  const totalSize = kernel.getTotalSize();
424
- const { scrollTop } = event;
425
- if ((direction === "forward" || direction === "both") && hasMoreForward) {
426
- const distanceFromBottom = totalSize - scrollTop - viewport.height;
436
+ const horizontal = kernel.getOptions().direction === "horizontal";
437
+ const scrollTop = horizontal ? event.scrollLeft : event.scrollTop;
438
+ const viewportSize = horizontal ? viewport.width : viewport.height;
439
+ if ((direction === "forward" || direction === "both") && state.hasMoreForward) {
440
+ const distanceFromBottom = totalSize - scrollTop - viewportSize;
427
441
  if (distanceFromBottom < threshold) {
428
442
  triggerLoad("forward");
429
443
  return;
430
444
  }
431
445
  }
432
- if ((direction === "backward" || direction === "both") && hasMoreBackward) {
446
+ if ((direction === "backward" || direction === "both") && state.hasMoreBackward) {
433
447
  if (scrollTop < threshold) {
434
448
  triggerLoad("backward");
435
449
  return;
436
450
  }
437
451
  }
438
452
  }
439
- function checkLoadMoreByRange(range) {
440
- if (loading || !kernel) return;
453
+ function checkLoadMoreByRange(range, forwardOnly = false) {
454
+ if (state.loading || !kernel) return;
441
455
  const itemCount = kernel.getItemCount();
442
- if ((direction === "forward" || direction === "both") && hasMoreForward) {
456
+ if ((direction === "forward" || direction === "both") && state.hasMoreForward) {
443
457
  const itemsFromEnd = itemCount - 1 - range.endIndex;
444
458
  if (itemsFromEnd <= thresholdItems) {
445
459
  triggerLoad("forward");
446
460
  return;
447
461
  }
448
462
  }
449
- if ((direction === "backward" || direction === "both") && hasMoreBackward) {
463
+ if (!forwardOnly && (direction === "backward" || direction === "both") && state.hasMoreBackward) {
450
464
  if (range.startIndex <= thresholdItems) {
451
465
  triggerLoad("backward");
452
466
  return;
@@ -454,10 +468,11 @@ function infiniteLoaderPlugin(options) {
454
468
  }
455
469
  }
456
470
  async function triggerLoad(loadDirection) {
457
- if (loading || !kernel) return;
458
- if (loadDirection === "forward" && !hasMoreForward) return;
459
- if (loadDirection === "backward" && !hasMoreBackward) return;
460
- loading = true;
471
+ if (state.loading || !kernel) return;
472
+ if (loadDirection === "forward" && !state.hasMoreForward) return;
473
+ if (loadDirection === "backward" && !state.hasMoreBackward) return;
474
+ state.loading = true;
475
+ const generation = ++state.loadGeneration;
461
476
  kernel.emit({
462
477
  type: "load-more",
463
478
  direction: loadDirection
@@ -467,39 +482,47 @@ function infiniteLoaderPlugin(options) {
467
482
  } catch (error) {
468
483
  console.error("[Scrollex] Error in onLoadMore:", error);
469
484
  } finally {
470
- loading = false;
485
+ if (generation === state.loadGeneration) {
486
+ state.loading = false;
487
+ }
471
488
  }
472
489
  }
473
490
  const api = {
474
491
  isLoading() {
475
- return loading;
492
+ return state.loading;
476
493
  },
477
494
  setLoading(l) {
478
- loading = l;
495
+ state.loading = l;
479
496
  },
480
497
  hasMore() {
481
- return hasMoreForward || hasMoreBackward;
498
+ return state.hasMoreForward || state.hasMoreBackward;
482
499
  },
483
500
  setHasMore(hasMore) {
484
- hasMoreForward = hasMore;
485
- hasMoreBackward = hasMore;
501
+ state.hasMoreForward = hasMore;
502
+ state.hasMoreBackward = hasMore;
486
503
  },
487
504
  hasMoreForward() {
488
- return hasMoreForward;
505
+ return state.hasMoreForward;
489
506
  },
490
507
  setHasMoreForward(hasMore) {
491
- hasMoreForward = hasMore;
508
+ state.hasMoreForward = hasMore;
492
509
  },
493
510
  hasMoreBackward() {
494
- return hasMoreBackward;
511
+ return state.hasMoreBackward;
495
512
  },
496
513
  setHasMoreBackward(hasMore) {
497
- hasMoreBackward = hasMore;
514
+ state.hasMoreBackward = hasMore;
498
515
  },
499
516
  reset() {
500
- loading = false;
501
- hasMoreForward = true;
502
- hasMoreBackward = direction === "backward" || direction === "both";
517
+ state.loadGeneration++;
518
+ state.loading = false;
519
+ state.hasMoreForward = true;
520
+ state.hasMoreBackward = direction === "backward" || direction === "both";
521
+ if (trailingTimer !== null) {
522
+ clearTimeout(trailingTimer);
523
+ trailingTimer = null;
524
+ }
525
+ pendingEvent = null;
503
526
  },
504
527
  triggerLoad(loadDirection) {
505
528
  triggerLoad(loadDirection);
@@ -511,10 +534,21 @@ function infiniteLoaderPlugin(options) {
511
534
  type: "core",
512
535
  install(k) {
513
536
  kernel = k;
537
+ const shared = sharedLoaderStates.get(k);
538
+ if (shared) {
539
+ state = shared;
540
+ } else {
541
+ sharedLoaderStates.set(k, state);
542
+ checkLoadMoreByRange(k.getVisibleRange(), true);
543
+ }
514
544
  },
515
545
  uninstall() {
546
+ if (trailingTimer !== null) {
547
+ clearTimeout(trailingTimer);
548
+ trailingTimer = null;
549
+ }
550
+ pendingEvent = null;
516
551
  kernel = null;
517
- loading = false;
518
552
  },
519
553
  hooks: {
520
554
  onScroll: checkLoadMore,
@@ -529,7 +563,7 @@ function raf(callback) {
529
563
  if (typeof requestAnimationFrame !== "undefined") {
530
564
  return requestAnimationFrame(callback);
531
565
  }
532
- return setTimeout(() => callback(Date.now()), 16);
566
+ return setTimeout(() => callback(performance.now()), 16);
533
567
  }
534
568
  function cancelRaf(id) {
535
569
  if (typeof cancelAnimationFrame !== "undefined") {
@@ -550,14 +584,30 @@ function scrollControllerPlugin(options = {}) {
550
584
  let kernel = null;
551
585
  let animationId = null;
552
586
  let animating = false;
587
+ let animationGeneration = 0;
588
+ function isHorizontal(k) {
589
+ return k.getOptions().direction === "horizontal";
590
+ }
591
+ function getOffset(k) {
592
+ const position = k.getScrollPosition();
593
+ return isHorizontal(k) ? position.scrollLeft : position.scrollTop;
594
+ }
595
+ function setOffset(k, offset) {
596
+ k.setScrollPosition(isHorizontal(k) ? { scrollLeft: offset } : { scrollTop: offset });
597
+ }
598
+ function getViewportSize(k) {
599
+ const viewport = k.getViewport();
600
+ return isHorizontal(k) ? viewport.width : viewport.height;
601
+ }
553
602
  function animateScroll(targetOffset, duration, easing) {
554
603
  if (!kernel) return;
555
604
  stopAnimation();
605
+ const generation = animationGeneration;
556
606
  const startTime = performance.now();
557
- const startOffset = kernel.getScrollPosition().scrollTop;
607
+ const startOffset = getOffset(kernel);
558
608
  const distance = targetOffset - startOffset;
559
- if (distance === 0 || duration === 0) {
560
- kernel.setScrollPosition({ scrollTop: targetOffset, scrollLeft: 0 });
609
+ if (distance === 0 || !(duration > 0)) {
610
+ setOffset(kernel, targetOffset);
561
611
  return;
562
612
  }
563
613
  animating = true;
@@ -566,11 +616,13 @@ function scrollControllerPlugin(options = {}) {
566
616
  animating = false;
567
617
  return;
568
618
  }
619
+ if (generation !== animationGeneration) return;
569
620
  const elapsed = currentTime - startTime;
570
- const progress = Math.min(elapsed / duration, 1);
621
+ const progress = Math.max(0, Math.min(elapsed / duration, 1));
571
622
  const easedProgress = easing(progress);
572
623
  const currentOffset = startOffset + distance * easedProgress;
573
- kernel.setScrollPosition({ scrollTop: currentOffset, scrollLeft: 0 });
624
+ setOffset(kernel, currentOffset);
625
+ if (generation !== animationGeneration) return;
574
626
  if (progress < 1) {
575
627
  animationId = raf(animate);
576
628
  } else {
@@ -581,6 +633,7 @@ function scrollControllerPlugin(options = {}) {
581
633
  animationId = raf(animate);
582
634
  }
583
635
  function stopAnimation() {
636
+ animationGeneration++;
584
637
  if (animationId !== null) {
585
638
  cancelRaf(animationId);
586
639
  animationId = null;
@@ -597,7 +650,7 @@ function scrollControllerPlugin(options = {}) {
597
650
  } = options2;
598
651
  if (behavior === "auto") {
599
652
  stopAnimation();
600
- kernel.setScrollPosition({ scrollTop: offset, scrollLeft: 0 });
653
+ setOffset(kernel, offset);
601
654
  } else {
602
655
  animateScroll(offset, duration, easing);
603
656
  }
@@ -611,35 +664,34 @@ function scrollControllerPlugin(options = {}) {
611
664
  } = options2;
612
665
  const itemOffset = kernel.getItemOffset(index);
613
666
  const itemSize = kernel.getCachedHeight(index) ?? kernel.getEstimatedHeight();
614
- const viewport = kernel.getViewport();
667
+ const viewportSize = getViewportSize(kernel);
615
668
  let targetOffset;
616
669
  switch (align) {
617
670
  case "start":
618
671
  targetOffset = itemOffset;
619
672
  break;
620
673
  case "center":
621
- targetOffset = itemOffset - viewport.height / 2 + itemSize / 2;
674
+ targetOffset = itemOffset - viewportSize / 2 + itemSize / 2;
622
675
  break;
623
676
  case "end":
624
- targetOffset = itemOffset - viewport.height + itemSize;
677
+ targetOffset = itemOffset - viewportSize + itemSize;
625
678
  break;
626
679
  case "auto":
627
680
  default: {
628
- const scrollPosition = kernel.getScrollPosition();
629
- const visibleStart = scrollPosition.scrollTop;
630
- const visibleEnd = visibleStart + viewport.height;
681
+ const visibleStart = getOffset(kernel);
682
+ const visibleEnd = visibleStart + viewportSize;
631
683
  const itemEnd = itemOffset + itemSize;
632
684
  if (itemOffset < visibleStart) {
633
685
  targetOffset = itemOffset;
634
686
  } else if (itemEnd > visibleEnd) {
635
- targetOffset = itemEnd - viewport.height;
687
+ targetOffset = itemEnd - viewportSize;
636
688
  } else {
637
689
  return;
638
690
  }
639
691
  break;
640
692
  }
641
693
  }
642
- const maxScroll = Math.max(0, kernel.getTotalSize() - viewport.height);
694
+ const maxScroll = Math.max(0, kernel.getTotalSize() - viewportSize);
643
695
  targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
644
696
  api.scrollTo(targetOffset, scrollOptions);
645
697
  },
@@ -648,9 +700,8 @@ function scrollControllerPlugin(options = {}) {
648
700
  },
649
701
  scrollToBottom(options2 = {}) {
650
702
  if (!kernel) return;
651
- const viewport = kernel.getViewport();
652
703
  const totalSize = kernel.getTotalSize();
653
- const maxScroll = Math.max(0, totalSize - viewport.height);
704
+ const maxScroll = Math.max(0, totalSize - getViewportSize(kernel));
654
705
  api.scrollTo(maxScroll, options2);
655
706
  },
656
707
  getScrollPosition() {
@@ -690,16 +741,16 @@ function masonryRenderer(options) {
690
741
  } = options;
691
742
  let kernel = null;
692
743
  let virtualItems = [];
693
- let columnCount = typeof columns === "number" ? columns : 1;
744
+ let columnCount = typeof columns === "number" ? normalizeColumnCount(columns) : 1;
694
745
  let columnWidth = 0;
695
746
  let columnHeights = [];
696
747
  let totalHeight = 0;
697
748
  const layoutCache = /* @__PURE__ */ new Map();
698
749
  function calculateColumns(containerWidth) {
699
750
  if (typeof columns === "number") {
700
- columnCount = columns;
751
+ columnCount = normalizeColumnCount(columns);
701
752
  } else {
702
- columnCount = Math.max(1, Math.floor((containerWidth + gap) / (minColumnWidth + gap)));
753
+ columnCount = autoColumnCount(containerWidth, minColumnWidth, gap);
703
754
  }
704
755
  columnWidth = (containerWidth - (columnCount - 1) * gap) / columnCount;
705
756
  }
@@ -707,6 +758,7 @@ function masonryRenderer(options) {
707
758
  if (!kernel) return;
708
759
  const itemCount = kernel.getItemCount();
709
760
  columnHeights = new Array(columnCount).fill(0);
761
+ const itemsInColumn = new Array(columnCount).fill(0);
710
762
  layoutCache.clear();
711
763
  for (let i = 0; i < itemCount; i++) {
712
764
  let shortestCol = 0;
@@ -715,15 +767,15 @@ function masonryRenderer(options) {
715
767
  shortestCol = j;
716
768
  }
717
769
  }
718
- const itemHeight = getItemHeight(i, columnWidth);
770
+ const measured = getItemHeight(i, columnWidth);
771
+ const itemHeight = Number.isFinite(measured) && measured > 0 ? measured : 0;
719
772
  const top = columnHeights[shortestCol] ?? 0;
720
773
  layoutCache.set(i, { top, lane: shortestCol, height: itemHeight });
721
774
  columnHeights[shortestCol] = top + itemHeight + gap;
775
+ itemsInColumn[shortestCol] = (itemsInColumn[shortestCol] ?? 0) + 1;
722
776
  }
777
+ columnHeights = columnHeights.map((height, column) => (itemsInColumn[column] ?? 0) > 0 ? height - gap : 0);
723
778
  totalHeight = Math.max(...columnHeights, 0);
724
- if (totalHeight > 0) {
725
- totalHeight -= gap;
726
- }
727
779
  }
728
780
  function buildVirtualItems() {
729
781
  if (!kernel) return [];
@@ -810,6 +862,8 @@ function masonryRenderer(options) {
810
862
  uninstall() {
811
863
  virtualItems = [];
812
864
  layoutCache.clear();
865
+ columnHeights = [];
866
+ totalHeight = 0;
813
867
  kernel = null;
814
868
  },
815
869
  hooks: {
@@ -854,12 +908,15 @@ function stickyHeaders(options) {
854
908
  }
855
909
  }
856
910
  }
857
- function updateStickyHeader(event) {
911
+ function offsetOf(position) {
912
+ return kernel?.getOptions().direction === "horizontal" ? position.scrollLeft : position.scrollTop;
913
+ }
914
+ function updateStickyHeader(scrollOffset) {
858
915
  if (!kernel || headerIndices.length === 0) {
859
916
  currentStickyHeader = null;
860
917
  return;
861
918
  }
862
- const scrollTop = event.scrollTop + stickyOffset;
919
+ const scrollTop = scrollOffset + stickyOffset;
863
920
  let newStickyHeader = null;
864
921
  for (const headerIndex of headerIndices) {
865
922
  const headerOffset = kernel.getItemOffset(headerIndex);
@@ -871,6 +928,10 @@ function stickyHeaders(options) {
871
928
  }
872
929
  currentStickyHeader = newStickyHeader;
873
930
  }
931
+ function refreshStickyHeader() {
932
+ if (!kernel) return;
933
+ updateStickyHeader(offsetOf(kernel.getScrollPosition()));
934
+ }
874
935
  function findHeaderForGroup(groupId) {
875
936
  const items = groupIdMap.get(groupId);
876
937
  if (!items || items.length === 0) return null;
@@ -911,6 +972,7 @@ function stickyHeaders(options) {
911
972
  install(k) {
912
973
  kernel = k;
913
974
  buildHeaderCache();
975
+ refreshStickyHeader();
914
976
  },
915
977
  uninstall() {
916
978
  headerIndices = [];
@@ -919,14 +981,24 @@ function stickyHeaders(options) {
919
981
  kernel = null;
920
982
  },
921
983
  hooks: {
922
- onScroll: updateStickyHeader,
923
- onItemsChange: () => buildHeaderCache()
984
+ onScroll: (event) => updateStickyHeader(offsetOf(event)),
985
+ onItemsChange: () => {
986
+ buildHeaderCache();
987
+ refreshStickyHeader();
988
+ }
924
989
  },
925
990
  api
926
991
  };
927
992
  }
928
993
 
929
994
  // src/plugins/optional/keyboard-nav.ts
995
+ var focusByKernel = /* @__PURE__ */ new WeakMap();
996
+ function isEditableTarget(target) {
997
+ if (!(target instanceof HTMLElement)) return false;
998
+ if (target.isContentEditable) return true;
999
+ const tag = target.tagName;
1000
+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";
1001
+ }
930
1002
  function keyboardNav(options = {}) {
931
1003
  const {
932
1004
  enabled: initialEnabled = true,
@@ -946,6 +1018,9 @@ function keyboardNav(options = {}) {
946
1018
  let focusedIndex = null;
947
1019
  let typeaheadBuffer = "";
948
1020
  let typeaheadTimer = null;
1021
+ function rememberFocus() {
1022
+ if (kernel) focusByKernel.set(kernel, focusedIndex);
1023
+ }
949
1024
  function getItemCount() {
950
1025
  return kernel?.getItemCount() ?? 0;
951
1026
  }
@@ -954,18 +1029,39 @@ function keyboardNav(options = {}) {
954
1029
  if (count === 0) return 0;
955
1030
  return Math.max(0, Math.min(index, count - 1));
956
1031
  }
957
- function setFocus(index) {
1032
+ function revealIndex(index) {
1033
+ if (!kernel) return;
1034
+ if (orientation !== "grid" || columns <= 1) {
1035
+ kernel.scrollToIndex(index, { align: "auto" });
1036
+ return;
1037
+ }
1038
+ const rows = Math.ceil(getItemCount() / columns);
1039
+ if (rows === 0) return;
1040
+ const pitch = kernel.getTotalSize() / rows;
1041
+ const top = Math.floor(index / columns) * pitch;
1042
+ const bottom = top + pitch;
1043
+ const viewportHeight = kernel.getViewport().height;
1044
+ const scrollTop = kernel.getScrollPosition().scrollTop;
1045
+ if (top < scrollTop) {
1046
+ kernel.scrollTo(top);
1047
+ } else if (bottom > scrollTop + viewportHeight) {
1048
+ kernel.scrollTo(bottom - viewportHeight);
1049
+ }
1050
+ }
1051
+ function setFocus(index, wrap = true) {
958
1052
  if (index === null) {
959
1053
  focusedIndex = null;
1054
+ rememberFocus();
960
1055
  return;
961
1056
  }
962
1057
  const count = getItemCount();
963
1058
  if (count === 0) {
964
1059
  focusedIndex = null;
1060
+ rememberFocus();
965
1061
  return;
966
1062
  }
967
1063
  let newIndex = index;
968
- if (loop) {
1064
+ if (loop && wrap) {
969
1065
  if (newIndex < 0) {
970
1066
  newIndex = count - 1;
971
1067
  } else if (newIndex >= count) {
@@ -976,12 +1072,14 @@ function keyboardNav(options = {}) {
976
1072
  }
977
1073
  if (newIndex !== focusedIndex) {
978
1074
  focusedIndex = newIndex;
1075
+ rememberFocus();
979
1076
  onFocus?.(newIndex);
980
- kernel?.scrollToIndex(newIndex, { align: "auto" });
1077
+ revealIndex(newIndex);
981
1078
  }
982
1079
  }
983
1080
  function handleKeyDown(event) {
984
1081
  if (!enabled || !kernel) return;
1082
+ if (isEditableTarget(event.target)) return;
985
1083
  if (onKeyDown) {
986
1084
  const handled = onKeyDown(event, focusedIndex);
987
1085
  if (handled === true) {
@@ -989,19 +1087,18 @@ function keyboardNav(options = {}) {
989
1087
  return;
990
1088
  }
991
1089
  }
1090
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
992
1091
  const count = getItemCount();
993
1092
  if (count === 0) return;
994
- if (focusedIndex === null && count > 0) {
995
- setFocus(0);
996
- }
1093
+ const focusBeforeKey = focusedIndex;
997
1094
  switch (event.key) {
998
1095
  case "ArrowDown":
999
1096
  if (orientation === "vertical" || orientation === "grid") {
1000
1097
  event.preventDefault();
1001
- if (orientation === "grid") {
1002
- setFocus((focusedIndex ?? 0) + columns);
1098
+ if (focusedIndex === null) {
1099
+ setFocus(0);
1003
1100
  } else {
1004
- setFocus((focusedIndex ?? 0) + 1);
1101
+ setFocus(focusedIndex + (orientation === "grid" ? columns : 1));
1005
1102
  }
1006
1103
  }
1007
1104
  break;
@@ -1018,7 +1115,7 @@ function keyboardNav(options = {}) {
1018
1115
  case "ArrowRight":
1019
1116
  if (orientation === "horizontal" || orientation === "grid") {
1020
1117
  event.preventDefault();
1021
- setFocus((focusedIndex ?? 0) + 1);
1118
+ setFocus(focusedIndex === null ? 0 : focusedIndex + 1);
1022
1119
  }
1023
1120
  break;
1024
1121
  case "ArrowLeft":
@@ -1037,35 +1134,35 @@ function keyboardNav(options = {}) {
1037
1134
  break;
1038
1135
  case "PageUp":
1039
1136
  event.preventDefault();
1040
- setFocus((focusedIndex ?? 0) - pageSize);
1137
+ setFocus((focusedIndex ?? 0) - pageSize, false);
1041
1138
  break;
1042
1139
  case "PageDown":
1043
1140
  event.preventDefault();
1044
- setFocus((focusedIndex ?? 0) + pageSize);
1141
+ setFocus((focusedIndex ?? 0) + pageSize, false);
1045
1142
  break;
1046
1143
  case "Enter":
1047
1144
  case " ":
1048
- event.preventDefault();
1049
1145
  if (focusedIndex !== null) {
1146
+ event.preventDefault();
1050
1147
  onSelect?.(focusedIndex);
1051
1148
  }
1052
1149
  break;
1053
1150
  default:
1054
1151
  if (typeahead && event.key.length === 1 && !event.ctrlKey && !event.metaKey) {
1055
1152
  event.preventDefault();
1056
- handleTypeahead(event.key);
1153
+ handleTypeahead(event.key, focusBeforeKey);
1057
1154
  }
1058
1155
  break;
1059
1156
  }
1060
1157
  }
1061
- function handleTypeahead(char) {
1158
+ function handleTypeahead(char, focusBeforeKey) {
1062
1159
  if (!kernel) return;
1063
1160
  if (typeaheadTimer) {
1064
1161
  clearTimeout(typeaheadTimer);
1065
1162
  }
1066
1163
  typeaheadBuffer += char.toLowerCase();
1067
1164
  const count = getItemCount();
1068
- const startIndex = focusedIndex !== null ? focusedIndex + 1 : 0;
1165
+ const startIndex = typeaheadBuffer.length > 1 ? focusedIndex ?? 0 : focusBeforeKey !== null ? focusBeforeKey + 1 : 0;
1069
1166
  for (let i = 0; i < count; i++) {
1070
1167
  const index = (startIndex + i) % count;
1071
1168
  const text = getItemText(index).toLowerCase();
@@ -1134,6 +1231,9 @@ function keyboardNav(options = {}) {
1134
1231
  type: "optional",
1135
1232
  install(k) {
1136
1233
  kernel = k;
1234
+ const remembered = focusByKernel.get(k) ?? null;
1235
+ const count = k.getItemCount();
1236
+ focusedIndex = remembered === null || count === 0 ? null : Math.min(remembered, count - 1);
1137
1237
  document.addEventListener("keydown", handleKeyDown);
1138
1238
  },
1139
1239
  uninstall() {
@@ -1160,6 +1260,7 @@ function keyboardNav(options = {}) {
1160
1260
  }
1161
1261
 
1162
1262
  // src/plugins/optional/scroll-restoration.ts
1263
+ var restoredKernels = /* @__PURE__ */ new WeakMap();
1163
1264
  function scrollRestoration(options) {
1164
1265
  const {
1165
1266
  key,
@@ -1173,6 +1274,8 @@ function scrollRestoration(options) {
1173
1274
  } = options;
1174
1275
  let kernel = null;
1175
1276
  let debouncedSave = null;
1277
+ let restoreFrame = null;
1278
+ let awaitingContent = false;
1176
1279
  function getStorage() {
1177
1280
  if (typeof storage === "string") {
1178
1281
  if (storage === "sessionStorage") {
@@ -1229,7 +1332,7 @@ function scrollRestoration(options) {
1229
1332
  if (!kernel) return false;
1230
1333
  const state = getSavedState();
1231
1334
  if (!state) return false;
1232
- kernel.scrollTo(state.scrollTop);
1335
+ kernel.scrollTo(kernel.getOptions().direction === "horizontal" ? state.scrollLeft : state.scrollTop);
1233
1336
  if (includeIndex && state.focusedIndex !== void 0) {
1234
1337
  const keyboardNav2 = kernel.getPlugin("keyboard-nav");
1235
1338
  if (keyboardNav2?.api?.setFocusedIndex) {
@@ -1238,6 +1341,26 @@ function scrollRestoration(options) {
1238
1341
  }
1239
1342
  return true;
1240
1343
  }
1344
+ function restoreOnceReachable() {
1345
+ if (!kernel || restoredKernels.get(kernel) === key) {
1346
+ awaitingContent = false;
1347
+ return;
1348
+ }
1349
+ const state = getSavedState();
1350
+ if (state) {
1351
+ const horizontal = kernel.getOptions().direction === "horizontal";
1352
+ const viewport = kernel.getViewport();
1353
+ const target = horizontal ? state.scrollLeft : state.scrollTop;
1354
+ const maxScroll = kernel.getTotalSize() - (horizontal ? viewport.width : viewport.height);
1355
+ if (target > maxScroll + 1) {
1356
+ awaitingContent = true;
1357
+ return;
1358
+ }
1359
+ }
1360
+ awaitingContent = false;
1361
+ restoredKernels.set(kernel, key);
1362
+ restore();
1363
+ }
1241
1364
  function clear() {
1242
1365
  try {
1243
1366
  getStorage().removeItem(getStorageKey());
@@ -1270,30 +1393,41 @@ function scrollRestoration(options) {
1270
1393
  if (saveOnScroll) {
1271
1394
  debouncedSave = debounce(save, debounceMs);
1272
1395
  }
1273
- if (restoreOnMount) {
1274
- requestAnimationFrame(() => {
1275
- restore();
1396
+ if (restoreOnMount && restoredKernels.get(k) !== key) {
1397
+ restoreFrame = requestAnimationFrame(() => {
1398
+ restoreFrame = null;
1399
+ restoreOnceReachable();
1276
1400
  });
1277
1401
  }
1278
1402
  },
1279
1403
  uninstall() {
1280
- if (saveOnUnmount) {
1404
+ const restorePending = restoreFrame !== null;
1405
+ if (restoreFrame !== null) {
1406
+ cancelAnimationFrame(restoreFrame);
1407
+ restoreFrame = null;
1408
+ }
1409
+ if (saveOnUnmount && !restorePending && !awaitingContent) {
1281
1410
  save();
1282
1411
  }
1283
1412
  if (debouncedSave) {
1284
1413
  debouncedSave.cancel();
1285
1414
  debouncedSave = null;
1286
1415
  }
1416
+ awaitingContent = false;
1287
1417
  kernel = null;
1288
1418
  },
1289
1419
  hooks: {
1290
- onScroll: handleScroll
1420
+ onScroll: handleScroll,
1421
+ onItemsChange: () => {
1422
+ if (awaitingContent) restoreOnceReachable();
1423
+ }
1291
1424
  },
1292
1425
  api
1293
1426
  };
1294
1427
  }
1295
1428
 
1296
1429
  // src/plugins/optional/bidirectional.ts
1430
+ var positionedKernels = /* @__PURE__ */ new WeakSet();
1297
1431
  function bidirectional(options = {}) {
1298
1432
  const {
1299
1433
  initialPosition = "bottom",
@@ -1308,18 +1442,25 @@ function bidirectional(options = {}) {
1308
1442
  let isSticking = initialStickToBottom;
1309
1443
  let previousTotalSize = 0;
1310
1444
  let isInitialized = false;
1445
+ let initialFrame = null;
1446
+ let backwardTriggered = false;
1447
+ let forwardTriggered = false;
1448
+ function isHorizontal() {
1449
+ return kernel?.getOptions().direction === "horizontal";
1450
+ }
1451
+ function getOffset(position) {
1452
+ return isHorizontal() ? position.scrollLeft : position.scrollTop;
1453
+ }
1311
1454
  function checkIsAtBottom() {
1312
1455
  if (!kernel) return false;
1313
1456
  const viewport = kernel.getViewport();
1314
- const scrollPosition = kernel.getScrollPosition();
1315
1457
  const totalSize = kernel.getTotalSize();
1316
- const maxScroll = totalSize - viewport.height;
1317
- return scrollPosition.scrollTop >= maxScroll - stickThreshold;
1458
+ const maxScroll = totalSize - (isHorizontal() ? viewport.width : viewport.height);
1459
+ return getOffset(kernel.getScrollPosition()) >= maxScroll - stickThreshold;
1318
1460
  }
1319
1461
  function checkIsAtTop() {
1320
1462
  if (!kernel) return false;
1321
- const scrollPosition = kernel.getScrollPosition();
1322
- return scrollPosition.scrollTop <= stickThreshold;
1463
+ return getOffset(kernel.getScrollPosition()) <= stickThreshold;
1323
1464
  }
1324
1465
  function handleScroll(event) {
1325
1466
  if (!kernel) return;
@@ -1329,16 +1470,30 @@ function bidirectional(options = {}) {
1329
1470
  if (onLoadMore) {
1330
1471
  const viewport = kernel.getViewport();
1331
1472
  const totalSize = kernel.getTotalSize();
1332
- if (event.scrollTop < loadMoreThreshold) {
1333
- onLoadMore("backward");
1473
+ const offset = getOffset(event);
1474
+ const viewportSize = isHorizontal() ? viewport.width : viewport.height;
1475
+ if (offset < loadMoreThreshold) {
1476
+ if (!backwardTriggered) {
1477
+ backwardTriggered = true;
1478
+ onLoadMore("backward");
1479
+ }
1480
+ } else {
1481
+ backwardTriggered = false;
1334
1482
  }
1335
- const distanceFromBottom = totalSize - event.scrollTop - viewport.height;
1483
+ const distanceFromBottom = totalSize - offset - viewportSize;
1336
1484
  if (distanceFromBottom < loadMoreThreshold) {
1337
- onLoadMore("forward");
1485
+ if (!forwardTriggered) {
1486
+ forwardTriggered = true;
1487
+ onLoadMore("forward");
1488
+ }
1489
+ } else {
1490
+ forwardTriggered = false;
1338
1491
  }
1339
1492
  }
1340
1493
  }
1341
1494
  function handleItemsChange(count, previousCount) {
1495
+ backwardTriggered = false;
1496
+ forwardTriggered = false;
1342
1497
  if (!kernel || !isInitialized) return;
1343
1498
  const newTotalSize = kernel.getTotalSize();
1344
1499
  const sizeDelta = newTotalSize - previousTotalSize;
@@ -1381,9 +1536,10 @@ function bidirectional(options = {}) {
1381
1536
  adjustForPrepend(prependedHeight) {
1382
1537
  if (!kernel || prependedHeight <= 0) return;
1383
1538
  const scrollPosition = kernel.getScrollPosition();
1539
+ const horizontal = isHorizontal();
1384
1540
  kernel.setScrollPosition({
1385
- scrollTop: scrollPosition.scrollTop + prependedHeight,
1386
- scrollLeft: scrollPosition.scrollLeft
1541
+ scrollTop: scrollPosition.scrollTop + (horizontal ? 0 : prependedHeight),
1542
+ scrollLeft: scrollPosition.scrollLeft + (horizontal ? prependedHeight : 0)
1387
1543
  });
1388
1544
  }
1389
1545
  };
@@ -1395,10 +1551,15 @@ function bidirectional(options = {}) {
1395
1551
  kernel = k;
1396
1552
  k.getItemCount();
1397
1553
  previousTotalSize = k.getTotalSize();
1398
- if (initialPosition === "bottom") {
1399
- requestAnimationFrame(() => {
1554
+ isSticking = stickToBottom && (initialPosition === "bottom" && !positionedKernels.has(k) || checkIsAtBottom());
1555
+ if (initialPosition === "bottom" && !positionedKernels.has(k)) {
1556
+ initialFrame = requestAnimationFrame(() => {
1557
+ initialFrame = null;
1400
1558
  if (kernel) {
1401
- kernel.scrollTo(kernel.getTotalSize());
1559
+ if (!positionedKernels.has(kernel)) {
1560
+ positionedKernels.add(kernel);
1561
+ kernel.scrollTo(kernel.getTotalSize());
1562
+ }
1402
1563
  isInitialized = true;
1403
1564
  }
1404
1565
  });
@@ -1407,8 +1568,14 @@ function bidirectional(options = {}) {
1407
1568
  }
1408
1569
  },
1409
1570
  uninstall() {
1571
+ if (initialFrame !== null) {
1572
+ cancelAnimationFrame(initialFrame);
1573
+ initialFrame = null;
1574
+ }
1410
1575
  kernel = null;
1411
1576
  isInitialized = false;
1577
+ backwardTriggered = false;
1578
+ forwardTriggered = false;
1412
1579
  },
1413
1580
  hooks: {
1414
1581
  onScroll: handleScroll,
@@ -1419,6 +1586,7 @@ function bidirectional(options = {}) {
1419
1586
  }
1420
1587
 
1421
1588
  // src/plugins/optional/drag-to-reorder.ts
1589
+ var dragByKernel = /* @__PURE__ */ new WeakMap();
1422
1590
  function dragToReorder(options) {
1423
1591
  const {
1424
1592
  enabled: initialEnabled = true,
@@ -1438,6 +1606,9 @@ function dragToReorder(options) {
1438
1606
  let draggedIndex = null;
1439
1607
  let dropTargetIndex = null;
1440
1608
  let autoScrollTimer = null;
1609
+ function rememberDrag() {
1610
+ if (kernel) dragByKernel.set(kernel, { dragged: draggedIndex, target: dropTargetIndex });
1611
+ }
1441
1612
  function handleDragStart(event, index) {
1442
1613
  if (!enabled || !canDrag(index)) {
1443
1614
  event.preventDefault();
@@ -1445,6 +1616,7 @@ function dragToReorder(options) {
1445
1616
  }
1446
1617
  draggedIndex = index;
1447
1618
  dropTargetIndex = index;
1619
+ rememberDrag();
1448
1620
  event.dataTransfer?.setData("text/plain", String(index));
1449
1621
  if (event.dataTransfer) {
1450
1622
  event.dataTransfer.effectAllowed = "move";
@@ -1454,27 +1626,22 @@ function dragToReorder(options) {
1454
1626
  startAutoScroll();
1455
1627
  }
1456
1628
  }
1457
- function handleDragEnd(event) {
1629
+ function finishDrag() {
1458
1630
  const currentDraggedIndex = draggedIndex;
1459
- const currentDropTargetIndex = dropTargetIndex;
1460
1631
  stopAutoScroll();
1461
- if (currentDraggedIndex !== null && currentDropTargetIndex !== null && currentDraggedIndex !== currentDropTargetIndex) {
1462
- if (canDrop(currentDraggedIndex, currentDropTargetIndex)) {
1463
- onReorder(currentDraggedIndex, currentDropTargetIndex);
1464
- }
1465
- }
1466
1632
  if (currentDraggedIndex !== null) {
1467
1633
  onDragEnd?.(currentDraggedIndex);
1468
1634
  }
1469
1635
  draggedIndex = null;
1470
1636
  dropTargetIndex = null;
1637
+ rememberDrag();
1638
+ }
1639
+ function handleDragEnd(_event) {
1640
+ finishDrag();
1471
1641
  }
1472
1642
  function handleDragOver(event, index) {
1473
1643
  if (draggedIndex === null) return;
1474
1644
  event.preventDefault();
1475
- if (event.dataTransfer) {
1476
- event.dataTransfer.dropEffect = canDrop(draggedIndex, index) ? "move" : "none";
1477
- }
1478
1645
  const target = event.currentTarget;
1479
1646
  const rect = target.getBoundingClientRect();
1480
1647
  let newDropTarget;
@@ -1489,6 +1656,10 @@ function dragToReorder(options) {
1489
1656
  newDropTarget--;
1490
1657
  }
1491
1658
  dropTargetIndex = Math.max(0, Math.min(newDropTarget, (kernel?.getItemCount() ?? 1) - 1));
1659
+ rememberDrag();
1660
+ if (event.dataTransfer) {
1661
+ event.dataTransfer.dropEffect = canDrop(draggedIndex, dropTargetIndex) ? "move" : "none";
1662
+ }
1492
1663
  }
1493
1664
  function handleDragEnter(event, _index) {
1494
1665
  event.preventDefault();
@@ -1497,6 +1668,14 @@ function dragToReorder(options) {
1497
1668
  }
1498
1669
  function handleDrop(event, _index) {
1499
1670
  event.preventDefault();
1671
+ const currentDraggedIndex = draggedIndex;
1672
+ const currentDropTargetIndex = dropTargetIndex;
1673
+ if (currentDraggedIndex !== null && currentDropTargetIndex !== null && currentDraggedIndex !== currentDropTargetIndex) {
1674
+ if (canDrop(currentDraggedIndex, currentDropTargetIndex)) {
1675
+ onReorder(currentDraggedIndex, currentDropTargetIndex);
1676
+ }
1677
+ }
1678
+ finishDrag();
1500
1679
  }
1501
1680
  function startAutoScroll() {
1502
1681
  if (autoScrollTimer) return;
@@ -1540,6 +1719,7 @@ function dragToReorder(options) {
1540
1719
  stopAutoScroll();
1541
1720
  draggedIndex = null;
1542
1721
  dropTargetIndex = null;
1722
+ rememberDrag();
1543
1723
  },
1544
1724
  enable() {
1545
1725
  enabled = true;
@@ -1559,6 +1739,14 @@ function dragToReorder(options) {
1559
1739
  type: "optional",
1560
1740
  install(k) {
1561
1741
  kernel = k;
1742
+ const previous = dragByKernel.get(k);
1743
+ if (previous && previous.dragged !== null && enabled) {
1744
+ draggedIndex = previous.dragged;
1745
+ dropTargetIndex = previous.target;
1746
+ if (autoScroll) startAutoScroll();
1747
+ } else if (previous) {
1748
+ rememberDrag();
1749
+ }
1562
1750
  },
1563
1751
  uninstall() {
1564
1752
  stopAutoScroll();
@@ -1592,6 +1780,7 @@ function debugPanel(options = {}) {
1592
1780
  let lastFpsUpdate = performance.now();
1593
1781
  let currentFps = 60;
1594
1782
  let rafId = null;
1783
+ let eventUnsubscribers = [];
1595
1784
  const emptyRange = {
1596
1785
  startIndex: 0,
1597
1786
  endIndex: 0,
@@ -1662,8 +1851,13 @@ function debugPanel(options = {}) {
1662
1851
  memoryUsage = Math.round(memory.usedJSHeapSize / 1024 / 1024 * 100) / 100;
1663
1852
  }
1664
1853
  }
1665
- const visibleItems = (visibleRange.end ?? visibleRange.endIndex) - (visibleRange.start ?? visibleRange.startIndex);
1666
- const renderedItems = (renderRange.end ?? renderRange.endIndex) - (renderRange.start ?? renderRange.startIndex);
1854
+ const countOf = (range) => itemCount === 0 ? 0 : (range.end ?? range.endIndex) - (range.start ?? range.startIndex) + 1;
1855
+ const visibleItems = countOf(visibleRange);
1856
+ const renderedItems = countOf(renderRange);
1857
+ const horizontal = kernel.getOptions().direction === "horizontal";
1858
+ const viewport = kernel.getViewport();
1859
+ const scrollOffset = horizontal ? scrollPos.scrollLeft : scrollPos.scrollTop;
1860
+ const maxScroll = kernel.getTotalSize() - (horizontal ? viewport.width : viewport.height);
1667
1861
  state.stats = {
1668
1862
  ...state.stats,
1669
1863
  memoryUsage,
@@ -1674,8 +1868,8 @@ function debugPanel(options = {}) {
1674
1868
  avgItemHeight: itemCount > 0 ? kernel.getTotalSize() / itemCount : 0,
1675
1869
  scrollPosition: {
1676
1870
  ...scrollPos,
1677
- offset: scrollPos.scrollTop,
1678
- percentage: kernel.getTotalSize() > 0 ? scrollPos.scrollTop / kernel.getTotalSize() : 0
1871
+ offset: scrollOffset,
1872
+ percentage: maxScroll > 0 ? Math.min(1, Math.max(0, scrollOffset / maxScroll)) : 0
1679
1873
  },
1680
1874
  visibleRange: {
1681
1875
  ...visibleRange,
@@ -1711,6 +1905,10 @@ function debugPanel(options = {}) {
1711
1905
  }
1712
1906
  function startMonitoring() {
1713
1907
  if (rafId !== null) return;
1908
+ const now = performance.now();
1909
+ frameCount = 0;
1910
+ lastFpsUpdate = now;
1911
+ lastFrameTime = now;
1714
1912
  updateFps();
1715
1913
  statsUpdateTimer = setInterval(updateStats, resolvedOptions.statsUpdateInterval);
1716
1914
  }
@@ -1808,23 +2006,24 @@ function debugPanel(options = {}) {
1808
2006
  kernel = k;
1809
2007
  const eventTypes = [
1810
2008
  "scroll",
1811
- "scrollStart",
1812
- "scrollEnd",
1813
- "visibleRangeChange",
1814
- "itemMeasured",
2009
+ "scroll-start",
2010
+ "scroll-end",
2011
+ "visible-range-change",
2012
+ "item-measured",
1815
2013
  "resize",
1816
- "loadMore",
1817
- "itemsChange"
2014
+ "load-more",
2015
+ "items-change"
1818
2016
  ];
1819
- eventTypes.forEach((type) => {
1820
- kernel?.on(type, logEvent);
1821
- });
2017
+ eventUnsubscribers.forEach((unsubscribe) => unsubscribe());
2018
+ eventUnsubscribers = eventTypes.map((type) => k.on(type, logEvent));
1822
2019
  if (state.visible) {
1823
2020
  startMonitoring();
1824
2021
  }
1825
2022
  },
1826
2023
  uninstall() {
1827
2024
  stopMonitoring();
2025
+ eventUnsubscribers.forEach((unsubscribe) => unsubscribe());
2026
+ eventUnsubscribers = [];
1828
2027
  kernel = null;
1829
2028
  },
1830
2029
  api: extendedApi
@@ -1834,6 +2033,7 @@ function useDebugPanelState(plugin) {
1834
2033
  const api = plugin.api;
1835
2034
  const [state, setState] = react.useState(api.getState());
1836
2035
  react.useEffect(() => {
2036
+ setState({ ...api.getState() });
1837
2037
  return api.subscribe(() => {
1838
2038
  setState({ ...api.getState() });
1839
2039
  });
@@ -1868,7 +2068,8 @@ function DebugPanelOverlay({
1868
2068
  }
1869
2069
  }, [options.position]);
1870
2070
  const themeStyles = react.useMemo(() => {
1871
- const isDark = options.theme === "dark" || options.theme === "auto" && window.matchMedia("(prefers-color-scheme: dark)").matches;
2071
+ const prefersDark = typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-color-scheme: dark)").matches;
2072
+ const isDark = options.theme === "dark" || options.theme === "auto" && prefersDark;
1872
2073
  return isDark ? {
1873
2074
  backgroundColor: "rgba(30, 30, 30, 0.95)",
1874
2075
  color: "#e0e0e0",
@@ -2161,13 +2362,13 @@ function EventsPanel({ eventLog, onClear }) {
2161
2362
  };
2162
2363
  const typeColors = {
2163
2364
  scroll: "#6bcb77",
2164
- scrollStart: "#4d96ff",
2165
- scrollEnd: "#4d96ff",
2166
- visibleRangeChange: "#ffd93d",
2167
- itemMeasured: "#9b59b6",
2365
+ "scroll-start": "#4d96ff",
2366
+ "scroll-end": "#4d96ff",
2367
+ "visible-range-change": "#ffd93d",
2368
+ "item-measured": "#9b59b6",
2168
2369
  resize: "#ff6b6b",
2169
- loadMore: "#1abc9c",
2170
- itemsChange: "#e74c3c"
2370
+ "load-more": "#1abc9c",
2371
+ "items-change": "#e74c3c"
2171
2372
  };
2172
2373
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2173
2374
  /* @__PURE__ */ jsxRuntime.jsx("button", { style: buttonStyles, onClick: onClear, children: "Clear Log" }),