1 import { FocusModal, clx } from "@medusajs/ui"
2 import {
3 ComponentPropsWithoutRef,
4 PropsWithChildren,
5 forwardRef,
6 useEffect,
7 } from "react"
8 import { useStackedModal } from "../stacked-modal-provider"
9
10 type StackedFocusModalProps = PropsWithChildren<{
11 /**
12 * A unique identifier for the modal. This is used to differentiate stacked modals,
13 * when multiple stacked modals are registered to the same parent modal.
14 */
15 id: string
16 /**
17 * An optional callback that is called when the modal is opened or closed.
18 */
19 onOpenChangeCallback?: (open: boolean) => void
20 }>
21
22 /**
23 * A stacked modal that can be rendered above a parent modal.
24 */
25 export const Root = ({
26 id,
27 onOpenChangeCallback,
28 children,
29 }: StackedFocusModalProps) => {
30 const { register, unregister, getIsOpen, setIsOpen } = useStackedModal()
31
32 useEffect(() => {
33 register(id)
34
35 return () => unregister(id)
36 // eslint-disable-next-line react-hooks/exhaustive-deps
37 }, [])
38
39 const handleOpenChange = (open: boolean) => {
40 setIsOpen(id, open)
41 onOpenChangeCallback?.(open)
42 }
43
44 return (
45 <FocusModal open={getIsOpen(id)} onOpenChange={handleOpenChange}>
46 {children}
47 </FocusModal>
48 )
49 }
50
51 const Close = FocusModal.Close
52 Close.displayName = "StackedFocusModal.Close"
53
54 const Header = FocusModal.Header
55 Header.displayName = "StackedFocusModal.Header"
56
57 const Body = FocusModal.Body
58 Body.displayName = "StackedFocusModal.Body"
59
60 const Trigger = FocusModal.Trigger
61 Trigger.displayName = "StackedFocusModal.Trigger"
62
63 const Footer = FocusModal.Footer
64 Footer.displayName = "StackedFocusModal.Footer"
65
66 const Title = FocusModal.Title
67 Title.displayName = "StackedFocusModal.Title"
68
69 const Description = FocusModal.Description
70 Description.displayName = "StackedFocusModal.Description"
71
72 const Content = forwardRef<
73 HTMLDivElement,
74 ComponentPropsWithoutRef<typeof FocusModal.Content>
75 >(({ className, ...props }, ref) => {
76 return (
77 <FocusModal.Content
78 ref={ref}
79 className={clx("!top-6", className)}
80 overlayProps={{
81 className: "bg-transparent",
82 }}
83 {...props}
84 />
85 )
86 })
87 Content.displayName = "StackedFocusModal.Content"
88
89 export const StackedFocusModal = Object.assign(Root, {
90 Close,
91 Header,
92 Body,
93 Content,
94 Trigger,
95 Footer,
96 Description,
97 Title,
98 })