├── .changeset ├── README.md └── config.json ├── .github └── workflows │ └── release.yml ├── .gitignore ├── .npmrc ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── eslint.config.js ├── examples ├── nuxt3 │ ├── .gitignore │ ├── README.md │ ├── app.vue │ ├── nuxt.config.ts │ ├── package.json │ ├── plugins │ │ └── shared-state.ts │ ├── store │ │ └── counter.ts │ └── tsconfig.json └── vite │ ├── .gitignore │ ├── README.md │ ├── index.html │ ├── package.json │ ├── public │ └── favicon.ico │ ├── src │ ├── App.vue │ ├── assets │ │ └── logo.png │ ├── main.ts │ ├── shims-vue.d.ts │ ├── store.ts │ └── vite-env.d.ts │ ├── tsconfig.json │ └── vite.config.ts ├── package.json ├── pnpm-lock.yaml ├── pnpm-workspace.yaml ├── src ├── index.ts ├── utils.ts └── vanilla.ts ├── tsconfig.base.json ├── tsconfig.json └── tsup.config.ts /.changeset/README.md: -------------------------------------------------------------------------------- 1 | # Changesets 2 | 3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works 4 | with multi-package repos, or single-package repos to help you version and publish your code. You can 5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets) 6 | 7 | We have a quick list of common questions to get you started engaging with this project in 8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) 9 | -------------------------------------------------------------------------------- /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@3.0.5/schema.json", 3 | "changelog": "@changesets/cli/changelog", 4 | "commit": false, 5 | "fixed": [], 6 | "linked": [], 7 | "access": "public", 8 | "baseBranch": "main", 9 | "updateInternalDependencies": "patch", 10 | "ignore": ["vite-example", "nuxt-example"] 11 | } 12 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | concurrency: ${{ github.workflow }}-${{ github.ref }} 9 | 10 | jobs: 11 | release: 12 | permissions: 13 | contents: write # to create release (changesets/action) 14 | pull-requests: write # to create pull request (changesets/action) 15 | name: Release 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout Repo 19 | uses: actions/checkout@v3 20 | with: 21 | # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits 22 | fetch-depth: 0 23 | - uses: pnpm/action-setup@v4 24 | with: 25 | version: 9.15.4 26 | - name: Setup Node.js 27 | uses: actions/setup-node@v3 28 | with: 29 | node-version: 20.x 30 | cache: pnpm 31 | 32 | - run: pnpm install 33 | 34 | - name: Create Release Pull Request or Publish to npm 35 | id: changesets 36 | uses: changesets/action@v1 37 | with: 38 | publish: pnpm release 39 | env: 40 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 41 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /dist 4 | 5 | 6 | # local env files 7 | .env.local 8 | .env.*.local 9 | 10 | # Log files 11 | npm-debug.log* 12 | yarn-debug.log* 13 | yarn-error.log* 14 | pnpm-debug.log* 15 | 16 | # Editor directories and files 17 | .idea 18 | .vscode 19 | *.suo 20 | *.ntvs* 21 | *.njsproj 22 | *.sln 23 | *.sw? 24 | 25 | # npm 26 | *.tgz 27 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | ignore-workspace-root-check=true 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # pinia-shared-state 2 | 3 | ## 1.0.1 4 | 5 | ### Patch Changes 6 | 7 | - 0db3569: Remove vue 2 mention in README 8 | 9 | ## 1.0.0 10 | 11 | ### Major Changes 12 | 13 | - fe3f0e1: Introduce Pinia v3 14 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2022 Robert Soriano 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pinia-shared-state 2 | 3 | [![npm (tag)](https://img.shields.io/npm/v/pinia-shared-state?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/pinia-shared-state) ![npm bundle size](https://img.shields.io/bundlephobia/minzip/pinia-shared-state?style=flat&colorA=000000&colorB=000000) ![NPM](https://img.shields.io/npm/l/pinia-shared-state?style=flat&colorA=000000&colorB=000000) 4 | 5 | Sync your Pinia state across browser tabs. 6 | 7 | ## Requirements 8 | 9 | - vue ^3.5.11 10 | 11 | ## Install 12 | 13 | ```sh 14 | npm install pinia-shared-state 15 | ``` 16 | 17 | ## Usage 18 | 19 | ```js 20 | import { PiniaSharedState } from 'pinia-shared-state' 21 | 22 | // Pass the plugin to your application's pinia plugin 23 | pinia.use( 24 | PiniaSharedState({ 25 | // Enables the plugin for all stores. Defaults to true. 26 | enable: true, 27 | // If set to true this tab tries to immediately recover the shared state from another tab. Defaults to true. 28 | initialize: false, 29 | // Enforce a type. One of native, idb, localstorage or node. Defaults to native. 30 | type: 'localstorage', 31 | }), 32 | ) 33 | ``` 34 | 35 | ```js 36 | const useStore = defineStore({ 37 | id: 'counter', 38 | state: () => ({ 39 | count: 0, 40 | foo: 'bar', 41 | }), 42 | share: { 43 | // An array of fields that the plugin will ignore. 44 | omit: ['foo'], 45 | // Override global config for this store. 46 | enable: true, 47 | initialize: true, 48 | }, 49 | }) 50 | ``` 51 | 52 | Vanilla usage: 53 | 54 | ```ts 55 | import { share } from 'pinia-shared-state' 56 | import { onMounted, onUnmounted } from 'vue' 57 | import useStore from './store' 58 | 59 | const counterStore = useStore() 60 | 61 | onMounted(() => { 62 | const { unshare } = share('counter', counterStore, { initialize: true }) 63 | 64 | onUnmounted(() => { 65 | // Call `unshare` method to close the channel 66 | unshare() 67 | }) 68 | }) 69 | ``` 70 | 71 | ## License 72 | 73 | MIT 74 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import antfu from '@antfu/eslint-config' 2 | 3 | export default antfu({ 4 | vue: true, 5 | }) 6 | -------------------------------------------------------------------------------- /examples/nuxt3/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.log* 3 | .nuxt 4 | .nitro 5 | .cache 6 | .output 7 | .env 8 | dist 9 | -------------------------------------------------------------------------------- /examples/nuxt3/README.md: -------------------------------------------------------------------------------- 1 | # Nuxt 3 Minimal Starter 2 | 3 | Look at the [nuxt 3 documentation](https://v3.nuxtjs.org) to learn more. 4 | 5 | ## Setup 6 | 7 | Make sure to install the dependencies: 8 | 9 | ```bash 10 | # yarn 11 | yarn install 12 | 13 | # npm 14 | npm install 15 | 16 | # pnpm 17 | pnpm install --shamefully-hoist 18 | ``` 19 | 20 | ## Development Server 21 | 22 | Start the development server on http://localhost:3000 23 | 24 | ```bash 25 | npm run dev 26 | ``` 27 | 28 | ## Production 29 | 30 | Build the application for production: 31 | 32 | ```bash 33 | npm run build 34 | ``` 35 | 36 | Locally preview production build: 37 | 38 | ```bash 39 | npm run preview 40 | ``` 41 | 42 | Checkout the [deployment documentation](https://v3.nuxtjs.org/guide/deploy/presets) for more information. 43 | -------------------------------------------------------------------------------- /examples/nuxt3/app.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 20 | 21 | 89 | -------------------------------------------------------------------------------- /examples/nuxt3/nuxt.config.ts: -------------------------------------------------------------------------------- 1 | import { defineNuxtConfig } from 'nuxt/config' 2 | 3 | // https://v3.nuxtjs.org/api/configuration/nuxt.config 4 | export default defineNuxtConfig({ 5 | modules: ['@pinia/nuxt'], 6 | }) 7 | -------------------------------------------------------------------------------- /examples/nuxt3/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nuxt-example", 3 | "private": true, 4 | "scripts": { 5 | "build": "nuxt build", 6 | "dev": "nuxt dev", 7 | "generate": "nuxt generate", 8 | "preview": "nuxt preview" 9 | }, 10 | "dependencies": { 11 | "@pinia/nuxt": "^0.10.1", 12 | "nuxt": "^3.15.1", 13 | "pinia": "^3.0.1", 14 | "pinia-shared-state": "workspace:*" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /examples/nuxt3/plugins/shared-state.ts: -------------------------------------------------------------------------------- 1 | import { PiniaSharedState } from 'pinia-shared-state' 2 | 3 | export default defineNuxtPlugin((nuxtApp) => { 4 | // @ts-expect-error: Missing types? 5 | nuxtApp.$pinia.use(PiniaSharedState({ 6 | enable: true, 7 | })) 8 | }) 9 | -------------------------------------------------------------------------------- /examples/nuxt3/store/counter.ts: -------------------------------------------------------------------------------- 1 | import { acceptHMRUpdate, defineStore } from 'pinia' 2 | 3 | export const useCounterStore = defineStore('counter', { 4 | state() { 5 | return { count: 0 } 6 | }, 7 | 8 | actions: { 9 | increment() { 10 | this.count++ 11 | }, 12 | decrement() { 13 | if (!this.count) 14 | return 15 | this.count-- 16 | }, 17 | }, 18 | 19 | share: { 20 | enable: true, 21 | }, 22 | }) 23 | 24 | if (import.meta.hot) 25 | import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot)) 26 | -------------------------------------------------------------------------------- /examples/nuxt3/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // https://v3.nuxtjs.org/concepts/typescript 3 | "extends": "./.nuxt/tsconfig.json", 4 | "compilerOptions": { 5 | "moduleResolution": "bundler", 6 | "strict": true, 7 | "noEmit": true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /examples/vite/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | dist 4 | dist-ssr 5 | *.local 6 | -------------------------------------------------------------------------------- /examples/vite/README.md: -------------------------------------------------------------------------------- 1 | # Vue 3 + Typescript + Vite 2 | 3 | This template should help get you started developing with Vue 3 and Typescript in Vite. 4 | 5 | ## Recommended IDE Setup 6 | 7 | [VSCode](https://code.visualstudio.com/) + [Vetur](https://marketplace.visualstudio.com/items?itemName=octref.vetur). Make sure to enable `vetur.experimental.templateInterpolationService` in settings! 8 | 9 | ### If Using ` 12 | 13 | 14 | -------------------------------------------------------------------------------- /examples/vite/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vite-example", 3 | "type": "module", 4 | "version": "0.0.0", 5 | "private": true, 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vue-tsc --noEmit && vite build", 9 | "serve": "vite preview", 10 | "deploy": "pnpm build && gh-pages -d dist" 11 | }, 12 | "dependencies": { 13 | "pinia": "^3.0.1", 14 | "pinia-shared-state": "workspace:*", 15 | "vue": "^3.5.11" 16 | }, 17 | "devDependencies": { 18 | "@types/node": "^18.19.1", 19 | "@vitejs/plugin-vue": "^5.1.4", 20 | "gh-pages": "^6.1.0", 21 | "typescript": "^5.3.2", 22 | "vite": "^5.4.10", 23 | "vue-tsc": "^2.1.8" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /examples/vite/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wobsoriano/pinia-shared-state/fac0b8a62bd1f16849ea752ae6253e232da25e01/examples/vite/public/favicon.ico -------------------------------------------------------------------------------- /examples/vite/src/App.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 20 | 21 | 89 | -------------------------------------------------------------------------------- /examples/vite/src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wobsoriano/pinia-shared-state/fac0b8a62bd1f16849ea752ae6253e232da25e01/examples/vite/src/assets/logo.png -------------------------------------------------------------------------------- /examples/vite/src/main.ts: -------------------------------------------------------------------------------- 1 | import { createPinia } from 'pinia' 2 | import { PiniaSharedState } from 'pinia-shared-state' 3 | import { createApp } from 'vue' 4 | import App from './App.vue' 5 | 6 | const app = createApp(App) 7 | 8 | const pinia = createPinia() 9 | pinia.use(PiniaSharedState({ 10 | enable: false, 11 | type: 'native', 12 | })) 13 | 14 | app.use(pinia) 15 | 16 | app.mount('#app') 17 | -------------------------------------------------------------------------------- /examples/vite/src/shims-vue.d.ts: -------------------------------------------------------------------------------- 1 | declare module '*.vue' { 2 | import type { DefineComponent } from 'vue' 3 | 4 | const component: DefineComponent, Record, any> 5 | export default component 6 | } 7 | -------------------------------------------------------------------------------- /examples/vite/src/store.ts: -------------------------------------------------------------------------------- 1 | import { defineStore } from 'pinia' 2 | 3 | export const useCounterStore = defineStore('counter', { 4 | state: () => ({ 5 | foo: { 6 | count: 0, 7 | }, 8 | }), 9 | 10 | actions: { 11 | increment() { 12 | this.foo.count++ 13 | }, 14 | decrement() { 15 | if (!this.foo.count) 16 | return 17 | this.foo.count-- 18 | }, 19 | }, 20 | 21 | share: { 22 | enable: true, 23 | }, 24 | }) 25 | -------------------------------------------------------------------------------- /examples/vite/src/vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /examples/vite/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.base.json", 3 | "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"] 4 | } 5 | -------------------------------------------------------------------------------- /examples/vite/vite.config.ts: -------------------------------------------------------------------------------- 1 | import vue from '@vitejs/plugin-vue' 2 | import { defineConfig } from 'vite' 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [vue()], 7 | // eslint-disable-next-line node/prefer-global/process 8 | base: process.env.NODE_ENV === 'production' ? '/pinia-shared-state/' : './', 9 | }) 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pinia-shared-state", 3 | "type": "module", 4 | "publishConfig": { 5 | "access": "public" 6 | }, 7 | "version": "1.0.1", 8 | "packageManager": "pnpm@9.15.4", 9 | "author": { 10 | "name": "Robert Soriano", 11 | "email": "sorianorobertc@gmail.com" 12 | }, 13 | "license": "MIT", 14 | "funding": "https://github.com/sponsors/wobsoriano", 15 | "repository": { 16 | "type": "git", 17 | "url": "https://github.com/wobsoriano/pinia-shared-state.git" 18 | }, 19 | "sideEffects": false, 20 | "exports": { 21 | ".": { 22 | "types": { 23 | "import": "./dist/index.d.ts", 24 | "require": "./dist/index.d.cts" 25 | }, 26 | "import": "./dist/index.js", 27 | "require": "./dist/index.cjs" 28 | } 29 | }, 30 | "main": "./dist/index.cjs", 31 | "module": "./dist/index.js", 32 | "unpkg": "dist/index.global.js", 33 | "jsdelivr": "dist/index.global.js", 34 | "types": "./dist/index.d.ts", 35 | "typesVersions": { 36 | "*": { 37 | "*": [ 38 | "./dist/*", 39 | "./*" 40 | ] 41 | } 42 | }, 43 | "files": [ 44 | "dist" 45 | ], 46 | "scripts": { 47 | "build": "tsup", 48 | "dev": "pnpm build --watch --onSuccess=\"pnpm --filter vite dev\"", 49 | "dev:nuxt": "pnpm build --watch --onSuccess=\"pnpm --filter nuxt3 dev\"", 50 | "release": "pnpm build && changeset publish", 51 | "prepublishOnly": "npm run build", 52 | "lint": "eslint .", 53 | "format": "eslint . --fix" 54 | }, 55 | "peerDependencies": { 56 | "pinia": "^3.0.0" 57 | }, 58 | "dependencies": { 59 | "broadcast-channel": "^7.0.0" 60 | }, 61 | "devDependencies": { 62 | "@antfu/eslint-config": "^4.2.0", 63 | "@changesets/cli": "^2.27.12", 64 | "eslint": "^9.20.0", 65 | "pinia": "^3.0.1", 66 | "tsup": "^8.3.6", 67 | "typescript": "^5.3.2", 68 | "vue": "^3.5.11" 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - . 3 | - examples/* 4 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import type { PiniaPluginContext } from 'pinia' 2 | import type { Options } from './vanilla' 3 | import { BroadcastChannel as BroadcastChannelImpl } from 'broadcast-channel' 4 | import { serialize } from './utils' 5 | 6 | function stateHasKey(key: string, $state: PiniaPluginContext['store']['$state']) { 7 | return Object.keys($state).includes(key) 8 | } 9 | 10 | /** 11 | * Adds a `share` option to your store to share state across browser tabs. 12 | * 13 | * @example 14 | * 15 | * ```ts 16 | * import { PiniaSharedState } from 'pinia-shared-state' 17 | * 18 | * // Pass the plugin to your application's pinia plugin 19 | * pinia.use(PiniaSharedState({ enable: true, initialize: false, type: 'localstorage' })) 20 | * ``` 21 | * 22 | * @param options - Global plugin options. 23 | * @param options.enable - Enable/disable sharing of state for all stores. 24 | * @param options.initialize - Immediately recover the shared state from another tab. 25 | * @param options.type - 'native', 'idb', 'localstorage', 'node'. 26 | * @param options.serializer - Custom serializer to serialize store state before broadcasting. 27 | */ 28 | export function PiniaSharedState({ 29 | enable = true, 30 | initialize = true, 31 | type, 32 | serializer, 33 | }: Options & { enable?: boolean }) { 34 | return ({ store, options }: PiniaPluginContext) => { 35 | const isEnabled = options?.share?.enable ?? enable 36 | const omittedKeys = options?.share?.omit ?? [] 37 | if (!isEnabled) 38 | return 39 | 40 | const channel = new BroadcastChannelImpl(store.$id, { 41 | type, 42 | }) 43 | 44 | let timestamp = 0 45 | let externalUpdate = false 46 | 47 | const keysToUpdate = Object.keys(store.$state).filter(key => !omittedKeys.includes(key) && stateHasKey(key, store.$state)) 48 | 49 | channel.onmessage = (newState) => { 50 | if (newState === undefined) { 51 | channel.postMessage({ 52 | timestamp, 53 | state: serialize(store.$state, serializer), 54 | }) 55 | return 56 | } 57 | 58 | if (newState.timestamp <= timestamp) 59 | return 60 | 61 | externalUpdate = true 62 | timestamp = newState.timestamp 63 | 64 | store.$patch((state) => { 65 | keysToUpdate.forEach((key) => { 66 | state[key] = newState.state[key] 67 | }) 68 | }) 69 | } 70 | 71 | const shouldInitialize = options?.share?.initialize ?? initialize 72 | if (shouldInitialize) 73 | channel.postMessage(undefined) 74 | 75 | store.$subscribe((_, state) => { 76 | if (!externalUpdate) { 77 | timestamp = Date.now() 78 | channel.postMessage({ 79 | timestamp, 80 | state: serialize(state, serializer), 81 | }) 82 | } 83 | externalUpdate = false 84 | }) 85 | } 86 | } 87 | 88 | export { share } from './vanilla' 89 | 90 | declare module 'pinia' { 91 | // eslint-disable-next-line unused-imports/no-unused-vars 92 | export interface DefineStoreOptionsBase { 93 | /** 94 | * Override global config. 95 | * 96 | * @example 97 | * 98 | * ```js 99 | * defineStore({ 100 | * id: 'counter', 101 | * state: () => ({ count: 0, name: 'John Doe' }) 102 | * share: { 103 | * // An array of fields that the plugin will ignore. 104 | * omit: ['name'], 105 | * // Enable/disable sharing of state for this store. 106 | * enable: false 107 | * // If set to true this tab tries to immediately recover the 108 | * // shared state from another tab. Defaults to true. 109 | * initialize: false 110 | * // Serialize store state before broadcasting. Defaults to `JSON.stringify`/`JSON.parse`. 111 | * serializer: { 112 | * serialize: JSON.stringify 113 | * deserialize: JSON.parse 114 | * } 115 | * } 116 | * }) 117 | * ``` 118 | */ 119 | share?: { 120 | omit?: Array 121 | enable?: boolean 122 | initialize?: boolean 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | export interface Serializer { 2 | serialize: (value: any) => string 3 | deserialize: (value: string) => any 4 | } 5 | 6 | export function serialize( 7 | obj: Record, 8 | serializer: Serializer = { serialize: JSON.stringify, deserialize: JSON.parse }, 9 | ) { 10 | return serializer.deserialize(serializer.serialize(obj)) 11 | } 12 | -------------------------------------------------------------------------------- /src/vanilla.ts: -------------------------------------------------------------------------------- 1 | import type { MethodType } from 'broadcast-channel' 2 | import type { Store } from 'pinia' 3 | import type { Serializer } from './utils' 4 | import { BroadcastChannel as BroadcastChannelImpl } from 'broadcast-channel' 5 | import { serialize } from './utils' 6 | 7 | export interface Options { 8 | initialize?: boolean 9 | type?: MethodType 10 | serializer?: Serializer 11 | } 12 | 13 | /** 14 | * Share state across browser tabs. 15 | * 16 | * @example 17 | * 18 | * ```ts 19 | * import useStore from './store' 20 | * 21 | * const counterStore = useStore() 22 | * 23 | * share('counter', counterStore, { initialize: true }) 24 | * ``` 25 | * 26 | * @param key - A property of a store state. 27 | * @param store - The store the plugin will augment. 28 | * @param options - Share state options. 29 | * @param options.initialize - Immediately recover the shared state from another tab. 30 | * @param options.type - 'native', 'idb', 'localstorage', 'node'. 31 | * @param options.serializer - Custom serializer to serialize state before broadcasting. 32 | */ 33 | export function share( 34 | key: K, 35 | store: T, 36 | { initialize, serializer, type }: Options, 37 | ): { sync: () => void, unshare: () => void } { 38 | const channelName = `${store.$id}-${key.toString()}` 39 | 40 | const channel = new BroadcastChannelImpl(channelName, { 41 | type, 42 | }) 43 | let externalUpdate = false 44 | let timestamp = 0 45 | 46 | store.$subscribe((_, state) => { 47 | if (!externalUpdate) { 48 | timestamp = Date.now() 49 | channel.postMessage({ 50 | timestamp, 51 | newValue: serialize(state, serializer)[key], 52 | }) 53 | } 54 | externalUpdate = false 55 | }) 56 | 57 | channel.onmessage = (evt) => { 58 | if (evt === undefined) { 59 | channel.postMessage({ 60 | timestamp, 61 | // @ts-expect-error: TODO 62 | newValue: serialize(store.$state, serializer)[key], 63 | }) 64 | return 65 | } 66 | if (evt.timestamp <= timestamp) 67 | return 68 | 69 | externalUpdate = true 70 | timestamp = evt.timestamp 71 | store[key] = evt.newValue 72 | } 73 | 74 | const sync = () => channel.postMessage(undefined) 75 | const unshare = () => { 76 | return channel.close() 77 | } 78 | 79 | if (initialize) 80 | sync() 81 | 82 | return { sync, unshare } 83 | } 84 | -------------------------------------------------------------------------------- /tsconfig.base.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "jsx": "preserve", 5 | "lib": ["esnext", "dom"], 6 | "module": "esnext", 7 | "moduleResolution": "bundler", 8 | "resolveJsonModule": true, 9 | "strict": true, 10 | "noImplicitReturns": true, 11 | "noUnusedLocals": true, 12 | "noUnusedParameters": true, 13 | "sourceMap": true, 14 | "esModuleInterop": true 15 | }, 16 | "exclude": ["node_modules", "dist"] 17 | } 18 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.base.json", 3 | "compilerOptions": { 4 | "noEmit": true 5 | }, 6 | "include": ["./src"] 7 | } 8 | -------------------------------------------------------------------------------- /tsup.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'tsup' 2 | 3 | export default defineConfig({ 4 | entry: ['src/index.ts'], 5 | splitting: false, 6 | sourcemap: true, 7 | clean: true, 8 | format: ['cjs', 'esm', 'iife'], 9 | globalName: 'PiniaSharedState', 10 | external: ['vue-demi'], 11 | dts: true, 12 | }) 13 | --------------------------------------------------------------------------------