@inglorious/store 12.4.0 → 12.5.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,38 @@ 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
+
838
+ ---
839
+
808
840
  ## 🧩 Migrating from Redux Toolkit (RTK)
809
841
 
810
842
  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.5.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"
@@ -86,7 +90,7 @@
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,105 @@
1
+ const RENDER = /^render/
2
+
3
+ /**
4
+ * Keeps some of an entity's fields in storage, as a byproduct of the entity:
5
+ * the entity stays the one source of truth. When the entity is created, the
6
+ * fields come back from storage, before the type's own `create`, whose
7
+ * defaults (`entity.consent ??= null`) then keep them. After every handler,
8
+ * the fields are written back if they changed.
9
+ *
10
+ * Put it last in the type's array: it saves after the handlers before it.
11
+ * Storage that is missing, full or refusing, as in a private window, only
12
+ * means nothing is kept.
13
+ *
14
+ * @param {string[]} fields The entity's fields to keep.
15
+ * @param {Object} [options]
16
+ * @param {string | ((entity: Object) => string)} [options.key] Where the
17
+ * fields are kept. Defaults to the entity's id.
18
+ * @param {() => Storage | undefined} [options.storage] A Web Storage, such as
19
+ * `() => sessionStorage` for the tab only. Defaults to `localStorage`.
20
+ *
21
+ * @example
22
+ * const types = {
23
+ * Analytics: [createAnalytics({ adapter }), withStorage(["consent"])],
24
+ * Settings: [Settings, withStorage(["theme", "volume"], { key: "my-app" })],
25
+ * }
26
+ */
27
+ export function withStorage(
28
+ fields,
29
+ { key, storage = () => globalThis.localStorage } = {},
30
+ ) {
31
+ const keyOf = (entity) =>
32
+ typeof key === "function" ? key(entity) : (key ?? entity.id)
33
+
34
+ return (type) => {
35
+ /** What is kept for each entity, as written. */
36
+ const kept = new Map()
37
+
38
+ function save(entity) {
39
+ if (!isEntity(entity)) return
40
+ const value = JSON.stringify(pick(entity, fields))
41
+ if (kept.get(entity.id) === value) return
42
+ kept.set(entity.id, value)
43
+ write(storage, keyOf(entity), value)
44
+ }
45
+
46
+ const behavior = {}
47
+
48
+ for (const [name, handler] of Object.entries(type)) {
49
+ if (typeof handler !== "function" || name === "create") continue
50
+ if (RENDER.test(name)) continue
51
+ behavior[name] = function (entity, payload, api) {
52
+ const result = handler.call(this, entity, payload, api)
53
+ save(entity)
54
+ return result
55
+ }
56
+ }
57
+
58
+ behavior.create = function (entity, payload, api) {
59
+ const stored = read(storage, keyOf(entity))
60
+ kept.set(entity.id, stored)
61
+ Object.assign(entity, pick(parse(stored), fields))
62
+ const result = type.create?.call(this, entity, payload, api)
63
+ save(entity)
64
+ return result
65
+ }
66
+
67
+ return behavior
68
+ }
69
+ }
70
+
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
77
+ }
78
+
79
+ function isEntity(value) {
80
+ return Boolean(value) && typeof value === "object" && "id" in value
81
+ }
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
+ }
@@ -0,0 +1,22 @@
1
+ import { Api } from "../api"
2
+ import { BaseEntity, EntityType } from "../store"
3
+
4
+ export interface StorageOptions {
5
+ /** Where the fields are kept. Defaults to the entity's id. */
6
+ key?: string | ((entity: BaseEntity & { id: string }) => string)
7
+ /** A Web Storage, such as `() => sessionStorage`. Defaults to `localStorage`. */
8
+ storage?: () => Storage | undefined
9
+ }
10
+
11
+ /**
12
+ * Keeps some of an entity's fields in storage, as a byproduct of the entity,
13
+ * which stays the one source of truth: they come back when it is created,
14
+ * 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.
16
+ */
17
+ export declare function withStorage(
18
+ fields: string[],
19
+ options?: StorageOptions,
20
+ ): <TEntity extends BaseEntity, TApi extends Api>(
21
+ type: EntityType<TEntity, TApi>,
22
+ ) => EntityType<TEntity, TApi>