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})
26Context.displayName = 'DialogContext'
27
28export function useDialogContext() {
29 return useContext(Context)
30}
31
32export function useDialogControl(): DialogOuterProps['control'] {
33 const id = useId()
34 const control = useRef<DialogControlRefProps>({
35 open: () => {},
36 close: () => {},
37 })
38 const {activeDialogs} = useDialogStateContext()
39
40 useEffect(() => {
41 activeDialogs.current.set(id, control)
42 return () => {
43 // eslint-disable-next-line react-hooks/exhaustive-deps
44 activeDialogs.current.delete(id)
45 }
46 }, [id, activeDialogs])
47
48 return useMemo<DialogOuterProps['control']>(
49 () => ({
50 id,
51 ref: control,
52 open: () => {
53 control.current.open()
54 },
55 close: cb => {
56 control.current.close(cb)
57 },
58 }),
59 [id, control],
60 )
61}