@oxog/scrollex 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,682 +1,8 @@
1
+ import { normalizeColumnCount, debounce, autoColumnCount } from '../chunk-CIB3EBBJ.js';
2
+ export { autoMeasurerPlugin, gridRendererPlugin, infiniteLoaderPlugin, listRendererPlugin, scrollControllerPlugin } from '../chunk-CIB3EBBJ.js';
1
3
  import { useMemo, useCallback, useState, useEffect } from 'react';
2
4
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
3
5
 
4
- // src/plugins/core/list-renderer.ts
5
- var VirtualItemPool = class {
6
- constructor() {
7
- this.pool = [];
8
- }
9
- acquire() {
10
- const item = this.pool.pop();
11
- if (item) {
12
- return item;
13
- }
14
- return { index: 0, key: 0, start: 0, end: 0, size: 0, lane: 0 };
15
- }
16
- release(item) {
17
- item.index = 0;
18
- item.key = 0;
19
- item.start = 0;
20
- item.end = 0;
21
- item.size = 0;
22
- item.lane = 0;
23
- this.pool.push(item);
24
- }
25
- releaseAll(items) {
26
- for (const item of items) {
27
- this.release(item);
28
- }
29
- }
30
- };
31
- function listRendererPlugin(options = {}) {
32
- const { getItemKey = (index) => index } = options;
33
- let kernel = null;
34
- let virtualItems = [];
35
- let currentRange = {
36
- startIndex: 0,
37
- endIndex: 0,
38
- overscanStartIndex: 0,
39
- overscanEndIndex: 0
40
- };
41
- const itemPool = new VirtualItemPool();
42
- function buildVirtualItems(range) {
43
- if (!kernel) return [];
44
- itemPool.releaseAll(virtualItems);
45
- const items = [];
46
- range.startIndex;
47
- range.endIndex;
48
- for (let i = range.overscanStartIndex; i <= range.overscanEndIndex; i++) {
49
- const item = itemPool.acquire();
50
- const offset = kernel.getItemOffset(i);
51
- const size = kernel.getCachedHeight(i) ?? kernel.getEstimatedHeight();
52
- item.index = i;
53
- item.key = getItemKey(i);
54
- item.start = offset;
55
- item.end = offset + size;
56
- item.size = size;
57
- item.lane = 0;
58
- items.push(item);
59
- }
60
- return items;
61
- }
62
- function recalculate() {
63
- if (!kernel) return;
64
- currentRange = kernel.getVisibleRange();
65
- virtualItems = buildVirtualItems(currentRange);
66
- }
67
- const api = {
68
- getVirtualItems() {
69
- return virtualItems;
70
- },
71
- getTotalHeight() {
72
- return kernel?.getTotalSize() ?? 0;
73
- },
74
- getStartOffset() {
75
- if (virtualItems.length === 0) return 0;
76
- return virtualItems[0]?.start ?? 0;
77
- },
78
- getEndOffset() {
79
- if (virtualItems.length === 0) return 0;
80
- const lastItem = virtualItems[virtualItems.length - 1];
81
- return lastItem?.end ?? 0;
82
- },
83
- isItemVisible(index) {
84
- return index >= currentRange.startIndex && index <= currentRange.endIndex;
85
- },
86
- recalculate
87
- };
88
- return {
89
- name: "list-renderer",
90
- version: "1.0.0",
91
- type: "core",
92
- install(k) {
93
- kernel = k;
94
- recalculate();
95
- },
96
- uninstall() {
97
- itemPool.releaseAll(virtualItems);
98
- virtualItems = [];
99
- kernel = null;
100
- },
101
- hooks: {
102
- onScroll: () => recalculate(),
103
- onResize: () => recalculate(),
104
- onItemMeasured: () => recalculate(),
105
- onVisibleRangeChange: (range) => {
106
- currentRange = range;
107
- virtualItems = buildVirtualItems(range);
108
- },
109
- onItemsChange: () => recalculate()
110
- },
111
- api
112
- };
113
- }
114
-
115
- // src/plugins/core/grid-renderer.ts
116
- function gridRendererPlugin(options) {
117
- const {
118
- columns,
119
- minColumnWidth = 100,
120
- rowHeight,
121
- gap = 0,
122
- getItemKey = (index) => index
123
- } = options;
124
- let kernel = null;
125
- let virtualItems = [];
126
- let columnCount = typeof columns === "number" ? columns : 1;
127
- let columnWidth = 0;
128
- let gapX = typeof gap === "number" ? gap : gap.x;
129
- let gapY = typeof gap === "number" ? gap : gap.y;
130
- function calculateColumns(containerWidth) {
131
- if (typeof columns === "number") {
132
- columnCount = columns;
133
- } else {
134
- columnCount = Math.max(1, Math.floor((containerWidth + gapX) / (minColumnWidth + gapX)));
135
- }
136
- columnWidth = (containerWidth - (columnCount - 1) * gapX) / columnCount;
137
- }
138
- function getRowCount() {
139
- if (!kernel) return 0;
140
- return Math.ceil(kernel.getItemCount() / columnCount);
141
- }
142
- function buildVirtualItems() {
143
- if (!kernel) return [];
144
- const viewport = kernel.getViewport();
145
- const scrollPosition = kernel.getScrollPosition();
146
- const scrollTop = scrollPosition.scrollTop;
147
- const effectiveRowHeight = rowHeight + gapY;
148
- const startRow = Math.max(0, Math.floor(scrollTop / effectiveRowHeight));
149
- const visibleRows = Math.ceil(viewport.height / effectiveRowHeight);
150
- const overscan = kernel.getOptions().overscan;
151
- const endRow = Math.min(getRowCount() - 1, startRow + visibleRows + overscan);
152
- const overscanStartRow = Math.max(0, startRow - overscan);
153
- const items = [];
154
- const itemCount = kernel.getItemCount();
155
- for (let row = overscanStartRow; row <= endRow; row++) {
156
- for (let col = 0; col < columnCount; col++) {
157
- const index = row * columnCount + col;
158
- if (index >= itemCount) break;
159
- const top = row * effectiveRowHeight;
160
- items.push({
161
- index,
162
- key: getItemKey(index),
163
- start: top,
164
- end: top + rowHeight,
165
- size: rowHeight,
166
- lane: col
167
- });
168
- }
169
- }
170
- return items;
171
- }
172
- function recalculate() {
173
- if (!kernel) return;
174
- const viewport = kernel.getViewport();
175
- calculateColumns(viewport.width);
176
- virtualItems = buildVirtualItems();
177
- }
178
- const api = {
179
- getVirtualItems() {
180
- return virtualItems;
181
- },
182
- getTotalHeight() {
183
- return getRowCount() * (rowHeight + gapY) - gapY;
184
- },
185
- getColumnCount() {
186
- return columnCount;
187
- },
188
- getColumnWidth() {
189
- return columnWidth;
190
- },
191
- getItemsPerRow() {
192
- return columnCount;
193
- },
194
- getRowCount,
195
- recalculate
196
- };
197
- return {
198
- name: "grid-renderer",
199
- version: "1.0.0",
200
- type: "core",
201
- install(k) {
202
- kernel = k;
203
- recalculate();
204
- },
205
- uninstall() {
206
- virtualItems = [];
207
- kernel = null;
208
- },
209
- hooks: {
210
- onScroll: () => {
211
- virtualItems = buildVirtualItems();
212
- },
213
- onResize: () => recalculate(),
214
- onItemsChange: () => recalculate()
215
- },
216
- api
217
- };
218
- }
219
-
220
- // src/utils/debounce.ts
221
- function debounce(fn, wait) {
222
- let timeoutId = null;
223
- let lastArgs = null;
224
- let lastThis = null;
225
- const debounced = function(...args) {
226
- lastArgs = args;
227
- lastThis = this;
228
- if (timeoutId) {
229
- clearTimeout(timeoutId);
230
- }
231
- timeoutId = setTimeout(() => {
232
- timeoutId = null;
233
- if (lastArgs) {
234
- fn.apply(lastThis, lastArgs);
235
- lastArgs = null;
236
- lastThis = null;
237
- }
238
- }, wait);
239
- };
240
- debounced.cancel = () => {
241
- if (timeoutId) {
242
- clearTimeout(timeoutId);
243
- timeoutId = null;
244
- }
245
- lastArgs = null;
246
- lastThis = null;
247
- };
248
- debounced.flush = () => {
249
- if (timeoutId) {
250
- clearTimeout(timeoutId);
251
- timeoutId = null;
252
- if (lastArgs) {
253
- fn.apply(lastThis, lastArgs);
254
- lastArgs = null;
255
- lastThis = null;
256
- }
257
- }
258
- };
259
- return debounced;
260
- }
261
-
262
- // src/plugins/core/auto-measurer.ts
263
- function autoMeasurerPlugin(options = {}) {
264
- const {
265
- estimatedItemHeight = 50,
266
- measureOnResize = true,
267
- debounceMs = 100
268
- } = options;
269
- let kernel = null;
270
- let resizeObserver = null;
271
- const observedElements = /* @__PURE__ */ new WeakMap();
272
- const elementsByIndex = /* @__PURE__ */ new Map();
273
- let measureQueue = /* @__PURE__ */ new Set();
274
- let flushScheduled = false;
275
- const debouncedFlush = debounce(() => {
276
- flush();
277
- }, debounceMs);
278
- function flush() {
279
- if (!kernel || measureQueue.size === 0) {
280
- flushScheduled = false;
281
- return;
282
- }
283
- const indicesToMeasure = Array.from(measureQueue);
284
- measureQueue = /* @__PURE__ */ new Set();
285
- flushScheduled = false;
286
- const measurements = [];
287
- for (const index of indicesToMeasure) {
288
- const ref = elementsByIndex.get(index);
289
- const element = ref?.deref();
290
- if (element) {
291
- const rect = element.getBoundingClientRect();
292
- measurements.push({ index, height: rect.height });
293
- }
294
- }
295
- for (const { index, height } of measurements) {
296
- if (height > 0) {
297
- kernel.measureItem(index, height);
298
- }
299
- }
300
- }
301
- function scheduleFlush() {
302
- if (!flushScheduled) {
303
- flushScheduled = true;
304
- requestAnimationFrame(() => {
305
- flush();
306
- });
307
- }
308
- }
309
- function handleResize(entries) {
310
- for (const entry of entries) {
311
- const index = observedElements.get(entry.target);
312
- if (index !== void 0) {
313
- measureQueue.add(index);
314
- }
315
- }
316
- if (measureOnResize && measureQueue.size > 0) {
317
- debouncedFlush();
318
- }
319
- }
320
- const api = {
321
- measureElement(index, element) {
322
- const rect = element.getBoundingClientRect();
323
- const height = rect.height;
324
- if (height > 0 && kernel) {
325
- kernel.measureItem(index, height);
326
- }
327
- return height;
328
- },
329
- getCachedSize(index) {
330
- return kernel?.getCachedHeight(index);
331
- },
332
- invalidate(index) {
333
- kernel?.invalidateMeasurement(index);
334
- },
335
- invalidateAll() {
336
- kernel?.invalidateAllMeasurements();
337
- },
338
- getMeasurementCache() {
339
- const cache = /* @__PURE__ */ new Map();
340
- if (!kernel) return cache;
341
- const itemCount = kernel.getItemCount();
342
- for (let i = 0; i < itemCount; i++) {
343
- const height = kernel.getCachedHeight(i);
344
- if (height !== void 0) {
345
- cache.set(i, height);
346
- }
347
- }
348
- return cache;
349
- },
350
- observe(index, element) {
351
- if (!resizeObserver) return;
352
- const existingRef = elementsByIndex.get(index);
353
- const existingElement = existingRef?.deref();
354
- if (existingElement && existingElement !== element) {
355
- resizeObserver.unobserve(existingElement);
356
- observedElements.delete(existingElement);
357
- }
358
- observedElements.set(element, index);
359
- elementsByIndex.set(index, new WeakRef(element));
360
- resizeObserver.observe(element);
361
- measureQueue.add(index);
362
- scheduleFlush();
363
- },
364
- unobserve(element) {
365
- if (!resizeObserver) return;
366
- const index = observedElements.get(element);
367
- if (index !== void 0) {
368
- resizeObserver.unobserve(element);
369
- observedElements.delete(element);
370
- elementsByIndex.delete(index);
371
- measureQueue.delete(index);
372
- }
373
- }
374
- };
375
- return {
376
- name: "auto-measurer",
377
- version: "1.0.0",
378
- type: "core",
379
- install(k) {
380
- kernel = k;
381
- kernel.configure({ estimatedItemHeight });
382
- if (measureOnResize && typeof ResizeObserver !== "undefined") {
383
- resizeObserver = new ResizeObserver(handleResize);
384
- }
385
- },
386
- uninstall() {
387
- if (resizeObserver) {
388
- resizeObserver.disconnect();
389
- resizeObserver = null;
390
- }
391
- debouncedFlush.cancel();
392
- measureQueue.clear();
393
- elementsByIndex.clear();
394
- flushScheduled = false;
395
- kernel = null;
396
- },
397
- api
398
- };
399
- }
400
-
401
- // src/plugins/core/infinite-loader.ts
402
- function infiniteLoaderPlugin(options) {
403
- const {
404
- threshold = 200,
405
- thresholdItems = 5,
406
- direction = "forward",
407
- onLoadMore
408
- } = options;
409
- let kernel = null;
410
- let loading = false;
411
- let hasMoreForward = true;
412
- let hasMoreBackward = direction === "backward" || direction === "both";
413
- let lastCheckTime = 0;
414
- const checkDebounceMs = 100;
415
- function checkLoadMore(event) {
416
- if (loading || !kernel) return;
417
- const now = performance.now();
418
- if (now - lastCheckTime < checkDebounceMs) return;
419
- lastCheckTime = now;
420
- const viewport = kernel.getViewport();
421
- const totalSize = kernel.getTotalSize();
422
- const { scrollTop } = event;
423
- if ((direction === "forward" || direction === "both") && hasMoreForward) {
424
- const distanceFromBottom = totalSize - scrollTop - viewport.height;
425
- if (distanceFromBottom < threshold) {
426
- triggerLoad("forward");
427
- return;
428
- }
429
- }
430
- if ((direction === "backward" || direction === "both") && hasMoreBackward) {
431
- if (scrollTop < threshold) {
432
- triggerLoad("backward");
433
- return;
434
- }
435
- }
436
- }
437
- function checkLoadMoreByRange(range) {
438
- if (loading || !kernel) return;
439
- const itemCount = kernel.getItemCount();
440
- if ((direction === "forward" || direction === "both") && hasMoreForward) {
441
- const itemsFromEnd = itemCount - 1 - range.endIndex;
442
- if (itemsFromEnd <= thresholdItems) {
443
- triggerLoad("forward");
444
- return;
445
- }
446
- }
447
- if ((direction === "backward" || direction === "both") && hasMoreBackward) {
448
- if (range.startIndex <= thresholdItems) {
449
- triggerLoad("backward");
450
- return;
451
- }
452
- }
453
- }
454
- async function triggerLoad(loadDirection) {
455
- if (loading || !kernel) return;
456
- if (loadDirection === "forward" && !hasMoreForward) return;
457
- if (loadDirection === "backward" && !hasMoreBackward) return;
458
- loading = true;
459
- kernel.emit({
460
- type: "load-more",
461
- direction: loadDirection
462
- });
463
- try {
464
- await onLoadMore(loadDirection);
465
- } catch (error) {
466
- console.error("[Scrollex] Error in onLoadMore:", error);
467
- } finally {
468
- loading = false;
469
- }
470
- }
471
- const api = {
472
- isLoading() {
473
- return loading;
474
- },
475
- setLoading(l) {
476
- loading = l;
477
- },
478
- hasMore() {
479
- return hasMoreForward || hasMoreBackward;
480
- },
481
- setHasMore(hasMore) {
482
- hasMoreForward = hasMore;
483
- hasMoreBackward = hasMore;
484
- },
485
- hasMoreForward() {
486
- return hasMoreForward;
487
- },
488
- setHasMoreForward(hasMore) {
489
- hasMoreForward = hasMore;
490
- },
491
- hasMoreBackward() {
492
- return hasMoreBackward;
493
- },
494
- setHasMoreBackward(hasMore) {
495
- hasMoreBackward = hasMore;
496
- },
497
- reset() {
498
- loading = false;
499
- hasMoreForward = true;
500
- hasMoreBackward = direction === "backward" || direction === "both";
501
- },
502
- triggerLoad(loadDirection) {
503
- triggerLoad(loadDirection);
504
- }
505
- };
506
- return {
507
- name: "infinite-loader",
508
- version: "1.0.0",
509
- type: "core",
510
- install(k) {
511
- kernel = k;
512
- },
513
- uninstall() {
514
- kernel = null;
515
- loading = false;
516
- },
517
- hooks: {
518
- onScroll: checkLoadMore,
519
- onVisibleRangeChange: (range) => checkLoadMoreByRange(range)
520
- },
521
- api
522
- };
523
- }
524
-
525
- // src/utils/raf.ts
526
- function raf(callback) {
527
- if (typeof requestAnimationFrame !== "undefined") {
528
- return requestAnimationFrame(callback);
529
- }
530
- return setTimeout(() => callback(Date.now()), 16);
531
- }
532
- function cancelRaf(id) {
533
- if (typeof cancelAnimationFrame !== "undefined") {
534
- cancelAnimationFrame(id);
535
- } else {
536
- clearTimeout(id);
537
- }
538
- }
539
-
540
- // src/plugins/core/scroll-controller.ts
541
- var easings = {
542
- easeInOut: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t};
543
- function scrollControllerPlugin(options = {}) {
544
- const {
545
- defaultDuration = 300,
546
- defaultEasing = easings.easeInOut
547
- } = options;
548
- let kernel = null;
549
- let animationId = null;
550
- let animating = false;
551
- function animateScroll(targetOffset, duration, easing) {
552
- if (!kernel) return;
553
- stopAnimation();
554
- const startTime = performance.now();
555
- const startOffset = kernel.getScrollPosition().scrollTop;
556
- const distance = targetOffset - startOffset;
557
- if (distance === 0 || duration === 0) {
558
- kernel.setScrollPosition({ scrollTop: targetOffset, scrollLeft: 0 });
559
- return;
560
- }
561
- animating = true;
562
- function animate(currentTime) {
563
- if (!kernel) {
564
- animating = false;
565
- return;
566
- }
567
- const elapsed = currentTime - startTime;
568
- const progress = Math.min(elapsed / duration, 1);
569
- const easedProgress = easing(progress);
570
- const currentOffset = startOffset + distance * easedProgress;
571
- kernel.setScrollPosition({ scrollTop: currentOffset, scrollLeft: 0 });
572
- if (progress < 1) {
573
- animationId = raf(animate);
574
- } else {
575
- animationId = null;
576
- animating = false;
577
- }
578
- }
579
- animationId = raf(animate);
580
- }
581
- function stopAnimation() {
582
- if (animationId !== null) {
583
- cancelRaf(animationId);
584
- animationId = null;
585
- }
586
- animating = false;
587
- }
588
- const api = {
589
- scrollTo(offset, options2 = {}) {
590
- if (!kernel) return;
591
- const {
592
- behavior = "auto",
593
- duration = defaultDuration,
594
- easing = defaultEasing
595
- } = options2;
596
- if (behavior === "auto") {
597
- stopAnimation();
598
- kernel.setScrollPosition({ scrollTop: offset, scrollLeft: 0 });
599
- } else {
600
- animateScroll(offset, duration, easing);
601
- }
602
- },
603
- scrollToIndex(index, options2 = {}) {
604
- if (!kernel) return;
605
- const {
606
- align = "auto",
607
- offset: additionalOffset = 0,
608
- ...scrollOptions
609
- } = options2;
610
- const itemOffset = kernel.getItemOffset(index);
611
- const itemSize = kernel.getCachedHeight(index) ?? kernel.getEstimatedHeight();
612
- const viewport = kernel.getViewport();
613
- let targetOffset;
614
- switch (align) {
615
- case "start":
616
- targetOffset = itemOffset;
617
- break;
618
- case "center":
619
- targetOffset = itemOffset - viewport.height / 2 + itemSize / 2;
620
- break;
621
- case "end":
622
- targetOffset = itemOffset - viewport.height + itemSize;
623
- break;
624
- case "auto":
625
- default: {
626
- const scrollPosition = kernel.getScrollPosition();
627
- const visibleStart = scrollPosition.scrollTop;
628
- const visibleEnd = visibleStart + viewport.height;
629
- const itemEnd = itemOffset + itemSize;
630
- if (itemOffset < visibleStart) {
631
- targetOffset = itemOffset;
632
- } else if (itemEnd > visibleEnd) {
633
- targetOffset = itemEnd - viewport.height;
634
- } else {
635
- return;
636
- }
637
- break;
638
- }
639
- }
640
- const maxScroll = Math.max(0, kernel.getTotalSize() - viewport.height);
641
- targetOffset = Math.max(0, Math.min(targetOffset + additionalOffset, maxScroll));
642
- api.scrollTo(targetOffset, scrollOptions);
643
- },
644
- scrollToTop(options2 = {}) {
645
- api.scrollTo(0, options2);
646
- },
647
- scrollToBottom(options2 = {}) {
648
- if (!kernel) return;
649
- const viewport = kernel.getViewport();
650
- const totalSize = kernel.getTotalSize();
651
- const maxScroll = Math.max(0, totalSize - viewport.height);
652
- api.scrollTo(maxScroll, options2);
653
- },
654
- getScrollPosition() {
655
- return kernel?.getScrollPosition() ?? { scrollTop: 0, scrollLeft: 0 };
656
- },
657
- isScrolling() {
658
- return kernel?.isScrolling() ?? false;
659
- },
660
- isAnimating() {
661
- return animating;
662
- },
663
- stopAnimation
664
- };
665
- return {
666
- name: "scroll-controller",
667
- version: "1.0.0",
668
- type: "core",
669
- install(k) {
670
- kernel = k;
671
- },
672
- uninstall() {
673
- stopAnimation();
674
- kernel = null;
675
- },
676
- api
677
- };
678
- }
679
-
680
6
  // src/plugins/optional/masonry-renderer.ts
