-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
527 lines (477 loc) · 13.7 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
// @ts-nocheck
/**
* External dependencies
*/
import classnames from 'classnames';
import {
useFloating,
flip as flipMiddleware,
shift,
autoUpdate,
arrow,
offset as offsetMiddleware,
limitShift,
size,
} from '@floating-ui/react-dom';
// eslint-disable-next-line no-restricted-imports
import { motion, useReducedMotion } from 'framer-motion';
/**
* WordPress dependencies
*/
import {
useRef,
useLayoutEffect,
forwardRef,
createContext,
useContext,
useMemo,
useEffect,
} from '@wordpress/element';
import {
useViewportMatch,
useMergeRefs,
__experimentalUseDialog as useDialog,
} from '@wordpress/compose';
import { close } from '@wordpress/icons';
import deprecated from '@wordpress/deprecated';
import { Path, SVG } from '@wordpress/primitives';
/**
* Internal dependencies
*/
import Button from '../button';
import ScrollLock from '../scroll-lock';
import { Slot, Fill, useSlot } from '../slot-fill';
import {
getFrameOffset,
positionToPlacement,
placementToMotionAnimationProps,
} from './utils';
/**
* Name of slot in which popover should fill.
*
* @type {string}
*/
const SLOT_NAME = 'Popover';
// An SVG displaying a triangle facing down, filled with a solid
// color and bordered in such a way to create an arrow-like effect.
// Keeping the SVG's viewbox squared simplify the arrow positioning
// calculations.
const ArrowTriangle = ( props ) => (
<SVG
{ ...props }
xmlns="http://www.w3.org/2000/svg"
viewBox={ `0 0 100 100` }
className="components-popover__triangle"
role="presentation"
>
<Path
className="components-popover__triangle-bg"
d="M 0 0 L 50 50 L 100 0"
/>
<Path
className="components-popover__triangle-border"
d="M 0 0 L 50 50 L 100 0"
vectorEffect="non-scaling-stroke"
/>
</SVG>
);
const MaybeAnimatedWrapper = forwardRef(
(
{
style: receivedInlineStyles,
placement,
shouldAnimate = false,
...props
},
forwardedRef
) => {
const shouldReduceMotion = useReducedMotion();
const { style: motionInlineStyles, ...otherMotionProps } = useMemo(
() => placementToMotionAnimationProps( placement ),
[ placement ]
);
if ( shouldAnimate && ! shouldReduceMotion ) {
return (
<motion.div
style={ {
...motionInlineStyles,
...receivedInlineStyles,
} }
{ ...otherMotionProps }
{ ...props }
ref={ forwardedRef }
/>
);
}
return (
<div
style={ receivedInlineStyles }
{ ...props }
ref={ forwardedRef }
/>
);
}
);
const slotNameContext = createContext();
const Popover = (
{
range,
animate = true,
headerTitle,
onClose,
children,
className,
noArrow = true,
isAlternate,
position,
placement: placementProp = 'bottom-start',
offset: offsetProp = 0,
focusOnMount = 'firstElement',
anchorRef,
anchorRect,
getAnchorRect,
expandOnMobile,
onFocusOutside,
__unstableSlotName = SLOT_NAME,
flip = true,
resize = true,
__unstableShift = false,
__unstableForcePosition,
...contentProps
},
forwardedRef
) => {
if ( range ) {
deprecated( 'range prop in Popover component', {
since: '6.1',
version: '6.3',
} );
}
if ( __unstableForcePosition !== undefined ) {
deprecated( '__unstableForcePosition prop in Popover component', {
since: '6.1',
version: '6.3',
alternative: '`flip={ false }` and `resize={ false }`',
} );
// Back-compat, set the `flip` and `resize` props
// to `false` to replicate `__unstableForcePosition`.
flip = ! __unstableForcePosition;
resize = ! __unstableForcePosition;
}
const arrowRef = useRef( null );
const anchorRefFallback = useRef( null );
const isMobileViewport = useViewportMatch( 'medium', '<' );
const isExpanded = expandOnMobile && isMobileViewport;
const hasArrow = ! isExpanded && ! noArrow;
const normalizedPlacementFromProps = position
? positionToPlacement( position )
: placementProp;
const referenceOwnerDocument = useMemo( () => {
let documentToReturn;
if ( anchorRef?.top ) {
documentToReturn = anchorRef?.top.ownerDocument;
} else if ( anchorRef?.startContainer ) {
documentToReturn = anchorRef.startContainer.ownerDocument;
} else if ( anchorRef?.current ) {
documentToReturn = anchorRef.current.ownerDocument;
} else if ( anchorRef ) {
// This one should be deprecated.
documentToReturn = anchorRef.ownerDocument;
} else if ( anchorRect && anchorRect?.ownerDocument ) {
documentToReturn = anchorRect.ownerDocument;
} else if ( getAnchorRect ) {
documentToReturn = getAnchorRect(
anchorRefFallback.current
)?.ownerDocument;
}
return documentToReturn ?? document;
}, [ anchorRef, anchorRect, getAnchorRect ] );
/**
* Offsets the position of the popover when the anchor is inside an iframe.
*
* Store the offset in a ref, due to constraints with floating-ui:
* https://floating-ui.com/docs/react-dom#variables-inside-middleware-functions.
*/
const frameOffsetRef = useRef( getFrameOffset( referenceOwnerDocument ) );
/**
* Store the offset prop in a ref, due to constraints with floating-ui:
* https://floating-ui.com/docs/react-dom#variables-inside-middleware-functions.
*/
const offsetRef = useRef( offsetProp );
const middleware = [
offsetMiddleware( ( { placement: currentPlacement } ) => {
if ( ! frameOffsetRef.current ) {
return offsetRef.current;
}
const isTopBottomPlacement =
currentPlacement.includes( 'top' ) ||
currentPlacement.includes( 'bottom' );
// The main axis should represent the gap between the
// floating element and the reference element. The cross
// axis is always perpendicular to the main axis.
const mainAxis = isTopBottomPlacement ? 'y' : 'x';
const crossAxis = mainAxis === 'x' ? 'y' : 'x';
// When the popover is before the reference, subtract the offset,
// of the main axis else add it.
const hasBeforePlacement =
currentPlacement.includes( 'top' ) ||
currentPlacement.includes( 'left' );
const mainAxisModifier = hasBeforePlacement ? -1 : 1;
return {
mainAxis:
offsetRef.current +
frameOffsetRef.current[ mainAxis ] * mainAxisModifier,
crossAxis: frameOffsetRef.current[ crossAxis ],
};
} ),
flip ? flipMiddleware() : undefined,
resize
? size( {
apply( sizeProps ) {
const { availableHeight } = sizeProps;
if ( ! refs.floating.current ) return;
// Reduce the height of the popover to the available space.
Object.assign( refs.floating.current.firstChild.style, {
maxHeight: `${ availableHeight }px`,
overflow: 'auto',
} );
},
} )
: undefined,
__unstableShift
? shift( {
crossAxis: true,
limiter: limitShift(),
padding: 1, // Necessary to avoid flickering at the edge of the viewport.
} )
: undefined,
hasArrow ? arrow( { element: arrowRef } ) : undefined,
].filter( ( m ) => !! m );
const slotName = useContext( slotNameContext ) || __unstableSlotName;
const slot = useSlot( slotName );
let onDialogClose;
if ( onClose || onFocusOutside ) {
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 {
// Positioning coordinates
x,
y,
// Callback refs (not regular refs). This allows the position to be updated.
// when either elements change.
reference,
floating,
// Object with "regular" refs to both "reference" and "floating"
refs,
// Type of CSS position property to use (absolute or fixed)
strategy,
update,
placement: computedPlacement,
middlewareData: { arrow: arrowData = {} },
} = useFloating( { placement: normalizedPlacementFromProps, middleware } );
useEffect( () => {
offsetRef.current = offsetProp;
update();
}, [ offsetProp, update ] );
// Update the `reference`'s ref.
//
// In floating-ui's terms:
// - "reference" refers to the popover's anchor element.
// - "floating" refers the floating popover's element.
// A floating element can also be positioned relative to a virtual element,
// instead of a real one. A virtual element is represented by an object
// with the `getBoundingClientRect()` function (like real elements).
// See https://floating-ui.com/docs/virtual-elements for more info.
useLayoutEffect( () => {
let resultingReferenceRef;
if ( anchorRef?.top ) {
// Create a virtual element for the ref. The expectation is that
// if anchorRef.top is defined, then anchorRef.bottom is defined too.
resultingReferenceRef = {
getBoundingClientRect() {
const topRect = anchorRef.top.getBoundingClientRect();
const bottomRect = anchorRef.bottom.getBoundingClientRect();
return new window.DOMRect(
topRect.x,
topRect.y,
topRect.width,
bottomRect.bottom - topRect.top
);
},
};
} else if ( anchorRef?.current ) {
// Standard React ref.
resultingReferenceRef = anchorRef.current;
} else if ( anchorRef ) {
// If `anchorRef` holds directly the element's value (no `current` key)
// This is a weird scenario and should be deprecated.
resultingReferenceRef = anchorRef;
} else if ( anchorRect ) {
// Create a virtual element for the ref.
resultingReferenceRef = {
getBoundingClientRect() {
return anchorRect;
},
};
} else if ( getAnchorRect ) {
// Create a virtual element for the ref.
resultingReferenceRef = {
getBoundingClientRect() {
const rect = getAnchorRect( anchorRefFallback.current );
return new window.DOMRect(
rect.x ?? rect.left,
rect.y ?? rect.top,
rect.width ?? rect.right - rect.left,
rect.height ?? rect.bottom - rect.top
);
},
};
} else if ( anchorRefFallback.current ) {
// If no explicit ref is passed via props, fall back to
// anchoring to the popover's parent node.
resultingReferenceRef = anchorRefFallback.current.parentNode;
}
if ( ! resultingReferenceRef ) {
return;
}
reference( resultingReferenceRef );
if ( ! refs.floating.current ) {
return;
}
return autoUpdate(
resultingReferenceRef,
refs.floating.current,
update,
{
animationFrame: true,
}
);
// 'reference' and 'refs.floating' are refs and don't need to be listed
// as dependencies (see https://github.com/WordPress/gutenberg/pull/41612)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ anchorRef, anchorRect, getAnchorRect, update ] );
// If the reference element is in a different ownerDocument (e.g. iFrame),
// we need to manually update the floating's position as the reference's owner
// document scrolls. Also update the frame offset if the view resizes.
useLayoutEffect( () => {
const referenceAndFloatingHaveSameDocument =
referenceOwnerDocument === document;
const hasFrameElement =
!! referenceOwnerDocument?.defaultView?.frameElement;
if ( referenceAndFloatingHaveSameDocument || ! hasFrameElement ) {
frameOffsetRef.current = undefined;
return;
}
const { defaultView } = referenceOwnerDocument;
const updateFrameOffset = () => {
frameOffsetRef.current = getFrameOffset( referenceOwnerDocument );
update();
};
defaultView.addEventListener( 'resize', updateFrameOffset );
updateFrameOffset();
return () => {
defaultView.removeEventListener( 'resize', updateFrameOffset );
};
}, [ referenceOwnerDocument, update ] );
const mergedFloatingRef = useMergeRefs( [
floating,
dialogRef,
forwardedRef,
] );
// 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
<MaybeAnimatedWrapper
shouldAnimate={ animate && ! isExpanded }
placement={ computedPlacement }
className={ classnames( 'components-popover', className, {
'is-expanded': isExpanded,
'is-alternate': isAlternate,
} ) }
{ ...contentProps }
ref={ mergedFloatingRef }
{ ...dialogProps }
tabIndex="-1"
style={
isExpanded
? undefined
: {
position: strategy,
left: Number.isNaN( x ) ? 0 : x,
top: Number.isNaN( y ) ? 0 : y,
}
}
>
{ /* Prevents scroll on the document */ }
{ 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 className="components-popover__content">{ children }</div>
{ hasArrow && (
<div
ref={ arrowRef }
className={ [
'components-popover__arrow',
`is-${ computedPlacement.split( '-' )[ 0 ] }`,
].join( ' ' ) }
style={ {
left: Number.isFinite( arrowData?.x )
? `${ arrowData.x }px`
: '',
top: Number.isFinite( arrowData?.y )
? `${ arrowData.y }px`
: '',
} }
>
<ArrowTriangle />
</div>
) }
</MaybeAnimatedWrapper>
);
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;