diff options
Diffstat (limited to 'static/app.js')
| -rw-r--r-- | static/app.js | 33 |
1 files changed, 31 insertions, 2 deletions
diff --git a/static/app.js b/static/app.js index 2f61c81..fb92352 100644 --- a/static/app.js +++ b/static/app.js @@ -228,6 +228,7 @@ function startPoll(name, panel, el) { const poll = async () => { try { const r = await fetch(`/api/${name}`); + awake(); if (r.ok) panel.update?.(await r.json(), el); } catch { // keep the last state; the next tick retries @@ -333,17 +334,45 @@ setInterval(refreshTheme, 5000); // dims or starts its screensaver. The lock drops whenever the page is hidden // and is taken again when it comes back. 127.0.0.1 is a secure context, which // the Wake Lock API requires. +const asleep = document.getElementById("asleep"); +let wakeLock = null; async function keepAwake() { try { - if (document.visibilityState === "visible") await navigator.wakeLock?.request("screen"); + if (document.visibilityState === "visible" && asleep.hidden && !wakeLock) { + wakeLock = (await navigator.wakeLock?.request("screen")) ?? null; + wakeLock?.addEventListener("release", () => { wakeLock = null; }); + } } catch { // refused (battery saver): the screen just follows its own timeout } } keepAwake(); +// A sleeping PC answers nothing: every poll fails or hangs. After 15 s +// without any answer the page says so and drops the wake lock, so the tablet +// sleeps too; the first answer takes both back. +// ponytail: a crashed server or a dropped tunnel reads as asleep as well. +const ASLEEP_AFTER = 15000; +let lastAnswer = Date.now(); +function awake() { + lastAnswer = Date.now(); + if (!asleep.hidden) { + asleep.hidden = true; + keepAwake(); + } +} +setInterval(() => { + if (asleep.hidden && Date.now() - lastAnswer > ASLEEP_AFTER) { + asleep.hidden = false; + wakeLock?.release(); + } +}, 2000); + document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "visible") refreshers.forEach((fn) => fn()); + if (document.visibilityState === "visible") { + lastAnswer = Math.max(lastAnswer, Date.now() - ASLEEP_AFTER + 5000); // a moment for the refresh below + refreshers.forEach((fn) => fn()); + } keepAwake(); }); |
