1"use client";
2
3import { Slot as SlotPrimitive } from "radix-ui";
4import * as React from "react";
5import { useComposedRefs } from "@/lib/compose-refs";
6import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
7
8const NODE_COLOR = {
9 RED: 0,
10 BLACK: 1,
11 SENTINEL: 2,
12} as const;
13
14const NODE_OPERATION = {
15 REMOVE: 0,
16 PRESERVE: 1,
17} as const;
18
19type NodeColor = (typeof NODE_COLOR)[keyof typeof NODE_COLOR];
20type NodeOperation = (typeof NODE_OPERATION)[keyof typeof NODE_OPERATION];
21
22interface ListNode {
23 index: number;
24 high: number;
25 next: ListNode | null;
26}
27
28interface TreeNode {
29 max: number;
30 low: number;
31 high: number;
32 color: NodeColor;
33 parent: TreeNode;
34 right: TreeNode;
35 left: TreeNode;
36 list: ListNode;
37}
38
39interface Tree {
40 root: TreeNode;
41 size: number;
42}
43
44function addInterval(treeNode: TreeNode, high: number, index: number): boolean {
45 let node: ListNode | null = treeNode.list;
46 let prevNode: ListNode | undefined;
47
48 while (node) {
49 if (node.index === index) return false;
50 if (high > node.high) break;
51 prevNode = node;
52 node = node.next;
53 }
54
55 if (!prevNode) treeNode.list = { index, high, next: node };
56 if (prevNode) prevNode.next = { index, high, next: prevNode.next };
57
58 return true;
59}
60
61function removeInterval(
62 treeNode: TreeNode,
63 index: number,
64): NodeOperation | undefined {
65 let node: ListNode | null = treeNode.list;
66 if (node.index === index) {
67 if (node.next === null) return NODE_OPERATION.REMOVE;
68 treeNode.list = node.next;
69 return NODE_OPERATION.PRESERVE;
70 }
71
72 let prevNode: ListNode | undefined = node;
73 node = node.next;
74
75 while (node !== null) {
76 if (node.index === index) {
77 prevNode.next = node.next;
78 return NODE_OPERATION.PRESERVE;
79 }
80 prevNode = node;
81 node = node.next;
82 }
83}
84
85const SENTINEL_NODE: TreeNode = {
86 low: 0,
87 max: 0,
88 high: 0,
89 color: NODE_COLOR.SENTINEL,
90 parent: undefined as unknown as TreeNode,
91 right: undefined as unknown as TreeNode,
92 left: undefined as unknown as TreeNode,
93 list: undefined as unknown as ListNode,
94};
95
96SENTINEL_NODE.parent = SENTINEL_NODE;
97SENTINEL_NODE.left = SENTINEL_NODE;
98SENTINEL_NODE.right = SENTINEL_NODE;
99
100function updateMax(node: TreeNode) {
101 const max = node.high;
102 if (node.left === SENTINEL_NODE && node.right === SENTINEL_NODE)
103 node.max = max;
104 else if (node.left === SENTINEL_NODE)
105 node.max = Math.max(node.right.max, max);
106 else if (node.right === SENTINEL_NODE)
107 node.max = Math.max(node.left.max, max);
108 else node.max = Math.max(Math.max(node.left.max, node.right.max), max);
109}
110
111function updateMaxUp(node: TreeNode) {
112 let x = node;
113
114 while (x.parent !== SENTINEL_NODE) {
115 updateMax(x.parent);
116 x = x.parent;
117 }
118}
119
120function rotateLeft(tree: Tree, x: TreeNode) {
121 if (x.right === SENTINEL_NODE) return;
122 const y = x.right;
123 x.right = y.left;
124 if (y.left !== SENTINEL_NODE) y.left.parent = x;
125 y.parent = x.parent;
126
127 if (x.parent === SENTINEL_NODE) tree.root = y;
128 else if (x === x.parent.left) x.parent.left = y;
129 else x.parent.right = y;
130
131 y.left = x;
132 x.parent = y;
133
134 updateMax(x);
135 updateMax(y);
136}
137
138function rotateRight(tree: Tree, x: TreeNode) {
139 if (x.left === SENTINEL_NODE) return;
140 const y = x.left;
141 x.left = y.right;
142 if (y.right !== SENTINEL_NODE) y.right.parent = x;
143 y.parent = x.parent;
144
145 if (x.parent === SENTINEL_NODE) tree.root = y;
146 else if (x === x.parent.right) x.parent.right = y;
147 else x.parent.left = y;
148
149 y.right = x;
150 x.parent = y;
151
152 updateMax(x);
153 updateMax(y);
154}
155
156function replaceNode(tree: Tree, x: TreeNode, y: TreeNode) {
157 if (x.parent === SENTINEL_NODE) tree.root = y;
158 else if (x === x.parent.left) x.parent.left = y;
159 else x.parent.right = y;
160 y.parent = x.parent;
161}
162
163function fixRemove(tree: Tree, node: TreeNode) {
164 let x = node;
165 let w: TreeNode;
166
167 while (x !== SENTINEL_NODE && x.color === NODE_COLOR.BLACK) {
168 if (x === x.parent.left) {
169 w = x.parent.right;
170
171 if (w.color === NODE_COLOR.RED) {
172 w.color = NODE_COLOR.BLACK;
173 x.parent.color = NODE_COLOR.RED;
174 rotateLeft(tree, x.parent);
175 w = x.parent.right;
176 }
177
178 if (
179 w.left.color === NODE_COLOR.BLACK &&
180 w.right.color === NODE_COLOR.BLACK
181 ) {
182 w.color = NODE_COLOR.RED;
183 x = x.parent;
184 } else {
185 if (w.right.color === NODE_COLOR.BLACK) {
186 w.left.color = NODE_COLOR.BLACK;
187 w.color = NODE_COLOR.RED;
188 rotateRight(tree, w);
189 w = x.parent.right;
190 }
191
192 w.color = x.parent.color;
193 x.parent.color = NODE_COLOR.BLACK;
194 w.right.color = NODE_COLOR.BLACK;
195 rotateLeft(tree, x.parent);
196 x = tree.root;
197 }
198 } else {
199 w = x.parent.left;
200
201 if (w.color === NODE_COLOR.RED) {
202 w.color = NODE_COLOR.BLACK;
203 x.parent.color = NODE_COLOR.RED;
204 rotateRight(tree, x.parent);
205 w = x.parent.left;
206 }
207
208 if (
209 w.right.color === NODE_COLOR.BLACK &&
210 w.left.color === NODE_COLOR.BLACK
211 ) {
212 w.color = NODE_COLOR.RED;
213 x = x.parent;
214 } else {
215 if (w.left.color === NODE_COLOR.BLACK) {
216 w.right.color = NODE_COLOR.BLACK;
217 w.color = NODE_COLOR.RED;
218 rotateLeft(tree, w);
219 w = x.parent.left;
220 }
221
222 w.color = x.parent.color;
223 x.parent.color = NODE_COLOR.BLACK;
224 w.left.color = NODE_COLOR.BLACK;
225 rotateRight(tree, x.parent);
226 x = tree.root;
227 }
228 }
229 }
230
231 x.color = NODE_COLOR.BLACK;
232}
233
234function minimumTree(node: TreeNode) {
235 let current = node;
236 while (current.left !== SENTINEL_NODE) {
237 current = current.left;
238 }
239 return current;
240}
241
242function fixInsert(tree: Tree, node: TreeNode) {
243 let current = node;
244 let y: TreeNode;
245
246 while (current.parent.color === NODE_COLOR.RED) {
247 if (current.parent === current.parent.parent.left) {
248 y = current.parent.parent.right;
249
250 if (y.color === NODE_COLOR.RED) {
251 current.parent.color = NODE_COLOR.BLACK;
252 y.color = NODE_COLOR.BLACK;
253 current.parent.parent.color = NODE_COLOR.RED;
254 current = current.parent.parent;
255 } else {
256 if (current === current.parent.right) {
257 current = current.parent;
258 rotateLeft(tree, current);
259 }
260
261 current.parent.color = NODE_COLOR.BLACK;
262 current.parent.parent.color = NODE_COLOR.RED;
263 rotateRight(tree, current.parent.parent);
264 }
265 } else {
266 y = current.parent.parent.left;
267
268 if (y.color === NODE_COLOR.RED) {
269 current.parent.color = NODE_COLOR.BLACK;
270 y.color = NODE_COLOR.BLACK;
271 current.parent.parent.color = NODE_COLOR.RED;
272 current = current.parent.parent;
273 } else {
274 if (current === current.parent.left) {
275 current = current.parent;
276 rotateRight(tree, current);
277 }
278
279 current.parent.color = NODE_COLOR.BLACK;
280 current.parent.parent.color = NODE_COLOR.RED;
281 rotateLeft(tree, current.parent.parent);
282 }
283 }
284 }
285 tree.root.color = NODE_COLOR.BLACK;
286}
287
288interface IntervalTree {
289 insert(low: number, high: number, index: number): void;
290 remove(index: number): void;
291 search(
292 low: number,
293 high: number,
294 onCallback: (index: number, low: number) => void,
295 ): void;
296 size: number;
297}
298
299function createIntervalTree(): IntervalTree {
300 const tree: Tree = {
301 root: SENTINEL_NODE,
302 size: 0,
303 };
304
305 const indexMap: Record<number, TreeNode> = {};
306
307 return {
308 insert(low, high, index) {
309 let x: TreeNode = tree.root;
310 let y: TreeNode = SENTINEL_NODE;
311
312 while (x !== SENTINEL_NODE) {
313 y = x;
314 if (low === y.low) break;
315 if (low < x.low) x = x.left;
316 else x = x.right;
317 }
318
319 if (low === y.low && y !== SENTINEL_NODE) {
320 if (!addInterval(y, high, index)) return;
321 y.high = Math.max(y.high, high);
322 updateMax(y);
323 updateMaxUp(y);
324 indexMap[index] = y;
325 tree.size++;
326 return;
327 }
328
329 const z: TreeNode = {
330 low,
331 high,
332 max: high,
333 color: NODE_COLOR.RED,
334 parent: y,
335 left: SENTINEL_NODE,
336 right: SENTINEL_NODE,
337 list: { index, high, next: null },
338 };
339
340 if (y === SENTINEL_NODE) {
341 tree.root = z;
342 } else {
343 if (z.low < y.low) y.left = z;
344 else y.right = z;
345 updateMaxUp(z);
346 }
347
348 fixInsert(tree, z);
349 indexMap[index] = z;
350 tree.size++;
351 },
352
353 remove(index) {
354 const z = indexMap[index];
355 if (z === void 0) return;
356 delete indexMap[index];
357
358 const intervalResult = removeInterval(z, index);
359 if (intervalResult === void 0) return;
360 if (intervalResult === NODE_OPERATION.PRESERVE) {
361 z.high = z.list.high;
362 updateMax(z);
363 updateMaxUp(z);
364 tree.size--;
365 return;
366 }
367
368 let y = z;
369 let originalYColor = y.color;
370 let x: TreeNode;
371
372 if (z.left === SENTINEL_NODE) {
373 x = z.right;
374 replaceNode(tree, z, z.right);
375 } else if (z.right === SENTINEL_NODE) {
376 x = z.left;
377 replaceNode(tree, z, z.left);
378 } else {
379 y = minimumTree(z.right);
380 originalYColor = y.color;
381 x = y.right;
382
383 if (y.parent === z) {
384 x.parent = y;
385 } else {
386 replaceNode(tree, y, y.right);
387 y.right = z.right;
388 y.right.parent = y;
389 }
390
391 replaceNode(tree, z, y);
392 y.left = z.left;
393 y.left.parent = y;
394 y.color = z.color;
395 }
396
397 updateMax(x);
398 updateMaxUp(x);
399
400 if (originalYColor === NODE_COLOR.BLACK) fixRemove(tree, x);
401 tree.size--;
402 },
403
404 search(low, high, onCallback) {
405 const stack = [tree.root];
406 while (stack.length !== 0) {
407 const node = stack.pop();
408 if (!node) continue;
409 if (node === SENTINEL_NODE || low > node.max) continue;
410 if (node.left !== SENTINEL_NODE) stack.push(node.left);
411 if (node.right !== SENTINEL_NODE) stack.push(node.right);
412 if (node.low <= high && node.high >= low) {
413 let curr: ListNode | null = node.list;
414 while (curr !== null) {
415 if (curr.high >= low) onCallback(curr.index, node.low);
416 curr = curr.next;
417 }
418 }
419 }
420 },
421
422 get size() {
423 return tree.size;
424 },
425 };
426}
427
428type CacheKey = string | number | symbol;
429type CacheConstructor = (new () => Cache) | Record<CacheKey, unknown>;
430
431interface Cache<K = CacheKey, V = unknown> {
432 set: (k: K, v: V) => V;
433 get: (k: K) => V | undefined;
434}
435
436function onDeepMemo<T extends unknown[], U>(
437 constructors: CacheConstructor[],
438 fn: (...args: T) => U,
439): (...args: T) => U {
440 if (!constructors.length || !constructors[0]) {
441 throw new Error("At least one constructor is required");
442 }
443
444 function createCache(obj: CacheConstructor): Cache {
445 let cache: Cache;
446 if (typeof obj === "function") {
447 try {
448 cache = new (obj as new () => Cache)();
449 } catch (_err) {
450 cache = new Map<CacheKey, unknown>();
451 }
452 } else {
453 cache = obj as unknown as Cache;
454 }
455 return {
456 set(k: CacheKey, v: unknown): unknown {
457 cache.set(k, v);
458 return v;
459 },
460 get(k: CacheKey): unknown | undefined {
461 return cache.get(k);
462 },
463 };
464 }
465
466 const depth = constructors.length;
467 const baseCache = createCache(constructors[0]);
468
469 let base: Cache | undefined;
470 let map: Cache | undefined;
471 let node: Cache;
472 let i: number;
473 const one = depth === 1;
474
475 function get(args: unknown[]): unknown {
476 if (depth < 3) {
477 const key = args[0] as CacheKey;
478 base = baseCache.get(key) as Cache | undefined;
479 return one ? base : base?.get(args[1] as CacheKey);
480 }
481
482 node = baseCache;
483 for (i = 0; i < depth; i++) {
484 const next = node.get(args[i] as CacheKey);
485 if (!next) return undefined;
486 node = next as Cache;
487 }
488 return node;
489 }
490
491 function set(args: unknown[], value: unknown): unknown {
492 if (depth < 3) {
493 if (one) {
494 baseCache.set(args[0] as CacheKey, value);
495 } else {
496 base = baseCache.get(args[0] as CacheKey) as Cache | undefined;
497 if (!base) {
498 if (!constructors[1]) {
499 throw new Error(
500 "Second constructor is required for non-single depth cache",
501 );
502 }
503 map = createCache(constructors[1]);
504 map.set(args[1] as CacheKey, value);
505 baseCache.set(args[0] as CacheKey, map);
506 } else {
507 base.set(args[1] as CacheKey, value);
508 }
509 }
510 return value;
511 }
512
513 node = baseCache;
514 for (i = 0; i < depth - 1; i++) {
515 map = node.get(args[i] as CacheKey) as Cache | undefined;
516 if (!map) {
517 const nextConstructor = constructors[i + 1];
518 if (!nextConstructor) {
519 throw new Error(`Constructor at index ${i + 1} is required`);
520 }
521 map = createCache(nextConstructor);
522 node.set(args[i] as CacheKey, map);
523 node = map;
524 } else {
525 node = map;
526 }
527 }
528 node.set(args[depth - 1] as CacheKey, value);
529 return value;
530 }
531
532 return (...args: T): U => {
533 const cached = get(args);
534 if (cached === undefined) {
535 return set(args, fn(...args)) as U;
536 }
537 return cached as U;
538 };
539}
540
541const COLUMN_WIDTH = 200;
542const GAP = 0;
543const ITEM_HEIGHT = 300;
544const OVERSCAN = 2;
545const SCROLL_FPS = 12;
546const DEBOUNCE_DELAY = 300;
547
548interface Positioner {
549 columnCount: number;
550 columnWidth: number;
551 set: (index: number, height: number) => void;
552 get: (index: number) => PositionerItem | undefined;
553 update: (updates: number[]) => void;
554 range: (
555 low: number,
556 high: number,
557 onItemRender: (index: number, left: number, top: number) => void,
558 ) => void;
559 size: () => number;
560 estimateHeight: (itemCount: number, defaultItemHeight: number) => number;
561 shortestColumn: () => number;
562 all: () => PositionerItem[];
563}
564
565interface PositionerItem {
566 top: number;
567 left: number;
568 height: number;
569 columnIndex: number;
570}
571
572interface UsePositionerOptions {
573 width: number;
574 columnWidth?: number;
575 columnGap?: number;
576 rowGap?: number;
577 columnCount?: number;
578 maxColumnCount?: number;
579 linear?: boolean;
580}
581
582function usePositioner(
583 {
584 width,
585 columnWidth = COLUMN_WIDTH,
586 columnGap = GAP,
587 rowGap,
588 columnCount,
589 maxColumnCount,
590 linear = false,
591 }: UsePositionerOptions,
592 deps: React.DependencyList = [],
593): Positioner {
594 const initPositioner = React.useCallback((): Positioner => {
595 function binarySearch(a: number[], y: number): number {
596 let l = 0;
597 let h = a.length - 1;
598
599 while (l <= h) {
600 const m = (l + h) >>> 1;
601 const x = a[m];
602 if (x === y) return m;
603 if (x === undefined || x <= y) l = m + 1;
604 else h = m - 1;
605 }
606
607 return -1;
608 }
609
610 const computedColumnCount =
611 columnCount ||
612 Math.min(
613 Math.floor((width + columnGap) / (columnWidth + columnGap)),
614 maxColumnCount || Number.POSITIVE_INFINITY,
615 ) ||
616 1;
617 const computedColumnWidth = Math.floor(
618 (width - columnGap * (computedColumnCount - 1)) / computedColumnCount,
619 );
620
621 const intervalTree = createIntervalTree();
622 const columnHeights: number[] = new Array(computedColumnCount).fill(0);
623 const items: (PositionerItem | undefined)[] = [];
624 const columnItems: number[][] = new Array(computedColumnCount)
625 .fill(0)
626 .map(() => []);
627
628 for (let i = 0; i < computedColumnCount; i++) {
629 columnHeights[i] = 0;
630 columnItems[i] = [];
631 }
632
633 return {
634 columnCount: computedColumnCount,
635 columnWidth: computedColumnWidth,
636 set: (index: number, height = 0) => {
637 let columnIndex = 0;
638
639 if (linear) {
640 const preferredColumn = index % computedColumnCount;
641
642 let shortestHeight = columnHeights[0] ?? 0;
643 let tallestHeight = shortestHeight;
644 let shortestIndex = 0;
645
646 for (let i = 0; i < columnHeights.length; i++) {
647 const currentHeight = columnHeights[i] ?? 0;
648 if (currentHeight < shortestHeight) {
649 shortestHeight = currentHeight;
650 shortestIndex = i;
651 }
652 if (currentHeight > tallestHeight) {
653 tallestHeight = currentHeight;
654 }
655 }
656
657 const preferredHeight =
658 (columnHeights[preferredColumn] ?? 0) + height;
659
660 const maxAllowedHeight = shortestHeight + height * 2.5;
661 columnIndex =
662 preferredHeight <= maxAllowedHeight
663 ? preferredColumn
664 : shortestIndex;
665 } else {
666 for (let i = 1; i < columnHeights.length; i++) {
667 const currentHeight = columnHeights[i];
668 const shortestHeight = columnHeights[columnIndex];
669 if (
670 currentHeight !== undefined &&
671 shortestHeight !== undefined &&
672 currentHeight < shortestHeight
673 ) {
674 columnIndex = i;
675 }
676 }
677 }
678
679 const columnHeight = columnHeights[columnIndex];
680 if (columnHeight === undefined) return;
681
682 const top = columnHeight;
683 columnHeights[columnIndex] = top + height + (rowGap ?? columnGap);
684
685 const columnItemsList = columnItems[columnIndex];
686 if (!columnItemsList) return;
687 columnItemsList.push(index);
688
689 items[index] = {
690 left: columnIndex * (computedColumnWidth + columnGap),
691 top,
692 height,
693 columnIndex,
694 };
695 intervalTree.insert(top, top + height, index);
696 },
697 get: (index: number) => items[index],
698 update: (updates: number[]) => {
699 const columns: (number | undefined)[] = new Array(computedColumnCount);
700 let i = 0;
701 let j = 0;
702
703 for (; i < updates.length - 1; i++) {
704 const currentIndex = updates[i];
705 if (typeof currentIndex !== "number") continue;
706
707 const item = items[currentIndex];
708 if (!item) continue;
709
710 const nextHeight = updates[++i];
711 if (typeof nextHeight !== "number") continue;
712
713 item.height = nextHeight;
714 intervalTree.remove(currentIndex);
715 intervalTree.insert(item.top, item.top + item.height, currentIndex);
716 columns[item.columnIndex] =
717 columns[item.columnIndex] === void 0
718 ? currentIndex
719 : Math.min(
720 currentIndex,
721 columns[item.columnIndex] ?? currentIndex,
722 );
723 }
724
725 for (i = 0; i < columns.length; i++) {
726 const currentColumn = columns[i];
727 if (currentColumn === void 0) continue;
728
729 const itemsInColumn = columnItems[i];
730 if (!itemsInColumn) continue;
731
732 const startIndex = binarySearch(itemsInColumn, currentColumn);
733 if (startIndex === -1) continue;
734
735 const currentItemIndex = itemsInColumn[startIndex];
736 if (typeof currentItemIndex !== "number") continue;
737
738 const startItem = items[currentItemIndex];
739 if (!startItem) continue;
740
741 const currentHeight = columnHeights[i];
742 if (typeof currentHeight !== "number") continue;
743
744 columnHeights[i] =
745 startItem.top + startItem.height + (rowGap ?? columnGap);
746
747 for (j = startIndex + 1; j < itemsInColumn.length; j++) {
748 const currentIndex = itemsInColumn[j];
749 if (typeof currentIndex !== "number") continue;
750
751 const item = items[currentIndex];
752 if (!item) continue;
753
754 const columnHeight = columnHeights[i];
755 if (typeof columnHeight !== "number") continue;
756
757 item.top = columnHeight;
758 columnHeights[i] = item.top + item.height + (rowGap ?? columnGap);
759 intervalTree.remove(currentIndex);
760 intervalTree.insert(item.top, item.top + item.height, currentIndex);
761 }
762 }
763 },
764 range: (low, high, onItemRender) =>
765 intervalTree.search(low, high, (index: number, top: number) => {
766 const item = items[index];
767 if (!item) return;
768 onItemRender(index, item.left, top);
769 }),
770 estimateHeight: (itemCount, defaultItemHeight): number => {
771 const tallestColumn = Math.max(0, Math.max.apply(null, columnHeights));
772
773 return itemCount === intervalTree.size
774 ? tallestColumn
775 : tallestColumn +
776 Math.ceil((itemCount - intervalTree.size) / computedColumnCount) *
777 defaultItemHeight;
778 },
779 shortestColumn: () => {
780 if (columnHeights.length > 1)
781 return Math.min.apply(null, columnHeights);
782 return columnHeights[0] ?? 0;
783 },
784 size(): number {
785 return intervalTree.size;
786 },
787 all(): PositionerItem[] {
788 return items.filter(Boolean) as PositionerItem[];
789 },
790 };
791 }, [
792 width,
793 columnWidth,
794 columnGap,
795 rowGap,
796 columnCount,
797 maxColumnCount,
798 linear,
799 ]);
800
801 const positionerRef = React.useRef<Positioner | null>(null);
802 if (positionerRef.current === null) positionerRef.current = initPositioner();
803
804 const prevDepsRef = React.useRef(deps);
805 const opts = [
806 width,
807 columnWidth,
808 columnGap,
809 rowGap,
810 columnCount,
811 maxColumnCount,
812 linear,
813 ];
814 const prevOptsRef = React.useRef(opts);
815 const optsChanged = !opts.every((item, i) => prevOptsRef.current[i] === item);
816
817 if (
818 optsChanged ||
819 !deps.every((item, i) => prevDepsRef.current[i] === item)
820 ) {
821 const prevPositioner = positionerRef.current;
822 const positioner = initPositioner();
823 prevDepsRef.current = deps;
824 prevOptsRef.current = opts;
825
826 if (optsChanged) {
827 const cacheSize = prevPositioner.size();
828 for (let index = 0; index < cacheSize; index++) {
829 const pos = prevPositioner.get(index);
830 positioner.set(index, pos !== void 0 ? pos.height : 0);
831 }
832 }
833
834 positionerRef.current = positioner;
835 }
836
837 return positionerRef.current;
838}
839
840interface DebouncedWindowSizeOptions {
841 containerRef: React.RefObject<RootElement | null>;
842 defaultWidth?: number;
843 defaultHeight?: number;
844 delayMs?: number;
845}
846
847function useDebouncedWindowSize(options: DebouncedWindowSizeOptions) {
848 const {
849 containerRef,
850 defaultWidth = 0,
851 defaultHeight = 0,
852 delayMs = DEBOUNCE_DELAY,
853 } = options;
854
855 const getDocumentSize = React.useCallback(() => {
856 if (typeof document === "undefined") {
857 return { width: defaultWidth, height: defaultHeight };
858 }
859 return {
860 width: document.documentElement.clientWidth,
861 height: document.documentElement.clientHeight,
862 };
863 }, [defaultWidth, defaultHeight]);
864
865 const [size, setSize] = React.useState(getDocumentSize());
866 const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);
867
868 const setDebouncedSize = React.useCallback(
869 (value: { width: number; height: number }) => {
870 if (timeoutRef.current) {
871 clearTimeout(timeoutRef.current);
872 }
873
874 timeoutRef.current = setTimeout(() => {
875 setSize(value);
876 }, delayMs);
877 },
878 [delayMs],
879 );
880
881 React.useEffect(() => {
882 function onResize() {
883 if (containerRef.current) {
884 setDebouncedSize({
885 width: containerRef.current.offsetWidth,
886 height: document.documentElement.clientHeight,
887 });
888 } else {
889 setDebouncedSize(getDocumentSize());
890 }
891 }
892
893 window?.addEventListener("resize", onResize, { passive: true });
894 window?.addEventListener("orientationchange", onResize);
895 window.visualViewport?.addEventListener("resize", onResize);
896
897 return () => {
898 window?.removeEventListener("resize", onResize);
899 window?.removeEventListener("orientationchange", onResize);
900 window.visualViewport?.removeEventListener("resize", onResize);
901 if (timeoutRef.current) clearTimeout(timeoutRef.current);
902 };
903 }, [setDebouncedSize, containerRef, getDocumentSize]);
904
905 return size;
906}
907
908type OnRafScheduleReturn<T extends unknown[]> = {
909 (...args: T): void;
910 cancel: () => void;
911};
912
913function onRafSchedule<T extends unknown[]>(
914 callback: (...args: T) => void,
915): OnRafScheduleReturn<T> {
916 let lastArgs: T = [] as unknown as T;
917 let frameId: number | null = null;
918
919 function onCallback(...args: T) {
920 lastArgs = args;
921
922 if (frameId)
923 frameId = requestAnimationFrame(() => {
924 frameId = null;
925 callback(...lastArgs);
926 });
927 }
928
929 onCallback.cancel = () => {
930 if (!frameId) return;
931 cancelAnimationFrame(frameId);
932 frameId = null;
933 };
934
935 return onCallback;
936}
937
938function useResizeObserver(positioner: Positioner) {
939 const [, setLayoutVersion] = React.useState(0);
940
941 const createResizeObserver = React.useMemo(() => {
942 if (typeof window === "undefined") {
943 return () => ({
944 disconnect: () => {},
945 observe: () => {},
946 unobserve: () => {},
947 });
948 }
949
950 return onDeepMemo(
951 [WeakMap],
952 (positioner: Positioner, onUpdate: () => void) => {
953 const updates: number[] = [];
954 const itemMap = new WeakMap<Element, number>();
955
956 const update = onRafSchedule(() => {
957 if (updates.length > 0) {
958 positioner.update(updates);
959 onUpdate();
960 }
961 updates.length = 0;
962 });
963
964 function onItemResize(target: ItemElement) {
965 const height = target.offsetHeight;
966 if (height > 0) {
967 const index = itemMap.get(target);
968 if (index !== void 0) {
969 const position = positioner.get(index);
970 if (position !== void 0 && height !== position.height) {
971 updates.push(index, height);
972 }
973 }
974 }
975 update();
976 }
977
978 const scheduledItemMap = new Map<
979 number,
980 OnRafScheduleReturn<[ItemElement]>
981 >();
982 function onResizeObserver(entries: ResizeObserverEntry[]) {
983 for (const entry of entries) {
984 if (!entry) continue;
985 const index = itemMap.get(entry.target);
986
987 if (index === void 0) continue;
988 let handler = scheduledItemMap.get(index);
989 if (!handler) {
990 handler = onRafSchedule(onItemResize);
991 scheduledItemMap.set(index, handler);
992 }
993 handler(entry.target as ItemElement);
994 }
995 }
996
997 const observer = new ResizeObserver(onResizeObserver);
998 const disconnect = observer.disconnect.bind(observer);
999 observer.disconnect = () => {
1000 disconnect();
1001 for (const [, scheduleItem] of scheduledItemMap) {
1002 scheduleItem.cancel();
1003 }
1004 };
1005
1006 return observer;
1007 },
1008 );
1009 }, []);
1010
1011 const resizeObserver = createResizeObserver(positioner, () =>
1012 setLayoutVersion((prev) => prev + 1),
1013 );
1014
1015 React.useEffect(() => () => resizeObserver.disconnect(), [resizeObserver]);
1016
1017 return resizeObserver;
1018}
1019
1020function useScroller({
1021 offset = 0,
1022 fps = SCROLL_FPS,
1023}: {
1024 offset?: number;
1025 fps?: number;
1026} = {}): { scrollTop: number; isScrolling: boolean } {
1027 const [scrollY, setScrollY] = useThrottle(
1028 typeof globalThis.window === "undefined"
1029 ? 0
1030 : (globalThis.window.scrollY ?? document.documentElement.scrollTop ?? 0),
1031 { fps, leading: true },
1032 );
1033
1034 const onScroll = React.useCallback(() => {
1035 setScrollY(
1036 globalThis.window.scrollY ?? document.documentElement.scrollTop ?? 0,
1037 );
1038 }, [setScrollY]);
1039
1040 React.useEffect(() => {
1041 if (typeof globalThis.window === "undefined") return;
1042 globalThis.window.addEventListener("scroll", onScroll, { passive: true });
1043
1044 return () => globalThis.window.removeEventListener("scroll", onScroll);
1045 }, [onScroll]);
1046
1047 const [isScrolling, setIsScrolling] = React.useState(false);
1048 const hasMountedRef = React.useRef(0);
1049
1050 React.useEffect(() => {
1051 if (hasMountedRef.current === 1) setIsScrolling(true);
1052 let didUnsubscribe = false;
1053
1054 function requestTimeout(fn: () => void, delay: number) {
1055 const start = performance.now();
1056 const handle = {
1057 id: requestAnimationFrame(function tick(timestamp) {
1058 if (timestamp - start >= delay) {
1059 fn();
1060 } else {
1061 handle.id = requestAnimationFrame(tick);
1062 }
1063 }),
1064 };
1065 return handle;
1066 }
1067
1068 const timeout = requestTimeout(
1069 () => {
1070 if (didUnsubscribe) return;
1071 setIsScrolling(false);
1072 },
1073 40 + 1000 / fps,
1074 );
1075 hasMountedRef.current = 1;
1076 return () => {
1077 didUnsubscribe = true;
1078 cancelAnimationFrame(timeout.id);
1079 };
1080 }, [fps]);
1081
1082 return { scrollTop: Math.max(0, scrollY - offset), isScrolling };
1083}
1084
1085function useThrottle<State>(
1086 initialState: State | (() => State),
1087 options: {
1088 fps?: number;
1089 leading?: boolean;
1090 } = {},
1091): [State, React.Dispatch<React.SetStateAction<State>>] {
1092 const { fps = 30, leading = false } = options;
1093 const [state, setState] = React.useState(initialState);
1094 const latestSetState = React.useRef(setState);
1095 latestSetState.current = setState;
1096
1097 const ms = 1000 / fps;
1098 const prevCountRef = React.useRef(0);
1099 const trailingTimeout = React.useRef<ReturnType<typeof setTimeout> | null>(
1100 null,
1101 );
1102
1103 const clearTrailing = React.useCallback(() => {
1104 if (trailingTimeout.current) {
1105 clearTimeout(trailingTimeout.current);
1106 }
1107 }, []);
1108
1109 React.useEffect(() => {
1110 return () => {
1111 prevCountRef.current = 0;
1112 clearTrailing();
1113 };
1114 }, [clearTrailing]);
1115
1116 const throttledSetState = React.useCallback(
1117 (action: React.SetStateAction<State>) => {
1118 const perf = typeof performance !== "undefined" ? performance : Date;
1119 const now = () => perf.now();
1120 const rightNow = now();
1121 const call = () => {
1122 prevCountRef.current = rightNow;
1123 clearTrailing();
1124 latestSetState.current(action);
1125 };
1126 const current = prevCountRef.current;
1127
1128 if (leading && current === 0) {
1129 return call();
1130 }
1131
1132 if (rightNow - current > ms) {
1133 if (current > 0) {
1134 return call();
1135 }
1136 prevCountRef.current = rightNow;
1137 }
1138
1139 clearTrailing();
1140 trailingTimeout.current = setTimeout(() => {
1141 call();
1142 prevCountRef.current = 0;
1143 }, ms);
1144 },
1145 [leading, ms, clearTrailing],
1146 );
1147
1148 return [state, throttledSetState];
1149}
1150
1151const ROOT_NAME = "MasonryRoot";
1152const VIEWPORT_NAME = "MasonryViewport";
1153const ITEM_NAME = "MasonryItem";
1154
1155const MASONRY_ERROR = {
1156 [ROOT_NAME]: `\`${ROOT_NAME}\` components must be within \`${ROOT_NAME}\``,
1157 [VIEWPORT_NAME]: `\`${VIEWPORT_NAME}\` components must be within \`${ROOT_NAME}\``,
1158 [ITEM_NAME]: `\`${ITEM_NAME}\` must be within \`${VIEWPORT_NAME}\``,
1159} as const;
1160
1161interface DivProps extends React.ComponentProps<"div"> {}
1162
1163type RootElement = React.ComponentRef<typeof Masonry>;
1164type ItemElement = React.ComponentRef<typeof MasonryItem>;
1165
1166interface MasonryContextValue {
1167 positioner: Positioner;
1168 resizeObserver?: ResizeObserver;
1169 columnWidth: number;
1170 onItemRegister: (index: number) => (node: ItemElement | null) => void;
1171 scrollTop: number;
1172 windowHeight: number;
1173 itemHeight: number;
1174 overscan: number;
1175 isScrolling?: boolean;
1176 fallback?: React.ReactNode;
1177}
1178
1179const MasonryContext = React.createContext<MasonryContextValue | null>(null);
1180
1181function useMasonryContext(name: keyof typeof MASONRY_ERROR) {
1182 const context = React.useContext(MasonryContext);
1183 if (!context) {
1184 throw new Error(MASONRY_ERROR[name]);
1185 }
1186 return context;
1187}
1188
1189interface MasonryProps extends DivProps {
1190 columnWidth?: number;
1191 columnCount?: number;
1192 maxColumnCount?: number;
1193 gap?: number | { column: number; row: number };
1194 itemHeight?: number;
1195 defaultWidth?: number;
1196 defaultHeight?: number;
1197 overscan?: number;
1198 scrollFps?: number;
1199 fallback?: React.ReactNode;
1200 linear?: boolean;
1201 asChild?: boolean;
1202}
1203
1204function Masonry(props: MasonryProps) {
1205 const {
1206 columnWidth = COLUMN_WIDTH,
1207 columnCount,
1208 maxColumnCount,
1209 gap = GAP,
1210 itemHeight = ITEM_HEIGHT,
1211 defaultWidth,
1212 defaultHeight,
1213 overscan = OVERSCAN,
1214 scrollFps = SCROLL_FPS,
1215 fallback,
1216 linear = false,
1217 asChild,
1218 children,
1219 style,
1220 ref,
1221 ...rootProps
1222 } = props;
1223
1224 const gapValue = typeof gap === "object" ? gap : { column: gap, row: gap };
1225 const columnGap = gapValue.column;
1226 const rowGap = gapValue.row;
1227
1228 const containerRef = React.useRef<RootElement | null>(null);
1229 const composedRef = useComposedRefs(ref, containerRef);
1230
1231 const size = useDebouncedWindowSize({
1232 containerRef,
1233 defaultWidth,
1234 defaultHeight,
1235 delayMs: DEBOUNCE_DELAY,
1236 });
1237
1238 const [containerPosition, setContainerPosition] = React.useState<{
1239 offset: number;
1240 width: number;
1241 }>({ offset: 0, width: 0 });
1242
1243 useIsomorphicLayoutEffect(() => {
1244 if (!containerRef.current) return;
1245
1246 let offset = 0;
1247 let container = containerRef.current;
1248
1249 do {
1250 offset += container.offsetTop ?? 0;
1251 container = container.offsetParent as RootElement;
1252 } while (container);
1253
1254 if (
1255 offset !== containerPosition.offset ||
1256 containerRef.current.offsetWidth !== containerPosition.width
1257 ) {
1258 setContainerPosition({
1259 offset,
1260 width: containerRef.current.offsetWidth,
1261 });
1262 }
1263 }, [containerPosition, size]);
1264
1265 const positioner = usePositioner({
1266 width: containerPosition.width ?? size.width,
1267 columnWidth,
1268 columnGap,
1269 rowGap,
1270 columnCount,
1271 maxColumnCount,
1272 linear,
1273 });
1274 const resizeObserver = useResizeObserver(positioner);
1275 const { scrollTop, isScrolling } = useScroller({
1276 offset: containerPosition.offset,
1277 fps: scrollFps,
1278 });
1279
1280 const itemMap = React.useRef(new WeakMap<ItemElement, number>()).current;
1281
1282 const onItemRegister = React.useCallback(
1283 (index: number) => (node: ItemElement | null) => {
1284 if (!node) return;
1285
1286 itemMap.set(node, index);
1287 if (resizeObserver) {
1288 resizeObserver.observe(node);
1289 }
1290 if (positioner.get(index) === void 0) {
1291 positioner.set(index, node.offsetHeight);
1292 }
1293 },
1294 [itemMap, positioner, resizeObserver],
1295 );
1296
1297 const contextValue = React.useMemo<MasonryContextValue>(
1298 () => ({
1299 positioner,
1300 resizeObserver,
1301 columnWidth: positioner.columnWidth,
1302 onItemRegister,
1303 scrollTop,
1304 windowHeight: size.height,
1305 itemHeight,
1306 overscan,
1307 fallback,
1308 isScrolling,
1309 }),
1310 [
1311 positioner,
1312 resizeObserver,
1313 onItemRegister,
1314 scrollTop,
1315 size.height,
1316 itemHeight,
1317 overscan,
1318 fallback,
1319 isScrolling,
1320 ],
1321 );
1322
1323 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
1324
1325 return (
1326 <MasonryContext.Provider value={contextValue}>
1327 <RootPrimitive
1328 {...rootProps}
1329 data-slot="masonry"
1330 ref={composedRef}
1331 style={{
1332 position: "relative",
1333 width: "100%",
1334 height: "100%",
1335 ...style,
1336 }}
1337 >
1338 <MasonryViewport>{children}</MasonryViewport>
1339 </RootPrimitive>
1340 </MasonryContext.Provider>
1341 );
1342}
1343
1344interface MasonryItemPropsWithRef extends MasonryItemProps {
1345 ref: React.Ref<ItemElement | null>;
1346}
1347
1348function MasonryViewport(props: DivProps) {
1349 const { children, style, ref, ...viewportProps } = props;
1350 const context = useMasonryContext(VIEWPORT_NAME);
1351 const [layoutVersion, setLayoutVersion] = React.useState(0);
1352 const rafId = React.useRef<number | null>(null);
1353 const [mounted, setMounted] = React.useState(false);
1354
1355 useIsomorphicLayoutEffect(() => {
1356 setMounted(true);
1357 }, []);
1358
1359 let startIndex = 0;
1360 let stopIndex: number | undefined;
1361
1362 const validChildren = React.Children.toArray(children).filter(
1363 (child): child is React.ReactElement<MasonryItemPropsWithRef> =>
1364 React.isValidElement(child) &&
1365 (child.type === MasonryItem || child.type === MasonryItem),
1366 );
1367 const itemCount = validChildren.length;
1368
1369 const shortestColumnSize = context.positioner.shortestColumn();
1370 const measuredCount = context.positioner.size();
1371 const overscanPixels = context.windowHeight * context.overscan;
1372 const rangeStart = Math.max(0, context.scrollTop - overscanPixels / 2);
1373 const rangeEnd = context.scrollTop + overscanPixels;
1374 const layoutOutdated =
1375 shortestColumnSize < rangeEnd && measuredCount < itemCount;
1376
1377 const positionedChildren: React.ReactElement[] = [];
1378
1379 const visibleItemStyle = React.useMemo(
1380 (): React.CSSProperties => ({
1381 position: "absolute",
1382 writingMode: "horizontal-tb",
1383 visibility: "visible",
1384 width: context.columnWidth,
1385 transform: context.isScrolling ? "translateZ(0)" : undefined,
1386 willChange: context.isScrolling ? "transform" : undefined,
1387 }),
1388 [context.columnWidth, context.isScrolling],
1389 );
1390
1391 const hiddenItemStyle = React.useMemo(
1392 (): React.CSSProperties => ({
1393 position: "absolute",
1394 writingMode: "horizontal-tb",
1395 visibility: "hidden",
1396 width: context.columnWidth,
1397 zIndex: -1000,
1398 }),
1399 [context.columnWidth],
1400 );
1401
1402 context.positioner.range(rangeStart, rangeEnd, (index, left, top) => {
1403 const child = validChildren[index];
1404 if (!child) return;
1405
1406 const itemStyle = {
1407 ...visibleItemStyle,
1408 top,
1409 left,
1410 ...child.props.style,
1411 };
1412
1413 positionedChildren.push(
1414 React.cloneElement(child, {
1415 key: child.key ?? index,
1416 ref: context.onItemRegister(index),
1417 style: itemStyle,
1418 }),
1419 );
1420
1421 if (stopIndex === undefined) {
1422 startIndex = index;
1423 stopIndex = index;
1424 } else {
1425 startIndex = Math.min(startIndex, index);
1426 stopIndex = Math.max(stopIndex, index);
1427 }
1428 });
1429
1430 if (layoutOutdated && mounted) {
1431 const batchSize = Math.min(
1432 itemCount - measuredCount,
1433 Math.ceil(
1434 ((context.scrollTop + overscanPixels - shortestColumnSize) /
1435 context.itemHeight) *
1436 context.positioner.columnCount,
1437 ),
1438 );
1439
1440 for (
1441 let index = measuredCount;
1442 index < measuredCount + batchSize;
1443 index++
1444 ) {
1445 const child = validChildren[index];
1446 if (!child) continue;
1447
1448 const itemStyle = {
1449 ...hiddenItemStyle,
1450 ...child.props.style,
1451 };
1452
1453 positionedChildren.push(
1454 React.cloneElement(child, {
1455 key: child.key ?? index,
1456 ref: context.onItemRegister(index),
1457 style: itemStyle,
1458 }),
1459 );
1460 }
1461 }
1462
1463 React.useEffect(() => {
1464 if (layoutOutdated && mounted) {
1465 if (rafId.current) {
1466 cancelAnimationFrame(rafId.current);
1467 }
1468 rafId.current = requestAnimationFrame(() => {
1469 setLayoutVersion((v) => v + 1);
1470 });
1471 }
1472 return () => {
1473 if (rafId.current) {
1474 cancelAnimationFrame(rafId.current);
1475 }
1476 };
1477 }, [layoutOutdated, mounted]);
1478
1479 const estimatedHeight = React.useMemo(() => {
1480 const measuredHeight = context.positioner.estimateHeight(
1481 measuredCount,
1482 context.itemHeight,
1483 );
1484 if (measuredCount === itemCount) {
1485 return measuredHeight;
1486 }
1487 const remainingItems = itemCount - measuredCount;
1488 const estimatedRemainingHeight = Math.ceil(
1489 (remainingItems / context.positioner.columnCount) * context.itemHeight,
1490 );
1491 return measuredHeight + estimatedRemainingHeight;
1492 }, [context.positioner, context.itemHeight, measuredCount, itemCount]);
1493
1494 const containerStyle = React.useMemo(
1495 () => ({
1496 position: "relative" as const,
1497 width: "100%",
1498 maxWidth: "100%",
1499 height: Math.ceil(estimatedHeight),
1500 maxHeight: Math.ceil(estimatedHeight),
1501 willChange: context.isScrolling ? "contents" : undefined,
1502 pointerEvents: context.isScrolling ? ("none" as const) : undefined,
1503 ...style,
1504 }),
1505 [context.isScrolling, estimatedHeight, style],
1506 );
1507
1508 if (!mounted && context.fallback) {
1509 return context.fallback;
1510 }
1511
1512 return (
1513 <div
1514 {...viewportProps}
1515 ref={ref}
1516 style={containerStyle}
1517 data-version={mounted ? layoutVersion : undefined}
1518 >
1519 {positionedChildren}
1520 </div>
1521 );
1522}
1523
1524interface MasonryItemProps extends DivProps {
1525 asChild?: boolean;
1526}
1527
1528function MasonryItem(props: MasonryItemProps) {
1529 const { asChild, ref, ...itemProps } = props;
1530
1531 const ItemPrimitive = asChild ? SlotPrimitive.Slot : "div";
1532
1533 return <ItemPrimitive data-slot="masonry-item" {...itemProps} ref={ref} />;
1534}
1535
1536export { Masonry, MasonryItem, type MasonryProps };
1537