-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlovelace-countdown-dates.js
112 lines (94 loc) · 2.76 KB
/
lovelace-countdown-dates.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
class CountdownCard extends HTMLElement {
set hass(hass) {
if (this.config.title) {
this.card.header = this.config.title;
}
if (!this.config.phrase) {
this.phrase = "days left";
} else {
this.phrase = this.config.phrase;
}
var line = "";
this.dates.forEach(element => {
var today = new Date();
var todayYear = today.getFullYear();
var eventDate = new Date(element.date);
var dd = String(eventDate.getDate()).padStart(2, '0');
var mm = String(eventDate.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = eventDate.getFullYear();
var age = (todayYear - yyyy) - 1;
var eventToday = mm + '/' + dd + '/' + (age > -1 ? today.getFullYear() : yyyy);
// console.log(this.date_diff(eventToday));
var daysLeft = this.date_diff(eventToday);
if (daysLeft < 0) {
age = age + 1;
daysLeft = this.date_diff(mm + '/' + dd + '/' + parseInt(todayYear+1));
}
if (age > -1) {
var daysLeft = (this.config.show_age ? "age " + age + ", " : "") + daysLeft;
}
line += `
<div style="padding: 5px;" class="row">
<div class="icon"><ha-icon icon="${element.icon ? element.icon : ""}"></ha-icon></div>
<div class="name">${element.name}</div>
<div class="data">${daysLeft} ${this.phrase}</div>
</div>
`;
});
this.content.innerHTML = this._renderStyle() + line;
}
setConfig(config) {
this.config = config;
this.dates = this.config.dates;
if (!this.content) {
this.card = document.createElement('ha-card');
this.content = document.createElement('div');
this.content.style.padding = '0 16px 16px';
this.card.appendChild(this.content);
this.appendChild(this.card);
}
}
_renderStyle() {
return `
<style>
.row
{
display: table;
width: 100%; /*Optional*/
table-layout: fixed; /*Optional*/
border-spacing: 5px; /*Optional*/
vertical-align: middle;
}
.row .icon
{
width: 24px;
display: table-cell;
}
.row .name
{
display: table-cell;
line-height: 1.5pt;
}
.row .data
{
display: table-cell;
text-align: right;
}
</style>
`;
}
date_diff(target) {
var now = new Date();
var then = new Date(target);
var timeDiff = Math.abs(then.getTime() - now.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (then.getTime() < now.getTime()) {
diffDays = diffDays * -1;
}
return diffDays;
}
getCardSize() {
return 1;
}
}
customElements.define('countdown-dates', CountdownCard);