/
Popover.js
601 lines (546 loc) · 17.9 KB
/
Popover.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
589
590
591
592
593
594
595
596
597
598
599
600
601
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import debounce from '../utils/debounce';
import clsx from 'clsx';
import { chainPropTypes, elementTypeAcceptingRef, refType } from '@material-ui/utils';
import ownerDocument from '../utils/ownerDocument';
import ownerWindow from '../utils/ownerWindow';
import createChainedFunction from '../utils/createChainedFunction';
import withStyles from '../styles/withStyles';
import Modal from '../Modal';
import Grow from '../Grow';
import Paper from '../Paper';
export function getOffsetTop(rect, vertical) {
let offset = 0;
if (typeof vertical === 'number') {
offset = vertical;
} else if (vertical === 'center') {
offset = rect.height / 2;
} else if (vertical === 'bottom') {
offset = rect.height;
}
return offset;
}
export function getOffsetLeft(rect, horizontal) {
let offset = 0;
if (typeof horizontal === 'number') {
offset = horizontal;
} else if (horizontal === 'center') {
offset = rect.width / 2;
} else if (horizontal === 'right') {
offset = rect.width;
}
return offset;
}
function getTransformOriginValue(transformOrigin) {
return [transformOrigin.horizontal, transformOrigin.vertical]
.map(n => (typeof n === 'number' ? `${n}px` : n))
.join(' ');
}
// Sum the scrollTop between two elements.
function getScrollParent(parent, child) {
let element = child;
let scrollTop = 0;
while (element && element !== parent) {
element = element.parentNode;
scrollTop += element.scrollTop;
}
return scrollTop;
}
function getAnchorEl(anchorEl) {
return typeof anchorEl === 'function' ? anchorEl() : anchorEl;
}
export const styles = {
/* Styles applied to the root element */
root: {},
/* Styles applied to the `Paper` component. */
paper: {
position: 'absolute',
overflowY: 'auto',
overflowX: 'hidden',
// So we see the popover when it's empty.
// It's most likely on issue on userland.
minWidth: 16,
minHeight: 16,
maxWidth: 'calc(100% - 32px)',
maxHeight: 'calc(100% - 32px)',
// We disable the focus ring for mouse, touch and keyboard users.
outline: 0,
},
};
const Popover = React.forwardRef(function Popover(props, ref) {
const {
action,
anchorEl,
anchorOrigin = {
vertical: 'top',
horizontal: 'left',
},
anchorPosition,
anchorReference = 'anchorEl',
children,
classes,
className,
container: containerProp,
elevation = 8,
getContentAnchorEl,
marginThreshold = 16,
onEnter,
onEntered,
onEntering,
onExit,
onExited,
onExiting,
open,
PaperProps = {},
transformOrigin = {
vertical: 'top',
horizontal: 'left',
},
TransitionComponent = Grow,
transitionDuration: transitionDurationProp = 'auto',
TransitionProps = {},
...other
} = props;
const paperRef = React.useRef();
// Returns the top/left offset of the position
// to attach to on the anchor element (or body if none is provided)
const getAnchorOffset = React.useCallback(
contentAnchorOffset => {
if (anchorReference === 'anchorPosition') {
if (process.env.NODE_ENV !== 'production') {
if (!anchorPosition) {
console.error(
'Material-UI: you need to provide a `anchorPosition` prop when using ' +
'<Popover anchorReference="anchorPosition" />.',
);
}
}
return anchorPosition;
}
const resolvedAnchorEl = getAnchorEl(anchorEl);
const containerWindow = ownerWindow(resolvedAnchorEl);
// If an anchor element wasn't provided, just use the parent body element of this Popover
const anchorElement =
resolvedAnchorEl instanceof containerWindow.Element
? resolvedAnchorEl
: ownerDocument(paperRef.current).body;
const anchorRect = anchorElement.getBoundingClientRect();
if (process.env.NODE_ENV !== 'production') {
const box = anchorElement.getBoundingClientRect();
if (
process.env.NODE_ENV !== 'test' &&
box.top === 0 &&
box.left === 0 &&
box.right === 0 &&
box.bottom === 0
) {
console.warn(
[
'Material-UI: the `anchorEl` prop provided to the component is invalid.',
'The anchor element should be part of the document layout.',
"Make sure the element is present in the document or that it's not display none.",
].join('\n'),
);
}
}
const anchorVertical = contentAnchorOffset === 0 ? anchorOrigin.vertical : 'center';
return {
top: anchorRect.top + getOffsetTop(anchorRect, anchorVertical),
left: anchorRect.left + getOffsetLeft(anchorRect, anchorOrigin.horizontal),
};
},
[anchorEl, anchorOrigin.horizontal, anchorOrigin.vertical, anchorPosition, anchorReference],
);
// Returns the vertical offset of inner content to anchor the transform on if provided
const getContentAnchorOffset = React.useCallback(
element => {
let contentAnchorOffset = 0;
if (getContentAnchorEl && anchorReference === 'anchorEl') {
const contentAnchorEl = getContentAnchorEl(element);
if (contentAnchorEl && element.contains(contentAnchorEl)) {
const scrollTop = getScrollParent(element, contentAnchorEl);
contentAnchorOffset =
contentAnchorEl.offsetTop + contentAnchorEl.clientHeight / 2 - scrollTop || 0;
}
// != the default value
if (process.env.NODE_ENV !== 'production') {
if (anchorOrigin.vertical !== 'top') {
console.error(
[
'Material-UI: you can not change the default `anchorOrigin.vertical` value ',
'when also providing the `getContentAnchorEl` prop to the popover component.',
'Only use one of the two props.',
'Set `getContentAnchorEl` to `null | undefined`' +
' or leave `anchorOrigin.vertical` unchanged.',
].join('\n'),
);
}
}
}
return contentAnchorOffset;
},
[anchorOrigin.vertical, anchorReference, getContentAnchorEl],
);
// Return the base transform origin using the element
// and taking the content anchor offset into account if in use
const getTransformOrigin = React.useCallback(
(elemRect, contentAnchorOffset = 0) => {
return {
vertical: getOffsetTop(elemRect, transformOrigin.vertical) + contentAnchorOffset,
horizontal: getOffsetLeft(elemRect, transformOrigin.horizontal),
};
},
[transformOrigin.horizontal, transformOrigin.vertical],
);
const getPositioningStyle = React.useCallback(
element => {
// Check if the parent has requested anchoring on an inner content node
const contentAnchorOffset = getContentAnchorOffset(element);
const elemRect = {
width: element.offsetWidth,
height: element.offsetHeight,
};
// Get the transform origin point on the element itself
const elemTransformOrigin = getTransformOrigin(elemRect, contentAnchorOffset);
if (anchorReference === 'none') {
return {
top: null,
left: null,
transformOrigin: getTransformOriginValue(elemTransformOrigin),
};
}
// Get the offset of of the anchoring element
const anchorOffset = getAnchorOffset(contentAnchorOffset);
// Calculate element positioning
let top = anchorOffset.top - elemTransformOrigin.vertical;
let left = anchorOffset.left - elemTransformOrigin.horizontal;
const bottom = top + elemRect.height;
const right = left + elemRect.width;
// Use the parent window of the anchorEl if provided
const containerWindow = ownerWindow(getAnchorEl(anchorEl));
// Window thresholds taking required margin into account
const heightThreshold = containerWindow.innerHeight - marginThreshold;
const widthThreshold = containerWindow.innerWidth - marginThreshold;
// Check if the vertical axis needs shifting
if (top < marginThreshold) {
const diff = top - marginThreshold;
top -= diff;
elemTransformOrigin.vertical += diff;
} else if (bottom > heightThreshold) {
const diff = bottom - heightThreshold;
top -= diff;
elemTransformOrigin.vertical += diff;
}
if (process.env.NODE_ENV !== 'production') {
if (elemRect.height > heightThreshold && elemRect.height && heightThreshold) {
console.error(
[
'Material-UI: the popover component is too tall.',
`Some part of it can not be seen on the screen (${elemRect.height -
heightThreshold}px).`,
'Please consider adding a `max-height` to improve the user-experience.',
].join('\n'),
);
}
}
// Check if the horizontal axis needs shifting
if (left < marginThreshold) {
const diff = left - marginThreshold;
left -= diff;
elemTransformOrigin.horizontal += diff;
} else if (right > widthThreshold) {
const diff = right - widthThreshold;
left -= diff;
elemTransformOrigin.horizontal += diff;
}
return {
top: `${top}px`,
left: `${left}px`,
transformOrigin: getTransformOriginValue(elemTransformOrigin),
};
},
[
anchorEl,
anchorReference,
getAnchorOffset,
getContentAnchorOffset,
getTransformOrigin,
marginThreshold,
],
);
const setPositioningStyles = React.useCallback(
element => {
const positioning = getPositioningStyle(element);
if (positioning.top !== null) {
element.style.top = positioning.top;
}
if (positioning.left !== null) {
element.style.left = positioning.left;
}
element.style.transformOrigin = positioning.transformOrigin;
},
[getPositioningStyle],
);
const handleEntering = (element, isAppearing) => {
if (onEntering) {
onEntering(element, isAppearing);
}
setPositioningStyles(element);
};
const handlePaperRef = React.useCallback(instance => {
// #StrictMode ready
paperRef.current = ReactDOM.findDOMNode(instance);
}, []);
const updatePosition = React.useMemo(() => {
if (!open) {
return undefined;
}
return debounce(() => {
setPositioningStyles(paperRef.current);
});
}, [open, setPositioningStyles]);
React.useImperativeHandle(action, () => (open ? { updatePosition } : null), [
open,
updatePosition,
]);
React.useEffect(() => {
if (!updatePosition) {
return undefined;
}
window.addEventListener('resize', updatePosition);
return () => {
window.removeEventListener('resize', updatePosition);
updatePosition.clear();
};
}, [updatePosition]);
let transitionDuration = transitionDurationProp;
if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) {
transitionDuration = undefined;
}
// If the container prop is provided, use that
// If the anchorEl prop is provided, use its parent body element as the container
// If neither are provided let the Modal take care of choosing the container
const container =
containerProp || (anchorEl ? ownerDocument(getAnchorEl(anchorEl)).body : undefined);
return (
<Modal
container={container}
open={open}
ref={ref}
BackdropProps={{ invisible: true }}
className={clsx(classes.root, className)}
{...other}
>
<TransitionComponent
appear
in={open}
onEnter={onEnter}
onEntered={onEntered}
onExit={onExit}
onExited={onExited}
onExiting={onExiting}
timeout={transitionDuration}
{...TransitionProps}
onEntering={createChainedFunction(handleEntering, TransitionProps.onEntering)}
>
<Paper
data-mui-test="Popover"
elevation={elevation}
ref={handlePaperRef}
{...PaperProps}
className={clsx(classes.paper, PaperProps.className)}
>
{children}
</Paper>
</TransitionComponent>
</Modal>
);
});
Popover.propTypes = {
/**
* A ref for imperative actions.
* It currently only supports updatePosition() action.
*/
action: refType,
/**
* This is the DOM element, or a function that returns the DOM element,
* that may be used to set the position of the popover.
*/
anchorEl: chainPropTypes(PropTypes.oneOfType([PropTypes.object, PropTypes.func]), props => {
if (props.open && (!props.anchorReference || props.anchorReference === 'anchorEl')) {
const resolvedAnchorEl = getAnchorEl(props.anchorEl);
const containerWindow = ownerWindow(resolvedAnchorEl);
if (resolvedAnchorEl instanceof containerWindow.Element) {
const box = resolvedAnchorEl.getBoundingClientRect();
if (
process.env.NODE_ENV !== 'test' &&
box.top === 0 &&
box.left === 0 &&
box.right === 0 &&
box.bottom === 0
) {
return new Error(
[
'Material-UI: the `anchorEl` prop provided to the component is invalid.',
'The anchor element should be part of the document layout.',
"Make sure the element is present in the document or that it's not display none.",
].join('\n'),
);
}
} else {
return new Error(
[
'Material-UI: the `anchorEl` prop provided to the component is invalid.',
`It should be an Element instance but it's \`${resolvedAnchorEl}\` instead.`,
].join('\n'),
);
}
}
return null;
}),
/**
* This is the point on the anchor where the popover's
* `anchorEl` will attach to. This is not used when the
* anchorReference is 'anchorPosition'.
*
* Options:
* vertical: [top, center, bottom];
* horizontal: [left, center, right].
*/
anchorOrigin: PropTypes.shape({
horizontal: PropTypes.oneOfType([
PropTypes.number,
PropTypes.oneOf(['left', 'center', 'right']),
]).isRequired,
vertical: PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['top', 'center', 'bottom'])])
.isRequired,
}),
/**
* This is the position that may be used
* to set the position of the popover.
* The coordinates are relative to
* the application's client area.
*/
anchorPosition: PropTypes.shape({
left: PropTypes.number.isRequired,
top: PropTypes.number.isRequired,
}),
/*
* This determines which anchor prop to refer to to set
* the position of the popover.
*/
anchorReference: PropTypes.oneOf(['anchorEl', 'anchorPosition', 'none']),
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* A node, component instance, or function that returns either.
* The `container` will passed to the Modal component.
* By default, it uses the body of the anchorEl's top-level document object,
* so it's simply `document.body` most of the time.
*/
container: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* The elevation of the popover.
*/
elevation: PropTypes.number,
/**
* This function is called in order to retrieve the content anchor element.
* It's the opposite of the `anchorEl` prop.
* The content anchor element should be an element inside the popover.
* It's used to correctly scroll and set the position of the popover.
* The positioning strategy tries to make the content anchor element just above the
* anchor element.
*/
getContentAnchorEl: PropTypes.func,
/**
* Specifies how close to the edge of the window the popover can appear.
*/
marginThreshold: PropTypes.number,
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be:`"escapeKeyDown"`, `"backdropClick"`
*/
onClose: PropTypes.func,
/**
* Callback fired before the component is entering.
*/
onEnter: PropTypes.func,
/**
* Callback fired when the component has entered.
*/
onEntered: PropTypes.func,
/**
* Callback fired when the component is entering.
*/
onEntering: PropTypes.func,
/**
* Callback fired before the component is exiting.
*/
onExit: PropTypes.func,
/**
* Callback fired when the component has exited.
*/
onExited: PropTypes.func,
/**
* Callback fired when the component is exiting.
*/
onExiting: PropTypes.func,
/**
* If `true`, the popover is visible.
*/
open: PropTypes.bool.isRequired,
/**
* Props applied to the [`Paper`](/api/paper/) element.
*/
PaperProps: PropTypes.shape({
component: elementTypeAcceptingRef,
}),
/**
* This is the point on the popover which
* will attach to the anchor's origin.
*
* Options:
* vertical: [top, center, bottom, x(px)];
* horizontal: [left, center, right, x(px)].
*/
transformOrigin: PropTypes.shape({
horizontal: PropTypes.oneOfType([
PropTypes.number,
PropTypes.oneOf(['left', 'center', 'right']),
]).isRequired,
vertical: PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['top', 'center', 'bottom'])])
.isRequired,
}),
/**
* The component used for the transition.
*/
TransitionComponent: PropTypes.elementType,
/**
* Set to 'auto' to automatically calculate transition time based on height.
*/
transitionDuration: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }),
PropTypes.oneOf(['auto']),
]),
/**
* Props applied to the `Transition` element.
*/
TransitionProps: PropTypes.object,
};
export default withStyles(styles, { name: 'MuiPopover' })(Popover);