-
-
Notifications
You must be signed in to change notification settings - Fork 31.6k
/
Drawer.js
424 lines (378 loc) · 12.4 KB
/
Drawer.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
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import EventListener from 'react-event-listener';
import keycode from 'keycode';
import autoPrefix from '../utils/autoPrefix';
import transitions from '../styles/transitions';
import Overlay from '../internal/Overlay';
import Paper from '../Paper';
import propTypes from '../utils/propTypes';
let openNavEventHandler = null;
class Drawer extends Component {
static propTypes = {
/**
* The contents of the `Drawer`
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* The CSS class name of the container element.
*/
containerClassName: PropTypes.string,
/**
* Override the inline-styles of the container element.
*/
containerStyle: PropTypes.object,
/**
* If true, swiping sideways when the `Drawer` is closed will not open it.
*/
disableSwipeToOpen: PropTypes.bool,
/**
* If true, the `Drawer` will be docked. In this state, the overlay won't show and
* clicking on a menu item will not close the `Drawer`.
*/
docked: PropTypes.bool,
/**
* Callback function fired when the `open` state of the `Drawer` is requested to be changed.
*
* @param {boolean} open If true, the `Drawer` was requested to be opened.
* @param {string} reason The reason for the open or close request. Possible values are
* 'swipe' for open requests; 'clickaway' (on overlay clicks),
* 'escape' (on escape key press), and 'swipe' for close requests.
*/
onRequestChange: PropTypes.func,
/**
* If true, the `Drawer` is opened. Providing a value will turn the `Drawer`
* into a controlled component.
*/
open: PropTypes.bool,
/**
* If true, the `Drawer` is positioned to open from the opposite side.
*/
openSecondary: PropTypes.bool,
/**
* The CSS class name to add to the `Overlay` component that is rendered behind the `Drawer`.
*/
overlayClassName: PropTypes.string,
/**
* Override the inline-styles of the `Overlay` component that is rendered behind the `Drawer`.
*/
overlayStyle: PropTypes.object,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
/**
* The width of the left most (or right most) area in pixels where the `Drawer` can be
* swiped open from. Setting this to `null` spans that area to the entire page
* (**CAUTION!** Setting this property to `null` might cause issues with sliders and
* swipeable `Tabs`: use at your own risk).
*/
swipeAreaWidth: PropTypes.number,
/**
* The width of the `Drawer` in pixels or percentage in string format ex. `50%` to fill
* half of the window or `100%` and so on. Defaults to using the values from theme.
*/
width: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
/**
* The zDepth of the `Drawer`.
*/
zDepth: propTypes.zDepth,
};
static defaultProps = {
disableSwipeToOpen: false,
docked: true,
open: null,
openSecondary: false,
swipeAreaWidth: 30,
width: null,
zDepth: 2,
};
static contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
componentWillMount() {
this.maybeSwiping = false;
this.touchStartX = null;
this.touchStartY = null;
this.swipeStartX = null;
this.setState({
open: (this.props.open !== null ) ? this.props.open : this.props.docked,
swiping: null,
});
}
componentDidMount() {
this.enableSwipeHandling();
}
componentWillReceiveProps(nextProps) {
// If controlled then the open prop takes precedence.
if (nextProps.open !== null) {
this.setState({
open: nextProps.open,
});
// Otherwise, if docked is changed, change the open state for when uncontrolled.
} else if (this.props.docked !== nextProps.docked) {
this.setState({
open: nextProps.docked,
});
}
}
componentDidUpdate() {
this.enableSwipeHandling();
}
componentWillUnmount() {
this.disableSwipeHandling();
this.removeBodyTouchListeners();
}
getStyles() {
const muiTheme = this.context.muiTheme;
const theme = muiTheme.drawer;
const x = this.getTranslateMultiplier() * (this.state.open ? 0 : this.getMaxTranslateX());
const styles = {
root: {
height: '100%',
width: this.getTranslatedWidth() || theme.width,
position: 'fixed',
zIndex: muiTheme.zIndex.drawer,
left: 0,
top: 0,
transform: `translate(${x}px, 0)`,
transition: !this.state.swiping && transitions.easeOut(null, 'transform', null),
backgroundColor: theme.color,
overflow: 'auto',
WebkitOverflowScrolling: 'touch', // iOS momentum scrolling
},
overlay: {
zIndex: muiTheme.zIndex.drawerOverlay,
pointerEvents: this.state.open ? 'auto' : 'none', // Bypass mouse events when left nav is closing.
},
rootWhenOpenRight: {
left: 'auto',
right: 0,
},
};
return styles;
}
shouldShow() {
return this.state.open || !!this.state.swiping; // component is swiping
}
close(reason) {
if (this.props.open === null) this.setState({open: false});
if (this.props.onRequestChange) this.props.onRequestChange(false, reason);
return this;
}
open(reason) {
if (this.props.open === null) this.setState({open: true});
if (this.props.onRequestChange) this.props.onRequestChange(true, reason);
return this;
}
handleClickOverlay = (event) => {
event.preventDefault();
this.close('clickaway');
};
handleKeyUp = (event) => {
if (this.state.open && !this.props.docked && keycode(event) === 'esc') {
this.close('escape');
}
};
getTranslatedWidth() {
if (typeof this.props.width === 'string') {
if (!/^\d+(\.\d+)?%$/.test(this.props.width)) {
throw new Error('Not a valid percentage format.');
}
const width = parseFloat(this.props.width) / 100.0;
// We are doing our best on the Server to render a consistent UI, hence the
// default value of 10000
return typeof window !== 'undefined' ? width * window.innerWidth : 10000;
} else {
return this.props.width;
}
}
getMaxTranslateX() {
const width = this.getTranslatedWidth() || this.context.muiTheme.drawer.width;
return width + 10;
}
getTranslateMultiplier() {
return this.props.openSecondary ? 1 : -1;
}
enableSwipeHandling() {
if (!this.props.docked) {
document.body.addEventListener('touchstart', this.onBodyTouchStart);
if (!openNavEventHandler) {
openNavEventHandler = this.onBodyTouchStart;
}
} else {
this.disableSwipeHandling();
}
}
disableSwipeHandling() {
document.body.removeEventListener('touchstart', this.onBodyTouchStart);
if (openNavEventHandler === this.onBodyTouchStart) {
openNavEventHandler = null;
}
}
onBodyTouchStart = (event) => {
const swipeAreaWidth = this.props.swipeAreaWidth;
const touchStartX = this.context.muiTheme.isRtl ?
(document.body.offsetWidth - event.touches[0].pageX) :
event.touches[0].pageX;
const touchStartY = event.touches[0].pageY;
// Open only if swiping from far left (or right) while closed
if (swipeAreaWidth !== null && !this.state.open) {
if (this.props.openSecondary) {
// If openSecondary is true calculate from the far right
if (touchStartX < document.body.offsetWidth - swipeAreaWidth) return;
} else {
// If openSecondary is false calculate from the far left
if (touchStartX > swipeAreaWidth) return;
}
}
if (!this.state.open &&
(openNavEventHandler !== this.onBodyTouchStart ||
this.props.disableSwipeToOpen)
) {
return;
}
this.maybeSwiping = true;
this.touchStartX = touchStartX;
this.touchStartY = touchStartY;
document.body.addEventListener('touchmove', this.onBodyTouchMove);
document.body.addEventListener('touchend', this.onBodyTouchEnd);
document.body.addEventListener('touchcancel', this.onBodyTouchEnd);
};
removeBodyTouchListeners() {
document.body.removeEventListener('touchmove', this.onBodyTouchMove);
document.body.removeEventListener('touchend', this.onBodyTouchEnd);
document.body.removeEventListener('touchcancel', this.onBodyTouchEnd);
}
setPosition(translateX) {
const rtlTranslateMultiplier = this.context.muiTheme.isRtl ? -1 : 1;
const drawer = ReactDOM.findDOMNode(this.refs.clickAwayableElement);
const transformCSS = `translate(${(this.getTranslateMultiplier() * rtlTranslateMultiplier * translateX)}px, 0)`;
this.refs.overlay.setOpacity(1 - translateX / this.getMaxTranslateX());
autoPrefix.set(drawer.style, 'transform', transformCSS);
}
getTranslateX(currentX) {
return Math.min(
Math.max(
this.state.swiping === 'closing' ?
this.getTranslateMultiplier() * (currentX - this.swipeStartX) :
this.getMaxTranslateX() - this.getTranslateMultiplier() * (this.swipeStartX - currentX),
0
),
this.getMaxTranslateX()
);
}
onBodyTouchMove = (event) => {
const currentX = this.context.muiTheme.isRtl ?
(document.body.offsetWidth - event.touches[0].pageX) :
event.touches[0].pageX;
const currentY = event.touches[0].pageY;
if (this.state.swiping) {
event.preventDefault();
this.setPosition(this.getTranslateX(currentX));
} else if (this.maybeSwiping) {
const dXAbs = Math.abs(currentX - this.touchStartX);
const dYAbs = Math.abs(currentY - this.touchStartY);
// If the user has moved his thumb ten pixels in either direction,
// we can safely make an assumption about whether he was intending
// to swipe or scroll.
const threshold = 10;
if (dXAbs > threshold && dYAbs <= threshold) {
this.swipeStartX = currentX;
this.setState({
swiping: this.state.open ? 'closing' : 'opening',
});
this.setPosition(this.getTranslateX(currentX));
} else if (dXAbs <= threshold && dYAbs > threshold) {
this.onBodyTouchEnd();
}
}
};
onBodyTouchEnd = (event) => {
if (this.state.swiping) {
const currentX = this.context.muiTheme.isRtl ?
(document.body.offsetWidth - event.changedTouches[0].pageX) :
event.changedTouches[0].pageX;
const translateRatio = this.getTranslateX(currentX) / this.getMaxTranslateX();
this.maybeSwiping = false;
const swiping = this.state.swiping;
this.setState({
swiping: null,
});
// We have to open or close after setting swiping to null,
// because only then CSS transition is enabled.
if (translateRatio > 0.5) {
if (swiping === 'opening') {
this.setPosition(this.getMaxTranslateX());
} else {
this.close('swipe');
}
} else {
if (swiping === 'opening') {
this.open('swipe');
} else {
this.setPosition(0);
}
}
} else {
this.maybeSwiping = false;
}
this.removeBodyTouchListeners();
};
render() {
const {
children,
className,
containerClassName,
containerStyle,
docked,
openSecondary,
overlayClassName,
overlayStyle,
style,
zDepth,
} = this.props;
const styles = this.getStyles();
let overlay;
if (!docked) {
overlay = (
<Overlay
ref="overlay"
show={this.shouldShow()}
className={overlayClassName}
style={Object.assign(styles.overlay, overlayStyle)}
transitionEnabled={!this.state.swiping}
onClick={this.handleClickOverlay}
/>
);
}
return (
<div
className={className}
style={style}
>
<EventListener target="window" onKeyUp={this.handleKeyUp} />
{overlay}
<Paper
ref="clickAwayableElement"
zDepth={zDepth}
rounded={false}
transitionEnabled={!this.state.swiping}
className={containerClassName}
style={Object.assign(styles.root, openSecondary && styles.rootWhenOpenRight, containerStyle)}
>
{children}
</Paper>
</div>
);
}
}
export default Drawer;