@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
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @typedef {import("../../../types/sensors/element-size.js").ElementSizeEntity} ElementSizeEntity
3
- * @typedef {import("../../../types/sensors/element-size.js").ElementSizeSize} ElementSizeSize
2
+ * @typedef {import("../../../types/device/element-size.js").ElementSizeEntity} ElementSizeEntity
3
+ * @typedef {import("../../../types/device/element-size.js").ElementSizeSize} ElementSizeSize
4
4
  */
5
5
 
6
6
  const listeners = new Map()
@@ -0,0 +1,120 @@
1
+ import { isNative } from "../../native/index.js"
2
+
3
+ const UNSUPPORTED = {
4
+ code: 0,
5
+ message: "Geolocation is not supported by this environment.",
6
+ }
7
+
8
+ const watches = new Map()
9
+
10
+ /**
11
+ * The type behind a position: `geolocationRequest` reads it once,
12
+ * `geolocationWatch` follows it until `geolocationUnwatch`. In a native app it
13
+ * uses `Geolocation` from `@capacitor/geolocation` when given as `plugin`, so
14
+ * iOS asks once, for the app; elsewhere `navigator.geolocation`.
15
+ *
16
+ * @param {{ plugin?: object }} [config]
17
+ *
18
+ * @example
19
+ * import { Geolocation } from "@capacitor/geolocation"
20
+ * const types = { Geolocation: createGeolocation({ plugin: Geolocation }) }
21
+ * api.notify("#geolocation:geolocationRequest", { enableHighAccuracy: true })
22
+ */
23
+ export function createGeolocation({ plugin } = {}) {
24
+ const source = () =>
25
+ plugin && isNative()
26
+ ? fromPlugin(plugin)
27
+ : globalThis.navigator?.geolocation
28
+
29
+ return {
30
+ create(entity) {
31
+ entity.error ??= null
32
+ entity.isLoading ??= false
33
+ entity.isSupported = Boolean(source())
34
+ entity.isWatching ??= false
35
+ entity.position ??= null
36
+ },
37
+
38
+ destroy(entity) {
39
+ unwatch(entity)
40
+ },
41
+
42
+ geolocationRequest(entity, options = {}, api) {
43
+ const geolocation = start(entity, api)
44
+ geolocation?.getCurrentPosition(...answers(entity.id, api), options)
45
+ },
46
+
47
+ geolocationWatch(entity, options = {}, api) {
48
+ if (watches.has(entity.id)) return
49
+ const geolocation = start(entity, api)
50
+ if (!geolocation) return
51
+
52
+ entity.isWatching = true
53
+ watches.set(entity.id, {
54
+ geolocation,
55
+ watch: geolocation.watchPosition(...answers(entity.id, api), options),
56
+ })
57
+ },
58
+
59
+ geolocationUnwatch: unwatch,
60
+
61
+ geolocationSuccess(entity, position) {
62
+ entity.error = null
63
+ entity.isLoading = false
64
+ entity.position = {
65
+ coords: {
66
+ accuracy: position.coords.accuracy,
67
+ altitude: position.coords.altitude,
68
+ altitudeAccuracy: position.coords.altitudeAccuracy,
69
+ heading: position.coords.heading,
70
+ latitude: position.coords.latitude,
71
+ longitude: position.coords.longitude,
72
+ speed: position.coords.speed,
73
+ },
74
+ timestamp: position.timestamp,
75
+ }
76
+ },
77
+
78
+ geolocationError(entity, error) {
79
+ entity.error = { code: error.code, message: error.message }
80
+ entity.isLoading = false
81
+ },
82
+ }
83
+
84
+ function start(entity, api) {
85
+ const geolocation = source()
86
+ entity.isSupported = Boolean(geolocation)
87
+ entity.error = null
88
+ entity.isLoading = Boolean(geolocation)
89
+ if (!geolocation) api.notify(`#${entity.id}:geolocationError`, UNSUPPORTED)
90
+ return geolocation
91
+ }
92
+ }
93
+
94
+ function unwatch(entity) {
95
+ const active = watches.get(entity.id)
96
+ active?.geolocation.clearWatch(active.watch)
97
+ watches.delete(entity.id)
98
+ entity.isLoading = false
99
+ entity.isWatching = false
100
+ }
101
+
102
+ function answers(id, api) {
103
+ return [
104
+ (position) => api.notify(`#${id}:geolocationSuccess`, position),
105
+ (error) => api.notify(`#${id}:geolocationError`, error),
106
+ ]
107
+ }
108
+
109
+ function fromPlugin(plugin) {
110
+ return {
111
+ getCurrentPosition: (onSuccess, onError, options) =>
112
+ plugin.getCurrentPosition(options).then(onSuccess, onError),
113
+ watchPosition: (onSuccess, onError, options) =>
114
+ plugin.watchPosition(options, (position, error) =>
115
+ position ? onSuccess(position) : onError(error),
116
+ ),
117
+ clearWatch: (watch) =>
118
+ Promise.resolve(watch).then((id) => plugin.clearWatch({ id })),
119
+ }
120
+ }
@@ -17,28 +17,68 @@ const TEXT_INPUTS = new Set([
17
17
  "week",
18
18
  ])
