@inglorious/store 12.5.0 → 12.6.1

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
@@ -834,6 +834,21 @@ const types = {
834
834
  - Put it last in the type's array: it saves after the handlers before it.
835
835
  - `key` names where the fields go (the entity's id by default), or derives it from the entity. `storage` is any Web Storage, `localStorage` by default.
836
836
  - Storage that is missing, full or refusing, as in a private window, only means nothing is kept.
837
+ - A storage whose `getItem` returns a promise works too, such as Capacitor Preferences through `createNativeStorage` from `@inglorious/web/mobile`. The entity then starts with the type's defaults, and once the storage answers, a `storageRestore` event brings back the fields no handler changed meanwhile. Nothing is written before that. A type with its own `storageRestore(entity, restored, api)` hears what came back, to announce it. Several `withStorage` on one type each restore their own fields:
838
+
839
+ ```javascript
840
+ const Session = [
841
+ {
842
+ create(entity) {
843
+ entity.user ??= null
844
+ },
845
+ storageRestore(entity, restored, api) {
846
+ api.notify("sessionChange", { user: entity.user })
847
+ },
848
+ },
849
+ withStorage(["user"], { storage: () => preferences }),
850
+ ]
851
+ ```
837
852
 
838
853
  ---
839
854
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/store",
3
- "version": "12.5.0",
3
+ "version": "12.6.1",
4
4
  "description": "A state manager for real-time, collaborative apps, inspired by game development patterns and compatible with Redux.",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -82,11 +82,11 @@
82
82
  "mutative": "^2.0.2"
83
83
  },
84
84
  "peerDependencies": {
85
- "@inglorious/utils": "^5.3.0"
85
+ "@inglorious/utils": "^5.4.0"
86
86
  },
87
87
  "devDependencies": {
88
88
  "@inglorious/eslint-config": "1.2.0",
89
- "@inglorious/utils": "5.3.0",
89
+ "@inglorious/utils": "5.4.0",
90
90
  "@reduxjs/toolkit": "^2.14.0",
91
91
  "prettier": "^3.9.10",
92
92
  "typescript": "~7.0.2",
@@ -1,5 +1,11 @@
1
+ import { pick } from "@inglorious/utils/data-structures/object.js"
2
+ import { isPromiseLike } from "@inglorious/utils/data-structures/promise.js"
3
+ import { parseJSON, readItem, writeItem } from "@inglorious/utils/storage.js"
4
+
1
5
  const RENDER = /^render/
2
6
 
7
+ let decorators = 0
8
+
3
9
  /**
4
10
  * Keeps some of an entity's fields in storage, as a byproduct of the entity:
5
11
  * the entity stays the one source of truth. When the entity is created, the
@@ -11,12 +17,20 @@ const RENDER = /^render/
11
17
  * Storage that is missing, full or refusing, as in a private window, only
12
18
  * means nothing is kept.
13
19
  *
20
+ * A storage whose `getItem` returns a promise, such as Capacitor Preferences,
21
+ * restores the fields once it answers: the entity starts with the type's
22
+ * defaults, and `storageRestore` then brings back the fields no handler has
23
+ * changed in the meantime. Nothing is written until then. A type's own
24
+ * `storageRestore(entity, restored, api)` runs after.
25
+ *
14
26
  * @param {string[]} fields The entity's fields to keep.
15
27
  * @param {Object} [options]
16
28
  * @param {string | ((entity: Object) => string)} [options.key] Where the
17
29
  * fields are kept. Defaults to the entity's id.
18
30
  * @param {() => Storage | undefined} [options.storage] A Web Storage, such as
19
- * `() => sessionStorage` for the tab only. Defaults to `localStorage`.
31
+ * `() => sessionStorage` for the tab only, or anything with the same
32
+ * `getItem` and `setItem`, answering now or with a promise. Defaults to
33
+ * `localStorage`.
20
34
  *
21
35
  * @example
22
36
  * const types = {
@@ -32,15 +46,19 @@ export function withStorage(
32
46
  typeof key === "function" ? key(entity) : (key ?? entity.id)
33
47
 
34
48
  return (type) => {
49
+ // Tells this decorator's restores from those of others on the same type.
50
+ const source = `withStorage:${++decorators}`
35
51
  /** What is kept for each entity, as written. */
36
52
  const kept = new Map()
53
+ /** For entities still waiting on storage, their fields as created. */
54
+ const pending = new Map()
37
55
 
38
56
  function save(entity) {
39
- if (!isEntity(entity)) return
57
+ if (!isEntity(entity) || pending.has(entity.id)) return
40
58
  const value = JSON.stringify(pick(entity, fields))
41
59
  if (kept.get(entity.id) === value) return
42
60
  kept.set(entity.id, value)
43
- write(storage, keyOf(entity), value)
61
+ writeItem(keyOf(entity), value, storage)
44
62
  }
45
63
 
46
64
  const behavior = {}
@@ -56,50 +74,55 @@ export function withStorage(
56
74
  }
57
75
 
58
76
  behavior.create = function (entity, payload, api) {
59
- const stored = read(storage, keyOf(entity))
77
+ const stored = readItem(keyOf(entity), storage)
78
+
79
+ if (isPromiseLike(stored)) {
80
+ const result = type.create?.call(this, entity, payload, api)
81
+ pending.set(entity.id, snapshot(entity, fields))
82
+ const { id } = entity
83
+ const restore = (value) =>
84
+ api.notify(`#${id}:storageRestore`, { source, value: value ?? null })
85
+ stored.then(restore, () => restore(null))
86
+ return result
87
+ }
88
+
60
89
  kept.set(entity.id, stored)
61
- Object.assign(entity, pick(parse(stored), fields))
90
+ Object.assign(entity, pick(parseJSON(stored), fields))
62
91
  const result = type.create?.call(this, entity, payload, api)
63
92
  save(entity)
64
93
  return result
65
94
  }
66
95
 
96
+ behavior.storageRestore = function (entity, payload, api) {
97
+ const created = pending.get(entity.id)
98
+ if (payload?.source !== source || !created) {
99
+ type.storageRestore?.call(this, entity, payload, api)
100
+ save(entity)
101
+ return
102
+ }
103
+ pending.delete(entity.id)
104
+ kept.set(entity.id, payload.value)
105
+
106
+ const restored = pick(parseJSON(payload.value), fields)
107
+ for (const [field, value] of Object.entries(restored)) {
108
+ if (JSON.stringify(entity[field]) === created[field]) {
109
+ entity[field] = value
110
+ }
111
+ }
112
+ type.storageRestore?.call(this, entity, restored, api)
113
+ save(entity)
114
+ }
115
+
67
116
  return behavior
68
117
  }
69
118
  }
