forked from matteobrusa/HASlideshow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhaslideshow.js
More file actions
529 lines (477 loc) · 18.6 KB
/
Copy pathhaslideshow.js
File metadata and controls
529 lines (477 loc) · 18.6 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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Formatting for debug output
function info(obj) {
console.log(
'%c Background Slideshow %c ' + (typeof obj == "string" ? obj : JSON.stringify(obj)),
'background: black; font-weight: bold; padding: 2px; border-radius: 2px',
'background: transparent; font-weight: normal; padding: 0px; border-radius: 0px'
);
}
function debug(obj) {
console.debug(
'%c Background Slideshow %c ' + (typeof obj == "string" ? obj : JSON.stringify(obj)),
'background: black; font-weight: bold; padding: 2px; border-radius: 2px',
'background: transparent; font-weight: normal; padding: 0px; border-radius: 0px'
);
}
/////////////////////////////////////////////////////////////////
// This code block randomizes the background images. Mostly...
let seed;
const getPrimes = (min, max) => {
const result = Array(max + 1)
.fill(0)
.map((_, i) => i);
for (let i = 2; i <= Math.sqrt(max + 1); i++) {
for (let j = i ** 2; j < max + 1; j += i) delete result[j];
}
return Object.values(result.slice(Math.max(min, 2)));
};
const getRandNum = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
};
const getRandPrime = (min, max) => {
const primes = getPrimes(min, max);
return primes[getRandNum(0, primes.length - 1)];
};
seed = getRandPrime(1, 100000);
debug("Seed initialized: " + seed);
/////////////////////////////////////////////////////////////////
const defaultPath = "/local/HASlideshow/backgrounds/";
// Cache for each path: {imagesCount, current}
const pathData = new Map();
let currentPath;
// Function to count images for a given path
function countImagesForPath(path, callback) {
function checkNumber(n, cb) {
var http = new XMLHttpRequest();
http.open('HEAD', path + n + ".jpg");
http.onreadystatechange = function () {
if (this.readyState == this.DONE) {
debug("Checked image " + n + ".jpg, exists: " + (this.status != 404));
cb(this.status != 404);
}
};
http.send();
}
let upward = true;
function recur(n, interval) {
checkNumber(n, function (exists) {
debug("interval: " + interval + " n: " + n + (exists ? " exists" : " not found"));
upward = upward && exists;
if (upward) interval *= 2;
else interval /= 2;
if (exists) {
if (interval >= 1) recur(n + interval, interval);
else {
const imagesCount = n + 1;
info(imagesCount + " pics available in " + path);
debug("Images count set for " + path);
callback(imagesCount);
}
} else {
if (interval >= 1) recur(n - interval, interval);
else {
const imagesCount = n;
info(imagesCount + " pics available in " + path);
debug("Images count set for " + path);
callback(imagesCount);
}
}
});
}
checkNumber(0, function (exists) {
if (exists) recur(2, 1);
else {
info("No local images found in " + path + ", slideshow disabled for this path");
callback(0);
}
});
}
function bs_clearBackground() {
const elem = bs_getBackgroundElement();
debug("bs_clearBackground called");
if (elem) {
elem.style.setProperty('--lovelace-background', 'none', 'important');
debug("Cleared background style");
} else {
debug("No elem for clearing theme background");
}
// Remove transition backgrounds from the container
if (elem) {
const bgOld = elem.querySelector('#bs-bg-old');
if (bgOld) {
bgOld.remove();
debug("Removed bg-old layer");
} else {
debug("No bg-old layer to remove");
}
const bgNew = elem.querySelector('#bs-bg-new');
if (bgNew) {
bgNew.remove();
debug("Removed bg-new layer");
} else {
debug("No bg-new layer to remove");
}
} else {
debug("No elem for removing layers");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// This path might need updating from time to time after an HA update. No matter where the theme is
// applied, (Globally, by User, or by Dashboard) this should find the CSS vars injected by the
// HASlideshow theme. The deepest element where a theme could be applied are the individual Lovelace
// dashboards so we just need to make sure the path crawls deep enough to find the <hui-view-container>.
function bs_getBackgroundElement() {
try {
const elem = document.querySelector("body > home-assistant")
.shadowRoot
.querySelector("home-assistant-main")
.shadowRoot
.querySelector("ha-drawer > partial-panel-resolver > ha-panel-lovelace")
.shadowRoot
.querySelector("hui-root")
.shadowRoot
.querySelector("hui-view-container#view");
debug("bs_getBackgroundElement: " + (elem ? "found" : "not found"));
return elem;
} catch (e) {
debug("Error accessing background element DOM: " + e.message);
return null;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
function bs_checkBackgroundElement(featureVar) {
const elem = bs_getBackgroundElement();
if (!elem) {
let base = featureVar.replace('--bs-', '').replace('-enabled', '');
if (base === 'doubletap') base = 'double-tap';
if (base === 'image') base = 'image-path';
debug(`Background element not found, cannot check ${base}`);
return null;
}
const currentView = elem.querySelector('hui-view');
if (!currentView) {
let base = featureVar.replace('--bs-', '').replace('-enabled', '');
if (base === 'doubletap') base = 'double-tap';
if (base === 'image') base = 'image-path';
debug(`Current view not found, cannot check ${base}`);
return null;
}
const value = getComputedStyle(currentView).getPropertyValue(featureVar).trim();
let base = featureVar.replace('--bs-', '').replace('-enabled', '');
if (base === 'doubletap') base = 'double-tap';
if (base === 'image') base = 'image-path';
const featureName = base.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('-');
debug(`Retrieved ${featureName}: ${value}`);
return value;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// If the theme doesn't specify these values it falls back to default to prevent errors.
// This retrieves how often the background changes images - default 10 seconds
let updateIntervalValue = bs_checkBackgroundElement('--bs-updateInterval');
let updateInterval = updateIntervalValue ? parseInt(updateIntervalValue, 10) : 10;
debug("Initial updateInterval: " + updateInterval);
// This retrieves the speed of the image transition animation - default 1000 milliseconds
let transitionDurationValue = bs_checkBackgroundElement('--bs-transitionDuration');
let transitionDuration = transitionDurationValue ? parseInt(transitionDurationValue, 10) : 1000;
debug("Initial transitionDuration: " + transitionDuration);
// This retrieves the custom image path - default to hardcoded
let imagePathValue = bs_checkBackgroundElement('--bs-image-path');
let initialPath = imagePathValue ? imagePathValue : defaultPath;
debug("Initial image path: " + initialPath);
///////////////////////////////////////////////////////////////////////////////////////////////////
let previouslyEnabled = false;
function bs_ensureBackgroundLayers() {
const view = bs_getBackgroundElement();
debug("bs_ensureBackgroundLayers called");
if (!view) return;
// Override any theme background
view.style.setProperty('--lovelace-background', 'none', 'important');
debug("Overrode theme background");
let bgOld = view.querySelector('#bs-bg-old');
let bgNew = view.querySelector('#bs-bg-new');
if (!bgOld) {
bgOld = document.createElement('div');
bgOld.id = 'bs-bg-old';
bgOld.style.position = 'fixed';
bgOld.style.top = '0';
bgOld.style.left = '0';
bgOld.style.width = '100%';
bgOld.style.height = '100%';
bgOld.style.backgroundSize = 'cover';
bgOld.style.backgroundPosition = 'center';
bgOld.style.backgroundRepeat = 'no-repeat';
bgOld.style.transition = `opacity ${transitionDuration / 1000}s ease-in-out`;
bgOld.style.opacity = '0';
bgOld.style.zIndex = '-2';
// Anti-flicker for transitions
bgOld.style.webkitBackfaceVisibility = 'hidden';
bgOld.style.backfaceVisibility = 'hidden';
// Hardware acceleration
bgOld.style.transform = 'translate3d(0,0,0)';
// GPU optimization for opacity changes
bgOld.style.willChange = 'opacity';
view.insertBefore(bgOld, view.firstChild);
debug("Created bg-old layer");
} else {
debug("bg-old layer already exists");
// Ensure anti-flicker styles on existing layer
bgOld.style.webkitBackfaceVisibility = 'hidden';
bgOld.style.backfaceVisibility = 'hidden';
bgOld.style.transform = 'translate3d(0,0,0)';
bgOld.style.willChange = 'opacity';
}
if (!bgNew) {
bgNew = document.createElement('div');
bgNew.id = 'bs-bg-new';
bgNew.style.position = 'fixed';
bgNew.style.top = '0';
bgNew.style.left = '0';
bgNew.style.width = '100%';
bgNew.style.height = '100%';
bgNew.style.backgroundSize = 'cover';
bgNew.style.backgroundPosition = 'center';
bgNew.style.backgroundRepeat = 'no-repeat';
bgNew.style.transition = `opacity ${transitionDuration / 1000}s ease-in-out`;
bgNew.style.opacity = '0';
bgNew.style.zIndex = '-1';
// Anti-flicker for transitions
bgNew.style.webkitBackfaceVisibility = 'hidden';
bgNew.style.backfaceVisibility = 'hidden';
// Hardware acceleration
bgNew.style.transform = 'translate3d(0,0,0)';
// GPU optimization for opacity changes
bgNew.style.willChange = 'opacity';
view.insertBefore(bgNew, view.firstChild);
debug("Created bg-new layer");
} else {
debug("bg-new layer already exists");
// Ensure anti-flicker styles on existing layer
bgNew.style.webkitBackfaceVisibility = 'hidden';
bgNew.style.backfaceVisibility = 'hidden';
bgNew.style.transform = 'translate3d(0,0,0)';
bgNew.style.willChange = 'opacity';
}
// Update transition duration if changed
[bgOld, bgNew].forEach(bg => {
if (bg) {
bg.style.transition = `opacity ${transitionDuration / 1000}s ease-in-out`;
}
});
debug("Updated transition styles on layers");
}
function bs_transitionToNewBackground(url, isInitial = false) {
const bgElement = bs_getBackgroundElement();
if (!bgElement) {
debug("No bgElement for transition");
return;
}
const bgOld = bgElement.querySelector('#bs-bg-old');
const bgNew = bgElement.querySelector('#bs-bg-new');
debug("bs_transitionToNewBackground called for: " + url + ", isInitial: " + isInitial);
if (!bgOld || !bgNew) {
debug("Missing bgOld or bgNew, aborting transition");
return;
}
// Preload image
const img = new Image();
img.src = url;
img.onload = () => {
debug("Image preloaded successfully");
if (isInitial) {
// For initial: fade in on bgOld only, no cross-fade/swap
bgOld.style.backgroundImage = `url("${url}")`;
bgOld.style.opacity = '1';
debug(`Initial fade-in to background: ${url}`);
} else {
// Standard cross-fade: set bgNew and fade in
bgNew.style.backgroundImage = `url("${url}")`;
bgNew.style.opacity = '1';
debug(`Starting cross-fade transition to new background: ${url}`);
// After transition, swap layers
setTimeout(() => {
bgOld.style.backgroundImage = `url("${url}")`;
bgOld.style.opacity = '1';
bgNew.style.opacity = '0';
debug(`Completed cross-fade, swapped to ${url}`);
}, transitionDuration);
}
};
img.onerror = () => {
debug("Image preload failed for: " + url);
};
}
function performUpdate(isNavigation = false) {
debug("performUpdate called, isNavigation: " + isNavigation);
const bgElement = bs_getBackgroundElement();
if (!bgElement) {
debug("Background element not found, skipping update");
return;
}
// Update interval and duration from current view
const currentUpdateIntervalValue = bs_checkBackgroundElement('--bs-updateInterval');
if (currentUpdateIntervalValue) {
const newInterval = parseInt(currentUpdateIntervalValue, 10);
if (newInterval && newInterval !== updateInterval) {
updateInterval = newInterval;
debug(`Updated interval to ${updateInterval}`);
// Restart interval if running
if (intervalId) {
clearInterval(intervalId);
intervalId = setInterval(() => {
debug("Interval update event");
bs_update(false);
}, updateInterval * 1000);
debug(`Restarted interval at ${updateInterval} seconds`);
}
}
}
const currentTransitionDurationValue = bs_checkBackgroundElement('--bs-transitionDuration');
if (currentTransitionDurationValue) {
const newDuration = parseInt(currentTransitionDurationValue, 10);
if (newDuration && newDuration !== transitionDuration) {
transitionDuration = newDuration;
debug(`Updated transition duration to ${transitionDuration}`);
}
}
const currentlyEnabled = bs_checkBackgroundElement('--bs-slideshow-enabled') === 'enabled';
debug("Currently enabled: " + currentlyEnabled + ", previouslyEnabled: " + previouslyEnabled);
if (currentlyEnabled) {
debug("Slideshow enabled in theme, performing update");
bs_ensureBackgroundLayers();
const bgOld = bgElement.querySelector('#bs-bg-old');
const bgNew = bgElement.querySelector('#bs-bg-new');
let url;
let shouldCycleAndTransition = true;
const pathInfo = pathData.get(currentPath);
const imagesCount = pathInfo.imagesCount;
let current = pathInfo.current;
let isInitialSetup = (current === undefined);
if (isNavigation) {
if (previouslyEnabled && current !== undefined && imagesCount > 0) {
// Resume previous image instantly without blanking or transition
if (bgOld && bgNew && bgOld.style.opacity === '1' && bgNew.style.opacity === '0') {
// Layers already in correct state (persisted from previous tab) – no need to re-set
debug("Navigation resume: layers already correct, skipping re-set");
shouldCycleAndTransition = false;
isInitialSetup = false;
} else {
// Fallback: set previous image instantly (omit cache buster for speed/cache hit)
const url = currentPath + current + ".jpg"; // No ?t= for instant resume
if (bgOld && bgNew) {
bgOld.style.backgroundImage = `url("${url}")`;
bgOld.style.opacity = '1';
bgNew.style.opacity = '0';
}
debug("Navigation resume: set previous image (fallback)");
shouldCycleAndTransition = false;
isInitialSetup = false;
}
} else {
// Fresh enable on navigation: blank and prepare for initial
if (bgOld) bgOld.style.opacity = '0';
if (bgNew) bgNew.style.opacity = '0';
debug("Blanking for fresh enable on navigation");
isInitialSetup = true;
}
} else {
// Non-navigation (interval, initial, doubletap): no special blanking, proceed to cycle/transition
debug("Non-navigation update: proceeding to cycle and transition");
}
if (shouldCycleAndTransition && imagesCount > 0) {
if (current === undefined) {
current = Math.floor(Math.random() * imagesCount);
debug(`Initialized current to ${current} for path ${currentPath}`);
} else {
current = (current + seed) % imagesCount;
}
pathInfo.current = current;
url = currentPath + current + ".jpg?t=" + Date.now(); // Cache buster
debug(`Cycling to image ${current} for path ${currentPath}`);
// Transition to new (or initial)
bs_transitionToNewBackground(url, isInitialSetup);
info("Updated background to " + url);
} else if (shouldCycleAndTransition) {
debug("No images available or condition not met, skipping cycle/transition");
}
previouslyEnabled = true;
} else {
debug("Slideshow not enabled in theme, clearing background");
bs_clearBackground();
previouslyEnabled = false;
}
}
function bs_update(isNavigation = false) {
debug("bs_update called, isNavigation: " + isNavigation);
const imagePathValue = bs_checkBackgroundElement('--bs-image-path');
const newPath = imagePathValue ? imagePathValue : defaultPath;
if (currentPath !== newPath || !pathData.has(newPath)) {
debug(`Path changed or not initialized: from ${currentPath} to ${newPath}`);
countImagesForPath(newPath, count => {
pathData.set(newPath, {imagesCount: count, current: undefined});
currentPath = newPath;
performUpdate(isNavigation);
});
} else {
performUpdate(isNavigation);
}
}
var bs_lastTap = 0;
function bs_handle_tap(e) {
const now = Date.now();
if (now - bs_lastTap < 500) {
// detect double tap
debug("Double tap event - manual update");
if (bs_checkBackgroundElement('--bs-doubletap-enabled') === 'enabled' && bs_checkBackgroundElement('--bs-slideshow-enabled') === 'enabled') {
bs_update();
} else {
debug("Double tap ignored - slideshow or double-tap not enabled");
}
}
bs_lastTap = now;
}
var bs_tap_handler = null;
function bs_register_tap() {
if (bs_tap_handler == null) {
bs_tap_handler = 1;
document.body.addEventListener('pointerdown', bs_handle_tap);
debug("Registered tap handler");
} else {
debug("Tap handler already registered");
}
}
let intervalId;
function bs_start() {
debug("bs_start called");
bs_register_tap();
bs_update(); // Initial immediate update
if (intervalId) {
clearInterval(intervalId);
debug("Cleared existing interval");
}
intervalId = setInterval(() => {
debug("Interval update event");
bs_update(false);
}, updateInterval * 1000);
debug(`Started interval updates every ${updateInterval} seconds`);
// Listen for HA navigation event
window.addEventListener('location-changed', () => {
debug("Detected navigation (location-changed event)");
// Defer to allow DOM to update – increased to 100ms for reliability
setTimeout(() => bs_update(true), 100);
});
debug("HA location-changed listener registered");
// Additional listener for popstate (for synthetic navigation like swipes)
window.addEventListener('popstate', () => {
debug("Detected popstate event (likely swipe navigation)");
// Defer to allow DOM to update – increased to 100ms for reliability
setTimeout(() => bs_update(true), 100);
});
debug("popstate listener registered");
}
// Initial setup
const initialImagePathValue = bs_checkBackgroundElement('--bs-image-path');
currentPath = initialImagePathValue ? initialImagePathValue : defaultPath;
countImagesForPath(currentPath, count => {
pathData.set(currentPath, {imagesCount: count, current: undefined});
bs_start();
});