atomaric 0.0.76 → 0.0.77

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "atomaric",
3
3
  "description": "Manage your project state",
4
- "version": "0.0.76",
4
+ "version": "0.0.77",
5
5
  "type": "module",
6
6
  "main": "./build/atomaric.umd.cjs",
7
7
  "module": "./build/atomaric.js",
@@ -15,9 +15,7 @@
15
15
  },
16
16
  "files": [
17
17
  "build",
18
- "types",
19
- "src/do.classes",
20
- "src/makeDeepProxyObject"
18
+ "types"
21
19
  ],
22
20
  "keywords": [
23
21
  "react",
@@ -0,0 +1,24 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+
3
+ export interface IAtomArrayDoActions<Value> {
4
+ /** like the Array.prototype.push() method */
5
+ push: (...values: Value[]) => void;
6
+
7
+ /** like the Array.prototype.unshift() method */
8
+ unshift: (...values: Value[]) => void;
9
+
10
+ /** transform current taken value */
11
+ update: (updater: (value: Value[]) => void) => void;
12
+
13
+ /** like the Array.prototype.filter() method, but callback is optional - (it) => !!it */
14
+ filter: (filter?: (value: Value, index: number, Array: Value[]) => any) => void;
15
+
16
+ /** will add value if not exists */
17
+ add: (value: Value) => void;
18
+
19
+ /** will delete value from array */
20
+ removeFirst: (value: Value) => void;
21
+
22
+ /** will add value if it doesn't exist, otherwise delete */
23
+ toggle: (value: Value, isAddToStart?: boolean) => void;
24
+ }
@@ -0,0 +1,4 @@
1
+ export interface IAtomBooleanDoActions {
2
+ /** toggle current value between true/false */
3
+ toggle: () => void;
4
+ }
@@ -0,0 +1,22 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+
3
+ export interface IAtomMapDoActions<
4
+ MapValue extends Map<any, any>,
5
+ Key extends MapValue extends Map<infer K, any> ? K : never,
6
+ Value extends MapValue extends Map<any, infer V> ? V : never,
7
+ > {
8
+ /** like the Map.prototype.set() method, when value is new for key in current atom value */
9
+ setValue: (key: Key, value: Value) => void;
10
+
11
+ /** like the Map.prototype.set() method, when key is not exists */
12
+ setIfNo: (key: Key, value: Value) => void;
13
+
14
+ /** like the Map.prototype.delete() method */
15
+ delete: (key: Key) => void;
16
+
17
+ /** will add value if it doesn't exist, otherwise delete */
18
+ toggle: (key: Key, value: Value) => void;
19
+
20
+ /** like the Map.prototype.clear() method */
21
+ clear: () => void;
22
+ }
@@ -0,0 +1,6 @@
1
+ export interface IAtomNumberDoActions {
2
+ /** pass the 2 to increment on 2, pass the -2 to decrement on 2
3
+ * **default: 1**
4
+ */
5
+ increment: (delta?: number) => void;
6
+ }
@@ -0,0 +1,12 @@
1
+ import { ObjectActionsSetDeepPartialDoAction } from '..';
2
+
3
+ export interface IAtomObjectDoActions<Value extends object> {
4
+ /** pass partial object to update some field values */
5
+ setPartial: (value: Partial<Value> | ((value: Value) => Partial<Value>)) => void;
6
+
7
+ /** transform current taken value */
8
+ update: (updater: (value: Value) => void) => void;
9
+
10
+ /** pass partial value to update some deep values by flat path */
11
+ setDeepPartial: ObjectActionsSetDeepPartialDoAction<Value>;
12
+ }
@@ -0,0 +1,13 @@
1
+ export interface IAtomSetDoActions<Value> {
2
+ /** like the Set.prototype.add() method */
3
+ add: (value: Value) => void;
4
+
5
+ /** like the Set.prototype.delete() method */
6
+ delete: (value: Value) => void;
7
+
8
+ /** will add value if it doesn't exist, otherwise delete */
9
+ toggle: (value: Value) => void;
10
+
11
+ /** like the Set.prototype.clear() method */
12
+ clear: () => void;
13
+ }
package/types/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
2
  import { useSyncExternalStore } from 'react';
3
- import { AtomArrayDoActions } from '../src/do.classes/Array';
4
- import { AtomBooleanDoActions } from '../src/do.classes/Boolean';
5
- import { AtomMapDoActions } from '../src/do.classes/Map';
6
- import { AtomNumberDoActions } from '../src/do.classes/Number';
7
- import { AtomObjectDoActions } from '../src/do.classes/Object';
8
- import { AtomSetDoActions } from '../src/do.classes/Set';
3
+ import { IAtomArrayDoActions } from './do.classes.model/Array';
4
+ import { IAtomBooleanDoActions } from './do.classes.model/Boolean';
5
+ import { IAtomMapDoActions } from './do.classes.model/Map';
6
+ import { IAtomNumberDoActions } from './do.classes.model/Number';
7
+ import { IAtomObjectDoActions } from './do.classes.model/Object';
8
+ import { IAtomSetDoActions } from './do.classes.model/Set';
9
9
  import { Path, PathValue, PathValueDonor } from './paths';
10
10
 
11
11
  export type AtomSecureLevel = 0 | 1 | 2 | 3;
@@ -80,17 +80,17 @@ export type ObjectActionsSetDeepPartialDoAction<Value> = <
80
80
  ) => void;