70
119
 
71
- function pick(source, fields) {
72
- const picked = {}
73
- for (const field of fields) {
74
- if (source && field in source) picked[field] = source[field]
75
- }
76
- return picked
120
+ function snapshot(entity, fields) {
121
+ return Object.fromEntries(
122
+ fields.map((field) => [field, JSON.stringify(entity[field])]),
123
+ )
77
124
  }
78
125
 
79
126
  function isEntity(value) {
80
127
  return Boolean(value) && typeof value === "object" && "id" in value
81
128
  }
82
-
83
- function parse(stored) {
84
- try {
85
- return stored ? JSON.parse(stored) : null
86
- } catch {
87
- return null
88
- }
89
- }
90
-
91
- function read(storage, key) {
92
- try {
93
- return storage()?.getItem(key) ?? null
94
- } catch {
95
- return null
96
- }
97
- }
98
-
99
- function write(storage, key, value) {
100
- try {
101
- storage()?.setItem(key, value)
102
- } catch {
103
- // Nothing is kept: the entity still has the value.
104
- }
105
- }
@@ -1,18 +1,28 @@
1
+ import type { KeyValueStorage } from "@inglorious/utils/storage"
2
+
1
3
  import { Api } from "../api"
2
4
  import { BaseEntity, EntityType } from "../store"
3
5
 
6
+ export type { KeyValueStorage }
7
+
4
8
  export interface StorageOptions {
5
9
  /** Where the fields are kept. Defaults to the entity's id. */
6
10
  key?: string | ((entity: BaseEntity & { id: string }) => string)
7
- /** A Web Storage, such as `() => sessionStorage`. Defaults to `localStorage`. */
8
- storage?: () => Storage | undefined
11
+ /**
12
+ * A Web Storage, such as `() => sessionStorage`, or one answering with
13
+ * promises, which restores the fields once it answers. Defaults to
14
+ * `localStorage`.
15
+ */
16
+ storage?: () => KeyValueStorage | undefined
9
17
  }
10
18
 
11
19
  /**
12
20
  * Keeps some of an entity's fields in storage, as a byproduct of the entity,
13
21
  * which stays the one source of truth: they come back when it is created,
14
22
  * before the type's own `create`, and are written back after any handler that
15
- * changes them. Put it last in the type's array.
23
+ * changes them. Put it last in the type's array. With a storage answering
24
+ * with promises, the entity starts with the defaults and `storageRestore`
25
+ * brings back the fields no handler changed while waiting.
16
26
  */
17
27
  export declare function withStorage(
18
28
  fields: string[],