@inglorious/store 12.4.0 → 12.6.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
@@ -805,6 +805,53 @@ Available scopes:
805
805
 
806
806
  ---
807
807
 
808
+ ### `withStorage`
809
+
810
+ The entity is the one source of truth; keeping some of it between visits is a byproduct. `withStorage` brings the fields back when the entity is created, before the type's own `create`, and writes them back after any handler that changes them:
811
+
812
+ ```ts
813
+ import { withStorage } from "@inglorious/store/storage"
814
+
815
+ const Settings = {
816
+ create(entity) {
817
+ entity.theme ??= "light" // kept from last time, else light
818
+ },
819
+ themeSet(entity, theme) {
820
+ entity.theme = theme // saved along the way
821
+ },
822
+ }
823
+
824
+ const types = {
825
+ Settings: [Settings, withStorage(["theme"])],
826
+ Draft: [
827
+ Draft,
828
+ withStorage(["text"], { key: "draft", storage: () => sessionStorage }),
829
+ ],
830
+ }
831
+ ```
832
+
833
+ - Nothing reads storage but `withStorage`: the app reads the entity, and the rest follows.
834
+ - Put it last in the type's array: it saves after the handlers before it.
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
+ - 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:
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
+ ```
852
+
853
+ ---
854
+
808
855
  ## 🧩 Migrating from Redux Toolkit (RTK)
809
856
 
810
857
  Inglorious Store now provides utilities to **gradually migrate from RTK slices and thunks**, leveraging `handleAsync` to simplify async logic.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/store",
3
- "version": "12.4.0",
3
+ "version": "12.6.0",
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",
@@ -48,6 +48,10 @@
48
48
  "types": "./types/behaviors/optimistic.d.ts",
49
49
  "import": "./src/behaviors/optimistic.js"
50
50
  },
51
+ "./storage": {
52
+ "types": "./types/behaviors/storage.d.ts",
53
+ "import": "./src/behaviors/storage.js"
54
+ },
51
55
  "./fsm": {
52
56
  "types": "./types/behaviors/state-machine/fsm.d.ts",
53
57
  "import": "./src/behaviors/state-machine/fsm.js"
@@ -78,15 +82,15 @@
78
82
  "mutative": "^2.0.2"
79
83
  },
80
84
  "peerDependencies": {
81
- "@inglorious/utils": "^5.3.0"
85
+ "@inglorious/utils": "^5.4.0"
82
86
  },
83
87
  "devDependencies": {
84
88
  "@inglorious/eslint-config": "1.2.0",
85
- "@inglorious/utils": "5.3.0",
89
+ "@inglorious/utils": "5.4.0",
86
90
  "@reduxjs/toolkit": "^2.14.0",
87
91
  "prettier": "^3.9.10",
88
92
  "typescript": "~7.0.2",
89
- "vite": "^8.3.7",
93
+ "vite": "^8.3.8",
90
94
  "vitest": "^5.1.0"
91
95
  },
92
96
  "engines": {
@@ -0,0 +1,120 @@
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
+
5
+ const RENDER = /^render/
6
+
7
+ /**
8
+ * Keeps some of an entity's fields in storage, as a byproduct of the entity:
9
+ * the entity stays the one source of truth. When the entity is created, the
10
+ * fields come back from storage, before the type's own `create`, whose
11
+ * defaults (`entity.consent ??= null`) then keep them. After every handler,
12
+ * the fields are written back if they changed.
13
+ *
14
+ * Put it last in the type's array: it saves after the handlers before it.
15
+ * Storage that is missing, full or refusing, as in a private window, only
16
+ * means nothing is kept.
17
+ *
18
+ * A storage whose `getItem` returns a promise, such as Capacitor Preferences,
19
+ * restores the fields once it answers: the entity starts with the type's
20
+ * defaults, and `storageRestore` then brings back the fields no handler has
21
+ * changed in the meantime. Nothing is written until then. A type's own
22
+ * `storageRestore(entity, restored, api)` runs after.
23
+ *
24
+ * @param {string[]} fields The entity's fields to keep.
25
+ * @param {Object} [options]
26
+ * @param {string | ((entity: Object) => string)} [options.key] Where the
27
+ * fields are kept. Defaults to the entity's id.
28
+ * @param {() => Storage | undefined} [options.storage] A Web Storage, such as
29
+ * `() => sessionStorage` for the tab only, or anything with the same
30
+ * `getItem` and `setItem`, answering now or with a promise. Defaults to
31
+ * `localStorage`.
32
+ *
33
+ * @example
34
+ * const types = {
35
+ * Analytics: [createAnalytics({ adapter }), withStorage(["consent"])],
36
+ * Settings: [Settings, withStorage(["theme", "volume"], { key: "my-app" })],
37
+ * }
38
+ */
39
+ export function withStorage(
40
+ fields,
41
+ { key, storage = () => globalThis.localStorage } = {},
42
+ ) {
43
+ const keyOf = (entity) =>
44
+ typeof key === "function" ? key(entity) : (key ?? entity.id)
45
+
46
+ return (type) => {
47
+ /** What is kept for each entity, as written. */
48
+ const kept = new Map()
49
+ /** For entities still waiting on storage, their fields as created. */
50
+ const pending = new Map()
51
+
52
+ function save(entity) {
53
+ if (!isEntity(entity) || pending.has(entity.id)) return
54
+ const value = JSON.stringify(pick(entity, fields))
55
+ if (kept.get(entity.id) === value) return
56
+ kept.set(entity.id, value)
57
+ writeItem(keyOf(entity), value, storage)
58
+ }
59
+
60
+ const behavior = {}
61
+
62
+ for (const [name, handler] of Object.entries(type)) {
63
+ if (typeof handler !== "function" || name === "create") continue
64
+ if (RENDER.test(name)) continue
65
+ behavior[name] = function (entity, payload, api) {
66
+ const result = handler.call(this, entity, payload, api)
67
+ save(entity)
68
+ return result
69
+ }
70
+ }
71
+
72
+ behavior.create = function (entity, payload, api) {
73
+ const stored = readItem(keyOf(entity), storage)
74
+
75
+ if (isPromiseLike(stored)) {
76
+ const result = type.create?.call(this, entity, payload, api)
77
+ pending.set(entity.id, snapshot(entity, fields))
78
+ const { id } = entity
79
+ const restore = (value) =>
80
+ api.notify(`#${id}:storageRestore`, value ?? null)
81
+ stored.then(restore, () => restore(null))
82
+ return result
83
+ }
84
+
85
+ kept.set(entity.id, stored)
86
+ Object.assign(entity, pick(parseJSON(stored), fields))
87
+ const result = type.create?.call(this, entity, payload, api)
88
+ save(entity)
89
+ return result
90
+ }
91
+
92
+ behavior.storageRestore = function (entity, stored, api) {
93
+ const created = pending.get(entity.id)
94
+ if (!created) return
95
+ pending.delete(entity.id)
96
+ kept.set(entity.id, stored)
97
+
98
+ const restored = pick(parseJSON(stored), fields)
99
+ for (const [field, value] of Object.entries(restored)) {
100
+ if (JSON.stringify(entity[field]) === created[field]) {
101
+ entity[field] = value
102
+ }
103
+ }
104
+ type.storageRestore?.call(this, entity, restored, api)
105
+ save(entity)
106
+ }
107
+
108
+ return behavior
109
+ }
110
+ }
111
+
112
+ function snapshot(entity, fields) {
113
+ return Object.fromEntries(
114
+ fields.map((field) => [field, JSON.stringify(entity[field])]),
115
+ )
116
+ }
117
+
118
+ function isEntity(value) {
119
+ return Boolean(value) && typeof value === "object" && "id" in value
120
+ }
@@ -0,0 +1,32 @@
1
+ import type { KeyValueStorage } from "@inglorious/utils/storage"
2
+
3
+ import { Api } from "../api"
4
+ import { BaseEntity, EntityType } from "../store"
5
+
6
+ export type { KeyValueStorage }
7
+
8
+ export interface StorageOptions {
9
+ /** Where the fields are kept. Defaults to the entity's id. */
10
+ key?: string | ((entity: BaseEntity & { id: string }) => string)
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
17
+ }
18
+
19
+ /**
20
+ * Keeps some of an entity's fields in storage, as a byproduct of the entity,
21
+ * which stays the one source of truth: they come back when it is created,
22
+ * before the type's own `create`, and are written back after any handler that
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.
26
+ */
27
+ export declare function withStorage(
28
+ fields: string[],
29
+ options?: StorageOptions,
30
+ ): <TEntity extends BaseEntity, TApi extends Api>(
31
+ type: EntityType<TEntity, TApi>,
32
+ ) => EntityType<TEntity, TApi>