-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.tsx
328 lines (303 loc) · 8.76 KB
/
index.tsx
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/**
* External dependencies
*/
import classnames from 'classnames';
import type { ForwardedRef, KeyboardEvent, UIEvent } from 'react';
/**
* WordPress dependencies
*/
import {
createPortal,
useCallback,
useEffect,
useRef,
useState,
forwardRef,
useLayoutEffect,
} from '@wordpress/element';
import {
useInstanceId,
useFocusReturn,
useFocusOnMount,
__experimentalUseFocusOutside as useFocusOutside,
useConstrainedTabbing,
useMergeRefs,
} from '@wordpress/compose';
import { __ } from '@wordpress/i18n';
import { close } from '@wordpress/icons';
import { getScrollContainer } from '@wordpress/dom';
/**
* Internal dependencies
*/
import * as ariaHelper from './aria-helper';
import Button from '../button';
import StyleProvider from '../style-provider';
import type { ModalProps } from './types';
// Used to count the number of open modals.
let openModalCount = 0;
function UnforwardedModal(
props: ModalProps,
forwardedRef: ForwardedRef< HTMLDivElement >
) {
const {
bodyOpenClassName = 'modal-open',
role = 'dialog',
title = null,
focusOnMount = true,
shouldCloseOnEsc = true,
shouldCloseOnClickOutside = true,
isDismissible = true,
/* Accessibility. */
aria = {
labelledby: undefined,
describedby: undefined,
},
onRequestClose,
icon,
closeButtonLabel,
children,
style,
overlayClassName,
className,
contentLabel,
onKeyDown,
isFullScreen = false,
headerActions = null,
__experimentalHideHeader = false,
} = props;
const ref = useRef< HTMLDivElement >();
const instanceId = useInstanceId( Modal );
const headingId = title
? `components-modal-header-${ instanceId }`
: aria.labelledby;
const focusOnMountRef = useFocusOnMount( focusOnMount );
const constrainedTabbingRef = useConstrainedTabbing();
const focusReturnRef = useFocusReturn();
const focusOutsideProps = useFocusOutside( onRequestClose );
const contentRef = useRef< HTMLDivElement >( null );
const childrenContainerRef = useRef< HTMLDivElement >( null );
const [ hasScrolledContent, setHasScrolledContent ] = useState( false );
const [ hasScrollableContent, setHasScrollableContent ] = useState( false );
// Determines whether the Modal content is scrollable and updates the state.
const isContentScrollable = useCallback( () => {
if ( ! contentRef.current ) {
return;
}
const closestScrollContainer = getScrollContainer( contentRef.current );
if ( contentRef.current === closestScrollContainer ) {
setHasScrollableContent( true );
} else {
setHasScrollableContent( false );
}
}, [ contentRef ] );
useEffect( () => {
openModalCount++;
if ( openModalCount === 1 ) {
ariaHelper.hideApp( ref.current );
document.body.classList.add( bodyOpenClassName );
}
return () => {
openModalCount--;
if ( openModalCount === 0 ) {
document.body.classList.remove( bodyOpenClassName );
ariaHelper.showApp();
}
};
}, [ bodyOpenClassName ] );
// Calls the isContentScrollable callback when the Modal children container resizes.
useLayoutEffect( () => {
if ( ! window.ResizeObserver || ! childrenContainerRef.current ) {
return;
}
const resizeObserver = new ResizeObserver( isContentScrollable );
resizeObserver.observe( childrenContainerRef.current );
isContentScrollable();
return () => {
resizeObserver.disconnect();
};
}, [ isContentScrollable, childrenContainerRef ] );
function handleEscapeKeyDown( event: KeyboardEvent< HTMLDivElement > ) {
if (
// Ignore keydowns from IMEs
event.nativeEvent.isComposing ||
// Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229
) {
return;
}
if (
shouldCloseOnEsc &&
event.code === 'Escape' &&
! event.defaultPrevented
) {
event.preventDefault();
if ( onRequestClose ) {
onRequestClose( event );
}
}
}
const onContentContainerScroll = useCallback(
( e: UIEvent< HTMLDivElement > ) => {
const scrollY = e?.currentTarget?.scrollTop ?? -1;
if ( ! hasScrolledContent && scrollY > 0 ) {
setHasScrolledContent( true );
} else if ( hasScrolledContent && scrollY <= 0 ) {
setHasScrolledContent( false );
}
},
[ hasScrolledContent ]
);
let pressTarget: EventTarget | null = null;
const overlayPressHandlers: {
onPointerDown: React.PointerEventHandler< HTMLDivElement >;
onPointerUp: React.PointerEventHandler< HTMLDivElement >;
} = {
onPointerDown: ( event ) => {
if ( event.isPrimary && event.target === event.currentTarget ) {
pressTarget = event.target;
// Avoids loss of focus yet also leaves `useFocusOutside`
// practically useless with its only potential trigger being
// programmatic focus movement. TODO opt for either removing
// the hook or enhancing it such that this isn't needed.
event.preventDefault();
}
},
// Closes the modal with two exceptions. 1. Opening the context menu on
// the overlay. 2. Pressing on the overlay then dragging the pointer
// over the modal and releasing. Due to the modal being a child of the
// overlay, such a gesture is a `click` on the overlay and cannot be
// excepted by a `click` handler. Thus the tactic of handling
// `pointerup` and comparing its target to that of the `pointerdown`.
onPointerUp: ( { target, button } ) => {
const isSameTarget = target === pressTarget;
pressTarget = null;
if ( button === 0 && isSameTarget ) onRequestClose();
},
};
return createPortal(
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div
ref={ useMergeRefs( [ ref, forwardedRef ] ) }
className={ classnames(
'components-modal__screen-overlay',
overlayClassName
) }
onKeyDown={ handleEscapeKeyDown }
{ ...( shouldCloseOnClickOutside ? overlayPressHandlers : {} ) }
>
<StyleProvider document={ document }>
<div
className={ classnames(
'components-modal__frame',
className,
{
'is-full-screen': isFullScreen,
}
) }
style={ style }
ref={ useMergeRefs( [
constrainedTabbingRef,
focusReturnRef,
focusOnMountRef,
] ) }
role={ role }
aria-label={ contentLabel }
aria-labelledby={ contentLabel ? undefined : headingId }
aria-describedby={ aria.describedby }
tabIndex={ -1 }
{ ...( shouldCloseOnClickOutside
? focusOutsideProps
: {} ) }
onKeyDown={ onKeyDown }
>
<div
className={ classnames( 'components-modal__content', {
'hide-header': __experimentalHideHeader,
'is-scrollable': hasScrollableContent,
'has-scrolled-content': hasScrolledContent,
} ) }
role="document"
onScroll={ onContentContainerScroll }
ref={ contentRef }
aria-label={
hasScrollableContent
? __( 'Scrollable section' )
: undefined
}
tabIndex={ hasScrollableContent ? 0 : undefined }
>
{ ! __experimentalHideHeader && (
<div className="components-modal__header">
<div className="components-modal__header-heading-container">
{ icon && (
<span
className="components-modal__icon-container"
aria-hidden
>
{ icon }
</span>
) }
{ title && (
<h1
id={ headingId }
className="components-modal__header-heading"
>
{ title }
</h1>
) }
</div>
{ headerActions }
{ isDismissible && (
<Button
onClick={ onRequestClose }
icon={ close }
label={
closeButtonLabel || __( 'Close' )
}
/>
) }
</div>
) }
<div ref={ childrenContainerRef }>{ children }</div>
</div>
</div>
</StyleProvider>
</div>,
document.body
);
}
/**
* Modals give users information and choices related to a task they’re trying to
* accomplish. They can contain critical information, require decisions, or
* involve multiple tasks.
*
* ```jsx
* import { Button, Modal } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyModal = () => {
* const [ isOpen, setOpen ] = useState( false );
* const openModal = () => setOpen( true );
* const closeModal = () => setOpen( false );
*
* return (
* <>
* <Button variant="secondary" onClick={ openModal }>
* Open Modal
* </Button>
* { isOpen && (
* <Modal title="This is my modal" onRequestClose={ closeModal }>
* <Button variant="secondary" onClick={ closeModal }>
* My custom close button
* </Button>
* </Modal>
* ) }
* </>
* );
* };
* ```
*/
export const Modal = forwardRef( UnforwardedModal );
export default Modal;