react-state-bucket 1.2.16 → 1.2.18

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
@@ -1,252 +1,252 @@
1
- <p align="center">
2
- <img width="120" src="https://raw.githubusercontent.com/devnax/react-state-bucket/main/logo.png" alt="React State Bucket logo">
3
- </p>
4
-
5
- <h1 align="center">React State Bucket</h1>
6
-
7
- Effortlessly manage React application states with **react-state-bucket**, a lightweight yet powerful state management library.
8
-
9
- ---
10
-
11
- ## 🚀 Features
12
-
13
- - **Global State Management**: Manage state across your entire React application with ease.
14
- - **CRUD Operations**: Create, Read, Update, and Delete state values effortlessly.
15
- - **Multiple Storage Options**: Store state in "memory," "session storage," "local storage," or "URL parameters."
16
- - **Reactivity**: Automatically update components when the state changes.
17
- - **Custom Hooks**: Seamlessly integrate with React’s functional components.
18
- - **TypeScript Support**: Fully typed for a better development experience.
19
- - **Lightweight**: Small bundle size with no unnecessary dependencies.
20
- - **Change Callbacks**: React to every `set` or `delete` via the optional `onChange` hook.
21
-
22
- ---
23
-
24
- ## 📦 Installation
25
-
26
- Install the package via npm or yarn:
27
-
28
- ```bash
29
- # Using npm
30
- npm install react-state-bucket
31
-
32
- # Using yarn
33
- yarn add react-state-bucket
34
- ```
35
-
36
- ---
37
-
38
- ## 🔧 Setup and Usage
39
-
40
- ### Step 1: Create a State Bucket
41
-
42
- Define your initial state and actions:
43
-
44
- ```javascript
45
- import { createBucket } from 'react-state-bucket';
46
-
47
- const initialState = {
48
- count: 0,
49
- user: 'Guest',
50
- };
51
-
52
- export const useGlobalState = createBucket(initialState);
53
- ```
54
-
55
- ### Step 2: Use the State Bucket in a Component
56
-
57
- Access state and actions in your React components:
58
-
59
- ```javascript
60
- import React from 'react';
61
- import { useGlobalState } from './state';
62
-
63
- const App = () => {
64
- const globalState = useGlobalState();
65
-
66
- return (
67
- <div>
68
- <h1>Global State Management</h1>
69
- <p>Count: {globalState.get('count')}</p>
70
- <button onClick={() => globalState.set('count', globalState.get('count') + 1)}>Increment</button>
71
- <button onClick={() => globalState.delete('count')}>Reset Count</button>
72
- <pre>{JSON.stringify(globalState.getState(), null, 2)}</pre>
73
- </div>
74
- );
75
- };
76
-
77
- export default App;
78
- ```
79
-
80
- ---
81
-
82
- ## 🌟 Advanced Features
83
-
84
- ### Using Multiple Buckets
85
-
86
- ```javascript
87
- const useUserBucket = createBucket({ name: '', age: 0 });
88
- const useSettingsBucket = createBucket({ theme: 'light', notifications: true });
89
-
90
- function Profile() {
91
- const userBucket = useUserBucket();
92
- const settingsBucket = useSettingsBucket();
93
-
94
- return (
95
- <div>
96
- <h1>User Profile</h1>
97
- <button onClick={() => userBucket.set('name', 'John Doe')}>Set Name</button>
98
- <button onClick={() => settingsBucket.set('theme', 'dark')}>Change Theme</button>
99
- <pre>User State: {JSON.stringify(userBucket.getState(), null, 2)}</pre>
100
- <p>Current Theme: {settingsBucket.get('theme')}</p>
101
- </div>
102
- );
103
- }
104
- ```
105
-
106
- ### Persistent Storage Options
107
-
108
- ```javascript
109
- const usePersistentBucket = createBucket(
110
- { token: '', language: 'en' },
111
- { store: 'local' }
112
- );
113
-
114
- function PersistentExample() {
115
- const persistentBucket = usePersistentBucket();
116
-
117
- return (
118
- <div>
119
- <h1>Persistent Bucket</h1>
120
- <button onClick={() => persistentBucket.set('token', 'abc123')}>Set Token</button>
121
- <p>Token: {persistentBucket.get('token')}</p>
122
- </div>
123
- );
124
- }
125
- ```
126
-
127
- ### Reusing State Across Components
128
-
129
- ```javascript
130
- import React from 'react';
131
- import { createBucket } from 'react-state-bucket';
132
-
133
- const useGlobalState = createBucket({ count: 0, user: 'Guest' });
134
-
135
- function Counter() {
136
- const globalState = useGlobalState();
137
-
138
- return (
139
- <div>
140
- <h2>Counter Component</h2>
141
- <p>Count: {globalState.get('count')}</p>
142
- <button onClick={() => globalState.set('count', globalState.get('count') + 1)}>Increment Count</button>
143
- </div>
144
- );
145
- }
146
-
147
- function UserDisplay() {
148
- const globalState = useGlobalState();
149
-
150
- return (
151
- <div>
152
- <h2>User Component</h2>
153
- <p>Current User: {globalState.get('user')}</p>
154
- <button onClick={() => globalState.set('user', 'John Doe')}>Set User to John Doe</button>
155
- </div>
156
- );
157
- }
158
-
159
- function App() {
160
- return (
161
- <div>
162
- <h1>Global State Example</h1>
163
- <Counter />
164
- <UserDisplay />
165
- <pre>Global State: {JSON.stringify(useGlobalState().getState(), null, 2)}</pre>
166
- </div>
167
- );
168
- }
169
-
170
- export default App;
171
- ```
172
-
173
- ---
174
-
175
- ## 📘 API Reference
176
-
177
- ### `createBucket(initial: object, option?: BucketOptions)`
178
-
179
- Creates a new bucket for managing the global state.
180
-
181
- #### Parameters
182
-
183
- | Name | Type | Description |
184
- | --------- | --------- | ----------------------------------------- |
185
- | `initial` | `object` | Initial state values. |
186
- | `option` | `object?` | Optional configuration (default: memory). |
187
-
188
- #### `BucketOptions`
189
-
190
- `BucketOptions` allows you to configure how and where the state is stored. It includes:
191
-
192
- | Property | Type | Description |
193
- | ---------- | ------------------------------------- | ---------------------------------------------------------------------------- |
194
- | `store` | `'memory', 'session', 'local', 'url'` | Specifies the storage mechanism for the state. |
195
- | `onChange` | `(key, value, type) => void` | Callback invoked after each `set`/`delete`. `type` is `'set'` or `'delete'`. |
196
-
197
- #### `onChange` Callback
198
-
199
- Use `onChange` to observe bucket mutations—for example, to sync analytics or trigger side effects.
200
-
201
- ```javascript
202
- const useBucketWithLogger = createBucket(
203
- { count: 0 },
204
- {
205
- onChange: (key, value, type) => {
206
- console.log(`[bucket] ${type} -> ${key}`, value);
207
- },
208
- }
209
- );
210
- ```
211
-
212
- When `set('count', 1)` runs, the callback fires with `(key='count', value=1, type='set')`. Deletions invoke the same hook with `type='delete'` and `value` as `undefined`.
213
-
214
- ### Returned Functions
215
-
216
- #### State Management
217
-
218
- | Function | Description |
219
- | ----------------- | ----------------------------------------------------- |
220
- | `set(key, value)` | Sets the value of a specific key in the state. |
221
- | `get(key)` | Retrieves the value of a specific key from the state. |
222
- | `delete(key)` | Removes a key-value pair from the state. |
223
- | `clear()` | Clears all state values. |
224
- | `getState()` | Returns the entire state as an object. |
225
- | `setState(state)` | Updates the state with a partial object. |
226
-
227
- #### Change Detection
228
-
229
- | Function | Description |
230
- | ---------------- | ------------------------------------------- |
231
- | `isChange(key)` | Checks if a specific key has been modified. |
232
- | `getChanges()` | Returns an array of keys that have changed. |
233
- | `clearChanges()` | Resets the change detection for all keys. |
234
-
235
- ---
236
-
237
- ## 🤝 Contributing
238
-
239
- Contributions are welcome! Please check out the [contribution guidelines](https://github.com/devnax/react-state-bucket).
240
-
241
- ---
242
-
243
- ## 📄 License
244
-
245
- This project is licensed under the [MIT License](https://opensource.org/licenses/MIT).
246
-
247
- ---
248
-
249
- ## 📞 Support
250
-
251
- For help or suggestions, feel free to open an issue on [GitHub](https://github.com/devnax/react-state-bucket/issues) or contact us via [devnaxrul@gmail.com](mailto:devnaxrul@gmail.com).
252
-
1
+ <p align="center">
2
+ <img width="120" src="https://raw.githubusercontent.com/devnax/react-state-bucket/main/logo.png" alt="React State Bucket logo">
3
+ </p>
4
+
5
+ <h1 align="center">React State Bucket</h1>
6
+
7
+ Effortlessly manage React application states with **react-state-bucket**, a lightweight yet powerful state management library.
8
+
9
+ ---
10
+
11
+ ## 🚀 Features
12
+
13
+ - **Global State Management**: Manage state across your entire React application with ease.
14
+ - **CRUD Operations**: Create, Read, Update, and Delete state values effortlessly.
15
+ - **Multiple Storage Options**: Store state in "memory," "session storage," "local storage," or "URL parameters."
16
+ - **Reactivity**: Automatically update components when the state changes.
17
+ - **Custom Hooks**: Seamlessly integrate with React’s functional components.
18
+ - **TypeScript Support**: Fully typed for a better development experience.
19
+ - **Lightweight**: Small bundle size with no unnecessary dependencies.
20
+ - **Change Callbacks**: React to every `set` or `delete` via the optional `onChange` hook.
21
+
22
+ ---
23
+
24
+ ## 📦 Installation
25
+
26
+ Install the package via npm or yarn:
27
+
28
+ ```bash
29
+ # Using npm
30
+ npm install react-state-bucket
31
+
32
+ # Using yarn
33
+ yarn add react-state-bucket
34
+ ```
35
+
36
+ ---
37
+
38
+ ## 🔧 Setup and Usage
39
+
40
+ ### Step 1: Create a State Bucket
41
+
42
+ Define your initial state and actions:
43
+
44
+ ```javascript
45
+ import { createBucket } from 'react-state-bucket';
46
+
47
+ const initialState = {
48
+ count: 0,
49
+ user: 'Guest',
50
+ };
51
+
52
+ export const useGlobalState = createBucket(initialState);
53
+ ```
54
+
55
+ ### Step 2: Use the State Bucket in a Component
56
+
57
+ Access state and actions in your React components:
58
+
59
+ ```javascript
60
+ import React from 'react';
61
+ import { useGlobalState } from './state';
62
+
63
+ const App = () => {
64
+ const globalState = useGlobalState();
65
+
66
+ return (
67
+ <div>
68
+ <h1>Global State Management</h1>
69
+ <p>Count: {globalState.get('count')}</p>
70
+ <button onClick={() => globalState.set('count', globalState.get('count') + 1)}>Increment</button>
71
+ <button onClick={() => globalState.delete('count')}>Reset Count</button>
72
+ <pre>{JSON.stringify(globalState.getState(), null, 2)}</pre>
73
+ </div>
74
+ );
75
+ };
76
+
77
+ export default App;
78
+ ```
79
+
80
+ ---
81
+
82
+ ## 🌟 Advanced Features
83
+
84
+ ### Using Multiple Buckets
85
+
86
+ ```javascript
87
+ const useUserBucket = createBucket({ name: '', age: 0 });
88
+ const useSettingsBucket = createBucket({ theme: 'light', notifications: true });
89
+
90
+ function Profile() {
91
+ const userBucket = useUserBucket();
92
+ const settingsBucket = useSettingsBucket();
93
+
94
+ return (
95
+ <div>
96
+ <h1>User Profile</h1>
97
+ <button onClick={() => userBucket.set('name', 'John Doe')}>Set Name</button>
98
+ <button onClick={() => settingsBucket.set('theme', 'dark')}>Change Theme</button>
99
+ <pre>User State: {JSON.stringify(userBucket.getState(), null, 2)}</pre>
100
+ <p>Current Theme: {settingsBucket.get('theme')}</p>
101
+ </div>
102
+ );
103
+ }
104
+ ```
105
+
106
+ ### Persistent Storage Options
107
+
108
+ ```javascript
109
+ const usePersistentBucket = createBucket(
110
+ { token: '', language: 'en' },
111
+ { store: 'local' }
112
+ );
113
+
114
+ function PersistentExample() {
115
+ const persistentBucket = usePersistentBucket();
116
+
117
+ return (
118
+ <div>
119
+ <h1>Persistent Bucket</h1>
120
+ <button onClick={() => persistentBucket.set('token', 'abc123')}>Set Token</button>
121
+ <p>Token: {persistentBucket.get('token')}</p>
122
+ </div>
123
+ );
124
+ }
125
+ ```
126
+
127
+ ### Reusing State Across Components
128
+
129
+ ```javascript
130
+ import React from 'react';
131
+ import { createBucket } from 'react-state-bucket';
132
+
133
+ const useGlobalState = createBucket({ count: 0, user: 'Guest' });
134
+
135
+ function Counter() {
136
+ const globalState = useGlobalState();
137
+
138
+ return (
139
+ <div>
140
+ <h2>Counter Component</h2>
141
+ <p>Count: {globalState.get('count')}</p>
142
+ <button onClick={() => globalState.set('count', globalState.get('count') + 1)}>Increment Count</button>
143
+ </div>
144
+ );
145
+ }
146
+
147
+ function UserDisplay() {
148
+ const globalState = useGlobalState();
149
+
150
+ return (
151
+ <div>
152
+ <h2>User Component</h2>
153
+ <p>Current User: {globalState.get('user')}</p>
154
+ <button onClick={() => globalState.set('user', 'John Doe')}>Set User to John Doe</button>
155
+ </div>
156
+ );
157
+ }
158
+
159
+ function App() {
160
+ return (
161
+ <div>
162
+ <h1>Global State Example</h1>
163
+ <Counter />
164
+ <UserDisplay />
165
+ <pre>Global State: {JSON.stringify(useGlobalState().getState(), null, 2)}</pre>
166
+ </div>
167
+ );
168
+ }
169
+
170
+ export default App;
171
+ ```
172
+
173
+ ---
174
+
175
+ ## 📘 API Reference
176
+
177
+ ### `createBucket(initial: object, option?: BucketOptions)`
178
+
179
+ Creates a new bucket for managing the global state.
180
+
181
+ #### Parameters
182
+
183
+ | Name | Type | Description |
184
+ | --------- | --------- | ----------------------------------------- |
185
+ | `initial` | `object` | Initial state values. |
186
+ | `option` | `object?` | Optional configuration (default: memory). |
187
+
188
+ #### `BucketOptions`
189
+
190
+ `BucketOptions` allows you to configure how and where the state is stored. It includes:
191
+
192
+ | Property | Type | Description |
193
+ | ---------- | ------------------------------------- | ---------------------------------------------------------------------------- |
194
+ | `store` | `'memory', 'session', 'local', 'url'` | Specifies the storage mechanism for the state. |
195
+ | `onChange` | `(key, value, type) => void` | Callback invoked after each `set`/`delete`. `type` is `'set'` or `'delete'`. |
196
+
197
+ #### `onChange` Callback
198
+
199
+ Use `onChange` to observe bucket mutations—for example, to sync analytics or trigger side effects.
200
+
201
+ ```javascript
202
+ const useBucketWithLogger = createBucket(
203
+ { count: 0 },
204
+ {
205
+ onChange: (key, value, type) => {
206
+ console.log(`[bucket] ${type} -> ${key}`, value);
207
+ },
208
+ }
209
+ );
210
+ ```
211
+
212
+ When `set('count', 1)` runs, the callback fires with `(key='count', value=1, type='set')`. Deletions invoke the same hook with `type='delete'` and `value` as `undefined`.
213
+
214
+ ### Returned Functions
215
+
216
+ #### State Management
217
+
218
+ | Function | Description |
219
+ | ----------------- | ----------------------------------------------------- |
220
+ | `set(key, value)` | Sets the value of a specific key in the state. |
221
+ | `get(key)` | Retrieves the value of a specific key from the state. |
222
+ | `delete(key)` | Removes a key-value pair from the state. |
223
+ | `clear()` | Clears all state values. |
224
+ | `getState()` | Returns the entire state as an object. |
225
+ | `setState(state)` | Updates the state with a partial object. |
226
+
227
+ #### Change Detection
228
+
229
+ | Function | Description |
230
+ | ---------------- | ------------------------------------------- |
231
+ | `isChange(key)` | Checks if a specific key has been modified. |
232
+ | `getChanges()` | Returns an array of keys that have changed. |
233
+ | `clearChanges()` | Resets the change detection for all keys. |
234
+
235
+ ---
236
+
237
+ ## 🤝 Contributing
238
+
239
+ Contributions are welcome! Please check out the [contribution guidelines](https://github.com/devnax/react-state-bucket).
240
+
241
+ ---
242
+
243
+ ## 📄 License
244
+
245
+ This project is licensed under the [MIT License](https://opensource.org/licenses/MIT).
246
+
247
+ ---
248
+
249
+ ## 📞 Support
250
+
251
+ For help or suggestions, feel free to open an issue on [GitHub](https://github.com/devnax/react-state-bucket/issues) or contact us via [devnaxrul@gmail.com](mailto:devnaxrul@gmail.com).
252
+
package/Cookie.mjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"Cookie.mjs","sources":["../src/Cookie.ts"],"sourcesContent":["export function setCookie(\n key: string,\n value: string,\n days = 7\n) {\n const expires = new Date(Date.now() + days * 864e5).toUTCString();\n document.cookie =\n `${encodeURIComponent(key)}=${encodeURIComponent(value)}; ` +\n `expires=${expires}; path=/; SameSite=Lax`;\n}\n\nexport function getCookie(key: string): string | null {\n const name = encodeURIComponent(key) + \"=\";\n const parts = document.cookie.split(\"; \");\n\n for (const part of parts) {\n if (part.startsWith(name)) {\n return decodeURIComponent(part.slice(name.length));\n }\n }\n\n return null;\n}"],"names":[],"mappings":"AAAM,SAAU,SAAS,CACtB,GAAW,EACX,KAAa,EACb,IAAI,GAAG,CAAC,EAAA;AAER,IAAA,MAAM,OAAO,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,WAAW,EAAE;AACjE,IAAA,QAAQ,CAAC,MAAM;QACZ,CAAA,EAAG,kBAAkB,CAAC,GAAG,CAAC,IAAI,kBAAkB,CAAC,KAAK,CAAC,CAAA,EAAA,CAAI;YAC3D,CAAA,QAAA,EAAW,OAAO,wBAAwB;AAChD;AAEM,SAAU,SAAS,CAAC,GAAW,EAAA;IAClC,MAAM,IAAI,GAAG,kBAAkB,CAAC,GAAG,CAAC,GAAG,GAAG;IAC1C,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC;AAEzC,IAAA,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;AACvB,QAAA,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;YACxB,OAAO,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACrD;IACH;AAEA,IAAA,OAAO,IAAI;AACd"}
package/Initial.mjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"Initial.mjs","sources":["../src/Initial.ts"],"sourcesContent":["import { BucketOptions, InitialBucketData } from \".\";\nimport { getCookie } from \"./Cookie\";\n\nconst Initial = (initial: InitialBucketData, data_key: string, option: BucketOptions) => {\n let state = {} as Record<string, any>;\n let data: any = \"\"\n\n if (typeof window !== 'undefined') {\n if (option.store === 'session' || option.store === 'local') {\n let storage = option.store === \"session\" ? sessionStorage : localStorage\n data = storage.getItem(data_key)\n } else if (option.store === 'url') {\n let url = new URL(window.location.href)\n data = decodeURIComponent(url.searchParams.get(data_key) || \"\")\n } else if (option.store === 'cookie') {\n data = getCookie(data_key)\n }\n }\n\n if (data) {\n try {\n data = JSON.parse(data)\n } catch (error) {\n data = {}\n }\n } else {\n data = {}\n }\n\n for (let key in initial) {\n try {\n state[key] = initial[key].parse(data[key])\n } catch (error) {\n state[key] = data[key]\n }\n }\n\n return state;\n}\n\nexport default Initial;"],"names":[],"mappings":"qCAGA,MAAM,OAAO,GAAG,CAAC,OAA0B,EAAE,QAAgB,EAAE,MAAqB,KAAI;IACrF,IAAI,KAAK,GAAG,EAAyB;IACrC,IAAI,IAAI,GAAQ,EAAE;AAElB,IAAA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;AAChC,QAAA,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,KAAK,OAAO,EAAE;AACzD,YAAA,IAAI,OAAO,GAAG,MAAM,CAAC,KAAK,KAAK,SAAS,GAAG,cAAc,GAAG,YAAY;AACxE,YAAA,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC;QACnC;AAAO,aAAA,IAAI,MAAM,CAAC,KAAK,KAAK,KAAK,EAAE;YAChC,IAAI,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;AACvC,YAAA,IAAI,GAAG,kBAAkB,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;QAClE;AAAO,aAAA,IAAI,MAAM,CAAC,KAAK,KAAK,QAAQ,EAAE;AACnC,YAAA,IAAI,GAAG,SAAS,CAAC,QAAQ,CAAC;QAC7B;IACH;IAEA,IAAI,IAAI,EAAE;AACP,QAAA,IAAI;AACD,YAAA,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;QAC1B;QAAE,OAAO,KAAK,EAAE;YACb,IAAI,GAAG,EAAE;QACZ;IACH;SAAO;QACJ,IAAI,GAAG,EAAE;IACZ;AAEA,IAAA,KAAK,IAAI,GAAG,IAAI,OAAO,EAAE;AACtB,QAAA,IAAI;AACD,YAAA,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7C;QAAE,OAAO,KAAK,EAAE;YACb,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC;QACzB;IACH;AAEA,IAAA,OAAO,KAAK;AACf"}
package/index.mjs DELETED
@@ -1,157 +0,0 @@
1
- import {useId,useState,useEffect}from'react';import {xv as xv$1}from'xanv';import youid from'youid';import {setCookie}from'./Cookie.mjs';import Initial from'./Initial.mjs';const createBucket = (initial, option) => {
2
- option = Object.assign({ store: "memory" }, option);
3
- if (!(option === null || option === void 0 ? void 0 : option.data_key)) {
4
- let data_key = '';
5
- for (let key in initial) {
6
- const field = initial[key];
7
- data_key += key + ':' + JSON.stringify(field.meta) + ';';
8
- }
9
- option.data_key = youid(data_key);
10
- }
11
- const hooks = new Map();
12
- const state = Initial(initial, (option === null || option === void 0 ? void 0 : option.data_key) || '', option || {});
13
- const changes = {};
14
- const errors = {};
15
- const useBucket = () => {
16
- const id = "rsb_" + useId();
17
- const [, setState] = useState(0);
18
- useEffect(() => {
19
- hooks.set(id, () => setState(Math.random()));
20
- return () => {
21
- hooks.delete(id);
22
- };
23
- }, []);
24
- const get = (key, defaultValue) => {
25
- if (!(key in initial)) {
26
- throw new Error(`Property ${String(key)} is not defined in the bucket.`);
27
- }
28
- let value = state[key];
29
- if (value === undefined && defaultValue !== undefined) {
30
- value = defaultValue;
31
- }
32
- return value;
33
- };
34
- const set = (key, value, dispatch = true) => {
35
- if (!(key in initial)) {
36
- throw new Error(`Property ${String(key)} is not defined in the bucket.`);
37
- }
38
- state[key] = value;
39
- if (dispatch) {
40
- hooks.forEach((hook) => hook());
41
- }
42
- changes[key] = true;
43
- if ((option === null || option === void 0 ? void 0 : option.onChange) && changes[key]) {
44
- option.onChange(key, value);
45
- }
46
- if (typeof window !== 'undefined') {
47
- value = JSON.stringify(value);
48
- if (option.store === 'session' || option.store === 'local') {
49
- let storage = option.store === "session" ? sessionStorage : localStorage;
50
- storage.setItem(option.data_key, JSON.stringify(state));
51
- }
52
- else if (option.store === 'url') {
53
- let url = new URL(window.location.href);
54
- url.searchParams.set(option.data_key, encodeURIComponent(JSON.stringify(state)));
55
- window.history.replaceState({}, '', url.toString());
56
- }
57
- else if (option.store === 'cookie') {
58
- setCookie(option.data_key, JSON.stringify(state));
59
- }
60
- }
61
- };
62
- const sets = (data, dispatch = true) => {
63
- for (let k in data) {
64
- let v = data[k];
65
- set(k, v, false);
66
- }
67
- if (dispatch) {
68
- hooks.forEach((hook) => hook());
69
- }
70
- };
71
- const _delete = (key) => {
72
- set(key, undefined);
73
- };
74
- const clear = () => {
75
- const initVal = Initial(initial, (option === null || option === void 0 ? void 0 : option.data_key) || '', option || {});
76
- for (let key in initial) {
77
- state[key] = initVal[key];
78
- delete changes[key];
79
- }
80
- hooks.forEach((hook) => hook());
81
- };
82
- const getChanges = () => {
83
- const changedData = {};
84
- for (let k in changes) {
85
- if (changes[k]) {
86
- changedData[k] = state[k];
87
- }
88
- }
89
- return changedData;
90
- };
91
- const isChanged = (k) => !!changes[k];
92
- const isValid = (key) => {
93
- try {
94
- initial[key].parse(state[key]);
95
- }
96
- catch (error) {
97
- errors[key] = error.message;
98
- }
99
- hooks.forEach((hook) => hook());
100
- return !(key in errors);
101
- };
102
- const validate = () => {
103
- for (let k in initial) {
104
- try {
105
- initial[k].parse(state[k]);
106
- }
107
- catch (error) {
108
- errors[k] = error.message;
109
- }
110
- }
111
- hooks.forEach((hook) => hook());
112
- return Object.keys(errors).length === 0;
113
- };
114
- const getError = (key) => {
115
- if (key in errors) {
116
- return errors[key];
117
- }
118
- return '';
119
- };
120
- const getErrors = () => {
121
- return errors;
122
- };
123
- const setError = (key, message) => {
124
- errors[key] = message;
125
- hooks.forEach((hook) => hook());
126
- };
127
- const clearErrors = () => {
128
- for (let k in errors) {
129
- delete errors[k];
130
- }
131
- hooks.forEach((hook) => hook());
132
- };
133
- const clearError = (key) => {
134
- delete errors[key];
135
- hooks.forEach((hook) => hook());
136
- };
137
- return {
138
- state,
139
- get,
140
- set,
141
- sets,
142
- delete: _delete,
143
- clear,
144
- validate,
145
- isValid,
146
- getChanges,
147
- isChanged,
148
- getErrors,
149
- getError,
150
- setError,
151
- clearErrors,
152
- clearError
153
- };
154
- };
155
- return useBucket;
156
- };
157
- const xv = xv$1;export{createBucket,xv};//# sourceMappingURL=index.mjs.map