1"use client";
2
3import { cva } from "class-variance-authority";
4import { Slot as SlotPrimitive } from "radix-ui";
5import * as React from "react";
6import { cn } from "@/lib/utils";
7
8interface ItemDimension {
9 itemId: number;
10 size: number;
11}
12
13type Side = "top" | "bottom";
14
15function getDataState(isExpanded: boolean) {
16 return isExpanded ? "expanded" : "collapsed";
17}
18
19interface StackContextValue {
20 side: Side;
21 childrenCount: number;
22 itemCount: number;
23 expandedItemCount: number;
24 gap: number;
25 scale: number;
26 offset: number;
27 expandOnHover: boolean;
28 isExpanded: boolean;
29 isInteracting: boolean;
30 dimensions: ItemDimension[];
31 setDimensions: React.Dispatch<React.SetStateAction<ItemDimension[]>>;
32}
33
34const StackContext = React.createContext<StackContextValue | null>(null);
35
36function useStackContext(consumerName: string) {
37 const context = React.useContext(StackContext);
38 if (!context) {
39 throw new Error(`\`${consumerName}\` must be used within \`Stack\``);
40 }
41 return context;
42}
43
44interface StackProps extends React.ComponentProps<"div"> {
45 side?: Side;
46 itemCount?: number;
47 expandedItemCount?: number;
48 gap?: number;
49 scale?: number;
50 offset?: number;
51 expandOnHover?: boolean;
52 asChild?: boolean;
53}
54
55function Stack(props: StackProps) {
56 const {
57 side = "bottom",
58 itemCount = 3,
59 expandedItemCount,
60 gap = 8,
61 scale = 0.05,
62 offset = 10,
63 className,
64 children,
65 style,
66 onMouseEnter: onMouseEnterProp,
67 onMouseLeave: onMouseLeaveProp,
68 onMouseMove: onMouseMoveProp,
69 onPointerDown: onPointerDownProp,
70 onPointerUp: onPointerUpProp,
71 expandOnHover = false,
72 asChild,
73 ...rootProps
74 } = props;
75
76 const [isExpanded, setIsExpanded] = React.useState(false);
77 const [isInteracting, setIsInteracting] = React.useState(false);
78 const [dimensions, setDimensions] = React.useState<ItemDimension[]>([]);
79
80 const childrenArray = React.Children.toArray(children).filter(
81 React.isValidElement,
82 );
83 const childrenCount = childrenArray.length;
84
85 const effectiveExpandedItemCount = expandedItemCount ?? childrenCount;
86
87 const onMouseEnter = React.useCallback(
88 (event: React.MouseEvent<HTMLDivElement>) => {
89 onMouseEnterProp?.(event);
90 if (event.defaultPrevented) return;
91
92 if (expandOnHover) {
93 setIsExpanded(true);
94 }
95 },
96 [expandOnHover, onMouseEnterProp],
97 );
98
99 const onMouseMove = React.useCallback(
100 (event: React.MouseEvent<HTMLDivElement>) => {
101 onMouseMoveProp?.(event);
102 if (event.defaultPrevented) return;
103
104 if (expandOnHover) {
105 setIsExpanded(true);
106 }
107 },
108 [expandOnHover, onMouseMoveProp],
109 );
110
111 const onMouseLeave = React.useCallback(
112 (event: React.MouseEvent<HTMLDivElement>) => {
113 onMouseLeaveProp?.(event);
114 if (event.defaultPrevented) return;
115
116 if (expandOnHover && !isInteracting) {
117 setIsExpanded(false);
118 }
119 },
120 [expandOnHover, isInteracting, onMouseLeaveProp],
121 );
122
123 const onPointerDown = React.useCallback(
124 (event: React.PointerEvent<HTMLDivElement>) => {
125 onPointerDownProp?.(event);
126 if (event.defaultPrevented) return;
127
128 setIsInteracting(true);
129 },
130 [onPointerDownProp],
131 );
132
133 const onPointerUp = React.useCallback(
134 (event: React.PointerEvent<HTMLDivElement>) => {
135 onPointerUpProp?.(event);
136 if (event.defaultPrevented) return;
137
138 setIsInteracting(false);
139 },
140 [onPointerUpProp],
141 );
142
143 const contextValue = React.useMemo<StackContextValue>(
144 () => ({
145 side,
146 childrenCount,
147 itemCount,
148 expandedItemCount: effectiveExpandedItemCount,
149 gap,
150 scale,
151 offset,
152 expandOnHover,
153 isExpanded,
154 isInteracting,
155 dimensions,
156 setDimensions,
157 }),
158 [
159 side,
160 childrenCount,
161 itemCount,
162 effectiveExpandedItemCount,
163 gap,
164 scale,
165 offset,
166 expandOnHover,
167 isExpanded,
168 isInteracting,
169 dimensions,
170 ],
171 );
172
173 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
174
175 return (
176 <StackContext.Provider value={contextValue}>
177 <RootPrimitive
178 data-slot="stack"
179 data-state={getDataState(isExpanded)}
180 onMouseEnter={onMouseEnter}
181 onMouseMove={onMouseMove}
182 onMouseLeave={onMouseLeave}
183 onPointerDown={onPointerDown}
184 onPointerUp={onPointerUp}
185 {...rootProps}
186 className={cn("relative w-full", className)}
187 style={
188 {
189 "--gap": `${gap}px`,
190 "--offset": `${offset}px`,
191 "--scale": scale,
192 ...style,
193 } as React.CSSProperties
194 }
195 >
196 {childrenArray.map((child, index) => (
197 <StackItemWrapper key={index} index={index}>
198 {child}
199 </StackItemWrapper>
200 ))}
201 </RootPrimitive>
202 </StackContext.Provider>
203 );
204}
205
206const stackItemWrapperVariants = cva(
207 "absolute w-full transition-all duration-300 ease-out",
208 {
209 variants: {
210 side: {
211 top: [
212 "top-0 left-0 origin-top",
213 "translate-y-[calc(var(--translate)*-1)] scale-[var(--item-scale)]",
214 "after:absolute after:top-full after:left-0 after:w-full after:content-['']",
215 ],
216 bottom: [
217 "bottom-0 left-0 origin-bottom",
218 "translate-y-[var(--translate)] scale-[var(--item-scale)]",
219 "after:absolute after:bottom-full after:left-0 after:w-full after:content-['']",
220 ],
221 },
222 isExpanded: {
223 true: "after:h-[calc(var(--gap)+1px)]",
224 false: "",
225 },
226 isVisible: {
227 true: "",
228 false: "pointer-events-none",
229 },
230 },
231 },
232);
233
234type StackItemWrapperElement = React.ComponentRef<typeof StackItemWrapper>;
235
236interface StackItemWrapperProps extends React.ComponentProps<"div"> {
237 index: number;
238}
239
240function StackItemWrapper(props: StackItemWrapperProps) {
241 const { children, className, index, style, ...itemProps } = props;
242
243 const {
244 side,
245 childrenCount,
246 itemCount,
247 expandedItemCount,
248 gap,
249 scale,
250 offset,
251 isExpanded,
252 dimensions,
253 setDimensions,
254 } = useStackContext("StackItemWrapper");
255
256 const itemRef = React.useRef<StackItemWrapperElement>(null);
257
258 const isFront = index === 0;
259 const isVisible = isExpanded ? index < expandedItemCount : index < itemCount;
260
261 React.useEffect(() => {
262 const itemNode = itemRef.current;
263 if (itemNode) {
264 const rect = itemNode.getBoundingClientRect();
265 const measuredHeight = rect.height;
266 const currentScale = 1 - index * scale;
267 const naturalHeight = measuredHeight / currentScale;
268
269 setDimensions((d) => {
270 const existing = d.find((item) => item.itemId === index);
271 if (!existing) {
272 return [...d, { itemId: index, size: naturalHeight }];
273 }
274 return d;
275 });
276 }
277 }, [index, scale, setDimensions]);
278
279 const itemsSizeBefore = React.useMemo(() => {
280 return dimensions.reduce((prev, curr) => {
281 if (curr.itemId >= index) return prev;
282 return prev + curr.size;
283 }, 0);
284 }, [dimensions, index]);
285
286 const itemScale = isExpanded ? 1 : 1 - index * scale;
287 const translateValue = isExpanded
288 ? index * gap + itemsSizeBefore
289 : index * offset;
290 const zIndex = childrenCount - index;
291
292 const opacity = !isVisible ? 0 : isExpanded ? 1 : 1 - index * 0.15;
293
294 return (
295 <div
296 ref={itemRef}
297 data-slot="stack-item-wrapper"
298 data-index={index}
299 data-front={isFront}
300 data-visible={isVisible}
301 data-expanded={isExpanded}
302 className={cn(
303 stackItemWrapperVariants({ side, isExpanded, isVisible, className }),
304 )}
305 style={
306 {
307 "--translate": `${translateValue}px`,
308 "--item-scale": itemScale,
309 zIndex,
310 opacity,
311 ...style,
312 } as React.CSSProperties
313 }
314 {...itemProps}
315 >
316 <SlotPrimitive.Slot
317 data-index={index}
318 data-position={isFront ? "front" : "back"}
319 data-state={getDataState(isExpanded)}
320 >
321 {children}
322 </SlotPrimitive.Slot>
323 </div>
324 );
325}
326
327interface StackItemProps extends React.ComponentProps<"div"> {
328 asChild?: boolean;
329}
330
331function StackItem(props: StackItemProps) {
332 const { asChild, className, ...itemProps } = props;
333
334 const ItemPrimitive = asChild ? SlotPrimitive.Slot : "div";
335
336 return (
337 <ItemPrimitive
338 data-slot="stack-item"
339 {...itemProps}
340 className={cn(
341 "rounded-lg border bg-card p-4 shadow-sm transition-shadow duration-200 hover:shadow-md",
342 className,
343 )}
344 />
345 );
346}
347
348export { Stack, StackItem, type StackProps };
349