-
Notifications
You must be signed in to change notification settings - Fork 6
/
px-calendar-picker.html
563 lines (503 loc) · 18.5 KB
/
px-calendar-picker.html
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
<!--
Copyright (c) 2018, General Electric
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<link rel="import" href="../polymer/polymer.html" />
<link rel="import" href="px-calendar-cell.html" />
<link rel="import" href="../px-datetime-common/px-datetime-range-behavior.html" />
<link rel="import" href="../px-datetime-common/px-datetime-behavior.html" />
<link rel="import" href="../px-icon-set/px-icon-set-navigation.html" />
<link rel="import" href="../px-icon-set/px-icon.html" />
<link rel="import" href="css/px-calendar-picker-styles.html" />
<!--
All datetime components rely on [Moment.js](https://momentjs.com/) and [Moment Timezone](https://momentjs.com/timezone/).
This element renders a calendar for a given decade, year, or month, based on `display-mode` and `base-date`.
A user can either select a range of dates or a single date, based on the `prevent-range-selection` property.
User-selected values can be read out from the `range` or `single-selected-date` properties accordingly.
A single date or range can be pre-set by manually setting either `from-moment` (single date) or `from-moment` and `to-moment` (range) using valid Moment.js objects.
### Usage
<px-calendar-picker
from-moment={...}
prevent-range-selection
single-selected-date={...}>
</px-calendar-picker>
<px-calendar-picker
from-moment={...}
to-moment={...}
range={...}>
</px-calendar-picker>
### Styling
The following custom properties are available for styling:
Custom property | Description
:----------------|:-------------
`--px-calendar-text-color` | Default text color for dates on the calendar
`--px-calendar-text-color--hover` | Text color for dates when hovered
`--px-calendar-text-color--selected` | Text color for dates when selected
`--px-calendar-title-color` | Color for the title and arrows
`--px-calendar-sub-labels--text-color` | Text color for days of the week
`--px-calendar-today-border` | Border color for today's date
`--px-calendar-background-color--hover` | Background color for dates when hovered
`--px-calendar-background-color--pressed` | Background color for dates when pressed
`--px-calendar-background-color--selected` | Background color for dates when selected
`--px-calendar-alt-background-color` | Background color for the range between start and end dates
@element px-calendar-picker
@homepage index.html
@demo index.html
-->
<dom-module id="px-calendar-picker">
<template>
<style include="px-calendar-picker-styles"></style>
<div class$="{{_getTableClass(shrink)}}" id="calendar">
<!-- Caption: month+year and previous/next arrows -->
<div class="caption">
<button type="button" on-tap="_onPrevious" class="actionable actionable--action title-color nextLastBtn">
<template is="dom-if" if="{{!hidePreviousButton}}">
<px-icon icon="px-nav:back" class="arrow"></px-icon>
</template>
</button>
<button on-tap="_onNextDisplayMode" class="actionable actionable--action title-color">[[_title]]</button>
<button id="btnNextMonth" type="button" on-tap="_onNext" class="actionable actionable--action title-color nextLastBtn">
<template is="dom-if" if="{{!hideNextButton}}">
<px-icon icon="px-nav:next" class="arrow"></px-icon>
</template>
</button>
</div>
<!-- Actual Calendar -->
<template is="dom-if" if="{{_isDayMode(_currentDisplayMode)}}">
<div class="tr">
<!-- Sunday -> Saturday -->
<template is="dom-repeat" items="{{daysOfTheWeek}}" as="dayOfTheWeek">
<div class="th caps">[[dayOfTheWeek]]</div>
</template>
</div>
</template>
<template is="dom-repeat" items="{{_valuesDisplayed}}" as="week" strip-whitespace>
<div class="tr">
<template is="dom-repeat" items="{{week}}" as="date" strip-whitespace>
<div class="td">
<px-calendar-cell
display-date="{{date}}"
from-moment="[[fromMoment]]"
time-zone="[[timeZone]]"
to-moment="[[toMoment]]"
block-future-dates="{{blockFutureDates}}"
block-past-dates="{{blockPastDates}}"
display-mode="{{_currentDisplayMode}}"
block-dates-after="[[maxDate]]"
block-dates-before="[[minDate]]">
</px-calendar-cell>
</div>
</template>
</div>
</template>
</div>
</template>
</dom-module>
<script>
Polymer({
is: 'px-calendar-picker',
behaviors: [PxDatetimeBehavior.Range],
properties: {
/**
* Moment object used as the base for the calendar (to decide which month to display)
*/
baseDate: {
type: Object,
notify: true,
value: function () {
return Px.moment.tz(Px.moment(), this.timeZone);
},
observer: '_baseDateChanged'
},
_oldBaseDate: {
type: Object
},
/**
* What the calendar should display:
* - 'day': calendar displays all days of a month
* - 'month': calendar displays all months in a year
* - 'year': calendar displays a 10 years range
*/
displayMode: {
type: String,
value: 'day',
observer: '_displayModeChanged'
},
/**
* What the calendar should display:
* - 'day': calendar displays all days of a month
* - 'month': calendar displays all months in a year
* - 'year': calendar displays a 10 year range
*
* Can internally change when the user clicks the title and changes the mode
*/
_currentDisplayMode: {
type: String,
observer: '_currentDisplayModeChanged',
value: 'day'
},
/**
* (optional)
*
* By default, the calendar will allow the user to select a date range by clicking on two
* different dates. If this property is set, the user will only be able to select a single date
* each time she clicks.
*
* If this property is set, then the 'singleSelectedDate' property will reflect the selected date. Otherwise
* the 'range' property should be observed and will reflect the selected date range.
*/
preventRangeSelection: {
type: Boolean,
value: false
},
/**
* (optional)
*
* Hides the 'previous' button on the calendar.
*/
hidePreviousButton: {
type: Boolean,
value: false
},
/**
* (optional)
*
* Hides the 'next' button on the calendar.
*/
hideNextButton: {
type: Boolean,
value: false
},
/**
* (optional)
*
* If set, allows the calendar picker to shrink rather than have a constant size.
* Typically the height would shrink when choosing months or years
*/
shrink: {
type: Boolean,
value: false
},
/*
* Whether the calendar picker is currently at the selection level: showing days
* in day mode, choosing month in month mode or showing years in year mode.
*/
isAtSelectionLevel: {
type: Boolean,
computed: '_isAtSelectionLevel(_currentDisplayMode, displayMode)'
},
/**
* The values currently displayed in the calendar cells, days, months or years
*
* @default []
*/
_valuesDisplayed: {
type: Array,
value: function () { return []; }
},
/**
*/
waitToFire: {
type: Boolean,
value: false
},
/**
* Title string for localization
*/
_title: {
type: String
}
},
observers: [
'_renderCurrent(_currentDisplayMode)',
'_localeChanged(language)',
'_getCurrentTitle(_currentDisplayMode, baseDate)',
'_timeZoneChanged(timeZone)'
],
ready: function () {
this.daysOfTheWeek = this._getDaysOfTheWeek();
var handler = this._cellClicked.bind(this);
this.addEventListener('px-cell-date-selected', handler);
this.toMoment = null;
this.fromMoment = null;
},
_localeChanged: function () {
if (Px.moment && this.baseDate && this._currentDisplayMode) {
this.daysOfTheWeek = this._getDaysOfTheWeek();
//reset base date so it picks up new moment locale
//get moment locale and update the base date
this.set('baseDate', this.baseDate.locale(Px.moment.locale()));
this._getCurrentTitle(this._currentDisplayMode, this.baseDate);
this._renderCurrent();
}
},
_timeZoneChanged: function () {
if(this.baseDate) {
this.set('baseDate', Px.moment.tz(this.baseDate, this.timeZone));
}
},
_getTableClass: function (shrink) {
var base = "table table--no-cells text--center ";
if (!shrink) {
base += "constantSize "
}
return base;
},
_cellClicked: function (e) {
var momentDate = e.detail,
copy = e.detail.clone();
if (this._currentDisplayMode === 'year') {
if (this.displayMode === 'year') {
//we want to select this year.
this._selectDate(momentDate);
this.fire('px-date-selected', copy);
}
else {
//go to 'month' mode
this.set('baseDate', momentDate);
this.set('_currentDisplayMode', 'month');
e.stopPropagation();
}
} else if (this._currentDisplayMode === 'month') {
if (this.displayMode === 'month') {
//we want to select this month.
this._selectDate(momentDate);
this.fire('px-date-selected', copy);
}
else {
//go to 'day' mode
this.set('baseDate', momentDate);
this.set('_currentDisplayMode', 'day');
e.stopPropagation();
}
} else {
this._selectDate(momentDate);
this.fire('px-date-selected', copy);
}
},
_displayModeChanged: function () {
if(this.displayMode !== undefined) {
this.set('_currentDisplayMode', this.displayMode);
}
},
_currentDisplayModeChanged: function () {
if (this._currentDisplayMode === 'year') {
//make sure we display the beginning of the decade
var year = this.baseDate.year();
for (var i = 0; i < 10; i++) {
if (((year - i) % 10) === 1) {
break;
}
}
this.set('baseDate', this.baseDate.clone().subtract(i, 'years'));
} else {
this._renderCurrent();
}
},
_isDayMode: function (_currentDisplayMode) {
return _currentDisplayMode === 'day';
},
/**
* Change the display mode after the user clicked the title
*/
_onNextDisplayMode: function () {
if (this._currentDisplayMode === 'day') {
this.set('_currentDisplayMode', 'month');
} else if (this._currentDisplayMode === 'month') {
this.set('_currentDisplayMode', 'year');
}
//else year already, do nothing
},
_getCurrentTitle: function (_currentDisplayMode, baseDate) {
if(_currentDisplayMode === undefined || baseDate === undefined || baseDate === null) {
return;
} else if (_currentDisplayMode === 'day') {
this.set('_title', baseDate.format('MMMM') + ' ' + baseDate.format('YYYY'));
} else if (_currentDisplayMode === 'month') {
this.set('_title', baseDate.format('YYYY'));
} else {
this.set('_title', baseDate.format('YYYY') + ' - ' + baseDate.clone().add(9, 'years').format('YYYY'));
}
},
_getDaysOfTheWeek: function () {
var day = Px.moment().startOf('week');
var daysOfWeek = [];
for (var i = 0; i < 7; i++) {
daysOfWeek.push(day.format('dd'));
day.add(1, 'days');
}
return daysOfWeek;
},
_renderCurrent: function (_currentDisplayMode) {
var newValues;
if (this._currentDisplayMode === 'day') {
newValues = this._constructMonth();
} else if (this._currentDisplayMode === 'month') {
newValues = this._constructYear();
} else {
newValues = this._constructYearRange();
}
this.set('_valuesDisplayed', newValues);
},
/**
* This event is fired when the user selects a date range in the calendar & 'preventRangeSelection' is false
*
* @event px-calendar-range-selected
* @param {object} range - {from, to} : the ISO 8601 Strings representing the date/time range selected by the user
* @param {object} momentObjs - {from, to} : the moment.js objects representing the date/time range selected by the user
*/
/**
* This event is fired when the user selects a date in the calendar & 'preventRangeSelection' is true
*
* @event px-calendar-selected
* @param {object} momentObj : the moment.js object representing the date/time selected by the user
*/
_selectDate: function (newSelectedDate) {
if (!this.preventRangeSelection && this.fromMoment && !this.toMoment) {
// treat the click as the second date - the range is selected!
if (newSelectedDate.isBefore(this.fromMoment)) {
//swap
this.set('toMoment', this.fromMoment);
this.set('fromMoment', this._preserveTime(this.fromMoment, newSelectedDate));
} else {
this.set('toMoment', this._preserveTime(this.toMoment, newSelectedDate));
}
this.fire('px-calendar-range-selected', { momentObjs: { from: this.fromMoment, to: this.toMoment } });
}
else {
this.set('toMoment', null);
this.set('fromMoment', this._preserveTime(this.fromMoment, newSelectedDate));
if (this.preventRangeSelection) {
this.fire('px-calendar-selected', { momentObj: this.fromMoment });
}
}
},
_constructYear: function () {
//3 rows of 4 months
var current = this.baseDate.clone().month(0),
months = [];
for (var i = 0; i < 3; i++) {
months[i] = [];
for (var j = 0; j < 4; j++) {
months[i].push(current);
current = current.clone().add(1, 'months');
}
}
return months;
},
_constructYearRange: function () {
//2 rows of 5 years
var current = this.baseDate.clone(),
years = [];
for (var i = 0; i < 2; i++) {
years[i] = [];
for (var j = 0; j < 5; j++) {
years[i].push(current);
current = current.clone().add(1, 'years');
}
}
return years;
},
_constructMonth: function () {
if (this.baseDate) {
var numberOfDaysInMonth = this.baseDate.daysInMonth(),
dayBeginningOfMonth = this.baseDate.clone().startOf('month').day(),
numberOfWeeks = 6, // will always have 6 weeks to make calendar not change height
daysBeforeMonthStartsCount = Px.moment.localeData().firstDayOfWeek(),
emptyCellsCount = dayBeginningOfMonth - daysBeforeMonthStartsCount,
date = 1,
month = [];
//make sure we have enough space to display the first day
if (emptyCellsCount < 0) {
emptyCellsCount += 7;
}
var week = [];
for (var j = 0; j < emptyCellsCount; j++) {
week.push(Px.moment(null)); // push empty cells on before the 1st of the month
}
for (var weekCount = 0; weekCount < numberOfWeeks; weekCount++) {
while (week.length < 7) {
if (date <= numberOfDaysInMonth) {
week.push(this.baseDate.clone().date(date));
date++;
}
else {
week.push(Px.moment(null)); // push empty cells on after the last day of the month (to fill the week, extra weeks)
}
}
month.push(week);
week = [];
}
return month;
}
},
/**
* Called when clicking the 'next' arrow
*/
_onNext: function () {
//create a new moment object so Polymer knows the property has changed
var newMoment;
if (this._currentDisplayMode === 'day') {
newMoment = Px.moment.tz(this.baseDate, this.timeZone).add(1, 'months');
} else if (this._currentDisplayMode === 'month') {
newMoment = Px.moment.tz(this.baseDate, this.timeZone).add(1, 'years');
}
else {
newMoment = Px.moment.tz(this.baseDate, this.timeZone).add(10, 'years');
}
this.set('baseDate', newMoment);
this._renderCurrent();
},
/**
* Called when clicking the 'previous' arrow
*/
_onPrevious: function () {
// create a new moment object so Polymer knows the property has changed
var newMoment;
if (this._currentDisplayMode === 'day') {
newMoment = Px.moment.tz(this.baseDate, this.timeZone).subtract(1, 'months');
} else if (this._currentDisplayMode === 'month') {
newMoment = Px.moment.tz(this.baseDate, this.timeZone).subtract(1, 'years');
}
else {
newMoment = Px.moment.tz(this.baseDate, this.timeZone).subtract(10, 'years');
}
this.set('baseDate', newMoment);
this._renderCurrent();
},
_isAtSelectionLevel: function (currentDisplayMode, displayMode) {
return currentDisplayMode === displayMode;
},
_baseDateChanged: function (newDate) {
if (newDate === undefined || newDate === null) {
//make sure baseDate is always defined
if(this._oldBaseDate) {
this.baseDate = this._oldBaseDate;
}
return;
} else if(!this._oldBaseDate) {
this._renderCurrent();
}
//rerender if we're in day mode and changed month or if we changed year
else if (this._currentDisplayMode === 'day' &&
(newDate.isAfter(this._oldBaseDate, 'month') || newDate.isBefore(this._oldBaseDate, 'month'))) {
this._renderCurrent();
}
else if (newDate.isAfter(this._oldBaseDate, 'year') || newDate.isBefore(this._oldBaseDate, 'year')) {
this._renderCurrent();
}
else if (this._oldBaseDate && newDate && newDate.tz() !== this._oldBaseDate.tz()) {
this._renderCurrent();
}
this._oldBaseDate = this.baseDate;
}
});
</script>