@inglorious/web 6.28.0 → 6.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +31 -2198
  2. package/package.json +50 -38
  3. package/src/auth/index.js +23 -21
  4. package/src/decorators/limit.js +67 -0
  5. package/src/decorators/with-debounce/index.js +6 -57
  6. package/src/decorators/with-throttle/index.js +12 -67
  7. package/src/device/biometrics/index.js +86 -0
  8. package/src/device/compass/handlers.js +163 -0
  9. package/src/{sensors → device}/element-size/handlers.js +2 -2
  10. package/src/device/geolocation/index.js +120 -0
  11. package/src/{keyboard → device/keyboard}/index.js +58 -21
  12. package/src/device/local-notifications/index.js +133 -0
  13. package/src/{sensors → device}/media-query/handlers.js +2 -2
  14. package/src/{sensors → device}/network-status/handlers.js +1 -1
  15. package/src/{sensors → device}/page-visibility/handlers.js +1 -1
  16. package/src/{native → device}/share/index.js +1 -1
  17. package/src/device/storage/index.js +61 -0
  18. package/src/mount.js +7 -4
  19. package/src/native/app-links/index.js +44 -30
  20. package/src/native/back-button/index.js +40 -21
  21. package/src/native/index.js +0 -32
  22. package/src/native/live-update/index.js +104 -92
  23. package/src/native/system-bars/index.js +63 -33
  24. package/src/native/update/index.js +37 -38
  25. package/src/pwa/index.js +67 -3
  26. package/src/pwa/update.js +10 -20
  27. package/types/auth.d.ts +1 -10
  28. package/types/device/biometrics.d.ts +51 -0
  29. package/types/{sensors → device}/compass.d.ts +0 -2
  30. package/types/{sensors → device}/geolocation.d.ts +25 -7
  31. package/types/device/keyboard.d.ts +28 -0
  32. package/types/device/local-notifications.d.ts +76 -0
  33. package/types/device/storage.d.ts +30 -0
  34. package/types/mount.d.ts +11 -5
  35. package/types/native/app-links.d.ts +22 -14
  36. package/types/native/back-button.d.ts +22 -12
  37. package/types/native/index.d.ts +0 -19
  38. package/types/native/live-update.d.ts +25 -32
  39. package/types/native/system-bars.d.ts +24 -8
  40. package/types/native/update.d.ts +12 -25
  41. package/types/pwa.d.ts +11 -20
  42. package/src/pwa/handlers.js +0 -17
  43. package/src/sensors/compass/handlers.js +0 -209
  44. package/src/sensors/geolocation/handlers.js +0 -168
  45. package/src/sensors/geolocation/index.js +0 -3
  46. package/types/keyboard.d.ts +0 -8
  47. /package/src/{sensors → device}/compass/index.js +0 -0
  48. /package/src/{sensors → device}/element-size/index.js +0 -0
  49. /package/src/{native → device}/haptics/index.js +0 -0
  50. /package/src/{sensors → device}/media-query/index.js +0 -0
  51. /package/src/{sensors → device}/network-status/index.js +0 -0
  52. /package/src/{sensors → device}/page-visibility/index.js +0 -0
  53. /package/types/{sensors → device}/element-size.d.ts +0 -0
  54. /package/types/{native → device}/haptics.d.ts +0 -0
  55. /package/types/{sensors → device}/media-query.d.ts +0 -0
  56. /package/types/{sensors → device}/network-status.d.ts +0 -0
  57. /package/types/{sensors → device}/page-visibility.d.ts +0 -0
  58. /package/types/{native → device}/share.d.ts +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/web",
3
- "version": "6.28.0",
3
+ "version": "6.30.0",
4
4
  "description": "A new web framework that leverages the power of the Inglorious Store combined with the performance and simplicity of lit-html.",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "contributors": [
@@ -53,18 +53,6 @@
53
53
  "types": "./types/native/system-bars.d.ts",
54
54
  "import": "./src/native/system-bars/index.js"
55
55
  },
