forked from thomasloven/lovelace-card-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcard-tools.js
428 lines (383 loc) · 12.7 KB
/
card-tools.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
customElements.define('card-tools',
class {
static get CUSTOM_TYPE_PREFIX() { return "custom:"}
static get version() { return "0.4"}
static checkVersion(v) {
if (this.version < v) {
throw new Error(`Old version of card-tools found. Get the latest version of card-tools.js from https://github.com/thomasloven/lovelace-card-tools`);
}
}
static deprecationWarning() {
if(window.cardTools_deprecationWarning) return;
console.warn("One or more of your lovelace plugins are using the functions cardTools.litElement(), cardTools.litHtml() or cardTools.hass(). Those are replaced with better alternatives and will be removed a some point in the future.")
console.warn("If you are a plugin developer, make sure you are using the new functions (see documentation).");
console.warn("If you are a plugin user, feel free to ignore this warning (or poke the developer of your plugins - not me though, I already know about this).")
console.warn("Best regards / thomasloven - " + (document.currentScript && document.currentScript.src));
window.cardTools_deprecationWarning = true;
}
static get LitElement() {
if(customElements.get('home-assistant-main'))
return Object.getPrototypeOf(customElements.get('home-assistant-main'));
return Object.getPrototypeOf(customElements.get('hui-view'));
}
static litElement() { // Backwards compatibility - deprecated
this.deprecationWarning();
return this.LitElement;
}
static get LitHtml() {
return this.LitElement.prototype.html;
}
static litHtml() { // Backwards compatibility - deprecated
this.deprecationWarning();
return this.LitHtml;
}
static get LitCSS() {
return this.LitElement.prototype.css;
}
static get hass() {
var hass = function() { // Backwards compatibility - deprecated
this.deprecationWarning();
return hass;
}
for (var k in document.querySelector('home-assistant').hass)
hass[k] = document.querySelector('home-assistant').hass[k];
hass.original = document.querySelector('home-assistant').hass;
return hass;
}
static fireEvent(ev, detail, entity=null) {
ev = new Event(ev, {
bubbles: true,
cancelable: false,
composed: true,
});
ev.detail = detail || {};
if(entity) {
entity.dispatchEvent(ev);
} else {
var root = document.querySelector("home-assistant");
root = root && root.shadowRoot;
root = root && root.querySelector("home-assistant-main");
root = root && root.shadowRoot;
root = root && root.querySelector("app-drawer-layout partial-panel-resolver");
root = root && root.shadowRoot || root;
root = root && root.querySelector("ha-panel-lovelace");
root = root && root.shadowRoot;
root = root && root.querySelector("hui-root");
root = root && root.shadowRoot;
root = root && root.querySelector("ha-app-layout #view");
root = root && root.firstElementChild;
if (root) root.dispatchEvent(ev);
}
}
static get lovelace() {
var root = document.querySelector("home-assistant");
root = root && root.shadowRoot;
root = root && root.querySelector("home-assistant-main");
root = root && root.shadowRoot;
root = root && root.querySelector("app-drawer-layout partial-panel-resolver");
root = root && root.shadowRoot || root;
root = root && root.querySelector("ha-panel-lovelace")
root = root && root.shadowRoot;
root = root && root.querySelector("hui-root")
if (root) {
var ll = root.lovelace
ll.current_view = root.___curView;
return ll;
}
return null;
}
static createThing(thing, config) {
const _createThing = (tag, config) => {
const element = document.createElement(tag);
try {
element.setConfig(config);
} catch (err) {
console.error(tag, err);
return _createError(err.message, config);
}
return element;
};
const _createError = (error, config) => {
return _createThing("hui-error-card", {
type: "error",
error,
config,
});
};
if(!config || typeof config !== "object" || !config.type)
return _createError(`No ${thing} type configured`, config);
let tag = config.type;
if(config.error) {
const err = config.error;
delete config.error;
return _createError(err, config);
}
if(tag.startsWith(this.CUSTOM_TYPE_PREFIX))
tag = tag.substr(this.CUSTOM_TYPE_PREFIX.length);
else
tag = `hui-${tag}-${thing}`;
if(customElements.get(tag))
return _createThing(tag, config);
// If element doesn't exist (yet) create an error
const element = _createError(
`Custom element doesn't exist: ${tag}.`,
config
);
element.style.display = "None";
const timer = setTimeout(() => {
element.style.display = "";
}, 2000);
// Remove error if element is defined later
customElements.whenDefined(tag).then(() => {
clearTimeout(timer);
this.fireEvent("ll-rebuild", {}, element);
});
return element;
}
static createCard(config) {
return this.createThing("card", config);
}
static createElement(config) {
return this.createThing("element", config);
}
static createEntityRow(config) {
const SPECIAL_TYPES = new Set([
"call-service",
"divider",
"section",
"weblink",
]);
const DEFAULT_ROWS = {
alert: "toggle",
automation: "toggle",
climate: "climate",
cover: "cover",
fan: "toggle",
group: "group",
input_boolean: "toggle",
input_number: "input-number",
input_select: "input-select",
input_text: "input-text",
light: "toggle",
media_player: "media-player",
lock: "lock",
remote: "toggle",
scene: "scene",
script: "script",
sensor: "sensor",
timer: "timer",
switch: "toggle",
vacuum: "toggle",
water_heater: "climate",
input_datetime: "input-datetime",
};
if(!config || typeof config !== "object" || (!config.entity && !config.type)) {
Object.assign(config, {error: "Invalid config given"});
return this.createThing("", config);
}
const type = config.type || "default";
if(SPECIAL_TYPES.has(type) || type.startsWith(this.CUSTOM_TYPE_PREFIX))
return this.createThing("row", config);
const domain = config.entity.split(".", 1)[0];
Object.assign(config, {type: DEFAULT_ROWS[domain] || "text"});
return this.createThing("entity-row", config);
}
static get deviceID() {
const ID_STORAGE_KEY = 'lovelace-player-device-id';
if(window['fully'] && typeof fully.getDeviceId === "function")
return fully.getDeviceId();
if(!localStorage[ID_STORAGE_KEY])
{
const s4 = () => {
return Math.floor((1+Math.random())*100000).toString(16).substring(1);
}
localStorage[ID_STORAGE_KEY] = `${s4()}${s4()}-${s4()}${s4()}`;
}
return localStorage[ID_STORAGE_KEY];
}
static moreInfo(entity) {
this.fireEvent("hass-more-info", {entityId: entity});
}
static longpress(element) {
customElements.whenDefined("long-press").then(() => {
const longpress = document.body.querySelector("long-press");
longpress.bind(element);
});
return element;
}
static hasTemplate(text) {
return /\[\[\s+.*\s+\]\]/.test(text);
}
static parseTemplateString(str, specialData = {}) {
if(typeof(str) !== "string") return text;
const FUNCTION = /^[a-zA-Z0-9_]+\(.*\)$/;
const EXPR = /([^=<>!]+)\s*(==|!=|<|>|<=|>=)\s*([^=<>!]+)/;
const SPECIAL = /^\{.+\}$/;
const STRING = /^"[^"]*"|'[^']*'$/;
if(typeof(specialData) === "string") specialData = {};
specialData = Object.assign({
user: this.hass.user.name,
browser: this.deviceID,
hash: location.hash.substr(1) || ' ',
}, specialData);
const _parse_function = (str) => {
let args = [str.substr(0, str.indexOf('(')).trim()]
str = str.substr(str.indexOf('(')+1);
while(str) {
let index = 0;
let parens = 0;
let quote = false;
while(str[index]) {
let c = str[index++];
if(c === quote && index > 1 && str[index-2] !== "\\")
quote = false;
else if(`"'`.includes(c))
quote = c;
if(quote) continue;
if(c === '(')
parens = parens + 1;
else if(c === ')') {
parens = parens - 1;
continue
}
if(parens > 0) continue;
if(",)".includes(c)) break;
}
args.push(str.substr(0, index-1).trim());
str = str.substr(index);
}
return args;
};
const _parse_special = (str) => {
str = str.substr(1, str.length - 2);
return specialData[str] || `{${str}}`;
};
const _parse_entity = (str) => {
str = str.split(".");
let v;
if(str[0].match(SPECIAL)) {
v = _parse_special(str.shift());
v = this.hass.states[v] || v;
} else {
v = this.hass.states[`${str.shift()}.${str.shift()}`];
if(!str.length) return v['state'];
}
str.forEach(item => v=v[item]);
return v;
}
const _eval_expr = (str) => {
str = EXPR.exec(str);
if(str === null) return false;
const lhs = this.parseTemplateString(str[1]);
const rhs = this.parseTemplateString(str[3]);
var expr = ''
if(parseFloat(lhs) != lhs)
expr = `"${lhs}" ${str[2]} "${rhs}"`;
else
expr = `${parseFloat(lhs)} ${str[2]} ${parseFloat(rhs)}`
return eval(expr);
}
const _eval_function = (args) => {
if(args[0] === "if") {
if(_eval_expr(args[1]))
return this.parseTemplateString(args[2]);
return this.parseTemplateString(args[3]);
}
}
try {
str = str.trim();
if(str.match(STRING))
return str.substr(1, str.length - 2);
if(str.match(SPECIAL))
return _parse_special(str);
if(str.match(FUNCTION))
return _eval_function(_parse_function(str));
if(str.includes("."))
return _parse_entity(str);
return str;
} catch (err) {
return `[[ Template matching failed: ${str} ]]`;
}
}
static parseTemplate(text, data = {}) {
if(typeof(text) !== "string") return text;
// Note: .*? is javascript regex syntax for NON-greedy matching
var RE_template = /\[\[\s(.*?)\s\]\]/g;
text = text.replace(RE_template, (str, p1, offset, s) => this.parseTemplateString(p1, data));
return text;
}
static args(script=null) {
script = script || document.currentScript;
var url = script.src;
url = url.substr(url.indexOf("?")+1)
let args = {};
url.split("&").forEach((a) => {
if(a.indexOf("=")) {
let parts = a.split("=");
args[parts[0]] = parts[1]
} else {
args[a] = true;
}
});
return args;
}
static localize(key, def="") {
const language = this.hass.language;
if(this.hass.resources[language] && this.hass.resources[language][key])
return this.hass.resources[language][key];
return def;
}
static popUp(title, message, large=false) {
let popup = document.createElement('div');
popup.innerHTML = `
<style>
app-toolbar {
color: var(--more-info-header-color);
background-color: var(--more-info-header-background);
}
</style>
<app-toolbar>
<paper-icon-button
icon="hass:close"
dialog-dismiss=""
></paper-icon-button>
<div class="main-title" main-title="">
${title}
</div>
</app-toolbar>
`;
popup.appendChild(message);
this.moreInfo(Object.keys(this.hass.states)[0]);
let moreInfo = document.querySelector("home-assistant")._moreInfoEl;
moreInfo._page = "none";
moreInfo.shadowRoot.appendChild(popup);
moreInfo.large = large;
document.querySelector("home-assistant").provideHass(message);
setTimeout(() => {
let interval = setInterval(() => {
if (moreInfo.getAttribute('aria-hidden')) {
popup.parentNode.removeChild(popup);
clearInterval(interval);
}
}, 100)
}, 1000);
return moreInfo;
}
static closePopUp() {
let moreInfo = document.querySelector("home-assistant")._moreInfoEl;
if (moreInfo) moreInfo.close()
}
static logger(message, script=null) {
if(!('debug' in this.args(script))) return;
if(typeof message !== "string")
message = JSON.stringify(message);
console.log(`%cDEBUG:%c ${message}`,
"color: blue; font-weight: bold", "");
}
});
// Global definition of cardTools
window.cardTools = customElements.get('card-tools');
console.info(`%cCARD-TOOLS IS INSTALLED
%cDeviceID: ${customElements.get('card-tools').deviceID}`,
"color: green; font-weight: bold",
"");