stunk 2.7.1 → 2.8.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/LICENSE +27 -27
- package/README.md +212 -204
- package/dist/{core-C7jFiHdO.d.ts → core-DMY69lzg.d.cts} +1 -1
- package/dist/core-DMY69lzg.d.ts +18 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/middleware/index.cjs +1 -0
- package/dist/middleware/index.d.cts +45 -0
- package/dist/middleware/index.d.ts +1 -1
- package/dist/middleware/index.js +1 -1
- package/dist/use-react/index.cjs +1 -0
- package/dist/use-react/index.d.cts +141 -0
- package/dist/use-react/index.d.ts +1 -1
- package/dist/use-react/index.js +1 -1
- package/package.json +121 -119
package/LICENSE
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
---
|
|
2
|
-
|
|
3
|
-
### **`LICENSE`**
|
|
4
|
-
|
|
5
|
-
```text
|
|
6
|
-
MIT License
|
|
7
|
-
|
|
8
|
-
Copyright (c) 2025 AbdulAzeez
|
|
9
|
-
|
|
10
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
-
in the Software without restriction, including without limitation the rights
|
|
13
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
-
furnished to do so, subject to the following conditions:
|
|
16
|
-
|
|
17
|
-
The above copyright notice and this permission notice shall be included in all
|
|
18
|
-
copies or substantial portions of the Software.
|
|
19
|
-
|
|
20
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
-
SOFTWARE.
|
|
27
|
-
```
|
|
1
|
+
---
|
|
2
|
+
|
|
3
|
+
### **`LICENSE`**
|
|
4
|
+
|
|
5
|
+
```text
|
|
6
|
+
MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 AbdulAzeez
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
```
|
package/README.md
CHANGED
|
@@ -1,204 +1,212 @@
|
|
|
1
|
-
# Stunk
|
|
2
|
-
|
|
3
|
-
Stunk is a lightweight, framework-agnostic state management library built on atomic state principles. It simplifies state management by breaking state into manageable "chunks", ensuring efficient updates and reactivity.
|
|
4
|
-
|
|
5
|
-
- **Pronunciation**: _Stunk_ (A playful blend of "state" and "chunk")
|
|
6
|
-
|
|
7
|
-
**Stunk** is like dividing your jar into many smaller containers, each holding a single piece of state. These smaller containers are called **chunks**. Each **chunk** can be updated and accessed easily, and any part of your app can subscribe to changes in a chunk so it gets updated automatically.
|
|
8
|
-
|
|
9
|
-
## Features
|
|
10
|
-
|
|
11
|
-
- 🚀 **Lightweight and Fast**: No dependencies, minimal overhead
|
|
12
|
-
- 🔄 **Reactive**: Automatic updates when state changes
|
|
13
|
-
- 📦 **Batch Updates**: Group multiple state updates together
|
|
14
|
-
- 🎯 **Atomic State Management**: Break down state into manageable chunks
|
|
15
|
-
- 🎭 **State Selection**: Select and derive specific parts of the state
|
|
16
|
-
- 🔄 **Async Support**: Handle async state with built-in loading and error states
|
|
17
|
-
- 🔌 **Middleware Support**: Extend functionality with custom middleware
|
|
18
|
-
- ⏱️ **Time Travel**: Undo/redo state changes
|
|
19
|
-
- 🔍 **Type-Safe**: Written in TypeScript with full type inference
|
|
20
|
-
|
|
21
|
-
## Installation
|
|
22
|
-
|
|
23
|
-
```bash
|
|
24
|
-
npm install stunk
|
|
25
|
-
# or
|
|
26
|
-
yarn add stunk
|
|
27
|
-
# or
|
|
28
|
-
pnpm install stunk
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
Read Docs:
|
|
32
|
-
|
|
33
|
-
[Stunk](https://stunk.
|
|
34
|
-
|
|
35
|
-
## Creating a Chunk
|
|
36
|
-
|
|
37
|
-
```typescript
|
|
38
|
-
import { chunk } from "stunk";
|
|
39
|
-
|
|
40
|
-
// Create a chunk holding a number
|
|
41
|
-
const count = chunk(0);
|
|
42
|
-
|
|
43
|
-
// Create a chunk holding a string
|
|
44
|
-
const name = chunk("Stunky, chunky");
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
👉 [See full explanation in docs](https://stunk.
|
|
48
|
-
|
|
49
|
-
## Interacting with a Chunk
|
|
50
|
-
|
|
51
|
-
```typescript
|
|
52
|
-
// Get value
|
|
53
|
-
console.log(count.get()); // 0
|
|
54
|
-
|
|
55
|
-
// Set a new value
|
|
56
|
-
count.set(10);
|
|
57
|
-
|
|
58
|
-
// Update based on the previous value
|
|
59
|
-
count.set((prev) => prev + 1);
|
|
60
|
-
|
|
61
|
-
// Reset to the initial value
|
|
62
|
-
count.reset();
|
|
63
|
-
|
|
64
|
-
// Destroy the chunk and all its subscribers.
|
|
65
|
-
count.destroy();
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
👉 [See full explanation in docs](https://stunk.
|
|
69
|
-
|
|
70
|
-
## React via useChunk
|
|
71
|
-
|
|
72
|
-
The `useChunk` hook, enables components to reactively read and update state from a Chunk. The counter example below depicts
|
|
73
|
-
|
|
74
|
-
```typescript
|
|
75
|
-
import { chunk } from "stunk";
|
|
76
|
-
import { useChunk } from "stunk/react";
|
|
77
|
-
|
|
78
|
-
const count = chunk(0);
|
|
79
|
-
|
|
80
|
-
const Counter = () => {
|
|
81
|
-
const [value, set, reset] = useChunk(count);
|
|
82
|
-
|
|
83
|
-
return (
|
|
84
|
-
<div>
|
|
85
|
-
<p>Count: {value}</p>
|
|
86
|
-
<button onClick={() => set((prev) => prev + 1)}>Increment</button>
|
|
87
|
-
<button onClick={() => reset()}>Reset</button>
|
|
88
|
-
</div>
|
|
89
|
-
);
|
|
90
|
-
};
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
👉 [See full explanation in docs](https://stunk.
|
|
94
|
-
|
|
95
|
-
## React via useDerive
|
|
96
|
-
|
|
97
|
-
Hook that lets you create a read-only derived state from a Chunk. It keeps the derived value reactive, automatically updating whenever the source Chunk changes.
|
|
98
|
-
|
|
99
|
-
```typescript
|
|
100
|
-
import { chunk } from "stunk";
|
|
101
|
-
import { useDerive } from "stunk/react";
|
|
102
|
-
|
|
103
|
-
const count = chunk(0);
|
|
104
|
-
|
|
105
|
-
const DoubledCount = () => {
|
|
106
|
-
const double = useDerive(count, (value) => value * 2);
|
|
107
|
-
|
|
108
|
-
return <p>Double: {double}</p>;
|
|
109
|
-
};
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
👉 [See full explanation in docs](https://stunk.
|
|
113
|
-
|
|
114
|
-
## React via useComputed
|
|
115
|
-
|
|
116
|
-
Hook that derives a computed value from one or more Chunks. It automatically re-evaluates whenever any of its dependencies change, ensuring efficient and reactive updates.
|
|
117
|
-
|
|
118
|
-
```typescript
|
|
119
|
-
import { chunk } from "stunk";
|
|
120
|
-
import { useComputed } from "stunk/react";
|
|
121
|
-
|
|
122
|
-
const count = chunk(2);
|
|
123
|
-
const multiplier = chunk(3);
|
|
124
|
-
|
|
125
|
-
const ComputedExample = () => {
|
|
126
|
-
const product = useComputed(
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
)
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
```
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
};
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
👉 [
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
👉 [Visit](https://
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
1
|
+
# Stunk
|
|
2
|
+
|
|
3
|
+
Stunk is a lightweight, framework-agnostic state management library built on atomic state principles. It simplifies state management by breaking state into manageable "chunks", ensuring efficient updates and reactivity.
|
|
4
|
+
|
|
5
|
+
- **Pronunciation**: _Stunk_ (A playful blend of "state" and "chunk")
|
|
6
|
+
|
|
7
|
+
**Stunk** is like dividing your jar into many smaller containers, each holding a single piece of state. These smaller containers are called **chunks**. Each **chunk** can be updated and accessed easily, and any part of your app can subscribe to changes in a chunk so it gets updated automatically.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- 🚀 **Lightweight and Fast**: No dependencies, minimal overhead
|
|
12
|
+
- 🔄 **Reactive**: Automatic updates when state changes
|
|
13
|
+
- 📦 **Batch Updates**: Group multiple state updates together
|
|
14
|
+
- 🎯 **Atomic State Management**: Break down state into manageable chunks
|
|
15
|
+
- 🎭 **State Selection**: Select and derive specific parts of the state
|
|
16
|
+
- 🔄 **Async Support**: Handle async state with built-in loading and error states
|
|
17
|
+
- 🔌 **Middleware Support**: Extend functionality with custom middleware
|
|
18
|
+
- ⏱️ **Time Travel**: Undo/redo state changes
|
|
19
|
+
- 🔍 **Type-Safe**: Written in TypeScript with full type inference
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install stunk
|
|
25
|
+
# or
|
|
26
|
+
yarn add stunk
|
|
27
|
+
# or
|
|
28
|
+
pnpm install stunk
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Read Docs:
|
|
32
|
+
|
|
33
|
+
[Stunk](https://stunk.dev/)
|
|
34
|
+
|
|
35
|
+
## Creating a Chunk
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
import { chunk } from "stunk";
|
|
39
|
+
|
|
40
|
+
// Create a chunk holding a number
|
|
41
|
+
const count = chunk<number>(0);
|
|
42
|
+
|
|
43
|
+
// Create a chunk holding a string
|
|
44
|
+
const name = chunk<string>("Stunky, chunky");
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
👉 [See full explanation in docs](https://stunk.dev/chunk.html)
|
|
48
|
+
|
|
49
|
+
## Interacting with a Chunk
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
// Get value
|
|
53
|
+
console.log(count.get()); // 0
|
|
54
|
+
|
|
55
|
+
// Set a new value
|
|
56
|
+
count.set(10);
|
|
57
|
+
|
|
58
|
+
// Update based on the previous value
|
|
59
|
+
count.set((prev: number) => prev + 1);
|
|
60
|
+
|
|
61
|
+
// Reset to the initial value
|
|
62
|
+
count.reset();
|
|
63
|
+
|
|
64
|
+
// Destroy the chunk and all its subscribers.
|
|
65
|
+
count.destroy();
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
👉 [See full explanation in docs](https://stunk.dev/chunk.html)
|
|
69
|
+
|
|
70
|
+
## React via useChunk
|
|
71
|
+
|
|
72
|
+
The `useChunk` hook, enables components to reactively read and update state from a Chunk. The counter example below depicts
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
import { chunk } from "stunk";
|
|
76
|
+
import { useChunk } from "stunk/react";
|
|
77
|
+
|
|
78
|
+
const count = chunk<number>(0);
|
|
79
|
+
|
|
80
|
+
const Counter = () => {
|
|
81
|
+
const [value, set, reset] = useChunk(count);
|
|
82
|
+
|
|
83
|
+
return (
|
|
84
|
+
<div>
|
|
85
|
+
<p>Count: {value}</p>
|
|
86
|
+
<button onClick={() => set((prev: number) => prev + 1)}>Increment</button>
|
|
87
|
+
<button onClick={() => reset()}>Reset</button>
|
|
88
|
+
</div>
|
|
89
|
+
);
|
|
90
|
+
};
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
👉 [See full explanation in docs](https://stunk.dev/useChunk.html)
|
|
94
|
+
|
|
95
|
+
## React via useDerive
|
|
96
|
+
|
|
97
|
+
Hook that lets you create a read-only derived state from a Chunk. It keeps the derived value reactive, automatically updating whenever the source Chunk changes.
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import { chunk } from "stunk";
|
|
101
|
+
import { useDerive } from "stunk/react";
|
|
102
|
+
|
|
103
|
+
const count = chunk<number>(0);
|
|
104
|
+
|
|
105
|
+
const DoubledCount = () => {
|
|
106
|
+
const double = useDerive(count, (value: number) => value * 2);
|
|
107
|
+
|
|
108
|
+
return <p>Double: {double}</p>;
|
|
109
|
+
};
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
👉 [See full explanation in docs](https://stunk.dev/useDerive.html)
|
|
113
|
+
|
|
114
|
+
## React via useComputed
|
|
115
|
+
|
|
116
|
+
Hook that derives a computed value from one or more Chunks. It automatically re-evaluates whenever any of its dependencies change, ensuring efficient and reactive updates.
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
import { chunk } from "stunk";
|
|
120
|
+
import { useComputed } from "stunk/react";
|
|
121
|
+
|
|
122
|
+
const count = chunk<number>(2);
|
|
123
|
+
const multiplier = chunk<number>(3);
|
|
124
|
+
|
|
125
|
+
const ComputedExample = () => {
|
|
126
|
+
const product = useComputed(
|
|
127
|
+
[count, multiplier],
|
|
128
|
+
(c: number, m: number) => c * m
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
return <p>Product: {product}</p>;
|
|
132
|
+
};
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
👉 [See full explanation in docs](https://stunk.dev/useComputed.html)
|
|
136
|
+
|
|
137
|
+
## React via useAsyncChunk
|
|
138
|
+
|
|
139
|
+
Hook that manages that manages asynchronous state. It offers built-in reactivity, handling loading, error, and data states, ensuring the UI stays in sync with asynchronous operations.
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
import { asyncChunk } from "stunk";
|
|
143
|
+
import { useAsyncChunk } from "stunk/react";
|
|
144
|
+
|
|
145
|
+
interface User {
|
|
146
|
+
name: string;
|
|
147
|
+
email: string;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const fetchUser = asyncChunk<User>(async () => {
|
|
151
|
+
const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
|
|
152
|
+
return res.json();
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
const UserProfile = () => {
|
|
156
|
+
const { data, loading, error, reload } = useAsyncChunk(fetchUser);
|
|
157
|
+
|
|
158
|
+
if (loading) return <p>Loading...</p>;
|
|
159
|
+
if (error) return <p>Error: {error.message}</p>;
|
|
160
|
+
|
|
161
|
+
return (
|
|
162
|
+
<div>
|
|
163
|
+
<h2>{data?.name}</h2>
|
|
164
|
+
<p>{data?.email}</p>
|
|
165
|
+
<button onClick={reload}>Reload</button>
|
|
166
|
+
</div>
|
|
167
|
+
);
|
|
168
|
+
};
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
👉 [See full explanation in docs](https://stunk.dev/useAysncChunk.html)
|
|
172
|
+
|
|
173
|
+
## React via useChunkValue
|
|
174
|
+
|
|
175
|
+
Hook that subscribes to a Chunk and returns its current value. It is useful for read-only components that don’t need to modify the state.
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
import { chunk } from "stunk";
|
|
179
|
+
import { useChunkValue } from "stunk/react";
|
|
180
|
+
|
|
181
|
+
const count = chunk<number>(0);
|
|
182
|
+
|
|
183
|
+
const CounterDisplay = () => {
|
|
184
|
+
const value = useChunkValue(count);
|
|
185
|
+
|
|
186
|
+
return <p>Count: {value}</p>;
|
|
187
|
+
};
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
👉 [See full explanation in docs](https://stunk.dev/read-only-values.html)
|
|
191
|
+
|
|
192
|
+
Live Examples:
|
|
193
|
+
|
|
194
|
+
👉 [Visit](https://stunk-examples.dev/)
|
|
195
|
+
|
|
196
|
+
Coding Examples:
|
|
197
|
+
|
|
198
|
+
👉 [Visit](https://stunk.dev/examples.html)
|
|
199
|
+
|
|
200
|
+
Further Examples:
|
|
201
|
+
|
|
202
|
+
👉 [Visit](https://github.com/I-am-abdulazeez/stunk-examples/)
|
|
203
|
+
|
|
204
|
+
## Contributing
|
|
205
|
+
|
|
206
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
207
|
+
|
|
208
|
+
[Pull Request](https://github.com/I-am-abdulazeez/stunk/pulls)
|
|
209
|
+
|
|
210
|
+
## License
|
|
211
|
+
|
|
212
|
+
This is licence under MIT
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
type Subscriber<T> = (newValue: T) => void;
|
|
2
|
+
type Middleware<T> = (value: T) => T | undefined;
|
|
3
|
+
interface Chunk<T> {
|
|
4
|
+
/** Get the current value of the chunk. */
|
|
5
|
+
get: () => T;
|
|
6
|
+
/** Set a new value for the chunk & Update existing value efficiently. */
|
|
7
|
+
set: (newValueOrUpdater: T | ((currentValue: T) => T)) => void;
|
|
8
|
+
/** Subscribe to changes in the chunk. Returns an unsubscribe function. */
|
|
9
|
+
subscribe: (callback: Subscriber<T>) => () => void;
|
|
10
|
+
/** Create a derived chunk based on this chunk's value. */
|
|
11
|
+
derive: <D>(fn: (value: T) => D) => Chunk<D>;
|
|
12
|
+
/** Reset the chunk to its initial value. */
|
|
13
|
+
reset: () => void;
|
|
14
|
+
/** Destroy the chunk and all its subscribers. */
|
|
15
|
+
destroy: () => void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type { Chunk as C, Middleware as M };
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var Y=Object.defineProperty;var Z=(e,
|
|
1
|
+
'use strict';var Y=Object.defineProperty;var Z=(e,o)=>{for(var r in o)Y(e,r,{get:o[r],enumerable:true});};function _(e){return e!==null}function ee(e){if(!e||typeof e!="object")return false;let o=e;return ["get","set","subscribe","derive","reset","destroy"].every(t=>typeof o[t]=="function")}function te(e){let o=false,r;return ()=>(o||(r=e(),o=true),r)}function re(e){let o=Object.keys(e).reduce((n,u)=>(n[u]=null,n),{}),r={loading:Object.keys(e).length>0,error:null,errors:{},data:o},t=k(r);return Object.entries(e).forEach(([n,u])=>{u.subscribe(a=>{let s=t.get(),l=false,c=null,f={};Object.entries(e).forEach(([h,x])=>{let p=x.get();p.loading&&(l=true),p.error&&(c||(c=p.error),f[h]=p.error);}),t.set({loading:l,error:c,errors:f,data:{...s.data,[n]:a.data}});});}),t}function N(e,o){if(e===null)throw new Error("Value cannot be null.");let r=e;for(let t=0;t<o.length;t++){let n=o[t],u=typeof n=="function"?n:n.fn,a=typeof n=="function"?`index ${t}`:n.name||`index ${t}`;try{let s=u(r);if(s===void 0)break;if(s===null)throw new Error(`Middleware "${a}" returned null value.`);r=s;}catch(s){let l=s instanceof Error?s.message:String(s);throw new Error(`Middleware "${a}" threw an error: ${l}`)}}return r}function M(e,o){if(e===o)return true;if(!e||!o||typeof e!=typeof o)return false;if(Array.isArray(e)&&Array.isArray(o)){if(e.length!==o.length)return false;for(let r=0;r<e.length;r++)if(e[r]!==o[r])return false;return true}if(typeof e=="object"&&typeof o=="object"){let r=Object.keys(e),t=Object.keys(o);if(r.length!==t.length)return false;for(let n of r)if(!Object.prototype.hasOwnProperty.call(o,n)||e[n]!==o[n])return false;return true}return false}function D(e,o,r=""){if(typeof e=="object"&&e!==null&&typeof o=="object"&&o!==null){if(Array.isArray(e)&&Array.isArray(o)){if(e.length>0&&typeof e[0]=="object")for(let t=0;t<o.length;t++)D(e[0],o[t],`${r}[${t}]`);}else if(!Array.isArray(e)&&!Array.isArray(o)){let t=Object.keys(e),n=Object.keys(o),u=n.filter(a=>!t.includes(a));u.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${r||"root"}': ${u.join(", ")}. This might cause bugs.`),console.error("Expected keys:",t),console.error("Received keys:",n));for(let a of t)D(e[a],o[a],r?`${r}.${a}`:a);}}}var V=false,R=new Set,O=new Map,ne=0;function oe(e){let o=V;V=true;try{e();}finally{if(!o){V=false;let r=Array.from(R);R.clear(),r.forEach(t=>{let n=O.get(t);n&&n.notify();});}}}function k(e,o=[]){if(e===null)throw new Error("Initial value cannot be null.");let r=e,t=new Set,n=ne++,u=()=>{t.forEach(p=>p(r));};O.set(n,{notify:u});let a=()=>{t.size!==0&&(V?R.add(n):u());},s=()=>r,l=p=>{let y;typeof p=="function"?y=p(r):y=p,D(r,y);let b=N(y,o);b!==r&&(r=b,a());},c=p=>{if(typeof p!="function")throw new Error("Callback must be a function.");return t.add(p),p(r),()=>t.delete(p)};return {get:s,set:l,subscribe:c,derive:p=>{if(typeof p!="function")throw new Error("Derive function must be a function.");let y=p(r),b=k(y),d=c(()=>{let w=p(r);b.set(w);}),g=b.destroy;return b.destroy=()=>{d(),g();},b},reset:()=>{r=e,a();},destroy:()=>{t.clear(),r=e,R.delete(n),O.delete(n);}}}function z(e,o={}){let{initialData:r=null,onError:t,retryCount:n=0,retryDelay:u=1e3,refresh:a={},pagination:s,enabled:l=true}=o,{staleTime:c=0,cacheTime:f=5*60*1e3,refetchInterval:h}=a,x=!!s,p=s?.mode||"replace",y=e.length>0,b={loading:l&&!y,error:null,data:r,lastFetched:void 0,pagination:x?{page:s.initialPage||1,pageSize:s.pageSize||10}:void 0},d=k(b),g={},w=null,v=null,L=()=>{let i=d.get();return !i.lastFetched||c===0?true:Date.now()-i.lastFetched>c},G=()=>{d.set({...d.get(),data:r,lastFetched:void 0});},Q=()=>{v&&clearTimeout(v),f>0&&(v=setTimeout(G,f));},m=async(i,T=n,A=false)=>{if(!l||(i!==void 0&&(g={...g,...i}),!A&&!L()&&d.get().data!==null))return;let C=d.get();d.set({...C,loading:true,error:null});try{let S={...g};x&&C.pagination&&(S.page=C.pagination.page,S.pageSize=C.pagination.pageSize);let P=y?await e(S):await e(),E,H,$;if(P&&typeof P=="object"&&"data"in P){let j=P;E=j.data,H=j.total,$=j.hasMore;}else E=P;x&&p==="accumulate"&&C.data&&Array.isArray(C.data)&&Array.isArray(E)&&(E=[...C.data,...E]);let X=Date.now();d.set({loading:!1,error:null,data:E,lastFetched:X,pagination:x?{...C.pagination,total:H,hasMore:$}:void 0}),Q();}catch(S){if(T>0)return await new Promise(E=>setTimeout(E,u)),m(i,T-1,A);let P=d.get();d.set({loading:false,error:S,data:P.data,lastFetched:P.lastFetched,pagination:P.pagination}),t&&t(S);}};h&&h>0&&l&&(w=setInterval(()=>{l&&m(void 0,0,false);},h)),l&&!y&&m();let F=()=>{w&&(clearInterval(w),w=null),v&&(clearTimeout(v),v=null);},I={...d,reload:async i=>{await m(i,n,true);},refresh:async i=>{await m(i,n,false);},mutate:i=>{let T=d.get(),A=i(T.data);d.set({...T,data:A});},reset:()=>{F(),g={},d.set({...b,loading:l&&!y}),l&&!y&&(m(),h&&h>0&&(w=setInterval(()=>{l&&m(void 0,0,false);},h)));},cleanup:F,setParams:i=>{g={...g,...i},l&&m(i,n,true);}};return x?{...I,nextPage:async()=>{let i=d.get();i.pagination&&i.pagination.hasMore!==false&&(d.set({...i,pagination:{...i.pagination,page:i.pagination.page+1}}),await m(g,n,true));},prevPage:async()=>{let i=d.get();!i.pagination||i.pagination.page<=1||(d.set({...i,pagination:{...i.pagination,page:i.pagination.page-1}}),await m(g,n,true));},goToPage:async i=>{let T=d.get();!T.pagination||i<1||(d.set({...T,pagination:{...T.pagination,page:i}}),await m(g,n,true));},resetPagination:async()=>{let i=d.get();if(!i.pagination)return;let T=s?.initialPage||1;d.set({...i,data:p==="accumulate"?r:i.data,pagination:{...i.pagination,page:T}}),await m(g,n,true);}}:I}function ae(e,o={}){let{pageSize:r=10,staleTime:t,cacheTime:n,retryCount:u,retryDelay:a,onError:s}=o;return z(e,{pagination:{pageSize:r,mode:"accumulate",initialPage:1},refresh:{staleTime:t,cacheTime:n},retryCount:u,retryDelay:a,onError:s})}function se(e,o){let r=e.map(c=>c.get()),t=o(...r),n=k(t),u=n.set,a=false,s=()=>{let c=false;for(let f=0;f<e.length;f++){let h=e[f].get();h!==r[f]&&(r[f]=h,c=true);}if(c){let f=o(...r);f!==t&&(typeof f!="object"||typeof t!="object"||!M(f,t))&&(t=f,u(f)),a=false;}},l=e.map(c=>c.subscribe(()=>{a=true,s();}));return {...n,get:()=>(a&&s(),t),recompute:s,isDirty:()=>a,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(c=>{typeof c.reset=="function"&&c.reset();}),a=true,s(),t),destroy:()=>{l.forEach(c=>c()),n.destroy?.();}}}function q(e,o,r={}){let{useShallowEqual:t=false}=r,n=e.get(),u=o(n),a=k(u),s=()=>{let c=e.get(),f=o(c);n=c,(t?!M(f,u):f!==u)&&(u=f,a.set(f));},l=e.subscribe(s);return {get:()=>a.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:a.subscribe,derive:c=>q(a,c,r),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),a.destroy();}}}var U={};Z(U,{logger:()=>K,nonNegativeValidator:()=>W,withHistory:()=>B,withPersistence:()=>J});var K=e=>(console.log("Setting value:",e),e);var W=e=>{if(e<0)throw new Error("Value must be non-negative!");return e};function B(e,o={}){let{maxHistory:r=100}=o,t=[e.get()],n=0,u=false,a={...e,set:s=>{if(u){e.set(s);return}let l;if(typeof s=="function"){let c=e.get();l=s(c);}else l=s;if(t.splice(n+1),t.push(l),t.length>r){console.warn("History limit reached. Removing oldest entries.");let c=t.length-r;t.splice(0,c),n=Math.max(0,n-c);}n=t.length-1,e.set(l);},undo:()=>{a.canUndo()&&(u=true,n--,a.set(t[n]),u=false);},redo:()=>{a.canRedo()&&(u=true,n++,a.set(t[n]),u=false);},canUndo:()=>n>0,canRedo:()=>n<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let s=e.get();t.length=0,t.push(s),n=0;},destroy:()=>{t.length=0,e.destroy();}};return a}function J(e,o){let{key:r,storage:t=localStorage,serialize:n=JSON.stringify,deserialize:u=JSON.parse}=o;try{let a=t.getItem(r);if(a){let s=u(a);e.set(s);}}catch(a){console.error("Failed to load persisted state:",a);}return e.subscribe(a=>{try{let s=n(a);t.setItem(r,s);}catch(s){console.log("Failed to persist chunk",s);}}),e}exports.asyncChunk=z;exports.batch=oe;exports.chunk=k;exports.combineAsyncChunks=re;exports.computed=se;exports.infiniteAsyncChunk=ae;exports.isChunk=ee;exports.isValidChunkValue=_;exports.middleware=U;exports.once=te;exports.select=q;
|
package/dist/index.d.cts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var Z=(e,
|
|
1
|
+
var Y=Object.defineProperty;var Z=(e,o)=>{for(var r in o)Y(e,r,{get:o[r],enumerable:true});};function _(e){return e!==null}function ee(e){if(!e||typeof e!="object")return false;let o=e;return ["get","set","subscribe","derive","reset","destroy"].every(t=>typeof o[t]=="function")}function te(e){let o=false,r;return ()=>(o||(r=e(),o=true),r)}function re(e){let o=Object.keys(e).reduce((n,u)=>(n[u]=null,n),{}),r={loading:Object.keys(e).length>0,error:null,errors:{},data:o},t=k(r);return Object.entries(e).forEach(([n,u])=>{u.subscribe(a=>{let s=t.get(),l=false,c=null,f={};Object.entries(e).forEach(([h,x])=>{let p=x.get();p.loading&&(l=true),p.error&&(c||(c=p.error),f[h]=p.error);}),t.set({loading:l,error:c,errors:f,data:{...s.data,[n]:a.data}});});}),t}function N(e,o){if(e===null)throw new Error("Value cannot be null.");let r=e;for(let t=0;t<o.length;t++){let n=o[t],u=typeof n=="function"?n:n.fn,a=typeof n=="function"?`index ${t}`:n.name||`index ${t}`;try{let s=u(r);if(s===void 0)break;if(s===null)throw new Error(`Middleware "${a}" returned null value.`);r=s;}catch(s){let l=s instanceof Error?s.message:String(s);throw new Error(`Middleware "${a}" threw an error: ${l}`)}}return r}function M(e,o){if(e===o)return true;if(!e||!o||typeof e!=typeof o)return false;if(Array.isArray(e)&&Array.isArray(o)){if(e.length!==o.length)return false;for(let r=0;r<e.length;r++)if(e[r]!==o[r])return false;return true}if(typeof e=="object"&&typeof o=="object"){let r=Object.keys(e),t=Object.keys(o);if(r.length!==t.length)return false;for(let n of r)if(!Object.prototype.hasOwnProperty.call(o,n)||e[n]!==o[n])return false;return true}return false}function D(e,o,r=""){if(typeof e=="object"&&e!==null&&typeof o=="object"&&o!==null){if(Array.isArray(e)&&Array.isArray(o)){if(e.length>0&&typeof e[0]=="object")for(let t=0;t<o.length;t++)D(e[0],o[t],`${r}[${t}]`);}else if(!Array.isArray(e)&&!Array.isArray(o)){let t=Object.keys(e),n=Object.keys(o),u=n.filter(a=>!t.includes(a));u.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${r||"root"}': ${u.join(", ")}. This might cause bugs.`),console.error("Expected keys:",t),console.error("Received keys:",n));for(let a of t)D(e[a],o[a],r?`${r}.${a}`:a);}}}var V=false,R=new Set,O=new Map,ne=0;function oe(e){let o=V;V=true;try{e();}finally{if(!o){V=false;let r=Array.from(R);R.clear(),r.forEach(t=>{let n=O.get(t);n&&n.notify();});}}}function k(e,o=[]){if(e===null)throw new Error("Initial value cannot be null.");let r=e,t=new Set,n=ne++,u=()=>{t.forEach(p=>p(r));};O.set(n,{notify:u});let a=()=>{t.size!==0&&(V?R.add(n):u());},s=()=>r,l=p=>{let y;typeof p=="function"?y=p(r):y=p,D(r,y);let b=N(y,o);b!==r&&(r=b,a());},c=p=>{if(typeof p!="function")throw new Error("Callback must be a function.");return t.add(p),p(r),()=>t.delete(p)};return {get:s,set:l,subscribe:c,derive:p=>{if(typeof p!="function")throw new Error("Derive function must be a function.");let y=p(r),b=k(y),d=c(()=>{let w=p(r);b.set(w);}),g=b.destroy;return b.destroy=()=>{d(),g();},b},reset:()=>{r=e,a();},destroy:()=>{t.clear(),r=e,R.delete(n),O.delete(n);}}}function z(e,o={}){let{initialData:r=null,onError:t,retryCount:n=0,retryDelay:u=1e3,refresh:a={},pagination:s,enabled:l=true}=o,{staleTime:c=0,cacheTime:f=5*60*1e3,refetchInterval:h}=a,x=!!s,p=s?.mode||"replace",y=e.length>0,b={loading:l&&!y,error:null,data:r,lastFetched:void 0,pagination:x?{page:s.initialPage||1,pageSize:s.pageSize||10}:void 0},d=k(b),g={},w=null,v=null,L=()=>{let i=d.get();return !i.lastFetched||c===0?true:Date.now()-i.lastFetched>c},G=()=>{d.set({...d.get(),data:r,lastFetched:void 0});},Q=()=>{v&&clearTimeout(v),f>0&&(v=setTimeout(G,f));},m=async(i,T=n,A=false)=>{if(!l||(i!==void 0&&(g={...g,...i}),!A&&!L()&&d.get().data!==null))return;let C=d.get();d.set({...C,loading:true,error:null});try{let S={...g};x&&C.pagination&&(S.page=C.pagination.page,S.pageSize=C.pagination.pageSize);let P=y?await e(S):await e(),E,H,$;if(P&&typeof P=="object"&&"data"in P){let j=P;E=j.data,H=j.total,$=j.hasMore;}else E=P;x&&p==="accumulate"&&C.data&&Array.isArray(C.data)&&Array.isArray(E)&&(E=[...C.data,...E]);let X=Date.now();d.set({loading:!1,error:null,data:E,lastFetched:X,pagination:x?{...C.pagination,total:H,hasMore:$}:void 0}),Q();}catch(S){if(T>0)return await new Promise(E=>setTimeout(E,u)),m(i,T-1,A);let P=d.get();d.set({loading:false,error:S,data:P.data,lastFetched:P.lastFetched,pagination:P.pagination}),t&&t(S);}};h&&h>0&&l&&(w=setInterval(()=>{l&&m(void 0,0,false);},h)),l&&!y&&m();let F=()=>{w&&(clearInterval(w),w=null),v&&(clearTimeout(v),v=null);},I={...d,reload:async i=>{await m(i,n,true);},refresh:async i=>{await m(i,n,false);},mutate:i=>{let T=d.get(),A=i(T.data);d.set({...T,data:A});},reset:()=>{F(),g={},d.set({...b,loading:l&&!y}),l&&!y&&(m(),h&&h>0&&(w=setInterval(()=>{l&&m(void 0,0,false);},h)));},cleanup:F,setParams:i=>{g={...g,...i},l&&m(i,n,true);}};return x?{...I,nextPage:async()=>{let i=d.get();i.pagination&&i.pagination.hasMore!==false&&(d.set({...i,pagination:{...i.pagination,page:i.pagination.page+1}}),await m(g,n,true));},prevPage:async()=>{let i=d.get();!i.pagination||i.pagination.page<=1||(d.set({...i,pagination:{...i.pagination,page:i.pagination.page-1}}),await m(g,n,true));},goToPage:async i=>{let T=d.get();!T.pagination||i<1||(d.set({...T,pagination:{...T.pagination,page:i}}),await m(g,n,true));},resetPagination:async()=>{let i=d.get();if(!i.pagination)return;let T=s?.initialPage||1;d.set({...i,data:p==="accumulate"?r:i.data,pagination:{...i.pagination,page:T}}),await m(g,n,true);}}:I}function ae(e,o={}){let{pageSize:r=10,staleTime:t,cacheTime:n,retryCount:u,retryDelay:a,onError:s}=o;return z(e,{pagination:{pageSize:r,mode:"accumulate",initialPage:1},refresh:{staleTime:t,cacheTime:n},retryCount:u,retryDelay:a,onError:s})}function se(e,o){let r=e.map(c=>c.get()),t=o(...r),n=k(t),u=n.set,a=false,s=()=>{let c=false;for(let f=0;f<e.length;f++){let h=e[f].get();h!==r[f]&&(r[f]=h,c=true);}if(c){let f=o(...r);f!==t&&(typeof f!="object"||typeof t!="object"||!M(f,t))&&(t=f,u(f)),a=false;}},l=e.map(c=>c.subscribe(()=>{a=true,s();}));return {...n,get:()=>(a&&s(),t),recompute:s,isDirty:()=>a,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(c=>{typeof c.reset=="function"&&c.reset();}),a=true,s(),t),destroy:()=>{l.forEach(c=>c()),n.destroy?.();}}}function q(e,o,r={}){let{useShallowEqual:t=false}=r,n=e.get(),u=o(n),a=k(u),s=()=>{let c=e.get(),f=o(c);n=c,(t?!M(f,u):f!==u)&&(u=f,a.set(f));},l=e.subscribe(s);return {get:()=>a.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:a.subscribe,derive:c=>q(a,c,r),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),a.destroy();}}}var U={};Z(U,{logger:()=>K,nonNegativeValidator:()=>W,withHistory:()=>B,withPersistence:()=>J});var K=e=>(console.log("Setting value:",e),e);var W=e=>{if(e<0)throw new Error("Value must be non-negative!");return e};function B(e,o={}){let{maxHistory:r=100}=o,t=[e.get()],n=0,u=false,a={...e,set:s=>{if(u){e.set(s);return}let l;if(typeof s=="function"){let c=e.get();l=s(c);}else l=s;if(t.splice(n+1),t.push(l),t.length>r){console.warn("History limit reached. Removing oldest entries.");let c=t.length-r;t.splice(0,c),n=Math.max(0,n-c);}n=t.length-1,e.set(l);},undo:()=>{a.canUndo()&&(u=true,n--,a.set(t[n]),u=false);},redo:()=>{a.canRedo()&&(u=true,n++,a.set(t[n]),u=false);},canUndo:()=>n>0,canRedo:()=>n<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let s=e.get();t.length=0,t.push(s),n=0;},destroy:()=>{t.length=0,e.destroy();}};return a}function J(e,o){let{key:r,storage:t=localStorage,serialize:n=JSON.stringify,deserialize:u=JSON.parse}=o;try{let a=t.getItem(r);if(a){let s=u(a);e.set(s);}}catch(a){console.error("Failed to load persisted state:",a);}return e.subscribe(a=>{try{let s=n(a);t.setItem(r,s);}catch(s){console.log("Failed to persist chunk",s);}}),e}export{z as asyncChunk,oe as batch,k as chunk,re as combineAsyncChunks,se as computed,ae as infiniteAsyncChunk,ee as isChunk,_ as isValidChunkValue,U as middleware,te as once,q as select};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var d=e=>(console.log("Setting value:",e),e);var u=e=>{if(e<0)throw new Error("Value must be non-negative!");return e};function g(e,a={}){let{maxHistory:s=100}=a,t=[e.get()],r=0,n=false,o={...e,set:i=>{if(n){e.set(i);return}let l;if(typeof i=="function"){let c=e.get();l=i(c);}else l=i;if(t.splice(r+1),t.push(l),t.length>s){console.warn("History limit reached. Removing oldest entries.");let c=t.length-s;t.splice(0,c),r=Math.max(0,r-c);}r=t.length-1,e.set(l);},undo:()=>{o.canUndo()&&(n=true,r--,o.set(t[r]),n=false);},redo:()=>{o.canRedo()&&(n=true,r++,o.set(t[r]),n=false);},canUndo:()=>r>0,canRedo:()=>r<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let i=e.get();t.length=0,t.push(i),r=0;},destroy:()=>{t.length=0,e.destroy();}};return o}function h(e,a){let{key:s,storage:t=localStorage,serialize:r=JSON.stringify,deserialize:n=JSON.parse}=a;try{let o=t.getItem(s);if(o){let i=n(o);e.set(i);}}catch(o){console.error("Failed to load persisted state:",o);}return e.subscribe(o=>{try{let i=r(o);t.setItem(s,i);}catch(i){console.log("Failed to persist chunk",i);}}),e}exports.logger=d;exports.nonNegativeValidator=u;exports.withHistory=g;exports.withPersistence=h;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { M as Middleware, C as Chunk } from '../core-DMY69lzg.cjs';
|
|
2
|
+
|
|
3
|
+
declare const logger: Middleware<any>;
|
|
4
|
+
|
|
5
|
+
declare const nonNegativeValidator: Middleware<number>;
|
|
6
|
+
|
|
7
|
+
interface ChunkWithHistory<T> extends Chunk<T> {
|
|
8
|
+
/**
|
|
9
|
+
* Reverts to the previous state (if available).
|
|
10
|
+
*/
|
|
11
|
+
undo: () => void;
|
|
12
|
+
/**
|
|
13
|
+
* Moves to the next state (if available).
|
|
14
|
+
*/
|
|
15
|
+
redo: () => void;
|
|
16
|
+
/**
|
|
17
|
+
* Returns true if there is a previous state to revert to.
|
|
18
|
+
*/
|
|
19
|
+
canUndo: () => boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Returns true if there is a next state to move to.
|
|
22
|
+
*/
|
|
23
|
+
canRedo: () => boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Returns an array of all the values in the history.
|
|
26
|
+
*/
|
|
27
|
+
getHistory: () => T[];
|
|
28
|
+
/**
|
|
29
|
+
* Clears the history, keeping only the current value.
|
|
30
|
+
*/
|
|
31
|
+
clearHistory: () => void;
|
|
32
|
+
}
|
|
33
|
+
declare function withHistory<T>(baseChunk: Chunk<T>, options?: {
|
|
34
|
+
maxHistory?: number;
|
|
35
|
+
}): ChunkWithHistory<T>;
|
|
36
|
+
|
|
37
|
+
interface PersistOptions<T> {
|
|
38
|
+
key: string;
|
|
39
|
+
storage?: Storage;
|
|
40
|
+
serialize?: (value: T) => string;
|
|
41
|
+
deserialize?: (value: string) => T;
|
|
42
|
+
}
|
|
43
|
+
declare function withPersistence<T>(baseChunk: Chunk<T>, options: PersistOptions<T>): Chunk<T>;
|
|
44
|
+
|
|
45
|
+
export { logger, nonNegativeValidator, withHistory, withPersistence };
|
package/dist/middleware/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var d=
|
|
1
|
+
var d=e=>(console.log("Setting value:",e),e);var u=e=>{if(e<0)throw new Error("Value must be non-negative!");return e};function g(e,a={}){let{maxHistory:s=100}=a,t=[e.get()],r=0,n=false,o={...e,set:i=>{if(n){e.set(i);return}let l;if(typeof i=="function"){let c=e.get();l=i(c);}else l=i;if(t.splice(r+1),t.push(l),t.length>s){console.warn("History limit reached. Removing oldest entries.");let c=t.length-s;t.splice(0,c),r=Math.max(0,r-c);}r=t.length-1,e.set(l);},undo:()=>{o.canUndo()&&(n=true,r--,o.set(t[r]),n=false);},redo:()=>{o.canRedo()&&(n=true,r++,o.set(t[r]),n=false);},canUndo:()=>r>0,canRedo:()=>r<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let i=e.get();t.length=0,t.push(i),r=0;},destroy:()=>{t.length=0,e.destroy();}};return o}function h(e,a){let{key:s,storage:t=localStorage,serialize:r=JSON.stringify,deserialize:n=JSON.parse}=a;try{let o=t.getItem(s);if(o){let i=n(o);e.set(i);}}catch(o){console.error("Failed to load persisted state:",o);}return e.subscribe(o=>{try{let i=r(o);t.setItem(s,i);}catch(i){console.log("Failed to persist chunk",i);}}),e}export{d as logger,u as nonNegativeValidator,g as withHistory,h as withPersistence};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var react=require('react');var U=new Set,V=new Map,N=0;function T(e,r=[]){if(e===null)throw new Error("Initial value cannot be null.");let t=e,n=new Set,s=N++,i=()=>{n.forEach(f=>f(t));};V.set(s,{notify:i});let o=()=>{n.size!==0&&(i());},u=()=>t,l=f=>{let h;typeof f=="function"?h=f(t):h=f,E(t,h);let p=j(h,r);p!==t&&(t=p,o());},a=f=>{if(typeof f!="function")throw new Error("Callback must be a function.");return n.add(f),f(t),()=>n.delete(f)};return {get:u,set:l,subscribe:a,derive:f=>{if(typeof f!="function")throw new Error("Derive function must be a function.");let h=f(t),p=T(h),b=a(()=>{let v=f(t);p.set(v);}),A=p.destroy;return p.destroy=()=>{b(),A();},p},reset:()=>{t=e,o();},destroy:()=>{n.clear(),t=e,U.delete(s),V.delete(s);}}}function j(e,r){if(e===null)throw new Error("Value cannot be null.");let t=e;for(let n=0;n<r.length;n++){let s=r[n],i=typeof s=="function"?s:s.fn,o=typeof s=="function"?`index ${n}`:s.name||`index ${n}`;try{let u=i(t);if(u===void 0)break;if(u===null)throw new Error(`Middleware "${o}" returned null value.`);t=u;}catch(u){let l=u instanceof Error?u.message:String(u);throw new Error(`Middleware "${o}" threw an error: ${l}`)}}return t}function x(e,r){if(e===r)return true;if(!e||!r||typeof e!=typeof r)return false;if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return false;for(let t=0;t<e.length;t++)if(e[t]!==r[t])return false;return true}if(typeof e=="object"&&typeof r=="object"){let t=Object.keys(e),n=Object.keys(r);if(t.length!==n.length)return false;for(let s of t)if(!Object.prototype.hasOwnProperty.call(r,s)||e[s]!==r[s])return false;return true}return false}function E(e,r,t=""){if(typeof e=="object"&&e!==null&&typeof r=="object"&&r!==null){if(Array.isArray(e)&&Array.isArray(r)){if(e.length>0&&typeof e[0]=="object")for(let n=0;n<r.length;n++)E(e[0],r[n],`${t}[${n}]`);}else if(!Array.isArray(e)&&!Array.isArray(r)){let n=Object.keys(e),s=Object.keys(r),i=s.filter(o=>!n.includes(o));i.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${t||"root"}': ${i.join(", ")}. This might cause bugs.`),console.error("Expected keys:",n),console.error("Received keys:",s));for(let o of n)E(e[o],r[o],t?`${t}.${o}`:o);}}}function R(e,r,t={}){let{useShallowEqual:n=false}=t,s=e.get(),i=r(s),o=T(i),u=()=>{let a=e.get(),c=r(a);s=a,(n?!x(c,i):c!==i)&&(i=c,o.set(c));},l=e.subscribe(u);return {get:()=>o.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:o.subscribe,derive:a=>R(o,a,t),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),o.destroy();}}}function k(e,r){let t=r?R(e,r):e,[n,s]=react.useState(()=>t.get());react.useEffect(()=>{let l=t.subscribe(a=>{s(()=>a);});return ()=>l()},[t]);let i=react.useCallback(l=>{e.set(l);},[e]),o=react.useCallback(()=>{e.reset();},[e]),u=react.useCallback(()=>{e.destroy();},[e]);return [n,i,o,u]}function J(e,r){let t=react.useRef(r);react.useEffect(()=>{t.current=r;},[r]);let n=react.useMemo(()=>e.derive(i=>t.current(i)),[e]),[s]=k(n);return s}function K(e,r){let t=e.map(a=>a.get()),n=r(...t),s=T(n),i=s.set,o=false,u=()=>{let a=false;for(let c=0;c<e.length;c++){let y=e[c].get();y!==t[c]&&(t[c]=y,a=true);}if(a){let c=r(...t);c!==n&&(typeof c!="object"||typeof n!="object"||!x(c,n))&&(n=c,i(c)),o=false;}},l=e.map(a=>a.subscribe(()=>{o=true,u();}));return {...s,get:()=>(o&&u(),n),recompute:u,isDirty:()=>o,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(a=>{typeof a.reset=="function"&&a.reset();}),o=true,u(),n),destroy:()=>{l.forEach(a=>a()),s.destroy?.();}}}function Z(e,r){let t=react.useMemo(()=>K(e,r),[...e]),[n,s]=react.useState(()=>t.get());return react.useEffect(()=>{let i=t.subscribe(o=>{s(o);});return ()=>{i();}},[t]),n}function D(e,r){let[t]=k(e,r);return t}function ee(e,r){let t=react.useMemo(()=>n=>n[r],[r]);return D(e,t)}function ne(e){let[r,t]=react.useState(()=>e.map(n=>n.get()));return react.useEffect(()=>{let n=e.map((s,i)=>s.subscribe(o=>{t(u=>{let l=[...u];return l[i]=o,l});}));return ()=>{n.forEach(s=>s());}},[e]),r}function C(e){return "nextPage"in e}function W(e){return "setParams"in e}function O(e,r){let{initialParams:t,fetchOnMount:n}=typeof r=="object"&&("initialParams"in r||"fetchOnMount"in r)?r:{initialParams:r,fetchOnMount:false},[s,i]=react.useState(()=>e.get()),o=react.useRef(null);(!o.current||o.current.chunk!==e)&&(o.current={chunk:e,initialParams:t,fetchOnMount:n}),react.useEffect(()=>e.subscribe(g=>{i(g);}),[e]),react.useEffect(()=>{let d=o.current,g=d?.initialParams,q=d?.fetchOnMount;g&&W(e)?e.setParams(g):q&&!g&&e.reload();},[e]),react.useEffect(()=>()=>{e.cleanup();},[e]);let u=react.useCallback(d=>e.reload(d),[e]),l=react.useCallback(d=>e.refresh(d),[e]),a=react.useCallback(d=>e.mutate(d),[e]),c=react.useCallback(()=>e.reset(),[e]),y=react.useCallback(d=>{"setParams"in e&&e.setParams(d);},[e]),P=react.useCallback(()=>C(e)?e.nextPage():Promise.resolve(),[e]),f=react.useCallback(()=>C(e)?e.prevPage():Promise.resolve(),[e]),h=react.useCallback(d=>C(e)?e.goToPage(d):Promise.resolve(),[e]),p=react.useCallback(()=>C(e)?e.resetPagination():Promise.resolve(),[e]),{data:b,loading:A,error:v,lastFetched:$,pagination:I}=s,w={data:b,loading:A,error:v,lastFetched:$,reload:u,refresh:l,mutate:a,reset:c};if(W(e)&&(w.setParams=y),C(e)){let d=w;d.pagination=I,d.nextPage=P,d.prevPage=f,d.goToPage=h,d.resetPagination=p;}return w}function ce(e,r={}){let{initialParams:t,autoLoad:n=true,threshold:s=1,...i}=r,o=react.useRef(null),u=O(e,{initialParams:{...t,page:1,pageSize:e.get().pagination?.pageSize||10},...i}),{loading:l,pagination:a,nextPage:c}=u;react.useEffect(()=>{if(!n)return;let P=new IntersectionObserver(h=>{h[0].isIntersecting&&!l&&a?.hasMore&&c();},{threshold:s}),f=o.current;return f&&P.observe(f),()=>{f&&P.unobserve(f);}},[l,a?.hasMore,c,n,s]);let y=react.useCallback(()=>{!l&&a?.hasMore&&c();},[l,a?.hasMore,c]);return {...u,loadMore:y,observerTarget:o,hasMore:a?.hasMore??false,isFetchingMore:l&&(u.data?.length??0)>0}}exports.useAsyncChunk=O;exports.useChunk=k;exports.useChunkProperty=ee;exports.useChunkValue=D;exports.useChunkValues=ne;exports.useComputed=Z;exports.useDerive=J;exports.useInfiniteAsyncChunk=ce;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { C as Chunk } from '../core-DMY69lzg.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A lightweight hook that subscribes to a chunk and returns its current value, along with setters, selector, reset and destroy.
|
|
5
|
+
* Ensures reactivity and prevents unnecessary re-renders.
|
|
6
|
+
*/
|
|
7
|
+
declare function useChunk<T, S = T>(chunk: Chunk<T>, selector?: (value: T) => S): readonly [S, (valueOrUpdater: T | ((currentValue: T) => T)) => void, () => void, () => void];
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A hook for creating a read-only derived value from a chunk.
|
|
11
|
+
* Ensures reactivity and updates when the source chunk changes.
|
|
12
|
+
*/
|
|
13
|
+
declare function useDerive<T, D>(chunk: Chunk<T>, fn: (value: T) => D): D;
|
|
14
|
+
|
|
15
|
+
type ChunkValue<T> = T extends Chunk<infer U> ? U : never;
|
|
16
|
+
type DependencyValues<T extends Chunk<any>[]> = {
|
|
17
|
+
[K in keyof T]: T[K] extends Chunk<any> ? ChunkValue<T[K]> : never;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A hook that computes a value based on multiple chunks.
|
|
22
|
+
* Automatically re-computes when any dependency changes.
|
|
23
|
+
*/
|
|
24
|
+
declare function useComputed<TDeps extends Chunk<any>[], TResult>(dependencies: [...TDeps], computeFn: (...args: DependencyValues<TDeps>) => TResult): TResult;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A lightweight hook that subscribes to a chunk and returns only its current value.
|
|
28
|
+
* Useful for read-only components that don't need to update the chunk.
|
|
29
|
+
*/
|
|
30
|
+
declare function useChunkValue<T, S = T>(chunk: Chunk<T>, selector?: (value: T) => S): S;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A hook that subscribes to a specific property of a chunk.
|
|
34
|
+
* This optimizes renders by only updating when the selected property changes.
|
|
35
|
+
*/
|
|
36
|
+
declare function useChunkProperty<T, K extends keyof T>(chunk: Chunk<T>, property: K): T[K];
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Hook to read values from multiple chunks at once.
|
|
40
|
+
* Only re-renders when any of the chunk values change.
|
|
41
|
+
*/
|
|
42
|
+
declare function useChunkValues<T extends Chunk<any>[]>(chunks: [...T]): {
|
|
43
|
+
[K in keyof T]: T[K] extends Chunk<infer U> ? U : never;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
interface AsyncState<T, E extends Error> {
|
|
47
|
+
loading: boolean;
|
|
48
|
+
error: E | null;
|
|
49
|
+
data: T | null;
|
|
50
|
+
lastFetched?: number;
|
|
51
|
+
}
|
|
52
|
+
interface PaginationState {
|
|
53
|
+
page: number;
|
|
54
|
+
pageSize: number;
|
|
55
|
+
total?: number;
|
|
56
|
+
hasMore?: boolean;
|
|
57
|
+
}
|
|
58
|
+
interface AsyncStateWithPagination<T, E extends Error> extends AsyncState<T, E> {
|
|
59
|
+
pagination?: PaginationState;
|
|
60
|
+
}
|
|
61
|
+
interface AsyncChunk<T, E extends Error = Error> extends Chunk<AsyncStateWithPagination<T, E>> {
|
|
62
|
+
/** Force reload data */
|
|
63
|
+
reload: (params?: any) => Promise<void>;
|
|
64
|
+
/** Smart refresh - respects stale time */
|
|
65
|
+
refresh: (params?: any) => Promise<void>;
|
|
66
|
+
/** Mutate data directly */
|
|
67
|
+
mutate: (mutator: (currentData: T | null) => T) => void;
|
|
68
|
+
/** Reset to initial state */
|
|
69
|
+
reset: () => void;
|
|
70
|
+
/** Clean up intervals */
|
|
71
|
+
cleanup: () => void;
|
|
72
|
+
}
|
|
73
|
+
interface PaginatedAsyncChunk<T, E extends Error = Error> extends AsyncChunk<T, E> {
|
|
74
|
+
/** Load next page */
|
|
75
|
+
nextPage: () => Promise<void>;
|
|
76
|
+
/** Load previous page */
|
|
77
|
+
prevPage: () => Promise<void>;
|
|
78
|
+
/** Go to specific page */
|
|
79
|
+
goToPage: (page: number) => Promise<void>;
|
|
80
|
+
/** Reset pagination to first page */
|
|
81
|
+
resetPagination: () => Promise<void>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface UseAsyncChunkResult<T, E extends Error, P extends Record<string, any>> {
|
|
85
|
+
data: T | null;
|
|
86
|
+
loading: boolean;
|
|
87
|
+
error: E | null;
|
|
88
|
+
lastFetched?: number;
|
|
89
|
+
reload: (params?: Partial<P>) => Promise<void>;
|
|
90
|
+
refresh: (params?: Partial<P>) => Promise<void>;
|
|
91
|
+
mutate: (mutator: (currentData: T | null) => T) => void;
|
|
92
|
+
reset: () => void;
|
|
93
|
+
}
|
|
94
|
+
interface UseAsyncChunkResultWithParams<T, E extends Error, P extends Record<string, any>> extends UseAsyncChunkResult<T, E, P> {
|
|
95
|
+
setParams: (params: Partial<P>) => void;
|
|
96
|
+
}
|
|
97
|
+
interface UseAsyncChunkResultWithPagination<T, E extends Error, P extends Record<string, any>> extends UseAsyncChunkResult<T, E, P> {
|
|
98
|
+
pagination?: PaginationState;
|
|
99
|
+
nextPage: () => Promise<void>;
|
|
100
|
+
prevPage: () => Promise<void>;
|
|
101
|
+
goToPage: (page: number) => Promise<void>;
|
|
102
|
+
resetPagination: () => Promise<void>;
|
|
103
|
+
}
|
|
104
|
+
interface UseAsyncChunkResultWithParamsAndPagination<T, E extends Error, P extends Record<string, any>> extends UseAsyncChunkResultWithParams<T, E, P>, Omit<UseAsyncChunkResultWithPagination<T, E, P>, keyof UseAsyncChunkResult<T, E, P>> {
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* A hook that handles asynchronous state with built-in reactivity.
|
|
108
|
+
* Provides loading, error, and data states with full asyncChunk functionality.
|
|
109
|
+
*/
|
|
110
|
+
interface UseAsyncChunkOptions<P extends Record<string, any> = {}> {
|
|
111
|
+
/** Initial parameters to pass to the fetcher */
|
|
112
|
+
initialParams?: Partial<P>;
|
|
113
|
+
/** Force fetch on mount, even without params (default: false) */
|
|
114
|
+
fetchOnMount?: boolean;
|
|
115
|
+
}
|
|
116
|
+
declare function useAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: PaginatedAsyncChunk<T, E> & {
|
|
117
|
+
setParams: (params: Partial<P>) => void;
|
|
118
|
+
}, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResultWithParamsAndPagination<T, E, P>;
|
|
119
|
+
declare function useAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: PaginatedAsyncChunk<T, E>, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResultWithPagination<T, E, P>;
|
|
120
|
+
declare function useAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: AsyncChunk<T, E> & {
|
|
121
|
+
setParams: (params: Partial<P>) => void;
|
|
122
|
+
}, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResultWithParams<T, E, P>;
|
|
123
|
+
declare function useAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: AsyncChunk<T, E>, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResult<T, E, P>;
|
|
124
|
+
|
|
125
|
+
interface UseInfiniteAsyncChunkOptions<P extends Record<string, any>> extends Omit<UseAsyncChunkOptions<P>, 'initialParams'> {
|
|
126
|
+
/** Initial parameters (page and pageSize added automatically) */
|
|
127
|
+
initialParams?: Omit<Partial<P>, 'page' | 'pageSize'>;
|
|
128
|
+
/** Enable auto-loading on scroll (default: true) */
|
|
129
|
+
autoLoad?: boolean;
|
|
130
|
+
/** Intersection observer threshold (default: 1.0) */
|
|
131
|
+
threshold?: number;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Hook for infinite scroll functionality.
|
|
135
|
+
* Automatically loads more data when scrolling to the bottom.
|
|
136
|
+
*/
|
|
137
|
+
declare function useInfiniteAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: PaginatedAsyncChunk<T[], E> & {
|
|
138
|
+
setParams: (params: Partial<P>) => void;
|
|
139
|
+
}, options?: UseInfiniteAsyncChunkOptions<P>): any;
|
|
140
|
+
|
|
141
|
+
export { useAsyncChunk, useChunk, useChunkProperty, useChunkValue, useChunkValues, useComputed, useDerive, useInfiniteAsyncChunk };
|
package/dist/use-react/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {useState,useEffect,useCallback,useRef,useMemo}from'react';var
|
|
1
|
+
import {useState,useEffect,useCallback,useRef,useMemo}from'react';var U=new Set,V=new Map,N=0;function T(e,r=[]){if(e===null)throw new Error("Initial value cannot be null.");let t=e,n=new Set,s=N++,i=()=>{n.forEach(f=>f(t));};V.set(s,{notify:i});let o=()=>{n.size!==0&&(i());},u=()=>t,l=f=>{let h;typeof f=="function"?h=f(t):h=f,E(t,h);let p=j(h,r);p!==t&&(t=p,o());},a=f=>{if(typeof f!="function")throw new Error("Callback must be a function.");return n.add(f),f(t),()=>n.delete(f)};return {get:u,set:l,subscribe:a,derive:f=>{if(typeof f!="function")throw new Error("Derive function must be a function.");let h=f(t),p=T(h),b=a(()=>{let v=f(t);p.set(v);}),A=p.destroy;return p.destroy=()=>{b(),A();},p},reset:()=>{t=e,o();},destroy:()=>{n.clear(),t=e,U.delete(s),V.delete(s);}}}function j(e,r){if(e===null)throw new Error("Value cannot be null.");let t=e;for(let n=0;n<r.length;n++){let s=r[n],i=typeof s=="function"?s:s.fn,o=typeof s=="function"?`index ${n}`:s.name||`index ${n}`;try{let u=i(t);if(u===void 0)break;if(u===null)throw new Error(`Middleware "${o}" returned null value.`);t=u;}catch(u){let l=u instanceof Error?u.message:String(u);throw new Error(`Middleware "${o}" threw an error: ${l}`)}}return t}function x(e,r){if(e===r)return true;if(!e||!r||typeof e!=typeof r)return false;if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return false;for(let t=0;t<e.length;t++)if(e[t]!==r[t])return false;return true}if(typeof e=="object"&&typeof r=="object"){let t=Object.keys(e),n=Object.keys(r);if(t.length!==n.length)return false;for(let s of t)if(!Object.prototype.hasOwnProperty.call(r,s)||e[s]!==r[s])return false;return true}return false}function E(e,r,t=""){if(typeof e=="object"&&e!==null&&typeof r=="object"&&r!==null){if(Array.isArray(e)&&Array.isArray(r)){if(e.length>0&&typeof e[0]=="object")for(let n=0;n<r.length;n++)E(e[0],r[n],`${t}[${n}]`);}else if(!Array.isArray(e)&&!Array.isArray(r)){let n=Object.keys(e),s=Object.keys(r),i=s.filter(o=>!n.includes(o));i.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${t||"root"}': ${i.join(", ")}. This might cause bugs.`),console.error("Expected keys:",n),console.error("Received keys:",s));for(let o of n)E(e[o],r[o],t?`${t}.${o}`:o);}}}function R(e,r,t={}){let{useShallowEqual:n=false}=t,s=e.get(),i=r(s),o=T(i),u=()=>{let a=e.get(),c=r(a);s=a,(n?!x(c,i):c!==i)&&(i=c,o.set(c));},l=e.subscribe(u);return {get:()=>o.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:o.subscribe,derive:a=>R(o,a,t),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),o.destroy();}}}function k(e,r){let t=r?R(e,r):e,[n,s]=useState(()=>t.get());useEffect(()=>{let l=t.subscribe(a=>{s(()=>a);});return ()=>l()},[t]);let i=useCallback(l=>{e.set(l);},[e]),o=useCallback(()=>{e.reset();},[e]),u=useCallback(()=>{e.destroy();},[e]);return [n,i,o,u]}function J(e,r){let t=useRef(r);useEffect(()=>{t.current=r;},[r]);let n=useMemo(()=>e.derive(i=>t.current(i)),[e]),[s]=k(n);return s}function K(e,r){let t=e.map(a=>a.get()),n=r(...t),s=T(n),i=s.set,o=false,u=()=>{let a=false;for(let c=0;c<e.length;c++){let y=e[c].get();y!==t[c]&&(t[c]=y,a=true);}if(a){let c=r(...t);c!==n&&(typeof c!="object"||typeof n!="object"||!x(c,n))&&(n=c,i(c)),o=false;}},l=e.map(a=>a.subscribe(()=>{o=true,u();}));return {...s,get:()=>(o&&u(),n),recompute:u,isDirty:()=>o,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(a=>{typeof a.reset=="function"&&a.reset();}),o=true,u(),n),destroy:()=>{l.forEach(a=>a()),s.destroy?.();}}}function Z(e,r){let t=useMemo(()=>K(e,r),[...e]),[n,s]=useState(()=>t.get());return useEffect(()=>{let i=t.subscribe(o=>{s(o);});return ()=>{i();}},[t]),n}function D(e,r){let[t]=k(e,r);return t}function ee(e,r){let t=useMemo(()=>n=>n[r],[r]);return D(e,t)}function ne(e){let[r,t]=useState(()=>e.map(n=>n.get()));return useEffect(()=>{let n=e.map((s,i)=>s.subscribe(o=>{t(u=>{let l=[...u];return l[i]=o,l});}));return ()=>{n.forEach(s=>s());}},[e]),r}function C(e){return "nextPage"in e}function W(e){return "setParams"in e}function O(e,r){let{initialParams:t,fetchOnMount:n}=typeof r=="object"&&("initialParams"in r||"fetchOnMount"in r)?r:{initialParams:r,fetchOnMount:false},[s,i]=useState(()=>e.get()),o=useRef(null);(!o.current||o.current.chunk!==e)&&(o.current={chunk:e,initialParams:t,fetchOnMount:n}),useEffect(()=>e.subscribe(g=>{i(g);}),[e]),useEffect(()=>{let d=o.current,g=d?.initialParams,q=d?.fetchOnMount;g&&W(e)?e.setParams(g):q&&!g&&e.reload();},[e]),useEffect(()=>()=>{e.cleanup();},[e]);let u=useCallback(d=>e.reload(d),[e]),l=useCallback(d=>e.refresh(d),[e]),a=useCallback(d=>e.mutate(d),[e]),c=useCallback(()=>e.reset(),[e]),y=useCallback(d=>{"setParams"in e&&e.setParams(d);},[e]),P=useCallback(()=>C(e)?e.nextPage():Promise.resolve(),[e]),f=useCallback(()=>C(e)?e.prevPage():Promise.resolve(),[e]),h=useCallback(d=>C(e)?e.goToPage(d):Promise.resolve(),[e]),p=useCallback(()=>C(e)?e.resetPagination():Promise.resolve(),[e]),{data:b,loading:A,error:v,lastFetched:$,pagination:I}=s,w={data:b,loading:A,error:v,lastFetched:$,reload:u,refresh:l,mutate:a,reset:c};if(W(e)&&(w.setParams=y),C(e)){let d=w;d.pagination=I,d.nextPage=P,d.prevPage=f,d.goToPage=h,d.resetPagination=p;}return w}function ce(e,r={}){let{initialParams:t,autoLoad:n=true,threshold:s=1,...i}=r,o=useRef(null),u=O(e,{initialParams:{...t,page:1,pageSize:e.get().pagination?.pageSize||10},...i}),{loading:l,pagination:a,nextPage:c}=u;useEffect(()=>{if(!n)return;let P=new IntersectionObserver(h=>{h[0].isIntersecting&&!l&&a?.hasMore&&c();},{threshold:s}),f=o.current;return f&&P.observe(f),()=>{f&&P.unobserve(f);}},[l,a?.hasMore,c,n,s]);let y=useCallback(()=>{!l&&a?.hasMore&&c();},[l,a?.hasMore,c]);return {...u,loadMore:y,observerTarget:o,hasMore:a?.hasMore??false,isFetchingMore:l&&(u.data?.length??0)>0}}export{O as useAsyncChunk,k as useChunk,ee as useChunkProperty,D as useChunkValue,ne as useChunkValues,Z as useComputed,J as useDerive,ce as useInfiniteAsyncChunk};
|
package/package.json
CHANGED
|
@@ -1,119 +1,121 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "stunk",
|
|
3
|
-
"version": "2.
|
|
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(WIP), Svelte(Coming soon), and Vanilla JS/TS applications.",
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
"
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
"
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
"
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
"
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
"
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
"
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
"
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"state
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
"
|
|
60
|
-
"
|
|
61
|
-
"
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
"
|
|
92
|
-
"react
|
|
93
|
-
"
|
|
94
|
-
"
|
|
95
|
-
"
|
|
96
|
-
"
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
"
|
|
100
|
-
"
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
"react":
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
"
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
"
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
"
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
"
|
|
118
|
-
|
|
119
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "stunk",
|
|
3
|
+
"version": "2.8.1",
|
|
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(WIP), Svelte(Coming soon), and Vanilla JS/TS applications.",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"build": "tsup",
|
|
7
|
+
"build:watch": "tsup --watch",
|
|
8
|
+
"test": "vitest",
|
|
9
|
+
"test:react17": "npm install react@^17.0.0 react-dom@^17.0.0 @types/react@^17.0.0 && npm test",
|
|
10
|
+
"test:react18": "npm install react@^18.0.0 react-dom@^18.0.0 @types/react@^18.0.0 && npm test",
|
|
11
|
+
"test:react19": "npm install react@^19.0.0 react-dom@^19.0.0 @types/react@^19.0.0 && npm test",
|
|
12
|
+
"prepublishOnly": "npm run build && vitest run",
|
|
13
|
+
"prepare": "npm run build",
|
|
14
|
+
"lint": "eslint . --ext .js,.ts,.tsx,.vue"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/I-am-abdulazeez/stunk"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://stunk.dev/",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/I-am-abdulazeez/stunk/issues"
|
|
24
|
+
},
|
|
25
|
+
"main": "dist/index.js",
|
|
26
|
+
"module": "dist/index.js",
|
|
27
|
+
"types": "dist/index.d.ts",
|
|
28
|
+
"files": [
|
|
29
|
+
"dist"
|
|
30
|
+
],
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"import": "./dist/index.js",
|
|
35
|
+
"require": "./dist/index.cjs"
|
|
36
|
+
},
|
|
37
|
+
"./middleware": {
|
|
38
|
+
"types": "./dist/middleware/index.d.ts",
|
|
39
|
+
"import": "./dist/middleware/index.js"
|
|
40
|
+
},
|
|
41
|
+
"./react": {
|
|
42
|
+
"types": "./dist/use-react/index.d.ts",
|
|
43
|
+
"import": "./dist/use-react/index.js"
|
|
44
|
+
},
|
|
45
|
+
"./vue": {
|
|
46
|
+
"types": "./dist/use-vue/index.d.ts",
|
|
47
|
+
"import": "./dist/use-vue/index.js"
|
|
48
|
+
},
|
|
49
|
+
"./package.json": "./package.json"
|
|
50
|
+
},
|
|
51
|
+
"keywords": [
|
|
52
|
+
"state-management",
|
|
53
|
+
"atomic-state",
|
|
54
|
+
"chunk-based state",
|
|
55
|
+
"framework-agnostic",
|
|
56
|
+
"reactive state library",
|
|
57
|
+
"frontend state management",
|
|
58
|
+
"JavaScript state management",
|
|
59
|
+
"TypeScript state management",
|
|
60
|
+
"React state management",
|
|
61
|
+
"Vue state management",
|
|
62
|
+
"Svelte state management",
|
|
63
|
+
"recoil alternative",
|
|
64
|
+
"jotai alternative",
|
|
65
|
+
"zustand alternative",
|
|
66
|
+
"lightweight state management",
|
|
67
|
+
"state container",
|
|
68
|
+
"reusable state",
|
|
69
|
+
"efficient state updates",
|
|
70
|
+
"performance optimization",
|
|
71
|
+
"stunk",
|
|
72
|
+
"chunk"
|
|
73
|
+
],
|
|
74
|
+
"author": "AbdulAzeez",
|
|
75
|
+
"contributors": [
|
|
76
|
+
{
|
|
77
|
+
"name": "AbdulAzeez",
|
|
78
|
+
"url": "https://github.com/I-am-abdulazeez"
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
"name": "Chiboy",
|
|
82
|
+
"url": "https://github.com/chibx"
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
"name": "Idris",
|
|
86
|
+
"url": "https://github.com/Dreezy305"
|
|
87
|
+
}
|
|
88
|
+
],
|
|
89
|
+
"license": "MIT",
|
|
90
|
+
"devDependencies": {
|
|
91
|
+
"@testing-library/dom": "^10.4.0",
|
|
92
|
+
"@testing-library/react": "^16.2.0",
|
|
93
|
+
"@testing-library/vue": "^8.1.0",
|
|
94
|
+
"@types/react": "^18.0.0",
|
|
95
|
+
"@typescript-eslint/eslint-plugin": "^8.26.1",
|
|
96
|
+
"@typescript-eslint/parser": "^8.27.0",
|
|
97
|
+
"@vitejs/plugin-react": "^4.3.4",
|
|
98
|
+
"@vitejs/plugin-vue": "^5.2.1",
|
|
99
|
+
"eslint": "^9.22.0",
|
|
100
|
+
"eslint-plugin-react-hooks": "^5.2.0",
|
|
101
|
+
"jsdom": "^26.0.0",
|
|
102
|
+
"react": "^18.0.0",
|
|
103
|
+
"react-dom": "^18.0.0",
|
|
104
|
+
"tsup": "^8.5.0",
|
|
105
|
+
"typescript": "^5.0.0",
|
|
106
|
+
"vitest": "^3.0.8",
|
|
107
|
+
"vue": "^3.5.13"
|
|
108
|
+
},
|
|
109
|
+
"peerDependencies": {
|
|
110
|
+
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
|
111
|
+
"vue": "^3.5.13"
|
|
112
|
+
},
|
|
113
|
+
"peerDependenciesMeta": {
|
|
114
|
+
"react": {
|
|
115
|
+
"optional": true
|
|
116
|
+
},
|
|
117
|
+
"vue": {
|
|
118
|
+
"optional": true
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|