-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
Expand file tree
/
Copy pathuseModal.ts
More file actions
255 lines (211 loc) · 7.61 KB
/
Copy pathuseModal.ts
File metadata and controls
255 lines (211 loc) · 7.61 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
'use client';
import * as React from 'react';
import ownerDocument from '@mui/utils/ownerDocument';
import useForkRef from '@mui/utils/useForkRef';
import useEventCallback from '@mui/utils/useEventCallback';
import createChainedFunction from '@mui/utils/createChainedFunction';
import extractEventHandlers from '@mui/utils/extractEventHandlers';
import { EventHandlers } from '../utils/types';
import { ModalManager, ariaHidden } from './ModalManager';
import {
UseModalParameters,
UseModalReturnValue,
UseModalRootSlotProps,
UseModalBackdropSlotProps,
} from './useModal.types';
function getContainer(container: UseModalParameters['container']) {
return typeof container === 'function' ? container() : container;
}
function getHasTransition(children: UseModalParameters['children']) {
return children ? children.props.hasOwnProperty('in') : false;
}
const noop = () => {};
// A modal manager used to track and manage the state of open Modals.
// Modals don't open on the server so this won't conflict with concurrent requests.
const manager = new ModalManager();
function useModal(parameters: UseModalParameters): UseModalReturnValue {
const {
container,
disableScrollLock = false,
closeAfterTransition = false,
onTransitionEnter,
onTransitionExited,
children,
onClose,
open,
rootRef,
} = parameters;
// @ts-ignore internal logic
const modal = React.useRef<{ modalRef: HTMLDivElement; mount: HTMLElement }>({});
const mountNodeRef = React.useRef<HTMLElement>(null);
const lastMountNodeRef = React.useRef<HTMLElement>(null);
const modalRef = React.useRef<HTMLDivElement>(null);
const registeredContainerRef = React.useRef<HTMLElement>(null);
const handleRef = useForkRef(modalRef, rootRef);
const [exited, setExited] = React.useState(!open);
const hasTransition = getHasTransition(children);
let ariaHiddenProp = true;
if (parameters['aria-hidden'] === 'false' || parameters['aria-hidden'] === false) {
ariaHiddenProp = false;
}
const getDoc = () => ownerDocument(mountNodeRef.current);
const getModal = () => {
modal.current.modalRef = modalRef.current!;
modal.current.mount = mountNodeRef.current!;
return modal.current;
};
const handleMounted = () => {
manager.mount(getModal(), { disableScrollLock });
// Fix a bug on Chrome where the scroll isn't initially 0.
if (modalRef.current) {
modalRef.current.scrollTop = 0;
}
};
const handleOpen = useEventCallback(() => {
const resolvedContainer = getContainer(container) || getDoc().body;
// When the container changes while the modal stays open, the previous container
// keeps the `aria-hidden` state computed for the previous sibling set.
// Unregister the modal first so the new container is evaluated against its own siblings.
if (registeredContainerRef.current && registeredContainerRef.current !== resolvedContainer) {
manager.remove(getModal(), ariaHiddenProp);
registeredContainerRef.current = null;
}
manager.add(getModal(), resolvedContainer as HTMLElement);
registeredContainerRef.current = resolvedContainer as HTMLElement;
// The element was already mounted.
if (modalRef.current) {
handleMounted();
}
});
const isTopModal = () => manager.isTopModal(getModal());
const handlePortalRef = useEventCallback((node: HTMLElement | null) => {
mountNodeRef.current = node;
if (!node) {
return;
}
lastMountNodeRef.current = node;
if (open && isTopModal()) {
handleMounted();
} else if (modalRef.current) {
ariaHidden(modalRef.current, ariaHiddenProp);
}
});
const handleClose = React.useCallback(() => {
registeredContainerRef.current = null;
manager.remove(getModal(), ariaHiddenProp);
}, [ariaHiddenProp]);
React.useEffect(() => {
return () => {
handleClose();
};
}, [handleClose]);
React.useEffect(() => {
if (open) {
handleOpen();
} else if (!hasTransition || !closeAfterTransition) {
handleClose();
}
}, [open, handleClose, hasTransition, closeAfterTransition, handleOpen, container]);
const createHandleKeyDown = (otherHandlers: EventHandlers) => (event: React.KeyboardEvent) => {
otherHandlers.onKeyDown?.(event);
// The handler doesn't take event.defaultPrevented into account:
//
// event.preventDefault() is meant to stop default behaviors like
// clicking a checkbox to check it, hitting a button to submit a form,
// and hitting left arrow to move the cursor in a text input etc.
// Only special HTML elements have these default behaviors.
if (
event.key !== 'Escape' ||
event.which === 229 || // Wait until IME is settled.
!isTopModal()
) {
return;
}
// Swallow the event, in case someone is listening for the escape key on the body.
event.stopPropagation();
if (onClose) {
onClose(event, 'escapeKeyDown');
}
};
const createHandleBackdropClick = (otherHandlers: EventHandlers) => (event: React.MouseEvent) => {
otherHandlers.onClick?.(event);
if (event.target !== event.currentTarget) {
return;
}
if (onClose) {
onClose(event, 'backdropClick');
}
};
const getRootProps = <TOther extends EventHandlers = {}>(
otherHandlers: TOther = {} as TOther,
): UseModalRootSlotProps<TOther> => {
const propsEventHandlers = extractEventHandlers(parameters) as Partial<UseModalParameters>;
// The custom event handlers shouldn't be spread on the root element
delete propsEventHandlers.onTransitionEnter;
delete propsEventHandlers.onTransitionExited;
const externalEventHandlers = {
...propsEventHandlers,
...otherHandlers,
};
return {
/*
* Marking an element with the role presentation indicates to assistive technology
* that this element should be ignored; it exists to support the web application and
* is not meant for humans to interact with directly.
* https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md
*/
role: 'presentation',
...externalEventHandlers,
onKeyDown: createHandleKeyDown(externalEventHandlers),
ref: handleRef,
};
};
const getBackdropProps = <TOther extends EventHandlers = {}>(
otherHandlers: TOther = {} as TOther,
): UseModalBackdropSlotProps<TOther> => {
const externalEventHandlers = otherHandlers;
return {
'aria-hidden': true,
...externalEventHandlers,
onClick: createHandleBackdropClick(externalEventHandlers),
open,
};
};
const getTransitionProps = () => {
const handleEnter = () => {
setExited(false);
if (onTransitionEnter) {
onTransitionEnter();
}
};
const handleExited = () => {
setExited(true);
if (onTransitionExited) {
onTransitionExited();
}
if (closeAfterTransition) {
handleClose();
}
};
return {
onEnter: createChainedFunction(handleEnter, children?.props.onEnter ?? noop),
onExited: createChainedFunction(handleExited, children?.props.onExited ?? noop),
};
};
// Changing a portal's container remounts its children. Keep an exiting transition in its
// current container so it can finish and notify the modal that it is safe to unmount.
const portalContainer =
!open && hasTransition && !exited ? (lastMountNodeRef.current ?? container) : container;
return {
getRootProps,
getBackdropProps,
getTransitionProps,
rootRef: handleRef,
portalRef: handlePortalRef,
portalContainer,
isTopModal,
exited,
hasTransition,
};
}
export default useModal;