-
Notifications
You must be signed in to change notification settings - Fork 2
/
last-changed-element.js
91 lines (77 loc) · 2.52 KB
/
last-changed-element.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
class LastChangedElement extends HTMLElement {
second = 1000;
minute = this.second * 60;
hour = this.minute * 60;
day = this.hour * 24;
month = this.day * 30;
year = this.day * 365;
timeAgo = (last_changed_millis) => {
const diff = new Date().getTime() - last_changed_millis;
switch (true) {
case diff < this.minute:
const seconds = Math.round(diff / 1000);
return seconds + 's';
case diff < this.hour:
return Math.round(diff / this.minute) + 'm';
case diff < this.day:
return Math.round(diff / this.hour) + 'h';
case diff < this.month:
return Math.round(diff / this.day) + 'd';
case diff < this.year:
return Math.round(diff / this.month) + 'M';
case diff > this.year:
return Math.round(diff / this.year) + 'y';
default:
return "";
}
};
set hass(hass) {
if (!this.content) {
this.content = document.createElement('text-element');
this.appendChild(this.content);
}
const entityId = this.config.entity;
const state = hass.states[entityId];
let stateStr = '-';
try {
if (state) {
const last_changed_millis = (new Date(state.last_changed)).getTime();
stateStr = this.timeAgo(last_changed_millis);
this.setTimer(last_changed_millis);
}
} catch (ex) {
}
this.setContent(stateStr);
}
setConfig(config) {
if (!config.entity) {
throw new Error('You need to define an entity');
}
this.config = config;
}
getCardSize() {
return 1;
}
setContent(str) {
this.content.innerHTML = str;
}
setTimer(last_changed_millis) {
if (this.timer) {
clearTimeout(this.timer);
}
const diff = new Date().getTime() - last_changed_millis;
let nextInterval;
if (diff < this.minute) {
nextInterval = this.second;
} else if (diff < this.hour) {
nextInterval = this.minute;
}
if (nextInterval) {
this.timer = setTimeout(() => {
this.setContent(this.timeAgo(last_changed_millis));
this.setTimer(last_changed_millis);
}, nextInterval);
}
}
}
customElements.define('last-changed-element', LastChangedElement);