Composable stacked dialogs, useful for creating a wizard, nested form or multi-step process. It provides a consistent layout and styling for each dialog, and includes navigation component.
1"use client";
2
3import { useControllableState } from "@radix-ui/react-use-controllable-state";
4import { Portal } from "radix-ui";
5import type {
6 ButtonHTMLAttributes,
7 Dispatch,
8 HTMLAttributes,
9 MouseEvent,
10 MouseEventHandler,
11 ReactElement,
12 SetStateAction,
13} from "react";
14import {
15 Children,
16 cloneElement,
17 createContext,
18 useCallback,
19 useContext,
20 useEffect,
21 useState,
22} from "react";
23import { cn } from "@/lib/utils";
24
25type DialogStackContextType = {
26 activeIndex: number;
27 setActiveIndex: Dispatch<SetStateAction<number>>;
28 totalDialogs: number;
29 setTotalDialogs: Dispatch<SetStateAction<number>>;
30 isOpen: boolean;
31 setIsOpen: Dispatch<SetStateAction<boolean>>;
32 clickable: boolean;
33};
34
35const DialogStackContext = createContext<DialogStackContextType>({
36 activeIndex: 0,
37 setActiveIndex: () => {},
38 totalDialogs: 0,
39 setTotalDialogs: () => {},
40 isOpen: false,
41 setIsOpen: () => {},
42 clickable: false,
43});
44
45type DialogStackChildProps = {
46 index?: number;
47};
48
49export type DialogStackProps = HTMLAttributes<HTMLDivElement> & {
50 open?: boolean;
51 clickable?: boolean;
52 onOpenChange?: (open: boolean) => void;
53 defaultOpen?: boolean;
54};
55
56export const DialogStack = ({
57 children,
58 className,
59 open,
60 defaultOpen = false,
61 onOpenChange,
62 clickable = false,
63 ...props
64}: DialogStackProps) => {
65 const [activeIndex, setActiveIndex] = useState(0);
66 const [isOpen, setIsOpen] = useControllableState({
67 defaultProp: defaultOpen,
68 prop: open,
69 onChange: onOpenChange,
70 });
71
72 useEffect(() => {
73 if (onOpenChange && isOpen !== undefined) {
74 onOpenChange(isOpen);
75 }
76 }, [isOpen, onOpenChange]);
77
78 return (
79 <DialogStackContext.Provider
80 value={{
81 activeIndex,
82 setActiveIndex,
83 totalDialogs: 0,
84 setTotalDialogs: () => {},
85 isOpen: isOpen ?? false,
86 setIsOpen: (value) => setIsOpen(Boolean(value)),
87 clickable,
88 }}
89 >
90 <div className={className} {...props}>
91 {children}
92 </div>
93 </DialogStackContext.Provider>
94 );
95};
96
97export type DialogStackTriggerProps =
98 ButtonHTMLAttributes<HTMLButtonElement> & {
99 asChild?: boolean;
100 };
101
102export const DialogStackTrigger = ({
103 children,
104 className,
105 onClick,
106 asChild,
107 ...props
108}: DialogStackTriggerProps) => {
109 const context = useContext(DialogStackContext);
110
111 if (!context) {
112 throw new Error("DialogStackTrigger must be used within a DialogStack");
113 }
114
115 const handleClick: MouseEventHandler<HTMLButtonElement> = (e) => {
116 context.setIsOpen(true);
117 onClick?.(e);
118 };
119
120 if (asChild && children) {
121 const child = children as ReactElement<{
122 onClick: MouseEventHandler<HTMLButtonElement>;
123 className?: string;
124 }>;
125 return cloneElement(child, {
126 onClick: (e: MouseEvent<HTMLButtonElement>) => {
127 handleClick(e);
128 child.props.onClick?.(e);
129 },
130 className: cn(className, child.props.className),
131 ...props,
132 });
133 }
134
135 return (
136 <button
137 className={cn(
138 "inline-flex items-center justify-center whitespace-nowrap rounded-md font-medium text-sm",
139 "ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2",
140 "focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
141 "bg-primary text-primary-foreground hover:bg-primary/90",
142 "h-10 px-4 py-2",
143 className
144 )}
145 onClick={handleClick}
146 {...props}
147 >
148 {children}
149 </button>
150 );
151};
152
153export type DialogStackOverlayProps = HTMLAttributes<HTMLDivElement>;
154
155export const DialogStackOverlay = ({
156 className,
157 ...props
158}: DialogStackOverlayProps) => {
159 const context = useContext(DialogStackContext);
160
161 if (!context) {
162 throw new Error("DialogStackOverlay must be used within a DialogStack");
163 }
164
165 const handleClick = useCallback(() => {
166 context.setIsOpen(false);
167 }, [context.setIsOpen]);
168
169 if (!context.isOpen) {
170 return null;
171 }
172
173 return (
174 // biome-ignore lint/a11y/noStaticElementInteractions: "This is a clickable overlay"
175 // biome-ignore lint/a11y/useKeyWithClickEvents: "This is a clickable overlay"
176 <div
177 className={cn(
178 "fixed inset-0 z-50 bg-black/80",
179 "data-[state=closed]:animate-out data-[state=open]:animate-in",
180 "data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
181 className
182 )}
183 onClick={handleClick}
184 {...props}
185 />
186 );
187};
188
189export type DialogStackBodyProps = HTMLAttributes<HTMLDivElement> & {
190 children:
191 | ReactElement<DialogStackChildProps>[]
192 | ReactElement<DialogStackChildProps>;
193};
194
195export const DialogStackBody = ({
196 children,
197 className,
198 ...props
199}: DialogStackBodyProps) => {
200 const context = useContext(DialogStackContext);
201 const [totalDialogs, setTotalDialogs] = useState(Children.count(children));
202
203 if (!context) {
204 throw new Error("DialogStackBody must be used within a DialogStack");
205 }
206
207 if (!context.isOpen) {
208 return null;
209 }
210
211 return (
212 <DialogStackContext.Provider
213 value={{
214 ...context,
215 totalDialogs,
216 setTotalDialogs,
217 }}
218 >
219 <Portal.Root>
220 <div
221 className={cn(
222 "pointer-events-none fixed inset-0 z-50 mx-auto flex w-full max-w-lg flex-col items-center justify-center",
223 className
224 )}
225 {...props}
226 >
227 <div className="pointer-events-auto relative flex w-full flex-col items-center justify-center">
228 {Children.map(children, (child, index) => {
229 const childElement = child as ReactElement<{
230 index: number;
231 onClick: MouseEventHandler<HTMLButtonElement>;
232 className?: string;
233 }>;
234
235 return cloneElement(childElement, {
236 ...childElement.props,
237 index,
238 });
239 })}
240 </div>
241 </div>
242 </Portal.Root>
243 </DialogStackContext.Provider>
244 );
245};
246
247export type DialogStackContentProps = HTMLAttributes<HTMLDivElement> & {
248 index?: number;
249 offset?: number;
250};
251
252export const DialogStackContent = ({
253 children,
254 className,
255 index = 0,
256 offset = 10,
257 ...props
258}: DialogStackContentProps) => {
259 const context = useContext(DialogStackContext);
260
261 if (!context) {
262 throw new Error("DialogStackContent must be used within a DialogStack");
263 }
264
265 if (!context.isOpen) {
266 return null;
267 }
268
269 const handleClick = () => {
270 if (context.clickable && context.activeIndex > index) {
271 context.setActiveIndex(index ?? 0);
272 }
273 };
274
275 const distanceFromActive = index - context.activeIndex;
276 const translateY =
277 distanceFromActive < 0
278 ? `-${Math.abs(distanceFromActive) * offset}px`
279 : `${Math.abs(distanceFromActive) * offset}px`;
280
281 return (
282 // biome-ignore lint/a11y/noStaticElementInteractions: "This is a clickable dialog"
283 // biome-ignore lint/a11y/useKeyWithClickEvents: "This is a clickable dialog"
284 <div
285 className={cn(
286 "h-auto w-full rounded-lg border bg-background p-6 shadow-lg transition-all duration-300",
287 className
288 )}
289 onClick={handleClick}
290 style={{
291 top: 0,
292 transform: `translateY(${translateY})`,
293 width: `calc(100% - ${Math.abs(distanceFromActive) * 10}px)`,
294 zIndex: 50 - Math.abs(context.activeIndex - (index ?? 0)),
295 position: distanceFromActive ? "absolute" : "relative",
296 opacity: distanceFromActive > 0 ? 0 : 1,
297 cursor:
298 context.clickable && context.activeIndex > index
299 ? "pointer"
300 : "default",
301 }}
302 {...props}
303 >
304 <div
305 className={cn(
306 "h-full w-full transition-all duration-300",
307 context.activeIndex !== index &&
308 "pointer-events-none select-none opacity-0"
309 )}
310 >
311 {children}
312 </div>
313 </div>
314 );
315};
316
317export type DialogStackTitleProps = HTMLAttributes<HTMLHeadingElement>;
318
319export const DialogStackTitle = ({
320 children,
321 className,
322 ...props
323}: DialogStackTitleProps) => (
324 <h2
325 className={cn(
326 "font-semibold text-lg leading-none tracking-tight",
327 className
328 )}
329 {...props}
330 >
331 {children}
332 </h2>
333);
334
335export type DialogStackDescriptionProps = HTMLAttributes<HTMLParagraphElement>;
336
337export const DialogStackDescription = ({
338 children,
339 className,
340 ...props
341}: DialogStackDescriptionProps) => (
342 <p className={cn("text-muted-foreground text-sm", className)} {...props}>
343 {children}
344 </p>
345);
346
347export type DialogStackHeaderProps = HTMLAttributes<HTMLDivElement>;
348
349export const DialogStackHeader = ({
350 className,
351 ...props
352}: DialogStackHeaderProps) => (
353 <div
354 className={cn(
355 "flex flex-col space-y-1.5 text-center sm:text-left",
356 className
357 )}
358 {...props}
359 />
360);
361
362export type DialogStackFooterProps = HTMLAttributes<HTMLDivElement>;
363
364export const DialogStackFooter = ({
365 children,
366 className,
367 ...props
368}: DialogStackFooterProps) => (
369 <div
370 className={cn("flex items-center justify-end space-x-2 pt-4", className)}
371 {...props}
372 >
373 {children}
374 </div>
375);
376
377export type DialogStackNextProps = ButtonHTMLAttributes<HTMLButtonElement> & {
378 asChild?: boolean;
379};
380
381export const DialogStackNext = ({
382 children,
383 className,
384 asChild,
385 ...props
386}: DialogStackNextProps) => {
387 const context = useContext(DialogStackContext);
388
389 if (!context) {
390 throw new Error("DialogStackNext must be used within a DialogStack");
391 }
392
393 const handleNext = () => {
394 if (context.activeIndex < context.totalDialogs - 1) {
395 context.setActiveIndex(context.activeIndex + 1);
396 }
397 };
398
399 if (asChild && children) {
400 const child = children as ReactElement<{
401 onClick: MouseEventHandler<HTMLButtonElement>;
402 className?: string;
403 }>;
404
405 return cloneElement(child, {
406 onClick: (e: MouseEvent<HTMLButtonElement>) => {
407 handleNext();
408 child.props.onClick?.(e);
409 },
410 className: cn(className, child.props.className),
411 ...props,
412 });
413 }
414
415 return (
416 <button
417 className={cn(
418 "inline-flex items-center justify-center whitespace-nowrap rounded-md font-medium text-sm ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
419 className
420 )}
421 disabled={context.activeIndex >= context.totalDialogs - 1}
422 onClick={handleNext}
423 type="button"
424 {...props}
425 >
426 {children || "Next"}
427 </button>
428 );
429};
430
431export type DialogStackPreviousProps =
432 ButtonHTMLAttributes<HTMLButtonElement> & {
433 asChild?: boolean;
434 };
435
436export const DialogStackPrevious = ({
437 children,
438 className,
439 asChild,
440 ...props
441}: DialogStackPreviousProps) => {
442 const context = useContext(DialogStackContext);
443
444 if (!context) {
445 throw new Error("DialogStackPrevious must be used within a DialogStack");
446 }
447
448 const handlePrevious = () => {
449 if (context.activeIndex > 0) {
450 context.setActiveIndex(context.activeIndex - 1);
451 }
452 };
453
454 if (asChild && children) {
455 const child = children as ReactElement<{
456 onClick: MouseEventHandler<HTMLButtonElement>;
457 className?: string;
458 }>;
459
460 return cloneElement(child, {
461 onClick: (e: MouseEvent<HTMLButtonElement>) => {
462 handlePrevious();
463 child.props.onClick?.(e);
464 },
465 className: cn(className, child.props.className),
466 ...props,
467 });
468 }
469
470 return (
471 <button
472 className={cn(
473 "inline-flex items-center justify-center whitespace-nowrap rounded-md font-medium text-sm ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
474 className
475 )}
476 disabled={context.activeIndex <= 0}
477 onClick={handlePrevious}
478 type="button"
479 {...props}
480 >
481 {children || "Previous"}
482 </button>
483 );
484};
485