@inglorious/web 6.29.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/web",
3
- "version": "6.29.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": [
@@ -174,7 +174,7 @@
174
174
  "lit-html": "^3.3.3"
175
175
  },
176
176
  "peerDependencies": {
177
- "@inglorious/store": "^12.6.2"
177
+ "@inglorious/store": "^12.7.0"
178
178
  },
179
179
  "devDependencies": {
180
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
  }
@@ -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
 
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
  }