diff options
Diffstat (limited to 'src/components/Dialog/context.ts')
-rw-r--r-- | src/components/Dialog/context.ts | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/src/components/Dialog/context.ts b/src/components/Dialog/context.ts new file mode 100644 index 000000000..b28b9f5a2 --- /dev/null +++ b/src/components/Dialog/context.ts @@ -0,0 +1,35 @@ +import React from 'react' + +import {useDialogStateContext} from '#/state/dialogs' +import {DialogContextProps, DialogControlProps} from '#/components/Dialog/types' + +export const Context = React.createContext<DialogContextProps>({ + close: () => {}, +}) + +export function useDialogContext() { + return React.useContext(Context) +} + +export function useDialogControl() { + const id = React.useId() + const control = React.useRef<DialogControlProps>({ + open: () => {}, + close: () => {}, + }) + const {activeDialogs} = useDialogStateContext() + + React.useEffect(() => { + activeDialogs.current.set(id, control) + return () => { + // eslint-disable-next-line react-hooks/exhaustive-deps + activeDialogs.current.delete(id) + } + }, [id, activeDialogs]) + + return { + ref: control, + open: () => control.current.open(), + close: () => control.current.close(), + } +} |