-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.tsx
571 lines (515 loc) · 14.5 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
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
/**
* External dependencies
*/
import type { ForwardedRef, SyntheticEvent, RefCallback } from 'react';
import classnames from 'classnames';
import {
useFloating,
flip as flipMiddleware,
shift as shiftMiddleware,
limitShift,
autoUpdate,
arrow,
offset as offsetMiddleware,
size,
} from '@floating-ui/react-dom';
// eslint-disable-next-line no-restricted-imports
import type { HTMLMotionProps, MotionProps } from 'framer-motion';
// eslint-disable-next-line no-restricted-imports
import { motion, useReducedMotion } from 'framer-motion';
/**
* WordPress dependencies
*/
import {
useRef,
useLayoutEffect,
forwardRef,
createContext,
useContext,
useMemo,
useState,
useCallback,
createPortal,
} 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';
import { getScrollContainer } from '@wordpress/dom';
/**
* Internal dependencies
*/
import Button from '../button';
import ScrollLock from '../scroll-lock';
import { Slot, Fill, useSlot } from '../slot-fill';
import {
computePopoverPosition,
positionToPlacement,
placementToMotionAnimationProps,
getReferenceOwnerDocument,
getReferenceElement,
} from './utils';
import type { WordPressComponentProps } from '../ui/context';
import type {
PopoverProps,
AnimatedWrapperProps,
PopoverAnchorRefReference,
PopoverAnchorRefTopBottom,
} from './types';
import { overlayMiddlewares } from './overlay-middlewares';
/**
* Name of slot in which popover should fill.
*
* @type {string}
*/
export 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 = () => (
<SVG
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 AnimatedWrapper = forwardRef(
(
{
style: receivedInlineStyles,
placement,
shouldAnimate = false,
...props
}: HTMLMotionProps< 'div' > & AnimatedWrapperProps,
forwardedRef: ForwardedRef< any >
) => {
const shouldReduceMotion = useReducedMotion();
const { style: motionInlineStyles, ...otherMotionProps } = useMemo(
() => placementToMotionAnimationProps( placement ),
[ placement ]
);
const computedAnimationProps: HTMLMotionProps< 'div' > =
shouldAnimate && ! shouldReduceMotion
? {
style: {
...motionInlineStyles,
...receivedInlineStyles,
},
...otherMotionProps,
}
: {
animate: false,
style: receivedInlineStyles,
};
return (
<motion.div
{ ...computedAnimationProps }
{ ...props }
ref={ forwardedRef }
/>
);
}
);
const slotNameContext = createContext< string | undefined >( undefined );
const fallbackContainerClassname = 'components-popover__fallback-container';
const getPopoverFallbackContainer = () => {
let container = document.body.querySelector(
'.' + fallbackContainerClassname
);
if ( ! container ) {
container = document.createElement( 'div' );
container.className = fallbackContainerClassname;
document.body.append( container );
}
return container;
};
const UnforwardedPopover = (
props: Omit<
WordPressComponentProps< PopoverProps, 'div', false >,
// To avoid overlaps between the standard HTML attributes and the props
// expected by `framer-motion`, omit all framer motion props from popover
// props (except for `animate` and `children`, which are re-defined in `PopoverProps`).
keyof Omit< MotionProps, 'animate' | 'children' >
>,
forwardedRef: ForwardedRef< any >
) => {
const {
animate = true,
headerTitle,
onClose,
children,
className,
noArrow = true,
position,
placement: placementProp = 'bottom-start',
offset: offsetProp = 0,
focusOnMount = 'firstElement',
anchor,
expandOnMobile,
onFocusOutside,
__unstableSlotName = SLOT_NAME,
flip = true,
resize = true,
shift = false,
inline = false,
variant,
// Deprecated props
__unstableForcePosition,
anchorRef,
anchorRect,
getAnchorRect,
isAlternate,
// Rest
...contentProps
} = props;
let computedFlipProp = flip;
let computedResizeProp = resize;
if ( __unstableForcePosition !== undefined ) {
deprecated( '`__unstableForcePosition` prop in wp.components.Popover', {
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`.
computedFlipProp = ! __unstableForcePosition;
computedResizeProp = ! __unstableForcePosition;
}
if ( anchorRef !== undefined ) {
deprecated( '`anchorRef` prop in wp.components.Popover', {
since: '6.1',
alternative: '`anchor` prop',
} );
}
if ( anchorRect !== undefined ) {
deprecated( '`anchorRect` prop in wp.components.Popover', {
since: '6.1',
alternative: '`anchor` prop',
} );
}
if ( getAnchorRect !== undefined ) {
deprecated( '`getAnchorRect` prop in wp.components.Popover', {
since: '6.1',
alternative: '`anchor` prop',
} );
}
const computedVariant = isAlternate ? 'toolbar' : variant;
if ( isAlternate !== undefined ) {
deprecated( '`isAlternate` prop in wp.components.Popover', {
since: '6.2',
alternative: "`variant` prop with the `'toolbar'` value",
} );
}
const arrowRef = useRef< HTMLElement | null >( null );
const [ fallbackReferenceElement, setFallbackReferenceElement ] =
useState< HTMLSpanElement | null >( null );
const [ referenceOwnerDocument, setReferenceOwnerDocument ] = useState<
Document | undefined
>();
const anchorRefFallback: RefCallback< HTMLSpanElement > = useCallback(
( node ) => {
setFallbackReferenceElement( node );
},
[]
);
const isMobileViewport = useViewportMatch( 'medium', '<' );
const isExpanded = expandOnMobile && isMobileViewport;
const hasArrow = ! isExpanded && ! noArrow;
const normalizedPlacementFromProps = position
? positionToPlacement( position )
: placementProp;
const middleware = [
...( placementProp === 'overlay' ? overlayMiddlewares() : [] ),
offsetMiddleware( offsetProp ),
computedFlipProp && flipMiddleware(),
computedResizeProp &&
size( {
apply( sizeProps ) {
const { firstElementChild } = refs.floating.current ?? {};
// Only HTMLElement instances have the `style` property.
if ( ! ( firstElementChild instanceof HTMLElement ) )
return;
// Reduce the height of the popover to the available space.
Object.assign( firstElementChild.style, {
maxHeight: `${ sizeProps.availableHeight }px`,
overflow: 'auto',
} );
},
} ),
shift &&
shiftMiddleware( {
crossAxis: true,
limiter: limitShift(),
padding: 1, // Necessary to avoid flickering at the edge of the viewport.
} ),
arrow( { element: arrowRef } ),
];
const slotName = useContext( slotNameContext ) || __unstableSlotName;
const slot = useSlot( slotName );
let onDialogClose;
if ( onClose || onFocusOutside ) {
onDialogClose = ( type: string | undefined, event: SyntheticEvent ) => {
// 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,
// @ts-expect-error The __unstableOnClose property needs to be deprecated first (see https://github.com/WordPress/gutenberg/pull/27675)
onClose: onDialogClose,
} );
const {
// Positioning coordinates
x,
y,
// 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 === 'overlay'
? undefined
: normalizedPlacementFromProps,
middleware,
whileElementsMounted: ( referenceParam, floatingParam, updateParam ) =>
autoUpdate( referenceParam, floatingParam, updateParam, {
animationFrame: true,
} ),
} );
const arrowCallbackRef = useCallback(
( node: HTMLElement | null ) => {
arrowRef.current = node;
update();
},
[ update ]
);
// When any of the possible anchor "sources" change,
// recompute the reference element (real or virtual) and its owner document.
const anchorRefTop = ( anchorRef as PopoverAnchorRefTopBottom | undefined )
?.top;
const anchorRefBottom = (
anchorRef as PopoverAnchorRefTopBottom | undefined
)?.bottom;
const anchorRefStartContainer = ( anchorRef as Range | undefined )
?.startContainer;
const anchorRefCurrent = ( anchorRef as PopoverAnchorRefReference )
?.current;
useLayoutEffect( () => {
const resultingReferenceOwnerDoc = getReferenceOwnerDocument( {
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
fallbackDocument: document,
} );
const resultingReferenceElement = getReferenceElement( {
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
} );
refs.setReference( resultingReferenceElement );
setReferenceOwnerDocument( resultingReferenceOwnerDoc );
}, [
anchor,
anchorRef,
anchorRefTop,
anchorRefBottom,
anchorRefStartContainer,
anchorRefCurrent,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
refs,
] );
// 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.
useLayoutEffect( () => {
if (
! referenceOwnerDocument ||
! referenceOwnerDocument.defaultView
) {
return;
}
const { defaultView } = referenceOwnerDocument;
const { frameElement } = defaultView;
const scrollContainer = frameElement
? getScrollContainer( frameElement )
: null;
defaultView.addEventListener( 'resize', update );
scrollContainer?.addEventListener( 'scroll', update );
update();
return () => {
defaultView.removeEventListener( 'resize', update );
scrollContainer?.removeEventListener( 'scroll', update );
};
}, [ referenceOwnerDocument, update ] );
const mergedFloatingRef = useMergeRefs( [
refs.setFloating,
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
<AnimatedWrapper
shouldAnimate={ animate && ! isExpanded }
placement={ computedPlacement }
className={ classnames( 'components-popover', className, {
'is-expanded': isExpanded,
'is-positioned': x !== null && y !== null,
// Use the 'alternate' classname for 'toolbar' variant for back compat.
[ `is-${
computedVariant === 'toolbar'
? 'alternate'
: computedVariant
}` ]: computedVariant,
} ) }
{ ...contentProps }
ref={ mergedFloatingRef }
{ ...dialogProps }
tabIndex={ -1 }
style={
isExpanded
? undefined
: {
position: strategy,
top: 0,
left: 0,
// `x` and `y` are framer-motion specific props and are shorthands
// for `translateX` and `translateY`. Currently it is not possible
// to use `translateX` and `translateY` because those values would
// be overridden by the return value of the
// `placementToMotionAnimationProps` function in `AnimatedWrapper`
x: computePopoverPosition( x ),
y: computePopoverPosition( 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={ arrowCallbackRef }
className={ [
'components-popover__arrow',
`is-${ computedPlacement.split( '-' )[ 0 ] }`,
].join( ' ' ) }
style={ {
left:
typeof arrowData?.x !== 'undefined' &&
Number.isFinite( arrowData.x )
? `${ arrowData.x }px`
: '',
top:
typeof arrowData?.y !== 'undefined' &&
Number.isFinite( arrowData.y )
? `${ arrowData.y }px`
: '',
} }
>
<ArrowTriangle />
</div>
) }
</AnimatedWrapper>
);
const shouldRenderWithinSlot = slot.ref && ! inline;
const hasAnchor = anchorRef || anchorRect || anchor;
if ( shouldRenderWithinSlot ) {
content = <Fill name={ slotName }>{ content }</Fill>;
}
if ( ! hasAnchor ) {
content = <span ref={ anchorRefFallback }>{ content }</span>;
}
if ( shouldRenderWithinSlot || inline ) {
return content;
}
return createPortal( content, getPopoverFallbackContainer() );
};
/**
* `Popover` renders its content in a floating modal. If no explicit anchor is passed via props, it anchors to its parent element by default.
*
* ```jsx
* import { Button, Popover } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyPopover = () => {
* const [ isVisible, setIsVisible ] = useState( false );
* const toggleVisible = () => {
* setIsVisible( ( state ) => ! state );
* };
*
* return (
* <Button variant="secondary" onClick={ toggleVisible }>
* Toggle Popover!
* { isVisible && <Popover>Popover is toggled!</Popover> }
* </Button>
* );
* };
* ```
*
*/
export const Popover = forwardRef( UnforwardedPopover );
function PopoverSlot(
{ name = SLOT_NAME }: { name?: string },
ref: ForwardedRef< any >
) {
return (
<Slot
// @ts-expect-error Need to type `SlotFill`
bubblesVirtually
name={ name }
className="popover-slot"
ref={ ref }
/>
);
}
// @ts-expect-error For Legacy Reasons
Popover.Slot = forwardRef( PopoverSlot );
// @ts-expect-error For Legacy Reasons
Popover.__unstableSlotNameProvider = slotNameContext.Provider;
export default Popover;