about summary refs log tree commit diff
path: root/src/components/Dialog/context.ts
blob: eb892403f72f4c7165c6ceed10073ab9f405d133 (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
import React 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 = React.createContext<DialogContextProps>({
  close: () => {},
  isNativeDialog: false,
  nativeSnapPoint: BottomSheetSnapPoint.Hidden,
  disableDrag: false,
  setDisableDrag: () => {},
  isWithinDialog: false,
})

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

export function useDialogControl(): DialogOuterProps['control'] {
  const id = React.useId()
  const control = React.useRef<DialogControlRefProps>({
    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 React.useMemo<DialogOuterProps['control']>(
    () => ({
      id,
      ref: control,
      open: () => {
        control.current.open()
      },
      close: cb => {
        control.current.close(cb)
      },
    }),
    [id, control],
  )
}