-
Notifications
You must be signed in to change notification settings - Fork 328
/
CalendarStrip.js
637 lines (574 loc) · 21 KB
/
CalendarStrip.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
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
/**
* Created by bogdanbegovic on 8/20/16.
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Animated, PixelRatio } from "react-native";
import moment from "moment";
import CalendarHeader from "./CalendarHeader";
import CalendarDay from "./CalendarDay";
import WeekSelector from "./WeekSelector";
import Scroller from "./Scroller";
import styles from "./Calendar.style.js";
/*
* Class CalendarStrip that is representing the whole calendar strip and contains CalendarDay elements
*
*/
class CalendarStrip extends Component {
static propTypes = {
style: PropTypes.any,
innerStyle: PropTypes.any,
calendarColor: PropTypes.string,
numDaysInWeek: PropTypes.number,
scrollable: PropTypes.bool,
scrollerPaging: PropTypes.bool,
externalScrollView: PropTypes.func,
startingDate: PropTypes.any,
selectedDate: PropTypes.any,
onDateSelected: PropTypes.func,
onWeekChanged: PropTypes.func,
onWeekScrollStart: PropTypes.func,
onWeekScrollEnd: PropTypes.func,
onHeaderSelected: PropTypes.func,
updateWeek: PropTypes.bool,
useIsoWeekday: PropTypes.bool,
minDate: PropTypes.any,
maxDate: PropTypes.any,
datesWhitelist: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
datesBlacklist: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
headerText: PropTypes.string,
markedDates: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
scrollToOnSetSelectedDate: PropTypes.bool,
showMonth: PropTypes.bool,
showDayName: PropTypes.bool,
showDayNumber: PropTypes.bool,
showDate: PropTypes.bool,
dayComponent: PropTypes.any,
leftSelector: PropTypes.any,
rightSelector: PropTypes.any,
iconLeft: PropTypes.any,
iconRight: PropTypes.any,
iconStyle: PropTypes.any,
iconLeftStyle: PropTypes.any,
iconRightStyle: PropTypes.any,
iconContainer: PropTypes.any,
maxDayComponentSize: PropTypes.number,
minDayComponentSize: PropTypes.number,
dayComponentHeight: PropTypes.number,
responsiveSizingOffset: PropTypes.number,
calendarHeaderContainerStyle: PropTypes.any,
calendarHeaderStyle: PropTypes.any,
calendarHeaderFormat: PropTypes.string,
calendarHeaderPosition: PropTypes.oneOf(["above", "below"]),
calendarAnimation: PropTypes.object,
daySelectionAnimation: PropTypes.object,
customDatesStyles: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
dateNameStyle: PropTypes.any,
dateNumberStyle: PropTypes.any,
dayContainerStyle: PropTypes.any,
weekendDateNameStyle: PropTypes.any,
weekendDateNumberStyle: PropTypes.any,
highlightDateNameStyle: PropTypes.any,
highlightDateNumberStyle: PropTypes.any,
highlightDateNumberContainerStyle: PropTypes.any,
highlightDateContainerStyle: PropTypes.any,
disabledDateNameStyle: PropTypes.any,
disabledDateNumberStyle: PropTypes.any,
markedDatesStyle: PropTypes.object,
disabledDateOpacity: PropTypes.number,
styleWeekend: PropTypes.bool,
locale: PropTypes.object,
shouldAllowFontScaling: PropTypes.bool,
useNativeDriver: PropTypes.bool,
upperCaseDays: PropTypes.bool,
};
static defaultProps = {
numDaysInWeek: 7,
useIsoWeekday: true,
showMonth: true,
showDate: true,
updateWeek: true,
iconLeft: require("./img/left-arrow-black.png"),
iconRight: require("./img/right-arrow-black.png"),
calendarHeaderFormat: "MMMM YYYY",
calendarHeaderPosition: "above",
datesWhitelist: undefined,
datesBlacklist: undefined,
disabledDateOpacity: 0.3,
customDatesStyles: [],
responsiveSizingOffset: 0,
innerStyle: { flex: 1 },
maxDayComponentSize: 80,
minDayComponentSize: 10,
shouldAllowFontScaling: true,
markedDates: [],
useNativeDriver: true,
scrollToOnSetSelectedDate: true,
upperCaseDays: true,
};
constructor(props) {
super(props);
this.numDaysScroll = 366; // prefer even number divisible by 3
if (props.locale) {
if (props.locale.name && props.locale.config) {
moment.updateLocale(props.locale.name, props.locale.config);
} else {
throw new Error(
"Locale prop is not in the correct format. \b Locale has to be in form of object, with params NAME and CONFIG!"
);
}
}
const startingDate = this.getInitialStartingDate();
const selectedDate = this.setLocale(this.props.selectedDate);
this.state = {
startingDate,
selectedDate,
datesList: [],
dayComponentWidth: 0,
height: 0,
monthFontSize: 0,
selectorSize: 0,
numVisibleDays: props.numDaysInWeek,
};
this.animations = [];
this.layout = {};
}
//Receiving props and set date states, minimizing state updates.
componentDidUpdate(prevProps, prevState) {
let startingDate = {};
let selectedDate = {};
let days = {};
let updateState = false;
if (!this.compareDates(prevProps.startingDate, this.props.startingDate) ||
!this.compareDates(prevProps.selectedDate, this.props.selectedDate) ||
prevProps.datesBlacklist !== this.props.datesBlacklist ||
prevProps.datesWhitelist !== this.props.datesWhitelist ||
prevProps.markedDates !== this.props.markedDates ||
prevProps.customDatesStyles !== this.props.customDatesStyles )
{
// Protect against undefined startingDate prop
let _startingDate = this.props.startingDate || this.state.startingDate;
startingDate = { startingDate: this.setLocale(_startingDate)};
selectedDate = { selectedDate: this.setLocale(this.props.selectedDate)};
days = this.createDays(startingDate.startingDate, selectedDate.selectedDate);
updateState = true;
}
if (updateState) {
this.setState({...startingDate, ...selectedDate, ...days });
}
}
shouldComponentUpdate(nextProps, nextState) {
// Extract selector icons since JSON.stringify fails on React component circular refs
let _nextProps = Object.assign({}, nextProps);
let _props = Object.assign({}, this.props);
delete _nextProps.leftSelector;
delete _nextProps.rightSelector;
delete _props.leftSelector;
delete _props.rightSelector;
return (
JSON.stringify(this.state) !== JSON.stringify(nextState) ||
JSON.stringify(_props) !== JSON.stringify(_nextProps) ||
this.props.leftSelector !== nextProps.leftSelector ||
this.props.rightSelector !== nextProps.rightSelector
);
}
// Check whether two datetimes are of the same value. Supports Moment date,
// JS date, or ISO 8601 strings.
// Returns true if the datetimes values are the same; false otherwise.
compareDates = (date1, date2) => {
if (date1 && date1.valueOf && date2 && date2.valueOf)
{
return moment(date1).isSame(date2, "day");
} else {
return JSON.stringify(date1) === JSON.stringify(date2);
}
}
//Function that checks if the locale is passed to the component and sets it to the passed date
setLocale = date => {
let _date = date && moment(date);
if (_date) {
_date.set({ hour: 12}); // keep date the same regardless of timezone shifts
if (this.props.locale) {
_date = _date.locale(this.props.locale.name);
}
}
return _date;
}
getInitialStartingDate = () => {
if (this.props.startingDate) {
return this.setLocale(this.props.startingDate);
} else {
// Fallback when startingDate isn't provided. However selectedDate
// may also be undefined, defaulting to today's date.
let date = this.setLocale(moment(this.props.selectedDate));
return this.props.useIsoWeekday ? date.startOf("isoweek") : date;
}
}
//Set startingDate to the previous week
getPreviousWeek = () => {
if (this.props.scrollable) {
this.scroller.scrollLeft();
return;
}
this.animations = [];
const previousWeekStartDate = this.state.startingDate.clone().subtract(1, "w");
const days = this.createDays(previousWeekStartDate);
this.setState({ startingDate: previousWeekStartDate, ...days });
}
//Set startingDate to the next week
getNextWeek = () => {
if (this.props.scrollable) {
this.scroller.scrollRight();
return;
}
this.animations = [];
const nextWeekStartDate = this.state.startingDate.clone().add(1, "w");
const days = this.createDays(nextWeekStartDate);
this.setState({ startingDate: nextWeekStartDate, ...days });
}
// Set the current visible week to the selectedDate
// When date param is undefined, an update always occurs (e.g. initialize)
updateWeekStart = (newStartDate, originalStartDate = this.state.startingDate) => {
if (!this.props.updateWeek) {
return originalStartDate;
}
let startingDate = moment(newStartDate).startOf("day");
let daysDiff = startingDate.diff(originalStartDate.startOf("day"), "days");
if (daysDiff === 0) {
return originalStartDate;
}
let addOrSubtract = daysDiff > 0 ? "add" : "subtract";
let adjustWeeks = daysDiff / 7;
adjustWeeks =
adjustWeeks > 0
? Math.floor(adjustWeeks)
: Math.ceil(Math.abs(adjustWeeks));
startingDate = originalStartDate[addOrSubtract](adjustWeeks, "w");
return this.setLocale(startingDate);
}
// updateWeekView allows external callers to update the visible week.
updateWeekView = date => {
if (this.props.scrollable) {
this.scroller.scrollToDate(date);
return;
}
this.animations = [];
let startingDate = moment(date);
startingDate = this.props.useIsoWeekday ? startingDate.startOf("isoweek") : startingDate;
const days = this.createDays(startingDate);
this.setState({startingDate, ...days});
}
//Handling press on date/selecting date
onDateSelected = selectedDate => {
let newState;
if (this.props.scrollable) {
newState = { selectedDate };
}
else {
newState = {
selectedDate,
...this.createDays(this.state.startingDate, selectedDate),
};
}
this.setState(() => newState);
const _selectedDate = selectedDate && selectedDate.clone();
this.props.onDateSelected && this.props.onDateSelected(_selectedDate);
}
// Get the currently selected date (Moment JS object)
getSelectedDate = () => {
if (!this.state.selectedDate || this.state.selectedDate.valueOf() === 0) {
return; // undefined (no date has been selected yet)
}
return this.state.selectedDate;
}
// Set the selected date. To clear the currently selected date, pass in 0.
setSelectedDate = date => {
let mDate = moment(date);
this.onDateSelected(mDate);
if (this.props.scrollToOnSetSelectedDate) {
// Scroll to selected date, centered in the week
const scrolledDate = moment(mDate);
scrolledDate.subtract(Math.floor(this.props.numDaysInWeek / 2), "days");
this.scroller.scrollToDate(scrolledDate);
}
}
// Gather animations from each day. Sequence animations must be started
// together to work around bug in RN Animated with individual starts.
registerAnimation = animation => {
this.animations.push(animation);
if (this.animations.length >= this.state.days.length) {
if (this.props.calendarAnimation?.type.toLowerCase() === "sequence") {
Animated.sequence(this.animations).start();
}
else {
Animated.parallel(this.animations).start();
}
}
}
// Responsive sizing based on container width.
// Debounce to prevent rapid succession of onLayout calls from thrashing.
onLayout = event => {
if (event.nativeEvent.layout.width === this.layout.width) {
return;
}
if (this.onLayoutTimer) {
clearTimeout(this.onLayoutTimer);
}
this.layout = event.nativeEvent.layout;
this.onLayoutTimer = setTimeout(() => {
this.onLayoutDebounce(this.layout);
this.onLayoutTimer = null;
}, 100);
}
onLayoutDebounce = layout => {
const {
numDaysInWeek,
responsiveSizingOffset,
maxDayComponentSize,
minDayComponentSize,
showMonth,
showDate,
scrollable,
dayComponentHeight,
} = this.props;
let csWidth = PixelRatio.roundToNearestPixel(layout.width);
let dayComponentWidth = csWidth / numDaysInWeek + responsiveSizingOffset;
dayComponentWidth = Math.min(dayComponentWidth, maxDayComponentSize);
dayComponentWidth = Math.max(dayComponentWidth, minDayComponentSize);
let numVisibleDays = numDaysInWeek;
let marginHorizontal;
if (scrollable) {
numVisibleDays = Math.floor(csWidth / dayComponentWidth);
// Scroller requires spacing between days
marginHorizontal = Math.round(dayComponentWidth * 0.05);
dayComponentWidth = Math.round(dayComponentWidth * 0.9);
}
let monthFontSize = Math.round(dayComponentWidth / 3.2);
let selectorSize = Math.round(dayComponentWidth / 2.5);
let height = showMonth ? monthFontSize : 0;
height += showDate ? dayComponentHeight || dayComponentWidth : 0;
selectorSize = Math.min(selectorSize, height);
this.setState({
dayComponentWidth,
dayComponentHeight: dayComponentHeight || dayComponentWidth,
height,
monthFontSize,
selectorSize,
marginHorizontal,
numVisibleDays,
},
() => this.setState( {...this.createDays(this.state.startingDate)} ));
}
getItemLayout = (data, index) => {
const length = this.state.height * 1.05; //include margin
return { length, offset: length * index, index }
}
updateMonthYear = (weekStartDate, weekEndDate) => {
this.setState({
weekStartDate,
weekEndDate,
});
}
createDayProps = selectedDate => {
return {
selectedDate,
onDateSelected: this.onDateSelected,
scrollable: this.props.scrollable,
datesWhitelist: this.props.datesWhitelist,
datesBlacklist: this.props.datesBlacklist,
showDayName: this.props.showDayName,
showDayNumber: this.props.showDayNumber,
dayComponent: this.props.dayComponent,
calendarColor: this.props.calendarColor,
dateNameStyle: this.props.dateNameStyle,
dateNumberStyle: this.props.dateNumberStyle,
dayContainerStyle: this.props.dayContainerStyle,
weekendDateNameStyle: this.props.weekendDateNameStyle,
weekendDateNumberStyle: this.props.weekendDateNumberStyle,
highlightDateNameStyle: this.props.highlightDateNameStyle,
highlightDateNumberStyle: this.props.highlightDateNumberStyle,
highlightDateNumberContainerStyle: this.props.highlightDateNumberContainerStyle,
highlightDateContainerStyle: this.props.highlightDateContainerStyle,
disabledDateNameStyle: this.props.disabledDateNameStyle,
disabledDateNumberStyle: this.props.disabledDateNumberStyle,
markedDatesStyle: this.props.markedDatesStyle,
disabledDateOpacity: this.props.disabledDateOpacity,
styleWeekend: this.props.styleWeekend,
calendarAnimation: this.props.calendarAnimation,
registerAnimation: this.registerAnimation,
daySelectionAnimation: this.props.daySelectionAnimation,
useNativeDriver: this.props.useNativeDriver,
customDatesStyles: this.props.customDatesStyles,
markedDates: this.props.markedDates,
height: this.state.dayComponentHeight,
width: this.state.dayComponentWidth,
marginHorizontal: this.state.marginHorizontal,
allowDayTextScaling: this.props.shouldAllowFontScaling,
upperCaseDays: this.props.upperCaseDays,
}
}
createDays = (startingDate, selectedDate = this.state.selectedDate) => {
const {
numDaysInWeek,
useIsoWeekday,
scrollable,
minDate,
maxDate,
onWeekChanged,
} = this.props;
let _startingDate = startingDate;
let days = [];
let datesList = [];
let numDays = numDaysInWeek;
let initialScrollerIndex;
if (scrollable) {
numDays = this.numDaysScroll;
// Center start date in scroller.
_startingDate = startingDate.clone().subtract(numDays/2, "days");
if (minDate && _startingDate.isBefore(minDate, "day")) {
_startingDate = moment(minDate);
}
}
for (let i = 0; i < numDays; i++) {
let date;
if (useIsoWeekday) {
// isoWeekday starts from Monday
date = this.setLocale(_startingDate.clone().isoWeekday(i + 1));
} else {
date = this.setLocale(_startingDate.clone().add(i, "days"));
}
if (scrollable) {
if (maxDate && date.isAfter(maxDate, "day")) {
break;
}
if (date.isSame(startingDate, "day")) {
initialScrollerIndex = i;
}
datesList.push({date});
}
else {
days.push(this.renderDay({
date,
key: date.format("YYYY-MM-DD"),
...this.createDayProps(selectedDate),
}));
datesList.push({date});
}
}
const newState = {
days,
datesList,
initialScrollerIndex,
};
if (!scrollable) {
const weekStartDate = datesList[0].date;
const weekEndDate = datesList[this.state.numVisibleDays - 1].date;
newState.weekStartDate = weekStartDate;
newState.weekEndDate = weekEndDate;
const _weekStartDate = weekStartDate && weekStartDate.clone();
const _weekEndDate = weekEndDate && weekEndDate.clone();
onWeekChanged && onWeekChanged(_weekStartDate, _weekEndDate);
}
// else Scroller sets weekStart/EndDate and fires onWeekChanged.
return newState;
}
renderDay(props) {
return (
<CalendarDay {...props} />
);
}
renderHeader() {
return ( this.props.showMonth &&
<CalendarHeader
calendarHeaderFormat={this.props.calendarHeaderFormat}
calendarHeaderContainerStyle={this.props.calendarHeaderContainerStyle}
calendarHeaderStyle={this.props.calendarHeaderStyle}
onHeaderSelected={this.props.onHeaderSelected}
weekStartDate={this.state.weekStartDate}
weekEndDate={this.state.weekEndDate}
fontSize={this.state.monthFontSize}
allowHeaderTextScaling={this.props.shouldAllowFontScaling}
headerText={this.props.headerText}
/>
);
}
renderWeekView(days) {
if (this.props.scrollable && this.state.datesList.length) {
return (
<Scroller
ref={scroller => this.scroller = scroller}
data={this.state.datesList}
pagingEnabled={this.props.scrollerPaging}
renderDay={this.renderDay}
renderDayParams={{...this.createDayProps(this.state.selectedDate)}}
maxSimultaneousDays={this.numDaysScroll}
initialRenderIndex={this.state.initialScrollerIndex}
minDate={this.props.minDate}
maxDate={this.props.maxDate}
updateMonthYear={this.updateMonthYear}
onWeekChanged={this.props.onWeekChanged}
onWeekScrollStart={this.props.onWeekScrollStart}
onWeekScrollEnd={this.props.onWeekScrollEnd}
externalScrollView={this.props.externalScrollView}
/>
);
}
return days;
}
render() {
// calendarHeader renders above or below of the dates & left/right selectors if dates are shown.
// However if dates are hidden, the header shows between the left/right selectors.
return (
<View
style={[
styles.calendarContainer,
{ backgroundColor: this.props.calendarColor },
this.props.style
]}
>
<View style={[this.props.innerStyle, { height: this.state.height }]}>
{this.props.showDate && this.props.calendarHeaderPosition === "above" &&
this.renderHeader()
}
<View style={styles.datesStrip}>
<WeekSelector
controlDate={this.props.minDate}
iconComponent={this.props.leftSelector}
iconContainerStyle={this.props.iconContainer}
iconInstanceStyle={this.props.iconLeftStyle}
iconStyle={this.props.iconStyle}
imageSource={this.props.iconLeft}
onPress={this.getPreviousWeek}
weekStartDate={this.state.weekStartDate}
weekEndDate={this.state.weekEndDate}
size={this.state.selectorSize}
/>
<View onLayout={this.onLayout} style={styles.calendarDates}>
{this.props.showDate ? (
this.renderWeekView(this.state.days)
) : (
this.renderHeader()
)}
</View>
<WeekSelector
controlDate={this.props.maxDate}
iconComponent={this.props.rightSelector}
iconContainerStyle={this.props.iconContainer}
iconInstanceStyle={this.props.iconRightStyle}
iconStyle={this.props.iconStyle}
imageSource={this.props.iconRight}
onPress={this.getNextWeek}
weekStartDate={this.state.weekStartDate}
weekEndDate={this.state.weekEndDate}
size={this.state.selectorSize}
/>
</View>
{this.props.showDate && this.props.calendarHeaderPosition === "below" &&
this.renderHeader()
}
</View>
</View>
);
}
}
export default CalendarStrip;