/
use-modal.ts
216 lines (194 loc) · 5.44 KB
/
use-modal.ts
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { useIds } from "@chakra-ui/hooks"
import { callAllHandlers } from "@chakra-ui/utils"
import { mergeRefs, PropGetter } from "@chakra-ui/react-utils"
import { hideOthers } from "aria-hidden"
import {
KeyboardEvent,
MouseEvent,
RefObject,
useCallback,
useEffect,
useRef,
useState,
} from "react"
import { manager, useModalManager } from "./modal-manager"
export interface UseModalProps {
/**
* If `true`, the modal will be open.
*/
isOpen: boolean
/**
* The `id` of the modal
*/
id?: string
/**
* Callback invoked to close the modal.
*/
onClose(): void
/**
* If `true`, the modal will close when the overlay is clicked
* @default true
*/
closeOnOverlayClick?: boolean
/**
* If `true`, the modal will close when the `Esc` key is pressed
* @default true
*/
closeOnEsc?: boolean
/**
* Callback fired when the overlay is clicked.
*/
onOverlayClick?(): void
/**
* Callback fired when the escape key is pressed and focus is within modal
*/
onEsc?(): void
/**
* A11y: If `true`, the siblings of the `modal` will have `aria-hidden`
* set to `true` so that screen readers can only see the `modal`.
*
* This is commonly known as making the other elements **inert**
*
* @default true
*/
useInert?: boolean
}
/**
* Modal hook that manages all the logic for the modal dialog widget
* and returns prop getters, state and actions.
*
* @param props
*/
export function useModal(props: UseModalProps) {
const {
isOpen,
onClose,
id,
closeOnOverlayClick = true,
closeOnEsc = true,
useInert = true,
onOverlayClick: onOverlayClickProp,
onEsc,
} = props
const dialogRef = useRef<HTMLElement>(null)
const overlayRef = useRef<HTMLElement>(null)
const [dialogId, headerId, bodyId] = useIds(
id,
`chakra-modal`,
`chakra-modal--header`,
`chakra-modal--body`,
)
/**
* Hook used to polyfill `aria-modal` for older browsers.
* It uses `aria-hidden` to all other nodes.
*
* @see https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/
*/
useAriaHidden(dialogRef, isOpen && useInert)
/**
* Hook use to manage multiple or nested modals
*/
useModalManager(dialogRef, isOpen)
const mouseDownTarget = useRef<EventTarget | null>(null)
const onMouseDown = useCallback((event: MouseEvent) => {
mouseDownTarget.current = event.target
}, [])
const onKeyDown = useCallback(
(event: KeyboardEvent) => {
if (event.key === "Escape") {
event.stopPropagation()
if (closeOnEsc) {
onClose?.()
}
onEsc?.()
}
},
[closeOnEsc, onClose, onEsc],
)
const [headerMounted, setHeaderMounted] = useState(false)
const [bodyMounted, setBodyMounted] = useState(false)
const getDialogProps: PropGetter = useCallback(
(props = {}, ref = null) => ({
role: "dialog",
...props,
ref: mergeRefs(ref, dialogRef),
id: dialogId,
tabIndex: -1,
"aria-modal": true,
"aria-labelledby": headerMounted ? headerId : undefined,
"aria-describedby": bodyMounted ? bodyId : undefined,
onClick: callAllHandlers(props.onClick, (event: MouseEvent) =>
event.stopPropagation(),
),
}),
[bodyId, bodyMounted, dialogId, headerId, headerMounted],
)
const onOverlayClick = useCallback(
(event: MouseEvent) => {
event.stopPropagation()
/**
* Make sure the event starts and ends on the same DOM element.
*
* This is used to prevent the modal from closing when you
* start dragging from the content, and release drag outside the content.
*
* We prevent this because it is technically not a considered "click outside"
*/
if (mouseDownTarget.current !== event.target) return
/**
* When you click on the overlay, we want to remove only the topmost modal
*/
if (!manager.isTopModal(dialogRef)) return
if (closeOnOverlayClick) {
onClose?.()
}
onOverlayClickProp?.()
},
[onClose, closeOnOverlayClick, onOverlayClickProp],
)
const getDialogContainerProps: PropGetter = useCallback(
(props = {}, ref = null) => ({
...props,
ref: mergeRefs(ref, overlayRef),
onClick: callAllHandlers(props.onClick, onOverlayClick),
onKeyDown: callAllHandlers(props.onKeyDown, onKeyDown),
onMouseDown: callAllHandlers(props.onMouseDown, onMouseDown),
}),
[onKeyDown, onMouseDown, onOverlayClick],
)
return {
isOpen,
onClose,
headerId,
bodyId,
setBodyMounted,
setHeaderMounted,
dialogRef,
overlayRef,
getDialogProps,
getDialogContainerProps,
}
}
export type UseModalReturn = ReturnType<typeof useModal>
/**
* Modal hook to polyfill `aria-modal`.
*
* It applies `aria-hidden` to elements behind the modal
* to indicate that they're `inert`.
*
* @param ref React ref of the node
* @param shouldHide whether `aria-hidden` should be applied
*/
export function useAriaHidden(
ref: RefObject<HTMLElement>,
shouldHide: boolean,
) {
// save current ref in a local var to trigger the effect on identity change
const currentElement = ref.current
useEffect(() => {
// keep using `ref.current` inside the effect
// it may have changed during render and the execution of the effect
if (!ref.current || !shouldHide) return undefined
return hideOthers(ref.current)
}, [shouldHide, ref, currentElement])
}