This repository has been archived by the owner on Sep 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
app.js
executable file
·1141 lines (915 loc) · 33.4 KB
/
app.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
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { LitElement,html } from 'lit-element';
import moment from 'moment';
import 'moment/min/locales';
class AtomicCalendar extends LitElement {
constructor() {
super();
this.lastCalendarUpdateTime;
this.lastEventsUpdateTime;
this.lastHTMLUpdateTime;
this.events;
this.content = html ``;
this.shouldUpdateHtml = true;
this.errorMessage = '';
this.modeToggle = 0;
this.selectedMonth = moment();
this.refreshCalEvents = null;
this.monthToGet = moment().format("MM");
this.month = [];
this.showLoader = false;
this.eventSummary = html ` `;
this.firstrun = true;
this.language = '';
}
static get properties() {
return {
hass: Object,
config: Object,
content: Object,
selectedMonth: Object
}
}
updated() {}
render() {
if(this.firstrun){
console.log("atomic_calendar v0.8.9 loaded")
}
this.language = this.config.language != '' ? this.config.language : this.hass.language.toLowerCase()
let timeFormat = moment.localeData(this.language).longDateFormat('LT')
if (this.config.hoursFormat=='12h') timeFormat = 'h:mm A'
else if (this.config.hoursFormat=='24h') timeFormat = 'H:mm'
else if(this.config.hoursFormat!='default') timeFormat = this.config.hoursFormat
moment.updateLocale(this.language, {
week: {
dow: this.config.firstDayOfWeek
},
longDateFormat : {
LT: timeFormat
}
});
this.firstrun=false
if (!this.isUpdating && this.modeToggle == 1) {
if (!this.lastEventsUpdateTime || moment().diff(this.lastEventsUpdateTime, 'minutes') > 15)
(async() => {
this.showLoader = true
this.isUpdating = true;
try {
this.events = await this.getEvents()
} catch (error) {
console.log(error)
this.errorMessage = 'The calendar can\'t be loaded from Home Assistant component'
this.showLoader = false
}
this.lastEventsUpdateTime = moment();
this.updateEventsHTML(this.events);
this.isUpdating = false;
this.showLoader = false
})()
}
if (this.modeToggle == 1)
this.updateEventsHTML(this.events);
else
this.updateCalendarHTML();
return html `
${this.setStyle()}
<ha-card class="cal-card">
<div class="cal-titleContainer">
<div class="cal-title" @click='${e => this.handleToggle()}'>
${this.config.title}
</div>
${(this.showLoader && this.config.showLoader) ? html`
<div class="loader" ></div>` : ''}
<div class="calDate">
${(this.config.showDate) ? this.getDate() : null}
</div>
</div>
<div style="padding-top: 4px;">
${this.content}
</div>
</ha-card>`
}
firstTimeConfig() {
}
handleToggle() {
if (this.config.enableModeChange) {
this.modeToggle == 1 ? this.modeToggle = 2 : this.modeToggle = 1
this.requestUpdate()
}
}
setStyle() {
return html `
<style>
.cal-card{
cursor: default;
padding: 16px;
}
.cal-title {
font-size: var(--paper-font-headline_-_font-size);
color: var(--primary-text-color);
padding: 4px 8px 12px 0px;
line-height: 40px;
cursor: default;
float:left;
}
.cal-titleContainer {
display: flex;
flex-direction: row;
justify-content: space-between;
vertical-align: middle;
align-items: center;
margin: 0 8px 0 8px;
}
.calDate {
font-size: var(--paper-font-headline_-_font-size);
font-size: 1.3rem;
font-weight: 400;
color: var(--primary-text-color);
padding: 4px 8px 12px 0px;
line-height: 40px;
cursor: default;
float:right;
opacity: .75;
}
table{
color:black;
margin-left: 0px;
margin-right: 0px;
border-spacing: 10px 5px;
border-collapse: collapse;
}
td {
padding: 4px 0 4px 0;
}
.daywrap{
padding: 2px 0 4px 0;
border-top: 1px solid;
}
tr{
width: 100%;
}
.event-left {
padding: 4px 10px 3px 8px;
text-align: center;
vertical-align: top;
}
.daywrap > td {
padding-top: 8px;
}
.event-right {
display: flex;
justify-content: space-between;
padding: 0px 5px 0 5px;
}
.event-description {
display: flex;
justify-content: space-between;
padding: 0px 5px 0 5px;
}
.event-main {
flex-direction:row nowrap;
display: inline-block;
vertical-align: top;
}
.event-location {
text-align: right;
display: inline-block;
vertical-align: top;
}
.event-title {
}
.event-location-icon {
height: 15px;
width: 15px;
margin-top: -2px;
}
.location-link {
text-decoration: none;
}
.event-circle {
width: 10px;
height: 10px;
margin-left: -2px
}
hr.event {
color: ${this.config.eventBarColor};
margin: -8px 0px 2px 0px;
border-width: 1px 0 0 0;
}
.eventBar {
margin-top: -10px;
margin-bottom: 0px;
}
hr.progress {
margin: -8px 0px 2px 0px;
border-width: 1px 0 0 0;
}
.progress-container {
margin-top: -5px;
}
.progress-circle {
width: 10px;
height: 10px;
color: ${this.config.progressBarColor};
margin-left: -2px
}
.progressBar {
margin-top: -5px;
margin-bottom: -2px;
border-color: ${this.config.progressBarColor};
}
.nextEventIcon{
width: 10px;
height: 10px;
float: left;
display: block;
margin-left: -14px;
}
table.cal{
margin-left: 0px;
margin-right: 0px;
border-spacing: 10px 5px;
border-collapse: collapse;
width: 100%;
table-layout:fixed;
}
td.cal {
padding: 0 0 0 0;
text-align: center;
vertical-align: middle;
width:100%;
}
.calDay {
height: 30px;
font-size: 95%;
max-width: 38px;
margin: auto;
}
tr.cal {
width: 100%;
}
paper-icon-button {
width: 30px;
height: 30px;
padding: 4px;
}
.calTableContainer {
width: 100%;
}
.calIcon {
width: 10px;
height:10px;
padding-top: 0px;
margin-top: -10px;
margin-right: -1px;
margin-left: -1px;
}
.loader {
border: 4px solid #f3f3f3;
border-top: 4px solid grey;
border-radius: 50%;
width: 14px;
height: 14px;
animation: spin 2s linear infinite;
float:left;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
`
}
getDate() {
const date=moment().format(this.config.dateFormat)
return html`${date}`
}
setConfig(config) {
if (!config.entities) {
throw new Error('You need to define entities');
}
this.config = {
// text translations
title: 'Calendar', // Card title
fullDayEventText: 'All day', // "All day" custom text
untilText: 'Until', // "Until" custom text
language: '',
// main settings
showColors: true, // show calendar title colors, if set in config (each calendar separately)
maxDaysToShow: 7, // maximum days to show
showLoader: true, // show animation when loading events from Google calendar
showLocation: true, // show location link (right side)
showMonth: false, // show month under day (left side)
fullTextTime: true, // show advanced time messages, like: All day, until Friday 12
showCurrentEventLine: false, // show a line between last and next event
showDate: false,
dateFormat: 'LL',
hoursFormat: 'default', // 12h / 24h / default time format. Default is HA language setting.
startDaysAhead: 0, // shows the events starting on x days from today. Default 0.
showLastCalendarWeek: true, // always shows last line/week in calendar mode, even if it's not the current month
showCalNameInEvent: false,
// color and font settings
dateColor: 'var(--primary-text-color)', // Date text color (left side)
dateSize: 90, //Date text size (percent of standard text)
descColor: 'var(--primary-text-color)', // Description text color (left side)
descSize: 80, //Description text size (percent of standard text)
showNoEventsForToday: false,
noEventsForTodayText: 'No events for today',
noEventsForNextDaysText: 'No events in the next days',
timeColor: 'var(--primary-color)', // Time text color (center bottom)
timeSize: 90, //Time text size
showHours: true, //shows the bottom line (time, duration of event)
titleColor: 'var(--primary-text-color)', //Event title settings (center top), if no custom color set
titleSize: 100,
locationIconColor: 'rgb(230, 124, 115)', //Location link settings (right side)
locationLinkColor: 'var(--primary-text-color)',
locationTextSize: 90,
// finished events settings
dimFinishedEvents: true, // make finished events greyed out or set opacity
finishedEventOpacity: 0.6, // opacity level
finishedEventFilter: 'grayscale(100%)', // css filter
// days separating
dayWrapperLineColor: 'var(--primary-text-color)', // days separating line color
eventBarColor: 'var(--primary-color)',
showProgressBar: true,
progressBarColor: 'var(--primary-color)',
enableModeChange: false,
defaultMode: 1,
CalEventBackgroundColor: '#ededed',
CalEventBackgroundFilter: null,
CalEventHolidayColor: 'red',
CalEventHolidayFilter: null,
CalEventIcon1: 'mdi:gift',
CalEventIcon1Color: 'var(--primary-text-color)',
CalEventIcon1Filter: null,
CalEventIcon2: 'mdi:home',
CalEventIcon2Color: 'var(--primary-text-color)',
CalEventIcon2Filter: null,
CalEventIcon3: 'mdi:star',
CalEventIcon3Color: 'var(--primary-text-color)',
CalEventIcon3Filter: null,
firstDayOfWeek: 1, // default 1 - monday
blacklist: null,
...config
}
this.modeToggle = this.config.defaultMode
if (typeof this.config.entities === 'string')
this.config.entities = [{
entity: config.entities
}];
this.config.entities.forEach((entity, i) => {
if (typeof entity === 'string')
this.config.entities[i] = {
entity: entity
};
});
}
// The height of your card. Home Assistant uses this to automatically
// distribute all cards over the available columns.
getCardSize() {
return this.config.entities.length + 1;
}
_toggle(state) {
this.hass.callService('homeassistant', 'toggle', {
entity_id: state.entity_id
});
}
/**
* generate Event Title (summary) HTML
*
*/
getTitleHTML(event) {
const titletext = (this.config.showCalNameInEvent) ? event.eventClass.organizer.displayName+": " + event.title : event.title
//var titleColor = this.config.titleColor !='' ? this.config.titleColor : 'var(--primary-text-color)'
//if (this.config.showColors && typeof event.config.titleColor != 'undefined') titleColor=event.config.titleColor
const titleColor = (this.config.showColors && typeof event.config.titleColor != 'undefined') ? event.config.titleColor : this.config.titleColor
//const eventIcon = isEventNext ? html`<ha-icon class="nextEventIcon" icon="mdi:arrow-right-bold"></ha-icon>` : ``
return html `
<a href="${event.link}" style="text-decoration: none;" target="_blank">
<div class="event-title" style="font-size: ${this.config.titleSize}%;color: ${titleColor}">${titletext}</div></a>
`
}
/**
* generate Hours HTML
*
*/
getHoursHTML(event) {
const today = moment()
if(event.isEmpty) return html `<div> </div>`
// full day events, no hours set
// 1. One day only, or multiple day ends today -> 'All day'
if (event.isFullOneDayEvent || (event.isFullMoreDaysEvent && moment(event.endTime).isSame(today, 'day')))
return html `<div>${this.config.fullDayEventText}</div>`
// 2. Starts any day, ends later -> 'All day, end date'
else if (event.isFullMoreDaysEvent)
return html `<div>${this.config.fullDayEventText}, ${this.config.untilText.toLowerCase()} ${this.getCurrDayAndMonth(moment(event.endTime))}</div>`
// 3. starts before today, ends after today -> 'date - date'
else if (event.isFullMoreDaysEvent && (moment(event.startTime).isBefore(today, 'day') || moment(event.endTime).isAfter(today, 'day')))
return html `<div>${this.config.fullDayEventText}, ${this.config.untilText.toLowerCase()} ${this.getCurrDayAndMonth(moment(event.endTime))}</div>`
// events with hours set
//4. long term event, ends later -> 'until date'
else if (moment(event.startTime).isBefore(today, 'day') && moment(event.endTime).isAfter(today, 'day'))
return html `<div>${this.config.untilText} ${this.getCurrDayAndMonth(moment(event.endTime))}</div>`
//5. long term event, ends today -> 'until hour'
else if (moment(event.startTime).isBefore(today, 'day') && moment(event.endTime).isSame(today, 'day'))
return html `<div>${this.config.untilText} ${event.endTime.format('LT')}</div>`
//6. starts today or later, ends later -> 'hour - until date'
else if (!moment(event.startTime).isBefore(today, 'day') && moment(event.endTime).isAfter(event.startTime, 'day'))
return html `<div>${event.startTime.format('LT')}, ${this.config.untilText.toLowerCase()} ${this.getCurrDayAndMonth(moment(event.endTime))}</div>`
// 7. Normal one day event, with time set -> 'hour - hour'
else return html `
<div>${event.startTime.format('LT')} - ${event.endTime.format('LT')}</div>`
}
/**
* generate Event Location link HTML
*
*/
getLocationHTML(event) {
if (!event.location || !this.config.showLocation) return html ``
else return html `
<div><a href="https://maps.google.com/?q=${event.location}" target="_blank" class="location-link" style="color: ${this.config.locationLinkColor};font-size: ${this.config.locationTextSize}%;"><ha-icon class="event-location-icon" style="${this.config.locationIconColor}" icon="mdi:map-marker"></ha-icon> ${event.address}</a></div>
`
}
/**
* update Events main HTML
*
*/
updateEventsHTML(days) {
var htmlDays = ''
if (!days) { // TODO some more tests end error message
this.content = html `${this.errorMessage}`
return
}
// TODO write something if no events
if (days.length == 0) {
this.content = this.config.noEventsForNextDaysText
return
}
// move today's finished events up
if (moment(days[0][0]).isSame(moment(), "day") && days[0].length > 1) {
var i = 1
while (i < days[0].length) {
if (days[0][i].isEventFinished && !days[0][i - 1].isEventFinished) {
[days[0][i], days[0][i - 1]] = [days[0][i - 1], days[0][i]]
if (i > 1) i--
} else
i++
}
}
// check if no events for today and push a "no events" fake event
if (this.config.showNoEventsForToday && moment(days[0][0].startTime).isAfter(moment(), "day") && days[0].length > 0) {
var emptyEv = {
eventClass :'',
config : '',
start : { dateTime: moment().endOf('day')},
end : { dateTime: moment().endOf('day')},
summary: this.config.noEventsForTodayText,
isFinished : false,
htmlLink : 'https://calendar.google.com/calendar/r/day?sf=true'
};
var emptyEvent = new EventClass(emptyEv , '')
emptyEvent.isEmpty = true
var d = []
d[0]=emptyEvent
days.unshift(d)
}
//loop through days
htmlDays = days.map((day, di) => {
//loop through events for each day
const htmlEvents = day.map((event, i, arr) => {
const dayWrap = (i == 0 && di > 0) ? 'daywrap' : ''
const isEventNext = (di == 0 && moment(event.startTime).isAfter(moment()) && (i == 0 || !moment(arr[i - 1].startTime).isAfter(moment()))) ? true : false
//show line before next event
const currentEventLine = (this.config.showCurrentEventLine &&
isEventNext) ? html `<div class="eventBar"><ha-icon icon="mdi:circle" class="event-circle" style="color: ${this.config.eventBarColor};"></ha-icon><hr class="event"/></div>` : ``
//show current event progress bar
var progressBar = ``
if (di == 0 && this.config.showProgressBar && event.isEventRunning) {
let eventDuration = event.endTime.diff(event.startTime, 'minutes');
let eventProgress = moment().diff(event.startTime, 'minutes');
let eventPercentProgress = Math.floor((eventProgress * 100) / eventDuration);
progressBar = html `<div class="progress-container"><ha-icon icon="mdi:circle" class="progress-circle" style="margin-left:${eventPercentProgress}%;"></ha-icon><hr class="progress" style="color: ${this.config.progressBarColor};border-color: ${this.config.progressBarColor};" /></div>`;
}
var finishedEventsStyle = (event.isEventFinished && this.config.dimFinishedEvents) ? `opacity: ` + this.config.finishedEventOpacity + `; filter: ` + this.config.finishedEventFilter : ``
const hoursHTML = this.config.showHours ? html`<div style="color: ${this.config.timeColor}; font-size: ${this.config.timeSize}%;">${this.getHoursHTML(event)}</div>` : ''
const descHTML = this.config.showDescription ? html`<div class="event-description" style="color: ${this.config.descColor};font-size: ${this.config.descSize}%;">${event.description}</div>` : ''
const lastEventStyle = i == arr.length - 1 ? 'padding-bottom: 8px;' : ''
return html `
<tr class="${dayWrap}" style="color: ${this.config.dayWrapperLineColor};">
<td class="event-left" style="color: ${this.config.dateColor};font-size: ${this.config.dateSize}%;"><div>
<div>${(i===0 && this.config.showMonth) ? event.startTimeToShow.format('MMM') : ''}</div>
<div>${i===0 ? event.startTimeToShow.format('DD') : ''}</div>
<div>${i===0 ? event.startTimeToShow.format('ddd') : ''}</div>
</td>
<td style="width: 100%; ${finishedEventsStyle} ${lastEventStyle} ">
<div>${currentEventLine}</div>
<div class="event-right">
<div class="event-main" >
${this.getTitleHTML(event)}
${hoursHTML}
</div>
<div class="event-location">
${this.getLocationHTML(event)}
</div>
</div>
${descHTML}
${progressBar}
</td>
</tr>`
})
return htmlEvents
})
this.content = html `<table><tbody>${htmlDays}</tbody></table>`
}
/**
* ready-to-use function to remove year from moment format('LL')
* @param {moment}
* @return {String} [month, day]
*/
getCurrDayAndMonth(locale) {
const today = locale.format('LL');
return today
.replace(locale.format('YYYY'), '') // remove year
.replace(/\s\s+/g, ' ') // remove double spaces, if any
.trim() // remove spaces from the start and the end
.replace(/[??]\./, '') // remove year letter from RU/UK locales
.replace(/de$/, '') // remove year prefix from PT
.replace(/b\.$/, '') // remove year prefix from SE
.trim() // remove spaces from the start and the end
.replace(/,$/g, ''); // remove comma from the end
}
/**
* check if string contains one of keywords
* @param {string} string to check inside
* @param {string} comma delimited keywords
* @return {bool}
*/
checkFilter(str, filter) {
if(typeof filter != 'undefined' && filter!=''){
const keywords = filter.split(',')
return (keywords.some((keyword) => {
if (RegExp('(?:^|\\s)' + keyword.trim(), 'i').test(str))
return true
else return false
}))
} else return false
}
/**
* gets events from HA Calendar to Events mode
*
*/
async getEvents() {
let timeOffset = -moment().utcOffset()
let start = moment().add(this.config.startDaysAhead, 'days').startOf('day').add(timeOffset,'minutes').format('YYYY-MM-DDTHH:mm:ss');
let end = moment().add((this.config.maxDaysToShow + this.config.startDaysAhead), 'days').endOf('day').add(timeOffset,'minutes').format('YYYY-MM-DDTHH:mm:ss');
let calendarUrlList = []
this.config.entities.map(entity =>{
calendarUrlList.push([`calendars/${entity.entity}?start=${start}Z&end=${end}Z`])
})
try {
return await (Promise.all(calendarUrlList.map(url =>
this.hass.callApi('get', url[0]))).then((result) => {
let singleEvents = []
result.map((calendar, i) => {
calendar.map((singleEvent) => {
let blacklist = typeof this.config.entities[i]["blacklist"] != 'undefined' ? this.config.entities[i]["blacklist"] : ''
if(blacklist=='' || !this.checkFilter(singleEvent.summary, blacklist)){
singleEvents.push(new EventClass(singleEvent, this.config.entities[i] ))
}
})
})
let ev = [].concat.apply([], singleEvents )
// grouping events by days, returns object with days and events
const groupsOfEvents = ev.reduce(function (r, a) {
r[a.daysToSort] = r[a.daysToSort] || []
r[a.daysToSort].push(a);
return r
}, {})
const days = Object.keys(groupsOfEvents).map(function (k) {
return groupsOfEvents[k];
});
this.showLoader = false
return days
}))
} catch (error) {
this.showLoader = false
throw error
}
}
/**
* gets events from HA to Calendar mode
*
*/
getCalendarEvents(startDay, endDay, monthToGet, month) {
this.refreshCalEvents = false
let timeOffset = new Date().getTimezoneOffset()
let start = moment(startDay).startOf('day').add(timeOffset,'minutes').format('YYYY-MM-DDTHH:mm:ss');
let end = moment(endDay).endOf('day').add(timeOffset,'minutes').format('YYYY-MM-DDTHH:mm:ss');
// calendarUrlList[url, type of event configured for this callendar,filters]
let calendarUrlList = []
this.config.entities.map(entity => {
if (typeof entity.type != 'undefined') {
calendarUrlList.push([`calendars/${entity.entity}?start=${start}Z&end=${end}Z`, entity.type,
typeof entity.blacklist!= 'undefined' ? entity.blacklist : ''
])
}
})
Promise.all(calendarUrlList.map(url =>
this.hass.callApi('get', url[0]))).then((result) => {
if (monthToGet == this.monthToGet)
result.map((eventsArray, i) => {
this.month.map(m => {
const calendarTypes = calendarUrlList[i][1]
const calendarUrl = calendarUrlList[i][0]
const calendarBlacklist = (typeof calendarUrlList[i][2] != 'undefined') ? calendarUrlList[i][2] : ''
eventsArray.map((event) => {
const startTime = event.start.dateTime ? moment(event.start.dateTime) : moment(event.start.date).startOf('day')
const endTime = event.end.dateTime ? moment(event.end.dateTime) : moment(event.end.date).subtract(1, 'days').endOf('day')
if (!moment(startTime).isAfter(m.date, 'day') && !moment(endTime).isBefore(m.date, 'day') && calendarTypes && !this.checkFilter(event.summary, calendarBlacklist))
//checking for calendar type (icons) and keywords
try {
if (this.checkFilter('icon1', calendarTypes)){
if (!this.config.CalEventIcon1Filter || this.checkFilter(event.summary, this.config.CalEventIcon1Filter))
m['icon1'].push(event.summary)
}
if (this.checkFilter('icon2', calendarTypes)){
if (!this.config.CalEventIcon2Filter || this.checkFilter(event.summary, this.config.CalEventIcon2Filter))
m['icon2'].push(event.summary)
}
if (this.checkFilter('icon3', calendarTypes)){
if (!this.config.CalEventIcon3Filter || this.checkFilter(event.summary, this.config.CalEventIcon3Filter))
m['icon3'].push(event.summary)
}
if (this.checkFilter('holiday', calendarTypes)) {
m['holiday'].push(event.summary)
}
} catch (e) {
console.log('error: ', e, calendarUrl)
}
})
})
return month
})
if (monthToGet == this.monthToGet) this.showLoader = false
this.refreshCalEvents = false
this.requestUpdate()
}).catch((err) => {
this.refreshCalEvents = false
console.log('error: ', err)
this.showLoader = false
})
}
/**
* create array for 42 calendar days
* showLastCalendarWeek
*/
buildCalendar(selectedMonth) {
const firstDay = moment(selectedMonth).startOf('month')
const dayOfWeekNumber = firstDay.day()
this.month = [];
let weekShift = 0;
(dayOfWeekNumber - this.config.firstDayOfWeek) >=0 ? weekShift = 0 : weekShift = 7
for (var i = this.config.firstDayOfWeek - dayOfWeekNumber - weekShift ; i < 42 - dayOfWeekNumber + this.config.firstDayOfWeek -weekShift; i++) {
this.month.push(new CalendarDay(moment(firstDay).add(i, 'days'), i))
}
}
/**
* change month in calendar mode
*
*/
handleMonthChange(i) {
this.selectedMonth = moment(this.selectedMonth).add(i, 'months');
this.monthToGet = this.selectedMonth.format("M");
this.eventSummary = html ` `;
this.refreshCalEvents = true
}
/**
* show events summary under the calendar
*
*/
handleEventSummary(day) {
let events = ([','].concat.apply([], [day.holiday, day.daybackground, day.icon1, day.icon2, day.icon3])).join(', ')
if (events == '') events = html ` `
this.eventSummary = html `${events}`
this.requestUpdate()
}
/**
* create html calendar header
*
*/
getCalendarHeaderHTML() {
return html`
<div class="calTitle">
<paper-icon-button icon="mdi:chevron-left" @click='${e => this.handleMonthChange(-1)}' title="left"></paper-icon-button>
<div style="display: inline-block; min-width: 9em; text-align: center;">
<a href="https://calendar.google.com/calendar/r/month/${moment(this.selectedMonth).format('YYYY')}/${moment(this.selectedMonth).format('MM')}/1" style="text-decoration: none; color: ${this.config.titleColor}" target="_blank">
${moment(this.selectedMonth).locale(this.language).format('MMMM')} ${moment(this.selectedMonth).format('YYYY')}
</a>
</div>
<paper-icon-button icon="mdi:chevron-right" @click='${e => this.handleMonthChange(1)}' title="right"></paper-icon-button>
</div>
`
}
/**
* create html cells for all days of calendar
*
*/
getCalendarDaysHTML(month) {
var showLastRow = true
if(!this.config.showLastCalendarWeek && !moment(month[35].date).isSame(this.selectedMonth, 'month')) showLastRow = false
return month.map((day, i) => {
const dayStyleOtherMonth = moment(day.date).isSame(moment(this.selectedMonth), 'month') ? '' : `opacity: .35;`
const dayStyleToday = moment(day.date).isSame(moment(), 'day') ? `border: 1px solid grey;` : `border: 1px solid grey; border-color: transparent;`
const dayHolidayStyle = (day.holiday && day.holiday.length > 0) ? `color: ${this.config.CalEventHolidayColor}; ` : ''
const dayBackgroundStyle = (day.daybackground && day.daybackground.length > 0) ? `background-color: ${this.config.CalEventBackgroundColor}; ` : ''
const dayIcon1 = (day.icon1 && day.icon1.length > 0) ? html `<span><ha-icon class="calIcon" style="color: ${this.config.CalEventIcon1Color};" icon="${this.config.CalEventIcon1}"></ha-icon></span>` : ''
const dayIcon2 = (day.icon2 && day.icon2.length > 0) ? html `<span><ha-icon class="calIcon" style="color: ${this.config.CalEventIcon2Color};" icon="${this.config.CalEventIcon2}"></ha-icon></span>` : ''
const dayIcon3 = (day.icon3 && day.icon3.length > 0) ? html `<span><ha-icon class="calIcon" style="color: ${this.config.CalEventIcon3Color};" icon="${this.config.CalEventIcon3}"></ha-icon></span>` : ''
if(i<35 || showLastRow)
return html `
${i % 7 === 0 ? html`<tr class="cal">` :''}
<td class="cal">
<div @click='${e => this.handleEventSummary(day)}' class="calDay" style=" color: ${this.config.titleColor}; ${dayStyleOtherMonth} ${dayStyleToday} ${dayHolidayStyle} ${dayBackgroundStyle}">
<div style="position: relative; top: 5%; ">
${(day.dayNumber).replace(/^0|[^\/]0./, '')}
</div>
<div>
${dayIcon1} ${dayIcon2} ${dayIcon3}
</div>
</div>
</td>
${i && (i % 6 === 0) ? html`</tr>` :''}
`
})
}
/**
* update Calendar mode HTML
*
*/
updateCalendarHTML() {
if (this.month.length == 0 || this.refreshCalEvents || moment().diff(this.lastCalendarUpdateTime, 'minutes') > 120) {
this.lastCalendarUpdateTime = moment()
this.showLoader = true
this.buildCalendar(this.selectedMonth)
this.getCalendarEvents(this.month[0].date, this.month[41].date, this.monthToGet, this.month)
this.showLoader = false
}
const month = this.month
var weekDays = moment.weekdaysMin(true)
const htmlDayNames = weekDays.map((day) => html `
<th class="cal" style="padding-bottom: 8px; color: ${this.config.titleColor};">${day}</th>`)
this.content = html `
<div class="calTitleContainer">
${this.getCalendarHeaderHTML()}
</div>
<div class="calTableContainer">
<table class="cal" style="color: ${this.config.titleColor};">
<thead> <tr>
${htmlDayNames}
</tr> </thead>
<tbody>
${this.getCalendarDaysHTML(month)}
</tbody>
</table>
</div>
<div style="font-size: 90%;">
${this.eventSummary}
</div>
`
}
}
customElements.define('atomic-calendar', AtomicCalendar);
/**
* class for 42 calendar days
*
*/
class CalendarDay {
constructor(calendarDay, d) {
this.calendarDay = calendarDay
this._lp = d;
this.ymd = moment(calendarDay).format("YYYY-MM-DD")
this._holiday = [];
this._icon1 = [];
this._icon2 = [];
this._icon3 = [];
this._daybackground = [];
}
get date() {
return moment(this.calendarDay)
}
get dayNumber() {
return moment(this.calendarDay).format("DD")
}
get monthNumber() {
return moment(this.calendarDay).month()
}
set holiday(eventName) {
this._holiday = eventName;
}
get holiday() {
return this._holiday;
}
set icon1(eventName) {
this._icon1 = eventName;
}
get icon1() {
return this._icon1;
}
set icon2(eventName) {