stunk 1.2.4 → 1.2.5

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
@@ -73,30 +73,6 @@ count.set(10);
73
73
  // "Double count: 20"
74
74
  ```
75
75
 
76
- ## Batch Updates
77
-
78
- Batch Update group multiple **state changes** together and notify **subscribers** only once at the end of the **batch**. This is particularly useful for **optimizing performance** when you need to **update multiple** chunks at the same time.
79
-
80
- ```typescript
81
- import { chunk, batch } from "stunk";
82
-
83
- const nameChunk = chunk("Olamide");
84
- const ageChunk = chunk(30);
85
-
86
- batch(() => {
87
- nameChunk.set("AbdulAzeez");
88
- ageChunk.set(31);
89
- }); // Only one notification will be sent to subscribers
90
-
91
- // Nested batches are also supported
92
- batch(() => {
93
- firstName.set("Olanrewaju");
94
- batch(() => {
95
- age.set(29);
96
- });
97
- }); // Only one notification will be sent to subscribers
98
- ```
99
-
100
76
  ## State Selection
101
77
 
102
78
  Efficiently access and react to specific state parts:
@@ -120,59 +96,30 @@ nameChunk.subscribe((name) => console.log("Name changed:", name));
120
96
  nameChunk.set("Olamide"); // ❌ this will throw an error, because it is a readonly.
121
97
  ```
122
98
 
123
- ## Middleware
124
-
125
- Middleware allows you to customize how values are set in a **chunk**. For example, you can add **logging**, **validation**, or any custom behavior when a chunk's value changes.
126
-
127
- ```typescript
128
- import { chunk } from "stunk";
129
- import { logger, nonNegativeValidator } from "stunk/middleware";
130
-
131
- // You can also create yours and pass it chunk as the second param
132
-
133
- // Use middleware for logging and validation
134
- const age = chunk(25, [logger, nonNegativeValidator]);
135
-
136
- age.set(30); // Logs: "Setting value: 30"
137
- age.set(-5); // ❌ Throws an error: "Value must be non-negative!"
138
- ```
139
-
140
- ## Time Travel (Middleware)
99
+ ## Batch Updates
141
100
 
142
- The withHistory middleware extends a chunk to support undo and redo functionality. This allows you to navigate back and forth between previous states, making it useful for implementing features like undo/redo, form history, and state time travel.
101
+ Batch Update group multiple **state changes** together and notify **subscribers** only once at the end of the **batch**. This is particularly useful for **optimizing performance** when you need to **update multiple** chunks at the same time.
143
102
 
144
103
  ```typescript
145
- import { chunk } from "stunk";
146
- import { withHistory } from "stunk/midddleware";
147
-
148
- const counterChunk = withHistory(chunk(0));
149
-
150
- counterChunk.set(1);
151
- counterChunk.set(2);
152
-
153
- counterChunk.undo(); // Goes back to 1
154
- counterChunk.undo(); // Goes back to 0
155
-
156
- counterChunk.redo(); // Goes forward to 1
157
-
158
- counterChunk.canUndo(); // Returns `true` if there is a previous state to revert to..
159
- counterChunk.canRedo(); // Returns `true` if there is a next state to move to.
160
-
161
- counterChunk.getHistory(); // Returns an array of all the values in the history.
104
+ import { chunk, batch } from "stunk";
162
105
 
163
- counterChunk.clearHistory(); // Clears the history, keeping only the current value.
164
- ```
106
+ const nameChunk = chunk("Olamide");
107
+ const ageChunk = chunk(30);
165
108
 
166
- **Example: Limiting History Size (Optional)**
167
- You can specify a max history size to prevent excessive memory usage.
109
+ batch(() => {
110
+ nameChunk.set("AbdulAzeez");
111
+ ageChunk.set(31);
112
+ }); // Only one notification will be sent to subscribers
168
113
 
169
- ```ts
170
- const counter = withHistory(chunk(0), { maxHistory: 5 });
171
- // Only keeps the last 5 changes -- default is 100.
114
+ // Nested batches are also supported
115
+ batch(() => {
116
+ firstName.set("Olanrewaju");
117
+ batch(() => {
118
+ age.set(29);
119
+ });
120
+ }); // Only one notification will be sent to subscribers
172
121
  ```
173
122
 
174
- This prevents the history from growing indefinitely and ensures efficient memory usage.
175
-
176
123
  ## Computed
177
124
 
178
125
  Computed Chunks in Stunk allow you to create state derived from other chunks in a reactive way. Unlike derived chunks, computed chunks can depend on multiple sources, and they automatically recalculate when any of the source chunks change.
@@ -202,7 +149,7 @@ firstNameChunk.set("Ola");
202
149
  ageChunk.set(10);