56
- "./keyboard": {
57
- "types": "./types/keyboard.d.ts",
58
- "import": "./src/keyboard/index.js"
59
- },
60
- "./native/haptics": {
61
- "types": "./types/native/haptics.d.ts",
62
- "import": "./src/native/haptics/index.js"
63
- },
64
- "./native/share": {
65
- "types": "./types/native/share.d.ts",
66
- "import": "./src/native/share/index.js"
67
- },
68
56
  "./decorators/with-debounce": {
69
57
  "types": "./types/decorators/with-debounce.d.ts",
70
58
  "import": "./src/decorators/with-debounce/index.js"
@@ -81,6 +69,54 @@
81
69
  "types": "./types/decorators/with-throttle.d.ts",
82
70
  "import": "./src/decorators/with-throttle/index.js"
83
71
  },
72
+ "./device/biometrics": {
73
+ "types": "./types/device/biometrics.d.ts",
74
+ "import": "./src/device/biometrics/index.js"
75
+ },
76
+ "./device/compass": {
77
+ "types": "./types/device/compass.d.ts",
78
+ "import": "./src/device/compass/index.js"
79
+ },
80
+ "./device/element-size": {
81
+ "types": "./types/device/element-size.d.ts",
82
+ "import": "./src/device/element-size/index.js"
83
+ },
84
+ "./device/geolocation": {
85
+ "types": "./types/device/geolocation.d.ts",
86
+ "import": "./src/device/geolocation/index.js"
87
+ },
88
+ "./device/haptics": {
89
+ "types": "./types/device/haptics.d.ts",
90
+ "import": "./src/device/haptics/index.js"
91
+ },
92
+ "./device/keyboard": {
93
+ "types": "./types/device/keyboard.d.ts",
94
+ "import": "./src/device/keyboard/index.js"
95
+ },
96
+ "./device/local-notifications": {
97
+ "types": "./types/device/local-notifications.d.ts",
98
+ "import": "./src/device/local-notifications/index.js"
99
+ },
100
+ "./device/media-query": {
101
+ "types": "./types/device/media-query.d.ts",
102
+ "import": "./src/device/media-query/index.js"
103
+ },
104
+ "./device/network-status": {
105
+ "types": "./types/device/network-status.d.ts",
106
+ "import": "./src/device/network-status/index.js"
107
+ },
108
+ "./device/page-visibility": {
109
+ "types": "./types/device/page-visibility.d.ts",
110
+ "import": "./src/device/page-visibility/index.js"
111
+ },
112
+ "./device/share": {
113
+ "types": "./types/device/share.d.ts",
114
+ "import": "./src/device/share/index.js"
115
+ },
116
+ "./device/storage": {
117
+ "types": "./types/device/storage.d.ts",
118
+ "import": "./src/device/storage/index.js"
119
+ },
84
120
  "./directives/*": {
85
121
  "types": "./types/directives/*.d.ts",
86
122
  "import": "./src/directives/*.js"
@@ -114,30 +150,6 @@
114
150
  "types": "./types/router.d.ts",
115
151
  "import": "./src/router/index.js"
116
152
  },
117
- "./sensors/compass": {
118
- "types": "./types/sensors/compass.d.ts",
119
- "import": "./src/sensors/compass/index.js"
120
- },
121
- "./sensors/element-size": {
122
- "types": "./types/sensors/element-size.d.ts",
123
- "import": "./src/sensors/element-size/index.js"
124
- },
125
- "./sensors/geolocation": {
126
- "types": "./types/sensors/geolocation.d.ts",
127
- "import": "./src/sensors/geolocation/index.js"
128
- },
129
- "./sensors/media-query": {
130
- "types": "./types/sensors/media-query.d.ts",
131
- "import": "./src/sensors/media-query/index.js"
132
- },
133
- "./sensors/network-status": {
134
- "types": "./types/sensors/network-status.d.ts",
135
- "import": "./src/sensors/network-status/index.js"
136
- },
137
- "./sensors/page-visibility": {
138
- "types": "./types/sensors/page-visibility.d.ts",
139
- "import": "./src/sensors/page-visibility/index.js"
140
- },
141
153
  "./static": {
142
154
  "types": "./types/static.d.ts",
143
155
  "import": "./src/static.js"
@@ -162,7 +174,7 @@
162
174
  "lit-html": "^3.3.3"
163
175
  },