19
19
 
20
+ const watches = new Map()
21
+
20
22
  /**
21
- * Tells the page when the on-screen keyboard is up, and how much of it the
22
- * keyboard covers, so what sits at the bottom of the screen can move above it
23
- * or step aside. Most phones don't shrink the page for the keyboard (iOS, and
24
- * Chrome on Android): a bottom sheet or a snackbar ends up behind it. This sets
25
- * `--iw-keyboard-height` on `<html>` from the visual viewport, and the
26
- * `iw-keyboard-open` class while the keyboard is up: no plugin needed, in a
27
- * browser or a native app. Where the page does shrink, as in an Android app,
28
- * the class is still set but the height stays 0, since nothing is covered.
29
- * Inglorious UI's sheets, snackbars and toasts follow it, and its bottom
30
- * navigation hides.
31
- *
32
- * @returns {() => void} Stops following.
23
+ * The type that knows when the on-screen keyboard is up, and how much of the
24
+ * page it covers. Most phones don't shrink the page for the keyboard (iOS, and
25
+ * Chrome on Android): a bottom sheet or a snackbar ends up behind it. The entity
26
+ * holds `isOpen` and `height`, read from the visual viewport, and the type sets
27
+ * `--iw-keyboard-height` on `<html>` and the `iw-keyboard-open` class while the
28
+ * keyboard is up, which Inglorious UI's sheets, snackbars, toasts and bottom
29
+ * navigation follow. Where the page does shrink, as in an Android app, `isOpen`
30
+ * is still set but `height` stays 0, since nothing is covered. No plugin is
31
+ * needed, in a browser or a native app.
33
32
  *
34
33
  * @example
35
- * watchKeyboard()
34
+ * const types = { Keyboard }
35
+ * const entities = { keyboard: { type: "Keyboard" } }
36
36
  */
