]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
refactor: merge defineStore
authorEduardo San Martin Morote <posva13@gmail.com>
Tue, 20 Jul 2021 10:27:47 +0000 (12:27 +0200)
committerEduardo San Martin Morote <posva13@gmail.com>
Tue, 20 Jul 2021 10:27:47 +0000 (12:27 +0200)
__tests__/store.patch.spec.ts
__tests__/storePlugins.spec.ts
__tests__/storeSetup.spec.ts
playground/src/stores/counterSetup.ts
size-checks/setup-store.js
src/index.ts
src/store.ts

index fbba9a75b079ade45cfd5308aba3aa3ff61d69e2..5f4f638b500730a8bc314f09599c07fb998a520a 100644 (file)
@@ -123,7 +123,7 @@ describe('store.$patch', () => {
     // const useStore = (pinia?: Pinia) => {
     //   // create a new store
     //   setActivePinia(pinia || createPinia())
-    //   return defineSetupStore('main', () => {
+    //   return defineStore('main', () => {
     //     const arr = ref([] as any[])
     //     const item = ref({ a: 0, b: 0 } as null | { a: number; b?: number })
 
index 1c198e2a5a27d15d579d80bfde81a57eb79c4792..6a7e184472cacfcd32fc977b17f2898167bdd9b2 100644 (file)
@@ -1,4 +1,4 @@
-import { createPinia, defineSetupStore, defineStore } from '../src'
+import { createPinia, defineStore } from '../src'
 import { mount } from '@vue/test-utils'
 import { App, computed, ref, toRef } from 'vue'
 
@@ -185,7 +185,7 @@ describe('store plugins', () => {
   })
 
   it('passes the options of a setup store', (done) => {
-    const useStore = defineSetupStore('main', () => {
+    const useStore = defineStore('main', () => {
       const n = ref(0)
 
       function increment() {
index df617d90b40b85da09e8deeee2fd5384e171f626..24a11ef5cd1a14c931f84b925234fe63783cb374 100644 (file)
@@ -1,15 +1,10 @@
-import {
-  createPinia,
-  defineSetupStore,
-  defineStore,
-  setActivePinia,
-} from '../src'
+import { createPinia, defineStore, setActivePinia } from '../src'
 import { computed, nextTick, ref, watch } from 'vue'
 
 function expectType<T>(value: T): void {}
 
 describe('store with setup syntax', () => {
-  const useStore = defineSetupStore('main', () => {
+  const useStore = defineStore('main', () => {
     const name = ref('Eduardo')
     const counter = ref(0)
     function increment(amount = 1) {
@@ -40,7 +35,7 @@ describe('store with setup syntax', () => {
   })
 
   it('can store a function', () => {
-    const store = defineSetupStore('main', () => {
+    const store = defineStore('main', () => {
       const fn = ref(() => {})
       function action() {}
       return { fn, action }
index 97e77c3b34c0c2d75d3c6835a331db49f3c0a2f0..fadca0a05e2553694dbc37f5641106ae433aeca2 100644 (file)
@@ -1,9 +1,9 @@
 import { computed, toRefs, reactive } from 'vue'
-import { acceptHMRUpdate, defineSetupStore } from '../../../src'
+import { acceptHMRUpdate, defineStore } from '../../../src'
 
 const delay = (t: number) => new Promise((r) => setTimeout(r, t))
 
-export const useCounter = defineSetupStore('counter-setup', () => {
+export const useCounter = defineStore('counter-setup', () => {
   const state = reactive({
     n: 0,
     incrementedTimes: 0,
index 8870abc5cf081361ee62a6229730f79e21182f84..5c02b114e840fa15075f7aa0a9a6d4d6bc4473bb 100644 (file)
@@ -1,5 +1,5 @@
-import { createPinia, defineSetupStore } from '../dist/pinia.esm-bundler'
+import { createPinia, defineStore } from '../dist/pinia.esm-bundler'
 
 createPinia()
 // @ts-ignore
-export default defineSetupStore()
+export default defineStore()
index 06ef34ae1647b1b92c293cb4bf107c9ab61d4e5f..bf7b29fd369f5e4caf6d6d657c6f76d024dcf2cb 100644 (file)
@@ -2,7 +2,7 @@ export { setActivePinia } from './rootStore'
 export { createPinia } from './createPinia'
 export type { Pinia, PiniaStorePlugin, PiniaPluginContext } from './rootStore'
 
-export { defineStore, defineSetupStore } from './store'
+export { defineStore } from './store'
 
 export type {
   StateTree,
index fe13c80858e7ef2f2a4bb1cead9a03a961b89426..6954103b68a067a86498813d7eb93808986556ad 100644 (file)
@@ -126,7 +126,7 @@ function createOptionsStore<
     )
   }
 
-  store = createSetupStore(id, setup, options, hot)
+  store = createSetupStore(id, setup, options, pinia, hot)
 
   // TODO: HMR should also replace getters here
 
@@ -149,9 +149,9 @@ function createSetupStore<
   options:
     | DefineSetupStoreOptions<Id, S, G, A>
     | DefineStoreOptions<Id, S, G, A> = {},
+  pinia: Pinia,
   hot?: boolean
 ): Store<Id, S, G, A> {
-  const pinia = getActivePinia()
   let scope!: EffectScope
   const buildState = (options as DefineStoreOptions<Id, S, G, A>).state
 
@@ -657,9 +657,41 @@ type _ExtractGettersFromSetupStore<SS> = _SpreadPropertiesFromObject<
 /**
  * Creates a `useStore` function that retrieves the store instance
  *
+ * @param id - id of the store (must be unique)
  * @param options - options to define the store
  */
-export function defineSetupStore<Id extends string, SS>(
+export function defineStore<
+  Id extends string,
+  S extends StateTree,
+  G extends GettersTree<S>,
+  // cannot extends ActionsTree because we loose the typings
+  A /* extends ActionsTree */
+>(
+  id: Id,
+  options: Omit<DefineStoreOptions<Id, S, G, A>, 'id'>
+): StoreDefinition<Id, S, G, A>
+
+/**
+ * Creates a `useStore` function that retrieves the store instance
+ *
+ * @param options - options to define the store
+ */
+export function defineStore<
+  Id extends string,
+  S extends StateTree,
+  G extends GettersTree<S>,
+  // cannot extends ActionsTree because we loose the typings
+  A /* extends ActionsTree */
+>(options: DefineStoreOptions<Id, S, G, A>): StoreDefinition<Id, S, G, A>
+
+/**
+ * Creates a `useStore` function that retrieves the store instance
+ *
+ * @param id - id of the store (must be unique)
+ * @param storeSetup - function that defines the store
+ * @param options - extra options
+ */
+export function defineStore<Id extends string, SS>(
   id: Id,
   storeSetup: () => SS,
   options?: DefineSetupStoreOptions<
@@ -673,91 +705,32 @@ export function defineSetupStore<Id extends string, SS>(
   _ExtractStateFromSetupStore<SS>,
   _ExtractGettersFromSetupStore<SS>,
   _ExtractActionsFromSetupStore<SS>
-> {
-  function useStore(
-    pinia?: Pinia | null,
-    hot?: Store
-  ): Store<
-    Id,
-    _ExtractStateFromSetupStore<SS>,
-    _ExtractGettersFromSetupStore<SS>,
-    _ExtractActionsFromSetupStore<SS>
-  > {
-    const currentInstance = getCurrentInstance()
-    pinia =
-      // in test mode, ignore the argument provided as we can always retrieve a
-      // pinia instance with getActivePinia()
-      (__TEST__ && activePinia && activePinia._testing ? null : pinia) ||
-      (currentInstance && inject(piniaSymbol))
-    if (pinia) setActivePinia(pinia)
-    // TODO: worth warning on server if no piniaKey as it can leak data
-    pinia = getActivePinia()
-
-    if (!pinia._s.has(id)) {
-      pinia._s.set(id, createSetupStore(id, storeSetup, options))
-      if (__DEV__) {
-        // @ts-expect-error: not the right inferred type
-        useStore._pinia = pinia
-      }
-    }
-
-    const store: Store<
-      Id,
-      _ExtractStateFromSetupStore<SS>,
-      _ExtractGettersFromSetupStore<SS>,
-      _ExtractActionsFromSetupStore<SS>
-    > = pinia._s.get(id)! as Store<
-      Id,
-      _ExtractStateFromSetupStore<SS>,
-      _ExtractGettersFromSetupStore<SS>,
-      _ExtractActionsFromSetupStore<SS>
-    >
-
-    if (__DEV__ && hot) {
-      const hotId = '__hot:' + id
-      const newStore = createSetupStore(hotId, storeSetup, options, true)
-      hot.hotUpdate(newStore as any)
-
-      // for state that exists in newStore, try to copy from old state
-
-      // actions
-
-      // cleanup the things
-      delete pinia.state.value[hotId]
-      pinia._s.delete(hotId)
-    }
-
-    // save stores in instances to access them devtools
-    if (__DEV__ && IS_CLIENT && currentInstance && currentInstance.proxy) {
-      const vm = currentInstance.proxy
-      const cache = '_pStores' in vm ? vm._pStores! : (vm._pStores = {})
-      // @ts-expect-error: still can't cast Store with generics to Store
-      cache[id] = store
-    }
-
-    return store
+>
+export function defineStore(idOrOptions: any, setup?: any, setupOptions?: any) {
+  let id: string
+  let options:
+    | DefineStoreOptions<string, StateTree, GettersTree<StateTree>, ActionsTree>
+    | DefineSetupStoreOptions<
+        string,
+        StateTree,
+        GettersTree<StateTree>,
+        ActionsTree
+      >
+
+  const isSetupStore = typeof setup === 'function'
+  if (typeof idOrOptions === 'string') {
+    id = idOrOptions
+    options = setupOptions
+  } else {
+    options = idOrOptions
+    id = idOrOptions.id
   }
 
-  useStore.$id = id
-
-  return useStore
-}
-
-/**
- * Creates a `useStore` function that retrieves the store instance
- *
- * @param options - options to define the store
- */
-export function defineStore<
-  Id extends string,
-  S extends StateTree,
-  G extends GettersTree<S>,
-  // cannot extends ActionsTree because we loose the typings
-  A /* extends ActionsTree */
->(options: DefineStoreOptions<Id, S, G, A>): StoreDefinition<Id, S, G, A> {
-  const { id } = options
+  if (__DEV__) {
+    // TODO: check duplicated ids
+  }
 
-  function useStore(pinia?: Pinia | null, hot?: Store) {
+  function useStore(pinia?: Pinia | null, hot?: Store): Store {
     const currentInstance = getCurrentInstance()
     pinia =
       // in test mode, ignore the argument provided as we can always retrieve a
@@ -771,11 +744,9 @@ export function defineStore<
     if (!pinia._s.has(id)) {
       pinia._s.set(
         id,
-        createOptionsStore(
-          // @ts-expect-error: bad actions
-          options,
-          pinia
-        )
+        isSetupStore
+          ? createSetupStore(id, setup, options, pinia)
+          : createOptionsStore(options as any, pinia)
       )
 
       if (__DEV__) {
@@ -784,22 +755,21 @@ export function defineStore<
       }
     }
 
-    const store: Store<Id, S, G, A> = pinia._s.get(id)! as Store<Id, S, G, A>
+    const store: Store = pinia._s.get(id)!
 
     if (__DEV__ && hot) {
       const hotId = '__hot:' + id
-      const newStore = createOptionsStore(
-        assign({}, options, { id: hotId }) as any,
-        pinia,
-        true
-      )
-      hot.hotUpdate(newStore as any)
-
-      // for state that exists in newStore, try to copy from old state
+      const newStore = isSetupStore
+        ? createSetupStore(hotId, setup, options, pinia, true)
+        : createOptionsStore(
+            assign({}, options, { id: hotId }) as any,
+            pinia,
+            true
+          )
 
-      // actions
+      hot.hotUpdate(newStore as any)
 
-      // cleanup the things
+      // cleanup the state properties and the store from the cache
       delete pinia.state.value[hotId]
       pinia._s.delete(hotId)
     }
@@ -810,11 +780,11 @@ export function defineStore<
       IS_CLIENT &&
       currentInstance &&
       currentInstance.proxy &&
+      // avoid adding stores that are just built for hot module replacement
       !hot
     ) {
       const vm = currentInstance.proxy
       const cache = '_pStores' in vm ? vm._pStores! : (vm._pStores = {})
-      // @ts-expect-error: still can't cast Store with generics to Store
       cache[id] = store
     }