-
Notifications
You must be signed in to change notification settings - Fork 126
/
Popup.tsx
702 lines (607 loc) · 23.4 KB
/
Popup.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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
import React from 'react';
import PropTypes from 'prop-types';
import { Transition } from 'react-transition-group';
import raf from 'raf';
import warning from 'warning';
import { Nullable } from '../../typings/utility-types';
import * as LayoutEvents from '../../lib/LayoutEvents';
import { ZIndex } from '../ZIndex';
import { RenderContainer } from '../RenderContainer';
import { FocusEventType, MouseEventType } from '../../typings/event-types';
import { ComponentType, isFunction, isNonNullable, isNullable, isRefableElement } from '../../lib/utils';
import { isIE11, isEdge, isSafari } from '../../lib/client';
import { ThemeContext } from '../../lib/theming/ThemeContext';
import { Theme } from '../../lib/theming/Theme';
import { isHTMLElement } from '../../lib/SSRSafe';
import { isTestEnv } from '../../lib/currentEnvironment';
import { CommonProps, CommonWrapper } from '../CommonWrapper';
import { cx } from '../../lib/theming/Emotion';
import { responsiveLayout } from '../../components/ResponsiveLayout/decorator';
import { MobilePopup } from '../MobilePopup';
import { getRootNode, rootNode, TSetRootNode } from '../../lib/rootNode';
import { callChildRef } from '../../lib/callChildRef/callChildRef';
import { isInstanceWithAnchorElement } from '../../lib/InstanceWithAnchorElement';
import { PopupPin } from './PopupPin';
import { Offset, PopupHelper, PositionObject, Rect } from './PopupHelper';
import { styles } from './Popup.styles';
const POPUP_BORDER_DEFAULT_COLOR = 'transparent';
const TRANSITION_TIMEOUT = { enter: 0, exit: 200 };
export const PopupPositions = [
'top left',
'top center',
'top right',
'right top',
'right middle',
'right bottom',
'bottom right',
'bottom center',
'bottom left',
'left bottom',
'left middle',
'left top',
] as const;
export const DefaultPosition = PopupPositions[0];
export type PopupPositionsType = typeof PopupPositions[number];
const DUMMY_LOCATION: PopupLocation = {
position: DefaultPosition,
coordinates: {
top: -9999,
left: -9999,
},
};
export interface PopupHandlerProps {
onMouseEnter?: (event: MouseEventType) => void;
onMouseLeave?: (event: MouseEventType) => void;
onClick?: (event: MouseEventType) => void;
onFocus?: (event: FocusEventType) => void;
onBlur?: (event: FocusEventType) => void;
onOpen?: () => void;
onClose?: () => void;
}
export interface PopupProps extends CommonProps, PopupHandlerProps {
anchorElement: React.ReactNode | HTMLElement;
backgroundColor?: React.CSSProperties['backgroundColor'];
borderColor?: React.CSSProperties['borderColor'];
children: React.ReactNode | (() => React.ReactNode);
hasPin: boolean;
hasShadow: boolean;
disableAnimations: boolean;
margin?: number;
maxWidth?: number | string;
opened: boolean;
pinOffset?: number;
pinSize?: number;
popupOffset: number;
positions: Readonly<PopupPositionsType[]>;
/**
* Явно указывает, что вложенные элементы должны быть обёрнуты в `<span/>`. <br/> Используется для корректного позиционирования тултипа при двух и более вложенных элементах.
*
* _Примечание_: при **двух и более** вложенных элементах обёртка будет добавлена автоматически.
*/
useWrapper: boolean;
ignoreHover: boolean;
width: React.CSSProperties['width'];
/**
* При очередном рендере пытаться сохранить первоначальную позицию попапа
* (в числе числе, когда он выходит за пределы экрана, но может быть проскролен в него).
*
* Нужен только для Tooltip. В остальных случаях позиция перестраивается автоматически.
* @see https://github.com/skbkontur/retail-ui/pull/1195
*/
tryPreserveFirstRenderedPosition?: boolean;
withoutMobile?: boolean;
mobileOnCloseRequest?: () => void;
}
interface PopupLocation {
coordinates: {
left: number;
top: number;
};
position: PopupPositionsType;
}
export interface PopupState {
location: Nullable<PopupLocation>;
}
@responsiveLayout
@rootNode
export class Popup extends React.Component<PopupProps, PopupState> {
public static __KONTUR_REACT_UI__ = 'Popup';
public static propTypes = {
/**
* Ссылка (ref) на элемент или React компонент, для которого рисуется попап
*/
anchorElement: ComponentType.isRequired,
/**
* Фон попапа и пина
*/
backgroundColor: PropTypes.string,
children: ComponentType,
/**
* Показывать ли пин
*/
hasPin: PropTypes.bool,
/**
* Применять ли box-shadow на попапе. При false отключает границу на пине
*/
hasShadow: PropTypes.bool,
/**
* Отступ попапа от элемента
*/
margin: PropTypes.number,
/**
* Показан или скрыт попап
*/
opened: PropTypes.bool,
/**
* Смещение пина от края попапа. Край задаётся в пропе position вторым словом
*/
pinOffset: PropTypes.number,
/**
* Сторона пина без учёта границы.
* Пин представляет собой равносторонний треугольник, высота от попапа
* до "носика" пина будет соответствовать формуле (size* √3)/2
*/
pinSize: PropTypes.number,
/**
* смещение попапа относительно родительского элемента
*/
popupOffset: PropTypes.number,
/**
* С какой стороны показывать попап и край попапа,
* на котором будет отображаться пин
*/
positions: PropTypes.array,
/**
* Игнорировать ли события hover/click
*/
ignoreHover: PropTypes.bool,
};
public static defaultProps = {
popupOffset: 0,
hasPin: false,
hasShadow: false,
disableAnimations: isTestEnv,
useWrapper: false,
ignoreHover: false,
width: 'auto',
};
// see #2873 and #2895
public static readonly defaultRootNode = null;
public state: PopupState = { location: this.props.opened ? DUMMY_LOCATION : null };
private theme!: Theme;
private layoutEventsToken: Nullable<ReturnType<typeof LayoutEvents.addListener>>;
private locationUpdateId: Nullable<number> = null;
private lastPopupElement: Nullable<HTMLElement>;
private isMobileLayout!: boolean;
private setRootNode!: TSetRootNode;
private refForTransition = React.createRef<HTMLDivElement>();
public anchorElement: Nullable<HTMLElement> = null;
public componentDidMount() {
this.updateLocation();
this.layoutEventsToken = LayoutEvents.addListener(this.handleLayoutEvent);
}
public static getDerivedStateFromProps(props: Readonly<PopupProps>, state: PopupState) {
/**
* Delaying updateLocation to ensure it happens after props update
*/
if (props.opened) {
if (!state.location) {
return { location: DUMMY_LOCATION };
}
} else if (state.location) {
return { location: DUMMY_LOCATION };
}
return state;
}
public componentDidUpdate(prevProps: PopupProps, prevState: PopupState) {
const hadNoLocation = prevState.location === DUMMY_LOCATION;
const hasLocation = this.state.location !== DUMMY_LOCATION;
const wasClosed = prevProps.opened && !this.props.opened;
if (this.isMobileLayout && prevState.location === null && this.state.location === null) {
this.setState({ location: DUMMY_LOCATION });
}
if (this.props.opened && hadNoLocation && hasLocation && this.props.onOpen) {
this.props.onOpen();
}
if (wasClosed && !hasLocation && this.props.onClose) {
this.props.onClose();
}
if (this.props.opened) {
this.delayUpdateLocation();
}
}
public componentWillUnmount() {
this.cancelDelayedUpdateLocation();
this.removeEventListeners(this.anchorElement);
if (this.layoutEventsToken) {
this.layoutEventsToken.remove();
this.layoutEventsToken = null;
}
if (this.state.location && this.props.onClose) {
this.props.onClose();
}
}
public render() {
return (
<ThemeContext.Consumer>
{(theme) => {
this.theme = theme;
return this.renderMain();
}}
</ThemeContext.Consumer>
);
}
private renderMobile() {
const { opened } = this.props;
const children = this.renderChildren();
return children ? (
<MobilePopup opened={opened} withoutRenderContainer onCloseRequest={this.props.mobileOnCloseRequest}>
{this.content(children)}
</MobilePopup>
) : null;
}
private renderMain() {
const { location } = this.state;
const { anchorElement, useWrapper } = this.props;
let anchor: Nullable<React.ReactNode> = null;
if (isHTMLElement(anchorElement)) {
this.updateAnchorElement(anchorElement);
} else if (React.isValidElement(anchorElement)) {
anchor = useWrapper ? <span>{anchorElement}</span> : anchorElement;
} else {
anchor = <span>{anchorElement}</span>;
}
const anchorWithRef =
anchor && React.isValidElement(anchor) && isRefableElement(anchor)
? React.cloneElement(anchor, {
ref: (instance: Nullable<React.ReactInstance>) => {
this.updateAnchorElement(instance);
const originalRef = (anchor as React.RefAttributes<any>)?.ref;
originalRef && callChildRef(originalRef, instance);
},
})
: null;
// we need to get anchor's DOM node
// so we either set our own ref on it via cloning
// or relay on findDOMNode (inside getRootNode)
// which should be called within updateAnchorElement
// in the case when the anchor is not refable
const canGetAnchorNode = !!anchorWithRef || isHTMLElement(anchorElement);
return (
<RenderContainer anchor={anchorWithRef || anchor} ref={canGetAnchorNode ? null : this.updateAnchorElement}>
{this.isMobileLayout && !this.props.withoutMobile
? this.renderMobile()
: location && this.renderContent(location)}
</RenderContainer>
);
}
private updateAnchorElement = (instance: Nullable<React.ReactInstance>) => {
const childDomNode = isInstanceWithAnchorElement(instance) ? instance.getAnchorElement() : getRootNode(instance);
const anchorElement = this.anchorElement;
if (childDomNode !== anchorElement) {
this.removeEventListeners(anchorElement);
this.anchorElement = childDomNode;
this.addEventListeners(childDomNode);
}
};
private addEventListeners(element: Nullable<HTMLElement>) {
if (element && isHTMLElement(element)) {
element.addEventListener('mouseenter', this.handleMouseEnter);
element.addEventListener('mouseleave', this.handleMouseLeave);
element.addEventListener('click', this.handleClick);
element.addEventListener('focusin', this.handleFocus as EventListener);
element.addEventListener('focusout', this.handleBlur as EventListener);
}
}
private removeEventListeners(element: Nullable<HTMLElement>) {
if (element && isHTMLElement(element)) {
element.removeEventListener('mouseenter', this.handleMouseEnter);
element.removeEventListener('mouseleave', this.handleMouseLeave);
element.removeEventListener('click', this.handleClick);
element.removeEventListener('focusin', this.handleFocus as EventListener);
element.removeEventListener('focusout', this.handleBlur as EventListener);
}
}
private handleMouseEnter = (event: MouseEventType) => {
if (this.props.onMouseEnter) {
this.props.onMouseEnter(event);
}
};
private handleMouseLeave = (event: MouseEventType) => {
if (this.props.onMouseLeave) {
this.props.onMouseLeave(event);
}
};
private handleClick = (event: MouseEventType) => {
if (this.props.onClick) {
this.props.onClick(event);
}
};
private handleFocus = (event: FocusEventType) => {
if (this.props.onFocus) {
this.props.onFocus(event);
}
};
private handleBlur = (event: FocusEventType) => {
if (this.props.onBlur) {
this.props.onBlur(event);
}
};
private calculateWidth = (width: PopupProps['width']) => {
if (typeof width === 'string' && width.includes('%')) {
return this.anchorElement ? (this.anchorElement.offsetWidth * parseFloat(width)) / 100 : 0;
}
return width;
};
private content = (children: React.ReactNode) => {
const { backgroundColor, width } = this.props;
return (
<div className={styles.content(this.theme)} data-tid={'PopupContent'} ref={this.refForTransition}>
<div
className={styles.contentInner(this.theme)}
style={{ backgroundColor, width: this.calculateWidth(width) }}
data-tid={'PopupContentInner'}
>
{children}
</div>
</div>
);
};
private renderContent(location: PopupLocation) {
const { disableAnimations, maxWidth, hasShadow, ignoreHover, opened } = this.props;
const children = this.renderChildren();
const { direction } = PopupHelper.getPositionObject(location.position);
const rootStyle: React.CSSProperties = { ...location.coordinates, maxWidth };
const shouldFallbackShadow = isIE11 || isEdge || isSafari;
return (
<Transition
timeout={TRANSITION_TIMEOUT}
appear={!disableAnimations}
in={Boolean(opened && children)}
mountOnEnter
unmountOnExit
enter={!disableAnimations}
exit={!disableAnimations}
onExited={this.resetLocation}
nodeRef={this.refForTransition}
>
{(state: string) => (
<CommonWrapper {...this.props} rootNodeRef={this.setRootNode}>
<ZIndex
data-tid={'Popup__root'}
wrapperRef={this.refPopupElement}
priority={'Popup'}
className={cx({
[styles.popup(this.theme)]: true,
[styles.shadow(this.theme)]: hasShadow && !shouldFallbackShadow,
[styles.shadowFallback(this.theme)]: hasShadow && shouldFallbackShadow,
[styles.popupIgnoreHover()]: ignoreHover,
...(disableAnimations
? {}
: {
[styles[`transition-enter-${direction}` as keyof typeof styles](this.theme)]: true,
[styles.transitionEnter()]: state === 'entering',
[styles.transitionEnterActive()]: state === 'entered',
[styles.transitionExit()]: state === 'exiting',
}),
})}
style={rootStyle}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
>
{this.content(children)}
{!this.isMobileLayout && this.renderPin(location.position)}
</ZIndex>
</CommonWrapper>
)}
</Transition>
);
}
private resetLocation = () => {
this.cancelDelayedUpdateLocation();
this.state.location !== null && this.setState({ location: null });
};
private renderChildren() {
return isFunction(this.props.children) ? this.props.children() : this.props.children;
}
private refPopupElement = (element: Nullable<HTMLElement>) => {
this.lastPopupElement = element;
};
private renderPin(positionName: string): React.ReactNode {
/**
* Box-shadow does not appear under the pin. Borders are used instead.
* In non-ie browsers drop-shadow filter is used. It is applying
* shadow to the pin too.
*/
const isDefaultBorderColor = this.theme.popupBorderColor === POPUP_BORDER_DEFAULT_COLOR;
const pinBorder = isIE11 && isDefaultBorderColor ? 'rgba(0, 0, 0, 0.09)' : this.theme.popupBorderColor;
const { pinSize, hasShadow, backgroundColor, borderColor } = this.props;
const position = PopupHelper.getPositionObject(positionName);
return (
this.props.hasPin && (
<PopupPin
popupElement={this.lastPopupElement}
popupPosition={positionName}
size={pinSize || parseInt(this.theme.popupPinSize)}
offset={this.getPinOffset(position.align)}
borderWidth={hasShadow ? 1 : 0}
backgroundColor={backgroundColor || this.theme.popupBackground}
borderColor={borderColor || pinBorder}
/>
)
);
}
private handleLayoutEvent = () => {
if (!this.state.location) {
return;
}
this.updateLocation();
};
private delayUpdateLocation() {
this.cancelDelayedUpdateLocation();
this.locationUpdateId = raf(this.updateLocation);
}
private cancelDelayedUpdateLocation() {
if (this.locationUpdateId) {
raf.cancel(this.locationUpdateId);
this.locationUpdateId = null;
}
}
private updateLocation = () => {
const popupElement = this.lastPopupElement;
if (!popupElement) {
return;
}
const location = this.getLocation(popupElement, this.state.location);
if (!this.locationEquals(this.state.location, location)) {
this.setState({ location });
}
};
private locationEquals(x: Nullable<PopupLocation>, y: Nullable<PopupLocation>) {
if (x === y) {
return true;
}
if (isNullable(x) || isNullable(y)) {
return false;
}
if (!isIE11 && !isEdge) {
return (
x.coordinates.left === y.coordinates.left &&
x.coordinates.top === y.coordinates.top &&
x.position === y.position
);
}
// Для ie/edge обновляем позицию только при разнице минимум в 1. Иначе есть вероятность
// уйти в бесконечный ререндер
return (
x.position === y.position &&
Math.abs(x.coordinates.top - y.coordinates.top) <= 1 &&
Math.abs(x.coordinates.left - y.coordinates.left) <= 1
);
}
private getLocation(popupElement: HTMLElement, location?: Nullable<PopupLocation>) {
const { positions, tryPreserveFirstRenderedPosition } = this.props;
const anchorElement = this.anchorElement;
warning(
anchorElement && isHTMLElement(anchorElement),
'Anchor element is not defined or not instance of HTMLElement',
);
if (!(anchorElement && isHTMLElement(anchorElement))) {
return location;
}
const anchorRect = PopupHelper.getElementAbsoluteRect(anchorElement);
const popupRect = PopupHelper.getElementAbsoluteRect(popupElement);
let position: PopupPositionsType;
let coordinates: Offset;
if (location && location !== DUMMY_LOCATION && location.position) {
position = location.position;
coordinates = this.getCoordinates(anchorRect, popupRect, position);
const isFullyVisible = PopupHelper.isFullyVisible(coordinates, popupRect);
const canBecomeVisible = !isFullyVisible && PopupHelper.canBecomeFullyVisible(position, coordinates);
if (
// если нужно сохранить первоначальную позицию и Попап целиком
// находится в пределах вьюпорта (или может быть проскроллен в него)
(tryPreserveFirstRenderedPosition && (isFullyVisible || canBecomeVisible)) ||
// если Попап целиком во вьюпорте и в самой приоритетной позиции
// (иначе нужно попытаться позицию сменить)
(isFullyVisible && position === positions[0])
) {
// сохраняем текущую позицию
return { coordinates, position };
}
}
for (position of positions) {
coordinates = this.getCoordinates(anchorRect, popupRect, position);
if (PopupHelper.isFullyVisible(coordinates, popupRect)) {
return { coordinates, position };
}
}
position = positions[0];
coordinates = this.getCoordinates(anchorRect, popupRect, position);
return { coordinates, position };
}
private getPinnedPopupOffset(anchorRect: Rect, position: PositionObject) {
if (!this.props.hasPin || /center|middle/.test(position.align)) {
return 0;
}
const anchorSize = /top|bottom/.test(position.direction) ? anchorRect.width : anchorRect.height;
const { pinSize } = this.props;
return Math.max(
0,
this.getPinOffset(position.align) + (pinSize || parseInt(this.theme.popupPinSize)) - anchorSize / 2,
);
}
private getCoordinates(anchorRect: Rect, popupRect: Rect, positionName: string) {
const { margin: marginFromProps } = this.props;
const margin =
isNonNullable(marginFromProps) && !isNaN(marginFromProps)
? marginFromProps
: parseInt(this.theme.popupMargin) || 0;
const position = PopupHelper.getPositionObject(positionName);
const popupOffset = this.props.popupOffset + this.getPinnedPopupOffset(anchorRect, position);
switch (position.direction) {
case 'top':
return {
top: anchorRect.top - popupRect.height - margin,
left: this.getHorizontalPosition(anchorRect, popupRect, position.align, popupOffset),
};
case 'bottom':
return {
top: anchorRect.top + anchorRect.height + margin,
left: this.getHorizontalPosition(anchorRect, popupRect, position.align, popupOffset),
};
case 'left':
return {
top: this.getVerticalPosition(anchorRect, popupRect, position.align, popupOffset),
left: anchorRect.left - popupRect.width - margin,
};
case 'right':
return {
top: this.getVerticalPosition(anchorRect, popupRect, position.align, popupOffset),
left: anchorRect.left + anchorRect.width + margin,
};
default:
throw new Error(`Unexpected direction '${position.direction}'`);
}
}
private getPinOffset(align: string) {
const { pinOffset } = this.props;
switch (align) {
case 'top':
case 'bottom':
return pinOffset || parseInt(this.theme.popupPinOffset) || parseInt(this.theme.popupPinOffsetY);
case 'left':
case 'right':
return pinOffset || parseInt(this.theme.popupPinOffset) || parseInt(this.theme.popupPinOffsetX);
case 'center':
case 'middle':
return 0;
default:
throw new Error(`Unexpected align '${align}'`);
}
}
private getHorizontalPosition(anchorRect: Rect, popupRect: Rect, align: string, popupOffset: number) {
switch (align) {
case 'left':
return anchorRect.left - popupOffset;
case 'center':
return anchorRect.left - (popupRect.width - anchorRect.width) / 2;
case 'right':
return anchorRect.left - (popupRect.width - anchorRect.width) + popupOffset;
default:
throw new Error(`Unexpected align '${align}'`);
}
}
private getVerticalPosition(anchorRect: Rect, popupRect: Rect, align: string, popupOffset: number) {
switch (align) {
case 'top':
return anchorRect.top - popupOffset;
case 'middle':
return anchorRect.top - (popupRect.height - anchorRect.height) / 2;
case 'bottom':
return anchorRect.top - (popupRect.height - anchorRect.height) + popupOffset;
default:
throw new Error(`Unexpected align '${align}'`);
}
}
}