paper-calendar.html
23 KB
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="../iron-icon/iron-icon.html">
<link rel="import" href="../paper-ripple/paper-ripple.html">
<link rel="import" href="../paper-styles/color.html">
<link rel="import" href="../paper-styles/default-theme.html">
<link rel="import" href="../paper-styles/shadow.html">
<link rel="import" href="../paper-styles/typography.html">
<link rel="import" href="../iron-resizable-behavior/iron-resizable-behavior.html">
<link rel="import" href="../moment-element/moment-import.html">
<link rel="import" href="paper-date-picker-icons.html">
<dom-module id="paper-calendar">
<template>
<style>
:host {
display: block;
box-sizing: border-box;
padding: 12px 0;
position: relative;
width: 100%;
height: 100%;
min-width: 160px;
min-height: 160px;
color: var(--primary-text-color);
-webkit-font-smoothing: antialiased;
-webkit-tap-highlight-color: rgba(0,0,0,0);
--ease-in-sine: cubic-bezier(0.47, 0, 0.745, 0.715);
--ease-out-sine: cubic-bezier(0.39, 0.575, 0.565, 1);
@apply(--paper-font-body1);
@apply(--paper-calendar);
overflow: hidden;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
@apply(--paper-calendar);
}
#calendar {
position: relative;
width: 100%;
height: 100%;
@apply(--layout-horizontal);
}
#months {
height: 100%;
@apply(--layout-horizontal);
}
#months.animating .month-nav {
opacity: 1;
}
#months.animating {
transition-property: transform, opacity;
transition-duration: 300ms;
}
#months.animating.swipe {
transition-timing-function: var(--ease-in-sine);
--webkit-transition-timing-function: var(--ease-in-sine);
}
#months.animating.reset {
transition-timing-function: var(--ease-out-sine);
--webkit-transition-timing-function: var(--ease-out-sine);
}
.month {
height: 100%;
@apply(--layout-vertical);
@apply(--layout-justified);
@apply(--layout-flex);
}
.month-row, .month-nav {
height: calc(100%/8);
box-sizing: border-box;
padding: 0 calc(100%/36);
}
.month-col {
position: relative;
@apply(--layout-vertical);
@apply(--layout-flex);
}
.month-nav {
position: absolute;
top: 0;
left: 0;
width: 100%;
opacity: 1;
@apply(--layout-horizontal);
@apply(--layout-center);
}
.month-nav .col {
position: relative;
@apply(--layout-vertical);
@apply(--layout-center-center);
}
.month-nav .btn .icon {
cursor: pointer;
}
.month-nav .btn .ripple {
position: absolute;
width: 48px;
height: 48px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.month-nav .btn.right {
text-align: right;
}
.month-name {
line-height: 24px;
vertical-align: middle;
text-align: center;
font-weight: bold;
@apply(--paper-font-body2);
@apply(--layout-horizontal);
@apply(--layout-center);
@apply(--layout-center-justified);
@apply(--layout-flex);
}
.month-weekdays {
color: var(--secondary-text-color);
@apply(--layout-horizontal);
@apply(--layout-justified);
@apply(--layout-flex);
}
.month-days {
@apply(--layout-horizontal);
@apply(--layout-justified);
@apply(--layout-flex);
}
.month-col .day {
cursor: default;
pointer-events: none;
@apply(--layout-fit);
@apply(--layout-vertical);
@apply(--layout-center-center);
}
.month-col {
position: relative;
width: 100%;
height: 100%;
@apply(--layout-center-center);
}
.day-item {
border-radius: 100%;
width: 100%;
height: 100%;
}
.day-item::selection {
background: none;
}
.day-item.selected {
background: var(--default-primary-color);
}
.day-item.selected .day {
color: var(--text-primary-color);
}
.day-item:not([disabled]) {
cursor: pointer;
}
.day-item[disabled] .day {
color: var(--text-disabled-color, #9d9d9d);
}
.day-item.today .day {
color: var(--default-primary-color);
}
.day-item.selected.today .day {
color: var(--text-primary-color);
}
.flex {
@apply(--layout-flex);
}
.flex-5 {
@apply(--layout-flex-5);
}
</style>
<div id="calendar">
<div id="months" on-track="_onTrack" class$="{{_contentClass}}">
<template is="dom-repeat" items="{{_months}}" as="month">
<div class$="{{_getMonthClass('month', month)}}">
<div class="month-row month-name">
<span>{{dateFormat(month.date, 'MMMM YYYY', locale)}}</span>
</div>
<div class="month-row month-weekdays week">
<template is="dom-repeat" items="{{_weekdays}}">
<div class="month-col layout vertical flex">
<div class="day">{{item.0}}</div>
</div>
</template>
</div>
<template is="dom-repeat" items="{{month.weeks}}" as="row">
<div class="month-row month-days">
<template is="dom-repeat" items="{{row}}">
<div class="month-col">
<div class$="{{_getDayClass('day-item selection', item.date, today, date)}}"
disabled$="{{_isDisabled(item.day, item.date, minDate, maxDate)}}"
on-tap="_tapDay" date$="{{item.name}}">
<div class="day">{{item.day}}</div>
</div>
</div>
</template>
</div>
</template>
</div>
</template>
</div>
<div id="monthNav" class="month-nav">
<div class="flex col self-stretch">
<div class="btn" on-tap="_swipePrevMonth">
<paper-ripple center class="ripple circle"></paper-ripple>
<iron-icon class="icon flex" icon="date-picker:chevron-left"></iron-icon>
</div>
</div>
<div class="flex-5"></div>
<div class="flex col self-stretch">
<div class="btn" on-tap="_swipeNextMonth">
<paper-ripple center class="ripple circle"></paper-ripple>
<iron-icon class="icon flex" icon="date-picker:chevron-right"></iron-icon>
</div>
</div>
</div>
</div>
</template>
<script>
(function() {
// Ignore movement within this distance (px)
var WIGGLE_THRESHOLD = 4;
var WIGGLE_THRESHOLD_SQUARE = WIGGLE_THRESHOLD * WIGGLE_THRESHOLD;
// what constitues a flick (px/ms)
var FLICK_SPEED = 0.5;
// Factor for "springy" resistence effect when swiping too far.
var RESIST_LENGTH = 40;
var RESIST_FACTOR = 2;
// Number of months to preload on both sides of the current month
var PRELOAD_MONTHS = 1;
function dateDiff(a, b) {
a = new Date(a.getTime());
b = new Date(b.getTime());
a.setHours(0, 0, 0, 0);
b.setHours(0, 0, 0, 0);
return (a.getTime() - b.getTime()) / 86400000;
}
Polymer({
is: 'paper-calendar',
properties: {
/*
* The selected date
*/
date: {
type: Date,
notify: true,
value: function() {
return new Date();
},
observer: '_dateChanged'
},
/**
* The current locale
*/
locale: {
type: String,
value: 'en',
notify: true,
observer: '_localeChanged'
},
/**
* The minimum allowed date
*/
minDate: {
type: Date,
value: null
},
/**
* The maximum allowed date
*/
maxDate: {
type: Date,
value: null
},
/**
* The currently selected month (1-12)
*/
currentMonth: {
type: Number
},
/**
* The currently selected year
*/
currentYear: {
type: Number
},
_contentClass: String,
_months: Array,
_firstDayOfWeek: Number,
},
behaviors: [
Polymer.IronResizableBehavior
],
observers: [
'_populate(currentYear, currentMonth, minDate, maxDate, locale)',
],
listeners: {
'iron-resize': '_resizeHandler',
'swiped': '_onSwipe'
},
ready: function() {
this._updateToday();
this.currentMonth = this.date.getMonth() + 1;
this.currentYear = this.date.getFullYear();
this._transitionEvent = this._whichTransitionEnd();
},
dateFormat: function(date, format, locale) {
if (!date) {
return '';
}
var value = moment(date);
value.locale(locale || this.locale);
return value.format(format);
},
_localeChanged: function(locale) {
var localeMoment = moment();
localeMoment.locale(locale);
var weekdays = [];
for (var i=0; i<7; i++) {
weekdays.push(localeMoment.weekday(i).format('dd'));
}
this._weekdays = weekdays;
this._firstDayOfWeek = localeMoment.weekday(0).format('d');
},
_populate: function(currentYear, currentMonth, minDate, maxDate) {
var date, month, weeks, day, d, dayInfo, monthData, months = [];
// Make sure currentYear/currentMonth are in min/max range
if (minDate && new Date(currentYear, currentMonth, 0) < minDate) {
this.currentYear = minDate.getFullYear();
this.currentMonth = minDate.getMonth() + 1;
return;
} else if (maxDate && new Date(currentYear, currentMonth - 1, 1) > maxDate) {
this.currentYear = maxDate.getFullYear();
this.currentMonth = maxDate.getMonth() + 1;
return;
}
for (var i=-PRELOAD_MONTHS; i<=PRELOAD_MONTHS; i++) {
weeks = [[]];
day = 1;
date = new Date(currentYear, currentMonth - 1 + i, 1);
month = date.getMonth();
monthData = {
year: date.getFullYear(),
month: date.getMonth() + 1,
date: new Date(date)
};
if (!this._monthWithinValidRange(monthData.year, monthData.month)) {
continue;
}
// add "padding" days
var firstDay = date.getDay() - this._firstDayOfWeek;
if (firstDay < 0) {
firstDay = 7 + firstDay;
}
for (d=0; d<firstDay; d++) {
weeks[0].push({day: null, date: null});
}
// add actual days
while (date.getMonth() === month) {
if (weeks[0].length && d % 7 === 0) {
// start new week
weeks.push([]);
}
dayInfo = {
date: new Date(date.getFullYear(), month, day),
name: this.dateFormat(date,'YYYY-MM-DD'),
year: currentYear,
month: month,
day: day,
};
weeks[weeks.length-1].push(dayInfo);
date.setDate(++day);
d++;
}
// add remaining "padding" days
while (d < 42) {
if (d % 7 === 0) {
weeks.push([]);
}
weeks[weeks.length-1].push({day: null, date: null});
d += 1;
}
monthData.weeks = weeks;
months.push(monthData);
}
if (!months.length) {
return;
}
this.set('_months', months);
this.async(function() {
this._updateSelection();
this._positionSlider();
});
},
_getDayClass: function(cssClass, date) {
if (date) {
if (dateDiff(date, this.today) === 0) {
cssClass += ' today';
}
if (dateDiff(date, this.date) === 0) {
cssClass += ' selected';
this.async(function() {
this._updateSelection();
});
}
}
return cssClass;
},
_isDisabled: function(day, date) {
return !day || !this._withinValidRange(date);
},
_getMonthClass: function(name, month) {
return name + ' month-' + month.year + '-' + month.month;
},
_onTrack: function(event) {
var dx = event.detail.dx;
var dy = event.detail.dy;
var adx = Math.abs(dx);
var ady = Math.abs(dy);
var width = this._containerWidth;
switch (event.detail.state) {
case 'start':
this._trackStartTime = (new Date()).getTime();
this._startPos = this._currentPos;
this._moveQueue = [];
break;
case 'track':
if (this._moveQueue.length >= 4) {
this._moveQueue.shift();
}
this._moveQueue.push(event);
// ignore movement within WIGGLE_THRESHOLD
var distance = (dx * dx) + (dy * dy);
if (!this._gesture && distance > WIGGLE_THRESHOLD_SQUARE) {
this._gesture = adx > ady ? 'pan-x' : 'pan-y';
}
// only drag during pan-x gesture
if (this._gesture !== 'pan-x') {
return;
}
this._dragging = true;
var fullWidth = width * this._months.length;
var x = this._startPos + dx;
// If we're dragging outside the bounds, add some resistence
if (x > 0 || x < (-fullWidth + width)) {
if (isNaN(parseInt(this._resistStart, 10))) {
this._resistStart = adx;
}
var rdx = adx - this._resistStart;
var p, d, max = RESIST_LENGTH;
p = rdx > width ? 1 : rdx / width;
d = max * (1 - Math.pow(1 - p, RESIST_FACTOR));
x = (dx < 0 ? -this._scrollWidth + width - d : d);
} else {
this._resistStart = null;
}
this._translateX(x);
break;
case 'end':
this._resistStart = null;
var lastIdx = this._getMonthIdx(this._startPos);
var idx = this._getMonthIdx(this._currentPos);
var speed = this._getFastestMovement(event).v;
var move = idx !== lastIdx || speed > FLICK_SPEED;
if (!this._resistStart && this._gesture === 'pan-x' && move) {
if (speed > FLICK_SPEED) {
// calculate an ideal transition duration based on current speed of swipe
var remainingDistance = width - adx;
var newDuration = remainingDistance / speed;
if (newDuration > 300) {
newDuration = 300;
}
this._transitionDuration = newDuration;
}
if (dx > 0) {
this._swipePrevMonth();
} else {
this._swipeNextMonth();
}
} else {
this._translateX(this._startPos, 'reset');
}
this._gesture = null;
}
},
_swipePrevMonth: function() {
this._translateX(0, 'swipe', function() {
this.set('_contentClass', '');
this.transform('translateX(' + this._startPos + 'px)', this.$.months);
this.fire('swiped', {direction: 'right'});
}.bind(this));
},
_swipeNextMonth: function() {
if (!this.maxDate || this.currentMonth < this.maxDate.getMonth() + 1) {
this._translateX(-this._containerWidth * 2, 'swipe', function() {
this.set('_contentClass', '');
this.transform('translateX(' + this._startPos + 'px)', this.$.months);
this.fire('swiped', {direction: 'left'});
}.bind(this));
}
},
_getMonthIdx: function(pos) {
// returns the index for the visible month according to the given position
var width = this._containerWidth;
var i = Math.floor((-pos + (width/2)) / width);
return i < 0 ? 0 : i;
},
_translateX: function(x, transition, cb) {
if (isNaN(parseInt(x, 10))) {
throw new Error('Not a number: ' + x);
}
this._currentPos = x;
if (transition) {
if (this._transitionDuration) {
this.$.months.style.transitionDuration = this._transitionDuration + 'ms';
}
this._once(this._transitionEvent, function() {
this.set('_contentClass', '');
this.$.months.style.transitionDuration = '';
this._transitionDuration = null;
this.$.monthNav.style.removeProperty('opacity');
if (cb) {
cb();
}
}.bind(this), this.$.months);
this.set('_contentClass', 'animating ' + transition);
this.$.monthNav.style.removeProperty('opacity');
// Fixes odd bug in chrome where we lose touch-events after changing opacity
this._once('touchstart', function() {});
}
window.requestAnimationFrame(function() {
if (!transition) {
var halfWidth = this._containerWidth / 2;
var dx = Math.abs(this._startPos - x);
var p = (1 - (dx / halfWidth)) * 100;
p = (100 - Math.pow(p, 2)) / 100 / 100;
var opacity = Math.abs(parseFloat(p).toFixed(2));
this.$.monthNav.style.opacity = opacity;
}
this.transform('translateX(' + x + 'px)', this.$.months);
}.bind(this));
},
_getFastestMovement: function(event) {
// detect flick based on fastest segment of movement
var l = this._moveQueue.length;
var dt, tx, ty, tv2, x = 0, y = 0, v2 = 0;
for (var i = 0, m; i < l && (m = this._moveQueue[i]); i++) {
dt = event.timeStamp - m.timeStamp;
tx = (event.detail.x - m.detail.x) / dt;
ty = (event.detail.y - m.detail.y) / dt;
tv2 = tx * tx + ty * ty;
if (tv2 > v2) {
x = tx;
y = ty;
v2 = tv2;
}
}
return {x: x, y: y, v: Math.sqrt(v2)};
},
_onSwipe: function(event) {
if (event.detail.direction === 'right') {
this._prevMonth();
} else {
this._nextMonth();
}
},
_once: function(eventName, callback, node) {
node = node || this;
function onceCallback() {
node.removeEventListener(eventName, onceCallback);
callback.apply(null, arguments);
}
node.addEventListener(eventName, onceCallback);
},
_incrMonth: function(i) {
var date = new Date(this.currentYear, this.currentMonth - 1 + i);
var year = date.getFullYear();
var month = date.getMonth() + 1;
if (this._monthWithinValidRange(year, month)) {
this.currentYear = year;
this.currentMonth = month;
}
},
_prevMonth: function() {
this._incrMonth(-1);
},
_nextMonth: function() {
this._incrMonth(1);
},
_dateChanged: function(date, oldValue) {
if (!this._isValidDate(date)) {
console.warn('Invalid date: ' + date);
this.date = date = oldValue;
}
if (!this._withinValidRange(date)) {
console.warn('Date outside of valid range: ' + date);
this.date = date = oldValue;
}
this.currentYear = date.getFullYear();
this.currentMonth = date.getMonth() + 1;
// Only trigger a notification if there actually is a difference.
if (oldValue && date.getTime && oldValue.getTime && date.getTime() === oldValue.getTime()) {
return;
}
this._updateSelection();
},
_tapDay: function(event) {
if (!this._withinValidRange(event.model.item.date)) {
return false;
}
var item = event.model.item;
var newDate = new Date(this.date.getTime());
newDate.setYear(item.year);
newDate.setMonth(item.month);
newDate.setDate(item.day);
this.date = newDate;
},
_isValidDate: function(date) {
return date && date.getTime && !isNaN(date.getTime());
},
_withinValidRange: function(date) {
if (this._isValidDate(date)) {
return (!this.minDate || date >= this.minDate) && (!this.maxDate || date <= this.maxDate);
}
return false;
},
_monthWithinValidRange: function(year, month) {
var monthStart = new Date(year, month-1, 1);
var monthEnd = new Date(year, month, 0);
return this._withinValidRange(monthStart) || this._withinValidRange(monthEnd);
},
_positionSlider: function() {
if (!this._months || !this._containerWidth) {
return;
}
this._scrollWidth = (this.$.calendar.offsetWidth * this._months.length);
this.$.months.style.minWidth = this._scrollWidth + 'px';
var i = ((this.currentYear * 12) + this.currentMonth) -
((this._months[0].year * 12) + this._months[0].month);
this._translateX(-i * this._containerWidth);
},
_updateSelection: function() {
// Force the day selection circle to maintain a 1:1 ratio
var selected = this.$$('.day-item.selected');
if (!selected) {
return;
}
selected.style.height = '';
selected.style.width = '';
var w = selected.parentElement.offsetWidth;
var h = selected.parentElement.offsetHeight;
selected.style.flex = '';
window.requestAnimationFrame(function() {
if (w > 0 && w < h) {
selected.style.height = w + 'px';
}
else if (h > 0) {
selected.style.width = h + 'px';
}
});
},
_resizeHandler: function() {
this._containerWidth = this.$.calendar.offsetWidth;
this._positionSlider();
this._updateSelection();
},
_getDayName: function(date) {
return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
},
_updateToday: function() {
this.today = new Date();
this.today.setHours(0, 0, 0, 0);
},
_whichTransitionEnd: function() {
var transitions = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'transition' : 'transitionend'
};
for (var t in transitions) {
if (this.style[t] !== undefined){
return transitions[t];
}
}
}
});
})();
</script>
</dom-module>