├── .babelrc.js
├── .editorconfig
├── .github
├── dependabot.yml
└── workflows
│ ├── build.yml
│ ├── shipjs-manual-prepare.yml
│ ├── shipjs-trigger.yml
│ └── test.yml
├── .gitignore
├── .prettierignore
├── .prettierrc
├── CHANGELOG.md
├── LICENSE
├── README.md
├── assets
└── logo.png
├── examples
├── demo-vue-2
│ ├── .gitignore
│ ├── README.md
│ ├── babel.config.js
│ ├── package.json
│ ├── public
│ │ ├── favicon.ico
│ │ └── index.html
│ ├── src
│ │ ├── App.vue
│ │ ├── components
│ │ │ ├── ChildComponent.vue
│ │ │ └── ParentComponent.vue
│ │ ├── main.ts
│ │ ├── shims-vue.d.ts
│ │ └── useCounter.ts
│ ├── tsconfig.json
│ └── yarn.lock
└── demo-vue-3
│ ├── .gitignore
│ ├── README.md
│ ├── babel.config.js
│ ├── package.json
│ ├── public
│ ├── favicon.ico
│ └── index.html
│ ├── src
│ ├── App.vue
│ ├── components
│ │ ├── ChildComponent.vue
│ │ └── ParentComponent.vue
│ ├── main.js
│ └── useCounter.js
│ ├── tsconfig.json
│ └── yarn.lock
├── jest.config.js
├── package.json
├── rollup.config.js
├── specs
└── index.spec.ts
├── src
└── index.ts
├── tsconfig.json
├── tsconfig.test.json
└── yarn.lock
/.babelrc.js:
--------------------------------------------------------------------------------
1 | const { NODE_ENV } = process.env;
2 |
3 | module.exports = {
4 | presets: [
5 | [
6 | '@babel/preset-env',
7 | {
8 | modules: NODE_ENV === 'test' ? 'auto' : false,
9 | },
10 | ],
11 | ],
12 | };
13 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = space
5 | indent_size = 2
6 | charset = utf-8
7 | trim_trailing_whitespace = true
8 | insert_final_newline = true
9 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "npm" # See documentation for possible values
4 | directory: "/" # Location of package manifests
5 | schedule:
6 | interval: "weekly"
7 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 | on: [push]
3 |
4 | jobs:
5 | build:
6 | runs-on: ubuntu-latest
7 | steps:
8 | - uses: actions/checkout@v1
9 | - uses: actions/setup-node@v1
10 | with:
11 | node-version: '12.x'
12 |
13 | - name: Get yarn cache
14 | id: yarn-cache
15 | run: echo "::set-output name=dir::$(yarn cache dir)"
16 | - uses: actions/cache@v1
17 | with:
18 | path: ${{ steps.yarn-cache.outputs.dir }}
19 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
20 | restore-keys: |
21 | ${{ runner.os }}-yarn-
22 | - run: yarn
23 |
24 | - name: Build
25 | run: yarn build
26 |
--------------------------------------------------------------------------------
/.github/workflows/shipjs-manual-prepare.yml:
--------------------------------------------------------------------------------
1 | name: Ship js Manual Prepare
2 | on:
3 | issue_comment:
4 | types: [created]
5 | jobs:
6 | manual_prepare:
7 | if: |
8 | github.event_name == 'issue_comment' &&
9 | (github.event.comment.author_association == 'member' || github.event.comment.author_association == 'owner') &&
10 | startsWith(github.event.comment.body, '@shipjs prepare')
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v2
14 | with:
15 | fetch-depth: 0
16 | ref: master
17 | - uses: actions/setup-node@v1
18 | - run: |
19 | if [ -f "yarn.lock" ]; then
20 | yarn install
21 | else
22 | npm install
23 | fi
24 | - run: |
25 | git config --global user.email "github-actions[bot]@users.noreply.github.com"
26 | git config --global user.name "github-actions[bot]"
27 | - run: npm run release -- --yes --no-browse
28 | env:
29 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
30 | SLACK_INCOMING_HOOK: ${{ secrets.SLACK_INCOMING_HOOK }}
31 |
32 | create_done_comment:
33 | if: success()
34 | needs: manual_prepare
35 | runs-on: ubuntu-latest
36 | steps:
37 | - uses: actions/github@master
38 | env:
39 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
40 | with:
41 | args: comment "@${{ github.actor }} `shipjs prepare` done"
42 |
43 | create_fail_comment:
44 | if: cancelled() || failure()
45 | needs: manual_prepare
46 | runs-on: ubuntu-latest
47 | steps:
48 | - uses: actions/github@master
49 | env:
50 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
51 | with:
52 | args: comment "@${{ github.actor }} `shipjs prepare` fail"
53 |
--------------------------------------------------------------------------------
/.github/workflows/shipjs-trigger.yml:
--------------------------------------------------------------------------------
1 | name: Ship js trigger
2 | on:
3 | pull_request:
4 | types:
5 | - closed
6 | jobs:
7 | build:
8 | name: Release
9 | runs-on: ubuntu-latest
10 | if: github.event.pull_request.merged == true && startsWith(github.head_ref, 'releases/v')
11 | steps:
12 | - uses: actions/checkout@v2
13 | with:
14 | fetch-depth: 0
15 | ref: master
16 | - uses: actions/setup-node@v1
17 | with:
18 | registry-url: "https://registry.npmjs.org"
19 | - run: |
20 | if [ -f "yarn.lock" ]; then
21 | yarn install
22 | else
23 | npm install
24 | fi
25 | - run: npx shipjs trigger
26 | env:
27 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
28 | NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
29 | SLACK_INCOMING_HOOK: ${{ secrets.SLACK_INCOMING_HOOK }}
30 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 | on: [push]
3 |
4 | jobs:
5 | build:
6 | runs-on: ubuntu-latest
7 | steps:
8 | - uses: actions/checkout@v1
9 | - uses: actions/setup-node@v1
10 | with:
11 | node-version: '12.x'
12 |
13 | - name: Get yarn cache
14 | id: yarn-cache
15 | run: echo "::set-output name=dir::$(yarn cache dir)"
16 | - uses: actions/cache@v1
17 | with:
18 | path: ${{ steps.yarn-cache.outputs.dir }}
19 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
20 | restore-keys: |
21 | ${{ runner.os }}-yarn-
22 | - run: yarn
23 |
24 | - name: Test
25 | run: yarn test
26 |
27 | - uses: codecov/codecov-action@v1
28 | with:
29 | token: ${{ secrets.CODECOV_TOKEN }}
30 | directory: ./packages/vue-unstated/coverage
31 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 | .rts2_cache_*
4 | lib
5 | coverage
6 |
7 | # Log files
8 | npm-debug.log*
9 | yarn-debug.log*
10 | yarn-error.log*
11 |
12 | # Editor directories and files
13 | .idea
14 | .vscode
15 | *.suo
16 | *.ntvs*
17 | *.njsproj
18 | *.sln
19 | *.sw*
20 | *.iml
21 | *.iws
22 | *.ipr
23 |
24 | *.map
25 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | package.json
2 | tsconfig.json
3 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "trailingComma": "es5",
3 | "semi": true,
4 | "singleQuote": true
5 | }
6 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## [0.1.2](https://github.com/resessh/vue-unstated/compare/v0.1.1...v0.1.2) (2020-09-18)
2 |
3 |
4 | ### Bug Fixes
5 |
6 | * remove unnecessary peer deps ([58d9d3d](https://github.com/resessh/vue-unstated/commit/58d9d3db791deb2a9d2fc76d5eb00b747e81f6ab))
7 |
8 |
9 |
10 | ## [0.1.1](https://github.com/resessh/vue-unstated/compare/v0.1.0...v0.1.1) (2020-09-17)
11 |
12 |
13 | ### Bug Fixes
14 |
15 | * fix type definition file path mistake ([a0ec407](https://github.com/resessh/vue-unstated/commit/a0ec407bb653ecd0d896f00766851101b2673014))
16 |
17 |
18 |
19 | # [0.1.0](https://github.com/resessh/vue-unstated/compare/v0.0.7...v0.1.0) (2020-09-17)
20 |
21 |
22 | ### Features
23 |
24 | * Enable using from Vue 3 ([5f3e3e6](https://github.com/resessh/vue-unstated/commit/5f3e3e683e3aa7b457f9c56b4d3b35fb4acb7571))
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright
2 |
3 | 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:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | 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.
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | ----
13 | # vue-unstated
14 | A tiny state management library for Vue Composition API based on [unstated-next](https://github.com/jamiebuilds/unstated-next) which is for React.
15 |
16 | ## :horse_racing: Demo
17 | [![Edit [vue-unstated DEMO] Todo](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/ugdg7-ugdg7?fontsize=14&hidenavigation=1&module=%2Fsrc%2Fuse%2Ftodos.js&theme=dark)
18 |
19 | ## :electric_plug: Installation
20 | ```shell
21 | $ npm install --save vue-unstated
22 | ```
23 | or
24 | ```shell
25 | $ yarn add vue-unstated
26 | ```
27 |
28 | ## :surfer: Usage
29 | __use/counter.js__
30 | ```js
31 | import { reactive } from '@vue/composition-api' // Vue 2 with @vue/composition-api
32 | import { reactive } from 'vue' // or Vue 3
33 | import { createContainer } from 'vue-unstated'
34 |
35 | const useCounter = (initialState = { count: 0 }) => {
36 | const state = reactive(initialState)
37 |
38 | const increment = () => {
39 | state.count++
40 | }
41 |
42 | return { state, increment }
43 | }
44 |
45 | export const counterContainer = createContainer(useCounter)
46 | ```
47 |
48 | __Parent.vue__
49 | ```vue
50 |
67 | ```
68 |
69 | __Child.vue__
70 | ```vue
71 |
86 | ```
87 |
88 | ## :checkered_flag: LICENSE
89 | MIT
90 |
--------------------------------------------------------------------------------
/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/resessh/vue-unstated/1fd71bb087339ff78adb43587527dcc302df3ccc/assets/logo.png
--------------------------------------------------------------------------------
/examples/demo-vue-2/.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 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/README.md:
--------------------------------------------------------------------------------
1 | # demo-vue-2
2 |
3 | ## Project setup
4 | ```
5 | yarn install
6 | ```
7 |
8 | ### Compiles and hot-reloads for development
9 | ```
10 | yarn serve
11 | ```
12 |
13 | ### Compiles and minifies for production
14 | ```
15 | yarn build
16 | ```
17 |
18 | ### Lints and fixes files
19 | ```
20 | yarn lint
21 | ```
22 |
23 | ### Customize configuration
24 | See [Configuration Reference](https://cli.vuejs.org/config/).
25 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: [
3 | '@vue/cli-plugin-babel/preset'
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "demo-vue-2",
3 | "version": "0.1.0",
4 | "private": true,
5 | "scripts": {
6 | "serve": "vue-cli-service serve",
7 | "build": "vue-cli-service build",
8 | "lint": "vue-cli-service lint"
9 | },
10 | "dependencies": {
11 | "@vue/composition-api": "^1.0.0-beta.14",
12 | "core-js": "^3.6.5",
13 | "vue": "^2.6.11",
14 | "vue-unstated": "^0.1.1"
15 | },
16 | "devDependencies": {
17 | "@vue/cli-plugin-babel": "~4.5.0",
18 | "@vue/cli-plugin-typescript": "^4.5.6",
19 | "@vue/cli-service": "~4.5.0",
20 | "typescript": "^4.0.2",
21 | "vue-template-compiler": "^2.6.11"
22 | },
23 | "browserslist": [
24 | "> 1%",
25 | "last 2 versions",
26 | "not dead"
27 | ]
28 | }
29 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/resessh/vue-unstated/1fd71bb087339ff78adb43587527dcc302df3ccc/examples/demo-vue-2/public/favicon.ico
--------------------------------------------------------------------------------
/examples/demo-vue-2/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | <%= htmlWebpackPlugin.options.title %>
9 |
10 |
11 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/src/App.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
17 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/src/components/ChildComponent.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Child
4 |
Count: {{ state.count }}
5 |
6 |
7 |
8 |
9 |
25 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/src/components/ParentComponent.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Parent
4 |
Count: {{ state.count }}
5 |
6 |
7 |
8 |
9 |
10 |
29 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/src/main.ts:
--------------------------------------------------------------------------------
1 | import Vue from 'vue';
2 | import VueCompositionAPI from '@vue/composition-api';
3 |
4 | import App from './App.vue';
5 |
6 | Vue.use(VueCompositionAPI);
7 | Vue.config.productionTip = false;
8 |
9 | new Vue({
10 | render: (h) => h(App),
11 | }).$mount('#app');
12 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/src/shims-vue.d.ts:
--------------------------------------------------------------------------------
1 | declare module '*.vue' {
2 | import Vue from 'vue';
3 | export default Vue;
4 | }
5 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/src/useCounter.ts:
--------------------------------------------------------------------------------
1 | import { reactive } from '@vue/composition-api';
2 | import { createContainer } from 'vue-unstated';
3 |
4 | const useCounter = (initialState = { count: 0 }) => {
5 | const state = reactive(initialState);
6 |
7 | const increment = () => {
8 | state.count++;
9 | };
10 |
11 | return { state, increment };
12 | };
13 |
14 | export const counterContainer = createContainer(useCounter);
15 |
--------------------------------------------------------------------------------
/examples/demo-vue-2/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "esnext",
5 | "strict": true,
6 | "importHelpers": true,
7 | "moduleResolution": "node",
8 | "esModuleInterop": true,
9 | "allowSyntheticDefaultImports": true,
10 | "sourceMap": true,
11 | "baseUrl": ".",
12 | "types": [
13 | "webpack-env"
14 | ],
15 | "paths": {
16 | "@/*": [
17 | "src/*"
18 | ]
19 | },
20 | "lib": [
21 | "esnext",
22 | "dom",
23 | "dom.iterable",
24 | "scripthost"
25 | ]
26 | },
27 | "include": [
28 | "src/**/*.ts",
29 | "src/**/*.vue"
30 | ],
31 | "exclude": [
32 | "node_modules"
33 | ]
34 | }
35 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/.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 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/README.md:
--------------------------------------------------------------------------------
1 | # demo-vue-3
2 |
3 | ## Project setup
4 | ```
5 | yarn install
6 | ```
7 |
8 | ### Compiles and hot-reloads for development
9 | ```
10 | yarn serve
11 | ```
12 |
13 | ### Compiles and minifies for production
14 | ```
15 | yarn build
16 | ```
17 |
18 | ### Lints and fixes files
19 | ```
20 | yarn lint
21 | ```
22 |
23 | ### Customize configuration
24 | See [Configuration Reference](https://cli.vuejs.org/config/).
25 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: [
3 | '@vue/cli-plugin-babel/preset'
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "demo-vue-3",
3 | "version": "0.1.0",
4 | "private": true,
5 | "scripts": {
6 | "serve": "vue-cli-service serve",
7 | "build": "vue-cli-service build",
8 | "lint": "vue-cli-service lint"
9 | },
10 | "dependencies": {
11 | "core-js": "^3.6.5",
12 | "vue": "^3.0.0-0",
13 | "vue-unstated": "^0.1.1"
14 | },
15 | "devDependencies": {
16 | "@vue/cli-plugin-babel": "~4.5.0",
17 | "@vue/cli-service": "~4.5.0",
18 | "@vue/compiler-sfc": "^3.0.0-0"
19 | },
20 | "browserslist": [
21 | "> 1%",
22 | "last 2 versions",
23 | "not dead"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/resessh/vue-unstated/1fd71bb087339ff78adb43587527dcc302df3ccc/examples/demo-vue-3/public/favicon.ico
--------------------------------------------------------------------------------
/examples/demo-vue-3/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | <%= htmlWebpackPlugin.options.title %>
9 |
10 |
11 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/src/App.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
21 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/src/components/ChildComponent.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Child
4 |
Count: {{ state.count }}
5 |
6 |
7 |
8 |
9 |
24 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/src/components/ParentComponent.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Parent
4 |
Count: {{ state.count }}
5 |
6 |
7 |
8 |
9 |
10 |
28 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/src/main.js:
--------------------------------------------------------------------------------
1 | import { createApp } from 'vue';
2 | import App from './App.vue';
3 |
4 | createApp(App).mount('#app');
5 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/src/useCounter.js:
--------------------------------------------------------------------------------
1 | import { reactive } from 'vue';
2 | import { createContainer } from 'vue-unstated';
3 |
4 | const useCounter = (initialState = { count: 0 }) => {
5 | const state = reactive(initialState);
6 |
7 | const increment = () => {
8 | state.count++;
9 | };
10 |
11 | return { state, increment };
12 | };
13 |
14 | export const counterContainer = createContainer(useCounter);
15 |
--------------------------------------------------------------------------------
/examples/demo-vue-3/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "esnext",
5 | "strict": true,
6 | "importHelpers": true,
7 | "moduleResolution": "node",
8 | "esModuleInterop": true,
9 | "allowSyntheticDefaultImports": true,
10 | "sourceMap": true,
11 | "baseUrl": ".",
12 | "types": [
13 | "webpack-env"
14 | ],
15 | "paths": {
16 | "@/*": [
17 | "src/*"
18 | ]
19 | },
20 | "lib": [
21 | "esnext",
22 | "dom",
23 | "dom.iterable",
24 | "scripthost"
25 | ]
26 | },
27 | "include": [
28 | "src/**/*.ts",
29 | "src/**/*.vue", "src/useCounter.js", "src/main.js"
30 | ],
31 | "exclude": [
32 | "node_modules"
33 | ]
34 | }
35 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | preset: 'ts-jest',
3 | globals: { 'ts-jest': { tsConfig: './tsconfig.test.json' } },
4 | testEnvironment: 'jsdom',
5 | collectCoverage: true,
6 | collectCoverageFrom: ['/src/**/*.ts'],
7 | };
8 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "vue-unstated",
3 | "version": "0.1.2",
4 | "description": "A tiny state management library for Vue Composition API.",
5 | "repository": "ssh://git@github.com/resessh/vue-unstated.git",
6 | "homepage": "https://github.com/resessh/vue-unstated#readme",
7 | "bugs": {
8 | "url": "https://github.com/resessh/vue-unstated/issues"
9 | },
10 | "author": "resessh ",
11 | "license": "MIT",
12 | "keywords": [
13 | "vue",
14 | "vue3",
15 | "state-management",
16 | "composition-api",
17 | "function-api"
18 | ],
19 | "main": "lib/vue-unstated.js",
20 | "module": "lib/vue-unstated.esm.js",
21 | "unpkg": "lib/vue-unstated.umd.js",
22 | "types": "lib/index.d.ts",
23 | "files": [
24 | "lib"
25 | ],
26 | "scripts": {
27 | "build": "rm -rf lib && rollup -c",
28 | "prettier": "prettier --write ./**/*.ts",
29 | "test": "jest --coverage",
30 | "release": "shipjs prepare",
31 | "commit": "cz"
32 | },
33 | "devDependencies": {
34 | "@babel/core": "^7.11.6",
35 | "@babel/preset-env": "^7.11.5",
36 | "@types/jest": "^26.0.13",
37 | "@vue/composition-api": "^1.0.0-beta.14",
38 | "@vue/test-utils": "^1.1.0",
39 | "commitizen": "^4.2.1",
40 | "jest": "^26.4.2",
41 | "prettier": "^2.1.2",
42 | "rollup": "^2.27.0",
43 | "rollup-plugin-babel": "^4.3.3",
44 | "rollup-plugin-external-globals": "^0.6.0",
45 | "rollup-plugin-terser": "^7.0.2",
46 | "rollup-plugin-typescript2": "^0.29.0",
47 | "shipjs": "0.22.0",
48 | "ts-jest": "^26.3.0",
49 | "typescript": "^4.0.2",
50 | "vue": "^2.6.12",
51 | "vue-template-compiler": "^2.6.12"
52 | },
53 | "dependencies": {
54 | "vue-demi": "^0.4.0"
55 | },
56 | "config": {
57 | "commitizen": {
58 | "path": "./node_modules/cz-conventional-changelog"
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import babel from 'rollup-plugin-babel';
2 | import { terser } from 'rollup-plugin-terser';
3 | import typescript from 'rollup-plugin-typescript2';
4 | import externalGlobals from 'rollup-plugin-external-globals';
5 | import pkg from './package.json';
6 |
7 | const input = 'src/index.ts';
8 |
9 | export default () => {
10 | const configs = [
11 | // UMD
12 | {
13 | input,
14 | output: {
15 | name: 'VueUnstated',
16 | file: pkg.unpkg,
17 | format: 'umd',
18 | },
19 | plugins: [
20 | typescript({
21 | typescript: require('typescript'),
22 | }),
23 | babel({
24 | exclude: ['node_modules/**'],
25 | }),
26 | terser({
27 | output: {
28 | comments: /^!/,
29 | },
30 | }),
31 | externalGlobals({
32 | vue: 'Vue',
33 | }),
34 | ],
35 | },
36 |
37 | // CommonJS and ES module
38 | {
39 | input,
40 | external: ['vue'],
41 | output: [
42 | {
43 | file: pkg.main,
44 | format: 'cjs',
45 | },
46 | {
47 | file: pkg.module,
48 | format: 'es',
49 | },
50 | ],
51 | plugins: [
52 | typescript({
53 | typescript: require('typescript'),
54 | }),
55 | babel({
56 | exclude: ['node_modules/**'],
57 | }),
58 | ],
59 | },
60 | ];
61 |
62 | return configs;
63 | };
64 |
--------------------------------------------------------------------------------
/specs/index.spec.ts:
--------------------------------------------------------------------------------
1 | import { createLocalVue, mount } from '@vue/test-utils';
2 | import VueCompositionApi, {
3 | reactive,
4 | defineComponent,
5 | } from '@vue/composition-api';
6 | import { createContainer } from '../src';
7 |
8 | // type
9 | import { CreateElement } from 'vue';
10 |
11 | const localVue = createLocalVue();
12 | localVue.use(VueCompositionApi);
13 |
14 | describe('useContainer', () => {
15 | // disable error logs.
16 | let consoleSpy: jest.SpyInstance;
17 | beforeEach(() => {
18 | consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {
19 | /* noop */
20 | });
21 | });
22 | afterEach(() => {
23 | consoleSpy.mockRestore();
24 | });
25 |
26 | const container = createContainer(
27 | (initialState: { count: number } = { count: 0 }) => {
28 | const state = reactive(initialState);
29 | const increment = () => {
30 | state.count++;
31 | };
32 |
33 | return { state, increment };
34 | }
35 | );
36 |
37 | it('should work.', () => {
38 | const ChildComponent = defineComponent({
39 | setup() {
40 | const { state, increment } = container.useContainer();
41 |
42 | return { state, increment };
43 | },
44 | template: ``,
45 | });
46 |
47 | const ParentComponent = defineComponent({
48 | components: { ChildComponent },
49 | setup() {
50 | container.provide();
51 | },
52 | template: ``,
53 | });
54 |
55 | const ParentWrapper = mount(ParentComponent, { localVue });
56 | const ChildWrapper = ParentWrapper.findComponent(ChildComponent);
57 | // @ts-ignore
58 | expect(ChildWrapper.vm.state.count).toBe(0);
59 | ChildWrapper.find('button').trigger('click');
60 | // @ts-ignore
61 | expect(ChildWrapper.vm.state.count).toBe(1);
62 | });
63 |
64 | it('should work with initial props.', () => {
65 | const ParentComponent = defineComponent({
66 | setup() {
67 | const { state } = container.provide({
68 | initialState: { count: 3 },
69 | });
70 |
71 | return { state };
72 | },
73 | template: ``,
74 | });
75 |
76 | const ParentWrapper = mount(ParentComponent, { localVue });
77 | expect(ParentWrapper.vm.state.count).toBe(3);
78 | });
79 |
80 | it('throws when used in a component not provided.', () => {
81 | const ChildComponent = defineComponent({
82 | setup() {
83 | const { state, increment } = container.useContainer();
84 |
85 | return { state, increment };
86 | },
87 | template: ``,
88 | });
89 |
90 | const ParentComponent = defineComponent({
91 | setup() {
92 | container.provide();
93 | },
94 | template: ``,
95 | });
96 |
97 | mount(ParentComponent, { localVue });
98 | expect(() => {
99 | mount(ChildComponent, { localVue });
100 | }).toThrowError();
101 | });
102 | });
103 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import { provide as _provide, inject, InjectionKey } from 'vue-demi';
2 |
3 | export type ContainerProviderProps = {
4 | initialState?: State;
5 | };
6 |
7 | export type Container = {
8 | provide: (props?: ContainerProviderProps) => Value;
9 | useContainer: () => Value;
10 | };
11 |
12 | export function createContainer(
13 | useComposition: (initialState?: State) => Value
14 | ): Container {
15 | let providerSymbol: InjectionKey;
16 |
17 | function provide(props?: ContainerProviderProps): Value {
18 | providerSymbol = Symbol();
19 | const value = useComposition(props && props.initialState);
20 | _provide(providerSymbol, value);
21 |
22 | return value;
23 | }
24 |
25 | function useContainer(): Value {
26 | const value = inject(providerSymbol);
27 | if (!value) {
28 | throw new Error('Container must be used in provided Component.');
29 | }
30 | return value;
31 | }
32 |
33 | return { provide, useContainer };
34 | }
35 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Basic Options */
4 | // "incremental": true, /* Enable incremental compilation */
5 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
6 | "module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
7 | "lib": ["esnext", "dom"], /* Specify library files to be included in the compilation. */
8 | // "allowJs": true, /* Allow javascript files to be compiled. */
9 | // "checkJs": true, /* Report errors in .js files. */
10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
11 | "declaration": true, /* Generates corresponding '.d.ts' file. */
12 | "declarationMap": false, /* Generates a sourcemap for each corresponding '.d.ts' file. */
13 | "sourceMap": false, /* Generates corresponding '.map' file. */
14 | // "outFile": "./", /* Concatenate and emit output to single file. */
15 | "outDir": "./lib", /* Redirect output structure to the directory. */
16 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
17 | // "composite": true, /* Enable project compilation */
18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
19 | // "removeComments": true, /* Do not emit comments to output. */
20 | // "noEmit": true, /* Do not emit outputs. */
21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */
22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
24 |
25 | /* Strict Type-Checking Options */
26 | "strict": true, /* Enable all strict type-checking options. */
27 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
28 | // "strictNullChecks": true, /* Enable strict null checks. */
29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */
30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
34 |
35 | /* Additional Checks */
36 | // "noUnusedLocals": true, /* Report errors on unused locals. */
37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */
38 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
40 |
41 | /* Module Resolution Options */
42 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
46 | // "typeRoots": [], /* List of folders to include type definitions from. */
47 | // "types": [], /* Type declaration files to be included in compilation. */
48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
49 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
52 |
53 | /* Source Map Options */
54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
58 |
59 | /* Experimental Options */
60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
62 |
63 | /* Advanced Options */
64 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
65 | },
66 | "exclude": ["specs", "examples", "node_modules"]
67 | }
68 |
--------------------------------------------------------------------------------
/tsconfig.test.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "experimentalDecorators": true,
5 | "declaration": false,
6 | "allowJs": true,
7 | "noEmit": true,
8 | "types": ["@types/jest"]
9 | },
10 | "include": ["/src/**/*", "./specs/**/*"]
11 | }
12 |
--------------------------------------------------------------------------------