@solid-primitives/deep 0.1.0 → 0.2.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
@@ -9,10 +9,11 @@
9
9
  [![version](https://img.shields.io/npm/v/@solid-primitives/deep?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/deep)
10
10
  [![stage](https://img.shields.io/endpoint?style=for-the-badge&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-1.json)](https://github.com/solidjs-community/solid-primitives#contribution-process)
11
11
 
12
- Primitives for tracking changes in stores.
12
+ Primitives for tracking and observing nested reactive objects in Solid.
13
13
 
14
14
  - [`trackDeep`](#trackDeep) - Tracks all properties of a store by iterating over them recursively.
15
15
  - [`trackStore`](#trackStore) - A more performant alternative to `trackDeep` utilizing specific store implementations.
16
+ - [`captureStoreUpdates`](#captureStoreUpdates) - A utility function that captures all updates to a store and returns them as an array.
16
17
 
17
18
  ## Installation
18
19
 
@@ -39,7 +40,7 @@ You can call this function with any store under a tracking scope and it will ite
39
40
  ```ts
40
41
  import { trackDeep } from "@solid-primitives/deep";
41
42
 
42
- const [state, setState] = createSignal({ name: "John", age: 42 });
43
+ const [state, setState] = createStore({ name: "John", age: 42 });
43
44
 
44
45
  createEffect(() => {
45
46
  trackDeep(state);
@@ -90,7 +91,7 @@ It can be used in almost the same way as `trackDeep`, the only difference is tha
90
91
  ```ts
91
92
  import { trackStore } from "@solid-primitives/deep";
92
93
 
93
- const [state, setState] = createSignal({ name: "John", age: 42 });
94
+ const [state, setState] = createStore({ name: "John", age: 42 });
94
95
 
95
96
  createEffect(() => {
96
97
  trackStore(state);
@@ -98,6 +99,64 @@ createEffect(() => {
98
99
  });
99
100
  ```
100
101
 
102
+ ## `captureStoreUpdates`
103
+
104
+ Creates a function for tracking and capturing updates to a store.
105
+
106
+ It could be useful for implementing [undo/redo functionality](https://primitives.solidjs.community/package/history) or for turning a store into a immutable stream of updates.
107
+
108
+ ### How to use it
109
+
110
+ Each execution of the returned function will return an array of updates to the store since the last execution.
111
+
112
+ ```ts
113
+ const [state, setState] = createStore({ todos: [] });
114
+
115
+ const getDelta = captureStoreUpdates(state);
116
+
117
+ getDelta(); // [{ path: [], value: { todos: [] } }]
118
+
119
+ setState("todos", ["foo"]);
120
+
121
+ getDelta(); // [{ path: ["todos"], value: ["foo"] }]
122
+ ```
123
+
124
+ The returned function will track all updates to a store (just like [`trackStore`](#trackStore)), so it can be used inside a tracking scope.
125
+
126
+ ```ts
127
+ const [state, setState] = createStore({ todos: [] });
128
+
129
+ const getDelta = captureStoreUpdates(state);
130
+
131
+ createEffect(() => {
132
+ const delta = getDelta();
133
+ /* execute some logic whenever the state changes */
134
+ console.log(delta);
135
+ });
136
+ ```
137
+
138
+ The returned function is not a signal - it won't get updated by itself, it has to be called manually, or under a tracking scope to capture new updates.
139
+
140
+ But it can be turned into a signal by using `createMemo`:
141
+
142
+ ```ts
143
+ const [state, setState] = createStore({ todos: [] });
144
+
145
+ const delta = createMemo(captureStoreUpdates(state));
146
+
147
+ // both of these effects will receive the same delta
148
+ createEffect(() => {
149
+ console.log(delta());
150
+ });
151
+ createEffect(() => {
152
+ console.log(delta());
153
+ });
154
+ ```
155
+
156
+ ### Demo
157
+
158
+ See a demo of this primitive in action [here](https://primitives.solidjs.community/playground/deep).
159
+
101
160
  ## Changelog
102
161
 
103
162
  See [CHANGELOG.md](./CHANGELOG.md)
package/dist/index.cjs CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  var solidJs = require('solid-js');
4
4
  var store = require('solid-js/store');
5
+ var memo = require('@solid-primitives/memo');
6
+ var web = require('solid-js/web');
5
7
 
6
8
  // src/track-deep.ts
7
9
  function trackDeep(store) {
@@ -36,21 +38,21 @@ function createLazyMemo(calc) {
36
38
  isReading = false;
37
39
  };
38
40
  }
39
- function getTrackStoreNode(value) {
40
- let track = TrackStoreCache.get(value);
41
+ function getTrackStoreNode(node) {
42
+ let track = TrackStoreCache.get(node);
41
43
  if (!track) {
42
44
  solidJs.createRoot(() => {
43
- const unwrapped = store.unwrap(value);
45
+ const unwrapped = store.unwrap(node);
44
46
  track = createLazyMemo(() => {
45
- value[solidJs.$TRACK];
47
+ node[solidJs.$TRACK];
46
48
  for (const [key, child] of Object.entries(unwrapped)) {
47
- let obj;
48
- if (child != null && typeof child === "object" && ((obj = child[solidJs.$PROXY]) || (obj = solidJs.untrack(() => value[key])) && solidJs.$TRACK in obj)) {
49
- getTrackStoreNode(obj)?.();
49
+ let childNode;
50
+ if (child != null && typeof child === "object" && ((childNode = child[solidJs.$PROXY]) || (childNode = solidJs.untrack(() => node[key])) && solidJs.$TRACK in childNode)) {
51
+ getTrackStoreNode(childNode)?.();
50
52
  }
51
53
  }
52
54
  });
53
- TrackStoreCache.set(value, track);
55
+ TrackStoreCache.set(node, track);
54
56
  });
55
57
  }
56
58
  return track;
@@ -60,6 +62,80 @@ function trackStore(store) {
60
62
  solidJs.$TRACK in store && getTrackStoreNode(store)?.();
61
63
  return store;
62
64
  }
65
+ function* entries(obj) {
66
+ if (Array.isArray(obj)) {
67
+ for (let i = 0; i < obj.length; i++) {
68
+ yield [i, obj[i]];
69
+ }
70
+ } else {
71
+ yield* Object.entries(obj)[Symbol.iterator]();
72
+ }
73
+ }
74
+ var StoreNodeChildrenCache = /* @__PURE__ */ new WeakMap();
75
+ function getStoreNodechildren(node) {
76
+ let signal = StoreNodeChildrenCache.get(node);
77
+ if (!signal) {
78
+ const unwrapped = store.unwrap(node), isArray = Array.isArray(unwrapped);
79
+ signal = solidJs.createRoot(
80
+ () => memo.createLazyMemo(() => {
81
+ node[solidJs.$TRACK];
82
+ const children = isArray ? [] : {};
83
+ for (const [key, child] of entries(unwrapped)) {
84
+ let childNode;
85
+ if (child != null && typeof child === "object" && ((childNode = child[solidJs.$PROXY]) || (childNode = solidJs.untrack(() => node[key])) && solidJs.$TRACK in childNode)) {
86
+ children[key] = childNode;
87
+ }
88
+ }
89
+ return children;
90
+ })
91
+ );
92
+ StoreNodeChildrenCache.set(node, signal);
93
+ }
94
+ return signal();
95
+ }
96
+ var CurrentUpdates;
97
+ var SeenNodes;
98
+ function newCacheNode(children) {
99
+ const record = { ...children };
100
+ for (const [key, node] of entries(children)) {
101
+ if (SeenNodes.has(node))
102
+ continue;
103
+ SeenNodes.add(node);
104
+ record[key] = newCacheNode(getStoreNodechildren(node));
105
+ }
106
+ return { children, record };
107
+ }
108
+ function compareStoreWithCache(node, parent, key, path) {
109
+ if (SeenNodes.has(node))
110
+ return;
111
+ SeenNodes.add(node);
112
+ const cacheNode = parent[key], children = getStoreNodechildren(node);
113
+ if (cacheNode && children === cacheNode.children) {
114
+ for (const [key2, child] of entries(children)) {
115
+ compareStoreWithCache(child, cacheNode.record, key2, [...path, key2]);
116
+ }
117
+ } else {
118
+ parent[key] = newCacheNode(children);
119
+ CurrentUpdates.push({ path, value: node });
120
+ }
121
+ }
122
+ function captureStoreUpdates(store) {
123
+ if (web.isServer || !(solidJs.$TRACK in store)) {
124
+ if (web.isDev) {
125
+ console.warn("createStoreDelta expects a store, got", store);
126
+ }
127
+ let init = true;
128
+ return () => init ? (init = false, [{ path: [], value: store }]) : [];
129
+ }
130
+ const cache = {};
131
+ return () => {
132
+ CurrentUpdates = [];
133
+ SeenNodes = /* @__PURE__ */ new WeakSet();
134
+ compareStoreWithCache(store, cache, "root", []);
135
+ return CurrentUpdates;
136
+ };
137
+ }
63
138
 
139
+ exports.captureStoreUpdates = captureStoreUpdates;
64
140
  exports.trackDeep = trackDeep;
65
141
  exports.trackStore = trackStore;
package/dist/index.d.ts CHANGED
@@ -44,4 +44,37 @@ declare const deepTrack: typeof trackDeep;
44
44
  */
45
45
  declare function trackStore<T extends object>(store: Store<T>): T;
46
46
 
47
- export { deepTrack, trackDeep, trackStore };
47
+ type Static<T = unknown> = {
48
+ [K in number | string]: T;
49
+ } | T[];
50
+ type AllNestedObjects<T> = T extends Static<infer U> ? AllNestedObjects<U> | T : never;
51
+ type NestedUpdate<T> = {
52
+ path: (string | number)[];
53
+ value: AllNestedObjects<T>;
54
+ };
55
+ /**
56
+ * Creates a function for tracking and capturing updates to a {@link store}.
57
+ *
58
+ * Each execution of the returned function will return an array of updates to the store since the last execution.
59
+ *
60
+ * @param store - The store to track.
61
+ * @returns A function that returns an array of updates to the store since the last execution.
62
+ *
63
+ * @see https://github.com/solidjs-community/solid-primitives/tree/main/packages/deep#captureStoreUpdates
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * const [state, setState] = createStore({ todos: [] });
68
+ *
69
+ * const getDelta = captureStoreUpdates(state);
70
+ *
71
+ * getDelta(); // [{ path: [], value: { todos: [] } }]
72
+ *
73
+ * setState("todos", ["foo"]);
74
+ *
75
+ * getDelta(); // [{ path: ["todos"], value: ["foo"] }]
76
+ * ```
77
+ */
78
+ declare function captureStoreUpdates<T extends Static>(store: T): () => NestedUpdate<T>[];
79
+
80
+ export { AllNestedObjects, NestedUpdate, captureStoreUpdates, deepTrack, trackDeep, trackStore };
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { $PROXY, $TRACK, createRoot, createSignal, createMemo, untrack } from 'solid-js';
2
2
  import { unwrap } from 'solid-js/store';
3
+ import { createLazyMemo as createLazyMemo$1 } from '@solid-primitives/memo';
4
+ import { isServer, isDev } from 'solid-js/web';
3
5
 
4
6
  // src/track-deep.ts
5
7
  function trackDeep(store) {
@@ -34,21 +36,21 @@ function createLazyMemo(calc) {
34
36
  isReading = false;
35
37
  };
36
38
  }
37
- function getTrackStoreNode(value) {
38
- let track = TrackStoreCache.get(value);
39
+ function getTrackStoreNode(node) {
40
+ let track = TrackStoreCache.get(node);
39
41
  if (!track) {
40
42
  createRoot(() => {
41
- const unwrapped = unwrap(value);
43
+ const unwrapped = unwrap(node);
42
44
  track = createLazyMemo(() => {
43
- value[$TRACK];
45
+ node[$TRACK];
44
46
  for (const [key, child] of Object.entries(unwrapped)) {
45
- let obj;
46
- if (child != null && typeof child === "object" && ((obj = child[$PROXY]) || (obj = untrack(() => value[key])) && $TRACK in obj)) {
47
- getTrackStoreNode(obj)?.();
47
+ let childNode;
48
+ if (child != null && typeof child === "object" && ((childNode = child[$PROXY]) || (childNode = untrack(() => node[key])) && $TRACK in childNode)) {
49
+ getTrackStoreNode(childNode)?.();
48
50
  }
49
51
  }
50
52
  });
51
- TrackStoreCache.set(value, track);
53
+ TrackStoreCache.set(node, track);
52
54
  });
53
55
  }
54
56
  return track;
@@ -58,5 +60,78 @@ function trackStore(store) {
58
60
  $TRACK in store && getTrackStoreNode(store)?.();
59
61
  return store;
60
62
  }
63
+ function* entries(obj) {
64
+ if (Array.isArray(obj)) {
65
+ for (let i = 0; i < obj.length; i++) {
66
+ yield [i, obj[i]];
67
+ }
68
+ } else {
69
+ yield* Object.entries(obj)[Symbol.iterator]();
70
+ }
71
+ }
72
+ var StoreNodeChildrenCache = /* @__PURE__ */ new WeakMap();
73
+ function getStoreNodechildren(node) {
74
+ let signal = StoreNodeChildrenCache.get(node);
75
+ if (!signal) {
76
+ const unwrapped = unwrap(node), isArray = Array.isArray(unwrapped);
77
+ signal = createRoot(
78
+ () => createLazyMemo$1(() => {
79
+ node[$TRACK];
80
+ const children = isArray ? [] : {};
81
+ for (const [key, child] of entries(unwrapped)) {
82
+ let childNode;
83
+ if (child != null && typeof child === "object" && ((childNode = child[$PROXY]) || (childNode = untrack(() => node[key])) && $TRACK in childNode)) {
84
+ children[key] = childNode;
85
+ }
86
+ }
87
+ return children;
88
+ })
89
+ );
90
+ StoreNodeChildrenCache.set(node, signal);
91
+ }
92
+ return signal();
93
+ }
94
+ var CurrentUpdates;
95
+ var SeenNodes;
96
+ function newCacheNode(children) {
97
+ const record = { ...children };
98
+ for (const [key, node] of entries(children)) {
99
+ if (SeenNodes.has(node))
100
+ continue;
101
+ SeenNodes.add(node);
102
+ record[key] = newCacheNode(getStoreNodechildren(node));
103
+ }
104
+ return { children, record };
105
+ }
106
+ function compareStoreWithCache(node, parent, key, path) {
107
+ if (SeenNodes.has(node))
108
+ return;
109
+ SeenNodes.add(node);
110
+ const cacheNode = parent[key], children = getStoreNodechildren(node);
111
+ if (cacheNode && children === cacheNode.children) {
112
+ for (const [key2, child] of entries(children)) {
113
+ compareStoreWithCache(child, cacheNode.record, key2, [...path, key2]);
114
+ }
115
+ } else {
116
+ parent[key] = newCacheNode(children);
117
+ CurrentUpdates.push({ path, value: node });
118
+ }
119
+ }
120
+ function captureStoreUpdates(store) {
121
+ if (isServer || !($TRACK in store)) {
122
+ if (isDev) {
123
+ console.warn("createStoreDelta expects a store, got", store);
124
+ }
125
+ let init = true;
126
+ return () => init ? (init = false, [{ path: [], value: store }]) : [];
127
+ }
128
+ const cache = {};
129
+ return () => {
130
+ CurrentUpdates = [];
131
+ SeenNodes = /* @__PURE__ */ new WeakSet();
132
+ compareStoreWithCache(store, cache, "root", []);
133
+ return CurrentUpdates;
134
+ };
135
+ }
61
136
 
62
- export { deepTrack, trackDeep, trackStore };
137
+ export { captureStoreUpdates, deepTrack, trackDeep, trackStore };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@solid-primitives/deep",
3
- "version": "0.1.0",
4
- "description": "Deep trigger effects for Stores.",
3
+ "version": "0.2.0",
4
+ "description": "Primitives for tracking and observing nested reactive objects in Solid.",
5
5
  "author": "Samuel Burbano <me@iosamuel.dev>",
6
6
  "contributors": [
7
7
  "Damian Tarnawski <gthetarnav@gmail.com>"
@@ -20,7 +20,8 @@
20
20
  "stage": 1,
21
21
  "list": [
22
22
  "trackDeep",
23
- "trackStore"
23
+ "trackStore",
24
+ "captureStoreUpdates"
24
25
  ],
25
26
  "category": "Reactivity"
26
27
  },
@@ -29,7 +30,8 @@
29
30
  "primitives",
30
31
  "deep",
31
32
  "store",
32
- "reactivity"
33
+ "reactivity",
34
+ "delta"
33
35
  ],
34
36
  "private": false,
35
37
  "sideEffects": false,
@@ -48,10 +50,16 @@
48
50
  },
49
51
  "require": "./dist/index.cjs"
50
52
  },
53
+ "typesVersions": {},
54
+ "dependencies": {
55
+ "@solid-primitives/memo": "^1.3.1"
56
+ },
51
57
  "peerDependencies": {
52
58
  "solid-js": "^1.6.12"
53
59
  },
54
- "typesVersions": {},
60
+ "devDependencies": {
61
+ "solid-js": "1.7.5"
62
+ },
55
63
  "scripts": {
56
64
  "dev": "jiti ../../scripts/dev.ts",
57
65
  "build": "jiti ../../scripts/build.ts",