81
81
 
82
82
  export type DefaultActions<Value> = Value extends Set<infer Val>
83
- ? AtomSetDoActions<Val>
83
+ ? IAtomSetDoActions<Val>
84
84
  : Value extends Map<infer Key, infer Val>
85
- ? AtomMapDoActions<Value, Key, Val>
85
+ ? IAtomMapDoActions<Value, Key, Val>
86
86
  : Value extends boolean
87
- ? AtomBooleanDoActions
87
+ ? IAtomBooleanDoActions
88
88
  : Value extends (infer Val)[]
89
- ? AtomArrayDoActions<Val>
89
+ ? IAtomArrayDoActions<Val>
90
90
  : Value extends number
91
- ? AtomNumberDoActions
91
+ ? IAtomNumberDoActions
92
92
  : Value extends object
93
- ? AtomObjectDoActions<Value>
93
+ ? IAtomObjectDoActions<Value>
94
94
  : object;
95
95
 
96
96
  declare class Atom<Value, Actions extends Record<string, AnyFunc> = Record<string, AnyFunc>> {
@@ -1,103 +0,0 @@
1
- import { useSyncExternalStore } from 'react';
2
- import { atom, configureAtomaric } from '../lib';
3
- import { wait } from '../utils';
4
-
5
- configureAtomaric({
6
- useSyncExternalStore,
7
- keyPathSeparator: '.',
8
- });
9
-
10
- describe('Array', () => {
11
- test('simple init', async () => {
12
- const initArray: number[] = [];
13
- const testAtom = atom(initArray);
14
- testAtom.set([]);
15
-
16
- expect(testAtom.get() !== initArray).toBeTruthy();
17
- });
18
-
19
- test('do actions', async () => {
20
- const testAtom = atom((): (number | nil | string | { nums: number[] })[] => [], {
21
- do: (_set, _get, self) => ({
22
- switch30(toggleValue: string) {
23
- self.do.toggle(30);
24
- self.do.toggle(toggleValue);
25
- },
26
- }),
27
- });
28
-
29
- testAtom.do.push(1, 2, 5, 2, 5, 5, 5, 5, 1, null, '', '#');
30
- await wait();
31
-
32
- expect(testAtom.get()).toEqual([1, 2, 5, 2, 5, 5, 5, 5, 1, null, '', '#']);
33
-
34
- testAtom.do.add(0);
35
- testAtom.do.add(5);
36
- testAtom.do.add(8);
37
- await wait();
38
-
39
- expect(testAtom.get()).toEqual([1, 2, 5, 2, 5, 5, 5, 5, 1, null, '', '#', 0, 8]);
40
-
41
- testAtom.do.removeFirst(5);
42
- await wait();
43
-
44
- expect(testAtom.get()).toEqual([1, 2, 2, 5, 5, 5, 5, 1, null, '', '#', 0, 8]);
45
-
46
- testAtom.do.toggle('+');
47
- await wait();
48
-
49
- expect(testAtom.get()).toEqual([1, 2, 2, 5, 5, 5, 5, 1, null, '', '#', 0, 8, '+']);
50
-
51
- testAtom.do.toggle('+');
52
- await wait();
53
-
54
- expect(testAtom.get()).toEqual([1, 2, 2, 5, 5, 5, 5, 1, null, '', '#', 0, 8]);
55
-
56
- testAtom.do.switch30('@');
57
- await wait();
58
-
59
- expect(testAtom.get()).toEqual([1, 2, 2, 5, 5, 5, 5, 1, null, '', '#', 0, 8, 30, '@']);
60
-
61
- testAtom.do.unshift('**');
62
- await wait();
63
-
64
- expect(testAtom.get()).toEqual(['**', 1, 2, 2, 5, 5, 5, 5, 1, null, '', '#', 0, 8, 30, '@']);
65
-
66
- testAtom.do.filter();
67
- await wait();
68
-
69
- expect(testAtom.get()).toEqual(['**', 1, 2, 2, 5, 5, 5, 5, 1, '#', 8, 30, '@']);
70
-
71
- testAtom.do.filter(val => typeof val === 'string');
72
- await wait();
73
-
74
- expect(testAtom.get()).toEqual(['**', '#', '@']);
75
-
76
- testAtom.do.update(val => val.reverse());
77
- await wait();
78
-
79
- expect(testAtom.get()).toEqual(['@', '#', '**']);
80
-
81
- const nums555 = { nums: [5, 5, 5] };
82
- const nums123 = { nums: [1, 2, 3] };
83
-
84
- testAtom.do.add(nums123);
85
- testAtom.do.add(nums555);
86
- await wait();
87
-
88
- expect(testAtom.get()).toEqual(['@', '#', '**', nums123, nums555]);
89
-
90
- testAtom.do.update(val => {
91
- if (val[3] && typeof val[3] === 'object' && 'nums' in val[3]) val[3].nums.reverse();
92
- });
93
- await wait();
94
-
95
- expect(testAtom.get()).toEqual(['@', '#', '**', { nums: [3, 2, 1] }, nums555]);
96
-
97
- expect(testAtom.get()[4] === nums555).toBeTruthy();
98
- expect(testAtom.get()[3] !== nums123).toBeTruthy();
99
-
100
- const value = testAtom.get();
101
- expect(value[3] && typeof value[3] === 'object' && value[3].nums !== nums123.nums).toBeTruthy();
102
- });
103
- });
@@ -1,66 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
- import { Atom } from '../../types';
3
- import { AtomUpdateDoAction } from './_Update';
4
-
5
- export class AtomArrayDoActions<Value> extends AtomUpdateDoAction {
6
- constructor(private a: Atom<Value[]>, actions: Record<string, AnyFunc> | nil) {
7
- super(actions);
8
- }
9
-
10
- /** like the Array.prototype.push() method */
11
- push = (...values: Value[]) => {
12
- if (values.length === 0) return;
13
- this.a.set(this.a.get().concat(values));
14
- };
15
-
16
- /** like the Array.prototype.unshift() method */
17
- unshift = (...values: Value[]) => {
18
- if (values.length === 0) return;
19
- this.a.set(values.concat(this.a.get()));
20
- };
21
-
22
- /** transform current taken value */
23
- update = (updater: (value: Value[]) => void) => {
24
- const prev = this.a.get();
25
- const newValue = this.updateValue(prev, updater);
26
- if (newValue === prev) return;
27
- this.a.set(newValue);
28
- };
29
-
30
- /** like the Array.prototype.filter() method, but callback is optional - (it) => !!it */
31
- filter = (filter?: (value: Value, index: number, Array: Value[]) => any) => {
32
- const filtered = this.a.get().filter(filter ?? itIt);
33
- if (filtered.length === this.a.get().length) return;
34
- this.a.set(filtered);
35
- };
36
-
37
- /** will add value if not exists */
38
- add = (value: Value) => {
39
- if (this.a.get().includes(value)) return;
40
- this.a.set(this.a.get().concat([value]));
41
- };
42
-
43
- /** will delete value from array */
44
- removeFirst = (value: Value) => {
45
- const index = this.a.get().indexOf(value);
46
- if (index < 0) return;
47
- const newArray = this.a.get().slice(0);
48
- newArray.splice(index, 1);
49
- this.a.set(newArray);
50
- };
51
-
52
- /** will add value if it doesn't exist, otherwise delete */
53
- toggle = (value: Value, isAddToStart?: boolean) => {
54
- const newArray = this.a.get().slice();
55
- const index = newArray.indexOf(value);
56
-
57
- if (index < 0) {
58
- if (isAddToStart) newArray.unshift(value);
59
- else newArray.push(value);
60
- } else newArray.splice(index, 1);
61
-
62
- this.a.set(newArray);
63
- };
64
- }
65
-
66
- const itIt = <It>(it: It) => it;
@@ -1,27 +0,0 @@
1
- import { useSyncExternalStore } from 'react';
2
- import { atom, configureAtomaric } from '../lib';
3
- import { wait } from '../utils';
4
-
5
- configureAtomaric({
6
- useSyncExternalStore,
7
- keyPathSeparator: '.',
8
- });
9
-
10
- describe('Boolean', () => {
11
- test('do actions', async () => {
12
- const testAtom = atom(false, {
13
- do: (set, get) => ({
14
- switch(news?: boolean) {
15
- set(news ?? !get());
16
- },
17
- }),
18
- });
19
-
20
- testAtom.do.switch(true);
21
- testAtom.do.switch();
22
- testAtom.do.toggle();
23
- await wait();
24
-
25
- expect(testAtom.get() === true).toBeTruthy();
26
- });
27
- });
@@ -1,13 +0,0 @@
1
- import { Atom } from '../../types';
2
- import { AtomDoActionsBasic } from './_Basic';
3
-
4
- export class AtomBooleanDoActions extends AtomDoActionsBasic {
5
- constructor(private a: Atom<boolean>, actions: Record<string, AnyFunc> | nil) {
6
- super(actions);
7
- }
8
-
9
- /** toggle current value between true/false */
10
- toggle = () => {
11
- this.a.set(!this.a.get());
12
- };
13
- }
@@ -1,77 +0,0 @@
1
- import { useSyncExternalStore } from 'react';
2
- import { atom, configureAtomaric } from '../lib';
3
- import { makeFullKey, wait } from '../utils';
4
-
5
- configureAtomaric({
6
- useSyncExternalStore,
7
- keyPathSeparator: '.',
8
- });
9
-
10
- describe('Map', () => {
11
- type Value = number | { asasa: '' };
12
- const testAtom = atom(new Map<string, Value>(), {
13
- storeKey: 'map:test',
14
- do: (set, get) => ({
15
- filterKeyValues: () => {
16
- const newMap = new Map();
17
- get().forEach((value, key) => {
18
- if (value) newMap.set(key, value);
19
- });
20
- set(newMap);
21
- },
22
- }),
23
- });
24
-
25
- test('do.setValue()', async () => {
26
- testAtom.do.setValue('!', 1);
27
- testAtom.do.setValue('@', 0);
28
- testAtom.do.setValue('#', { asasa: '' });
29
- testAtom.do.setValue('', 123);
30
- await wait();
31
-
32
- expect(localStorage[makeFullKey('map:test')]).toEqual('[[["!",1],["@",0],["#",{"asasa":""}],["",123]]]');
33
-
34
- expect(testAtom.get()).toEqual(
35
- new Map<string, Value>([
36
- ['!', 1],
37
- ['@', 0],
38
- ['#', { asasa: '' }],
39
- ['', 123],
40
- ]),
41
- );
42
- });
43
-
44
- test('do.<filterKeyValues>()', async () => {
45
- testAtom.do.filterKeyValues();
46
- await wait();
47
-
48
- expect(localStorage[makeFullKey('map:test')]).toEqual('[[["!",1],["#",{"asasa":""}],["",123]]]');
49
- });
50
-
51
- test('do.delete()', async () => {
52
- testAtom.do.delete('#');
53
- await wait();
54
-
55
- expect(localStorage[makeFullKey('map:test')]).toEqual('[[["!",1],["",123]]]');
56
- });
57
-
58
- test('do.toggle()', async () => {
59
- testAtom.do.toggle('#', 555);
60
- await wait();
61
-
62
- expect(localStorage[makeFullKey('map:test')]).toEqual('[[["!",1],["",123],["#",555]]]');
63
-
64
- testAtom.do.toggle('', 999);
65
- testAtom.do.toggle('!', 1234567890);
66
- await wait();
67
-
68
- expect(localStorage[makeFullKey('map:test')]).toEqual('[[["#",555]]]');
69
- });
70
-
71
- test('do.clear()', async () => {
72
- testAtom.do.clear();
73
- await wait();
74
-
75
- expect(localStorage[makeFullKey('map:test')]).toEqual('[[]]');
76
- });
77
- });
@@ -1,59 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
- import { Atom } from '../../types';
3
- import { AtomDoActionsBasic } from './_Basic';
4
-
5
- export class AtomMapDoActions<
6
- MapValue extends Map<any, any>,
7
- Key extends MapValue extends Map<infer K, any> ? K : never,
8
- Value extends MapValue extends Map<any, infer V> ? V : never,
9
- > extends AtomDoActionsBasic {
10
- constructor(private a: Atom<MapValue>, actions: Record<string, AnyFunc> | nil) {
11
- super(actions);
12
- this.a = a;
13
- }
14
-
15
- /** like the Map.prototype.set() method, when value is new for key in current atom value */
16
- setValue = (key: Key, value: Value) => {
17
- if (this.a.get().get(key) === value) return;
18
-
19
- const newMap = new Map(this.a.get());
20
- newMap.set(key, value);
21
-
22
- this.a.set(newMap as never);
23
- };
24
-
25
- /** like the Map.prototype.set() method, when key is not exists */
26
- setIfNo = (key: Key, value: Value) => {
27
- if (this.a.get().has(key)) return;
28
-
29
- const newMap = new Map(this.a.get());
30
- newMap.set(key, value);
31
-
32
- this.a.set(newMap as never);
33
- };
34
-
35
- /** like the Map.prototype.delete() method */
36
- delete = (key: Key) => {
37
- if (!this.a.get().has(key)) return;
38
-
39
- const newMap = new Map(this.a.get());
40
- newMap.delete(key);
41
-
42
- this.a.set(newMap as never);
43
- };
44
-
45
- /** will add value if it doesn't exist, otherwise delete */
46
- toggle = (key: Key, value: Value) => {
47
- const newMap = new Map(this.a.get());
48
-
49
- if (newMap.has(key)) newMap.delete(key);
50
- else newMap.set(key, value);
51
-
52
- this.a.set(newMap as never);
53
- };
54
-
55
- /** like the Map.prototype.clear() method */
56
- clear = () => {
57
- this.a.set(new Map() as never);
58
- };
59
- }
@@ -1,25 +0,0 @@
1
- import { useSyncExternalStore } from 'react';
2
- import { atom, configureAtomaric } from '../lib';
3
- import { wait } from '../utils';
4
-
5
- configureAtomaric({
6
- useSyncExternalStore,
7
- keyPathSeparator: '.',
8
- });
9
-
10
- describe('Number', () => {
11
- test('do actions', async () => {
12
- const testAtom = atom(100, { do: (set, get) => ({ switchSign: () => set(-get()) }) });
13
- const testFuncAtom = atom(() => 200, { do: (set, get) => ({ switchSign: () => set(-get()) }) });
14
-
15
- testAtom.do.increment();
16
- testAtom.do.switchSign();
17
-
18
- testFuncAtom.do.increment(-3);
19
- testFuncAtom.do.switchSign();
20
- await wait();
21
-
22
- expect(testAtom.get()).toEqual(-101);
23
- expect(testFuncAtom.get()).toEqual(-197);
24
- });
25
- });
@@ -1,15 +0,0 @@
1
- import { Atom } from '../../types';
2
- import { AtomDoActionsBasic } from './_Basic';
3
-
4
- export class AtomNumberDoActions extends AtomDoActionsBasic {
5
- constructor(private a: Atom<number>, actions: Record<string, AnyFunc> | nil) {
6
- super(actions);
7
- }
8
-
9
- /** pass the 2 to increment on 2, pass the -2 to decrement on 2
10
- * **default: 1**
11
- */
12
- increment = (delta?: number) => {
13
- this.a.set(+this.a.get() + (delta ?? 1));
14
- };
15
- }
@@ -1,67 +0,0 @@
1
- import { useSyncExternalStore } from 'react';
2
- import { atom, configureAtomaric } from '../lib';
3
- import { wait } from '../utils';
4
-
5
- configureAtomaric({
6
- useSyncExternalStore,
7
- keyPathSeparator: '.',
8
- });
9
-
10
- describe('Object', () => {
11
- test('do.setDeepPartial()', async () => {
12
- const b = { c: [{ d: 8, e: 'e', f: 'F', g: { h: 'HHH' } }] };
13
- const a = { f: { g: '' }, b };
14
- const testAtom = atom({ a, b });
15
-
16
- testAtom.do.setDeepPartial('b.c.0.d', 123, { b: { c: [{}] } });
17
-
18
- await wait();
19
-
20
- expect(testAtom.get().b).not.toEqual(b);
21
- expect(testAtom.get().b.c[0].d).toEqual(123);
22
- expect(testAtom.get().b.c).not.toEqual(b.c);
23
- expect(testAtom.get().a).toEqual(a);
24
-
25
- testAtom.do.setDeepPartial('b+c+8+e', 'EE', null, '+');
26
-
27
- await wait();
28
-
29
- expect(testAtom.get().b.c[8].e).toEqual('EE');
30
- });
31
-
32
- test('do.setDeepPartial() with first numeric prop', async () => {
33
- enum Num {
34
- num = 123,
35
- }
36
- const testAtom = atom({ [Num.num]: { a: 'A' } });
37
-
38
- testAtom.do.setDeepPartial(`${Num.num}.a`, 'AA', { [Num.num]: {} });
39
-
40
- await wait();
41
-
42
- expect(testAtom.get()[Num.num].a).toEqual('AA');
43
- });
44
-
45
- test('do.setPartial()', async () => {
46
- const testAtom = atom((): Record<number, unknown> => ({ 2: { a: 'A' } }));
47
-
48
- testAtom.do.setPartial({ 3: { b: 'B' } });
49
- testAtom.do.setPartial({ 4: [] });
50
- await wait();
51
-
52
- expect(testAtom.get()).toEqual({ 2: { a: 'A' }, 3: { b: 'B' }, 4: [] });
53
- });
54
-
55
- test('do.update()', async () => {
56
- const init = { a: { b: { c: { d: { e: 'E' } }, f: { g: {} } }, h: { i: { j: {} } } } };
57
- const testAtom = atom(init);
58
-
59
- testAtom.do.update(obj => (obj.a.b.c.d.e = 'eE'));
60
-
61
- await wait();
62
-
63
- expect(testAtom.get().a.b.c.d.e).toEqual('eE');
64
- expect(testAtom.get().a.b.c).not.toEqual(init.a.b.c);
65
- expect(testAtom.get().a.h.i).toEqual(init.a.h.i);
66
- });
67
- });
@@ -1,75 +0,0 @@
1
- import { Atom, ObjectActionsSetDeepPartialDoAction } from '../../types';
2
- import { configuredOptions } from '../lib';
3
- import { AtomUpdateDoAction } from './_Update';
4
-
5
- export class AtomObjectDoActions<Value extends object> extends AtomUpdateDoAction {
6
- constructor(private a: Atom<Value>, actions: Record<string, AnyFunc> | nil) {
7
- super(actions);
8
- }
9
-
10
- /** pass partial object to update some field values */
11
- setPartial = (value: Partial<Value> | ((value: Value) => Partial<Value>)) =>
12
- this.a.set(prev => ({
13
- ...prev,
14
- ...(typeof value === 'function' ? value(this.a.get()) : value),
15
- }));
16
-
17
- /** transform current taken value */
18
- update = (updater: (value: Value) => void) => {
19
- const prev = this.a.get();
20
- const newValue = this.updateValue(prev, updater);
21
- if (newValue === prev) return;
22
- this.a.set(newValue);
23
- };
24
-
25
- /** pass partial value to update some deep values by flat path */
26
- setDeepPartial: ObjectActionsSetDeepPartialDoAction<Value> = (
27
- path,
28
- value,
29
- donor,
30
- separator = (configuredOptions.keyPathSeparator || '.') as never,
31
- ) => {
32
- if (!separator) return;
33
-
34
- if (path.includes(separator)) {
35
- let keys = path.split(separator);
36
- const lastKey = keys[keys.length - 1];
37
- keys = keys.slice(0, -1);
38
- const newObject = { ...this.a.get() };
39
- let lastObject = newObject as Record<string, unknown>;
40
- let lastDonorObject = donor as Record<string, unknown> | nil;
41
-
42
- for (const key of keys) {
43
- lastDonorObject = lastDonorObject?.[Array.isArray(lastDonorObject) ? '0' : key] as never;
44
- const currentObject = lastObject[makeKey(lastObject, key)] ?? (Array.isArray(lastDonorObject) ? [] : {});
45
-
46
- if (currentObject == null || typeof currentObject !== 'object') {
47
- if (donor == null) throw 'Incorrect path for setDeepPartial';
48
-
49
- const newValue = typeof value === 'function' ? (value as (val: undefined) => Value)(undefined) : value;
50
-
51
- if (this.a.get()[path as never] !== newValue) this.setPartial({ [path]: newValue } as never);
52
- return;
53
- }
54
-
55
- lastObject = lastObject[makeKey(lastObject, key)] = (
56
- Array.isArray(currentObject) ? [...currentObject] : { ...currentObject }
57
- ) as never;
58
- }
59
-
60
- const prev = lastObject[lastKey];
61
- lastObject[lastKey] =
62
- typeof value === 'function' ? (value as (val: unknown) => Value)(lastObject[lastKey]) : value;
63
-
64
- if (prev !== lastObject[lastKey]) this.a.set(newObject);
65
-
66
- return;
67
- }
68
-
69
- const prevValue = this.a.get()[path as never];
70
- const newValue = typeof value === 'function' ? (value as (val: Value) => Value)(prevValue) : value;
71
- if (newValue !== prevValue) this.setPartial({ [path]: newValue } as never);
72
- };
73
- }
74
-
75
- const makeKey = (obj: object, key: string) => (Array.isArray(obj) ? `${+key}` : key);
@@ -1,46 +0,0 @@
1
- import { useSyncExternalStore } from 'react';
2
- import { atom, configureAtomaric } from '../lib';
3
- import { makeFullKey, wait } from '../utils';
4
-
5
- configureAtomaric({
6
- useSyncExternalStore,
7
- keyPathSeparator: '.',
8
- });
9
-
10
- describe('Set', () => {
11
- test('do actions', async () => {
12
- const testAtom = atom(new Set<string>(), {
13
- storeKey: 'set:test',
14
- do: (set, get) => ({
15
- filterValues: () => {
16
- const array = Array.from(get());
17
- set(new Set(array.filter(it => it)));
18
- },
19
- }),
20
- });
21
-
22
- testAtom.do.add('!');
23
- testAtom.do.add('@');
24
- testAtom.do.add('#');
25
- testAtom.do.add('');
26
- await wait();
27
-
28
- expect(localStorage[makeFullKey('set:test')]).toEqual('[["!","@","#",""]]');
29
-
30
- testAtom.do.filterValues();
31
- await wait();
32
-
33
- expect(localStorage[makeFullKey('set:test')]).toEqual('[["!","@","#"]]');
34
-
35
- testAtom.do.toggle('@');
36
- await wait();
37
-
38
- expect(localStorage[makeFullKey('set:test')]).toEqual('[["!","#"]]');
39
-
40
- testAtom.do.toggle('@');
41
- testAtom.do.delete('!');
42
- await wait();
43
-
44
- expect(localStorage[makeFullKey('set:test')]).toEqual('[["#","@"]]');
45
- });
46
- });
@@ -1,40 +0,0 @@
1
- import { Atom } from '../../types';
2
- import { AtomDoActionsBasic } from './_Basic';
3
-
4
- export class AtomSetDoActions<Value> extends AtomDoActionsBasic {
5
- constructor(private a: Atom<Set<Value>>, actions: Record<string, AnyFunc> | nil) {
6
- super(actions);
7
- this.a = a;
8
- }
9
-
10
- /** like the Set.prototype.add() method */
11
- add = (value: Value) => {
12
- if (this.a.get().has(value)) return;
13
-
14
- this.a.set(new Set(this.a.get()).add(value));
15
- };
16
-
17
- /** like the Set.prototype.delete() method */
18
- delete = (value: Value) => {
19
- if (!this.a.get().has(value)) return;
20
-
21
- const newSet = new Set(this.a.get());
22
- newSet.delete(value);
23
- this.a.set(newSet);
24
- };
25
-
26
- /** will add value if it doesn't exist, otherwise delete */
27
- toggle = (value: Value) => {
28
- const newSet = new Set(this.a.get());
29
-
30
- if (newSet.has(value)) newSet.delete(value);
31
- else newSet.add(value);
32
-
33
- this.a.set(newSet);
34
- };
35
-
36
- /** like the Set.prototype.clear() method */
37
- clear = () => {
38
- this.a.set(new Set());
39
- };
40
- }
@@ -1,11 +0,0 @@
1
- export class AtomDoActionsBasic {
2
- constructor(actions: Record<string, AnyFunc> | nil) {
3
- if (actions)
4
- return new Proxy(this, {
5
- get: (self, p) => {
6
- if (p in this) return self[p as never];
7
- return actions[p as never];
8
- },
9
- });
10
- }
11
- }
@@ -1,37 +0,0 @@
1
- import { makeDeepProxyObject } from '../makeDeepProxyObject';
2
- import { AtomDoActionsBasic } from './_Basic';
3
-
4
- export class AtomUpdateDoAction extends AtomDoActionsBasic {
5
- protected updateValue = <Object extends object | unknown[]>(
6
- object: Object,
7
- updater: (object: Object) => void,
8
- ): Object => {
9
- const newObject = Array.isArray(object) ? object.slice(0) : { ...object };
10
- let isSomeSetted = false;
11
-
12
- const pro = makeDeepProxyObject(object, {
13
- onSet: (_, keys, setKey, value, prevValue) => {
14
- if (value === prevValue) return true;
15
- let currentObject = newObject as Record<string, unknown> | unknown[];
16
-
17
- isSomeSetted = true;
18
-
19
- for (const key of keys) {
20
- const nextObject = currentObject[key as never] as object;
21
-
22
- currentObject = currentObject[key as never] = (
23
- Array.isArray(nextObject) ? nextObject.slice() : { ...nextObject }
24
- ) as never;
25
- }
26
-
27
- currentObject[setKey as never] = value as never;
28
-
29
- return true;
30
- },
31
- });
32
-
33
- updater(pro);
34
-
35
- return isSomeSetted ? (newObject as never) : object;
36
- };
37
- }