@@ -8,11 +8,14 @@ import React, {
88 useEffect ,
99 useState ,
1010 useCallback ,
11+ useImperativeHandle ,
1112} from "react"
1213import { twJoin , twMerge } from "tailwind-merge"
13- import { getPortal } from "../utils/getPortal"
14+
1415import { overlayBaseStyle } from "./styleHelper"
1516import { VisuallyHidden } from "@radix-ui/react-visually-hidden"
17+ import { Button } from "./Button"
18+ import usePortalContainer from "../utils/usePortalContainer"
1619
1720type ModalDialogProps = {
1821 open ?: boolean
@@ -25,7 +28,7 @@ type ModalDialogProps = {
2528 style ?: CSSProperties
2629 shouldCloseOnEscapePress ?: boolean
2730 shouldCloseOnOverlayClick ?: boolean
28- usePortal ?: boolean
31+ usePortal ?: boolean | ShadowRoot
2932 useModal ?: boolean
3033 id ?: string
3134 triggerId ?: string
@@ -35,11 +38,14 @@ type ModalDialogProps = {
3538 accessibleDialogDescription : string
3639 role ?: RDialog . DialogContentProps [ "role" ]
3740 tabIndex ?: RDialog . DialogContentProps [ "tabIndex" ]
41+ ref ?: React . Ref < HTMLButtonElement >
3842}
3943
4044const blanketStyles =
4145 "fixed inset-0 bg-blanket ease-out transition-opacity duration-200 animate-fade-in"
4246
47+ const portalContainerId = "uikts-modal" as const
48+
4349function Container ( {
4450 shouldCloseOnEscapePress = true ,
4551 shouldCloseOnOverlayClick = true ,
@@ -60,7 +66,18 @@ function Container({
6066 role = "dialog" ,
6167 accessibleDialogDescription,
6268 tabIndex = undefined ,
69+ ref,
6370} : ModalDialogProps ) {
71+ const triggerRef = useRef < HTMLButtonElement > ( null )
72+ // biome-ignore lint/style/noNonNullAssertion: safe if the trigger is used
73+ useImperativeHandle ( ref , ( ) => triggerRef . current ! )
74+
75+ const portalContainer : HTMLElement | null = usePortalContainer (
76+ usePortal ,
77+ portalContainerId ,
78+ triggerRef . current ,
79+ )
80+
6481 const content = useMemo (
6582 ( ) => (
6683 < >
@@ -126,6 +143,8 @@ function Container({
126143 ] ,
127144 )
128145
146+ console . log ( "portalContainer" , portalContainer ?. parentElement ?. parentNode )
147+
129148 return (
130149 < RDialog . Root
131150 open = { open }
@@ -134,13 +153,18 @@ function Container({
134153 modal = { useModal }
135154 >
136155 { trigger && (
137- < RDialog . Trigger id = { triggerId } data-testid = { triggerTestId } >
138- { trigger }
156+ < RDialog . Trigger
157+ id = { triggerId }
158+ data-testid = { triggerTestId }
159+ asChild
160+ ref = { triggerRef }
161+ >
162+ < Button > { "Open Modal" } </ Button >
139163 </ RDialog . Trigger >
140164 ) }
141165
142166 { usePortal ? (
143- < RDialog . Portal container = { getPortal ( "uikts-modal" ) } >
167+ < RDialog . Portal container = { portalContainer } >
144168 { content }
145169 </ RDialog . Portal >
146170 ) : (
0 commit comments