-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathindex.tsx
644 lines (575 loc) · 19 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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import cx from 'classnames';
import PropTypes from 'prop-types';
import deprecateValuesWithin from '../../prop-types/deprecateValuesWithin';
import React, {
useRef,
useMemo,
useEffect,
type ForwardedRef,
type WeakValidationMap,
type ElementType,
} from 'react';
import useIsomorphicEffect from '../../internal/useIsomorphicEffect';
import { useMergedRefs } from '../../internal/useMergedRefs';
import { usePrefix } from '../../internal/usePrefix';
import { type PolymorphicProps } from '../../types/common';
import { useWindowEvent } from '../../internal/useEvent';
import { mapPopoverAlignProp } from '../../tools/createPropAdapter';
import {
useFloating,
flip,
autoUpdate,
arrow,
offset,
} from '@floating-ui/react';
import { hide } from '@floating-ui/dom';
import { useFeatureFlag } from '../FeatureFlags';
interface PopoverContext {
setFloating: React.Ref<HTMLSpanElement>;
caretRef: React.Ref<HTMLSpanElement>;
autoAlign: boolean | null;
}
const PopoverContext = React.createContext<PopoverContext>({
setFloating: {
current: null,
},
caretRef: {
current: null,
},
autoAlign: null,
});
/**
* Deprecated popover alignment values.
* @deprecated Use NewPopoverAlignment instead.
*/
export type DeprecatedPopoverAlignment =
| 'top-left'
| 'top-right'
| 'bottom-left'
| 'bottom-right'
| 'left-bottom'
| 'left-top'
| 'right-bottom'
| 'right-top';
export type NewPopoverAlignment =
| 'top'
| 'bottom'
| 'left'
| 'right'
| 'top-start'
| 'top-end'
| 'bottom-start'
| 'bottom-end'
| 'left-end'
| 'left-start'
| 'right-end'
| 'right-start';
export type PopoverAlignment = DeprecatedPopoverAlignment | NewPopoverAlignment;
const propMappingFunction = (deprecatedValue) => {
const mapping = {
'top-left': 'top-start',
'top-right': 'top-end',
'bottom-left': 'bottom-start',
'bottom-right': 'bottom-end',
'left-bottom': 'left-end',
'left-top': 'left-start',
'right-bottom': 'right-end',
'right-top': 'right-start',
};
return mapping[deprecatedValue];
};
interface PopoverBaseProps {
/**
* Specify how the popover should align with the trigger element.
*/
align?: PopoverAlignment;
/**
* Will auto-align the popover on first render if it is not visible. This prop is currently experimental and is subject to future changes.
*/
autoAlign?: boolean;
/**
* Specify whether a caret should be rendered
*/
caret?: boolean;
/**
* Provide elements to be rendered inside of the component
*/
children?: React.ReactNode;
/**
* Provide a custom class name to be added to the outermost node in the
* component
*/
className?: string;
/**
* Specify whether a drop shadow should be rendered on the popover
*/
dropShadow?: boolean;
/**
* Render the component using the high-contrast variant
*/
highContrast?: boolean;
/**
* Render the component using the tab tip variant
*/
isTabTip?: boolean;
/**
* Specify a handler for closing popover.
* The handler should take care of closing the popover, e.g. changing the `open` prop.
*/
onRequestClose?: () => void;
/**
* Specify whether the component is currently open or closed
*/
open: boolean;
}
export type PopoverProps<E extends ElementType> = PolymorphicProps<
E,
PopoverBaseProps
>;
export interface PopoverComponent {
<E extends ElementType = 'span'>(
props: PopoverProps<E> & { forwardRef?: ForwardedRef<ElementType> }
): JSX.Element | null;
displayName?: string;
propTypes?: WeakValidationMap<PopoverProps<any>>;
}
export const Popover: PopoverComponent = React.forwardRef(
function PopoverRenderFunction<E extends ElementType = 'span'>(
{
isTabTip,
align: initialAlign = isTabTip ? 'bottom-start' : 'bottom',
as: BaseComponent = 'span' as E,
autoAlign = false,
caret = isTabTip ? false : true,
className: customClassName,
children,
dropShadow = true,
highContrast = false,
onRequestClose,
open,
...rest
}: PopoverProps<E>,
forwardRef: ForwardedRef<Element>
) {
const prefix = usePrefix();
const floating = useRef<HTMLSpanElement>(null);
const caretRef = useRef<HTMLSpanElement>(null);
const popover = useRef<Element>(null);
const enableFloatingStyles =
useFeatureFlag('enable-v12-dynamic-floating-styles') || autoAlign;
let align = mapPopoverAlignProp(initialAlign);
// If the `Popover` is the last focusable item in the tab order, it should also close when the browser window loses focus (#12922)
useWindowEvent('blur', () => {
if (open) {
onRequestClose?.();
}
});
useWindowEvent('click', (event: Event) => {
if (open && !popover?.current?.contains(event.target as Node)) {
onRequestClose?.();
}
});
// Slug styling places a border around the popover content so the caret
// needs to be placed 1px further outside the popover content. To do so,
// we look to see if any of the children has a className containing "slug"
const initialCaretHeight = React.Children.toArray(children).some((x) => {
return (x as any)?.props?.className?.includes('slug');
})
? 7
: 6;
// These defaults match the defaults defined in packages/styles/scss/components/popover/_popover.scss
const popoverDimensions = useRef({
offset: 10,
caretHeight: initialCaretHeight,
});
useIsomorphicEffect(() => {
// The popover is only offset when a caret is present. Technically, the custom properties
// accessed below can be set by a user even if caret=false, but doing so does not follow
// the design specification for Popover.
if (caret && popover.current) {
// Gather the dimensions of the caret and prefer the values set via custom properties.
// If a value is not set via a custom property, provide a default value that matches the
// default values defined in the sass style file
const getStyle = window.getComputedStyle(popover.current, null);
const offsetProperty = getStyle.getPropertyValue(
'--cds-popover-offset'
);
const caretProperty = getStyle.getPropertyValue(
'--cds-popover-caret-height'
);
// Handle if the property values are in px or rem.
// We want to store just the base number value without a unit suffix
if (offsetProperty) {
popoverDimensions.current.offset = offsetProperty.includes('px')
? Number(offsetProperty.split('px', 1)[0]) * 1
: Number(offsetProperty.split('rem', 1)[0]) * 16;
}
if (caretProperty) {
popoverDimensions.current.caretHeight = caretProperty.includes('px')
? Number(caretProperty.split('px', 1)[0]) * 1
: Number(caretProperty.split('rem', 1)[0]) * 16;
}
}
});
const { refs, floatingStyles, placement, middlewareData } = useFloating(
enableFloatingStyles
? {
placement: align,
// The floating element is positioned relative to its nearest
// containing block (usually the viewport). It will in many cases also
// “break” the floating element out of a clipping ancestor.
// https://floating-ui.com/docs/misc#clipping
strategy: 'fixed',
// Middleware order matters, arrow should be last
middleware: [
offset(!isTabTip ? popoverDimensions?.current?.offset : 0),
autoAlign &&
flip({
fallbackPlacements: align.includes('bottom')
? [
'bottom',
'bottom-start',
'bottom-end',
'right',
'right-start',
'right-end',
'left',
'left-start',
'left-end',
'top',
'top-start',
'top-end',
]
: [
'top',
'top-start',
'top-end',
'left',
'left-start',
'left-end',
'right',
'right-start',
'right-end',
'bottom',
'bottom-start',
'bottom-end',
],
fallbackStrategy: 'initialPlacement',
fallbackAxisSideDirection: 'start',
}),
arrow({
element: caretRef,
}),
autoAlign && hide(),
],
whileElementsMounted: autoUpdate,
}
: {}
// When autoAlign is turned off & the `enable-v12-dynamic-floating-styles` feature flag is not
// enabled, floating-ui will not be used
);
const value = useMemo(() => {
return {
floating,
setFloating: refs.setFloating,
caretRef,
autoAlign: autoAlign,
};
}, [refs.setFloating, autoAlign]);
if (isTabTip) {
const tabTipAlignments: PopoverAlignment[] = [
'bottom-start',
'bottom-end',
];
if (!tabTipAlignments.includes(align)) {
align = 'bottom-start';
}
}
useEffect(() => {
if (enableFloatingStyles) {
const updatedFloatingStyles = {
...floatingStyles,
visibility: middlewareData.hide?.referenceHidden
? 'hidden'
: 'visible',
};
Object.keys(updatedFloatingStyles).forEach((style) => {
if (refs.floating.current) {
refs.floating.current.style[style] = updatedFloatingStyles[style];
}
});
if (
caret &&
middlewareData &&
middlewareData.arrow &&
caretRef?.current
) {
const { x, y } = middlewareData.arrow;
const staticSide = {
top: 'bottom',
right: 'left',
bottom: 'top',
left: 'right',
}[placement.split('-')[0]];
caretRef.current.style.left = x != null ? `${x}px` : '';
caretRef.current.style.top = y != null ? `${y}px` : '';
// Ensure the static side gets unset when flipping to other placements' axes.
caretRef.current.style.right = '';
caretRef.current.style.bottom = '';
if (staticSide) {
caretRef.current.style[staticSide] = `${-popoverDimensions?.current
?.caretHeight}px`;
}
}
}
}, [
floatingStyles,
refs.floating,
enableFloatingStyles,
middlewareData,
placement,
caret,
]);
const ref = useMergedRefs([forwardRef, popover]);
const currentAlignment =
autoAlign && placement !== align ? placement : align;
const className = cx(
{
[`${prefix}--popover-container`]: true,
[`${prefix}--popover--caret`]: caret,
[`${prefix}--popover--drop-shadow`]: dropShadow,
[`${prefix}--popover--high-contrast`]: highContrast,
[`${prefix}--popover--open`]: open,
[`${prefix}--popover--auto-align ${prefix}--autoalign`]:
enableFloatingStyles,
[`${prefix}--popover--${currentAlignment}`]: true,
[`${prefix}--popover--tab-tip`]: isTabTip,
},
customClassName
);
const mappedChildren = React.Children.map(children, (child) => {
const item = child as any;
const displayName = item?.type?.displayName;
/**
* Only trigger elements (button) or trigger components (ToggletipButton) should be
* cloned because these will be decorated with a trigger-specific className and ref.
*
* There are also some specific components that should not be cloned when autoAlign
* is on, even if they are a trigger element.
*/
const isTriggerElement = item?.type === 'button';
const isTriggerComponent =
enableFloatingStyles &&
displayName &&
['ToggletipButton'].includes(displayName);
const isAllowedTriggerComponent =
enableFloatingStyles &&
!['ToggletipContent', 'PopoverContent'].includes(displayName);
if (
React.isValidElement(item) &&
(isTriggerElement || isTriggerComponent || isAllowedTriggerComponent)
) {
const className = (item?.props as any)?.className;
const ref = (item?.props as any).ref;
const tabTipClasses = cx(
`${prefix}--popover--tab-tip__button`,
className
);
return React.cloneElement(item as any, {
className:
isTabTip && item?.type === 'button'
? tabTipClasses
: className || '',
// With cloneElement, if you pass a `ref`, it overrides the original ref.
// https://react.dev/reference/react/cloneElement#parameters
// The block below works around this and ensures that the original ref is still
// called while allowing the floating-ui reference element to be set as well.
// `useMergedRefs` can't be used here because hooks can't be called from within a callback.
// More here: https://github.com/facebook/react/issues/8873#issuecomment-489579878
ref: (node) => {
// For a popover, there isn't an explicit trigger component, it's just the first child that's
// passed in which should *not* be PopoverContent.
// For a toggletip there is a specific trigger component, ToggletipButton.
// In either of these caes we want to set this as the reference node for floating-ui autoAlign
// positioning.
if (
(enableFloatingStyles &&
(item?.type as any)?.displayName !== 'PopoverContent') ||
(enableFloatingStyles &&
(item?.type as any)?.displayName === 'ToggletipButton')
) {
// Set the reference element for floating-ui
refs.setReference(node);
}
// Call the original ref, if any
if (typeof ref === 'function') {
ref(node);
} else if (ref !== null && ref !== undefined) {
ref.current = node;
}
},
});
} else {
return item;
}
});
const BaseComponentAsAny = BaseComponent as any;
return (
<PopoverContext.Provider value={value}>
<BaseComponentAsAny {...rest} className={className} ref={ref}>
{enableFloatingStyles || isTabTip ? mappedChildren : children}
</BaseComponentAsAny>
</PopoverContext.Provider>
);
}
);
// Note: this displayName is temporarily set so that Storybook ArgTable
// correctly displays the name of this component
if (__DEV__) {
Popover.displayName = 'Popover';
}
Popover.propTypes = {
/**
* Specify how the popover should align with the trigger element
*/
align: deprecateValuesWithin(
PropTypes.oneOf([
'top',
'top-left', // deprecated use top-start instead
'top-right', // deprecated use top-end instead
'bottom',
'bottom-left', // deprecated use bottom-start instead
'bottom-right', // deprecated use bottom-end instead
'left',
'left-bottom', // deprecated use left-end instead
'left-top', // deprecated use left-start instead
'right',
'right-bottom', // deprecated use right-end instead
'right-top', // deprecated use right-start instead
// new values to match floating-ui
'top-start',
'top-end',
'bottom-start',
'bottom-end',
'left-end',
'left-start',
'right-end',
'right-start',
]),
//allowed prop values
[
'top',
'top-start',
'top-end',
'bottom',
'bottom-start',
'bottom-end',
'left',
'left-start',
'left-end',
'right',
'right-start',
'right-end',
],
//optional mapper function
propMappingFunction
),
/**
* Provide a custom element or component to render the top-level node for the
* component.
*/
as: PropTypes.oneOfType([PropTypes.string, PropTypes.elementType]),
/**
* Will auto-align the popover on first render if it is not visible. This prop is currently experimental and is subject to future changes.
*/
autoAlign: PropTypes.bool,
/**
* Specify whether a caret should be rendered
*/
caret: PropTypes.bool,
/**
* Provide elements to be rendered inside of the component
*/
children: PropTypes.node,
/**
* Provide a custom class name to be added to the outermost node in the
* component
*/
className: PropTypes.string,
/**
* Specify whether a drop shadow should be rendered on the popover
*/
dropShadow: PropTypes.bool,
/**
* Render the component using the high-contrast variant
*/
highContrast: PropTypes.bool,
/**
* Render the component using the tab tip variant
*/
isTabTip: PropTypes.bool,
/**
* Specify a handler for closing popover.
* The handler should take care of closing the popover, e.g. changing the `open` prop.
*/
onRequestClose: PropTypes.func,
/**
* Specify whether the component is currently open or closed
*/
open: PropTypes.bool.isRequired,
};
export type PopoverContentProps = React.HTMLAttributes<HTMLSpanElement>;
function PopoverContentRenderFunction(
// eslint-disable-next-line react/prop-types
{ className, children, ...rest }: PopoverContentProps,
forwardRef: React.ForwardedRef<HTMLSpanElement>
) {
const prefix = usePrefix();
const { setFloating, caretRef, autoAlign } = React.useContext(PopoverContext);
const ref = useMergedRefs([setFloating, forwardRef]);
const enableFloatingStyles =
useFeatureFlag('enable-v12-dynamic-floating-styles') || autoAlign;
return (
<span {...rest} className={`${prefix}--popover`}>
<span className={cx(`${prefix}--popover-content`, className)} ref={ref}>
{children}
{enableFloatingStyles && (
<span
className={cx({
[`${prefix}--popover-caret`]: true,
[`${prefix}--popover--auto-align`]: true,
})}
ref={caretRef}
/>
)}
</span>
{!enableFloatingStyles && (
<span
className={cx({
[`${prefix}--popover-caret`]: true,
})}
ref={caretRef}
/>
)}
</span>
);
}
export const PopoverContent = React.forwardRef(PopoverContentRenderFunction);
PopoverContent.displayName = 'PopoverContent';
PopoverContent.propTypes = {
/**
* Provide elements to be rendered inside of the component
*/
children: PropTypes.node,
/**
* Provide a custom class name to be added to the outermost node in the
* component
*/
className: PropTypes.string,
};