164
176
  "peerDependencies": {
165
- "@inglorious/store": "^12.6.2"
177
+ "@inglorious/store": "^12.7.0"
166
178
  },
167
179
  "devDependencies": {
168
180
  "@inglorious/eslint-config": "1.2.0",
package/src/auth/index.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { handleRequest } from "@inglorious/store/async"
2
2
 
3
- const DEFAULT_ID = "auth"
4
3
  const DEFAULT_METHODS = ["password"]
5
4
  const DEFAULT_MIN_PASSWORD_LENGTH = 8
6
5
  const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
@@ -29,8 +28,12 @@ const CODE = /^\d{6,10}$/
29
28
  * `linkSubmit({ tokenHash, purpose })` signs in with the link of an email
30
29
  * instead of its code, for a page the link opens.
31
30
  *
32
- * The `adapter` talks to the backend: `signIn`, `signUp`, `sendCode`,
33
- * `verifyCode`, `verifyLink`, `resendCode`, `sendResetCode`,
31
+ * The entity's `user` follows the backend's session from the moment the entity
32
+ * is created: signed in or out, from this tab or another, and when a saved
33
+ * session is restored at launch, which sets `isReady`.
34
+ *
35
+ * The `adapter` talks to the backend: `onSessionChange`, `signIn`, `signUp`,
36
+ * `sendCode`, `verifyCode`, `verifyLink`, `resendCode`, `sendResetCode`,
34
37
  * `updatePassword`, `signOut`, `eraseAccount`, `errorCode`, and optionally
35
38
  * `accountExists`, which skips straight to the password or the new account,
36
39
  * and `prepare(action)`, called as soon as the next step is known, such as
@@ -44,7 +47,6 @@ const CODE = /^\d{6,10}$/
44
47
  *
45
48
  * @example
46
49
  * const types = { Auth: [createAuth({ adapter: supabaseAuth(supabase) }), screen] }
47
- * watchAuth(supabaseAuth(supabase), store)
48
50
  */
49
51
  export function createAuth({
50
52
  adapter,
@@ -53,13 +55,29 @@ export function createAuth({
53
55
  }) {
54
56
  const hasPassword = methods.includes("password")
55
57
  const hasCode = methods.includes("code")
58
+ const sessions = new Map()
56
59
 
57
60
  return {
58
- create(entity) {
61
+ create(entity, _, api) {
59
62
  entity.user ??= null
60
63
  entity.isReady ??= false
61
64
  entity.methods = methods
62
65
  reset(entity)
66
+
67
+ if (!adapter.onSessionChange) return
68
+ const { id } = entity
69
+ sessions.get(id)?.()
70
+ sessions.set(
71
+ id,
72
+ adapter.onSessionChange((user) =>
73
+ api.notify(`#${id}:sessionChange`, user),
74
+ ),
75
+ )
76
+ },
77
+
78
+ destroy(entity) {
79
+ sessions.get(entity.id)?.()
80
+ sessions.delete(entity.id)
63
81
  },
64
82
 
65
83
  sessionChange(entity, user) {
@@ -285,22 +303,6 @@ export function createAuth({
285
303
  }
286
304
  }
287
305
 
288
- /**
289
- * Keeps the entity's `user` in step with the backend's session: signed in or
290
- * out, from this tab or another, and when a saved session is restored at
291
- * launch, which sets `isReady`.
292
- *
293
- * @param {{ onSessionChange: (listener: (user: object | null) => void) => () => void }} adapter
294
- * @param {{ notify: (type: string, payload?: unknown) => void }} store
295
- * @param {{ id?: string }} [options]
296
- * @returns {() => void} Stops watching.
297
- */
298
- export function watchAuth(adapter, store, { id = DEFAULT_ID } = {}) {
299
- return adapter.onSessionChange((user) =>
300
- store.notify(`#${id}:sessionChange`, user),
301
- )
302
- }
303
-
304
306
  function signedIn(entity, { user, isNew }, api) {
305
307
  entity.user = user
306
308
  reset(entity)
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Wraps selected handlers of a type so that each call goes through a limiter,
3
+ * one per entity and handler, which notifies `#id:<handler><Suffix>` when the
4
+ * call gets through. The original handler then runs in an update of its own,
5
+ * with a live draft: a call that fires later, on a timer, is outside the update
6
+ * that brought the event, when its draft is revoked. An entity destroyed in the
7
+ * meantime gets nothing.
8
+ *
9
+ * @param {Object.<string, number>} delays - The handlers to wrap, by name, with their delay.
10
+ * @param {string} suffix - What the event the limiter notifies ends with.
11
+ * @param {(fn: Function, delay: number) => Function & { cancel(): void }} createLimiter
12
+ * @returns {(type: object) => object} The behavior.
13
+ */
14
+ export function withLimiter(delays, suffix, createLimiter) {
15
+ return (type) => {
16
+ const limitersByEntity = new Map()
17
+ const behavior = {}
18
+
19
+ for (const handlerName of Object.keys(delays)) {
20
+ const originalHandler = type[handlerName]
21
+ if (!originalHandler) continue
22
+
23
+ const limitedEvent = `${handlerName}${suffix}`
24
+ behavior[limitedEvent] = originalHandler
25
+
26
+ behavior[handlerName] = (entity, payload, api) => {
27
+ const entityId = entity.id
28
+
29
+ let perEntity = limitersByEntity.get(entityId)
30
+ if (!perEntity) {
31
+ perEntity = {}
32
+ limitersByEntity.set(entityId, perEntity)
33
+ }
34
+
35
+ perEntity[handlerName] ??= createLimiter((entityId, payload, api) => {
36
+ api.notify(`#${entityId}:${limitedEvent}`, payload)
37
+ }, delays[handlerName])
38
+
39
+ perEntity[handlerName](entityId, payload, api)
40
+ }
41
+ }
42
+
43
+ behavior.destroy = (entity, payload, api) => {
44
+ const perEntity = limitersByEntity.get(entity.id)
45
+ if (perEntity) {
46
+ Object.values(perEntity).forEach((limiter) => limiter.cancel())
47
+ limitersByEntity.delete(entity.id)
48
+ }
49
+
50
+ type.destroy?.(entity, payload, api)
51
+ }
52
+
53
+ return behavior
54
+ }
55
+ }
56
+
57
+ /**
58
+ * The delays by handler name, from either form of a decorator's arguments.
59
+ * @param {number|Object.<string, number>} config - One delay for every handler listed, or a map of handler names to delays.
60
+ * @param {string[]} [handlerNames] - The handlers, when `config` is one delay.
61
+ * @returns {Object.<string, number>}
62
+ */
63
+ export function toDelays(config, handlerNames) {
64
+ return typeof config === "number"
65
+ ? Object.fromEntries(handlerNames.map((name) => [name, config]))
66
+ : config
67
+ }
@@ -1,13 +1,11 @@
1
1
  import { debounce } from "@inglorious/utils/functions"
2
2
 
3
+ import { toDelays, withLimiter } from "../limit.js"
4
+
3
5
  /**
4
- * Wraps selected event handlers of a type with debouncing, scoped per-entity.
5
- *
6
- * A debounced call fires later, on its own timer, outside any update: the
7
- * entity the event brought is a draft revoked by then. So the timer notifies
8
- * `#id:<handler>Debounced`, which runs the original handler inside an update
9
- * of its own, with a live draft whose changes reach subscribers. An entity
10
- * destroyed in the meantime gets nothing.
6
+ * Wraps selected event handlers of a type with debouncing, scoped per entity.
7
+ * When the delay ends, the original handler runs in an update of its own,
8
+ * through the `<handler>Debounced` event.
11
9
  *
12
10
  * @param {number|Object} config - Either a single delay (ms) applied to all
13
11
  * handlers listed in `handlerNames`, or a map of handlerName -> delay (ms).
@@ -28,54 +26,5 @@ import { debounce } from "@inglorious/utils/functions"
28
26
  * }
29
27
  */
30
28
  export function withDebounce(config, handlerNames) {
31
- const delays =
32
- typeof config === "number"
33
- ? Object.fromEntries(handlerNames.map((name) => [name, config]))
34
- : config
35
-
36
- return (type) => {
37
- const debouncedByEntity = new Map()
38
-
39
- const behavior = {}
40
-
41
- for (const handlerName of Object.keys(delays)) {
42
- const originalHandler = type[handlerName]
43
- if (!originalHandler) continue
44
-
45
- const debouncedEvent = `${handlerName}Debounced`
46
- behavior[debouncedEvent] = originalHandler
47
-
48
- behavior[handlerName] = (entity, payload, api) => {
49
- const entityId = entity.id
50
-
51
- let perEntity = debouncedByEntity.get(entityId)
52
- if (!perEntity) {
53
- perEntity = {}
54
- debouncedByEntity.set(entityId, perEntity)
55
- }
56
-
57
- if (!perEntity[handlerName]) {
58
- perEntity[handlerName] = debounce((entityId, payload, api) => {
59
- api.notify(`#${entityId}:${debouncedEvent}`, payload)
60
- }, delays[handlerName])
61
- }
62
-
63
- perEntity[handlerName](entityId, payload, api)
64
- }
65
- }
66
-
67
- behavior.destroy = (entity, payload, api) => {
68
- const entityId = entity.id
69
-
70
- const perEntity = debouncedByEntity.get(entityId)
71
- if (perEntity) {
72
- Object.values(perEntity).forEach((d) => d.cancel())
73
- debouncedByEntity.delete(entityId)
74
- }
75
-
76
- type.destroy?.(entity, payload, api)
77
- }
78
-
79
- return behavior
80
- }
29
+ return withLimiter(toDelays(config, handlerNames), "Debounced", debounce)
81
30
  }
@@ -1,18 +1,16 @@
1
1
  import { throttle } from "@inglorious/utils/functions"
2
2
 
3
+ import { toDelays, withLimiter } from "../limit.js"
4
+
3
5
  /**
4
- * Wraps selected event handlers of a type with throttling, scoped per-entity.
6
+ * Wraps selected event handlers of a type with throttling, scoped per entity.
5
7
  *
6
8
  * By default this is leading-edge only: the first call in a burst runs
7
- * immediately, and further calls are dropped until `delay` has elapsed — the
9
+ * immediately, and further calls are dropped until `delay` has elapsed, so the
8
10
  * last call of a burst may be lost. Pass `{ hasTrailing: true }` to also invoke
9
- * the handler once more after `delay`, using the most recent suppressed
10
- * call's arguments, so the final state of a burst is never dropped.
11
- *
12
- * Every call that gets through notifies `#id:<handler>Throttled`, which runs
13
- * the original handler inside an update with a live draft: a trailing call
14
- * fires on its own timer, outside any update, after the event's draft is
15
- * revoked. An entity destroyed in the meantime gets nothing.
11
+ * the handler once more after `delay`, with the most recent suppressed call's
12
+ * arguments. Every call that gets through runs the original handler in an
13
+ * update of its own, through the `<handler>Throttled` event.
16
14
  *
17
15
  * @param {number|Object} config - Either a single delay (ms) applied to all
18
16
  * handlers listed in `handlerNames`, or a map of handlerName -> delay (ms).
@@ -21,12 +19,10 @@ import { throttle } from "@inglorious/utils/functions"
21
19
  * are used instead).
22
20
  * @param {Object} [options]
23
21
  * @param {boolean} [options.hasTrailing=false] - Whether throttled handlers
24
- * should also fire once more after `delay`, using the last suppressed
25
- * call's arguments. Applies to every handler wrapped by this call.
22
+ * also fire once more after `delay`, with the last suppressed call's arguments.
26
23
  *
27
24
  * @example
28
- * // leading-edge only (default): rate-limit a frequent event, last call in
29
- * // a burst may be dropped
25
+ * // leading-edge only (default)
30
26
  * const types = {
31
27
  * ScrollTracker: [Base, withThrottle(200, ["scroll"])],
32
28
  * }
@@ -42,58 +38,7 @@ export function withThrottle(
42
38
  handlerNames,
43
39
  { hasTrailing = false } = {},
44
40
  ) {
45
- const delays =
46
- typeof config === "number"
47
- ? Object.fromEntries(handlerNames.map((name) => [name, config]))
48
- : config
49
-
50
- return (type) => {
51
- const throttledByEntity = new Map()
52
-
53
- const behavior = {}
54
-
55
- for (const handlerName of Object.keys(delays)) {
56
- const originalHandler = type[handlerName]
57
- if (!originalHandler) continue
58
-
59
- const throttledEvent = `${handlerName}Throttled`
60
- behavior[throttledEvent] = originalHandler
61
-
62
- behavior[handlerName] = (entity, payload, api) => {
63
- const entityId = entity.id
64
-
65
- let perEntity = throttledByEntity.get(entityId)
66
- if (!perEntity) {
67
- perEntity = {}
68
- throttledByEntity.set(entityId, perEntity)
69
- }
70
-
71
- if (!perEntity[handlerName]) {
72
- perEntity[handlerName] = throttle(
73
- (entityId, payload, api) => {
74
- api.notify(`#${entityId}:${throttledEvent}`, payload)
75
- },
76
- delays[handlerName],
77
- { hasTrailing },
78
- )
79
- }
80
-
81
- perEntity[handlerName](entityId, payload, api)
82
- }
83
- }
84
-
85
- behavior.destroy = (entity, payload, api) => {
86
- const entityId = entity.id
87
-
88
- const perEntity = throttledByEntity.get(entityId)
89
- if (perEntity) {
90
- Object.values(perEntity).forEach((t) => t.cancel())
91
- throttledByEntity.delete(entityId)
92
- }
93
-
94
- type.destroy?.(entity, payload, api)
95
- }
96
-
97
- return behavior
98
- }
41
+ return withLimiter(toDelays(config, handlerNames), "Throttled", (fn, delay) =>
42
+ throttle(fn, delay, { hasTrailing }),
43
+ )
99
44
  }
@@ -0,0 +1,86 @@
1
+ import { handleRequest } from "@inglorious/store/async"
2
+
3
+ import { isNative } from "../../native/index.js"
4
+
5
+ const UNAVAILABLE = "unavailable"
6
+ const FAILED = "failed"
7
+ const USER_CANCEL = 16
8
+ const TYPES = {
9
+ 1: "fingerprint",
10
+ 2: "face",
11
+ 3: "fingerprint",
12
+ 4: "face",
13
+ 5: "iris",
14
+ 6: "multiple",
15
+ 7: "passcode",
16
+ }
17
+
18
+ /**
19
+ * The type behind "unlock with Face ID": `verify` shows the system's
20
+ * biometric prompt through `NativeBiometric` from
21
+ * `@capgo/capacitor-native-biometric`, given as `plugin`, in a native app.
22
+ *
23
+ * `isAvailable` says whether the device can verify, to hide the button
24
+ * otherwise, and `biometryType` (`"face"`, `"fingerprint"`, `"iris"`,
25
+ * `"multiple"` or `"passcode"`) to name it. `result` is `"verified"` or
26
+ * `"cancelled"`: closing the prompt is not an error. `status` and `error`
27
+ * (`"unavailable"` or `"failed"`) are those of `handleRequest`. A browser has
28
+ * no equivalent: there it is never available.
29
+ *
30
+ * @param {{ plugin?: object }} [config]
31
+ *
32
+ * @example
33
+ * import { NativeBiometric } from "@capgo/capacitor-native-biometric"
34
+ * const types = { Biometrics: createBiometrics({ plugin: NativeBiometric }) }
35
+ * api.notify("#biometrics:verify", { reason: "Unlock your account" })
36
+ */
37
+ export function createBiometrics({ plugin } = {}) {
38
+ const device = plugin && isNative() ? plugin : null
39
+
40
+ return {
41
+ create(entity, _, api) {
42
+ const { id } = entity
43
+ entity.isAvailable ??= false
44
+ entity.biometryType ??= null
45
+ entity.status ??= "idle"
46
+ entity.error ??= null
47
+ entity.result ??= null
48
+ device
49
+ ?.isAvailable()
50
+ .then((answer) => api.notify(`#${id}:biometricsAvailable`, answer))
51
+ },
52
+
53
+ biometricsAvailable(entity, { isAvailable, biometryType }) {
54
+ entity.isAvailable = isAvailable
55
+ entity.biometryType = TYPES[biometryType] ?? null
56
+ },
57
+
58
+ ...handleRequest(
59
+ "verify",
60
+ {
61
+ start(entity) {
62
+ entity.result = null
63
+ },
64
+ run: (options) => verify(device, options),
65
+ success(entity, result) {
66
+ entity.result = result
67
+ },
68
+ },
69
+ {
70
+ toError: (error) =>
71
+ error?.message === UNAVAILABLE ? UNAVAILABLE : FAILED,
72
+ },
73
+ ),
74
+ }
75
+ }
76
+
77
+ async function verify(device, options = {}) {
78
+ if (!device) throw new Error(UNAVAILABLE)
79
+ try {
80
+ await device.verifyIdentity(options)
81
+ return "verified"
82
+ } catch (error) {
83
+ if (Number(error?.code) === USER_CANCEL) return "cancelled"
84
+ throw error
85
+ }
86
+ }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * @typedef {import("../../../types/device/compass.js").CompassEntity} CompassEntity
3
+ * @typedef {import("../../../types/device/compass.js").CompassError} CompassError
4
+ */
5
+
6
+ const COMPASS_TIMEOUT = 3000
7
+
8
+ const FULL_CIRCLE = 360
9
+ const DEFAULT_ORIENTATION = 0
10
+ const DEFAULT_ERROR_CODE = 0
11
+
12
+ const watches = new Map()
13
+
14
+ export function create(entity) {
15
+ entity.error ??= null
16
+ entity.heading ??= null
17
+ entity.isActive ??= false
18
+ entity.isPermissionGranted ??= false
19
+ entity.isLoading ??= false
20
+ entity.isSupported = isCompassSupported()
21
+ entity.manualOffset ??= 0
22
+ }
23
+
24
+ export function destroy(entity) {
25
+ compassUnwatch(entity)
26
+ }
27
+
28
+ export function compassUnwatch(entity) {
29
+ watches.get(entity.id)?.()
30
+ watches.delete(entity.id)
31
+ entity.isLoading = false
32
+ entity.isActive = false
33
+ }
34
+
35
+ export function compassError(entity, error) {
36
+ entity.error = normalizeError(error)
37
+ entity.isLoading = false
38
+ entity.isPermissionGranted = false
39
+ }
40
+
41
+ export function compassPermissionsRequest(entity, _, api) {
42
+ const { id } = entity
43
+ entity.isSupported = isCompassSupported()
44
+ entity.error = null
45
+
46
+ if (!entity.isSupported) {
47
+ api.notify(`#${id}:compassError`, createUnsupportedError())
48
+ return
49
+ }
50
+
51
+ entity.isLoading = true
52
+ requestPermission().then(
53
+ (permission) =>
54
+ permission === "granted"
55
+ ? api.notify(`#${id}:compassPermissionsGrant`)
56
+ : api.notify(`#${id}:compassError`, createPermissionDeniedError()),
57
+ (error) => api.notify(`#${id}:compassError`, error),
58
+ )
59
+ }
60
+
61
+ export function compassPermissionsGrant(entity) {
62
+ entity.isLoading = false
63
+ entity.isPermissionGranted = true
64
+ }
65
+
66
+ export function compassWatch(entity, _, api) {
67
+ const { id, manualOffset } = entity
68
+ const win = getWindow()
69
+ if (!win || watches.has(id)) return
70
+
71
+ const timeoutId = setTimeout(
72
+ () => api.notify(`#${id}:compassActiveChange`, false),
73
+ COMPASS_TIMEOUT,
74
+ )
75
+
76
+ const onOrientation = (event) => {
77
+ if (typeof event?.alpha !== "number") return
78
+ clearTimeout(timeoutId)
79
+ api.notify(`#${id}:compassActiveChange`, true)
80
+ api.notify(
81
+ `#${id}:compassHeadingChange`,
82
+ heading(event.alpha, manualOffset),
83
+ )
84
+ }
85
+
86
+ let isUsingAbsolute = false
87
+ const onAbsolute = (event) => {
88
+ if (!isUsingAbsolute) {
89
+ isUsingAbsolute = true
90
+ win.removeEventListener("deviceorientation", onOrientation)
91
+ }
92
+ onOrientation(event)
93
+ }
94
+
95
+ win.addEventListener("deviceorientationabsolute", onAbsolute)
96
+ win.addEventListener("deviceorientation", onOrientation)
97
+
98
+ watches.set(id, () => {
99
+ clearTimeout(timeoutId)
100
+ win.removeEventListener("deviceorientation", onOrientation)
101
+ win.removeEventListener("deviceorientationabsolute", onAbsolute)
102
+ })
103
+ }
104
+
105
+ export function compassActiveChange(entity, value) {
106
+ entity.isActive = value
107
+ }
108
+
109
+ export function compassHeadingChange(entity, value) {
110
+ entity.isLoading = false
111
+ entity.heading = value
112
+ }
113
+
114
+ function heading(alpha, manualOffset) {
115
+ const degrees = alpha - getScreenAngle() + manualOffset
116
+ return Math.round(((degrees % FULL_CIRCLE) + FULL_CIRCLE) % FULL_CIRCLE)
117
+ }
118
+
119
+ function requestPermission() {
120
+ return (
121
+ globalThis.DeviceOrientationEvent?.requestPermission?.() ??
122
+ Promise.resolve("granted")
123
+ )
124
+ }
125
+
126
+ function getWindow() {
127
+ return typeof window !== "undefined" ? window : null
128
+ }
129
+
130
+ function getScreenAngle() {
131
+ const win = getWindow()
132
+ return (
133
+ win?.screen?.orientation?.angle ?? win?.orientation ?? DEFAULT_ORIENTATION
134
+ )
135
+ }
136
+
137
+ function isCompassSupported() {
138
+ return (
139
+ typeof DeviceOrientationEvent !== "undefined" &&
140
+ Boolean(getWindow()?.addEventListener)
141
+ )
142
+ }
143
+
144
+ function createUnsupportedError() {
145
+ return {
146
+ code: 0,
147
+ message: "Compass is not supported by this environment.",
148
+ }
149
+ }
150
+
151
+ function createPermissionDeniedError() {
152
+ return {
153
+ code: 1,
154
+ message: "Compass permission denied.",
155
+ }
156
+ }
157
+
158
+ function normalizeError(error) {
159
+ return {
160
+ code: error?.code ?? DEFAULT_ERROR_CODE,
161
+ message: error?.message ?? String(error),
162
+ }
163
+ }