-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
81 lines (65 loc) · 1.66 KB
/
index.ts
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
import { browser, toReadable, toWritable, unstore } from "@sveu/shared"
import { on } from "../eventListener"
import { support } from "../support"
import type {
NavigatorWithWakeLock,
WakeLockSentinel,
WakeLockType,
} from "../utils"
/**
* Reactive Screen Wake Lock API.
*
* @example
* ```ts
* const { supported, active, request, release } = wakeLock()
* ```
*
* @returns
* - `supported` - Whether the Wake Lock API is supported.
* - `active` - Whether the Wake Lock is active.
* - `request` - Request a Wake Lock.
* - `release` - Release the Wake Lock.
*/
export function wakeLock() {
let _wake_lock: WakeLockSentinel | null
const supported = support("wakeLock")
const active = toWritable(false)
async function on_visibility_change() {
if (!unstore(supported) || !_wake_lock) return
if (document.visibilityState === "visible")
_wake_lock = await (
navigator as NavigatorWithWakeLock
).wakeLock.request("screen")
active.set(!_wake_lock.released)
}
if (browser)
on(document, "visibilitychange", on_visibility_change, {
passive: true,
})
/**
* Request a Wake Lock.
*
* @param type - The type of Wake Lock to request. Defaults to "screen".
*
*/
async function request(type: WakeLockType) {
if (!unstore(supported)) return
_wake_lock = await (
navigator as NavigatorWithWakeLock
).wakeLock.request(type)
active.set(!_wake_lock.released)
}
/** Release the Wake Lock. */
async function release() {
if (!unstore(supported) || !_wake_lock) return
await _wake_lock.release()
active.set(!_wake_lock.released)
_wake_lock = null
}
return {
supported,
active: toReadable(active),
request,
release,
}
}