1 "use client"
2
3 import * as React from "react"
4 import { useRef } from "react"
5 import { createRoot } from "react-dom/client"
6 import { RenderPrompt, RenderPromptProps } from "./render-prompt"
7
8 type UsePromptProps = Omit<RenderPromptProps, "onConfirm" | "onCancel" | "open">
9
10 const usePrompt = () => {
11 const currentPromptPromise = useRef<Promise<boolean> | null>(null)
12
13 const prompt = async (props: UsePromptProps): Promise<boolean> => {
14 if (currentPromptPromise.current) {
15 return currentPromptPromise.current
16 }
17
18 const promptPromise = new Promise<boolean>((resolve) => {
19 let open = true
20 const mountRoot = createRoot(document.createElement("div"))
21
22 const onCancel = () => {
23 open = false
24 mountRoot.unmount()
25 resolve(false)
26 currentPromptPromise.current = null
27
28 // TEMP FIX for Radix issue with dropdowns persisting pointer-events: none on body after closing
29 document.body.style.pointerEvents = "auto"
30 }
31
32 const onConfirm = () => {
33 open = false
34 resolve(true)
35 mountRoot.unmount()
36 currentPromptPromise.current = null
37
38 // TEMP FIX for Radix issue with dropdowns persisting pointer-events: none on body after closing
39 document.body.style.pointerEvents = "auto"
40 }
41
42 const render = () => {
43 mountRoot.render(
44 <RenderPrompt
45 open={open}
46 onConfirm={onConfirm}
47 onCancel={onCancel}
48 {...props}
49 />
50 )
51 }
52
53 render()
54 })
55
56 currentPromptPromise.current = promptPromise
57 return promptPromise
58 }
59
60 return prompt
61 }
62
63 export { usePrompt }