681
7
  function masonryRenderer(options) {
682
8
  const {
@@ -688,16 +14,16 @@ function masonryRenderer(options) {
688
14
  } = options;
689
15
  let kernel = null;
690
16
  let virtualItems = [];
691
- let columnCount = typeof columns === "number" ? columns : 1;
17
+ let columnCount = typeof columns === "number" ? normalizeColumnCount(columns) : 1;
692
18
  let columnWidth = 0;
693
19
  let columnHeights = [];
694
20
  let totalHeight = 0;
695
21
  const layoutCache = /* @__PURE__ */ new Map();
696
22
  function calculateColumns(containerWidth) {
697
23
  if (typeof columns === "number") {
698
- columnCount = columns;
24
+ columnCount = normalizeColumnCount(columns);
699
25
  } else {
700
- columnCount = Math.max(1, Math.floor((containerWidth + gap) / (minColumnWidth + gap)));
26
+ columnCount = autoColumnCount(containerWidth, minColumnWidth, gap);
701
27
  }
702
28
  columnWidth = (containerWidth - (columnCount - 1) * gap) / columnCount;
703
29
  }
@@ -705,6 +31,7 @@ function masonryRenderer(options) {
705
31
  if (!kernel) return;
706
32
  const itemCount = kernel.getItemCount();
707
33
  columnHeights = new Array(columnCount).fill(0);
34
+ const itemsInColumn = new Array(columnCount).fill(0);
708
35
  layoutCache.clear();
709
36
  for (let i = 0; i < itemCount; i++) {
710
37
  let shortestCol = 0;
@@ -713,15 +40,15 @@ function masonryRenderer(options) {
713
40
  shortestCol = j;
714
41
  }
715
42
  }
716
- const itemHeight = getItemHeight(i, columnWidth);
43
+ const measured = getItemHeight(i, columnWidth);
44
+ const itemHeight = Number.isFinite(measured) && measured > 0 ? measured : 0;
717
45
  const top = columnHeights[shortestCol] ?? 0;
718
46
  layoutCache.set(i, { top, lane: shortestCol, height: itemHeight });
719
47
  columnHeights[shortestCol] = top + itemHeight + gap;
48
+ itemsInColumn[shortestCol] = (itemsInColumn[shortestCol] ?? 0) + 1;
720
49
  }
50
+ columnHeights = columnHeights.map((height, column) => (itemsInColumn[column] ?? 0) > 0 ? height - gap : 0);
721
51
  totalHeight = Math.max(...columnHeights, 0);
722
- if (totalHeight > 0) {
723
- totalHeight -= gap;
724
- }
725
52
  }
726
53
  function buildVirtualItems() {
727
54
  if (!kernel) return [];
@@ -808,6 +135,8 @@ function masonryRenderer(options) {
808
135
  uninstall() {
809
136
  virtualItems = [];
810
137
  layoutCache.clear();
138
+ columnHeights = [];
139
+ totalHeight = 0;
811
140
  kernel = null;
812
141
  },
813
142
  hooks: {
@@ -824,10 +153,8 @@ function masonryRenderer(options) {
824
153
  // src/plugins/optional/sticky-headers.ts
825
154
  function stickyHeaders(options) {
826
155
  const {
827
- headerHeight,
828
156
  isHeader,
829
157
  getGroupId,
830
- zIndex = 10,
831
158
  stickyOffset = 0
832
159
  } = options;
833
160
  let kernel = null;
@@ -852,12 +179,15 @@ function stickyHeaders(options) {
852
179
  }
853
180
  }
854
181
  }
855
- function updateStickyHeader(event) {
182
+ function offsetOf(position) {
183
+ return kernel?.getOptions().direction === "horizontal" ? position.scrollLeft : position.scrollTop;
184
+ }
185
+ function updateStickyHeader(scrollOffset) {
856
186
  if (!kernel || headerIndices.length === 0) {
857
187
  currentStickyHeader = null;
858
188
  return;
859
189
  }
860
- const scrollTop = event.scrollTop + stickyOffset;
190
+ const scrollTop = scrollOffset + stickyOffset;
861
191
  let newStickyHeader = null;
862
192
  for (const headerIndex of headerIndices) {
863
193
  const headerOffset = kernel.getItemOffset(headerIndex);
@@ -869,6 +199,10 @@ function stickyHeaders(options) {
869
199
  }
870
200
  currentStickyHeader = newStickyHeader;
871
201
  }
202
+ function refreshStickyHeader() {
203
+ if (!kernel) return;
204
+ updateStickyHeader(offsetOf(kernel.getScrollPosition()));
205
+ }
872
206
  function findHeaderForGroup(groupId) {
873
207
  const items = groupIdMap.get(groupId);
874
208
  if (!items || items.length === 0) return null;
@@ -909,6 +243,7 @@ function stickyHeaders(options) {
909
243
  install(k) {
910
244
  kernel = k;
911
245
  buildHeaderCache();
246
+ refreshStickyHeader();
912
247
  },
913
248
  uninstall() {
914
249
  headerIndices = [];
@@ -917,14 +252,24 @@ function stickyHeaders(options) {
917
252
  kernel = null;
918
253
  },
919
254
  hooks: {
920
- onScroll: updateStickyHeader,
921
- onItemsChange: () => buildHeaderCache()
255
+ onScroll: (event) => updateStickyHeader(offsetOf(event)),
256
+ onItemsChange: () => {
257
+ buildHeaderCache();
258
+ refreshStickyHeader();
259
+ }
922
260
  },
923
261
  api
924
262
  };
925
263
  }
926
264
 
927
265
  // src/plugins/optional/keyboard-nav.ts
266
+ var focusByKernel = /* @__PURE__ */ new WeakMap();
267
+ function isEditableTarget(target) {
268
+ if (!(target instanceof HTMLElement)) return false;
269
+ if (target.isContentEditable) return true;
270
+ const tag = target.tagName;
271
+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";
272
+ }
928
273
  function keyboardNav(options = {}) {
929
274
  const {
930
275
  enabled: initialEnabled = true,
@@ -944,6 +289,9 @@ function keyboardNav(options = {}) {
944
289
  let focusedIndex = null;
945
290
  let typeaheadBuffer = "";
946
291
  let typeaheadTimer = null;
292
+ function rememberFocus() {
293
+ if (kernel) focusByKernel.set(kernel, focusedIndex);
294
+ }
947
295
  function getItemCount() {
948
296
  return kernel?.getItemCount() ?? 0;
949
297
  }
@@ -952,18 +300,39 @@ function keyboardNav(options = {}) {
952
300
  if (count === 0) return 0;
953
301
  return Math.max(0, Math.min(index, count - 1));
954
302
  }
955
- function setFocus(index) {
303
+ function revealIndex(index) {
304
+ if (!kernel) return;
305
+ if (orientation !== "grid" || columns <= 1) {
306
+ kernel.scrollToIndex(index, { align: "auto" });
307
+ return;
308
+ }
309
+ const rows = Math.ceil(getItemCount() / columns);
310
+ if (rows === 0) return;
311
+ const pitch = kernel.getTotalSize() / rows;
312
+ const top = Math.floor(index / columns) * pitch;
313
+ const bottom = top + pitch;
314
+ const viewportHeight = kernel.getViewport().height;
315
+ const scrollTop = kernel.getScrollPosition().scrollTop;
316
+ if (top < scrollTop) {
317
+ kernel.scrollTo(top);
318
+ } else if (bottom > scrollTop + viewportHeight) {
319
+ kernel.scrollTo(bottom - viewportHeight);
320
+ }
321
+ }
322
+ function setFocus(index, wrap = true) {
956
323
  if (index === null) {
957
324
  focusedIndex = null;
325
+ rememberFocus();
958
326
  return;
959
327
  }
960
328
  const count = getItemCount();
961
329
  if (count === 0) {
962
330
  focusedIndex = null;
331
+ rememberFocus();
963
332
  return;
964
333
  }
965
334
  let newIndex = index;
966
- if (loop) {
335
+ if (loop && wrap) {
967
336
  if (newIndex < 0) {
968
337
  newIndex = count - 1;
969
338
  } else if (newIndex >= count) {
@@ -974,12 +343,14 @@ function keyboardNav(options = {}) {
974
343
  }
975
344
  if (newIndex !== focusedIndex) {
976
345
  focusedIndex = newIndex;
346
+ rememberFocus();
977
347
  onFocus?.(newIndex);
978
- kernel?.scrollToIndex(newIndex, { align: "auto" });
348
+ revealIndex(newIndex);
979
349
  }
980
350
  }
981
351
  function handleKeyDown(event) {
982
352
  if (!enabled || !kernel) return;
353
+ if (isEditableTarget(event.target)) return;
983
354
  if (onKeyDown) {
984
355
  const handled = onKeyDown(event, focusedIndex);
985
356
  if (handled === true) {
@@ -987,19 +358,18 @@ function keyboardNav(options = {}) {
987
358
  return;
988
359
  }
989
360
  }
361
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
990
362
  const count = getItemCount();
991
363
  if (count === 0) return;
992
- if (focusedIndex === null && count > 0) {
993
- setFocus(0);
994
- }
364
+ const focusBeforeKey = focusedIndex;
995
365
  switch (event.key) {
996
366
  case "ArrowDown":
997
367
  if (orientation === "vertical" || orientation === "grid") {
998
368
  event.preventDefault();
999
- if (orientation === "grid") {
1000
- setFocus((focusedIndex ?? 0) + columns);
369
+ if (focusedIndex === null) {
370
+ setFocus(0);
1001
371
  } else {
1002
- setFocus((focusedIndex ?? 0) + 1);
372
+ setFocus(focusedIndex + (orientation === "grid" ? columns : 1));
1003
373
  }
1004
374
  }
1005
375
  break;
@@ -1016,7 +386,7 @@ function keyboardNav(options = {}) {
1016
386
  case "ArrowRight":
1017
387
  if (orientation === "horizontal" || orientation === "grid") {
1018
388
  event.preventDefault();
1019
- setFocus((focusedIndex ?? 0) + 1);
389
+ setFocus(focusedIndex === null ? 0 : focusedIndex + 1);
1020
390
  }
1021
391
  break;
1022
392
  case "ArrowLeft":
@@ -1035,35 +405,35 @@ function keyboardNav(options = {}) {
1035
405
  break;
1036
406
  case "PageUp":
1037
407
  event.preventDefault();
1038
- setFocus((focusedIndex ?? 0) - pageSize);
408
+ setFocus((focusedIndex ?? 0) - pageSize, false);
1039
409
  break;
1040
410
  case "PageDown":
1041
411
  event.preventDefault();
1042
- setFocus((focusedIndex ?? 0) + pageSize);
412
+ setFocus((focusedIndex ?? 0) + pageSize, false);
1043
413
  break;
1044
414
  case "Enter":
1045
415
  case " ":
1046
- event.preventDefault();
1047
416
  if (focusedIndex !== null) {
417
+ event.preventDefault();
1048
418
  onSelect?.(focusedIndex);
1049
419
  }
1050
420
  break;
1051
421
  default:
1052
422
  if (typeahead && event.key.length === 1 && !event.ctrlKey && !event.metaKey) {
1053
423
  event.preventDefault();
1054
- handleTypeahead(event.key);
424
+ handleTypeahead(event.key, focusBeforeKey);
1055
425
  }
1056
426
  break;
1057
427
  }
1058
428
  }
1059
- function handleTypeahead(char) {
429
+ function handleTypeahead(char, focusBeforeKey) {
1060
430
  if (!kernel) return;
1061
431
  if (typeaheadTimer) {
1062
432
  clearTimeout(typeaheadTimer);
1063
433
  }
1064
434
  typeaheadBuffer += char.toLowerCase();
1065
435
  const count = getItemCount();
1066
- const startIndex = focusedIndex !== null ? focusedIndex + 1 : 0;
436
+ const startIndex = typeaheadBuffer.length > 1 ? focusedIndex ?? 0 : focusBeforeKey !== null ? focusBeforeKey + 1 : 0;
1067
437
  for (let i = 0; i < count; i++) {
1068
438
  const index = (startIndex + i) % count;
1069
439
  const text = getItemText(index).toLowerCase();
@@ -1132,6 +502,9 @@ function keyboardNav(options = {}) {
1132
502
  type: "optional",
1133
503
  install(k) {
1134
504
  kernel = k;
505
+ const remembered = focusByKernel.get(k) ?? null;
506
+ const count = k.getItemCount();
507
+ focusedIndex = remembered === null || count === 0 ? null : Math.min(remembered, count - 1);
1135
508
  document.addEventListener("keydown", handleKeyDown);
1136
509
  },
1137
510
  uninstall() {
@@ -1158,6 +531,7 @@ function keyboardNav(options = {}) {
1158
531
  }
1159
532
 
1160
533
  // src/plugins/optional/scroll-restoration.ts
534
+ var restoredKernels = /* @__PURE__ */ new WeakMap();
1161
535
  function scrollRestoration(options) {
1162
536
  const {
1163
537
  key,
@@ -1171,6 +545,8 @@ function scrollRestoration(options) {
1171
545
  } = options;
1172
546
  let kernel = null;
1173
547
  let debouncedSave = null;
548
+ let restoreFrame = null;
549
+ let awaitingContent = false;
1174
550
  function getStorage() {
1175
551
  if (typeof storage === "string") {
1176
552
  if (storage === "sessionStorage") {
@@ -1227,7 +603,7 @@ function scrollRestoration(options) {
1227
603
  if (!kernel) return false;
1228
604
  const state = getSavedState();
1229
605
  if (!state) return false;
1230
- kernel.scrollTo(state.scrollTop);
606
+ kernel.scrollTo(kernel.getOptions().direction === "horizontal" ? state.scrollLeft : state.scrollTop);
1231
607
  if (includeIndex && state.focusedIndex !== void 0) {
1232
608
  const keyboardNav2 = kernel.getPlugin("keyboard-nav");
1233
609
  if (keyboardNav2?.api?.setFocusedIndex) {
@@ -1236,6 +612,26 @@ function scrollRestoration(options) {
1236
612
  }
1237
613
  return true;
1238
614
  }
615
+ function restoreOnceReachable() {
616
+ if (!kernel || restoredKernels.get(kernel) === key) {
617
+ awaitingContent = false;
618
+ return;
619
+ }
620
+ const state = getSavedState();
621
+ if (state) {
622
+ const horizontal = kernel.getOptions().direction === "horizontal";
623
+ const viewport = kernel.getViewport();
624
+ const target = horizontal ? state.scrollLeft : state.scrollTop;
625
+ const maxScroll = kernel.getTotalSize() - (horizontal ? viewport.width : viewport.height);
626
+ if (target > maxScroll + 1) {
627
+ awaitingContent = true;
628
+ return;
629
+ }
630
+ }
631
+ awaitingContent = false;
632
+ restoredKernels.set(kernel, key);
633
+ restore();
634
+ }
1239
635
  function clear() {
1240
636
  try {
1241
637
  getStorage().removeItem(getStorageKey());
@@ -1244,6 +640,10 @@ function scrollRestoration(options) {
1244
640
  }
1245
641
  }
1246
642
  function handleScroll(_event) {
643
+ if (awaitingContent && kernel) {
644
+ awaitingContent = false;
645
+ restoredKernels.set(kernel, key);
646
+ }
1247
647
  if (saveOnScroll && debouncedSave) {
1248
648
  debouncedSave();
1249
649
  }
@@ -1268,30 +668,41 @@ function scrollRestoration(options) {
1268
668
  if (saveOnScroll) {
1269
669
  debouncedSave = debounce(save, debounceMs);
1270
670
  }
1271
- if (restoreOnMount) {
1272
- requestAnimationFrame(() => {
1273
- restore();
671
+ if (restoreOnMount && restoredKernels.get(k) !== key) {
672
+ restoreFrame = requestAnimationFrame(() => {
673
+ restoreFrame = null;
674
+ restoreOnceReachable();
1274
675
  });
1275
676
  }
1276
677
  },
1277
678
  uninstall() {
1278
- if (saveOnUnmount) {
679
+ const restorePending = restoreFrame !== null;
680
+ if (restoreFrame !== null) {
681
+ cancelAnimationFrame(restoreFrame);
682
+ restoreFrame = null;
683
+ }
684
+ if (saveOnUnmount && !restorePending && !awaitingContent) {
1279
685
  save();
1280
686
  }
1281
687
  if (debouncedSave) {
1282
688
  debouncedSave.cancel();
1283
689
  debouncedSave = null;
1284
690
  }
691
+ awaitingContent = false;
1285
692
  kernel = null;
1286
693
  },
1287
694
  hooks: {
1288
- onScroll: handleScroll
695
+ onScroll: handleScroll,
696
+ onItemsChange: () => {
697
+ if (awaitingContent) restoreOnceReachable();
698
+ }
1289
699
  },
1290
700
  api
1291
701
  };
1292
702
  }
1293
703
 
1294
704
  // src/plugins/optional/bidirectional.ts
705
+ var positionedKernels = /* @__PURE__ */ new WeakSet();
1295
706
  function bidirectional(options = {}) {
1296
707
  const {
1297
708
  initialPosition = "bottom",
@@ -1306,18 +717,25 @@ function bidirectional(options = {}) {
1306
717
  let isSticking = initialStickToBottom;
1307
718
  let previousTotalSize = 0;
1308
719
  let isInitialized = false;
720
+ let initialFrame = null;
721
+ let backwardTriggered = false;
722
+ let forwardTriggered = false;
723
+ function isHorizontal() {
724
+ return kernel?.getOptions().direction === "horizontal";
725
+ }
726
+ function getOffset(position) {
727
+ return isHorizontal() ? position.scrollLeft : position.scrollTop;
728
+ }
1309
729
  function checkIsAtBottom() {
1310
730
  if (!kernel) return false;
1311
731
  const viewport = kernel.getViewport();
1312
- const scrollPosition = kernel.getScrollPosition();
1313
732
  const totalSize = kernel.getTotalSize();
1314
- const maxScroll = totalSize - viewport.height;
1315
- return scrollPosition.scrollTop >= maxScroll - stickThreshold;
733
+ const maxScroll = totalSize - (isHorizontal() ? viewport.width : viewport.height);
734
+ return getOffset(kernel.getScrollPosition()) >= maxScroll - stickThreshold;
1316
735
  }
1317
736
  function checkIsAtTop() {
1318
737
  if (!kernel) return false;
1319
- const scrollPosition = kernel.getScrollPosition();
1320
- return scrollPosition.scrollTop <= stickThreshold;
738
+ return getOffset(kernel.getScrollPosition()) <= stickThreshold;
1321
739
  }
1322
740
  function handleScroll(event) {
1323
741
  if (!kernel) return;
@@ -1327,16 +745,30 @@ function bidirectional(options = {}) {
1327
745
  if (onLoadMore) {
1328
746
  const viewport = kernel.getViewport();
1329
747
  const totalSize = kernel.getTotalSize();
1330
- if (event.scrollTop < loadMoreThreshold) {
1331
- onLoadMore("backward");
748
+ const offset = getOffset(event);
749
+ const viewportSize = isHorizontal() ? viewport.width : viewport.height;
750
+ if (offset < loadMoreThreshold) {
751
+ if (!backwardTriggered) {
752
+ backwardTriggered = true;
753
+ onLoadMore("backward");
754
+ }
755
+ } else {
756
+ backwardTriggered = false;
1332
757
  }
1333
- const distanceFromBottom = totalSize - event.scrollTop - viewport.height;
758
+ const distanceFromBottom = totalSize - offset - viewportSize;
1334
759
  if (distanceFromBottom < loadMoreThreshold) {
1335
- onLoadMore("forward");
760
+ if (!forwardTriggered) {
761
+ forwardTriggered = true;
762
+ onLoadMore("forward");
763
+ }
764
+ } else {
765
+ forwardTriggered = false;
1336
766
  }
1337
767
  }
1338
768
  }
1339
769
  function handleItemsChange(count, previousCount) {
770
+ backwardTriggered = false;
771
+ forwardTriggered = false;
1340
772
  if (!kernel || !isInitialized) return;
1341
773
  const newTotalSize = kernel.getTotalSize();
1342
774
  const sizeDelta = newTotalSize - previousTotalSize;
@@ -1346,8 +778,9 @@ function bidirectional(options = {}) {
1346
778
  if (scrollPosition.scrollTop > stickThreshold) ;
1347
779
  }
1348
780
  if (isSticking && stickToBottom) {
781
+ const k = kernel;
1349
782
  requestAnimationFrame(() => {
1350
- kernel?.scrollTo(kernel?.getTotalSize() ?? 0);
783
+ k.scrollTo(k.getTotalSize());
1351
784
  });
1352
785
  }
1353
786
  }
@@ -1379,9 +812,10 @@ function bidirectional(options = {}) {
1379
812
  adjustForPrepend(prependedHeight) {
1380
813
  if (!kernel || prependedHeight <= 0) return;
1381
814
  const scrollPosition = kernel.getScrollPosition();
815
+ const horizontal = isHorizontal();
1382
816
  kernel.setScrollPosition({
1383
- scrollTop: scrollPosition.scrollTop + prependedHeight,
1384
- scrollLeft: scrollPosition.scrollLeft
817
+ scrollTop: scrollPosition.scrollTop + (horizontal ? 0 : prependedHeight),
818
+ scrollLeft: scrollPosition.scrollLeft + (horizontal ? prependedHeight : 0)
1385
819
  });
1386
820
  }
1387
821
  };
@@ -1391,12 +825,16 @@ function bidirectional(options = {}) {
1391
825
  type: "optional",
1392
826
  install(k) {
1393
827
  kernel = k;
1394
- k.getItemCount();
1395
828
  previousTotalSize = k.getTotalSize();
1396
- if (initialPosition === "bottom") {
1397
- requestAnimationFrame(() => {
829
+ isSticking = stickToBottom && (initialPosition === "bottom" && !positionedKernels.has(k) || checkIsAtBottom());
830
+ if (initialPosition === "bottom" && !positionedKernels.has(k)) {
831
+ initialFrame = requestAnimationFrame(() => {
832
+ initialFrame = null;
1398
833
  if (kernel) {
1399
- kernel.scrollTo(kernel.getTotalSize());
834
+ if (!positionedKernels.has(kernel)) {
835
+ positionedKernels.add(kernel);
836
+ kernel.scrollTo(kernel.getTotalSize());
837
+ }
1400
838
  isInitialized = true;
1401
839
  }
1402
840
  });
@@ -1405,8 +843,14 @@ function bidirectional(options = {}) {
1405
843
  }
1406
844
  },
1407
845
  uninstall() {
846
+ if (initialFrame !== null) {
847
+ cancelAnimationFrame(initialFrame);
848
+ initialFrame = null;
849
+ }
1408
850
  kernel = null;
1409
851
  isInitialized = false;
852
+ backwardTriggered = false;
853
+ forwardTriggered = false;
1410
854
  },
1411
855
  hooks: {
1412
856
  onScroll: handleScroll,
@@ -1417,14 +861,12 @@ function bidirectional(options = {}) {
1417
861
  }
1418
862
 
1419
863
  // src/plugins/optional/drag-to-reorder.ts
864
+ var dragByKernel = /* @__PURE__ */ new WeakMap();
1420
865
  function dragToReorder(options) {
1421
866
  const {
1422
867
  enabled: initialEnabled = true,
1423
868
  axis = "vertical",
1424
- handle = true,
1425
869
  autoScroll = true,
1426
- autoScrollSpeed = 10,
1427
- dropIndicator = "line",
1428
870
  onDragStart,
1429
871
  onDragEnd,
1430
872
  onReorder,
@@ -1436,6 +878,9 @@ function dragToReorder(options) {
1436
878
  let draggedIndex = null;
1437
879
  let dropTargetIndex = null;
1438
880
  let autoScrollTimer = null;
881
+ function rememberDrag() {
882
+ if (kernel) dragByKernel.set(kernel, { dragged: draggedIndex, target: dropTargetIndex });
883
+ }
1439
884
  function handleDragStart(event, index) {
1440
885
  if (!enabled || !canDrag(index)) {
1441
886
  event.preventDefault();
@@ -1443,6 +888,7 @@ function dragToReorder(options) {
1443
888
  }
1444
889
  draggedIndex = index;
1445
890
  dropTargetIndex = index;
891
+ rememberDrag();
1446
892
  event.dataTransfer?.setData("text/plain", String(index));
1447
893
  if (event.dataTransfer) {
1448
894
  event.dataTransfer.effectAllowed = "move";
@@ -1452,27 +898,22 @@ function dragToReorder(options) {
1452
898
  startAutoScroll();
1453
899
  }
1454
900
  }
1455
- function handleDragEnd(event) {
901
+ function finishDrag() {
1456
902
  const currentDraggedIndex = draggedIndex;
1457
- const currentDropTargetIndex = dropTargetIndex;
1458
903
  stopAutoScroll();
1459
- if (currentDraggedIndex !== null && currentDropTargetIndex !== null && currentDraggedIndex !== currentDropTargetIndex) {
1460
- if (canDrop(currentDraggedIndex, currentDropTargetIndex)) {
1461
- onReorder(currentDraggedIndex, currentDropTargetIndex);
1462
- }
1463
- }
1464
904
  if (currentDraggedIndex !== null) {
1465
905
  onDragEnd?.(currentDraggedIndex);
1466
906
  }
1467
907
  draggedIndex = null;
1468
908
  dropTargetIndex = null;
909
+ rememberDrag();
910
+ }
911
+ function handleDragEnd(_event) {
912
+ finishDrag();
1469
913
  }
1470
914
  function handleDragOver(event, index) {
1471
915
  if (draggedIndex === null) return;
1472
916
  event.preventDefault();
1473
- if (event.dataTransfer) {
1474
- event.dataTransfer.dropEffect = canDrop(draggedIndex, index) ? "move" : "none";
1475
- }
1476
917
  const target = event.currentTarget;
1477
918
  const rect = target.getBoundingClientRect();
1478
919
  let newDropTarget;
@@ -1487,6 +928,10 @@ function dragToReorder(options) {
1487
928
  newDropTarget--;
1488
929
  }
1489
930
  dropTargetIndex = Math.max(0, Math.min(newDropTarget, (kernel?.getItemCount() ?? 1) - 1));
931
+ rememberDrag();
932
+ if (event.dataTransfer) {
933
+ event.dataTransfer.dropEffect = canDrop(draggedIndex, dropTargetIndex) ? "move" : "none";
934
+ }
1490
935
  }
1491
936
  function handleDragEnter(event, _index) {
1492
937
  event.preventDefault();
@@ -1495,6 +940,14 @@ function dragToReorder(options) {
1495
940
  }
1496
941
  function handleDrop(event, _index) {
1497
942
  event.preventDefault();
943
+ const currentDraggedIndex = draggedIndex;
944
+ const currentDropTargetIndex = dropTargetIndex;
945
+ if (currentDraggedIndex !== null && currentDropTargetIndex !== null && currentDraggedIndex !== currentDropTargetIndex) {
946
+ if (canDrop(currentDraggedIndex, currentDropTargetIndex)) {
947
+ onReorder(currentDraggedIndex, currentDropTargetIndex);
948
+ }
949
+ }
950
+ finishDrag();
1498
951
  }
1499
952
  function startAutoScroll() {
1500
953
  if (autoScrollTimer) return;
@@ -1538,6 +991,7 @@ function dragToReorder(options) {
1538
991
  stopAutoScroll();
1539
992
  draggedIndex = null;
1540
993
  dropTargetIndex = null;
994
+ rememberDrag();
1541
995
  },
1542
996
  enable() {
1543
997
  enabled = true;
@@ -1557,6 +1011,14 @@ function dragToReorder(options) {
1557
1011
  type: "optional",
1558
1012
  install(k) {
1559
1013
  kernel = k;
1014
+ const previous = dragByKernel.get(k);
1015
+ if (previous && previous.dragged !== null && enabled) {
1016
+ draggedIndex = previous.dragged;
1017
+ dropTargetIndex = previous.target;
1018
+ if (autoScroll) startAutoScroll();
1019
+ } else if (previous) {
1020
+ rememberDrag();
1021
+ }
1560
1022
  },
1561
1023
  uninstall() {
1562
1024
  stopAutoScroll();
@@ -1590,6 +1052,7 @@ function debugPanel(options = {}) {
1590
1052
  let lastFpsUpdate = performance.now();
1591
1053
  let currentFps = 60;
1592
1054
  let rafId = null;
1055
+ let eventUnsubscribers = [];
1593
1056
  const emptyRange = {
1594
1057
  startIndex: 0,
1595
1058
  endIndex: 0,
@@ -1660,8 +1123,13 @@ function debugPanel(options = {}) {
1660
1123
  memoryUsage = Math.round(memory.usedJSHeapSize / 1024 / 1024 * 100) / 100;
1661
1124
  }
1662
1125
  }
1663
- const visibleItems = (visibleRange.end ?? visibleRange.endIndex) - (visibleRange.start ?? visibleRange.startIndex);
1664
- const renderedItems = (renderRange.end ?? renderRange.endIndex) - (renderRange.start ?? renderRange.startIndex);
1126
+ const countOf = (range) => itemCount === 0 ? 0 : (range.end ?? range.endIndex) - (range.start ?? range.startIndex) + 1;
1127
+ const visibleItems = countOf(visibleRange);
1128
+ const renderedItems = countOf(renderRange);
1129
+ const horizontal = kernel.getOptions().direction === "horizontal";
1130
+ const viewport = kernel.getViewport();
1131
+ const scrollOffset = horizontal ? scrollPos.scrollLeft : scrollPos.scrollTop;
1132
+ const maxScroll = kernel.getTotalSize() - (horizontal ? viewport.width : viewport.height);
1665
1133
  state.stats = {
1666
1134
  ...state.stats,
1667
1135
  memoryUsage,
@@ -1672,8 +1140,8 @@ function debugPanel(options = {}) {
1672
1140
  avgItemHeight: itemCount > 0 ? kernel.getTotalSize() / itemCount : 0,
1673
1141
  scrollPosition: {
1674
1142
  ...scrollPos,
1675
- offset: scrollPos.scrollTop,
1676
- percentage: kernel.getTotalSize() > 0 ? scrollPos.scrollTop / kernel.getTotalSize() : 0
1143
+ offset: scrollOffset,
1144
+ percentage: maxScroll > 0 ? Math.min(1, Math.max(0, scrollOffset / maxScroll)) : 0
1677
1145
  },
1678
1146
  visibleRange: {
1679
1147
  ...visibleRange,
@@ -1709,6 +1177,10 @@ function debugPanel(options = {}) {
1709
1177
  }
1710
1178
  function startMonitoring() {
1711
1179
  if (rafId !== null) return;
1180
+ const now = performance.now();
1181
+ frameCount = 0;
1182
+ lastFpsUpdate = now;
1183
+ lastFrameTime = now;
1712
1184
  updateFps();
1713
1185
  statsUpdateTimer = setInterval(updateStats, resolvedOptions.statsUpdateInterval);
1714
1186
  }
@@ -1806,23 +1278,24 @@ function debugPanel(options = {}) {
1806
1278
  kernel = k;
1807
1279
  const eventTypes = [
1808
1280
  "scroll",
1809
- "scrollStart",
1810
- "scrollEnd",
1811
- "visibleRangeChange",
1812
- "itemMeasured",
1281
+ "scroll-start",
1282
+ "scroll-end",
1283
+ "visible-range-change",
1284
+ "item-measured",
1813
1285
  "resize",
1814
- "loadMore",
1815
- "itemsChange"
1286
+ "load-more",
1287
+ "items-change"
1816
1288
  ];
1817
- eventTypes.forEach((type) => {
1818
- kernel?.on(type, logEvent);
1819
- });
1289
+ eventUnsubscribers.forEach((unsubscribe) => unsubscribe());
1290
+ eventUnsubscribers = eventTypes.map((type) => k.on(type, logEvent));
1820
1291
  if (state.visible) {
1821
1292
  startMonitoring();
1822
1293
  }
1823
1294
  },
1824
1295
  uninstall() {
1825
1296
  stopMonitoring();
1297
+ eventUnsubscribers.forEach((unsubscribe) => unsubscribe());
1298
+ eventUnsubscribers = [];
1826
1299
  kernel = null;
1827
1300
  },
1828
1301
  api: extendedApi
@@ -1832,6 +1305,7 @@ function useDebugPanelState(plugin) {
1832
1305
  const api = plugin.api;
1833
1306
  const [state, setState] = useState(api.getState());
1834
1307
  useEffect(() => {
1308
+ setState({ ...api.getState() });
1835
1309
  return api.subscribe(() => {
1836
1310
  setState({ ...api.getState() });
1837
1311
  });
@@ -1866,7 +1340,8 @@ function DebugPanelOverlay({
1866
1340
  }
1867
1341
  }, [options.position]);
1868
1342
  const themeStyles = useMemo(() => {
1869
- const isDark = options.theme === "dark" || options.theme === "auto" && window.matchMedia("(prefers-color-scheme: dark)").matches;
1343
+ const prefersDark = typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-color-scheme: dark)").matches;
1344
+ const isDark = options.theme === "dark" || options.theme === "auto" && prefersDark;
1870
1345
  return isDark ? {
1871
1346
  backgroundColor: "rgba(30, 30, 30, 0.95)",
1872
1347
  color: "#e0e0e0",
@@ -2159,13 +1634,13 @@ function EventsPanel({ eventLog, onClear }) {
2159
1634
  };
2160
1635
  const typeColors = {
2161
1636
  scroll: "#6bcb77",
2162
- scrollStart: "#4d96ff",
2163
- scrollEnd: "#4d96ff",
2164
- visibleRangeChange: "#ffd93d",
2165
- itemMeasured: "#9b59b6",
1637
+ "scroll-start": "#4d96ff",
1638
+ "scroll-end": "#4d96ff",
1639
+ "visible-range-change": "#ffd93d",
1640
+ "item-measured": "#9b59b6",
2166
1641
  resize: "#ff6b6b",
2167
- loadMore: "#1abc9c",
2168
- itemsChange: "#e74c3c"
1642
+ "load-more": "#1abc9c",
1643
+ "items-change": "#e74c3c"
2169
1644
  };
2170
1645
  return /* @__PURE__ */ jsxs("div", { children: [
2171
1646
  /* @__PURE__ */ jsx("button", { style: buttonStyles, onClick: onClear, children: "Clear Log" }),
@@ -2176,6 +1651,6 @@ function EventsPanel({ eventLog, onClear }) {
2176
1651
  ] });
2177
1652
  }
2178
1653
 
2179
- export { DebugPanelOverlay, autoMeasurerPlugin, bidirectional, debugPanel, dragToReorder, gridRendererPlugin, infiniteLoaderPlugin, keyboardNav, listRendererPlugin, masonryRenderer, scrollControllerPlugin, scrollRestoration, stickyHeaders };
1654
+ export { DebugPanelOverlay, bidirectional, debugPanel, dragToReorder, keyboardNav, masonryRenderer, scrollRestoration, stickyHeaders };
2180
1655
  //# sourceMappingURL=index.js.map
2181
1656
  //# sourceMappingURL=index.js.map