65 lines
1.8 KiB
JavaScript
65 lines
1.8 KiB
JavaScript
// Screen wake lock and fullscreen helpers.
|
|
|
|
export function createWakeLock() {
|
|
let sentinel = null;
|
|
let pending = false;
|
|
let wanted = false;
|
|
|
|
async function acquire() {
|
|
if (!('wakeLock' in navigator) || sentinel || pending || document.visibilityState !== 'visible') return;
|
|
pending = true;
|
|
try {
|
|
sentinel = await navigator.wakeLock.request('screen');
|
|
sentinel.addEventListener('release', () => {
|
|
sentinel = null;
|
|
});
|
|
if (!wanted) release();
|
|
} catch {
|
|
/* denied, insecure context or low battery: no big deal */
|
|
} finally {
|
|
pending = false;
|
|
}
|
|
}
|
|
|
|
function release() {
|
|
const s = sentinel;
|
|
sentinel = null;
|
|
s?.release().catch(() => {});
|
|
}
|
|
|
|
// The lock is dropped automatically when the page is hidden.
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (wanted && document.visibilityState === 'visible') acquire();
|
|
});
|
|
|
|
return {
|
|
set(on) {
|
|
if (on === wanted) return;
|
|
wanted = on;
|
|
if (on) acquire();
|
|
else release();
|
|
},
|
|
};
|
|
}
|
|
|
|
export const fullscreenSupported = () => !!(document.fullscreenEnabled || document.webkitFullscreenEnabled);
|
|
export const isFullscreen = () => !!(document.fullscreenElement || document.webkitFullscreenElement);
|
|
|
|
export async function toggleFullscreen() {
|
|
try {
|
|
if (isFullscreen()) {
|
|
await (document.exitFullscreen || document.webkitExitFullscreen).call(document);
|
|
} else {
|
|
const el = document.documentElement;
|
|
if (el.requestFullscreen) await el.requestFullscreen({ navigationUI: 'hide' });
|
|
else el.webkitRequestFullscreen?.();
|
|
}
|
|
} catch {
|
|
/* user agent refused */
|
|
}
|
|
}
|
|
|
|
export function onFullscreenChange(fn) {
|
|
document.addEventListener('fullscreenchange', fn);
|
|
document.addEventListener('webkitfullscreenchange', fn);
|
|
}
|