about summary refs log tree commit diff
path: root/src/components/Dialog/context.ts
blob: 1caa4eac85853c83f700d60e5cbf628e1e4154c2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import {
  createContext,
  useContext,
  useEffect,
  useId,
  useMemo,
  useRef,
} from 'react'

import {useDialogStateContext} from '#/state/dialogs'
import {
  type DialogContextProps,
  type DialogControlRefProps,
  type DialogOuterProps,
} from '#/components/Dialog/types'
import {BottomSheetSnapPoint} from '../../../modules/bottom-sheet/src/BottomSheet.types'

export const Context = createContext<DialogContextProps>({
  close: () => {},
  isNativeDialog: false,
  nativeSnapPoint: BottomSheetSnapPoint.Hidden,
  disableDrag: false,
  setDisableDrag: () => {},
  isWithinDialog: false,
})
Context.displayName = 'DialogContext'

export function useDialogContext() {
  return useContext(Context)
}

export function useDialogControl(): DialogOuterProps['control'] {
  const id = useId()
  const control = useRef<DialogControlRefProps>({
    open: () => {},
    close: () => {},
  })
  const {activeDialogs} = useDialogStateContext()

  useEffect(() => {
    activeDialogs.current.set(id, control)
    return () => {
      // eslint-disable-next-line react-hooks/exhaustive-deps
      activeDialogs.current.delete(id)
    }
  }, [id, activeDialogs])

  return useMemo<DialogOuterProps['control']>(
    () => ({
      id,
      ref: control,
      open: () => {
        control.current.open()
      },
      close: cb => {
        control.current.close(cb)
      },
    }),
    [id, control],
  )
}