@inglorious/web 6.25.0 → 6.26.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/README.md CHANGED
@@ -609,9 +609,10 @@ test("requireAuth blocks unauthenticated access", () => {
609
609
  // Compose the guard with the page type
610
610
  const GuardedPage = requireAuth(AdminPage)
611
611
 
612
- // Mock localStorage.getItem to return null (not logged in)
612
+ // Signed out: the session entity has no user
613
613
  const mockApi = {
614
614
  notify: jest.fn(),
615
+ getEntity: () => ({ user: null }),
615
616
  }
616
617
 
617
618
  const { events } = trigger(
@@ -631,11 +632,12 @@ test("requireAuth blocks unauthenticated access", () => {
631
632
  })
632
633
 
633
634
  test("requireAuth allows authenticated access", () => {
634
- // Mock localStorage.getItem to return user data
635
- localStorage.setItem("user", JSON.stringify({ id: 1 }))
636
-
635
+ // Signed in: the session entity has a user
637
636
  const GuardedPage = requireAuth(AdminPage)
638
- const mockApi = { notify: jest.fn() }
637
+ const mockApi = {
638
+ notify: jest.fn(),
639
+ getEntity: () => ({ user: { id: 1 } }),
640
+ }
639
641
 
640
642
  const { events } = trigger(
641
643
  { type: "GuardedPage", id: "admin" },
@@ -646,9 +648,6 @@ test("requireAuth allows authenticated access", () => {
646
648
 
647
649
  // Should NOT redirect
648
650
  expect(events).toEqual([])
649
-
650
- // Cleanup
651
- localStorage.removeItem("user")
652
651
  })
653
652
  ```
654
653
 
@@ -1135,8 +1134,9 @@ export const requireAuth = (type) => ({
1135
1134
  // Only act when navigating to this specific route
1136
1135
  if (payload.route !== entity.id) return
1137
1136
 
1138
- // Check authentication
1139
- const user = localStorage.getItem("user")
1137
+ // Check authentication: the session entity is the one place the user
1138
+ // lives (kept between visits with withStorage, if at all)
1139
+ const { user } = api.getEntity("session") ?? {}
1140
1140
  if (!user) {
1141
1141
  // Redirect to login, preserving the intended destination
1142
1142
  api.notify("navigate", {
@@ -1689,6 +1689,35 @@ It returns a function that stops following.
1689
1689
 
1690
1690
  ---
1691
1691
 
1692
+ ## Share
1693
+
1694
+ `@inglorious/web/share` is the type behind a share button. `share` hands a title, a text, a link or a file to whatever the device does best, and the entity says what happened:
1695
+
1696
+ - in a native app, the system's share sheet, through [`@capacitor/share`](https://capacitorjs.com/docs/apis/share) when you hand it over;
1697
+ - in a browser, a file (a `url` with a `fileName`) downloads, since a browser has nowhere better to put it;
1698
+ - otherwise the browser's share sheet where there is one (Web Share API), else the link is copied.
1699
+
1700
+ ```javascript
1701
+ import { Share } from "@capacitor/share"
1702
+ import { createShare } from "@inglorious/web/share"
1703
+
1704
+ const types = { Share: createShare({ plugin: Share }) }
1705
+
1706
+ api.notify("#share:share", {
1707
+ title: "My job",
1708
+ url: "https://example.com/jobs/1",
1709
+ })
1710
+ api.notify("#share:share", {
1711
+ title: "Wedding",
1712
+ url: icsUrl,
1713
+ fileName: "wedding.ics",
1714
+ })
1715
+ ```
1716
+
1717
+ `result` is `"shared"`, `"downloaded"`, `"copied"` or `"cancelled"`: closing the sheet is not an error. `status` and `error` (`"unsupported"` or `"failed"`) come from `handleRequest`. `canShare` says whether a link can be shared at all, to hide the button where it can't.
1718
+
1719
+ ---
1720
+
1692
1721
  ## Haptics
1693
1722
 
1694
1723
  `@inglorious/web/haptics` plays taps the user can feel. In a native app it uses the system's haptics through [`@capacitor/haptics`](https://capacitorjs.com/docs/apis/haptics), once you hand the plugin over. Elsewhere it vibrates where the browser can (Chrome on Android), once the user has tapped the page; iOS browsers stay silent. Every call returns whether it played.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/web",
3
- "version": "6.25.0",
3
+ "version": "6.26.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": [
@@ -61,6 +61,10 @@
61
61
  "types": "./types/haptics.d.ts",
62
62
  "import": "./src/haptics/index.js"
63
63
  },
64
+ "./share": {
65
+ "types": "./types/share.d.ts",
66
+ "import": "./src/share/index.js"
67
+ },
64
68
  "./decorators/with-debounce": {
65
69
  "types": "./types/decorators/with-debounce.d.ts",
66
70
  "import": "./src/decorators/with-debounce/index.js"
@@ -158,7 +162,7 @@
158
162
  "lit-html": "^3.3.3"
159
163
  },
160
164
  "peerDependencies": {
161
- "@inglorious/store": "^12.4.0"
165
+ "@inglorious/store": "^12.5.0"
162
166
  },
163
167
  "devDependencies": {
164
168
  "@inglorious/eslint-config": "1.2.0",
@@ -1,4 +1,3 @@
1
- const DEFAULT_CONSENT_KEY = "inglorious-analytics-consent"
2
1
  const GRANTED = "granted"
3
2
  const DENIED = "denied"
4
3
 
@@ -8,7 +7,8 @@ const DENIED = "denied"
8
7
  * to an analytics library is what sets its cookies and sends its first hit.
9
8
  *
10
9
  * Its entity's `consent` is `"granted"`, `"denied"` or `null` (not asked
11
- * yet), remembered on the device. While `isAsking`, the app renders its own
10
+ * yet). Keep it between visits with `withStorage(["consent"])` from
11
+ * `@inglorious/store/storage`. While `isAsking`, the app renders its own
12
12
  * consent prompt, whose answer is `analyticsConsent` with `true` or `false`.
13
13
  * `analyticsAsk` brings the prompt back, for a settings page where the
14
14
  * choice can be changed as easily as it was made.
@@ -25,35 +25,19 @@ const DENIED = "denied"
25
25
  *
26
26
  * @param {Object} config
27
27
  * @param {Object} config.adapter
28
- * @param {string} [config.consentKey] - The localStorage key of the choice.
29
28
  *
30
29
  * @example
31
- * const types = { Analytics: [createAnalytics({ adapter }), template] }
30
+ * const types = {
31
+ * Analytics: [createAnalytics({ adapter }), template, withStorage(["consent"])],
32
+ * }
32
33
  * const entities = { analytics: { type: "Analytics" } }
33
34
  * // later, anywhere
34
35
  * api.notify("#analytics:analyticsTrack", { name: "sign_up" })
35
36
  */
36
- export function createAnalytics({ adapter, consentKey = DEFAULT_CONSENT_KEY }) {
37
- function readConsent() {
38
- try {
39
- const stored = window.localStorage.getItem(consentKey)
40
- return stored === GRANTED || stored === DENIED ? stored : null
41
- } catch {
42
- return null
43
- }
44
- }
45
-
46
- function writeConsent(consent) {
47
- try {
48
- window.localStorage.setItem(consentKey, consent)
49
- } catch {
50
- // Without storage the prompt comes back next visit, nothing worse.
51
- }
52
- }
53
-
37
+ export function createAnalytics({ adapter }) {
54
38
  return {
55
39
  create(entity) {
56
- entity.consent ??= readConsent()
40
+ entity.consent ??= null
57
41
  entity.isAsking ??= entity.consent === null
58
42
  if (entity.consent === GRANTED) call(() => adapter.setConsent(true))
59
43
  },
@@ -65,7 +49,6 @@ export function createAnalytics({ adapter, consentKey = DEFAULT_CONSENT_KEY }) {
65
49
 
66
50
  analyticsConsent(entity, isGranted, api) {
67
51
  const consent = isGranted ? GRANTED : DENIED
68
- writeConsent(consent)
69
52
  entity.consent = consent
70
53
  entity.isAsking = false
71
54
  call(() => adapter.setConsent(isGranted))
package/src/push/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  import { handleAsync } from "@inglorious/store/async"
2
2
 
3
- const DEFAULT_DECLINE_KEY = "inglorious-push-declined"
4
-
5
3
  // The adapters whose taps are already wired: an entity created again (a hot
6
4
  // update, a second store) must not open each push twice.
7
5
  const tappedAdapters = new WeakSet()
@@ -12,9 +10,10 @@ const tappedAdapters = new WeakSet()
12
10
  * A device shows its permission dialog only so many times, and a refusal
13
11
  * there may be for good. So the type asks in the app's own words first: an
14
12
  * entity with `isOpen` the app renders as a prompt, whose yes brings up the
15
- * system's dialog (`pushAsk`) and whose no (`pushDecline`) is remembered on
16
- * the device, so it never asks again. Allowed later from the system's
17
- * settings, pushes still register.
13
+ * system's dialog (`pushAsk`) and whose no (`pushDecline`) sets
14
+ * `isDeclined`, so it never asks again. Keep it between visits with
15
+ * `withStorage(["isDeclined"])` from `@inglorious/store/storage`. Allowed
16
+ * later from the system's settings, pushes still register.
18
17
  *
19
18
  * The app tells it when there is someone to register for: `pushStart` (at
20
19
  * sign-in) checks the permission, registers the device if it is granted, and
@@ -37,7 +36,6 @@ const tappedAdapters = new WeakSet()
37
36
  *
38
37
  * @param {Object} config
39
38
  * @param {Object} config.adapter
40
- * @param {string} [config.declineKey] - The localStorage key of a decline.
41
39
  * @param {(url: string, api: Object) => void} [config.onTap]
42
40
  *
43
41
  * @example
@@ -51,21 +49,10 @@ const tappedAdapters = new WeakSet()
51
49
  * },
52
50
  * }
53
51
  */
54
- export function createPushPrompt({
55
- adapter,
56
- declineKey = DEFAULT_DECLINE_KEY,
57
- onTap = navigate,
58
- }) {
59
- function isDeclined() {
60
- try {
61
- return window.localStorage.getItem(declineKey) !== null
62
- } catch {
63
- return false
64
- }
65
- }
66
-
52
+ export function createPushPrompt({ adapter, onTap = navigate }) {
67
53
  return {
68
54
  create(entity, _, api) {
55
+ entity.isDeclined ??= false
69
56
  entity.isOpen ??= false
70
57
  entity.isActive ??= false
71
58
  if (adapter.onTap && !tappedAdapters.has(adapter)) {
@@ -95,7 +82,7 @@ export function createPushPrompt({
95
82
  api.notify(`#${entity.id}:pushRegister`)
96
83
  return
97
84
  }
98
- entity.isOpen = permission === "prompt" && !isDeclined()
85
+ entity.isOpen = permission === "prompt" && !entity.isDeclined
99
86
  },
100
87
  error() {},
101
88
  }),
@@ -114,11 +101,7 @@ export function createPushPrompt({
114
101
  }),
115
102
 
116
103
  pushDecline(entity) {
117
- try {
118
- window.localStorage.setItem(declineKey, "true")
119
- } catch {
120
- // Without storage the prompt comes back next start, nothing worse.
121
- }
104
+ entity.isDeclined = true
122
105
  entity.isOpen = false
123
106
  },
124
107
 
@@ -0,0 +1,109 @@
1
+ import { handleRequest } from "@inglorious/store/async"
2
+
3
+ import { isNative } from "../mobile/index.js"
4
+
5
+ const UNSUPPORTED = "unsupported"
6
+ const FAILED = "failed"
7
+ // Capacitor's Share rejects with this when the person closes the sheet.
8
+ const NATIVE_CANCEL = /cancel/i
9
+
10
+ /**
11
+ * The type behind a share button. `share` hands a title, text, link or file
12
+ * to whatever the device does best, and the entity says what happened:
13
+ *
14
+ * - in a native app, the system's share sheet, through `Share` from
15
+ * `@capacitor/share` when given as `plugin`;
16
+ * - in a browser, a file (a `url` with a `fileName`) downloads, since a
17
+ * browser has nowhere better to put it;
18
+ * - otherwise the browser's share sheet where there is one (Web Share API),
19
+ * else the link is copied.
20
+ *
21
+ * `result` is `"shared"`, `"downloaded"`, `"copied"` or `"cancelled"`: closing
22
+ * the sheet is not an error. `status` and `error` (`"unsupported"` or
23
+ * `"failed"`) are those of `handleRequest`. `canShare` says whether a link can
24
+ * be shared at all, to hide the button otherwise; a file can always download.
25
+ *
26
+ * @param {{ plugin?: { share(options: object): Promise<unknown> } }} [config]
27
+ *
28
+ * @example
29
+ * import { Share } from "@capacitor/share"
30
+ * const types = { Share: createShare({ plugin: Share }) }
31
+ * api.notify("#share:share", { title: "My job", url })
32
+ */
33
+ export function createShare({ plugin } = {}) {
34
+ return {
35
+ create(entity) {
36
+ entity.status ??= "idle"
37
+ entity.error ??= null
38
+ entity.result ??= null
39
+ entity.canShare = canShare(plugin)
40
+ },
41
+
42
+ ...handleRequest(
43
+ "share",
44
+ {
45
+ start(entity) {
46
+ entity.result = null
47
+ },
48
+ run: (content) => share(content, plugin),
49
+ success(entity, result) {
50
+ entity.result = result
51
+ },
52
+ },
53
+ {
54
+ toError: (error) =>
55
+ error?.message === UNSUPPORTED ? UNSUPPORTED : FAILED,
56
+ },
57
+ ),
58
+ }
59
+ }
60
+
61
+ async function share({ title, text, url, fileName } = {}, plugin) {
62
+ if (plugin && isNative()) {
63
+ try {
64
+ await plugin.share({ title, text, url, dialogTitle: title })
65
+ return "shared"
66
+ } catch (error) {
67
+ if (NATIVE_CANCEL.test(error?.message ?? "")) return "cancelled"
68
+ throw error
69
+ }
70
+ }
71
+
72
+ if (url && fileName) {
73
+ download(url, fileName)
74
+ return "downloaded"
75
+ }
76
+
77
+ const navigator = globalThis.navigator
78
+ if (navigator?.share) {
79
+ try {
80
+ await navigator.share({ title, text, url })
81
+ return "shared"
82
+ } catch (error) {
83
+ if (error?.name === "AbortError") return "cancelled"
84
+ throw error
85
+ }
86
+ }
87
+
88
+ if (url && navigator?.clipboard) {
89
+ await navigator.clipboard.writeText(url)
90
+ return "copied"
91
+ }
92
+
93
+ throw new Error(UNSUPPORTED)
94
+ }
95
+
96
+ function canShare(plugin) {
97
+ if (plugin && isNative()) return true
98
+ const navigator = globalThis.navigator
99
+ return Boolean(navigator?.share || navigator?.clipboard)
100
+ }
101
+
102
+ function download(url, fileName) {
103
+ const link = document.createElement("a")
104
+ link.href = url
105
+ link.download = fileName
106
+ document.body.append(link)
107
+ link.click()
108
+ link.remove()
109
+ }
@@ -12,8 +12,6 @@ export interface AnalyticsAdapter {
12
12
 
13
13
  export interface AnalyticsConfig {
14
14
  adapter: AnalyticsAdapter
15
- /** The localStorage key of the choice. Defaults to `"inglorious-analytics-consent"`. */
16
- consentKey?: string
17
15
  }
18
16
 
19
17
  export interface AnalyticsEntity {
package/types/push.d.ts CHANGED
@@ -20,8 +20,6 @@ export interface PushAdapter {
20
20
 
21
21
  export interface PushPromptConfig {
22
22
  adapter: PushAdapter
23
- /** The localStorage key of a decline. Defaults to `"inglorious-push-declined"`. */
24
- declineKey?: string
25
23
  /** Opens a tapped push's `url`. Defaults to `#router:navigate`. */
26
24
  onTap?: (url: string, api: Api) => void
27
25
  }
@@ -31,6 +29,8 @@ export interface PushPromptEntity {
31
29
  type: string
32
30
  /** The app's own prompt is showing. */
33
31
  isOpen: boolean
32
+ /** The prompt was declined: it never opens again. Keep it with `withStorage`. */
33
+ isDeclined: boolean
34
34
  /** Between `pushStart` and `pushStop`: someone to register for. */
35
35
  isActive: boolean
36
36
  }
@@ -0,0 +1,42 @@
1
+ /** What `createShare` needs of `Share` from `@capacitor/share`. */
2
+ export interface SharePlugin {
3
+ share(options: {
4
+ title?: string
5
+ text?: string
6
+ url?: string
7
+ dialogTitle?: string
8
+ }): Promise<unknown>
9
+ }
10
+
11
+ /** What to share: a link, a text, or a file to download in a browser. */
12
+ export interface ShareContent {
13
+ title?: string
14
+ text?: string
15
+ url?: string
16
+ /** Makes `url` a file: a browser downloads it under this name. */
17
+ fileName?: string
18
+ }
19
+
20
+ export interface ShareEntity {
21
+ id?: string
22
+ type: string
23
+ status: "idle" | "loading" | "success" | "error"
24
+ error: "unsupported" | "failed" | null
25
+ result: "shared" | "downloaded" | "copied" | "cancelled" | null
26
+ /** A link can be shared, by sheet or by copying it. */
27
+ canShare: boolean
28
+ }
29
+
30
+ export type ShareType = {
31
+ create(entity: ShareEntity): void
32
+ share(entity: ShareEntity, content: ShareContent): void
33
+ [handler: string]: unknown
34
+ }
35
+
36
+ /**
37
+ * The type behind a share button: the system's sheet in a native app, a
38
+ * download for files in a browser, else the browser's sheet, else a copy.
39
+ */
40
+ export declare function createShare(config?: {
41
+ plugin?: SharePlugin
42
+ }): ShareType