-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
overlay.tsx
338 lines (293 loc) · 12.1 KB
/
overlay.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
/*
* Copyright 2015 Palantir Technologies, Inc. All rights reserved.
* Licensed under the BSD-3 License as modified (the “License”); you may obtain a copy
* of the license at https://github.com/palantir/blueprint/blob/master/LICENSE
* and https://github.com/palantir/blueprint/blob/master/PATENTS
*/
import * as classNames from "classnames";
import * as PureRender from "pure-render-decorator";
import * as React from "react";
import * as CSSTransitionGroup from "react-addons-css-transition-group";
import * as Classes from "../../common/classes";
import * as Keys from "../../common/keys";
import { IProps } from "../../common/props";
import { safeInvoke } from "../../common/utils";
import { Portal } from "../portal/portal";
export interface IOverlayableProps {
/**
* Whether the overlay should acquire application focus when it first opens.
* @default true
*/
autoFocus?: boolean;
/**
* Whether pressing the `esc` key should invoke `onClose`.
* @default true
*/
canEscapeKeyClose?: boolean;
/**
* Whether the overlay should prevent focus from leaving itself. That is, if the user attempts
* to focus an element outside the overlay and this prop is enabled, then the overlay will
* immediately bring focus back to itself. If you are nesting overlay components, either disable
* this prop on the "outermost" overlays or mark the nested ones `inline={true}`.
* @default true
*/
enforceFocus?: boolean;
/**
* Whether the overlay should be rendered inline or into a new element on `document.body`.
* This prop essentially determines which element is covered by the backdrop: if `true`,
* then only its parent is covered; otherwise, the entire application is covered.
* Set this prop to true when this component is used inside an `Overlay` (such as
* `Dialog` or `Popover`) to ensure that this component is rendered above its parent.
* @default false
*/
inline?: boolean;
/**
* If `true` and not `inline`, the `Portal` containing the children is created and attached
* to the DOM when the overlay is opened for the first time; otherwise this happens when the
* component mounts. Lazy mounting provides noticeable performance improvements if you have lots
* of overlays at once, such as on each row of a table.
* @default true
*/
lazy?: boolean;
/**
* Indicates how long (in milliseconds) the overlay's enter/leave transition takes.
* This is used by React `CSSTransitionGroup` to know when a transition completes and must match
* the duration of the animation in CSS. Only set this prop if you override Blueprint's default
* transitions with new transitions of a different length.
* @default 100
*/
transitionDuration?: number;
/**
* A callback that is invoked when user interaction causes the overlay to close, such as
* clicking on the overlay or pressing the `esc` key (if enabled).
* Receives the event from the user's interaction, if there was an event (generally either a
* mouse or key event). Note that, since this component is controlled by the `isOpen` prop, it
* will not actually close itself until that prop becomes `false`.
*/
onClose?(event?: React.SyntheticEvent<HTMLElement>): void;
}
export interface IBackdropProps {
/** CSS class names to apply to backdrop element. */
backdropClassName?: string;
/** HTML props for the backdrop element. */
backdropProps?: React.HTMLProps<HTMLDivElement>;
/**
* Whether clicking outside the overlay element (either on backdrop when present or on document)
* should invoke `onClose`.
* @default true
*/
canOutsideClickClose?: boolean;
/**
* Whether a container-spanning backdrop element should be rendered behind the contents.
* @default true
*/
hasBackdrop?: boolean;
}
export interface IOverlayProps extends IOverlayableProps, IBackdropProps, IProps {
/** Lifecycle callback invoked after the overlay opens and is mounted in the DOM. */
didOpen?: () => any;
/**
* Toggles the visibility of the overlay and its children.
* This prop is required because the component is controlled.
*/
isOpen: boolean;
/**
* Name of the transition for internal `CSSTransitionGroup`.
* Providing your own name here will require defining new CSS transition properties.
* @default "pt-overlay"
*/
transitionName?: string;
}
export interface IOverlayState {
hasEverOpened?: boolean;
}
@PureRender
export class Overlay extends React.Component<IOverlayProps, IOverlayState> {
public static defaultProps: IOverlayProps = {
autoFocus: true,
backdropProps: {},
canEscapeKeyClose: true,
canOutsideClickClose: true,
enforceFocus: true,
hasBackdrop: true,
inline: false,
isOpen: false,
lazy: true,
transitionDuration: 300,
transitionName: "pt-overlay",
};
private static openStack: Overlay[] = [];
private static getLastOpened = () => Overlay.openStack[Overlay.openStack.length - 1];
public displayName = "Blueprint.Overlay";
// an HTMLElement that contains the backdrop and any children, to query for focus target
private containerElement: HTMLElement;
private refHandlers = {
container: (ref: HTMLDivElement) => this.containerElement = ref,
};
public constructor(props?: IOverlayProps, context?: any) {
super(props, context);
this.state = { hasEverOpened: props.isOpen };
}
public render() {
// oh snap! no reason to render anything at all if we're being truly lazy
if (this.props.lazy && !this.state.hasEverOpened) {
return null;
}
const { children, className, inline, isOpen, transitionDuration, transitionName } = this.props;
const transitionGroup = (
<CSSTransitionGroup
transitionAppear={true}
transitionAppearTimeout={transitionDuration}
transitionEnterTimeout={transitionDuration}
transitionLeaveTimeout={transitionDuration}
transitionName={transitionName}
>
{this.maybeRenderBackdrop()}
{isOpen ? children : null}
</CSSTransitionGroup>
);
const elementProps = {
className: classNames({ [Classes.OVERLAY_OPEN]: isOpen }, className),
onKeyDown: this.handleKeyDown,
// make the container focusable so we can trap focus inside it (via `persistentFocus()`)
tabIndex: 0,
};
if (inline) {
return <span {...elementProps} ref={this.refHandlers.container}>{transitionGroup}</span>;
} else {
return (
<Portal
{...elementProps}
containerRef={this.refHandlers.container}
onChildrenMount={this.handleContentMount}
>
{transitionGroup}
</Portal>
);
}
}
public componentDidMount() {
if (this.props.isOpen) {
this.overlayWillOpen();
}
}
public componentWillReceiveProps(nextProps: IOverlayProps) {
this.setState({ hasEverOpened: this.state.hasEverOpened || nextProps.isOpen });
}
public componentDidUpdate(prevProps: IOverlayProps) {
if (prevProps.isOpen && !this.props.isOpen) {
this.overlayWillClose();
} else if (!prevProps.isOpen && this.props.isOpen) {
this.overlayWillOpen();
}
}
public componentWillUnmount() {
this.overlayWillClose();
}
private maybeRenderBackdrop() {
const { backdropClassName, backdropProps, hasBackdrop, isOpen } = this.props;
if (hasBackdrop && isOpen) {
return (
<div
{...backdropProps}
className={classNames(Classes.OVERLAY_BACKDROP, backdropClassName, backdropProps.className)}
onMouseDown={this.handleBackdropMouseDown}
tabIndex={this.props.canOutsideClickClose ? 0 : null}
/>
);
} else {
return undefined;
}
}
private overlayWillClose() {
document.removeEventListener("focus", this.handleDocumentFocus, /* useCapture */ true);
document.removeEventListener("mousedown", this.handleDocumentClick);
const { openStack } = Overlay;
const idx = openStack.indexOf(this);
if (idx > 0) {
openStack.splice(idx, 1);
const lastOpenedOverlay = Overlay.getLastOpened();
if (openStack.length > 0 && lastOpenedOverlay.props.enforceFocus) {
document.addEventListener("focus", lastOpenedOverlay.handleDocumentFocus, /* useCapture */ true);
}
}
}
private overlayWillOpen() {
const { openStack } = Overlay;
if (openStack.length > 0) {
document.removeEventListener("focus", Overlay.getLastOpened().handleDocumentFocus, /* useCapture */ true);
}
openStack.push(this);
if (this.props.canOutsideClickClose && !this.props.hasBackdrop) {
document.addEventListener("mousedown", this.handleDocumentClick);
}
if (this.props.enforceFocus) {
document.addEventListener("focus", this.handleDocumentFocus, /* useCapture */ true);
}
if (this.props.inline) {
safeInvoke(this.props.didOpen);
if (this.props.autoFocus) {
this.bringFocusInsideOverlay();
}
}
}
private bringFocusInsideOverlay = () => {
const { containerElement } = this;
// container ref may be undefined between component mounting and Portal rendering
// activeElement may be undefined in some rare cases in IE
if (containerElement == null || document.activeElement == null || !this.props.isOpen) {
return;
}
const isFocusOutsideModal = !containerElement.contains(document.activeElement);
if (isFocusOutsideModal) {
// element marked autofocus has higher priority than the other clowns
let autofocusElement = containerElement.query("[autofocus]") as HTMLElement;
if (autofocusElement != null) {
autofocusElement.focus();
} else {
containerElement.focus();
}
}
}
private handleBackdropMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
if (this.props.canOutsideClickClose) {
safeInvoke(this.props.onClose, e);
}
safeInvoke(this.props.backdropProps.onMouseDown, e);
}
private handleDocumentClick = (e: MouseEvent) => {
const { isOpen, onClose } = this.props;
const eventTarget = e.target as HTMLElement;
const isClickInOverlay = this.containerElement != null
&& this.containerElement.contains(eventTarget);
if (isOpen && this.props.canOutsideClickClose && !isClickInOverlay) {
// casting to any because this is a native event
safeInvoke(onClose, e as any);
}
}
private handleContentMount = () => {
if (this.props.isOpen) {
safeInvoke(this.props.didOpen);
}
if (this.props.autoFocus) {
this.bringFocusInsideOverlay();
}
}
private handleDocumentFocus = (e: FocusEvent) => {
if (this.props.enforceFocus
&& this.containerElement != null
&& !this.containerElement.contains(e.target as HTMLElement)) {
e.stopImmediatePropagation();
this.bringFocusInsideOverlay();
}
}
private handleKeyDown = (e: React.KeyboardEvent<HTMLElement>) => {
const { canEscapeKeyClose, onClose } = this.props;
if (e.which === Keys.ESCAPE && canEscapeKeyClose) {
safeInvoke(onClose, e);
// prevent browser-specific escape key behavior (Safari exits fullscreen)
e.preventDefault();
}
}
}
export const OverlayFactory = React.createFactory(Overlay);