-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtimeout.js
More file actions
219 lines (182 loc) · 6.21 KB
/
timeout.js
File metadata and controls
219 lines (182 loc) · 6.21 KB
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
class ViewTimeout {
constructor() {
this.timer = null;
this.checkInterval = null;
this.boundReset = this.resetTimer.bind(this);
// State
this.activePanelUrl = null; // The dashboard we are currently "serving"
this.currentUser = null;
this.homeView = "home";
this.timeoutDuration = 15000;
this.viewSpecificRedirects = {};
this.isEnabled = false;
// Reset triggers
this.resetOnMove = false;
this.resetOnClick = true;
// Start the global watcher
this.init();
}
get ha() {
return document.querySelector("home-assistant");
}
get main() {
return this.ha?.shadowRoot?.querySelector("home-assistant-main")?.shadowRoot;
}
get lovelace() {
// This dynamically grabs the CURRENT lovelace panel
return this.main?.querySelector("ha-panel-lovelace");
}
log(msg, error = false) {
const style = "color: orange; font-weight: bold; background: black; padding: 2px;";
if (error) {
console.error(`%c VIEWTIMEOUT %c ERROR: ${msg}`, style, "color: red;");
} else {
console.info(`%c VIEWTIMEOUT %c ${msg}`, style, "color: gray;");
}
}
init() {
// We check every second. This interval runs forever, across all dashboards.
this.checkInterval = setInterval(() => this.masterLoop(), 1000);
this.log("Service started. Waiting for config...");
}
// This loop runs every second to check:
// 1. Did we change dashboards?
// 2. If yes, load new config.
// 3. If no, run the timeout logic.
masterLoop() {
if (new URLSearchParams(window.location.search).has("disable_timeout")) return;
const currentPanelUrl = this.ha?.hass?.panelUrl;
// SCENARIO 1: Dashboard Change Detected
if (currentPanelUrl !== this.activePanelUrl) {
this.handleDashboardChange(currentPanelUrl);
return;
}
// SCENARIO 2: We are on the active dashboard, and it is enabled.
if (this.isEnabled) {
this.checkTimeoutLogic();
}
}
handleDashboardChange(newPanelUrl) {
// 1. Stop any running timers from the previous dashboard
this.stopTimer();
// 2. Try to find config for this new dashboard
// It might take a moment for the new ha-panel-lovelace to load its config
const llConfig = this.lovelace?.lovelace?.config;
if (llConfig && llConfig.view_timeout) {
// Config FOUND. Activate for this dashboard.
this.activePanelUrl = newPanelUrl;
this.parseConfig(llConfig);
} else {
// Config NOT FOUND.
// We update the activePanelUrl to prevent constantly retrying this logic every second
// But we mark isEnabled as false so we stay dormant.
// (Unless llConfig is completely null, meaning it hasn't loaded yet, then we wait and retry next loop)
if (this.lovelace?.lovelace) {
this.activePanelUrl = newPanelUrl;
this.isEnabled = false;
// Silent mode: We are on a dashboard that doesn't use ViewTimeout.
}
}
}
parseConfig(llConfig) {
const config = llConfig.view_timeout || {};
// Global Toggle Check
if (config.timeout === false) {
this.isEnabled = false;
return;
}
// User Whitelist Check
this.currentUser = this.ha?.hass?.user?.name?.toLowerCase();
if (config.users && Array.isArray(config.users)) {
const allowedUsers = config.users.map(u => u.toLowerCase());
if (!allowedUsers.includes(this.currentUser)) {
this.isEnabled = false;
return;
}
}
// Load Settings
this.timeoutDuration = config.duration ?? 15000;
this.homeView = config.default ?? "home";
this.resetOnMove = config.reset?.mouse_move ?? false;
this.resetOnClick = config.reset?.mouse_click ?? true;
this.viewSpecificRedirects = config.views || {};
// Activate
this.isEnabled = true;
this.log(`Active on /${this.activePanelUrl} (Timeout: ${this.timeoutDuration}ms)`);
}
getCurrentView() {
return window.location.pathname.split("/").pop();
}
checkTimeoutLogic() {
// Safety: If we drifted somehow, stop.
if (this.ha?.hass?.panelUrl !== this.activePanelUrl) return;
const currentView = this.getCurrentView();
// 1. Is this the default home view?
if (currentView === this.homeView) {
this.stopTimer();
return;
}
// 2. Is this view explicitly disabled?
const specificTarget = this.viewSpecificRedirects[currentView];
if (specificTarget === false) {
this.stopTimer();
return;
}
// 3. If no default home and no specific target, do nothing.
if (!this.homeView && !specificTarget) {
this.stopTimer();
return;
}
// Run timer if not already running
if (!this.timer) {
this.startTimer();
}
}
startTimer() {
// Re-bind listeners (idempotent, safe to call multiple times due to boundReset)
if (this.resetOnMove) window.addEventListener("mousemove", this.boundReset);
if (this.resetOnClick) window.addEventListener("click", this.boundReset);
this.resetTimer();
}
stopTimer() {
window.removeEventListener("mousemove", this.boundReset);
window.removeEventListener("click", this.boundReset);
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
resetTimer() {
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(() => this.executeRedirect(), this.timeoutDuration);
}
executeRedirect() {
// Double check we are still on the right dashboard
if (this.ha?.hass?.panelUrl !== this.activePanelUrl) {
this.stopTimer();
return;
}
this.stopTimer();
try {
const activeEl = this.main?.activeElement || document.activeElement;
activeEl?.blur();
} catch (e) {}
const currentView = this.getCurrentView();
const target = this.viewSpecificRedirects[currentView] ?? this.homeView;
if (target) {
this.navigate(`/${this.activePanelUrl}/${target}`);
}
}
navigate(path) {
window.history.pushState(null, "", path);
window.dispatchEvent(new CustomEvent("location-changed", {
bubbles: true,
composed: true
}));
}
}
Promise.resolve(customElements.whenDefined("hui-view")).then(() => {
if (!window.ViewTimeout) {
window.ViewTimeout = new ViewTimeout();
}
});