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