forked from maykar/kiosk-mode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kiosk-mode.js
237 lines (208 loc) · 9.08 KB
/
kiosk-mode.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
class KioskMode {
constructor() {
window.kioskModeEntities = {};
if (this.queryString("clear_km_cache")) this.setCache(["kmHeader", "kmSidebar", "kmOverflow", "kmMenuButton"], "false");
this.ha = document.querySelector("home-assistant");
this.main = this.ha.shadowRoot.querySelector("home-assistant-main").shadowRoot;
this.user = this.ha.hass.user;
this.llAttempts = 0;
this.run();
this.entityWatch();
new MutationObserver(this.watchDashboards).observe(this.main.querySelector("partial-panel-resolver"), {
childList: true,
});
}
run(lovelace = this.main.querySelector("ha-panel-lovelace")) {
if (this.queryString("disable_km") || !lovelace) return;
this.getConfig(lovelace);
}
getConfig(lovelace) {
this.llAttempts++;
try {
const llConfig = lovelace.lovelace.config;
const config = llConfig.kiosk_mode || {};
this.processConfig(lovelace, config);
} catch (e) {
if (this.llAttempts < 200) {
setTimeout(() => this.getConfig(lovelace), 50);
} else {
console.log("Lovelace config not found, continuing with default configuration.");
console.log(e);
this.processConfig(lovelace, {});
}
}
}
processConfig(lovelace, config) {
const dash = this.ha.hass.panelUrl;
if (!window.kioskModeEntities[dash]) window.kioskModeEntities[dash] = [];
this.hideHeader = this.hideSidebar = this.hideOverflow = this.ignoreEntity = this.ignoreMobile = false;
// Retrieve localStorage values & query string options.
const queryStringsSet =
this.cached(["kmHeader", "kmSidebar", "kmOverflow", "kmMenuButton"]) || this.queryString(["kiosk", "hide_sidebar", "hide_header", "hide_overflow", "hide_menubutton", "debug"]);
if (queryStringsSet) {
this.debug = this.queryString(["debug"]);
this.trace = this.queryString(["trace"]);
this.hideHeader = this.cached("kmHeader") || this.queryString(["kiosk", "hide_header"]);
this.hideSidebar = this.cached("kmSidebar") || this.queryString(["kiosk", "hide_sidebar"]);
this.hideOverflow = this.cached("kmOverflow") || this.queryString(["kiosk", "hide_overflow"]);
this.hideMenuButton = this.cached("kmMenuButton") || this.queryString(["kiosk", "hide_menubutton"]);
}
// Use config values only if config strings and cache aren't used.
this.hideHeader = queryStringsSet ? this.hideHeader : config.kiosk || config.hide_header;
this.hideSidebar = queryStringsSet ? this.hideSidebar : config.kiosk || config.hide_sidebar;
this.hideOverflow = queryStringsSet ? this.hideOverflow : config.kiosk || config.hide_overflow;
this.hideMenuButton = queryStringsSet ? this.hideMenuButton : config.kiosk || config.hide_menubutton;
const adminConfig = this.user.is_admin ? config.admin_settings : config.non_admin_settings;
if (adminConfig) this.setOptions(adminConfig);
if (config.user_settings) {
for (let conf of this.array(config.user_settings)) {
if (this.array(conf.users).some((x) => x.toLowerCase() == this.user.name.toLowerCase())) this.setOptions(conf);
}
}
const mobileConfig = this.ignoreMobile ? null : config.mobile_settings;
if (mobileConfig) {
const mobileWidth = mobileConfig.custom_width ? mobileConfig.custom_width : 812;
if (window.innerWidth <= mobileWidth) this.setOptions(mobileConfig);
}
const entityConfig = this.ignoreEntity ? null : config.entity_settings;
if (entityConfig) {
for (let conf of entityConfig) {
const entity = Object.keys(conf.entity)[0];
if (!window.kioskModeEntities[dash].includes(entity)) window.kioskModeEntities[dash].push(entity);
if (this.ha.hass.states[entity].state == conf.entity[entity]) {
if ("hide_header" in conf) this.hideHeader = conf.hide_header;
if ("hide_sidebar" in conf) this.hideSidebar = conf.hide_sidebar;
if ("hide_overflow" in conf) this.hideOverflow = conf.hide_overflow;
if ("hide_menubutton" in conf) this.hideMenuButton = conf.hide_menubutton;
if ("kiosk" in conf) this.hideHeader = this.hideSidebar = conf.kiosk;
}
}
}
this.insertStyles(lovelace);
}
insertStyles(lovelace) {
const huiRoot = lovelace.shadowRoot.querySelector("hui-root").shadowRoot;
const drawerLayout = this.main.querySelector("ha-sidebar");
const appToolbar = huiRoot.querySelector(".header");
const overflowStyle = "ha-button-menu{display:none !important;}";
const headerStyle = "#view{--header-height:0;}";
if (this.debug) {
console.log({ huiRoot, main: this.main, drawerLayout, appToolbar });
}
if (this.hideHeader || this.hideOverflow) {
this.addStyle(`${this.hideHeader ? headerStyle : ""}${this.hideOverflow ? overflowStyle : ""}`, huiRoot, "huiRoot");
if (this.queryString("cache")) {
if (this.hideHeader) this.setCache("kmHeader", "true");
if (this.hideOverflow) this.setCache("kmOverflow", "true");
}
} else {
this.removeStyle(huiRoot);
}
if (this.hideSidebar) {
this.addStyle(":host{--mdc-drawer-width:0 !important;}", drawerLayout, "drawerLayout");
this.addStyle(".header{display:none !important;}", appToolbar, "appToolbar");
if (this.queryString("cache")) this.setCache("kmSidebar", "true");
} else {
this.removeStyle([appToolbar, drawerLayout]);
}
if (this.hideMenuButton) {
this.addStyle("ha-menu-button{display:none !important;}", appToolbar, "appToolbar");
if (this.queryString("cache")) this.setCache("kmMenuButton", "true");
} else {
this.removeStyle(appToolbar);
}
// Resize window to "refresh" view.
window.dispatchEvent(new Event("resize"));
this.llAttempts = 0;
}
// Run on dashboard change.
watchDashboards(mutations) {
mutations.forEach(({ addedNodes }) => {
for (let node of addedNodes) if (node.localName == "ha-panel-lovelace") window.KioskMode.run(node);
});
}
// Run on entity change.
async entityWatch() {
(await window.hassConnection).conn.subscribeMessage((e) => this.entityWatchCallback(e), {
type: "subscribe_events",
event_type: "state_changed",
});
}
entityWatchCallback(event) {
const entities = window.kioskModeEntities[this.ha.hass.panelUrl] || [];
if (
entities.length &&
event.event_type == "state_changed" &&
entities.includes(event.data.entity_id) &&
(!event.data.old_state || event.data.new_state.state != event.data.old_state.state)
) {
this.run();
}
}
setOptions(config) {
this.hideHeader = config.kiosk || config.hide_header;
this.hideSidebar = config.kiosk || config.hide_sidebar;
this.hideOverflow = config.kiosk || config.hide_overflow;
this.hideMenuButton = config.kiosk || config.hide_menubutton;
this.ignoreEntity = config.ignore_entity_settings;
this.ignoreMobile = config.ignore_mobile_settings;
}
// Convert to array.
array(x) {
return Array.isArray(x) ? x : [x];
}
// Return true if keyword is found in query strings.
queryString(keywords) {
return this.array(keywords).some((x) => window.location.search.includes(x));
}
// Set localStorage item.
setCache(k, v) {
this.array(k).forEach((x) => window.localStorage.setItem(x, v));
}
// Retrieve localStorage item as bool.
cached(key) {
return this.array(key).some((x) => window.localStorage.getItem(x) == "true");
}
styleExists(elem) {
return elem.querySelector(`#kiosk_mode_${elem.localName}`);
}
addStyle(css, elem, calledFor) {
if (!elem) {
console.warn("Missing element that should have style added: " + calledFor);
if (this.trace) console.trace();
return;
}
if (!this.styleExists(elem)) {
const style = document.createElement("style");
style.setAttribute("id", `kiosk_mode_${calledFor ?? elem.localName}`);
style.innerHTML = css;
elem.appendChild(style);
}
}
removeStyle(elements) {
this.array(elements).forEach((elem) => {
if (!elem) {
console.warn("Missing element that should have style removed");
if (this.trace) console.trace();
return;
}
if (this.styleExists(elem)) elem.querySelector(`#kiosk_mode_${elem.localName}`).remove();
});
}
}
// Overly complicated console tag.
const conInfo = { header: "%c≡ kiosk-mode".padEnd(27), ver: "%cversion *DEV " };
const br = "%c\n";
const maxLen = Math.max(...Object.values(conInfo).map((el) => el.length));
for (const [key] of Object.entries(conInfo)) {
if (conInfo[key].length <= maxLen) conInfo[key] = conInfo[key].padEnd(maxLen);
if (key == "header") conInfo[key] = `${conInfo[key].slice(0, -1)}⋮ `;
}
const header =
"display:inline-block;border-width:1px 1px 0 1px;border-style:solid;border-color:#424242;color:white;background:#03a9f4;font-size:12px;padding:4px 4.5px 5px 6px;";
const info = "border-width:0px 1px 1px 1px;padding:7px;background:white;color:#424242;line-height:0.7;";
console.info(conInfo.header + br + conInfo.ver, header, "", `${header} ${info}`);
// Initial Run
Promise.resolve(customElements.whenDefined("hui-view")).then(() => {
window.KioskMode = new KioskMode();
});