one
Version:
One is a React framework for web, iOS, and Android apps.
64 lines (61 loc) • 2.05 kB
JavaScript
import { useEffect, useId } from "react";
import { KeepAwake as KeepAwake$1 } from "./unavailable.mjs";
import { assertKeepAwakeEnabled, assertKeepAwakeTag, normalizeKeepAwakeTag } from "./validate.mjs";
const active = /* @__PURE__ */ new Set();
let lock;
let operation = Promise.resolve();
function live() {
return !!lock && !lock.released;
}
function apply(owner) {
const next = operation.catch(() => {}).then(async () => {
if (active.size === 0) {
await lock?.release();
lock = void 0;
return;
}
if (live()) return;
if (!navigator.wakeLock) throw new Error(`KeepAwake.${owner}: Screen Wake Lock is unavailable`);
lock = await navigator.wakeLock.request("screen");
});
operation = next;
return next;
}
const KeepAwake = Object.freeze({
isEnabled: async () => typeof window !== "undefined" && active.size > 0 && live(),
setEnabled: (enabled) => {
assertKeepAwakeEnabled(enabled);
if (typeof window === "undefined") return KeepAwake$1.setEnabled(enabled);
if (enabled) active.add(normalizeKeepAwakeTag(void 0));
else active.delete(normalizeKeepAwakeTag(void 0));
return apply("setEnabled");
},
activate: (tag) => {
assertKeepAwakeTag(tag, "activate");
if (typeof window === "undefined") return KeepAwake$1.activate(tag);
active.add(normalizeKeepAwakeTag(tag));
return apply("activate");
},
deactivate: (tag) => {
assertKeepAwakeTag(tag, "deactivate");
if (typeof window === "undefined") return KeepAwake$1.deactivate(tag);
active.delete(normalizeKeepAwakeTag(tag));
return apply("deactivate");
}
});
function useKeepAwake(tag) {
const fallback = useId();
assertKeepAwakeTag(tag, "useKeepAwake");
const effective = tag ?? fallback;
useEffect(() => {
if (typeof window === "undefined") return;
KeepAwake.activate(effective).catch((error) => {
console.error(`Failed to keep the screen awake: ${String(error)}`);
});
return () => {
KeepAwake.deactivate(effective).catch(() => {});
};
}, [effective]);
}
export { KeepAwake, useKeepAwake };
//# sourceMappingURL=index.mjs.map