mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import React from 'react'
2
3import {useDialogStateContext} from '#/state/dialogs'
4import {
5 DialogContextProps,
6 DialogControlRefProps,
7 DialogOuterProps,
8} from '#/components/Dialog/types'
9
10export const Context = React.createContext<DialogContextProps>({
11 close: () => {},
12})
13
14export function useDialogContext() {
15 return React.useContext(Context)
16}
17
18export function useDialogControl(): DialogOuterProps['control'] {
19 const id = React.useId()
20 const control = React.useRef<DialogControlRefProps>({
21 open: () => {},
22 close: () => {},
23 })
24 const {activeDialogs} = useDialogStateContext()
25
26 React.useEffect(() => {
27 activeDialogs.current.set(id, control)
28 return () => {
29 // eslint-disable-next-line react-hooks/exhaustive-deps
30 activeDialogs.current.delete(id)
31 }
32 }, [id, activeDialogs])
33
34 return React.useMemo<DialogOuterProps['control']>(
35 () => ({
36 id,
37 ref: control,
38 open: () => {
39 control.current.open()
40 },
41 close: cb => {
42 control.current.close(cb)
43 },
44 }),
45 [id, control],
46 )
47}