203
150
 
204
151
  console.log(fullInfoChunk.get());
205
- // ✅ { fullName: "Jane Doe", isAdult: true }
152
+ // ✅ { fullName: "Ola Doe", isAdult: true }
206
153
  ```
207
154
 
208
155
  Computed chunks are ideal for scenarios where state depends on multiple sources or needs complex calculations. They ensure your application remains performant and maintainable.
@@ -277,7 +224,61 @@ const filteredPostsChunk = computed(
277
224
  );
278
225
  ```
279
226
 
280
- ## State Persistence
227
+ ## Middleware
228
+
229
+ Middleware allows you to customize how values are set in a **chunk**. For example, you can add **logging**, **validation**, or any custom behavior when a chunk's value changes.
230
+
231
+ ```typescript
232
+ import { chunk } from "stunk";
233
+ import { logger, nonNegativeValidator } from "stunk/middleware";
234
+
235
+ // You can also create yours and pass it chunk as the second param
236
+
237
+ // Use middleware for logging and validation
238
+ const age = chunk(25, [logger, nonNegativeValidator]);
239
+
240
+ age.set(30); // Logs: "Setting value: 30"
241
+ age.set(-5); // ❌ Throws an error: "Value must be non-negative!"
242
+ ```
243
+
244
+ ## Time Travel (Middleware)
245
+
246
+ The withHistory middleware extends a chunk to support undo and redo functionality. This allows you to navigate back and forth between previous states, making it useful for implementing features like undo/redo, form history, and state time travel.
247
+
248
+ ```typescript
249
+ import { chunk } from "stunk";
250
+ import { withHistory } from "stunk/midddleware";
251
+
252
+ const counterChunk = withHistory(chunk(0));
253
+
254
+ counterChunk.set(1);
255
+ counterChunk.set(2);
256
+
257
+ counterChunk.undo(); // Goes back to 1
258
+ counterChunk.undo(); // Goes back to 0
259
+
260
+ counterChunk.redo(); // Goes forward to 1
261
+
262
+ counterChunk.canUndo(); // Returns `true` if there is a previous state to revert to..
263
+ counterChunk.canRedo(); // Returns `true` if there is a next state to move to.
264
+
265
+ counterChunk.getHistory(); // Returns an array of all the values in the history.
266
+
267
+ counterChunk.clearHistory(); // Clears the history, keeping only the current value.
268
+ ```
269
+
270
+ **Example: Limiting History Size (Optional)**
271
+ You can specify a max history size to prevent excessive memory usage.
272
+
273
+ ```ts
274
+ const counter = withHistory(chunk(0), { maxHistory: 5 });
275
+ // Only keeps the last 5 changes -- default is 100.
276
+ ```
277
+
278
+ This prevents the history from growing indefinitely and ensures efficient memory usage.
279
+
280
+
281
+ ## State Persistence (Middleware)
281
282
 
282
283
  Stunk provides a persistence middleware to automatically save state changes to storage (localStorage, sessionStorage, etc).
283
284
 
package/dist/utils.js CHANGED
@@ -12,6 +12,18 @@ export function isChunk(value) {
12
12
  typeof value.reset === 'function' &&
13
13
  typeof value.destroy === 'function';
14
14
  }
15
+ export function once(fn) {
16
+ let called = false;
17
+ let result;
18
+ return () => {
19
+ if (!called) {
20
+ result = fn();
21
+ called = true;
22
+ }
23
+ return result;
24
+ };
25
+ }
26
+ ;
15
27
  export function combineAsyncChunks(chunks) {
16
28
  // Create initial state with proper typing
17
29
  const initialData = Object.keys(chunks).reduce((acc, key) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stunk",
3
- "version": "1.2.4",
3
+ "version": "1.2.5",
4
4
  "description": "Stunk is a lightweight, framework-agnostic state management library for JavaScript and TypeScript. It uses chunk-based state units for efficient updates, reactivity, and performance optimization in React, Vue, Svelte, and Vanilla JS/TS applications.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/utils.ts CHANGED
@@ -18,6 +18,18 @@ export function isChunk<T>(value: any): value is Chunk<T> {
18
18
  typeof value.destroy === 'function';
19
19
  }
20
20
 
21
+ export function once<T>(fn: () => T): () => T {
22
+ let called = false;
23
+ let result: T;
24
+ return () => {
25
+ if (!called) {
26
+ result = fn();
27
+ called = true;
28
+ }
29
+ return result;
30
+ };
31
+ };
32
+
21
33
  export function combineAsyncChunks<T extends Record<string, AsyncChunk<any>>>(
22
34
  chunks: T
23
35
  ): Chunk<{