-
-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathkiosk.ts
More file actions
659 lines (576 loc) · 18.8 KB
/
Copy pathkiosk.ts
File metadata and controls
659 lines (576 loc) · 18.8 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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
import { formatRFC3339 } from "date-fns/formatRFC3339";
import DOMPurify from "dompurify";
import htmx from "htmx.org";
import type { TimeFormat } from "./clock";
import { initClock } from "./clock";
import {
addFullscreenEventListener,
fullscreenAPI,
toggleFullscreen,
} from "./fullscreen";
import fullyKiosk from "./fullykiosk";
import { livePhoto } from "./live-photo";
import {
disableAssetNavigationButtons,
enableAssetNavigationButtons,
initMenu,
toggleAssetOverlay,
toggleRedirectsOverlay,
} from "./menu";
import { toggleMute } from "./mute";
import {
initPolling,
pausePolling,
resumePolling,
startPolling,
stopPolling,
togglePolling,
triggerNewAsset,
videoHandler,
} from "./polling";
import { sleepMode } from "./sleep";
import { preventSleep } from "./wakelock";
import { weatherRotationPosition } from "./weather";
import { initMqttSSE } from "./mqtt-sse";
("use strict");
interface HTMXEvent extends Event {
preventDefault: () => void;
detail: {
successful: boolean;
parameters: FormData;
method: string;
pathInfo: {
requestPath: string;
};
};
}
enum customKeyboardActions {
MUTE = "mute",
REDIRECTS = "redirects",
PAUSE = "pause",
MORE_INFO = "more-info",
FULLSCREEN = "fullscreen",
}
/**
* Configuration data for managing the kiosk display and behavior
*/
type KioskData = {
debug: boolean;
debugVerbose: boolean;
version: string;
langCode: string;
params: Record<string, unknown>;
duration: number;
disableNavigation: boolean;
disableScreensaver: boolean;
showDate: boolean;
dateFormat: string;
showTime: boolean;
timeFormat: TimeFormat;
showAmPm: boolean;
clockSource: "client" | "server";
transition: string;
showMoreInfo: boolean;
showRedirects: boolean;
livePhotos: boolean;
livePhotoLoopDelay: number;
burnInInterval: number;
burnInDuration: number;
httpTimeout: number;
upArrowAction: string;
downArrowAction: string;
};
const MAX_FRAMES: number = 2 as const;
const TIMEOUT_RETRIES: number = 2 as const;
const timeouts: Record<string, number> = {};
// Parse kiosk data from the HTML element
const kioskData: KioskData = JSON.parse(
document.getElementById("kiosk-data")?.textContent || "{}",
);
// Set polling interval based on the duration rate in kiosk data
const pollInterval = htmx.parseInterval(`${kioskData.duration}s`);
// Cache DOM elements for better performance
const documentBody = document.body;
const fullscreenButton = htmx.find(
".navigation--fullscreen",
) as HTMLElement | null;
const fullScreenButtonSeperator = htmx.find(
".navigation--fullscreen-separator",
) as HTMLElement | null;
const kiosk = htmx.find("#kiosk") as HTMLElement | null;
const kioskQueries = htmx.findAll(".kiosk-param");
const menu = htmx.find(".navigation") as HTMLElement | null;
const menuInteraction = htmx.find(
"#navigation-interaction-area--menu",
) as HTMLElement | null;
const menuPausePlayButton = htmx.find(
".navigation--play-pause",
) as HTMLElement | null;
const nextImageMenuButton = htmx.find(
".navigation--next-asset",
) as HTMLElement | null;
const prevImageMenuButton = htmx.find(
".navigation--prev-asset",
) as HTMLElement | null;
const toggleMuteMenuButton = htmx.find(
".navigation--mute",
) as HTMLElement | null;
const moreInfoButton = htmx.find(
".navigation--more-info",
) as HTMLElement | null;
const linksButton = htmx.find(".navigation--links") as HTMLElement | null;
const offlineSVG = htmx.find("#offline") as HTMLElement | null;
let requestInFlight = false;
let burnInTimerId: number | null = null;
/**
* Initialize Kiosk functionality
* @description Sets up kiosk by configuring:
* - Debug logging if verbose mode enabled
* - Clock display with configured date/time settings
* - Screen sleep prevention if enabled
* - Service worker registration for offline functionality
* - Fullscreen capability checking and button setup
* - Image polling with configured interval
* - Navigation menu initialization
* - Event listener registration for interactivity
* @returns {Promise<void>} Promise that resolves when initialization is complete
*/
async function init(): Promise<void> {
if (kioskData.debugVerbose) {
htmx.logAll();
}
const MILLISECONDS_PER_SECOND = 1000;
const TIMEOUT_GRACE_FACTOR = 3;
if (kioskData.httpTimeout <= 0) {
htmx.config.timeout = 0;
} else {
htmx.config.timeout =
kioskData.httpTimeout *
MILLISECONDS_PER_SECOND *
TIMEOUT_GRACE_FACTOR;
}
if (
kioskData.clockSource === "client" &&
(kioskData.showDate || kioskData.showTime)
) {
initClock(
kioskData.showDate,
kioskData.dateFormat,
kioskData.showTime,
kioskData.timeFormat,
kioskData.showAmPm,
kioskData.langCode,
);
}
if (kioskData.disableScreensaver) {
await preventSleep();
}
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/assets/js/sw.js").then(
() => {
console.log("ServiceWorker registration successful");
},
(err) => {
console.log("ServiceWorker registration failed: ", err);
},
);
}
if (!fullscreenAPI.requestFullscreen) {
fullscreenButton && htmx.remove(fullscreenButton);
fullScreenButtonSeperator && htmx.remove(fullScreenButtonSeperator);
}
if (pollInterval) {
initPolling(pollInterval, kiosk, menu);
} else {
console.error("Could not start polling");
}
initMenu(
kioskData.disableNavigation,
nextImageMenuButton as HTMLElement,
prevImageMenuButton as HTMLElement,
kioskData.showMoreInfo,
handleInfoKeyPress,
handleRedirectsKeyPress,
);
addEventListeners();
if (kioskData.livePhotos) livePhoto(kioskData.livePhotoLoopDelay);
initMqttSSE();
// Burn-in prevention
if (kioskData.burnInInterval > 0 && kioskData.burnInDuration > 0)
burnInCycle();
}
function burnInCycle() {
if (burnInTimerId !== null) {
clearTimeout(burnInTimerId);
burnInTimerId = null;
}
const runBurnInCycle = () => {
document.body.classList.add("burn-in-dim");
console.debug("Burn-in cycle started");
setTimeout(() => {
document.body.classList.remove("burn-in-dim");
console.debug("Burn-in cycle ended");
burnInTimerId = setTimeout(
runBurnInCycle,
kioskData.burnInInterval * 1000,
);
}, kioskData.burnInDuration * 1000);
};
burnInTimerId = setTimeout(runBurnInCycle, kioskData.burnInInterval * 1000);
}
/**
* Handler for fullscreen button clicks
* @description Toggles fullscreen mode for the document body using the browser's fullscreen API
* The button state is automatically updated based on fullscreen status
*/
function handleFullscreenClick(): void {
toggleFullscreen(documentBody, fullscreenButton);
}
/**
* Handles toggling of overlays with associated polling state management
* @param overlayClass - CSS class name that identifies the overlay
* @param toggleFn - Function to toggle the overlay visibility
* @description Manages overlay state by:
* - Checking current polling and overlay states
* - Toggling polling if needed based on overlay state
* - Toggling the overlay visibility
*/
function handleOverlayToggle(overlayClass: string, toggleFn: () => void): void {
const isPollingPaused = document.body.classList.contains("polling-paused");
const isOverlayOpen = document.body.classList.contains(overlayClass);
if (isPollingPaused && isOverlayOpen) {
togglePolling();
toggleFn();
} else {
if (!isPollingPaused) {
togglePolling();
}
toggleFn();
}
}
/**
* Handles keyboard shortcut for toggling image info overlay
* @description Toggles the image info overlay and manages polling state
* when 'i' key is pressed
*/
function handleInfoKeyPress(): void {
handleOverlayToggle("more-info", toggleAssetOverlay);
}
/**
* Handles keyboard shortcut for toggling redirects overlay
* @description Toggles the redirects overlay and manages polling state
* when 'r' key is pressed
*/
function handleRedirectsKeyPress(): void {
handleOverlayToggle("redirects-open", toggleRedirectsOverlay);
}
function keyboardActionPause(e: KeyboardEvent): void {
e.preventDefault();
togglePolling(true);
}
function keyboardActionInfo(e: KeyboardEvent): void {
if (!kioskData.showMoreInfo) return;
if (e.ctrlKey || e.metaKey) return;
e.preventDefault();
handleInfoKeyPress();
}
function keyboardActionRedirects(e: KeyboardEvent): void {
if (!kioskData.showRedirects) return;
if (e.ctrlKey || e.metaKey) return;
e.preventDefault();
handleRedirectsKeyPress();
}
function keyboardActionMute(e: KeyboardEvent): void {
if (!toggleMuteMenuButton) return;
e.preventDefault();
toggleMute();
}
function keyboardActionFullscreen(e: KeyboardEvent): void {
e.preventDefault();
handleFullscreenClick();
}
function handleCustomKeyboardAction(
e: KeyboardEvent,
customKeyboardAction: string,
): void {
switch (customKeyboardAction) {
case customKeyboardActions.MUTE:
keyboardActionMute(e);
break;
case customKeyboardActions.REDIRECTS:
keyboardActionRedirects(e);
break;
case customKeyboardActions.PAUSE:
keyboardActionPause(e);
break;
case customKeyboardActions.MORE_INFO:
keyboardActionInfo(e);
break;
case customKeyboardActions.FULLSCREEN:
keyboardActionFullscreen(e);
break;
default:
break;
}
}
/**
* Add event listeners to Kiosk elements
* @description Sets up all interactive behaviors and event handling:
* - Menu interaction for polling control via clicks
* - Keyboard shortcuts (Space for polling, 'i' for info overlay)
* - Fullscreen mode toggling via button
* - Image overlay visibility control
* - HTMX error handling for offline detection
* - Server connectivity status monitoring and display
* - Mute button handling
*/
function addEventListeners(): void {
// Unable to send ajax. probably offline.
htmx.on("htmx:sendError", () => {
releaseRequestLock();
if (!offlineSVG) {
console.error("offline svg missing");
return;
}
htmx.addClass(offlineSVG, "offline");
});
// Server online check. Fires after every AJAX request.
htmx.on("htmx:afterRequest", (e: HTMXEvent) => {
if (!offlineSVG) {
console.error("offline svg missing");
return;
}
if (e.detail.successful) {
htmx.removeClass(offlineSVG, "offline");
timeouts[e.detail.pathInfo.requestPath] = 0;
} else {
htmx.addClass(offlineSVG, "offline");
}
});
htmx.on("htmx:timeout", (e: HTMXEvent) => {
let currentTimeout = timeouts[e.detail.pathInfo.requestPath];
currentTimeout =
currentTimeout === undefined || Number.isNaN(currentTimeout)
? 1
: currentTimeout + 1;
timeouts[e.detail.pathInfo.requestPath] = currentTimeout;
if (currentTimeout > TIMEOUT_RETRIES) {
window.location.reload();
}
});
if (kioskData.disableNavigation) {
console.log("Navigation disabled");
return;
}
// Pause/resume polling and show/hide menu
menuInteraction?.addEventListener("click", () => togglePolling());
menuPausePlayButton?.addEventListener("click", () => togglePolling());
document.addEventListener("keydown", (e) => {
if (e.target !== document.body) return;
switch (e.code) {
case "KeyP":
if (!e.shiftKey) {
// Regular P
e.preventDefault();
pausePolling(true);
} else {
// Shift + P
e.preventDefault();
resumePolling(true);
}
break;
case "Space":
e.preventDefault();
togglePolling(true);
break;
case "KeyI":
keyboardActionInfo(e);
break;
case "KeyR":
keyboardActionRedirects(e);
break;
case "KeyM":
keyboardActionMute(e);
break;
case "ArrowUp":
handleCustomKeyboardAction(e, kioskData.upArrowAction);
break;
case "ArrowDown":
handleCustomKeyboardAction(e, kioskData.downArrowAction);
break;
}
});
// Fullscreen
fullscreenButton?.addEventListener("click", handleFullscreenClick);
addFullscreenEventListener(fullscreenButton);
// Toggle mute
toggleMuteMenuButton?.addEventListener("click", toggleMute);
// More info overlay
moreInfoButton?.addEventListener("click", () => toggleAssetOverlay());
// Links overlay
linksButton?.addEventListener("click", () => toggleRedirectsOverlay());
}
/**
* Performs DOM cleanup to prevent memory leaks
* @description Performs two cleanup operations:
* 1. Removes any script tags in the kiosk element after 1 second delay
* 2. Removes oldest frame element when total frames exceed MAX_FRAMES
*
* This helps maintain optimal performance by preventing too many
* elements accumulating in the DOM over time.
*
* @returns {Promise<void>} Resolves when cleanup is complete
* @throws {Error} If frame removal operation fails
*/
async function cleanupFrames(): Promise<void> {
const kioskScripts = htmx.findAll(kiosk as HTMLElement, "script");
if (kioskScripts?.length) {
kioskScripts.forEach((s) => {
htmx.remove(s, 1000);
});
}
const frames = htmx.findAll(".frame");
if (!frames?.length) {
console.debug("No frames found to clean up");
return;
}
if (frames.length > MAX_FRAMES) {
try {
htmx.remove(frames[0]);
} catch (error) {
console.error("Failed to remove frame:", error);
}
}
}
/**
* Sets a lock to prevent concurrent requests
* @param {HTMXEvent} e Event object that triggered the request
* @description Request management function that coordinates:
* - Concurrent request prevention via locking
* - Polling pause during active requests
* - Navigation control disabling
* - Request lock state management
* @throws {Error} If request lock is already set
*/
function setRequestLock(e: HTMXEvent): void {
if (requestInFlight) {
e.preventDefault();
return;
}
pausePolling(false);
disableAssetNavigationButtons();
requestInFlight = true;
}
/**
* Releases the request lock after a request completes
* @description Request cleanup function that:
* - Re-enables navigation button controls
* - Clears the request lock flag
* - Restores normal kiosk operation state
*/
function releaseRequestLock(): void {
enableAssetNavigationButtons();
requestInFlight = false;
}
/**
* Checks if there are enough history entries to navigate back
* @param {HTMXEvent} e Event object for the history navigation request
* @description Navigation safety check that ensures:
* - Sufficient history depth exists before navigation
* - No active requests are in progress
* - Sets request lock when navigation is permitted
*/
function checkHistoryExists(e: HTMXEvent): void {
const historyItems = htmx.findAll(
".kiosk-history--entry",
) as NodeListOf<HTMLInputElement>;
if (
requestInFlight ||
historyItems.length < 2 ||
(historyItems.length > 0 && historyItems[0].value[0] === "*")
) {
e.preventDefault();
return;
}
setRequestLock(e);
}
/**
* Browser viewport dimensions
* @description Contains current window dimensions:
* - client_width: Width of the browser viewport in pixels
* - client_height: Height of the browser viewport in pixels
*/
type BrowserData = {
client_time: string;
client_width: number;
client_height: number;
fully_version?: string;
fully_webview_version?: string;
fully_android_version?: string;
fully_screen_orientation?: number;
fully_screen_brightness?: number;
};
/**
* Returns the current browser viewport dimensions and, if available, Fully Kiosk Browser details.
*
* When debug mode is enabled and Fully Kiosk Browser integration is present, the returned object includes version, orientation, and brightness information from the browser.
*
* @returns An object containing the viewport width and height, and optionally Fully Kiosk Browser details.
*/
function clientData(): BrowserData {
const data: BrowserData = {
client_time: formatRFC3339(new Date()),
client_width: fullyKiosk.getDisplayDimensions().width,
client_height: fullyKiosk.getDisplayDimensions().height,
};
if (kioskData.debug && fullyKiosk.fully !== undefined) {
data.fully_version = fullyKiosk.fully.getFullyVersion();
data.fully_webview_version = fullyKiosk.fully.getWebviewVersion();
data.fully_android_version = fullyKiosk.fully.getAndroidVersion();
data.fully_screen_orientation = fullyKiosk.fully.getScreenOrientation();
data.fully_screen_brightness = fullyKiosk.fully.getScreenBrightness();
}
return data;
}
// Add kiosk query parameters to HTMX requests
if (kioskQueries.length > 0) {
document.body.addEventListener("htmx:configRequest", (e: HTMXEvent) => {
if (!e.detail?.parameters) {
console.warn("Request parameters object not found");
return;
}
try {
kioskQueries.forEach((q: HTMLInputElement) => {
if (!(q instanceof HTMLInputElement)) {
console.warn(`Element ${q} is not an input`);
return;
}
if (!q.name || !q.value) {
console.debug(`Skipping invalid input: ${q}`);
return;
}
const sanitizedValue = DOMPurify.sanitize(q.value);
e.detail.parameters.append(q.name, sanitizedValue);
});
} catch (error) {
console.error("Error processing parameters:", error);
}
});
}
// Initialize Kiosk when the DOM is fully loaded
document.addEventListener("DOMContentLoaded", () => {
init();
});
export {
triggerNewAsset,
cleanupFrames,
startPolling,
stopPolling,
setRequestLock,
releaseRequestLock,
checkHistoryExists,
clientData,
videoHandler,
sleepMode,
weatherRotationPosition,
};