/
DayPicker.jsx
484 lines (404 loc) · 13.7 KB
/
DayPicker.jsx
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
import React, { PropTypes } from 'react';
import shallowCompare from 'react-addons-shallow-compare';
import ReactDOM from 'react-dom';
import { forbidExtraProps } from 'airbnb-prop-types';
import moment from 'moment';
import cx from 'classnames';
import { DayPickerPhrases } from '../defaultPhrases';
import getPhrasePropTypes from '../utils/getPhrasePropTypes';
import OutsideClickHandler from './OutsideClickHandler';
import CalendarMonthGrid from './CalendarMonthGrid';
import DayPickerNavigation from './DayPickerNavigation';
import getTransformStyles from '../utils/getTransformStyles';
import ScrollableOrientationShape from '../shapes/ScrollableOrientationShape';
import {
HORIZONTAL_ORIENTATION,
VERTICAL_ORIENTATION,
VERTICAL_SCROLLABLE,
} from '../../constants';
const CALENDAR_MONTH_WIDTH = 300;
const DAY_PICKER_PADDING = 9;
const MONTH_PADDING = 23;
const PREV_TRANSITION = 'prev';
const NEXT_TRANSITION = 'next';
const propTypes = forbidExtraProps({
// calendar presentation props
enableOutsideDays: PropTypes.bool,
numberOfMonths: PropTypes.number,
orientation: ScrollableOrientationShape,
withPortal: PropTypes.bool,
onOutsideClick: PropTypes.func,
hidden: PropTypes.bool,
initialVisibleMonth: PropTypes.func,
// navigation props
navPrev: PropTypes.node,
navNext: PropTypes.node,
onPrevMonthClick: PropTypes.func,
onNextMonthClick: PropTypes.func,
// day props
modifiers: PropTypes.object,
renderDay: PropTypes.func,
onDayClick: PropTypes.func,
onDayMouseEnter: PropTypes.func,
onDayMouseLeave: PropTypes.func,
// internationalization
monthFormat: PropTypes.string,
phrases: PropTypes.shape(getPhrasePropTypes(DayPickerPhrases)),
});
const defaultProps = {
// calendar presentation props
enableOutsideDays: false,
numberOfMonths: 2,
orientation: HORIZONTAL_ORIENTATION,
withPortal: false,
onOutsideClick() {},
hidden: false,
initialVisibleMonth: () => moment(),
// navigation props
navPrev: null,
navNext: null,
onPrevMonthClick() {},
onNextMonthClick() {},
// day props
modifiers: {},
renderDay: null,
onDayClick() {},
onDayMouseEnter() {},
onDayMouseLeave() {},
// internationalization
monthFormat: 'MMMM YYYY',
phrases: DayPickerPhrases,
};
function applyTransformStyles(el, transform, opacity = '') {
const transformStyles = getTransformStyles(transform);
transformStyles.opacity = opacity;
Object.keys(transformStyles).forEach((styleKey) => {
// eslint-disable-next-line no-param-reassign
el.style[styleKey] = transformStyles[styleKey];
});
}
export function calculateDimension(el, axis, borderBox = false, withMargin = false) {
if (!el) {
return 0;
}
const axisStart = (axis === 'width') ? 'Left' : 'Top';
const axisEnd = (axis === 'width') ? 'Right' : 'Bottom';
// Only read styles if we need to
const style = (!borderBox || withMargin) ? window.getComputedStyle(el) : {};
// Offset includes border and padding
let size = (axis === 'width') ? el.offsetWidth : el.offsetHeight;
// Get the inner size
if (!borderBox) {
size -= (
parseFloat(style[`padding${axisStart}`]) +
parseFloat(style[`padding${axisEnd}`]) +
parseFloat(style[`border${axisStart}Width`]) +
parseFloat(style[`border${axisEnd}Width`])
);
}
// Apply margin
if (withMargin) {
size += (
parseFloat(style[`margin${axisStart}`]) +
parseFloat(style[`margin${axisEnd}`])
);
}
return size;
}
function getMonthHeight(el) {
const caption = el.querySelector('.js-CalendarMonth__caption');
const grid = el.querySelector('.js-CalendarMonth__grid');
// Need to separate out table children for FF
// Add an additional +1 for the border
return (
calculateDimension(caption, 'height', true, true) + calculateDimension(grid, 'height') + 1
);
}
export default class DayPicker extends React.Component {
constructor(props) {
super(props);
this.hasSetInitialVisibleMonth = !props.hidden;
this.state = {
currentMonth: props.hidden ? moment() : props.initialVisibleMonth(),
monthTransition: null,
translationValue: 0,
scrollableMonthMultiple: 1,
};
this.onPrevMonthClick = this.onPrevMonthClick.bind(this);
this.onNextMonthClick = this.onNextMonthClick.bind(this);
this.multiplyScrollableMonths = this.multiplyScrollableMonths.bind(this);
this.updateStateAfterMonthTransition = this.updateStateAfterMonthTransition.bind(this);
}
componentDidMount() {
if (this.isHorizontal()) {
this.adjustDayPickerHeight();
this.initializeDayPickerWidth();
}
}
componentWillReceiveProps(nextProps) {
if (!nextProps.hidden) {
if (!this.hasSetInitialVisibleMonth) {
this.hasSetInitialVisibleMonth = true;
this.setState({
currentMonth: nextProps.initialVisibleMonth(),
});
}
if (!this.dayPickerWidth && this.isHorizontal()) {
this.initializeDayPickerWidth();
this.adjustDayPickerHeight();
}
}
}
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
componentDidUpdate(prevProps, prevState) {
if (this.state.monthTransition || !this.state.currentMonth.isSame(prevState.currentMonth)) {
if (this.isHorizontal()) {
this.adjustDayPickerHeight();
}
}
}
onPrevMonthClick(e) {
if (e) e.preventDefault();
if (this.props.onPrevMonthClick) {
this.props.onPrevMonthClick(e);
}
const translationValue =
this.isVertical() ? this.getMonthHeightByIndex(0) : this.dayPickerWidth;
// The first CalendarMonth is always positioned absolute at top: 0 or left: 0
// so we need to transform it to the appropriate location before the animation.
// This behavior is because we would otherwise need a double-render in order to
// adjust the container position once we had the height the first calendar
// (ie first draw all the calendar, then in a second render, use the first calendar's
// height to position the container). Variable calendar heights, amirite? <3 Maja
this.translateFirstDayPickerForAnimation(translationValue);
this.setState({
monthTransition: PREV_TRANSITION,
translationValue,
});
}
onNextMonthClick(e) {
if (e) e.preventDefault();
if (this.props.onNextMonthClick) {
this.props.onNextMonthClick(e);
}
const translationValue =
this.isVertical() ? -this.getMonthHeightByIndex(1) : -this.dayPickerWidth;
this.setState({
monthTransition: NEXT_TRANSITION,
translationValue,
});
}
getMonthHeightByIndex(i) {
return getMonthHeight(this.transitionContainer.querySelectorAll('.CalendarMonth')[i]);
}
multiplyScrollableMonths(e) {
if (e) e.preventDefault();
this.setState({
scrollableMonthMultiple: this.state.scrollableMonthMultiple + 1,
});
}
isHorizontal() {
return this.props.orientation === HORIZONTAL_ORIENTATION;
}
isVertical() {
return this.props.orientation === VERTICAL_ORIENTATION ||
this.props.orientation === VERTICAL_SCROLLABLE;
}
initializeDayPickerWidth() {
this.dayPickerWidth = calculateDimension(
// eslint-disable-next-line react/no-find-dom-node
ReactDOM.findDOMNode(this.calendarMonthGrid).querySelector('.CalendarMonth'),
'width',
true,
);
}
updateStateAfterMonthTransition() {
const { currentMonth, monthTransition } = this.state;
let newMonth = currentMonth;
if (monthTransition === PREV_TRANSITION) {
newMonth = currentMonth.clone().subtract(1, 'month');
} else if (monthTransition === NEXT_TRANSITION) {
newMonth = currentMonth.clone().add(1, 'month');
}
// clear the previous transforms
applyTransformStyles(
// eslint-disable-next-line react/no-find-dom-node
ReactDOM.findDOMNode(this.calendarMonthGrid).querySelector('.CalendarMonth'),
'none',
);
this.setState({
currentMonth: newMonth,
monthTransition: null,
translationValue: 0,
});
}
adjustDayPickerHeight() {
const heights = [];
Array.prototype.forEach.call(this.transitionContainer.querySelectorAll('.CalendarMonth'),
(el) => {
if (el.getAttribute('data-visible') === 'true') {
heights.push(getMonthHeight(el));
}
},
);
const newMonthHeight = Math.max(...heights) + MONTH_PADDING;
if (newMonthHeight !== calculateDimension(this.transitionContainer, 'height')) {
this.monthHeight = newMonthHeight;
this.transitionContainer.style.height = `${newMonthHeight}px`;
}
}
translateFirstDayPickerForAnimation(translationValue) {
const transformType = this.isVertical() ? 'translateY' : 'translateX';
const transformValue = `${transformType}(-${translationValue}px)`;
applyTransformStyles(
this.transitionContainer.querySelector('.CalendarMonth'),
transformValue,
1,
);
}
renderNavigation() {
const {
navPrev,
navNext,
orientation,
} = this.props;
let onNextMonthClick;
if (orientation === VERTICAL_SCROLLABLE) {
onNextMonthClick = this.multiplyScrollableMonths;
} else {
onNextMonthClick = this.onNextMonthClick;
}
return (
<DayPickerNavigation
onPrevMonthClick={this.onPrevMonthClick}
onNextMonthClick={onNextMonthClick}
navPrev={navPrev}
navNext={navNext}
orientation={orientation}
/>
);
}
renderWeekHeader(index) {
const horizontalStyle = {
left: index * CALENDAR_MONTH_WIDTH,
};
const style = this.isHorizontal() ? horizontalStyle : {};
const header = [];
for (let i = 0; i < 7; i += 1) {
header.push(
<li key={i}>
<small>{moment().weekday(i).format('dd')}</small>
</li>,
);
}
return (
<div
className="DayPicker__week-header"
key={`week-${index}`}
style={style}
>
<ul>
{header}
</ul>
</div>
);
}
render() {
const {
currentMonth,
monthTransition,
translationValue,
scrollableMonthMultiple,
} = this.state;
const {
enableOutsideDays,
numberOfMonths,
orientation,
modifiers,
withPortal,
onDayClick,
onDayMouseEnter,
onDayMouseLeave,
renderDay,
onOutsideClick,
monthFormat,
} = this.props;
const numOfWeekHeaders = this.isVertical() ? 1 : numberOfMonths;
const weekHeaders = [];
for (let i = 0; i < numOfWeekHeaders; i += 1) {
weekHeaders.push(this.renderWeekHeader(i));
}
let firstVisibleMonthIndex = 1;
if (monthTransition === PREV_TRANSITION) {
firstVisibleMonthIndex -= 1;
} else if (monthTransition === NEXT_TRANSITION) {
firstVisibleMonthIndex += 1;
}
const verticalScrollable = this.props.orientation === VERTICAL_SCROLLABLE;
const dayPickerClassNames = cx('DayPicker', {
'DayPicker--horizontal': this.isHorizontal(),
'DayPicker--vertical': this.isVertical(),
'DayPicker--vertical-scrollable': verticalScrollable,
'DayPicker--portal': withPortal,
});
const transitionContainerClasses = cx('transition-container', {
'transition-container--horizontal': this.isHorizontal(),
'transition-container--vertical': this.isVertical(),
});
const horizontalWidth = (CALENDAR_MONTH_WIDTH * numberOfMonths) + (2 * DAY_PICKER_PADDING);
// this is a kind of made-up value that generally looks good. we'll
// probably want to let the user set this explicitly.
const verticalHeight = 1.75 * CALENDAR_MONTH_WIDTH;
const dayPickerStyle = {
width: this.isHorizontal() && horizontalWidth,
// These values are to center the datepicker (approximately) on the page
marginLeft: this.isHorizontal() && withPortal && -horizontalWidth / 2,
marginTop: this.isHorizontal() && withPortal && -CALENDAR_MONTH_WIDTH / 2,
};
const transitionContainerStyle = {
width: this.isHorizontal() && horizontalWidth,
height: this.isVertical() && !verticalScrollable && !withPortal && verticalHeight,
};
const isCalendarMonthGridAnimating = monthTransition !== null;
const transformType = this.isVertical() ? 'translateY' : 'translateX';
const transformValue = `${transformType}(${translationValue}px)`;
return (
<div className={dayPickerClassNames} style={dayPickerStyle} >
<OutsideClickHandler onOutsideClick={onOutsideClick}>
{!verticalScrollable && this.renderNavigation()}
<div className="DayPicker__week-headers">
{weekHeaders}
</div>
<div
className={transitionContainerClasses}
ref={(ref) => { this.transitionContainer = ref; }}
style={transitionContainerStyle}
>
<CalendarMonthGrid
ref={(ref) => { this.calendarMonthGrid = ref; }}
transformValue={transformValue}
enableOutsideDays={enableOutsideDays}
firstVisibleMonthIndex={firstVisibleMonthIndex}
initialMonth={currentMonth}
isAnimating={isCalendarMonthGridAnimating}
modifiers={modifiers}
orientation={orientation}
numberOfMonths={numberOfMonths * scrollableMonthMultiple}
onDayClick={onDayClick}
onDayMouseEnter={onDayMouseEnter}
onDayMouseLeave={onDayMouseLeave}
renderDay={renderDay}
onMonthTransitionEnd={this.updateStateAfterMonthTransition}
monthFormat={monthFormat}
/>
{verticalScrollable && this.renderNavigation()}
</div>
</OutsideClickHandler>
</div>
);
}
}
DayPicker.propTypes = propTypes;
DayPicker.defaultProps = defaultProps;