UNPKG

esp-web-tools

Version:
65 lines (64 loc) • 2.12 kB
/** * Holds a screen wake lock while wanted, so the display doesn't sleep (and the * tab isn't throttled) in the middle of an install. Does nothing in browsers * without the Screen Wake Lock API. * * The browser drops the lock whenever the page is hidden, so it is requested * again when the page becomes visible while the lock is still wanted. */ export class ScreenWakeLock { constructor() { this._wanted = false; this._handleVisibility = () => { if (document.visibilityState === "visible") { this._request(); } }; } async acquire() { if (this._wanted) { return; } this._wanted = true; document.addEventListener("visibilitychange", this._handleVisibility); await this._request(); } async release() { if (!this._wanted) { return; } this._wanted = false; document.removeEventListener("visibilitychange", this._handleVisibility); const sentinel = this._sentinel; this._sentinel = undefined; try { await (sentinel === null || sentinel === void 0 ? void 0 : sentinel.release()); } catch (err) { console.warn("Failed to release screen wake lock", err); } } async _request() { if (!("wakeLock" in navigator) || this._sentinel) { return; } try { const sentinel = await navigator.wakeLock.request("screen"); if (!this._wanted) { // Released while the request was in flight. await sentinel.release(); return; } this._sentinel = sentinel; sentinel.addEventListener("release", () => { if (this._sentinel === sentinel) { this._sentinel = undefined; } }); } catch (err) { // Denied (e.g. low battery or page not visible). Installing still works. console.warn("Failed to acquire screen wake lock", err); } } }