-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtab-redirect-card.js
70 lines (61 loc) · 2.64 KB
/
tab-redirect-card.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
class TabRedirectCard extends HTMLElement {
set hass(hass) {
this.style.display = 'none';
const homeAssistant = document.querySelector('home-assistant');
const root = homeAssistant.shadowRoot.querySelector('home-assistant-main').shadowRoot;
const sidebarRoot = root.querySelector('ha-sidebar').shadowRoot;
const sidebarListbox = sidebarRoot.querySelector('paper-listbox');
const panel = root.querySelector('ha-panel-lovelace')
if(!panel) { return; }
const uiRoot = panel.shadowRoot.querySelector('hui-root')
if(!uiRoot) { return; }
const isEditing = uiRoot.shadowRoot.querySelector('.edit-mode');
if(isEditing) { return; }
let tabs = uiRoot.shadowRoot.querySelector('ha-tabs');
if(!tabs) {
tabs = uiRoot.shadowRoot.querySelector('paper-tabs');
}
const tabList = tabs.querySelectorAll('paper-tab');
const userConfigs = this.config.redirect.filter((item) => item.user === hass.user.name);
userConfigs.forEach((config) => {
const state = hass.states[config.entity_id].state;
const keyId = `${config.user}-${config.entity_id}`;
const lastSeenStateKey = `TabRedirectCard-LastSeenState-${keyId}`;
const lastRedirectKey = `TabRedirectCard-LastRedirect-${keyId}`;
// if previous recorded state is different, remove cache
if(state !== sessionStorage.getItem(lastSeenStateKey)) {
sessionStorage.removeItem(lastRedirectKey);
}
sessionStorage.setItem(lastSeenStateKey, state);
// if we should redirect and cache is empty
if(state === config.entity_state && !sessionStorage.getItem(lastRedirectKey)) {
sessionStorage.setItem(lastRedirectKey, 'true');
tabList[config.redirect_to_tab_index].click();
}
});
}
setConfig(config) {
if (!config.redirect || !Array.isArray(config.redirect) || config.redirect.length === 0) {
throw new Error('You need to define a redirect (array)');
}
config.redirect.forEach((redirect) => {
if(!redirect) {
throw new Error('You need to define a redirect (array)');
}
if(!redirect.user || typeof redirect.user !== 'string') {
throw new Error('You need to define user (string)');
}
if(!redirect.entity_id || typeof redirect.entity_id !== 'string') {
throw new Error('You need to define entity_id (string)');
}
if(!redirect.entity_state) {
throw new Error('You need to define entity_state');
}
if(redirect.redirect_to_tab_index === undefined || typeof redirect.redirect_to_tab_index !== 'number' || !Number.isInteger(redirect.redirect_to_tab_index)) {
throw new Error('You need to define redirect_to_tab_index (integer, starting from 0)');
}
});
this.config = config;
}
}
customElements.define('tab-redirect-card', TabRedirectCard);