37
- export function watchKeyboard() {
38
- const viewport = window.visualViewport
39
- if (!viewport) return () => {}
37
+ export const Keyboard = {
38
+ create(entity, _, api) {
39
+ entity.isSupported = Boolean(globalThis.visualViewport)
40
+ entity.isOpen ??= false
41
+ entity.height ??= NONE
42
+ if (!entity.isSupported) return
40
43
 
41
- const root = document.documentElement
44
+ const { id } = entity
45
+ watches.get(id)?.()
46
+ watches.set(
47
+ id,
48
+ watch((change) => api.notify(`#${id}:keyboardChange`, change)),
49
+ )
50
+ },
51
+
52
+ destroy(entity) {
53
+ watches.get(entity.id)?.()
54
+ watches.delete(entity.id)
55
+ const root = globalThis.document?.documentElement
56
+ root?.style.removeProperty(HEIGHT)
57
+ root?.classList.remove(OPEN)
58
+ },
59
+
60
+ keyboardChange(entity, { isOpen, height }) {
61
+ entity.isOpen = isOpen
62
+ entity.height = height
63
+ apply({ isOpen, height })
64
+ },
65
+ }
66
+
67
+ function apply({ isOpen, height }) {
68
+ const root = globalThis.document?.documentElement
69
+ if (!root) return
70
+ root.style.setProperty(HEIGHT, `${height}px`)
71
+ root.classList.toggle(OPEN, isOpen)
72
+ }
73
+
74
+ /**
75
+ * Follows the visual viewport, calling `onChange` when the keyboard opens,
76
+ * closes or covers a different height.
77
+ * @param {(change: { isOpen: boolean, height: number }) => void} onChange
78
+ * @returns {() => void} Stops following.
79
+ */
80
+ function watch(onChange) {
81
+ const viewport = window.visualViewport
42
82
  let isOpen = false
43
83
  let height = NONE
44
84
  let fullWidth = window.innerWidth
@@ -64,8 +104,7 @@ export function watchKeyboard() {
64
104
  const isOpening = isKeyboard && !isOpen
65
105
  isOpen = isKeyboard
66
106
  height = nextHeight
67
- root.style.setProperty(HEIGHT, `${height}px`)
68
- root.classList.toggle(OPEN, isOpen)
107
+ onChange({ isOpen, height })
69
108
  if (isOpening) {
70
109
  requestAnimationFrame(() =>
71
110
  document.activeElement?.scrollIntoView?.({ block: "nearest" }),
@@ -82,8 +121,6 @@ export function watchKeyboard() {
82
121
  viewport.removeEventListener("resize", update)
83
122
  viewport.removeEventListener("scroll", update)
84
123
  window.removeEventListener("resize", update)
85
- root.style.removeProperty(HEIGHT)
86
- root.classList.remove(OPEN)
87
124
  }
88
125
  }
89
126
 
@@ -0,0 +1,133 @@
1
+ import { isNative } from "../../native/index.js"
2
+
3
+ /**
4
+ * The type behind reminders the device shows on its own, such as "your job
5
+ * starts in an hour". In a native app they go through `LocalNotifications`
6
+ * from `@capacitor/local-notifications`, given as `plugin`, and show even with
7
+ * the app closed. In a browser they show only while the page is open, through
8
+ * the Notification API.
9
+ *
10
+ * `permission` is `"granted"`, `"denied"`, `"prompt"` or `"unsupported"`.
11
+ * `localNotificationsAsk` brings up the system's dialog: send it from a tap,
12
+ * which a browser requires. `localNotificationSchedule({ id, title, body, at,
13
+ * url })` schedules one, `id` being a whole number to cancel it by with
14
+ * `localNotificationCancel(id)`. A tap on one with a `url` navigates there,
15
+ * through `onTap(url, api)`, by default `#router:navigate`.
16
+ *
17
+ * @param {{ plugin?: object, onTap?: (url: string, api: object) => void }} [config]
18
+ *
19
+ * @example
20
+ * import { LocalNotifications } from "@capacitor/local-notifications"
21
+ * const types = {
22
+ * Reminders: createLocalNotifications({ plugin: LocalNotifications }),
23
+ * }
24
+ * api.notify("#reminders:localNotificationSchedule", {
25
+ * id: 1,
26
+ * title: "Wedding in an hour",
27
+ * at: new Date(start - HOUR),
28
+ * url: "/jobs/1",
29
+ * })
30
+ */
31
+ export function createLocalNotifications({
32
+ plugin,
33
+ onTap = (url, api) => api.notify("#router:navigate", url),
34
+ } = {}) {
35
+ const device = plugin && isNative() ? fromPlugin(plugin) : fromBrowser()
36
+
37
+ return {
38
+ create(entity, _, api) {
39
+ const { id } = entity
40
+ entity.permission ??= null
41
+ device.onTap((url) => api.notify(`#${id}:localNotificationTap`, url))
42
+ device
43
+ .permission()
44
+ .then((permission) =>
45
+ api.notify(`#${id}:localNotificationsPermission`, permission),
46
+ )
47
+ },
48
+
49
+ localNotificationsAsk(entity, _, api) {
50
+ const { id } = entity
51
+ device
52
+ .request()
53
+ .then((permission) =>
54
+ api.notify(`#${id}:localNotificationsPermission`, permission),
55
+ )
56
+ },
57
+
58
+ localNotificationsPermission(entity, permission) {
59
+ entity.permission = permission
60
+ },
61
+
62
+ localNotificationSchedule(entity, notification) {
63
+ device.schedule(notification)
64
+ },
65
+
66
+ localNotificationCancel(entity, notificationId) {
67
+ device.cancel(notificationId)
68
+ },
69
+
70
+ localNotificationTap(entity, url, api) {
71
+ if (url) onTap(url, api)
72
+ },
73
+ }
74
+ }
75
+
76
+ function fromPlugin(plugin) {
77
+ return {
78
+ permission: () => plugin.checkPermissions().then(toPermission),
79
+ request: () => plugin.requestPermissions().then(toPermission),
80
+ schedule: ({ id, title, body, at, url }) =>
81
+ plugin.schedule({
82
+ notifications: [{ id, title, body, schedule: { at }, extra: { url } }],
83
+ }),
84
+ cancel: (id) => plugin.cancel({ notifications: [{ id }] }),
85
+ onTap: (listener) =>
86
+ plugin.addListener(
87
+ "localNotificationActionPerformed",
88
+ ({ notification }) => listener(notification.extra?.url),
89
+ ),
90
+ }
91
+ }
92
+
93
+ function fromBrowser() {
94
+ const Notification = globalThis.Notification
95
+ const timers = new Map()
96
+ let tapListener = () => {}
97
+
98
+ return {
99
+ permission: async () =>
100
+ Notification ? toPermission(Notification.permission) : "unsupported",
101
+ request: async () =>
102
+ Notification
103
+ ? toPermission(await Notification.requestPermission())
104
+ : "unsupported",
105
+ schedule: ({ id, title, body, at, url }) => {
106
+ if (!Notification) return
107
+ clearTimeout(timers.get(id))
108
+ const delay = new Date(at).getTime() - Date.now()
109
+ const show = () => {
110
+ timers.delete(id)
111
+ const notification = new Notification(title, { body })
112
+ notification.onclick = () => {
113
+ globalThis.focus?.()
114
+ tapListener(url)
115
+ }
116
+ }
117
+ timers.set(id, setTimeout(show, delay))
118
+ },
119
+ cancel: (id) => {
120
+ clearTimeout(timers.get(id))
121
+ timers.delete(id)
122
+ },
123
+ onTap: (listener) => {
124
+ tapListener = listener
125
+ },
126
+ }
127
+ }
128
+
129
+ function toPermission(result) {
130
+ const value = typeof result === "string" ? result : result.display
131
+ if (value === "granted" || value === "denied") return value
132
+ return "prompt"
133
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @typedef {import("../../../types/sensors/media-query.js").MediaQueryEntity} MediaQueryEntity
3
- * @typedef {import("../../../types/sensors/media-query.js").MediaQueryMatchEvent} MediaQueryMatchEvent
2
+ * @typedef {import("../../../types/device/media-query.js").MediaQueryEntity} MediaQueryEntity
3
+ * @typedef {import("../../../types/device/media-query.js").MediaQueryMatchEvent} MediaQueryMatchEvent
4
4
  */
5
5
 
6
6
  const listeners = new Map()
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @typedef {import("../../../types/sensors/network-status.js").NetworkStatusEntity} NetworkStatusEntity
2
+ * @typedef {import("../../../types/device/network-status.js").NetworkStatusEntity} NetworkStatusEntity
3
3
  */
4
4
 
5
5
  const ONLINE_EVENT = "online"
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @typedef {import("../../../types/sensors/page-visibility.js").PageVisibilityEntity} PageVisibilityEntity
2
+ * @typedef {import("../../../types/device/page-visibility.js").PageVisibilityEntity} PageVisibilityEntity
3
3
  */
4
4
 
5
5
  const VISIBILITY_EVENT = "visibilitychange"
@@ -1,6 +1,6 @@
1
1
  import { handleRequest } from "@inglorious/store/async"
2
2
 
3
- import { isNative } from "../index.js"
3
+ import { isNative } from "../../native/index.js"
4
4
 
5
5
  const UNSUPPORTED = "unsupported"
6
6
  const FAILED = "failed"
@@ -0,0 +1,61 @@
1
+ import { isNative } from "../../native/index.js"
2
+
3
+ /**
4
+ * A storage for `withStorage` that survives the operating system clearing the
5
+ * WebView's data: in a native app, Capacitor Preferences (`Preferences` from
6
+ * `@capacitor/preferences`, given as `plugin`), answering with promises; in a
7
+ * browser, `localStorage`, looked up at each call. It also serves as Supabase's `auth.storage`,
8
+ * keeping the session there too.
9
+ *
10
+ * @param {{ plugin?: { get(options: { key: string }): Promise<{ value: string | null }>, set(options: { key: string, value: string }): Promise<void>, remove(options: { key: string }): Promise<void> } }} [config]
11
+ *
12
+ * @example
13
+ * import { Preferences } from "@capacitor/preferences"
14
+ * const preferences = createNativeStorage({ plugin: Preferences })
15
+ * const types = {
16
+ * Settings: [Settings, withStorage(["theme"], { storage: () => preferences })],
17
+ * }
18
+ */
19
+ export function createNativeStorage({ plugin } = {}) {
20
+ if (!plugin || !isNative()) {
21
+ return {
22
+ getItem: (key) => globalThis.localStorage?.getItem(key) ?? null,
23
+ setItem: (key, value) => globalThis.localStorage?.setItem(key, value),
24
+ removeItem: (key) => globalThis.localStorage?.removeItem(key),
25
+ }
26
+ }
27
+
28
+ return {
29
+ getItem: async (key) => (await plugin.get({ key })).value,
30
+ setItem: (key, value) => plugin.set({ key, value }),
31
+ removeItem: (key) => plugin.remove({ key }),
32
+ }
33
+ }
34
+
35
+ /**
36
+ * A storage for secrets, such as a session's tokens: in a native app the
37
+ * Keychain (iOS) or Keystore (Android), through `NativeBiometric` from
38
+ * `@capgo/capacitor-native-biometric`, given as `plugin`; in a browser, which
39
+ * has nothing safer, `localStorage`. Use it as `withStorage`'s storage or
40
+ * Supabase's `auth.storage`.
41
+ *
42
+ * @param {{ plugin?: { getData(options: { key: string }): Promise<{ value: string }>, setData(options: { key: string, value: string }): Promise<void>, deleteData(options: { key: string }): Promise<void> } }} [config]
43
+ *
44
+ * @example
45
+ * import { NativeBiometric } from "@capgo/capacitor-native-biometric"
46
+ * const secrets = createSecureStorage({ plugin: NativeBiometric })
47
+ * createClient(url, key, { auth: { storage: secrets } })
48
+ */
49
+ export function createSecureStorage({ plugin } = {}) {
50
+ if (!plugin || !isNative()) return createNativeStorage()
51
+
52
+ return {
53
+ getItem: (key) =>
54
+ plugin.getData({ key }).then(
55
+ ({ value }) => value,
56
+ () => null,
57
+ ),
58
+ setItem: (key, value) => plugin.setData({ key, value }),
59
+ removeItem: (key) => plugin.deleteData({ key }),
60
+ }
61
+ }
package/src/mount.js CHANGED
@@ -10,22 +10,25 @@ import { createAccessibleNavigation } from "./router/accessible-navigation.js"
10
10
 
11
11
  /**
12
12
  * Mounts a lit-html template to the DOM and subscribes to a store for re-rendering.
13
+ * Markup already in the element, as a server-rendered page has, is hydrated rather
14
+ * than replaced. In an app with the `Router` type, each navigation is also announced
15
+ * to screen readers and moves focus back to the top of the new page, as a full page
16
+ * load would. Once mounted, it notifies `init`.
17
+ *
13
18
  * @param {Store} store - The application state store.
14
19
  * @param {(api: Api) => TemplateResult | null} renderFn - The root render function.
15
20
  * @param {HTMLElement | DocumentFragment} element - The DOM element to mount the template to.
16
- * In an app with the `Router` type, each navigation is also announced to screen readers
17
- * and moves focus back to the top of the new page, as a full page load would.
18
- *
19
21
  * @param {Object} [options] - Root error-boundary and navigation options.
20
22
  * @param {(error: unknown, api: Api) => void} [options.onError] - Called when the
21
23
  * root render throws. Defaults to `console.error`.
22
24
  * @param {(error: unknown, api: Api) => TemplateResult | null} [options.fallback] -
23
25
  * Optional fallback template rendered in place of the failed root render.
26
+ * @param {boolean} [options.hydrate=true] - Whether existing markup is hydrated.
24
27
  * @param {boolean} [options.hasAccessibleNavigation=true] - Whether navigations are
25
28
  * announced and move focus. Only apps with the `Router` type navigate.
26
29
  * @param {() => string | null} [options.getPageName] - The name to announce for the
27
30
  * current page, or `null` while it is not known yet; by default the document title.
28
- * @returns {() => void} An unsubscribe function
31
+ * @returns {Promise<() => void>} An unsubscribe function, once mounted.
29
32
  */
30
33
  export async function mount(store, renderFn, element, options = {}) {
31
34
  const {
@@ -1,46 +1,60 @@
1
1
  import { isNative } from "../index.js"
2
2
 
3
- const DEFAULT_ID = "router"
3
+ const DEFAULT_ROUTER = "router"
4
4
  const URL_OPEN_EVENT = "appUrlOpen"
5
5
 
6
6
  /**
7
- * Opens Universal Links and App Links in the app's router: a link to the
8
- * app's domain, tapped while the app is installed, opens the app instead of
9
- * the browser, and the router goes to the link's path. Covers a link that
10
- * starts the app as well as one that arrives while it runs. Does nothing
11
- * outside a native app.
7
+ * The type that opens Universal Links and App Links in the app's router: a
8
+ * link to the app's domain, tapped while the app is installed, opens the app
9
+ * instead of the browser, and the router goes to the link's path. It covers a
10
+ * link that starts the app as well as one that arrives while it runs. The
11
+ * entity's `url` is the last link opened. Does nothing outside a native app.
12
12
  *
13
- * @param {Object} app `App` from `@capacitor/app`.
14
- * @param {{ notify: (type: string, payload?: unknown) => void }} store
15
- * @param {{ id?: string }} [options] The router entity, `router` by default.
16
- * @returns {() => Promise<void>} Stops listening.
13
+ * @param {Object} config
14
+ * @param {Object} config.plugin `App` from `@capacitor/app`.
15
+ * @param {string} [config.router] The router entity, `router` by default.
17
16
  *
18
17
  * @example
19
- * watchAppLinks(App, store)
18
+ * import { App } from "@capacitor/app"
19
+ * const types = { AppLinks: createAppLinks({ plugin: App }) }
20
+ * const entities = { appLinks: { type: "AppLinks" } }
20
21
  */
21
- export function watchAppLinks(app, store, { id = DEFAULT_ID } = {}) {
22
- if (!isNative()) return async () => {}
22
+ export function createAppLinks({ plugin, router = DEFAULT_ROUTER }) {
23
+ const listeners = new Map()
23
24
 
24
- openLaunchUrl()
25
- const listener = app.addListener(URL_OPEN_EVENT, ({ url }) => open(url))
25
+ return {
26
+ create(entity, _, api) {
27
+ entity.url ??= null
28
+ if (!isNative()) return
26
29
 
27
- return async function stop() {
28
- const handle = await listener
29
- await handle.remove()
30
- }
30
+ const { id } = entity
31
+ const open = (url) => api.notify(`#${id}:appLinkOpen`, url)
31
32
 
32
- async function openLaunchUrl() {
33
- try {
34
- const launch = await app.getLaunchUrl()
35
- if (launch?.url) open(launch.url)
36
- } catch {
37
- // No launch URL to read is the same as none.
38
- }
39
- }
33
+ plugin.getLaunchUrl().then(
34
+ (launch) => {
35
+ if (launch?.url) open(launch.url)
36
+ },
37
+ () => {
38
+ // No launch URL to read is the same as none.
39
+ },
40
+ )
41
+ listeners.set(
42
+ id,
43
+ plugin.addListener(URL_OPEN_EVENT, ({ url }) => open(url)),
44
+ )
45
+ },
46
+
47
+ destroy(entity) {
48
+ const listener = listeners.get(entity.id)
49
+ listeners.delete(entity.id)
50
+ listener?.then((handle) => handle.remove())
51
+ },
40
52
 
41
- function open(url) {
42
- const path = toPath(url)
43
- if (path) store.notify(`#${id}:navigate`, path)
53
+ appLinkOpen(entity, url, api) {
54
+ entity.url = url
55
+ const path = toPath(url)
56
+ if (path) api.notify(`#${router}:navigate`, path)
57
+ },
44
58
  }
45
59
  }
46
60
 
@@ -4,32 +4,51 @@ const DEFAULT_ROOT_PATHS = ["/"]
4
4
  const BACK_BUTTON_EVENT = "backButton"
5
5
 
6
6
  /**
7
- * Android's back button and back gesture, as other Android apps have them:
8
- * they go back in history, and close the app on a root path or when there is
9
- * no history left. Root paths are the top-level pages, like a tab bar's: going
10
- * back from one leaves the app at once. Does nothing outside a native app, and
11
- * iOS sends no back button.
7
+ * The type behind Android's back button and back gesture, as other Android
8
+ * apps have them: they go back in history, and close the app on a root path or
9
+ * when there is no history left. The entity's `rootPaths` are the top-level
10
+ * pages, like a tab bar's: going back from one leaves the app at once. Does
11
+ * nothing outside a native app, and iOS sends no back button.
12
12
  *
13
- * @param {Object} app `App` from `@capacitor/app`.
14
- * @param {{ rootPaths?: string[] }} [options] `["/"]` by default.
15
- * @returns {() => Promise<void>} Stops listening.
13
+ * @param {Object} config
14
+ * @param {Object} config.plugin `App` from `@capacitor/app`.
16
15
  *
17
16
  * @example
18
- * watchBackButton(App, { rootPaths: ["/", "/search", "/profile"] })
17
+ * import { App } from "@capacitor/app"
18
+ * const types = { BackButton: createBackButton({ plugin: App }) }
19
+ * const entities = {
20
+ * backButton: { type: "BackButton", rootPaths: ["/", "/search", "/profile"] },
21
+ * }
19
22
  */
20
- export function watchBackButton(app, { rootPaths = DEFAULT_ROOT_PATHS } = {}) {
21
- if (!isNative()) return async () => {}
23
+ export function createBackButton({ plugin }) {
24
+ const listeners = new Map()
22
25
 
23
- const listener = app.addListener(BACK_BUTTON_EVENT, ({ canGoBack }) => {
24
- if (canGoBack && !rootPaths.includes(window.location.pathname)) {
25
- window.history.back()
26
- } else {
27
- app.exitApp()
28
- }
29
- })
26
+ return {
27
+ create(entity, _, api) {
28
+ entity.rootPaths ??= DEFAULT_ROOT_PATHS
29
+ if (!isNative()) return
30
30
 
31
- return async function stop() {
32
- const handle = await listener
33
- await handle.remove()
31
+ const { id } = entity
32
+ listeners.set(
33
+ id,
34
+ plugin.addListener(BACK_BUTTON_EVENT, ({ canGoBack }) =>
35
+ api.notify(`#${id}:backButtonPress`, { canGoBack }),
36
+ ),
37
+ )
38
+ },
39
+
40
+ destroy(entity) {
41
+ const listener = listeners.get(entity.id)
42
+ listeners.delete(entity.id)
43
+ listener?.then((handle) => handle.remove())
44
+ },
45
+
46
+ backButtonPress(entity, { canGoBack }) {
47
+ if (canGoBack && !entity.rootPaths.includes(window.location.pathname)) {
48
+ window.history.back()
49
+ } else {
50
+ plugin.exitApp()
51
+ }
52
+ },
34
53
  }
35
54
  }