atomaric 0.0.87 → 0.1.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 +498 -8
- package/build/atomaric.js +282 -811
- package/build/atomaric.umd.cjs +1 -1
- package/package.json +5 -2
- package/types/do.classes.model/IObject.ts +2 -1
- package/types/index.d.ts +69 -6
package/README.md
CHANGED
|
@@ -1,29 +1,519 @@
|
|
|
1
|
-
|
|
1
|
+
# atomaric
|
|
2
|
+
|
|
3
|
+
Manage your project state. Lazy atoms, localStorage persistence, built-in actions, and subscription through `useSyncExternalStore`.
|
|
4
|
+
|
|
5
|
+
## 🕹️installation
|
|
2
6
|
|
|
3
7
|
```sh
|
|
4
|
-
npm install atomaric
|
|
8
|
+
npm install atomaric immer
|
|
5
9
|
```
|
|
6
10
|
|
|
7
|
-
|
|
11
|
+
Runtime dependencies per `package.json` are `typescript` only. The library never imports React or immer itself: you pass the `useSyncExternalStore` hook and immer's `produce` yourself through `configureAtomaric`, importing them from `'react'` and `'immer'` in your app. Requires React 18+.
|
|
12
|
+
|
|
13
|
+
## 🚀quick start
|
|
8
14
|
|
|
9
15
|
```tsx
|
|
10
|
-
import { atom, useAtom, configureAtomaric } from 'atomaric';
|
|
16
|
+
import { atom, useAtom, configureAtomaric, AtomaricLocalStorage } from 'atomaric';
|
|
11
17
|
import { useSyncExternalStore } from 'react';
|
|
18
|
+
import { produce } from 'immer';
|
|
12
19
|
|
|
13
|
-
configureAtomaric({
|
|
20
|
+
configureAtomaric({
|
|
21
|
+
useSyncExternalStore,
|
|
22
|
+
produce,
|
|
23
|
+
keyPathSeparator: '.',
|
|
24
|
+
storage: new AtomaricLocalStorage(),
|
|
25
|
+
});
|
|
14
26
|
|
|
15
27
|
const nameAtom = atom(
|
|
16
28
|
'World',
|
|
17
|
-
'greats:name',
|
|
29
|
+
'greats:name',
|
|
18
30
|
);
|
|
19
31
|
|
|
20
32
|
function App() {
|
|
21
|
-
const [name,
|
|
33
|
+
const [name, setName] = useAtom(nameAtom);
|
|
22
34
|
|
|
23
35
|
return (
|
|
24
|
-
<div onClick={() =>
|
|
36
|
+
<div onClick={() => setName(name === 'World' ? 'Man' : 'World')}>
|
|
25
37
|
Hello <span className="color-accent">{name}</span>
|
|
26
38
|
</div>
|
|
27
39
|
);
|
|
28
40
|
}
|
|
29
41
|
```
|
|
42
|
+
|
|
43
|
+
Call `configureAtomaric` before using any hook. The second argument of `atom()` is an optional localStorage key, and it must contain a colon. In the example, the value `'World'` is stored under the `greats:name` key and survives a page reload.
|
|
44
|
+
|
|
45
|
+
## 🧭configureatomaric
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
configureAtomaric({
|
|
49
|
+
useSyncExternalStore,
|
|
50
|
+
produce,
|
|
51
|
+
keyPathSeparator: '.',
|
|
52
|
+
storage: new AtomaricLocalStorage(),
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Configuration is mandatory before any hook usage, otherwise hooks throw `'call configureAtomaric() before all!'`.
|
|
57
|
+
|
|
58
|
+
- `useSyncExternalStore` is a required parameter; pass React's own hook.
|
|
59
|
+
- `produce` is a required parameter; pass immer's `produce`. It is what gives `do.update` its immer-style mutative drafting on arrays and objects. Before configuration the internal stub throws `'call configureAtomaric() before all!'`, the same as the React hook.
|
|
60
|
+
- `keyPathSeparator` is required in the types and sets the separator for `do.setDeepPartial` flat paths; `'.'` is the runtime default.
|
|
61
|
+
- `securifyKeyLevel` and `securifyValueLevel` are optional global security levels from `0` to `3`.
|
|
62
|
+
- `storage` is a required `AtomaricStorage` instance that persists atom values. Pass `new AtomaricLocalStorage()` for the default `localStorage`-backed storage or implement your own contract.
|
|
63
|
+
|
|
64
|
+
Creating atoms at module level is safe before configuration: an atom initializes lazily on the first access to any of its members.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const themeAtom = atom('light', 'app:theme');
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## 💾storage
|
|
71
|
+
|
|
72
|
+
`configureAtomaric` requires a `storage` parameter: an `AtomaricStorage` instance the library uses to persist atom values instead of accessing `localStorage` directly.
|
|
73
|
+
|
|
74
|
+
### AtomaricLocalStorage
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import { AtomaricLocalStorage, configureAtomaric } from 'atomaric';
|
|
78
|
+
|
|
79
|
+
configureAtomaric({
|
|
80
|
+
useSyncExternalStore,
|
|
81
|
+
produce,
|
|
82
|
+
keyPathSeparator: '.',
|
|
83
|
+
storage: new AtomaricLocalStorage(),
|
|
84
|
+
});
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`AtomaricLocalStorage` is the default implementation on top of `window.localStorage`. Its constructor accepts `{ listenStorageChanges?: boolean; unchangable?: boolean }`:
|
|
88
|
+
|
|
89
|
+
- `listenStorageChanges` defaults to `true`. With `true`, the storage listens to `localStorage` changes made in other tabs/windows, resets an atom when its key is removed there, and protects atoms when the `unchangable` option is enabled on the storage. With `false`, there is no cross-tab listening and no `unchangable` protection.
|
|
90
|
+
- `unchangable` defaults to `false`. With `true`, every atom using this storage is unchangable from outside: an atom restores its current stored value instead of applying an external change, and direct `localStorage.setItem`/`removeItem` calls for the keys of its atoms are blocked. The protection relies on `listenStorageChanges`; with `listenStorageChanges: false` it is inert.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const storage = new AtomaricLocalStorage({ listenStorageChanges: false });
|
|
94
|
+
const lockedStorage = new AtomaricLocalStorage({ unchangable: true });
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`localStorage` is accessed only when `AtomaricLocalStorage` is instantiated, so simply importing the library never touches it.
|
|
98
|
+
|
|
99
|
+
### unchangable
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
configureAtomaric({
|
|
103
|
+
useSyncExternalStore,
|
|
104
|
+
produce,
|
|
105
|
+
keyPathSeparator: '.',
|
|
106
|
+
storage: new AtomaricLocalStorage({ unchangable: true }),
|
|
107
|
+
});
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`unchangable` is a constructor option of `AtomaricLocalStorage`, not an atom option, and it defaults to `false`. With `true`, every atom using this storage is unchangable from outside:
|
|
111
|
+
|
|
112
|
+
- when an external change arrives (another tab/window or a script bypassing the storage), the atom restores its current stored value instead of applying the external one;
|
|
113
|
+
- direct `localStorage.setItem`/`removeItem` calls for the keys of these atoms are blocked.
|
|
114
|
+
|
|
115
|
+
The protection is coupled with `listenStorageChanges` (default `true`). With `listenStorageChanges: false` it is inert: there is no cross-tab listening and no blocking. Because the flag lives on the storage, it applies to all atoms that use that storage instance.
|
|
116
|
+
|
|
117
|
+
### custom storage
|
|
118
|
+
|
|
119
|
+
Implement `AtomaricStorage` to keep values somewhere else, for example in memory:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import type { AtomaricStorage, AtomaricStorageEvent } from 'atomaric';
|
|
123
|
+
|
|
124
|
+
type Listener = (event: AtomaricStorageEvent) => void;
|
|
125
|
+
|
|
126
|
+
const values = new Map<string, string>();
|
|
127
|
+
const listeners = new Map<string, Set<Listener>>();
|
|
128
|
+
|
|
129
|
+
const memoryStorage: AtomaricStorage = {
|
|
130
|
+
set: (key, value) => {
|
|
131
|
+
values.set(key, value);
|
|
132
|
+
},
|
|
133
|
+
get: key => values.get(key),
|
|
134
|
+
rem: key => {
|
|
135
|
+
values.delete(key);
|
|
136
|
+
},
|
|
137
|
+
has: key => values.has(key),
|
|
138
|
+
keys: () => Array.from(values.keys()),
|
|
139
|
+
listen: (key, listener) => {
|
|
140
|
+
const keyListeners = listeners.get(key) ?? new Set<Listener>();
|
|
141
|
+
listeners.set(key, keyListeners);
|
|
142
|
+
keyListeners.add(listener);
|
|
143
|
+
return () => {
|
|
144
|
+
keyListeners.delete(listener);
|
|
145
|
+
};
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
This in-memory storage has no external source of changes, so its listeners never fire; `protect` is omitted because the member is optional.
|
|
151
|
+
|
|
152
|
+
Contract members:
|
|
153
|
+
|
|
154
|
+
- `set(key, value)` saves a value by key and must overwrite an already existing value.
|
|
155
|
+
- `get(key)` reads a value by key and must return `undefined` when the key is absent.
|
|
156
|
+
- `rem(key)` removes a key and must do nothing when the key is absent.
|
|
157
|
+
- `has(key)` checks whether the key is present in storage.
|
|
158
|
+
- `keys()` lists every key currently present in storage.
|
|
159
|
+
- `listen(key, listener)` subscribes to key changes made from outside the storage instance (other tabs/windows or scripts bypassing its methods); the listener must NOT be invoked for changes made through the storage's own `set`/`rem`; returns an unsubscribe function.
|
|
160
|
+
- `protect?(key)` optionally forbids external modifications of a key (used when the storage `unchangable` option is enabled); same-tab `set`/`rem` attempts that bypass the storage methods must be silently ignored. Omit it when the storage cannot protect keys — atoms then lose that protection when `unchangable` is enabled.
|
|
161
|
+
|
|
162
|
+
The listener receives an `AtomaricStorageEvent` of the shape `{ newValue: string | null }`, where `newValue` is `null` when the key was removed.
|
|
163
|
+
|
|
164
|
+
## 🧩atom
|
|
165
|
+
|
|
166
|
+
Signature: `atom(value, storageKeyOrOptions?)`. The first argument is a raw value or a lazy initializer like `() => Value`, evaluated on the first access. The second argument is either a localStorage key string or an options object.
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
const lazyAtom = atom(() => expensiveComputation(), 'calc:result');
|
|
170
|
+
const plainAtom = atom(0);
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The storage key must contain a colon, for example `'app:theme'`. Values are stored in localStorage under the `atom\` prefix as JSON. A `Set` is stored as an array, a `Map` as an array of entries, and this is handled automatically.
|
|
174
|
+
|
|
175
|
+
## 🪝hooks
|
|
176
|
+
|
|
177
|
+
### useAtom
|
|
178
|
+
|
|
179
|
+
```tsx
|
|
180
|
+
const [count, setCount] = useAtom(countAtom);
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Returns the `[value, set]` pair, where `set` accepts a new value or an updater function like `prev => next`.
|
|
184
|
+
|
|
185
|
+
### useAtomValue
|
|
186
|
+
|
|
187
|
+
```tsx
|
|
188
|
+
const count = useAtomValue(countAtom);
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Returns the value only and re-renders the component when it changes.
|
|
192
|
+
|
|
193
|
+
### useAtomSet
|
|
194
|
+
|
|
195
|
+
```tsx
|
|
196
|
+
const setCount = useAtomSet(countAtom);
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Returns a stable setter, handy in callbacks and effects.
|
|
200
|
+
|
|
201
|
+
### useAtomSetDeferred
|
|
202
|
+
|
|
203
|
+
```tsx
|
|
204
|
+
const setSearch = useAtomSetDeferred(searchAtom);
|
|
205
|
+
setSearch('query', 300);
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Returns a debounced setter: the first call of a burst applies immediately, and the final value applies after `debounceMs` of silence. By default `debounceMs` is `500`. Signature: `(value | fn, debounceMs?, isPreventSave?, isInitInvoke?)`, where `isInitInvoke` controls the immediate first apply.
|
|
209
|
+
|
|
210
|
+
### useAtomGet
|
|
211
|
+
|
|
212
|
+
```tsx
|
|
213
|
+
const getCount = useAtomGet(countAtom);
|
|
214
|
+
const current = getCount();
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Reads the value without subscribing, so the component does not re-render.
|
|
218
|
+
|
|
219
|
+
### useAtomDo
|
|
220
|
+
|
|
221
|
+
```tsx
|
|
222
|
+
const countDo = useAtomDo(countAtom);
|
|
223
|
+
countDo.increment();
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Returns the atom's built-in and custom actions.
|
|
227
|
+
|
|
228
|
+
## 🧬atom instance members
|
|
229
|
+
|
|
230
|
+
All members are usable outside React.
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
const counterAtom = atom(0, 'counter:c');
|
|
234
|
+
|
|
235
|
+
counterAtom.get();
|
|
236
|
+
counterAtom.set(5);
|
|
237
|
+
counterAtom.set(prev => prev + 1);
|
|
238
|
+
counterAtom.setDeferred(10, 300);
|
|
239
|
+
counterAtom.reset();
|
|
240
|
+
counterAtom.subscribe(v => console.log(v));
|
|
241
|
+
counterAtom.isInitialValue();
|
|
242
|
+
counterAtom.do.increment();
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
`set` is batched: the first `set` in a tick notifies subscribers immediately with that moment's value, further `set` calls in the same tick do not notify again, and the localStorage write is deferred to a microtask that stores the last value. If the next value is identical to the current one by `===`, nothing happens — mutate objects through `do.*`. In `set(value, isPreventSave?)` the second argument skips the localStorage write for that call. `reset()` deletes the stored key and restores the initial value without saving. `subscribe` returns an unsubscribe function.
|
|
246
|
+
|
|
247
|
+
## 📦batching
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
const testAtom = atom('');
|
|
251
|
+
testAtom.set('1');
|
|
252
|
+
testAtom.set('2');
|
|
253
|
+
testAtom.set('3');
|
|
254
|
+
testAtom.set(prev => prev.repeat(2));
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
The first `set` of a tick notifies subscribers immediately with the value at that moment (`'1'`); further `set` calls of the same tick do not notify again, and the localStorage write is deferred to a microtask that stores the last value of the tick (`'3'`). React components still end up with the final value because `useSyncExternalStore` re-reads `get()` on re-render.
|
|
258
|
+
|
|
259
|
+
## ⚙️atom options
|
|
260
|
+
|
|
261
|
+
The second argument of `atom()` can be passed as an options object.
|
|
262
|
+
|
|
263
|
+
### storageKey
|
|
264
|
+
|
|
265
|
+
```ts
|
|
266
|
+
const themeAtom = atom('light', { storageKey: 'app:theme' });
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
The key used to persist the value; the string form is its shorthand.
|
|
270
|
+
|
|
271
|
+
### warnOnDuplicateStorageKey
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
const dupAtom = atom(0, { storageKey: 'dup:key', warnOnDuplicateStorageKey: false });
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
Defaults to `true` and warns in the console with `'Duplicate Atom key'`.
|
|
278
|
+
|
|
279
|
+
### zipValue / unzipValue
|
|
280
|
+
|
|
281
|
+
On save the library calls `zipValue`, wraps the result in a one-element array, and persists it with `JSON.stringify` under the prefixed key. On read it runs `JSON.parse` and passes `parsed[0]` to `unzipValue`. So the full chain is: value → `zipValue` → `JSON.stringify` → localStorage string → `JSON.parse` → `unzipValue` → value.
|
|
282
|
+
|
|
283
|
+
Because `JSON.stringify` is the final step, `zipValue` MUST return JSON-serializable data: plain objects, arrays, strings, numbers, booleans, and null. Values JSON cannot represent are silently mangled or throw:
|
|
284
|
+
|
|
285
|
+
- `Date` becomes an ISO string and is not revived automatically — you get a string back unless your `unzipValue` restores it.
|
|
286
|
+
- Class instances lose their prototype and methods; only own enumerable fields survive.
|
|
287
|
+
- `undefined`, functions, and symbols are dropped from objects and become `null` in arrays.
|
|
288
|
+
- `NaN` and `Infinity` become `null`.
|
|
289
|
+
- Cyclic structures throw.
|
|
290
|
+
- `Set`, `Map`, and typed arrays do not survive plain JSON at all and need explicit conversion.
|
|
291
|
+
|
|
292
|
+
Defaults are chosen by the runtime type of the initial value:
|
|
293
|
+
|
|
294
|
+
- Initial value is a `Set`: the default `zipValue` is `val => Array.from(val)` and the default `unzipValue` is `arr => new Set(arr)`.
|
|
295
|
+
- Initial value is a `Map`: the default `zipValue` converts it to an array of `[key, value]` entry pairs and the default `unzipValue` is `entries => new Map(entries)`.
|
|
296
|
+
- Anything else: both are identity (`val => val`), so the value is stored as-is.
|
|
297
|
+
|
|
298
|
+
The default `zipValue` checks the type of every value being saved and throws if the value is not an instance of the initial value's type — for example, setting a plain array into a `Set` atom throws. A `Set` holding `1` persists as `'[[1]]'`, and a `Map` persists as an array of pairs such as `'[[["a",1]]]'`.
|
|
299
|
+
|
|
300
|
+
```ts
|
|
301
|
+
const setAtom = atom(new Set<number>([1]), 'set:numbers');
|
|
302
|
+
const mapAtom = atom(new Map<string, number>(), 'map:scores');
|
|
303
|
+
const plainAtom = atom({ theme: 'dark' }, 'ui:settings');
|
|
304
|
+
|
|
305
|
+
setAtom.do.add(2);
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
`setAtom` persists as `[[1,2]]` and revives as a real `Set` automatically. `mapAtom` persists as an array of `[key, value]` pairs. `plainAtom` is stored as-is, because plain objects are already JSON-serializable.
|
|
309
|
+
|
|
310
|
+
Use a custom pair whenever the value contains `Date`, class instances, typed arrays, `NaN`/`Infinity`, `undefined`, functions, or anything cyclic. Plain objects, arrays, strings, numbers, booleans, and null need no conversion.
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
type Session = { user: string; lastSeen: Date };
|
|
314
|
+
|
|
315
|
+
const sessionAtom = atom<Session>({ user: 'ann', lastSeen: new Date(0) }, {
|
|
316
|
+
storageKey: 'session:data',
|
|
317
|
+
zipValue: value => ({ user: value.user, lastSeen: value.lastSeen.toISOString() }),
|
|
318
|
+
unzipValue: packed => ({ user: packed.user, lastSeen: new Date(packed.lastSeen) }),
|
|
319
|
+
});
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
Without the custom pair the `Date` would come back as an ISO string, not a `Date` instance.
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
class Money {
|
|
326
|
+
constructor(public cents: number) {}
|
|
327
|
+
format() {
|
|
328
|
+
return `$${(this.cents / 100).toFixed(2)}`;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const priceAtom = atom(new Money(1099), {
|
|
333
|
+
storageKey: 'shop:price',
|
|
334
|
+
zipValue: value => ({ cents: value.cents }),
|
|
335
|
+
unzipValue: packed => new Money(packed.cents),
|
|
336
|
+
});
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
`zipValue` flattens the instance to plain data and `unzipValue` rebuilds it with its prototype and methods. A plain `JSON.stringify` of a class instance keeps the fields but loses the prototype, so methods would be gone on the next load.
|
|
340
|
+
|
|
341
|
+
If the stored string is not valid JSON on read, the atom falls back to the initial value and logs a console warning.
|
|
342
|
+
|
|
343
|
+
### exp
|
|
344
|
+
|
|
345
|
+
```ts
|
|
346
|
+
const sessionAtom = atom('', {
|
|
347
|
+
storageKey: 'session:value',
|
|
348
|
+
exp: () => new Date(Date.now() + 2 * 1000),
|
|
349
|
+
});
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
Sets the value's lifetime. The value is stored as `[value, {"exp": <unixSeconds>}]`. When it expires, the atom resets and the key is removed.
|
|
353
|
+
|
|
354
|
+
### map
|
|
355
|
+
|
|
356
|
+
```ts
|
|
357
|
+
const filteredNumAtom = atom(0, {
|
|
358
|
+
do: () => ({}),
|
|
359
|
+
map: (val, prev) => (val >= 10 && val < 20 ? val : prev),
|
|
360
|
+
});
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
Transforms or validates every new value; return `prevValue` to reject the change.
|
|
364
|
+
|
|
365
|
+
### do
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
const counterAtom = atom(0, {
|
|
369
|
+
do: (set, get, self, setDeferred) => ({
|
|
370
|
+
incrementBy: (delta: number) => set(get() + delta),
|
|
371
|
+
}),
|
|
372
|
+
});
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
Declares custom actions. Details below.
|
|
376
|
+
|
|
377
|
+
## 🛠️do actions
|
|
378
|
+
|
|
379
|
+
Built-in actions are chosen automatically by the initial value's type.
|
|
380
|
+
|
|
381
|
+
### number
|
|
382
|
+
|
|
383
|
+
```ts
|
|
384
|
+
const counterAtom = atom(0);
|
|
385
|
+
counterAtom.do.increment();
|
|
386
|
+
counterAtom.do.increment(-3);
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
`increment(delta?)` adds `1` by default, and `increment(-3)` decrements by `3`.
|
|
390
|
+
|
|
391
|
+
### boolean
|
|
392
|
+
|
|
393
|
+
```ts
|
|
394
|
+
const isOpenAtom = atom(false);
|
|
395
|
+
isOpenAtom.do.toggle();
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
`toggle()` flips the value.
|
|
399
|
+
|
|
400
|
+
### array
|
|
401
|
+
|
|
402
|
+
```ts
|
|
403
|
+
const listAtom = atom<string[]>([]);
|
|
404
|
+
listAtom.do.push('a', 'b');
|
|
405
|
+
listAtom.do.unshift('z');
|
|
406
|
+
listAtom.do.update(list => {
|
|
407
|
+
list.reverse();
|
|
408
|
+
});
|
|
409
|
+
listAtom.do.filter();
|
|
410
|
+
listAtom.do.add('only-if-absent');
|
|
411
|
+
listAtom.do.removeFirst('a');
|
|
412
|
+
listAtom.do.toggle('b', true);
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
Available are `push`, `unshift`, `update(updater)` with immer-style mutations, plus `filter(filter?)` which drops falsy values by default, `add(value)` which only adds an absent value, `removeFirst(value)` and `toggle(value, isAddToStart?)`.
|
|
416
|
+
|
|
417
|
+
Immer keeps structural sharing: untouched branches keep reference identity.
|
|
418
|
+
|
|
419
|
+
```ts
|
|
420
|
+
const listAtom = atom([{ nums: [1, 2, 3] }, { nums: [4, 5] }]);
|
|
421
|
+
|
|
422
|
+
listAtom.do.update(list => {
|
|
423
|
+
list[0].nums.reverse();
|
|
424
|
+
});
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
### object
|
|
428
|
+
|
|
429
|
+
```ts
|
|
430
|
+
const userAtom = atom({ name: 'Ann', age: 20 });
|
|
431
|
+
userAtom.do.setPartial({ age: 21 });
|
|
432
|
+
userAtom.do.update(user => {
|
|
433
|
+
user.age += 1;
|
|
434
|
+
});
|
|
435
|
+
userAtom.do.setDeepPartial('name', 'Bob', { name: '' });
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
`setPartial(partial | fn)` performs a shallow merge, `update(updater)` works through immer, and `setDeepPartial` updates a nested path (deprecated).
|
|
439
|
+
|
|
440
|
+
Two immer behaviors matter for `update` on arrays and objects. Immer's default `produce` deep-freezes the state it returns, so after the first `do.update` mutating an atom's value in place throws in development; always change state through `do.*` or `set`. Values immer cannot draft, such as class instances without the `[immerable]` symbol, pass through the recipe as-is: mutating them inside the recipe mutates the base value in place, and `update` then applies nothing because the new value is reference-equal to the previous one.
|
|
441
|
+
|
|
442
|
+
### set
|
|
443
|
+
|
|
444
|
+
```ts
|
|
445
|
+
const tagsAtom = atom(new Set<string>());
|
|
446
|
+
tagsAtom.do.add('react');
|
|
447
|
+
tagsAtom.do.delete('react');
|
|
448
|
+
tagsAtom.do.toggle('typescript');
|
|
449
|
+
tagsAtom.do.clear();
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
All operations are immutable and create a new `Set`.
|
|
453
|
+
|
|
454
|
+
### map
|
|
455
|
+
|
|
456
|
+
```ts
|
|
457
|
+
const scoresAtom = atom(new Map<string, number>());
|
|
458
|
+
scoresAtom.do.setValue('ann', 10);
|
|
459
|
+
scoresAtom.do.setIfNo('bob', 5);
|
|
460
|
+
scoresAtom.do.delete('ann');
|
|
461
|
+
scoresAtom.do.toggle('bob', 7);
|
|
462
|
+
scoresAtom.do.clear();
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
Available are `setValue(key, value)`, `setIfNo(key, value)`, `delete(key)`, `toggle(key, value)` and `clear`, all immutable.
|
|
466
|
+
|
|
467
|
+
## 🧑💻custom do actions
|
|
468
|
+
|
|
469
|
+
```ts
|
|
470
|
+
const testAtom = atom(new Set<number>(), {
|
|
471
|
+
do: set => ({
|
|
472
|
+
add12num: () => set(prev => new Set(prev).add(12)),
|
|
473
|
+
}),
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
testAtom.do.add12num();
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
Custom actions receive `(set, get, self, setDeferred)` and use lazy getters, so they never go stale. Built-in actions take precedence over same-named custom ones. Custom actions can be combined with `storageKey` in the same options object.
|
|
480
|
+
|
|
481
|
+
```ts
|
|
482
|
+
const todoAtom = atom((): string[] => [], {
|
|
483
|
+
storageKey: 'todo:list',
|
|
484
|
+
do: (_set, _get, self) => ({
|
|
485
|
+
addTodo: (todo: string) => self.do.push(todo),
|
|
486
|
+
}),
|
|
487
|
+
});
|
|
488
|
+
```
|
|
489
|
+
|
|
490
|
+
## 🕳️setdeeppartial
|
|
491
|
+
|
|
492
|
+
```ts
|
|
493
|
+
const stateAtom = atom({ a: { b: [{ d: 8 }] } });
|
|
494
|
+
|
|
495
|
+
stateAtom.do.setDeepPartial('a.b.0.d', 123, { a: { b: [{}] } });
|
|
496
|
+
stateAtom.do.setDeepPartial('a+b+0+d', 123, null, '+');
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
Creates intermediate objects and arrays as needed, and numeric segments address array indices. `donor` is an optional typed template for TS inference; it may be `null`, but then an invalid path throws. The value may be an updater function. This action is deprecated; prefer `do.update` (immer) for nested changes or `do.setPartial` for shallow changes.
|
|
500
|
+
|
|
501
|
+
## 🔒security levels
|
|
502
|
+
|
|
503
|
+
`securifyKeyLevel` and `securifyValueLevel` accept values from `0` to `3` and are set per atom in options or globally in `configureAtomaric`. Level `1` is base64 of encoded JSON. Level `2` adds letter-case shuffling. Level `3` adds another base64 pass. Secured values are stored under the ``atom`s\`` prefix. Keys are auto-migrated between plain and secured forms on init. This is obfuscation, not cryptography.
|
|
504
|
+
|
|
505
|
+
```ts
|
|
506
|
+
const tokenAtom = atom('', {
|
|
507
|
+
storageKey: 'auth:token',
|
|
508
|
+
securifyKeyLevel: 2,
|
|
509
|
+
securifyValueLevel: 2,
|
|
510
|
+
});
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
## 🩺faq / gotchas
|
|
514
|
+
|
|
515
|
+
- A key requires a colon — this is enforced at the TypeScript type level.
|
|
516
|
+
- `set` compares by identity, so change objects through `do.update`.
|
|
517
|
+
- Saving a value equal to the initial one deletes the storage key.
|
|
518
|
+
- Invalid JSON in storage falls back to the initial value with a console warning.
|
|
519
|
+
- SSR is not supported: the library touches `window`, and `localStorage` is accessed only when `AtomaricLocalStorage` is instantiated, that is inside `configureAtomaric`, not at import time.
|