pinia-react 1.2.1 → 1.3.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 +2 -1
- package/README.md +165 -3
- package/dist/index.d.ts +534 -37
- package/dist/index.js +1 -162
- package/package.json +3 -3
package/LICENSE
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
MIT License
|
|
1
|
+
The MIT License (MIT)
|
|
2
2
|
|
|
3
3
|
Copyright (c) 2025 karl
|
|
4
|
+
Copyright (c) 2019-present Eduardo San Martin Morote
|
|
4
5
|
|
|
5
6
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
7
|
of this software and associated documentation files (the "Software"), to deal
|
package/README.md
CHANGED
|
@@ -1,5 +1,167 @@
|
|
|
1
|
-
# pinia-react
|
|
2
1
|
|
|
3
|
-
|
|
2
|
+
# React Pinia
|
|
4
3
|
|
|
5
|
-
|
|
4
|
+
Pinia-react is a state management library for React inspired by Vue's Pinia, bringing a clean, reactive, and TypeScript-friendly state management experience.
|
|
5
|
+
|
|
6
|
+
[](https://www.npmjs.com/package/pinia-react)
|
|
7
|
+
[](https://github.com/your-username/pinia-react/blob/main/LICENSE)
|
|
8
|
+
|
|
9
|
+
## Motivation
|
|
10
|
+
|
|
11
|
+
The React ecosystem has a variety of state management tools, but they can often be overly complex or lack structure. Inspired by Pinia's modular design and elegant API, pinia-react combines React Hooks with the Pinia philosophy to provide a lightweight, intuitive, and TypeScript-friendly state management solution suitable for modern React applications.
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- 🔄 **Powerful Reactivity** - Based on the Vue 3 reactivity system, it automatically tracks dependencies and efficiently updates components.
|
|
16
|
+
- ⚡️ **Reactive** - Built on `useSyncExternalStore`, it perfectly adapts to React rendering.
|
|
17
|
+
- 🛠 **Modular** - Independent stores that support dynamic loading.
|
|
18
|
+
- 🔍 **TypeScript Friendly** - Automatic type inference with zero configuration.
|
|
19
|
+
- 🧩 **Plugin System** - Flexible extensions for features like persistence and logging.
|
|
20
|
+
- 🔀 **Familiar API** - The API design is fully inspired by Pinia, making it friendly for Vue developers.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pnpm add pinia-react
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Basic Usage
|
|
29
|
+
|
|
30
|
+
### Creating and Using a Store
|
|
31
|
+
|
|
32
|
+
```tsx
|
|
33
|
+
import { defineStore } from 'pinia-react'
|
|
34
|
+
import { useEffect } from 'react'
|
|
35
|
+
|
|
36
|
+
// Define a store (API is identical to Pinia)
|
|
37
|
+
const useCounterStore = defineStore('counter', {
|
|
38
|
+
// Define the initial state
|
|
39
|
+
state: () => ({
|
|
40
|
+
count: 0,
|
|
41
|
+
name: 'Counter'
|
|
42
|
+
}),
|
|
43
|
+
|
|
44
|
+
// Define getter methods (similar to computed properties)
|
|
45
|
+
getters: {
|
|
46
|
+
doubleCount() {
|
|
47
|
+
return this.count * 2
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
// Define action methods
|
|
52
|
+
actions: {
|
|
53
|
+
increment() {
|
|
54
|
+
this.count++
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
async fetchSomething() {
|
|
58
|
+
// Supports asynchronous operations
|
|
59
|
+
const result = await api.get('/data')
|
|
60
|
+
this.count = result.count
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
// Use in a component
|
|
66
|
+
function Counter() {
|
|
67
|
+
// Get the store instance
|
|
68
|
+
const store = useCounterStore()
|
|
69
|
+
|
|
70
|
+
useEffect(() => {
|
|
71
|
+
// You can call an action method
|
|
72
|
+
store.fetchSomething()
|
|
73
|
+
}, [])
|
|
74
|
+
|
|
75
|
+
return (
|
|
76
|
+
<div>
|
|
77
|
+
<h1>{store.name}: {store.count}</h1>
|
|
78
|
+
<p>Double count: {store.doubleCount}</p>
|
|
79
|
+
<button onClick={() => store.increment()}>Increment</button>
|
|
80
|
+
</div>
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Interacting Between Multiple Stores
|
|
86
|
+
|
|
87
|
+
```tsx
|
|
88
|
+
import { defineStore } from 'pinia-react'
|
|
89
|
+
|
|
90
|
+
// User Store
|
|
91
|
+
const useUserStore = defineStore('user', {
|
|
92
|
+
state: () => ({
|
|
93
|
+
name: 'Anonymous',
|
|
94
|
+
isAdmin: false
|
|
95
|
+
}),
|
|
96
|
+
actions: {
|
|
97
|
+
login(name, admin = false) {
|
|
98
|
+
this.name = name
|
|
99
|
+
this.isAdmin = admin
|
|
100
|
+
},
|
|
101
|
+
logout() {
|
|
102
|
+
this.name = 'Anonymous'
|
|
103
|
+
this.isAdmin = false
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
// Cart Store, which depends on the User Store
|
|
109
|
+
const useCartStore = defineStore('cart', {
|
|
110
|
+
state: () => ({
|
|
111
|
+
items: []
|
|
112
|
+
}),
|
|
113
|
+
getters: {
|
|
114
|
+
isEmpty() {
|
|
115
|
+
return this.items.length === 0
|
|
116
|
+
},
|
|
117
|
+
// Can use other stores
|
|
118
|
+
isCheckoutAllowed() {
|
|
119
|
+
const userStore = useUserStore.$getStore()
|
|
120
|
+
return this.items.length > 0 && userStore.name !== 'Anonymous'
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
actions: {
|
|
124
|
+
addItem(item) {
|
|
125
|
+
this.items.push(item)
|
|
126
|
+
},
|
|
127
|
+
checkout() {
|
|
128
|
+
const userStore = useUserStore.$getStore()
|
|
129
|
+
if (userStore.name === 'Anonymous') {
|
|
130
|
+
throw new Error('Login required')
|
|
131
|
+
}
|
|
132
|
+
// Handle checkout logic...
|
|
133
|
+
this.items = []
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
})
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Plugin System
|
|
140
|
+
|
|
141
|
+
Pinia-react supports extending functionality through plugins.
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
import { createpinia } from 'pinia-react'
|
|
145
|
+
|
|
146
|
+
// Create a pinia instance
|
|
147
|
+
const pinia = createpinia()
|
|
148
|
+
|
|
149
|
+
// Use a plugin
|
|
150
|
+
pinia.use(myPlugin)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
// Plugin example
|
|
154
|
+
function myPlugin({ store, options }) {
|
|
155
|
+
// Add custom properties or methods to the store
|
|
156
|
+
return {
|
|
157
|
+
customProperty: 'value',
|
|
158
|
+
customMethod() {
|
|
159
|
+
// Custom logic
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## License
|
|
166
|
+
|
|
167
|
+
MIT
|
package/dist/index.d.ts
CHANGED
|
@@ -1,41 +1,334 @@
|
|
|
1
|
+
import { ComputedRef, DebuggerEvent, EffectScope, Ref, UnwrapRef, WatchOptions, WritableComputedRef } from "@maoism/runtime-core";
|
|
2
|
+
|
|
1
3
|
//#region src/types.d.ts
|
|
2
4
|
|
|
3
|
-
type StateTree = Record<string | number | symbol, unknown>;
|
|
4
|
-
type _StoreWithGetters<G> = { readonly [k in keyof G]: G[k] extends ((...args: any[]) => infer R) ? R : G[k] };
|
|
5
|
-
type _ActionsTree = Record<string | number | symbol, (...args: any[]) => any>;
|
|
6
|
-
type PiniaCustomStateProperties<S extends StateTree = StateTree> = {};
|
|
7
|
-
type _GettersTree<S extends StateTree> = Record<string, (state: S & PiniaCustomStateProperties<S>) => any>;
|
|
8
5
|
/**
|
|
9
|
-
*
|
|
6
|
+
* Generic state of a Store
|
|
7
|
+
*/
|
|
8
|
+
type StateTree = Record<PropertyKey, any>;
|
|
9
|
+
/**
|
|
10
|
+
* Recursive `Partial<T>`. Used by {@link Store['$patch']}.
|
|
11
|
+
*
|
|
12
|
+
* For internal use **only**
|
|
10
13
|
*/
|
|
11
|
-
type PiniaCustomProperties<Id extends string = string, S extends StateTree = StateTree, G = _GettersTree<S>, A = _ActionsTree> = {};
|
|
12
14
|
type _DeepPartial<T> = { [K in keyof T]?: _DeepPartial<T[K]> };
|
|
13
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Possible types for SubscriptionCallback
|
|
17
|
+
*/
|
|
18
|
+
declare enum MutationType {
|
|
19
|
+
/**
|
|
20
|
+
* Direct mutation of the state:
|
|
21
|
+
*
|
|
22
|
+
* - `store.name = 'new name'`
|
|
23
|
+
* - `store.$state.name = 'new name'`
|
|
24
|
+
* - `store.list.push('new item')`
|
|
25
|
+
*/
|
|
26
|
+
direct = "direct",
|
|
27
|
+
/**
|
|
28
|
+
* Mutated the state with `$patch` and an object
|
|
29
|
+
*
|
|
30
|
+
* - `store.$patch({ name: 'newName' })`
|
|
31
|
+
*/
|
|
32
|
+
patchObject = "patch object",
|
|
33
|
+
/**
|
|
34
|
+
* Mutated the state with `$patch` and a function
|
|
35
|
+
*
|
|
36
|
+
* - `store.$patch(state => state.name = 'newName')`
|
|
37
|
+
*/
|
|
38
|
+
patchFunction = "patch function",
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Base type for the context passed to a subscription callback. Internal type.
|
|
42
|
+
*/
|
|
43
|
+
interface _SubscriptionCallbackMutationBase {
|
|
44
|
+
/**
|
|
45
|
+
* Type of the mutation.
|
|
46
|
+
*/
|
|
47
|
+
type: MutationType;
|
|
48
|
+
/**
|
|
49
|
+
* `id` of the store doing the mutation.
|
|
50
|
+
*/
|
|
51
|
+
storeId: string;
|
|
52
|
+
/**
|
|
53
|
+
* 🔴 DEV ONLY, DO NOT use for production code. Different mutation calls. Comes from
|
|
54
|
+
* https://vuejs.org/guide/extras/reactivity-in-depth.html#reactivity-debugging and allows to track mutations in
|
|
55
|
+
* devtools and plugins **during development only**.
|
|
56
|
+
*/
|
|
57
|
+
events?: DebuggerEvent[] | DebuggerEvent;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Context passed to a subscription callback when directly mutating the state of
|
|
61
|
+
* a store with `store.someState = newValue` or `store.$state.someState =
|
|
62
|
+
* newValue`.
|
|
63
|
+
*/
|
|
64
|
+
interface SubscriptionCallbackMutationDirect extends _SubscriptionCallbackMutationBase {
|
|
65
|
+
type: MutationType.direct;
|
|
66
|
+
events: DebuggerEvent;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Context passed to a subscription callback when `store.$patch()` is called
|
|
70
|
+
* with an object.
|
|
71
|
+
*/
|
|
72
|
+
interface SubscriptionCallbackMutationPatchObject<S> extends _SubscriptionCallbackMutationBase {
|
|
73
|
+
type: MutationType.patchObject;
|
|
74
|
+
events: DebuggerEvent[];
|
|
75
|
+
/**
|
|
76
|
+
* Object passed to `store.$patch()`.
|
|
77
|
+
*/
|
|
78
|
+
payload: _DeepPartial<UnwrapRef<S>>;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Context passed to a subscription callback when `store.$patch()` is called
|
|
82
|
+
* with a function.
|
|
83
|
+
*/
|
|
84
|
+
interface SubscriptionCallbackMutationPatchFunction extends _SubscriptionCallbackMutationBase {
|
|
85
|
+
type: MutationType.patchFunction;
|
|
86
|
+
events: DebuggerEvent[];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Context object passed to a subscription callback.
|
|
90
|
+
*/
|
|
91
|
+
type SubscriptionCallbackMutation<S> = SubscriptionCallbackMutationDirect | SubscriptionCallbackMutationPatchObject<S> | SubscriptionCallbackMutationPatchFunction;
|
|
92
|
+
/**
|
|
93
|
+
* Callback of a subscription
|
|
94
|
+
*/
|
|
95
|
+
type SubscriptionCallback<S> = (
|
|
96
|
+
/**
|
|
97
|
+
* Object with information relative to the store mutation that triggered the
|
|
98
|
+
* subscription.
|
|
99
|
+
*/
|
|
100
|
+
mutation: SubscriptionCallbackMutation<S>,
|
|
101
|
+
/**
|
|
102
|
+
* State of the store when the subscription is triggered. Same as
|
|
103
|
+
* `store.$state`.
|
|
104
|
+
*/
|
|
105
|
+
state: UnwrapRef<S>) => void;
|
|
106
|
+
/**
|
|
107
|
+
* Actual type for {@link StoreOnActionListenerContext}. Exists for refactoring
|
|
108
|
+
* purposes. For internal use only.
|
|
109
|
+
* For internal use **only**
|
|
110
|
+
*/
|
|
111
|
+
interface _StoreOnActionListenerContext<Store, ActionName extends string, A> {
|
|
112
|
+
/**
|
|
113
|
+
* Name of the action
|
|
114
|
+
*/
|
|
115
|
+
name: ActionName;
|
|
116
|
+
/**
|
|
117
|
+
* Store that is invoking the action
|
|
118
|
+
*/
|
|
119
|
+
store: Store;
|
|
120
|
+
/**
|
|
121
|
+
* Parameters passed to the action
|
|
122
|
+
*/
|
|
123
|
+
args: A extends Record<ActionName, _Method> ? Parameters<A[ActionName]> : unknown[];
|
|
124
|
+
/**
|
|
125
|
+
* Sets up a hook once the action is finished. It receives the return value
|
|
126
|
+
* of the action, if it's a Promise, it will be unwrapped.
|
|
127
|
+
*/
|
|
128
|
+
after: (callback: A extends Record<ActionName, _Method> ? (resolvedReturn: Awaited<ReturnType<A[ActionName]>>) => void : () => void) => void;
|
|
129
|
+
/**
|
|
130
|
+
* Sets up a hook if the action fails. Return `false` to catch the error and
|
|
131
|
+
* stop it from propagating.
|
|
132
|
+
*/
|
|
133
|
+
onError: (callback: (error: unknown) => void) => void;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Context object passed to callbacks of `store.$onAction(context => {})`
|
|
137
|
+
* TODO: should have only the Id, the Store and Actions to generate the proper object
|
|
138
|
+
*/
|
|
139
|
+
type StoreOnActionListenerContext<Id extends string, S extends StateTree, G, A> = _ActionsTree extends A ? _StoreOnActionListenerContext<StoreGeneric, string, _ActionsTree> : { [Name in keyof A]: Name extends string ? _StoreOnActionListenerContext<Store<Id, S, G, A>, Name, A> : never }[keyof A];
|
|
140
|
+
/**
|
|
141
|
+
* Argument of `store.$onAction()`
|
|
142
|
+
*/
|
|
143
|
+
type StoreOnActionListener<Id extends string, S extends StateTree, G, A> = (context: StoreOnActionListenerContext<Id, S, G, {} extends A ? _ActionsTree : A>) => void;
|
|
144
|
+
/**
|
|
145
|
+
* Properties of a store.
|
|
146
|
+
*/
|
|
147
|
+
interface StoreProperties<Id extends string> {
|
|
148
|
+
/**
|
|
149
|
+
* Unique identifier of the store
|
|
150
|
+
*/
|
|
14
151
|
$id: Id;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
152
|
+
/**
|
|
153
|
+
* Private property defining the pinia the store is attached to.
|
|
154
|
+
*
|
|
155
|
+
* @internal
|
|
156
|
+
*/
|
|
157
|
+
_p: Pinia;
|
|
158
|
+
/**
|
|
159
|
+
* Used by devtools plugin to retrieve getters. Removed in production.
|
|
160
|
+
*
|
|
161
|
+
* @internal
|
|
162
|
+
*/
|
|
163
|
+
_getters?: string[];
|
|
164
|
+
/**
|
|
165
|
+
* Used (and added) by devtools plugin to detect Setup vs Options API usage.
|
|
166
|
+
*
|
|
167
|
+
* @internal
|
|
168
|
+
*/
|
|
169
|
+
_isOptionsAPI?: boolean;
|
|
170
|
+
/**
|
|
171
|
+
* Used by devtools plugin to retrieve properties added with plugins. Removed
|
|
172
|
+
* in production. Can be used by the user to add property keys of the store
|
|
173
|
+
* that should be displayed in devtools.
|
|
174
|
+
*/
|
|
175
|
+
_customProperties: Set<string>;
|
|
176
|
+
/**
|
|
177
|
+
* Handles a HMR replacement of this store. Dev Only.
|
|
178
|
+
*
|
|
179
|
+
* @internal
|
|
180
|
+
*/
|
|
181
|
+
_hotUpdate(useStore: StoreGeneric): void;
|
|
182
|
+
/**
|
|
183
|
+
* Allows pausing some of the watching mechanisms while the store is being
|
|
184
|
+
* patched with a newer version.
|
|
185
|
+
*
|
|
186
|
+
* @internal
|
|
187
|
+
*/
|
|
188
|
+
_hotUpdating: boolean;
|
|
189
|
+
/**
|
|
190
|
+
* Payload of the hmr update. Dev only.
|
|
191
|
+
*
|
|
192
|
+
* @internal
|
|
193
|
+
*/
|
|
194
|
+
_hmrPayload: {
|
|
195
|
+
state: string[];
|
|
196
|
+
hotState: Ref<StateTree>;
|
|
197
|
+
actions: _ActionsTree;
|
|
198
|
+
getters: _ActionsTree;
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Base store with state and functions. Should not be used directly.
|
|
203
|
+
*/
|
|
204
|
+
interface _StoreWithState<Id extends string, S extends StateTree, G, A> extends StoreProperties<Id> {
|
|
205
|
+
/**
|
|
206
|
+
* State of the Store. Setting it will internally call `$patch()` to update the state.
|
|
207
|
+
*/
|
|
208
|
+
$state: UnwrapRef<S> & PiniaCustomStateProperties<S>;
|
|
209
|
+
/**
|
|
210
|
+
* Applies a state patch to current state. Allows passing nested values
|
|
211
|
+
*
|
|
212
|
+
* @param partialState - patch to apply to the state
|
|
213
|
+
*/
|
|
214
|
+
$patch(partialState: _DeepPartial<UnwrapRef<S>>): void;
|
|
215
|
+
/**
|
|
216
|
+
* Group multiple changes into one function. Useful when mutating objects like
|
|
217
|
+
* Sets or arrays and applying an object patch isn't practical, e.g. appending
|
|
218
|
+
* to an array. The function passed to `$patch()` **must be synchronous**.
|
|
219
|
+
*
|
|
220
|
+
* @param stateMutator - function that mutates `state`, cannot be asynchronous
|
|
221
|
+
*/
|
|
222
|
+
$patch<F extends (state: UnwrapRef<S>) => any>(stateMutator: ReturnType<F> extends Promise<any> ? never : F): void;
|
|
223
|
+
/**
|
|
224
|
+
* Resets the store to its initial state by building a new state object.
|
|
225
|
+
*/
|
|
18
226
|
$reset(): void;
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
227
|
+
/**
|
|
228
|
+
* Setups a callback to be called whenever the state changes. It also returns a function to remove the callback. Note
|
|
229
|
+
* that when calling `store.$subscribe()` inside of a component, it will be automatically cleaned up when the
|
|
230
|
+
* component gets unmounted unless `detached` is set to true.
|
|
231
|
+
*
|
|
232
|
+
* @param callback - callback passed to the watcher
|
|
233
|
+
* @param options - `watch` options + `detached` to detach the subscription from the context (usually a component)
|
|
234
|
+
* this is called from. Note that the `flush` option does not affect calls to `store.$patch()`.
|
|
235
|
+
* @returns function that removes the watcher
|
|
236
|
+
*/
|
|
237
|
+
$subscribe(callback: SubscriptionCallback<S>, options?: {
|
|
238
|
+
detached?: boolean;
|
|
239
|
+
} & WatchOptions): () => void;
|
|
240
|
+
/**
|
|
241
|
+
* Setups a callback to be called every time an action is about to get
|
|
242
|
+
* invoked. The callback receives an object with all the relevant information
|
|
243
|
+
* of the invoked action:
|
|
244
|
+
* - `store`: the store it is invoked on
|
|
245
|
+
* - `name`: The name of the action
|
|
246
|
+
* - `args`: The parameters passed to the action
|
|
247
|
+
*
|
|
248
|
+
* On top of these, it receives two functions that allow setting up a callback
|
|
249
|
+
* once the action finishes or when it fails.
|
|
250
|
+
*
|
|
251
|
+
* It also returns a function to remove the callback. Note than when calling
|
|
252
|
+
* `store.$onAction()` inside of a component, it will be automatically cleaned
|
|
253
|
+
* up when the component gets unmounted unless `detached` is set to true.
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
*
|
|
257
|
+
*```js
|
|
258
|
+
*store.$onAction(({ after, onError }) => {
|
|
259
|
+
* // Here you could share variables between all of the hooks as well as
|
|
260
|
+
* // setting up watchers and clean them up
|
|
261
|
+
* after((resolvedValue) => {
|
|
262
|
+
* // can be used to cleanup side effects
|
|
263
|
+
* . // `resolvedValue` is the value returned by the action, if it's a
|
|
264
|
+
* . // Promise, it will be the resolved value instead of the Promise
|
|
265
|
+
* })
|
|
266
|
+
* onError((error) => {
|
|
267
|
+
* // can be used to pass up errors
|
|
268
|
+
* })
|
|
269
|
+
*})
|
|
270
|
+
*```
|
|
271
|
+
*
|
|
272
|
+
* @param callback - callback called before every action
|
|
273
|
+
* @param detached - detach the subscription from the context this is called from
|
|
274
|
+
* @returns function that removes the watcher
|
|
275
|
+
*/
|
|
276
|
+
$onAction(callback: StoreOnActionListener<Id, S, G, A>, detached?: boolean): () => void;
|
|
277
|
+
/**
|
|
278
|
+
* Stops the associated effect scope of the store and remove it from the store
|
|
279
|
+
* registry. Plugins can override this method to cleanup any added effects.
|
|
280
|
+
* e.g. devtools plugin stops displaying disposed stores from devtools.
|
|
281
|
+
* Note this doesn't delete the state of the store, you have to do it manually with
|
|
282
|
+
* `delete pinia.state.value[store.$id]` if you want to. If you don't and the
|
|
283
|
+
* store is used again, it will reuse the previous state.
|
|
284
|
+
*/
|
|
285
|
+
$dispose(): void;
|
|
22
286
|
}
|
|
23
|
-
|
|
287
|
+
/**
|
|
288
|
+
* Generic type for a function that can infer arguments and return type
|
|
289
|
+
*
|
|
290
|
+
* For internal use **only**
|
|
291
|
+
*/
|
|
292
|
+
type _Method = (...args: any[]) => any;
|
|
293
|
+
/**
|
|
294
|
+
* Store augmented for actions. For internal usage only.
|
|
295
|
+
* For internal use **only**
|
|
296
|
+
*/
|
|
297
|
+
type _StoreWithActions<A> = { [k in keyof A]: A[k] extends ((...args: infer P) => infer R) ? (...args: P) => R : never };
|
|
298
|
+
/**
|
|
299
|
+
* Store augmented with getters. For internal usage only.
|
|
300
|
+
* For internal use **only**
|
|
301
|
+
*/
|
|
302
|
+
type _StoreWithGetters<G> = _StoreWithGetters_Readonly<G> & _StoreWithGetters_Writable<G>;
|
|
303
|
+
/**
|
|
304
|
+
* Store augmented with readonly getters. For internal usage **only**.
|
|
305
|
+
*/
|
|
306
|
+
type _StoreWithGetters_Readonly<G> = { readonly [K in keyof G as G[K] extends ((...args: any[]) => any) ? K : ComputedRef extends G[K] ? K : never]: G[K] extends ((...args: any[]) => infer R) ? R : UnwrapRef<G[K]> };
|
|
307
|
+
/**
|
|
308
|
+
* Store augmented with writable getters. For internal usage **only**.
|
|
309
|
+
*/
|
|
310
|
+
type _StoreWithGetters_Writable<G> = { [K in keyof G as G[K] extends WritableComputedRef<any> ? K : never]: G[K] extends Readonly<WritableComputedRef<infer R>> ? R : never };
|
|
311
|
+
/**
|
|
312
|
+
* Store type to build a store.
|
|
313
|
+
*/
|
|
314
|
+
type Store<Id extends string = string, S extends StateTree = {}, G = {}, A = {}> = _StoreWithState<Id, S, G, A> & UnwrapRef<S> & _StoreWithGetters<G> & (_ActionsTree extends A ? {} : A) & PiniaCustomProperties<Id, S, G, A> & PiniaCustomStateProperties<S>;
|
|
315
|
+
/**
|
|
316
|
+
* Generic and type-unsafe version of Store. Doesn't fail on access with
|
|
317
|
+
* strings, making it much easier to write generic functions that do not care
|
|
318
|
+
* about the kind of store that is passed.
|
|
319
|
+
*/
|
|
24
320
|
type StoreGeneric = Store<string, StateTree, _GettersTree<StateTree>, _ActionsTree>;
|
|
25
|
-
type DefineStoreOptionsBase<S extends StateTree, Store> = {};
|
|
26
|
-
interface DefineStoreOptions<Id extends string, S extends StateTree, G, A> extends DefineStoreOptionsBase<S, Store<Id, S, G, A>> {
|
|
27
|
-
state?: () => S;
|
|
28
|
-
getters?: G & ThisType<S & _StoreWithGetters<G> & PiniaCustomProperties>;
|
|
29
|
-
actions?: A & ThisType<A & S & _StoreWithState<Id, S, G, A> & _StoreWithGetters<G> & PiniaCustomProperties>;
|
|
30
|
-
}
|
|
31
321
|
/**
|
|
32
322
|
* Return type of `defineStore()`. Function that allows instantiating a store.
|
|
33
323
|
*/
|
|
34
324
|
interface StoreDefinition<Id extends string = string, S extends StateTree = StateTree, G = _GettersTree<S>, A = _ActionsTree> {
|
|
35
325
|
/**
|
|
36
326
|
* Returns a store, creates it if necessary.
|
|
327
|
+
*
|
|
328
|
+
* @param pinia - Pinia instance to retrieve the store
|
|
329
|
+
* @param hot - dev only hot module replacement
|
|
37
330
|
*/
|
|
38
|
-
(): Store<Id, S, G, A>;
|
|
331
|
+
(pinia?: Pinia | null | undefined, hot?: StoreGeneric): Store<Id, S, G, A>;
|
|
39
332
|
/**
|
|
40
333
|
* Id of the store. Used by map helpers.
|
|
41
334
|
*/
|
|
@@ -44,25 +337,229 @@ interface StoreDefinition<Id extends string = string, S extends StateTree = Stat
|
|
|
44
337
|
* Return to store for use within non-functional components
|
|
45
338
|
*/
|
|
46
339
|
$getStore: () => Store<Id, S, G, A>;
|
|
340
|
+
/**
|
|
341
|
+
* Dev only pinia for HMR.
|
|
342
|
+
*
|
|
343
|
+
* @internal
|
|
344
|
+
*/
|
|
345
|
+
_pinia?: Pinia;
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Interface to be extended by the user when they add properties through plugins.
|
|
349
|
+
*/
|
|
350
|
+
interface PiniaCustomProperties<Id extends string = string, S extends StateTree = StateTree, G = _GettersTree<S>, A = _ActionsTree> {}
|
|
351
|
+
/**
|
|
352
|
+
* Properties that are added to every `store.$state` by `pinia.use()`.
|
|
353
|
+
*/
|
|
354
|
+
interface PiniaCustomStateProperties<S extends StateTree = StateTree> {}
|
|
355
|
+
/**
|
|
356
|
+
* Type of an object of Getters that infers the argument. For internal usage only.
|
|
357
|
+
* For internal use **only**
|
|
358
|
+
*/
|
|
359
|
+
type _GettersTree<S extends StateTree> = Record<string, ((state: UnwrapRef<S> & UnwrapRef<PiniaCustomStateProperties<S>>) => any) | (() => any)>;
|
|
360
|
+
/**
|
|
361
|
+
* Type of an object of Actions. For internal usage only.
|
|
362
|
+
* For internal use **only**
|
|
363
|
+
*/
|
|
364
|
+
type _ActionsTree = Record<string, _Method>;
|
|
365
|
+
/**
|
|
366
|
+
* Type that enables refactoring through IDE.
|
|
367
|
+
* For internal use **only**
|
|
368
|
+
*/
|
|
369
|
+
type _ExtractStateFromSetupStore_Keys<SS> = keyof { [K in keyof SS as SS[K] extends _Method | ComputedRef ? never : K]: any };
|
|
370
|
+
/**
|
|
371
|
+
* Type that enables refactoring through IDE.
|
|
372
|
+
* For internal use **only**
|
|
373
|
+
*/
|
|
374
|
+
type _ExtractActionsFromSetupStore_Keys<SS> = keyof { [K in keyof SS as SS[K] extends _Method ? K : never]: any };
|
|
375
|
+
/**
|
|
376
|
+
* Type that enables refactoring through IDE.
|
|
377
|
+
* For internal use **only**
|
|
378
|
+
*/
|
|
379
|
+
type _ExtractGettersFromSetupStore_Keys<SS> = keyof { [K in keyof SS as SS[K] extends ComputedRef ? K : never]: any };
|
|
380
|
+
/**
|
|
381
|
+
* Type that enables refactoring through IDE.
|
|
382
|
+
* For internal use **only**
|
|
383
|
+
*/
|
|
384
|
+
type _UnwrapAll<SS> = { [K in keyof SS]: UnwrapRef<SS[K]> };
|
|
385
|
+
/**
|
|
386
|
+
* For internal use **only**
|
|
387
|
+
*/
|
|
388
|
+
type _ExtractStateFromSetupStore<SS> = SS extends undefined | void ? {} : Pick<SS, _ExtractStateFromSetupStore_Keys<SS>>;
|
|
389
|
+
/**
|
|
390
|
+
* For internal use **only**
|
|
391
|
+
*/
|
|
392
|
+
type _ExtractActionsFromSetupStore<SS> = SS extends undefined | void ? {} : Pick<SS, _ExtractActionsFromSetupStore_Keys<SS>>;
|
|
393
|
+
/**
|
|
394
|
+
* For internal use **only**
|
|
395
|
+
*/
|
|
396
|
+
type _ExtractGettersFromSetupStore<SS> = SS extends undefined | void ? {} : Pick<SS, _ExtractGettersFromSetupStore_Keys<SS>>;
|
|
397
|
+
/**
|
|
398
|
+
* Options passed to `defineStore()` that are common between option and setup
|
|
399
|
+
* stores. Extend this interface if you want to add custom options to both kinds
|
|
400
|
+
* of stores.
|
|
401
|
+
*/
|
|
402
|
+
type DefineStoreOptionsBase<S extends StateTree, Store> = {};
|
|
403
|
+
/**
|
|
404
|
+
* Options parameter of `defineStore()` for option stores. Can be extended to
|
|
405
|
+
* augment stores with the plugin API. @see {@link DefineStoreOptionsBase}.
|
|
406
|
+
*/
|
|
407
|
+
interface DefineStoreOptions<Id extends string, S extends StateTree, G, A> extends DefineStoreOptionsBase<S, Store<Id, S, G, A>> {
|
|
408
|
+
/**
|
|
409
|
+
* Unique string key to identify the store across the application.
|
|
410
|
+
*/
|
|
411
|
+
id: Id;
|
|
412
|
+
/**
|
|
413
|
+
* Function to create a fresh state. **Must be an arrow function** to ensure
|
|
414
|
+
* correct typings!
|
|
415
|
+
*/
|
|
416
|
+
state?: () => S;
|
|
417
|
+
/**
|
|
418
|
+
* Optional object of getters.
|
|
419
|
+
*/
|
|
420
|
+
getters?: G & ThisType<UnwrapRef<S> & _StoreWithGetters<G> & PiniaCustomProperties> & _GettersTree<S>;
|
|
421
|
+
/**
|
|
422
|
+
* Optional object of actions.
|
|
423
|
+
*/
|
|
424
|
+
actions?: A & ThisType<A & UnwrapRef<S> & _StoreWithState<Id, S, G, A> & _StoreWithGetters<G> & PiniaCustomProperties>;
|
|
425
|
+
/**
|
|
426
|
+
* Allows hydrating the store during SSR when complex state (like client side only refs) are used in the store
|
|
427
|
+
* definition and copying the value from `pinia.state` isn't enough.
|
|
428
|
+
*
|
|
429
|
+
* @example
|
|
430
|
+
* If in your `state`, you use any `customRef`s, any `computed`s, or any `ref`s that have a different value on
|
|
431
|
+
* Server and Client, you need to manually hydrate them. e.g., a custom ref that is stored in the local
|
|
432
|
+
* storage:
|
|
433
|
+
*
|
|
434
|
+
* ```ts
|
|
435
|
+
* const useStore = defineStore('main', {
|
|
436
|
+
* state: () => ({
|
|
437
|
+
* n: useLocalStorage('key', 0)
|
|
438
|
+
* }),
|
|
439
|
+
* hydrate(storeState, initialState) {
|
|
440
|
+
* // @ts-expect-error: https://github.com/microsoft/TypeScript/issues/43826
|
|
441
|
+
* storeState.n = useLocalStorage('key', 0)
|
|
442
|
+
* }
|
|
443
|
+
* })
|
|
444
|
+
* ```
|
|
445
|
+
*
|
|
446
|
+
* @param storeState - the current state in the store
|
|
447
|
+
* @param initialState - initialState
|
|
448
|
+
*/
|
|
449
|
+
hydrate?(storeState: UnwrapRef<S>, initialState: UnwrapRef<S>): void;
|
|
47
450
|
}
|
|
451
|
+
/**
|
|
452
|
+
* Options parameter of `defineStore()` for setup stores. Can be extended to
|
|
453
|
+
* augment stores with the plugin API. @see {@link DefineStoreOptionsBase}.
|
|
454
|
+
*/
|
|
455
|
+
interface DefineSetupStoreOptions<Id extends string, S extends StateTree, G, A> extends DefineStoreOptionsBase<S, Store<Id, S, G, A>> {
|
|
456
|
+
/**
|
|
457
|
+
* Extracted actions. Added by useStore(). SHOULD NOT be added by the user when
|
|
458
|
+
* creating the store. Can be used in plugins to get the list of actions in a
|
|
459
|
+
* store defined with a setup function. Note this is always defined
|
|
460
|
+
*/
|
|
461
|
+
actions?: A;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Available `options` when creating a pinia plugin.
|
|
465
|
+
*/
|
|
466
|
+
interface DefineStoreOptionsInPlugin<Id extends string, S extends StateTree, G, A> extends Omit<DefineStoreOptions<Id, S, G, A>, 'id' | 'actions'> {
|
|
467
|
+
/**
|
|
468
|
+
* Extracted object of actions. Added by useStore() when the store is built
|
|
469
|
+
* using the setup API, otherwise uses the one passed to `defineStore()`.
|
|
470
|
+
* Defaults to an empty object if no actions are defined.
|
|
471
|
+
*/
|
|
472
|
+
actions: A;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Utility type. For internal use **only**
|
|
476
|
+
*/
|
|
477
|
+
//#endregion
|
|
478
|
+
//#region src/rootStore.d.ts
|
|
479
|
+
/**
|
|
480
|
+
* Get the currently active pinia if there is any.
|
|
481
|
+
*/
|
|
482
|
+
declare const getActivePinia: () => Pinia | undefined;
|
|
483
|
+
/**
|
|
484
|
+
* Every application must own its own pinia to be able to create stores
|
|
485
|
+
*/
|
|
486
|
+
interface Pinia {
|
|
487
|
+
/**
|
|
488
|
+
* root state
|
|
489
|
+
*/
|
|
490
|
+
state: Ref<Record<string, StateTree>>;
|
|
491
|
+
/**
|
|
492
|
+
* Adds a store plugin to extend every store
|
|
493
|
+
*
|
|
494
|
+
* @param plugin - store plugin to add
|
|
495
|
+
*/
|
|
496
|
+
use(plugin: PiniaPlugin): Pinia;
|
|
497
|
+
/**
|
|
498
|
+
* Installed store plugins
|
|
499
|
+
*
|
|
500
|
+
* @internal
|
|
501
|
+
*/
|
|
502
|
+
_p: PiniaPlugin[];
|
|
503
|
+
/**
|
|
504
|
+
* Effect scope the pinia is attached to
|
|
505
|
+
*
|
|
506
|
+
* @internal
|
|
507
|
+
*/
|
|
508
|
+
_e: EffectScope;
|
|
509
|
+
/**
|
|
510
|
+
* Registry of stores used by this pinia.
|
|
511
|
+
*
|
|
512
|
+
* @internal
|
|
513
|
+
*/
|
|
514
|
+
_s: Map<string, StoreGeneric>;
|
|
515
|
+
/**
|
|
516
|
+
* Added by `createTestingPinia()` to bypass `useStore(pinia)`.
|
|
517
|
+
*
|
|
518
|
+
* @internal
|
|
519
|
+
*/
|
|
520
|
+
_testing?: boolean;
|
|
521
|
+
}
|
|
522
|
+
declare function setActivePinia(_pinia: Pinia): void;
|
|
48
523
|
type PiniaPluginContext<Id extends string = string, S extends StateTree = StateTree, G = _GettersTree<S>, A = _ActionsTree> = {
|
|
49
|
-
|
|
524
|
+
/**
|
|
525
|
+
* pinia instance.
|
|
526
|
+
*/
|
|
527
|
+
pinia: Pinia;
|
|
528
|
+
/**
|
|
529
|
+
* Current store being extended.
|
|
530
|
+
*/
|
|
50
531
|
store: Store<Id, S, G, A>;
|
|
532
|
+
/**
|
|
533
|
+
* Initial options defining the store when calling `defineStore()`.
|
|
534
|
+
*/
|
|
535
|
+
options: DefineStoreOptionsInPlugin<Id, S, G, A>;
|
|
51
536
|
};
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
537
|
+
/**
|
|
538
|
+
* Plugin to extend every store.
|
|
539
|
+
*/
|
|
540
|
+
interface PiniaPlugin {
|
|
541
|
+
/**
|
|
542
|
+
* Plugin to extend every store. Returns an object to extend the store or
|
|
543
|
+
* nothing.
|
|
544
|
+
*
|
|
545
|
+
* @param context - Context
|
|
546
|
+
*/
|
|
547
|
+
(context: PiniaPluginContext): Partial<PiniaCustomProperties & PiniaCustomStateProperties> | void;
|
|
63
548
|
}
|
|
64
|
-
|
|
549
|
+
//#endregion
|
|
550
|
+
//#region src/createPinia.d.ts
|
|
551
|
+
/**
|
|
552
|
+
* Creates a Pinia instance to be used by the application
|
|
553
|
+
*/
|
|
65
554
|
declare function createPinia(): Pinia;
|
|
66
|
-
declare function setActivePinia(_pinia: Pinia): void;
|
|
67
555
|
//#endregion
|
|
68
|
-
|
|
556
|
+
//#region src/store.d.ts
|
|
557
|
+
/**
|
|
558
|
+
* Creates a `useStore` function that retrieves the store instance
|
|
559
|
+
*
|
|
560
|
+
* @param id - id of the store (must be unique)
|
|
561
|
+
* @param options - options to define the store
|
|
562
|
+
*/
|
|
563
|
+
declare function defineStore<Id extends string, S extends StateTree = {}, G extends _GettersTree<S> = {}, A = {}>(id: Id, options: Omit<DefineStoreOptions<Id, S, G, A>, 'id'>): StoreDefinition<Id, S, G, A>;
|
|
564
|
+
//#endregion
|
|
565
|
+
export { type DefineSetupStoreOptions, type DefineStoreOptions, type DefineStoreOptionsBase, type DefineStoreOptionsInPlugin, MutationType, type Pinia, type PiniaCustomProperties, type PiniaCustomStateProperties, type PiniaPlugin, type PiniaPluginContext, type StateTree, type Store, type StoreDefinition, type StoreGeneric, type StoreOnActionListener, type StoreOnActionListenerContext, type StoreProperties, type SubscriptionCallback, type SubscriptionCallbackMutation, type SubscriptionCallbackMutationDirect, type SubscriptionCallbackMutationPatchFunction, type SubscriptionCallbackMutationPatchObject, type _ActionsTree, type _DeepPartial, type _ExtractActionsFromSetupStore, type _ExtractActionsFromSetupStore_Keys, type _ExtractGettersFromSetupStore, type _ExtractGettersFromSetupStore_Keys, type _ExtractStateFromSetupStore, type _ExtractStateFromSetupStore_Keys, type _GettersTree, type _Method, type _StoreOnActionListenerContext, type _StoreWithActions, type _StoreWithGetters, type _StoreWithState, type _SubscriptionCallbackMutationBase, type _UnwrapAll, createPinia, defineStore, getActivePinia, setActivePinia };
|
package/dist/index.js
CHANGED
|
@@ -1,162 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { useCallback, useId, useRef, useSyncExternalStore } from "react";
|
|
3
|
-
import { isFunction } from "savage-types";
|
|
4
|
-
import "savage-utils";
|
|
5
|
-
|
|
6
|
-
//#region src/pinia.ts
|
|
7
|
-
let pinia;
|
|
8
|
-
function createPinia() {
|
|
9
|
-
return {
|
|
10
|
-
_store: /* @__PURE__ */ new Map(),
|
|
11
|
-
_state: /* @__PURE__ */ new Map(),
|
|
12
|
-
_plugins: /* @__PURE__ */ new Set(),
|
|
13
|
-
use(p) {
|
|
14
|
-
this._plugins.add(p);
|
|
15
|
-
return this;
|
|
16
|
-
}
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
function setActivePinia(_pinia) {
|
|
20
|
-
pinia = _pinia;
|
|
21
|
-
}
|
|
22
|
-
setActivePinia(createPinia());
|
|
23
|
-
|
|
24
|
-
//#endregion
|
|
25
|
-
//#region src/utils.ts
|
|
26
|
-
function noop() {
|
|
27
|
-
return {};
|
|
28
|
-
}
|
|
29
|
-
function isPlainObject(o) {
|
|
30
|
-
return o && typeof o === "object" && Object.prototype.toString.call(o) === "[object Object]" && typeof o.toJSON !== "function";
|
|
31
|
-
}
|
|
32
|
-
function mergeReactiveObjects(target, patchToApply) {
|
|
33
|
-
if (target instanceof Map && patchToApply instanceof Map) patchToApply.forEach((value, key) => target.set(key, value));
|
|
34
|
-
if (target instanceof Set && patchToApply instanceof Set) patchToApply.forEach(target.add, target);
|
|
35
|
-
for (const key in patchToApply) {
|
|
36
|
-
if (!Object.hasOwn(patchToApply, key)) continue;
|
|
37
|
-
const subPatch = patchToApply[key];
|
|
38
|
-
const targetValue = target[key];
|
|
39
|
-
if (isPlainObject(targetValue) && isPlainObject(subPatch) && target.hasOwnProperty(key) && !isRef(subPatch) && !isReactive(subPatch)) target[key] = mergeReactiveObjects(targetValue, subPatch);
|
|
40
|
-
else target[key] = subPatch;
|
|
41
|
-
}
|
|
42
|
-
return target;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
//#endregion
|
|
46
|
-
//#region src/subscription.ts
|
|
47
|
-
const subscriptions = /* @__PURE__ */ new Set();
|
|
48
|
-
function addSubscriptions(callback, onCleanup = noop) {
|
|
49
|
-
subscriptions.add(callback);
|
|
50
|
-
const remove = () => {
|
|
51
|
-
subscriptions.delete(callback);
|
|
52
|
-
onCleanup();
|
|
53
|
-
};
|
|
54
|
-
return remove;
|
|
55
|
-
}
|
|
56
|
-
function triggerSubscription(state) {
|
|
57
|
-
subscriptions.forEach((callback) => callback(state));
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
//#endregion
|
|
61
|
-
//#region src/defineStore.ts
|
|
62
|
-
let isLoadingPlugin = false;
|
|
63
|
-
function defineStore(id, options) {
|
|
64
|
-
let isSyncListening = false;
|
|
65
|
-
function createStore() {
|
|
66
|
-
const { state, actions, getters } = options;
|
|
67
|
-
const $state = reactive(state ? state() : {});
|
|
68
|
-
const initState = state ? state() : {};
|
|
69
|
-
const baseStore = {
|
|
70
|
-
$id: id,
|
|
71
|
-
$state,
|
|
72
|
-
$patch(val) {
|
|
73
|
-
isSyncListening = false;
|
|
74
|
-
if (isFunction(val)) val($state);
|
|
75
|
-
else mergeReactiveObjects($state, val);
|
|
76
|
-
isSyncListening = true;
|
|
77
|
-
triggerSubscription($state);
|
|
78
|
-
},
|
|
79
|
-
$reset() {
|
|
80
|
-
this.$patch((v) => {
|
|
81
|
-
Object.assign(v, initState);
|
|
82
|
-
});
|
|
83
|
-
},
|
|
84
|
-
$subscribe(cb) {
|
|
85
|
-
const remove = addSubscriptions(cb, () => unwatch());
|
|
86
|
-
const unwatch = watch($state, (state$1) => {
|
|
87
|
-
if (isSyncListening) cb(state$1);
|
|
88
|
-
}, {
|
|
89
|
-
deep: true,
|
|
90
|
-
flush: "sync"
|
|
91
|
-
});
|
|
92
|
-
return remove;
|
|
93
|
-
}
|
|
94
|
-
};
|
|
95
|
-
pinia._state.set(id, $state);
|
|
96
|
-
const store = reactive(Object.assign(baseStore, toRefs($state), Object.keys(actions ?? []).reduce((x, y) => Object.assign(x, { [y]: (...args) => actions[y].call(store, ...args) }), {}), Object.keys(getters || {}).reduce((computedGetters, name) => {
|
|
97
|
-
computedGetters[name] = markRaw(computed(() => {
|
|
98
|
-
return getters?.[name].call(store, store);
|
|
99
|
-
}));
|
|
100
|
-
return computedGetters;
|
|
101
|
-
}, {})));
|
|
102
|
-
const lastLoadingPlugin = isLoadingPlugin;
|
|
103
|
-
isLoadingPlugin = true;
|
|
104
|
-
pinia._plugins.forEach((p) => {
|
|
105
|
-
Object.assign(store, p({
|
|
106
|
-
store,
|
|
107
|
-
options
|
|
108
|
-
}) || {});
|
|
109
|
-
});
|
|
110
|
-
isLoadingPlugin = lastLoadingPlugin;
|
|
111
|
-
pinia._store.set(id, store);
|
|
112
|
-
}
|
|
113
|
-
const effectMap = /* @__PURE__ */ new WeakMap();
|
|
114
|
-
const subscribeMap = /* @__PURE__ */ new WeakMap();
|
|
115
|
-
function useStore() {
|
|
116
|
-
if (!pinia._store.has(id)) createStore();
|
|
117
|
-
const store = pinia._store.get(id);
|
|
118
|
-
isSyncListening = true;
|
|
119
|
-
const _id = useRef([useId()]);
|
|
120
|
-
const storeSnapshotRef = useRef({ ...store });
|
|
121
|
-
const isCollectDep = useRef(false);
|
|
122
|
-
const subscribe = useCallback((onStoreChange) => {
|
|
123
|
-
subscribeMap.set(_id.current, onStoreChange);
|
|
124
|
-
return () => {
|
|
125
|
-
const effect$1 = effectMap.get(_id.current);
|
|
126
|
-
if (effect$1) effect$1.stop();
|
|
127
|
-
subscribeMap.delete(_id.current);
|
|
128
|
-
effectMap.delete(_id.current);
|
|
129
|
-
};
|
|
130
|
-
}, []);
|
|
131
|
-
useSyncExternalStore(subscribe, () => storeSnapshotRef.current, () => storeSnapshotRef.current);
|
|
132
|
-
let effect = effectMap.get(_id.current);
|
|
133
|
-
if (!effect) {
|
|
134
|
-
const fn = () => {
|
|
135
|
-
const onStoreChange = subscribeMap.get(_id.current);
|
|
136
|
-
if (!isCollectDep.current) {
|
|
137
|
-
storeSnapshotRef.current = { ...store };
|
|
138
|
-
onStoreChange?.();
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
effect = new ReactiveEffect(fn, noop, () => {
|
|
142
|
-
if (effect?.dirty) effect.run();
|
|
143
|
-
});
|
|
144
|
-
activeEffect.value = effect;
|
|
145
|
-
isCollectDep.current = true;
|
|
146
|
-
effect.run();
|
|
147
|
-
effectMap.set(_id.current, effect);
|
|
148
|
-
isCollectDep.current = false;
|
|
149
|
-
}
|
|
150
|
-
return store;
|
|
151
|
-
}
|
|
152
|
-
useStore.$id = id;
|
|
153
|
-
useStore.$getStore = () => {
|
|
154
|
-
if (!pinia._store.has(id)) createStore();
|
|
155
|
-
const store = pinia._store.get(id);
|
|
156
|
-
return store;
|
|
157
|
-
};
|
|
158
|
-
return useStore;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
//#endregion
|
|
162
|
-
export { createPinia, defineStore, pinia, setActivePinia };
|
|
1
|
+
import{ReactiveEffect as e,activeEffect as t,computed as n,effectScope as r,isReactive as i,isRef as a,markRaw as o,nextTick as s,reactive as c,ref as l,toRaw as u,toRefs as d,watch as f}from"@maoism/runtime-core";import{useCallback as p,useId as m,useRef as h,useSyncExternalStore as g}from"react";import"savage-types";import"savage-utils";const _=()=>v;let v;function y(e){v=e}function b(){let e=r(!0),t=e.run(()=>l({})),n=[],i=o({use(e){return n.push(e),this},_p:n,_e:e,_s:new Map,state:t});return y(i),i}const x=()=>{};function S(e,t,n,r=x){e.add(t);let i=()=>{e.delete(t),r()};return i}function C(e,...t){e.forEach(e=>{e(...t)})}let w=function(e){return e.direct=`direct`,e.patchObject=`patch object`,e.patchFunction=`patch function`,e}({});function T(){return{}}function E(e){return e&&typeof e==`object`&&Object.prototype.toString.call(e)===`[object Object]`&&typeof e.toJSON!=`function`}function D(e,t){for(let n in e instanceof Map&&t instanceof Map&&t.forEach((t,n)=>e.set(n,t)),e instanceof Set&&t instanceof Set&&t.forEach(e.add,e),t){if(!Object.hasOwn(t,n))continue;let r=t[n],o=e[n];E(o)&&E(r)&&e.hasOwnProperty(n)&&!a(r)&&!i(r)?e[n]=D(o,r):e[n]=r}return e}const O=Symbol(),k=Symbol(),{assign:A}=Object;function j(e,t,r){let{state:i,actions:a,getters:s}=t,c=r.state.value[e],l;function u(){c||(r.state.value[e]=i?i():{});let t=d(r.state.value[e]);return A(t,a,Object.keys(s||{}).reduce((t,i)=>(t[i]=o(n(()=>{y(r);let t=r._s.get(e);return s[i].call(t,t)})),t),{}))}return l=M(e,u,t,r),l}function M(e,t,n={},i){let a,o=A({actions:{}},n),l={deep:!0},d,p,m=new Set,h=new Set,g=[],_;function v(t){let n;d=p=!1,typeof t==`function`?(t(i.state.value[e]),n={type:w.patchFunction,storeId:e,events:g}):(D(i.state.value[e],t),n={type:w.patchObject,payload:t,storeId:e,events:g}),_=Symbol();let r=_;s().then(()=>{_===r&&(d=!0)}),p=!0,C(m,n,i.state.value[e])}let b=function(){let{state:e}=n,t=e?e():{};this.$patch(e=>{A(e,t)})},x=(t,n=``)=>{if(O in t)return t[k]=n,t;let r=function(){y(i);let n=Array.from(arguments),a=new Set,o=new Set;function s(e){a.add(e)}function c(e){o.add(e)}C(h,{args:n,name:r[k],store:E,after:s,onError:c});let l;try{l=t.apply(this&&this.$id===e?this:E,n)}catch(e){throw C(o,e),e}return l instanceof Promise?l.then(e=>(C(a,e),e)).catch(e=>(C(o,e),Promise.reject(e))):(C(a,l),l)};return r[O]=!0,r[k]=n,r},T={_p:i,$id:e,$onAction:S.bind(null,h),$patch:v,$reset:b,$subscribe(t,n={}){let r=S(m,t,n.detached,()=>o()),o=a.run(()=>f(()=>i.state.value[e],r=>{(n.flush===`sync`?p:d)&&t({storeId:e,type:w.direct,events:g},r)},A({},l,n)));return r}},E=c(T);i._s.set(e,E),a=r();let j=a.run(()=>t({action:x}));for(let e in j){let t=j[e];if(typeof t==`function`){let n=x(t,e);j[e]=n,o.actions[e]=t}}return A(E,j),A(u(E),j),Object.defineProperty(E,`$state`,{get:()=>i.state.value[e],set:e=>{v(t=>{A(t,e)})}}),i._p.forEach(e=>{A(E,a.run(()=>e({store:E,pinia:i,options:o})))}),d=!0,p=!0,E}function N(n,r){let i=new WeakMap,a=new WeakMap;function o(o){o&&y(o),o=v;let s=t.value;t.value=void 0,o._s.has(n)||j(n,r,o),t.value=s;let c=o._s.get(n),l=h([m()]),u=h({...c}),d=h(!1),f=p(e=>(a.set(l.current,e),()=>{let e=i.get(l.current);e&&e.stop(),a.delete(l.current),i.delete(l.current)}),[]);g(f,()=>u.current,()=>u.current);let _=i.get(l.current);if(!_){let n=()=>{let e=a.get(l.current);d.current||(u.current={...c},e?.())};_=new e(n,T,()=>{_?.dirty&&_.run()}),t.value=_,d.current=!0,_.run(),i.set(l.current,_),d.current=!1}return c}return o.$id=n,o.$getStore=e=>{e&&y(e),e=v,e._s.has(n)||j(n,r,e);let t=e._s.get(n);return t},o}export{w as MutationType,b as createPinia,N as defineStore,_ as getActivePinia,y as setActivePinia};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pinia-react",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"homepage": "https://github.com/savageKarl/pinia-react#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"prepare": "npx simple-git-hooks",
|
|
29
29
|
"build": "tsdown",
|
|
30
30
|
"dev": "tsdown --watch",
|
|
31
|
-
"playground-react": "vite
|
|
31
|
+
"playground-react": "vite playground/react",
|
|
32
32
|
"playground-nextjs": "pnpm next dev ./playground/nextjs",
|
|
33
33
|
"test": "vitest",
|
|
34
34
|
"semantic-release": "semantic-release",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"simple-git-hooks": "^2.13.1",
|
|
68
68
|
"tsdown": "^0.13.3",
|
|
69
69
|
"typescript": "^5.8.3",
|
|
70
|
-
"vite": "
|
|
70
|
+
"vite": "^7.1.2",
|
|
71
71
|
"vitest": "^3.2.4"
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|