-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
588 lines (517 loc) · 14.6 KB
/
index.js
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
// @ts-nocheck
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import {
useRef,
useState,
useLayoutEffect,
forwardRef,
createContext,
useContext,
} from '@wordpress/element';
import { getRectangleFromRange } from '@wordpress/dom';
import {
useViewportMatch,
useResizeObserver,
useMergeRefs,
__experimentalUseDialog as useDialog,
} from '@wordpress/compose';
import { close } from '@wordpress/icons';
/**
* Internal dependencies
*/
import { computePopoverPosition, offsetIframe } from './utils';
import Button from '../button';
import ScrollLock from '../scroll-lock';
import { Slot, Fill, useSlot } from '../slot-fill';
import { getAnimateClassName } from '../animate';
/**
* Name of slot in which popover should fill.
*
* @type {string}
*/
const SLOT_NAME = 'Popover';
const slotNameContext = createContext();
function computeAnchorRect(
anchorRefFallback,
anchorRect,
getAnchorRect,
anchorRef = false,
shouldAnchorIncludePadding,
container
) {
if ( anchorRect ) {
return anchorRect;
}
if ( getAnchorRect ) {
if ( ! anchorRefFallback.current ) {
return;
}
const rect = getAnchorRect( anchorRefFallback.current );
return offsetIframe(
rect,
rect.ownerDocument || anchorRefFallback.current.ownerDocument,
container
);
}
if ( anchorRef !== false ) {
if (
! anchorRef ||
! window.Range ||
! window.Element ||
! window.DOMRect
) {
return;
}
// Duck-type to check if `anchorRef` is an instance of Range
// `anchorRef instanceof window.Range` checks will break across document boundaries
// such as in an iframe
if ( typeof anchorRef?.cloneRange === 'function' ) {
return offsetIframe(
getRectangleFromRange( anchorRef ),
anchorRef.endContainer.ownerDocument,
container
);
}
// Duck-type to check if `anchorRef` is an instance of Element
// `anchorRef instanceof window.Element` checks will break across document boundaries
// such as in an iframe
if ( typeof anchorRef?.getBoundingClientRect === 'function' ) {
const rect = offsetIframe(
anchorRef.getBoundingClientRect(),
anchorRef.ownerDocument,
container
);
if ( shouldAnchorIncludePadding ) {
return rect;
}
return withoutPadding( rect, anchorRef );
}
const { top, bottom } = anchorRef;
const topRect = top.getBoundingClientRect();
const bottomRect = bottom.getBoundingClientRect();
const rect = offsetIframe(
new window.DOMRect(
topRect.left,
topRect.top,
topRect.width,
bottomRect.bottom - topRect.top
),
top.ownerDocument,
container
);
if ( shouldAnchorIncludePadding ) {
return rect;
}
return withoutPadding( rect, anchorRef );
}
if ( ! anchorRefFallback.current ) {
return;
}
const { parentNode } = anchorRefFallback.current;
const rect = offsetIframe(
parentNode.getBoundingClientRect(),
parentNode.ownerDocument,
container
);
if ( shouldAnchorIncludePadding ) {
return rect;
}
return withoutPadding( rect, parentNode );
}
function getComputedStyle( node ) {
return node.ownerDocument.defaultView.getComputedStyle( node );
}
function withoutPadding( rect, element ) {
const {
paddingTop,
paddingBottom,
paddingLeft,
paddingRight,
} = getComputedStyle( element );
const top = paddingTop ? parseInt( paddingTop, 10 ) : 0;
const bottom = paddingBottom ? parseInt( paddingBottom, 10 ) : 0;
const left = paddingLeft ? parseInt( paddingLeft, 10 ) : 0;
const right = paddingRight ? parseInt( paddingRight, 10 ) : 0;
return {
x: rect.left + left,
y: rect.top + top,
width: rect.width - left - right,
height: rect.height - top - bottom,
left: rect.left + left,
right: rect.right - right,
top: rect.top + top,
bottom: rect.bottom - bottom,
};
}
/**
* Sets or removes an element attribute.
*
* @param {Element} element The element to modify.
* @param {string} name The attribute name to set or remove.
* @param {?string} value The value to set. A falsy value will remove the
* attribute.
*/
function setAttribute( element, name, value ) {
if ( ! value ) {
if ( element.hasAttribute( name ) ) {
element.removeAttribute( name );
}
} else if ( element.getAttribute( name ) !== value ) {
element.setAttribute( name, value );
}
}
/**
* Sets or removes an element style property.
*
* @param {Element} element The element to modify.
* @param {string} property The property to set or remove.
* @param {?string} value The value to set. A falsy value will remove the
* property.
*/
function setStyle( element, property, value = '' ) {
if ( element.style[ property ] !== value ) {
element.style[ property ] = value;
}
}
/**
* Sets or removes an element class.
*
* @param {Element} element The element to modify.
* @param {string} name The class to set or remove.
* @param {boolean} toggle True to set the class, false to remove.
*/
function setClass( element, name, toggle ) {
if ( toggle ) {
if ( ! element.classList.contains( name ) ) {
element.classList.add( name );
}
} else if ( element.classList.contains( name ) ) {
element.classList.remove( name );
}
}
function getAnchorDocument( anchor ) {
if ( ! anchor ) {
return;
}
if ( anchor.endContainer ) {
return anchor.endContainer.ownerDocument;
}
if ( anchor.top ) {
return anchor.top.ownerDocument;
}
return anchor.ownerDocument;
}
const Popover = (
{
headerTitle,
onClose,
children,
className,
noArrow = true,
isAlternate,
// Disable reason: We generate the `...contentProps` rest as remainder
// of props which aren't explicitly handled by this component.
/* eslint-disable no-unused-vars */
position = 'bottom right',
range,
focusOnMount = 'firstElement',
anchorRef,
shouldAnchorIncludePadding,
anchorRect,
getAnchorRect,
expandOnMobile,
animate = true,
onFocusOutside,
__unstableStickyBoundaryElement,
__unstableSlotName = SLOT_NAME,
__unstableObserveElement,
__unstableBoundaryParent,
__unstableForcePosition,
__unstableForceXAlignment,
__unstableEditorCanvasWrapper,
/* eslint-enable no-unused-vars */
...contentProps
},
ref
) => {
const anchorRefFallback = useRef( null );
const contentRef = useRef( null );
const containerRef = useRef();
const isMobileViewport = useViewportMatch( 'medium', '<' );
const [ animateOrigin, setAnimateOrigin ] = useState();
const slotName = useContext( slotNameContext ) || __unstableSlotName;
const slot = useSlot( slotName );
const isExpanded = expandOnMobile && isMobileViewport;
const [ containerResizeListener, contentSize ] = useResizeObserver();
noArrow = isExpanded || noArrow;
useLayoutEffect( () => {
if ( isExpanded ) {
setClass( containerRef.current, 'is-without-arrow', noArrow );
setClass( containerRef.current, 'is-alternate', isAlternate );
setAttribute( containerRef.current, 'data-x-axis' );
setAttribute( containerRef.current, 'data-y-axis' );
setStyle( containerRef.current, 'top' );
setStyle( containerRef.current, 'left' );
setStyle( contentRef.current, 'maxHeight' );
setStyle( contentRef.current, 'maxWidth' );
return;
}
const refresh = () => {
if ( ! containerRef.current || ! contentRef.current ) {
return;
}
let anchor = computeAnchorRect(
anchorRefFallback,
anchorRect,
getAnchorRect,
anchorRef,
shouldAnchorIncludePadding,
containerRef.current
);
if ( ! anchor ) {
return;
}
const { offsetParent, ownerDocument } = containerRef.current;
let relativeOffsetTop = 0;
// If there is a positioned ancestor element that is not the body,
// subtract the position from the anchor rect. If the position of
// the popover is fixed, the offset parent is null or the body
// element, in which case the position is relative to the viewport.
// See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
if ( offsetParent && offsetParent !== ownerDocument.body ) {
const offsetParentRect = offsetParent.getBoundingClientRect();
relativeOffsetTop = offsetParentRect.top;
anchor = new window.DOMRect(
anchor.left - offsetParentRect.left,
anchor.top - offsetParentRect.top,
anchor.width,
anchor.height
);
}
let boundaryElement;
if ( __unstableBoundaryParent ) {
boundaryElement = containerRef.current.parentElement;
}
const usedContentSize = ! contentSize.height
? contentRef.current.getBoundingClientRect()
: contentSize;
const {
popoverTop,
popoverLeft,
xAxis,
yAxis,
contentHeight,
contentWidth,
} = computePopoverPosition(
anchor,
usedContentSize,
position,
__unstableStickyBoundaryElement,
containerRef.current,
relativeOffsetTop,
boundaryElement,
__unstableForcePosition,
__unstableForceXAlignment,
__unstableEditorCanvasWrapper
);
if (
typeof popoverTop === 'number' &&
typeof popoverLeft === 'number'
) {
setStyle( containerRef.current, 'top', popoverTop + 'px' );
setStyle( containerRef.current, 'left', popoverLeft + 'px' );
}
setClass(
containerRef.current,
'is-without-arrow',
noArrow || ( xAxis === 'center' && yAxis === 'middle' )
);
setClass( containerRef.current, 'is-alternate', isAlternate );
setAttribute( containerRef.current, 'data-x-axis', xAxis );
setAttribute( containerRef.current, 'data-y-axis', yAxis );
setStyle(
contentRef.current,
'maxHeight',
typeof contentHeight === 'number' ? contentHeight + 'px' : ''
);
setStyle(
contentRef.current,
'maxWidth',
typeof contentWidth === 'number' ? contentWidth + 'px' : ''
);
// Compute the animation position
const yAxisMapping = {
top: 'bottom',
bottom: 'top',
};
const xAxisMapping = {
left: 'right',
right: 'left',
};
const animateYAxis = yAxisMapping[ yAxis ] || 'middle';
const animateXAxis = xAxisMapping[ xAxis ] || 'center';
setAnimateOrigin( animateXAxis + ' ' + animateYAxis );
};
refresh();
const { ownerDocument } = containerRef.current;
const { defaultView } = ownerDocument;
/*
* There are sometimes we need to reposition or resize the popover that
* are not handled by the resize/scroll window events (i.e. CSS changes
* in the layout that changes the position of the anchor).
*
* For these situations, we refresh the popover every 0.5s
*/
const intervalHandle = defaultView.setInterval( refresh, 500 );
let rafId;
const refreshOnAnimationFrame = () => {
defaultView.cancelAnimationFrame( rafId );
rafId = defaultView.requestAnimationFrame( refresh );
};
// Sometimes a click trigger a layout change that affects the popover
// position. This is an opportunity to immediately refresh rather than
// at the interval.
defaultView.addEventListener( 'click', refreshOnAnimationFrame );
defaultView.addEventListener( 'resize', refresh );
defaultView.addEventListener( 'scroll', refresh, true );
const anchorDocument = getAnchorDocument( anchorRef );
// If the anchor is within an iframe, the popover position also needs
// to refrest when the iframe content is scrolled or resized.
if ( anchorDocument && anchorDocument !== ownerDocument ) {
anchorDocument.defaultView.addEventListener( 'resize', refresh );
anchorDocument.defaultView.addEventListener(
'scroll',
refresh,
true
);
}
let observer;
if ( __unstableObserveElement ) {
observer = new defaultView.MutationObserver( refresh );
observer.observe( __unstableObserveElement, { attributes: true } );
}
return () => {
defaultView.clearInterval( intervalHandle );
defaultView.removeEventListener( 'resize', refresh );
defaultView.removeEventListener( 'scroll', refresh, true );
defaultView.removeEventListener( 'click', refreshOnAnimationFrame );
defaultView.cancelAnimationFrame( rafId );
if ( anchorDocument && anchorDocument !== ownerDocument ) {
anchorDocument.defaultView?.removeEventListener(
'resize',
refresh
);
anchorDocument.defaultView?.removeEventListener(
'scroll',
refresh,
true
);
}
if ( observer ) {
observer.disconnect();
}
};
}, [
isExpanded,
anchorRect,
getAnchorRect,
anchorRef,
shouldAnchorIncludePadding,
position,
contentSize,
__unstableStickyBoundaryElement,
__unstableObserveElement,
__unstableBoundaryParent,
] );
const onDialogClose = ( type, event ) => {
// Ideally the popover should have just a single onClose prop and
// not three props that potentially do the same thing.
if ( type === 'focus-outside' && onFocusOutside ) {
onFocusOutside( event );
} else if ( onClose ) {
onClose();
}
};
const [ dialogRef, dialogProps ] = useDialog( {
focusOnMount,
__unstableOnClose: onDialogClose,
onClose: onDialogClose,
} );
const mergedRefs = useMergeRefs( [ containerRef, dialogRef, ref ] );
/** @type {false | string} */
const animateClassName =
Boolean( animate && animateOrigin ) &&
getAnimateClassName( {
type: 'appear',
origin: animateOrigin,
} );
// Disable reason: We care to capture the _bubbled_ events from inputs
// within popover as inferring close intent.
let content = (
// eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div
className={ classnames(
'components-popover',
className,
animateClassName,
{
'is-expanded': isExpanded,
'is-without-arrow': noArrow,
'is-alternate': isAlternate,
}
) }
{ ...contentProps }
ref={ mergedRefs }
{ ...dialogProps }
tabIndex="-1"
>
{ isExpanded && <ScrollLock /> }
{ isExpanded && (
<div className="components-popover__header">
<span className="components-popover__header-title">
{ headerTitle }
</span>
<Button
className="components-popover__close"
icon={ close }
onClick={ onClose }
/>
</div>
) }
<div ref={ contentRef } className="components-popover__content">
<div style={ { position: 'relative' } }>
{ containerResizeListener }
{ children }
</div>
</div>
</div>
);
if ( slot.ref ) {
content = <Fill name={ slotName }>{ content }</Fill>;
}
if ( anchorRef || anchorRect ) {
return content;
}
return <span ref={ anchorRefFallback }>{ content }</span>;
};
const PopoverContainer = forwardRef( Popover );
function PopoverSlot( { name = SLOT_NAME }, ref ) {
return (
<Slot
bubblesVirtually
name={ name }
className="popover-slot"
ref={ ref }
/>
);
}
PopoverContainer.Slot = forwardRef( PopoverSlot );
PopoverContainer.__unstableSlotNameProvider = slotNameContext.Provider;
export default PopoverContainer;