├── .browserslistrc ├── .eslintrc.js ├── .gitignore ├── .npmrc ├── .prettierrc ├── LICENSE ├── README.md ├── demos └── vue3 │ ├── App.vue │ ├── components │ ├── Alert.vue │ ├── EditableTable.vue │ ├── Loader.vue │ ├── LoginModal.vue │ ├── PopupEdit.vue │ └── SimpleModal.vue │ ├── composables │ ├── useAlertMessage.ts │ └── useLoader.ts │ ├── examples │ ├── AlertExample.vue │ ├── BasicExample.vue │ ├── IntroductionPart.vue │ ├── LoaderExample.vue │ ├── PropsBehavior.vue │ └── TableExample.vue │ ├── main.ts │ └── shims-vue.d.ts ├── index.html ├── jest.config.js ├── package.json ├── pnpm-lock.yaml ├── src ├── DialogsWrapper.ts ├── createConfirmDialog.ts ├── index.ts ├── shims-vue.d.ts └── useDialogWrapper.ts ├── tests ├── components │ └── DialogComp.ts ├── unit │ └── test.spec.ts └── utils │ └── index.ts ├── tsconfig.json └── vite.config.js /.browserslistrc: -------------------------------------------------------------------------------- 1 | > 1% 2 | last 2 versions 3 | not dead 4 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | es2021: true, 5 | }, 6 | extends: [ 7 | 'plugin:vue/vue3-essential', 8 | 'eslint:recommended', 9 | '@vue/typescript/recommended', 10 | '@vue/prettier', 11 | '@vue/prettier/@typescript-eslint', 12 | ], 13 | parserOptions: { 14 | ecmaVersion: 2020, 15 | }, 16 | rules: { 17 | indent: ['error', 2], 18 | 'no-unused-vars': 'off', 19 | '@typescript-eslint/no-unused-vars': 'off', 20 | 'no-console': 'off', 21 | 'no-debugger': 'off', 22 | }, 23 | overrides: [ 24 | { 25 | files: [ 26 | '**/__tests__/*.{j,t}s?(x)', 27 | '**/tests/unit/**/*.spec.{j,t}s?(x)', 28 | ], 29 | env: { 30 | jest: true, 31 | }, 32 | }, 33 | ], 34 | } 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /dist 4 | pnpm-lock.yaml 5 | 6 | 7 | # local env files 8 | .env.local 9 | .env.*.local 10 | 11 | # Log files 12 | npm-debug.log* 13 | yarn-debug.log* 14 | yarn-error.log* 15 | pnpm-debug.log* 16 | 17 | # Editor directories and files 18 | .idea 19 | .vscode 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | shamefully-hoist=true 2 | strict-peer-dependencies=false -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "es5", 3 | "intend": 2, 4 | "semi": false, 5 | "singleQuote": true, 6 | "useTabs": false, 7 | "endOfLine": "auto" 8 | } 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Roman Harmyder 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vuejs-confirm-dialog 2 | 3 | Convert your dialogs to async functions and use them all over your project! 4 | 5 | This plugin just makes it simple to create, reuse, promisify and build chains of modal dialogs in Vue.js. It provides just one function `createConfirmDialog` that does all the hard work for you. 6 | 7 | > New documentation is ready! Try a new [site](https://vcd-docs.netlify.app) that contains all the docs of the project! 8 | > [vcd-docs.netlify.app](https://vcd-docs.netlify.app) 9 | 10 | ## About 11 | 12 | How does it work? The idea is simple, this function -- `createConfirmDialog` gets a modal component and magically provides to it emits `confirm` and `cancel` and its props values. This function returns to you a dialog instance that controls the rendering of the modal component and reacts to user decisions. It reduces you to write all the boilerplate code over and over again and makes it simple to reuse your modals everywhere in your project. 13 | 14 | You can work with dialogs like with promises or with hooks that the dialog instance generates for you. 15 | 16 | ## Installation 17 | 18 | in 3 steps 19 | 20 | ### Step 0 21 | 22 | Add the plugin to your `node_modules` 23 | 24 | ```bash 25 | npm i vuejs-confirm-dialog 26 | ``` 27 | 28 | ### Step 1 (optional) 29 | 30 | Install the plugin: 31 | 32 | ```js 33 | // main.js 34 | import { createApp } from 'vue' 35 | import App from './App.vue' 36 | import * as ConfirmDialog from 'vuejs-confirm-dialog' 37 | 38 | createApp(App).use(ConfirmDialog).mount('#app') 39 | ``` 40 | 41 | ### Step 2 42 | 43 | Add `DialogsWrapper` to `App.vue` template: 44 | 45 | ```html 46 | 47 | 55 | 56 | 61 | ``` 62 | 63 | 64 | And that's it. Now you can use it. 65 | 66 | ## Usage 67 | 68 | Build Modal Window. It must contain emits `confirm` and `cancel`. ~~It also must contain~~ ~~prop `show`~~. ~~Put `v-if="show"` in its template for conditional rendering~~(no longer need to). 69 | 70 | ```html 71 | 72 | 75 | 76 | 83 | ``` 84 | 85 | Use this modal window wherever you want in your project: 86 | 87 | ```html 88 | 89 | 104 | ``` 105 | 106 | ### Two ways of usage 107 | 108 | The plugin lets you decide how to use it. The first way is to use hooks: 109 | 110 | - `onConfirm` - hook gets a callback that runs after the user confirmed the modal message 111 | - `onCancel` - run callback if the user decides to click cancel 112 | 113 | The second way is promisify modal dialog. `reveal` the function returns a Promise, that resolves data and `isCanceled` boolean from the dialog after the user commits the action. 114 | 115 | for example(not real): 116 | 117 | ```html 118 | 132 | ``` 133 | 134 | ## Passing data to/from the dialog 135 | 136 | It will be not so useful if we will not have the option to pass data to and from а component. 137 | There are several ways to deal with it. First of all, you can pass data to the second argument of the `createConfirmDialog` function. Data must be an object with names of properties matching to props of the component you use as dialog. For example, if a component has a prop with the name `title` we have to pass this `{ title: 'Some Title' }`. So these will be the initial props that the dialog component will receive. 138 | 139 | You can change props values during the calling `reveal` function by passing to its object with props data. So you can call the `reveal` function several times with different props. This is an excellent way to reuse the same dialog in different situations. 140 | 141 | And finally, you can pass data to emit functions inside your modal dialog component: `confirm` and `cancel`. Hooks `onConfirm` and `onCancel` will receive this data. Also, it will be passed by Promise, so you can use the async/await syntax if you prefer. 142 | 143 | The full example, that displays passing data, reusing, and modal chains: 144 | 145 | ```html 146 | 172 | ``` 173 | 174 | ## Props Behavior Options 175 | 176 | Unfortunately, the way of passing props is not so clear to the developers. The problem occurs when you try to reuse a dialog instance already created with `createConfirmDialog`. See also the [issue](https://github.com/harmyderoman/vuejs-confirm-dialog/issues/21). 177 | 178 | Let's consider this process step by step. Props values ​​are assigned three times, the first time is default props values, in the component, this plugin does not show up on them in any way. The second time occurs on creating an instance of the dialog, let's define these values ​​as initial props. The third time passing values ​​is possible when the user prompts the dialog using the `reveal` method. If you don't set the props behavior options, then each time you pass values, this data will be saved. 179 | 180 | For example, if you have an alert component and you called it with the message "Authorization failed!", then next time if you don't pass a new message value, it will show this message again. 181 | 182 | Perhaps it will be convenient if every time after closing the dialog, the values ​​of the props will be reset to the initial or even default values. For this functionality, props transfer settings have been added. 183 | 184 | There are only two options: 185 | 186 | - `chore` - if `true` will tell to function reset values after closing dialog 187 | - `keepInitial` - if `true` reset props values to initial values, otherwise to default values of the component 188 | 189 | The simplest example: 190 | 191 | ```javascript 192 | const dialog = createConfirmDialog( 193 | ModalComponent, 194 | { message: 'Some message...' }, // Initial props values 195 | { chore: true, keepInitial: true } 196 | ) 197 | ``` 198 | ## Using inside Options API 199 | 200 | If you prefer you can use it with Options API inside methods. 201 | 202 | ```javascript 203 | import Dialog from './Dialog.vue' 204 | import { createConfirmDialog } from 'vuejs-confirm-dialog' 205 | 206 | export default { 207 | data(){ 208 | return { 209 | isConfirmed: false 210 | } 211 | }, 212 | methods: { 213 | showDialog(){ 214 | const dialog = createConfirmDialog(Dialog) 215 | 216 | dialog.onConfirm(() => { 217 | this.isConfirmed = true 218 | }) 219 | 220 | dialog.reveal() 221 | } 222 | } 223 | } 224 | ``` 225 | 226 | For more info check this full Vue 3 [example](https://github.com/harmyderoman/vuejs-confirm-dialog/blob/main/demos/vue3). 227 | 228 | ## Close dialogs programmable 229 | 230 | Sometimes you need to close dialogs and don't want to wait for the user's action. For these purposes, dialog instance provides method `close`. 231 | 232 | ```javascript 233 | import Alert from './Alert.vue' 234 | import { createConfirmDialog } from 'vuejs-confirm-dialog' 235 | 236 | const dialog = createConfirmDialog(Alert) 237 | 238 | dialog.reveal() 239 | 240 | setTimeout(() => { 241 | dialog.close() 242 | }, 3000) 243 | ``` 244 | 245 | It also doesn't trigger any hooks. 246 | 247 | If you need to close all dialog just call `dialog.closeAll()`. 248 | 249 | 250 | ## Demo 251 | 252 | Clone the project, install dependencies and run the following command to see the demo: 253 | 254 | ```bash 255 | pnpm run demo 256 | ``` 257 | 258 | The demo is styled by beautiful [daisyUI](https://daisyui.com/). 259 | 260 | ## Roadmap 261 | 262 | * [x] Make it work! 263 | 264 | * [x] Make it work without `show` a prop 265 | 266 | * [x] TSDoc 267 | 268 | * [x] Change testing tools to Vitest 269 | 270 | * [x] Improve tests 271 | 272 | * [x] Improve docs( reuse, passing props ...) 273 | 274 | * [x] More examples 275 | 276 | ## Thanks 277 | 278 | Inspired by [`Vueuse`](https://github.com/vueuse/vueuse) and [`vue-modal-dialogs`](https://github.com/hjkcai/vue-modal-dialogs). Thanks to all creators of these projects ❤️! 279 | 280 | Keep calm and support :ukraine:! 281 | -------------------------------------------------------------------------------- /demos/vue3/App.vue: -------------------------------------------------------------------------------- 1 | 10 | 11 | 26 | 27 | 137 | -------------------------------------------------------------------------------- /demos/vue3/components/Alert.vue: -------------------------------------------------------------------------------- 1 | 24 | 25 | 43 | 44 | 55 | 56 | -------------------------------------------------------------------------------- /demos/vue3/components/EditableTable.vue: -------------------------------------------------------------------------------- 1 | 49 | 50 | 73 | 74 | 82 | -------------------------------------------------------------------------------- /demos/vue3/components/Loader.vue: -------------------------------------------------------------------------------- 1 | 159 | 160 | 177 | -------------------------------------------------------------------------------- /demos/vue3/components/LoginModal.vue: -------------------------------------------------------------------------------- 1 | 10 | 11 | -------------------------------------------------------------------------------- /demos/vue3/components/PopupEdit.vue: -------------------------------------------------------------------------------- 1 | 17 | 18 | 38 | 39 | 67 | -------------------------------------------------------------------------------- /demos/vue3/components/SimpleModal.vue: -------------------------------------------------------------------------------- 1 | 11 | 12 | 25 | 26 | 45 | -------------------------------------------------------------------------------- /demos/vue3/composables/useAlertMessage.ts: -------------------------------------------------------------------------------- 1 | import { createConfirmDialog } from './../../../src/createConfirmDialog'; 2 | import Alert from '../components/Alert.vue' 3 | 4 | export const useAlertMessage = function(){ 5 | 6 | return function (msg: any) { 7 | const { reveal } = createConfirmDialog(Alert, { message: msg}) 8 | 9 | reveal() 10 | } 11 | } -------------------------------------------------------------------------------- /demos/vue3/composables/useLoader.ts: -------------------------------------------------------------------------------- 1 | import Loader from './../components/Loader.vue' 2 | import { createConfirmDialog } from './../../../src/index' 3 | 4 | const loader = createConfirmDialog(Loader) 5 | export const useLoader = (cb: () => any) => { 6 | 7 | const start = () => { 8 | loader.reveal({ process: cb }) 9 | } 10 | 11 | return { 12 | start, 13 | onLoaded: loader.onConfirm 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /demos/vue3/examples/AlertExample.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 39 | -------------------------------------------------------------------------------- /demos/vue3/examples/BasicExample.vue: -------------------------------------------------------------------------------- 1 | 28 | 29 | -------------------------------------------------------------------------------- /demos/vue3/examples/IntroductionPart.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 40 | 41 | 44 | -------------------------------------------------------------------------------- /demos/vue3/examples/LoaderExample.vue: -------------------------------------------------------------------------------- 1 | 23 | 24 | -------------------------------------------------------------------------------- /demos/vue3/examples/PropsBehavior.vue: -------------------------------------------------------------------------------- 1 | 46 | 47 | 113 | -------------------------------------------------------------------------------- /demos/vue3/examples/TableExample.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | -------------------------------------------------------------------------------- /demos/vue3/main.ts: -------------------------------------------------------------------------------- 1 | import { createApp } from 'vue' 2 | import App from './App.vue' 3 | import * as ConfirmDialog from '../../src/index' 4 | 5 | createApp(App).use(ConfirmDialog).mount('#app') 6 | -------------------------------------------------------------------------------- /demos/vue3/shims-vue.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | declare module '*.vue' { 3 | import type { DefineComponent } from 'vue' 4 | const component: DefineComponent<{}, {}, any> 5 | export default component 6 | } 7 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Confirm Dialog 8 | 9 | 10 | 17 |
18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: "@vue/cli-plugin-unit-jest/presets/typescript-and-babel", 3 | transform: { 4 | "^.+\\.vue$": "vue-jest", 5 | }, 6 | }; 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vuejs-confirm-dialog", 3 | "version": "0.5.2", 4 | "packageManager": "pnpm@7.12.2", 5 | "main": "./dist/vuejs-confirm-dialog.umd.js", 6 | "module": "./dist/vuejs-confirm-dialog.es.js", 7 | "types": "./dist/index.d.ts", 8 | "exports": { 9 | ".": { 10 | "import": "./dist/vuejs-confirm-dialog.es.js", 11 | "require": "./dist/vuejs-confirm-dialog.umd.js", 12 | "types": "./dist/index.d.ts" 13 | } 14 | }, 15 | "files": [ 16 | "dist/*" 17 | ], 18 | "private": false, 19 | "author": { 20 | "name": "Roman Garmider" 21 | }, 22 | "keywords": [ 23 | "vue.js", 24 | "vue", 25 | "dialogs", 26 | "vue-use" 27 | ], 28 | "license": "MIT", 29 | "scripts": { 30 | "demo": "vite --host", 31 | "lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src", 32 | "build": "vite build && vue-tsc --emitDeclarationOnly", 33 | "test": "vitest" 34 | }, 35 | "dependencies": { 36 | "@vueuse/core": "^7.7.1", 37 | "vue-demi": "0.13.11" 38 | }, 39 | "peerDependencies": { 40 | "@vue/composition-api": "^1.0.0", 41 | "vue": "^2.0.0 || >=3.0.0" 42 | }, 43 | "peerDependenciesMeta": { 44 | "@vue/composition-api": { 45 | "optional": true 46 | } 47 | }, 48 | "devDependencies": { 49 | "@types/node": "^18.17.19", 50 | "@typescript-eslint/eslint-plugin": "^4.33.0", 51 | "@typescript-eslint/parser": "^4.33.0", 52 | "@vitejs/plugin-vue": "^1.10.2", 53 | "@vue/compiler-sfc": "^3.3.4", 54 | "@vue/eslint-config-prettier": "^6.0.0", 55 | "@vue/eslint-config-typescript": "^7.0.0", 56 | "@vue/test-utils": "^2.4.1", 57 | "eslint": "^8.50.0", 58 | "eslint-plugin-prettier": "^3.4.1", 59 | "eslint-plugin-vue": "^8.7.1", 60 | "happy-dom": "^2.55.0", 61 | "pnpm": "^7.33.6", 62 | "prettier": "^2.8.8", 63 | "sass": "^1.68.0", 64 | "typescript": "^4.9.5", 65 | "vite": "^2.9.16", 66 | "vite-plugin-vue2": "1.9.0", 67 | "vitest": "^0.23.4", 68 | "vue": "^3.3.4", 69 | "vue-github-button": "^3.1.0", 70 | "vue-tsc": "^0.31.4" 71 | }, 72 | "pnpm": { 73 | "overrides": { 74 | "vue-demi": "0.13.11", 75 | "vite": "^2.8.6" 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/DialogsWrapper.ts: -------------------------------------------------------------------------------- 1 | import { h } from 'vue' 2 | import { useDialogWrapper } from './useDialogWrapper' 3 | import { defineComponent } from 'vue-demi' 4 | 5 | /** 6 | * `DialogsWrapper` - the component that contains all 7 | * modal dialogs of the app 8 | */ 9 | export default defineComponent({ 10 | name: 'DialogsWrapper', 11 | setup() { 12 | const { DialogsStore } = useDialogWrapper() 13 | 14 | return () => DialogsStore.map(dialogData => { 15 | return h(dialogData.dialog, { 16 | is: dialogData.dialog, 17 | onConfirm: dialogData.confirm, 18 | onCancel: dialogData.cancel, 19 | key: dialogData.id, 20 | ...dialogData.props 21 | }) 22 | }) 23 | } 24 | }) -------------------------------------------------------------------------------- /src/createConfirmDialog.ts: -------------------------------------------------------------------------------- 1 | import { ref, watch, computed, Component, VNodeProps, AllowedComponentProps } from 'vue-demi' 2 | import type { ComputedRef, DefineComponent, UnwrapRef } from 'vue-demi' 3 | import { useDialogWrapper } from './useDialogWrapper' 4 | import { 5 | EventHookOn, 6 | useConfirmDialog, 7 | UseConfirmDialogRevealResult, 8 | } from '@vueuse/core' 9 | 10 | export type ComponentProps = C extends new (...args: any) => any 11 | ? Omit['$props'], keyof VNodeProps | keyof AllowedComponentProps> 12 | : never 13 | 14 | type PropsBehaviorOptions = { 15 | chore: boolean, 16 | keepInitial: boolean 17 | } 18 | 19 | let lastDialogId = 0 20 | 21 | function getDialogId() { 22 | return ++lastDialogId 23 | } 24 | 25 | /** 26 | * Function that makes simple to create, reuse, 27 | * promisify and build chains of modal dialogs. 28 | * 29 | * @param dialog - a component that used for modal dialog 30 | * @param initialAttrs - new props data for dialog component, optional 31 | * @param options - props behavior settings, optional 32 | * @returns `{ reveal, isRevealed, onConfirm, onCancel, close, closeAll }` - 33 | * `reveal` - shows the component 34 | * `isRevealed` - return computed mark if the component is shown 35 | * `onConfirm` - hook that gets a callback for user's confirmation 36 | * `onCancel` - hook that gets a callback for user's canceling 37 | * `close` - close the dialog without triggering any hook and don't change `isRevealed` 38 | * `closeAll` - close all open dialogs 39 | */ 40 | export function createConfirmDialog 41 | > ( 42 | dialog: C, 43 | initialAttrs: ComponentProps = {} as ComponentProps, 44 | options: PropsBehaviorOptions = { chore: false, keepInitial: false } 45 | ): { 46 | close: () => void 47 | 48 | closeAll: () => void 49 | 50 | reveal: ( 51 | props?: ComponentProps 52 | ) => Promise> 53 | 54 | isRevealed: ComputedRef 55 | 56 | onConfirm: EventHookOn 57 | 58 | onCancel: EventHookOn 59 | } { 60 | 61 | const setAttrs = (attrs: ComponentProps | null) => { 62 | if(!attrs) { 63 | propsRef.value = {} as UnwrapRef> 64 | return 65 | } 66 | for (const prop in attrs) { 67 | // @ts-ignore 68 | propsRef.value[prop] = attrs[prop] 69 | } 70 | } 71 | 72 | const propsRef = ref({} as ComponentProps) 73 | setAttrs(initialAttrs) 74 | const revealed = ref(false) 75 | 76 | const close = () => { 77 | revealed.value = false 78 | removeDialog(DIALOG_ID) 79 | } 80 | 81 | const { addDialog, removeDialog, removeAll, DialogsStore } = useDialogWrapper() 82 | 83 | const { 84 | reveal, 85 | isRevealed, 86 | onConfirm, 87 | onReveal, 88 | onCancel, 89 | confirm, 90 | cancel 91 | } = useConfirmDialog() 92 | 93 | const DIALOG_ID = getDialogId() 94 | 95 | onReveal((props?: ComponentProps) => { 96 | 97 | revealed.value = true 98 | if(props) setAttrs(props as ComponentProps) 99 | 100 | addDialog({ 101 | id: DIALOG_ID, 102 | dialog, 103 | isRevealed, 104 | confirm, 105 | cancel, 106 | // @ts-ignore 107 | props: propsRef.value, 108 | close, 109 | revealed 110 | }) 111 | 112 | }) 113 | 114 | watch( isRevealed, 115 | (value) => { 116 | if(!value) { 117 | 118 | if(options.chore) { 119 | setAttrs(options.keepInitial ? initialAttrs : null) 120 | } 121 | 122 | removeDialog(DIALOG_ID) 123 | } 124 | }) 125 | 126 | const closeAll = () =>{ 127 | DialogsStore.forEach(dialog => { 128 | dialog.revealed.value = false 129 | }) 130 | removeAll() 131 | } 132 | 133 | return { 134 | close, 135 | closeAll, 136 | reveal, 137 | isRevealed: computed(() => isRevealed.value && revealed.value), 138 | onConfirm, 139 | onCancel, 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { createConfirmDialog } from './createConfirmDialog' 2 | import DialogsWrapper from './DialogsWrapper' 3 | 4 | import type { UseDialogWrapperReturn, DialogData } from './useDialogWrapper' 5 | import type { ComponentProps } from './createConfirmDialog' 6 | import { App } from 'vue-demi' 7 | 8 | function install(app: App) { 9 | app.component('DialogsWrapper', DialogsWrapper) 10 | } 11 | 12 | export { 13 | createConfirmDialog, 14 | DialogsWrapper, 15 | install, 16 | ComponentProps, 17 | UseDialogWrapperReturn, 18 | DialogData 19 | } 20 | -------------------------------------------------------------------------------- /src/shims-vue.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | declare module '*.vue' { 3 | import type { DefineComponent } from 'vue-demi' 4 | const component: DefineComponent<{}, {}, any> 5 | export default component 6 | } 7 | -------------------------------------------------------------------------------- /src/useDialogWrapper.ts: -------------------------------------------------------------------------------- 1 | import { markRaw, Ref, reactive, DefineComponent } from 'vue-demi' 2 | import { ComponentProps } from './index' 3 | 4 | export type UseDialogWrapperReturn = { 5 | DialogsStore: DialogData[] 6 | addDialog: (dialogData: DialogData) => void, 7 | removeDialog: (id: number) => void, 8 | removeAll: () => void 9 | } 10 | 11 | export type DialogData> = { 12 | id: number 13 | dialog: C 14 | isRevealed: Ref 15 | confirm: (props?: ComponentProps) => void 16 | cancel: (props?: ComponentProps) => void 17 | props: ComponentProps, 18 | close: () => void, 19 | revealed: Ref 20 | } 21 | 22 | const DialogsStore: DialogData[] = reactive([]) 23 | 24 | export const useDialogWrapper = function (): UseDialogWrapperReturn { 25 | 26 | const addDialog = function (dialogData: DialogData) { 27 | DialogsStore.push(markRaw(dialogData)) 28 | } 29 | 30 | const removeDialog = function (id: number){ 31 | const index = DialogsStore.findIndex(dialog => dialog.id == id) 32 | DialogsStore.splice( index, 1) 33 | } 34 | 35 | const removeAll = function () { 36 | DialogsStore.splice(0) 37 | } 38 | 39 | return { 40 | DialogsStore, 41 | addDialog, 42 | removeDialog, 43 | removeAll 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tests/components/DialogComp.ts: -------------------------------------------------------------------------------- 1 | import { defineComponent, h } from "vue" 2 | 3 | const DEFAULT_MESSAGE = "Default Message" 4 | 5 | const DialogComp = defineComponent({ 6 | emits: ['confirm', 'cancel'], 7 | props: { 8 | message: { 9 | type: String, 10 | default: DEFAULT_MESSAGE 11 | } 12 | }, 13 | render() { 14 | return h('div') 15 | } 16 | }) 17 | 18 | export default DialogComp -------------------------------------------------------------------------------- /tests/unit/test.spec.ts: -------------------------------------------------------------------------------- 1 | import { createConfirmDialog } from './../../src/index' 2 | import { useDialogWrapper } from './../../src/useDialogWrapper' 3 | import { useSetup } from '../utils' 4 | import { Component, nextTick } from 'vue' 5 | import { useConfirmDialog } from '@vueuse/core' 6 | import { describe, it, expect } from 'vitest' 7 | import { mount } from '@vue/test-utils' 8 | import DialogComp from './../components/DialogComp' 9 | import { ref } from 'vue' 10 | import DialogsWrapper from './../../src/DialogsWrapper' 11 | 12 | const INITIAL_MESSAGE = "Initial Message" 13 | 14 | const clearDialogsStore = function () { 15 | const { DialogsStore } = useDialogWrapper() 16 | while (DialogsStore.length > 0) { 17 | DialogsStore.pop() 18 | } 19 | } 20 | 21 | describe('Props Behavior Options', () => { 22 | it('should accept prop options, and do nothing with all options set to false', async () => { 23 | 24 | // @ts-ignore 25 | const { reveal } = createConfirmDialog(DialogComp, 26 | { message: INITIAL_MESSAGE}, 27 | { chore: false, keepInitial: false } 28 | ) 29 | 30 | const TEST_MESSAGE = 'test message' 31 | 32 | reveal({ message: TEST_MESSAGE }) 33 | await nextTick() 34 | const { DialogsStore } = useDialogWrapper() 35 | 36 | expect(DialogsStore[0].isRevealed.value).toBe(true) 37 | expect(DialogsStore[0].props.message).toBe(TEST_MESSAGE) 38 | 39 | DialogsStore[0].confirm() 40 | await nextTick() 41 | reveal() 42 | await nextTick() 43 | 44 | expect(DialogsStore[0].isRevealed.value).toBe(true) 45 | expect(DialogsStore[0].props.message).toBe(TEST_MESSAGE) 46 | 47 | clearDialogsStore() 48 | }) 49 | 50 | it(`should return to default props values of modal component, 51 | if { chore: true, keepInitial: false }`, async () => { 52 | 53 | // @ts-ignore 54 | const { reveal, isRevealed } = createConfirmDialog(DialogComp, 55 | { message: INITIAL_MESSAGE }, 56 | { chore: true, keepInitial: false } 57 | ) 58 | const INIT_PROP = 'test prop' 59 | reveal({ message: INIT_PROP }) 60 | await nextTick() 61 | const { DialogsStore } = useDialogWrapper() 62 | expect(DialogsStore[0].props.message).toBe(INIT_PROP) 63 | 64 | DialogsStore[0].confirm() 65 | await nextTick() 66 | expect(isRevealed.value).toBe(false) 67 | reveal() 68 | await nextTick() 69 | expect(isRevealed.value).toBe(true) 70 | expect(DialogsStore[0].props.message).toBe(undefined) 71 | 72 | clearDialogsStore() 73 | }) 74 | it(`should return to initial props values passed to create function, 75 | if { chore: true, keepInitial: true }`, async () => { 76 | 77 | // @ts-ignore 78 | const { reveal, isRevealed } = createConfirmDialog(DialogComp, 79 | { message: INITIAL_MESSAGE }, 80 | { chore: true, keepInitial: true } 81 | ) 82 | const INIT_PROP = 'test prop' 83 | reveal({ message: INIT_PROP }) 84 | await nextTick() 85 | const { DialogsStore } = useDialogWrapper() 86 | expect(DialogsStore[0].props.message).toBe(INIT_PROP) 87 | 88 | DialogsStore[0].confirm() 89 | await nextTick() 90 | expect(isRevealed.value).toBe(false) 91 | reveal() 92 | await nextTick() 93 | expect(isRevealed.value).toBe(true) 94 | expect(DialogsStore[0].props.message).toBe(INITIAL_MESSAGE) 95 | 96 | clearDialogsStore() 97 | }) 98 | }) 99 | 100 | describe('createConfirmDialog', () => { 101 | it('should be defined', () => { 102 | expect(createConfirmDialog).toBeDefined() 103 | }) 104 | 105 | it('should add Vue component to the DialogsStore', () => { 106 | // @ts-ignore 107 | const { reveal } = createConfirmDialog(DialogComp) 108 | 109 | reveal() 110 | 111 | const { DialogsStore } = useDialogWrapper() 112 | expect(DialogsStore[0].dialog).toBe(DialogComp) 113 | 114 | clearDialogsStore() 115 | }) 116 | 117 | it('should set `isRevealed.value` to `true` after call the dialog', () => { 118 | // @ts-ignore 119 | const { reveal, isRevealed } = createConfirmDialog(DialogComp) 120 | reveal() 121 | 122 | expect(isRevealed.value).toBe(true) 123 | 124 | clearDialogsStore() 125 | }) 126 | 127 | it('should set `isRevealed.value` to `false` after confirming or canceling the dialog', () => { 128 | // @ts-ignore 129 | const { reveal, isRevealed } = createConfirmDialog(DialogComp) 130 | reveal() 131 | 132 | const { DialogsStore } = useDialogWrapper() 133 | DialogsStore[0].confirm() 134 | 135 | expect(isRevealed.value).toBe(false) 136 | 137 | reveal() 138 | DialogsStore[0].cancel() 139 | 140 | expect(isRevealed.value).toBe(false) 141 | 142 | clearDialogsStore() 143 | }) 144 | 145 | it('should call `onConfirm` and `onCancel` hooks', () => { 146 | // @ts-ignore 147 | const { reveal, onConfirm, onCancel } = createConfirmDialog(DialogComp) 148 | 149 | let isCalled = false 150 | onConfirm(() => { 151 | isCalled = true 152 | }) 153 | onCancel(() => { 154 | isCalled = true 155 | }) 156 | 157 | reveal() 158 | const { DialogsStore } = useDialogWrapper() 159 | DialogsStore[0].confirm() 160 | 161 | expect(isCalled).toBe(true) 162 | 163 | isCalled = false 164 | DialogsStore[0].cancel() 165 | expect(isCalled).toBe(true) 166 | 167 | clearDialogsStore() 168 | }) 169 | 170 | it('should pass props to component by the second argument', () => { 171 | // @ts-ignore 172 | const { reveal } = createConfirmDialog(DialogComp, { message: 'message' }) 173 | reveal() 174 | 175 | const { DialogsStore } = useDialogWrapper() 176 | expect(DialogsStore[0].props.message).toBe('message') 177 | 178 | clearDialogsStore() 179 | }) 180 | 181 | it('should pass props to component by `reveal()` argument', () => { 182 | // @ts-ignore 183 | const { reveal } = createConfirmDialog(DialogComp) 184 | reveal({ message: 'message' }) 185 | 186 | const { DialogsStore } = useDialogWrapper() 187 | expect(DialogsStore[0].props.message).toBe('message') 188 | 189 | clearDialogsStore() 190 | }) 191 | 192 | it('should return promise on reveil', async () => { 193 | // @ts-ignore 194 | const { reveal } = createConfirmDialog(DialogComp) 195 | 196 | let isCanceled: boolean | undefined 197 | const { DialogsStore } = useDialogWrapper() 198 | 199 | reveal().then(result => { 200 | isCanceled = result.isCanceled 201 | }) 202 | 203 | await nextTick() 204 | 205 | DialogsStore[0].confirm() 206 | 207 | await nextTick() 208 | 209 | 210 | expect(isCanceled).toBe(false) 211 | 212 | isCanceled = undefined 213 | reveal().then(result => { 214 | isCanceled = result.isCanceled 215 | }) 216 | 217 | await nextTick() 218 | DialogsStore[0].cancel() 219 | await nextTick() 220 | 221 | expect(isCanceled).toBe(true) 222 | 223 | clearDialogsStore() 224 | }) 225 | 226 | it('should close dialog without triggering any hook', async () => { 227 | // @ts-ignore 228 | const dialog = createConfirmDialog(DialogComp) 229 | let onConfirmTriggered = false 230 | let onCancelTriggered = false 231 | 232 | dialog.onConfirm(() => { 233 | onConfirmTriggered = true 234 | }) 235 | 236 | dialog.onCancel(() => { 237 | onCancelTriggered = true 238 | }) 239 | 240 | dialog.reveal() 241 | 242 | expect(dialog.isRevealed.value).toBe(true) 243 | 244 | await nextTick() 245 | 246 | dialog.close() 247 | 248 | await nextTick() 249 | 250 | expect(dialog.isRevealed.value).toBe(false) 251 | expect(onConfirmTriggered).toBe(false) 252 | expect(onCancelTriggered).toBe(false) 253 | 254 | clearDialogsStore() 255 | }) 256 | it('should close all dialogs', async () => { 257 | // @ts-ignore 258 | const dialog = createConfirmDialog(DialogComp) 259 | // @ts-ignore 260 | const dialog2 = createConfirmDialog(DialogComp) 261 | 262 | dialog.reveal() 263 | dialog2.reveal() 264 | 265 | expect(dialog.isRevealed.value).toBe(true) 266 | expect(dialog2.isRevealed.value).toBe(true) 267 | 268 | dialog.closeAll() 269 | 270 | 271 | expect(dialog.isRevealed.value).toBe(false) 272 | expect(dialog2.isRevealed.value).toBe(false) 273 | 274 | clearDialogsStore() 275 | }) 276 | 277 | }) 278 | 279 | describe('DialogsWrapper.vue', () => { 280 | it('should be defined', () => { 281 | expect(DialogsWrapper).toBeDefined() 282 | 283 | clearDialogsStore() 284 | }) 285 | 286 | it('should mount component to the document', async () => { 287 | const wrapper = mount(DialogsWrapper) 288 | 289 | const { addDialog } = useDialogWrapper() 290 | const { isRevealed, confirm, cancel } = useConfirmDialog() 291 | addDialog({ 292 | dialog: DialogComp, 293 | isRevealed, 294 | confirm, 295 | cancel, 296 | props: {}, 297 | id: 0, 298 | close: function (): void { 299 | throw new Error('Function not implemented.') 300 | }, 301 | revealed: ref(false) 302 | }) 303 | 304 | await nextTick() 305 | 306 | const modal = wrapper.findComponent(DialogComp) 307 | expect(modal.exists()).toBe(true) 308 | 309 | clearDialogsStore() 310 | }) 311 | 312 | }) 313 | 314 | describe('useDialogWrapper', () => { 315 | it('should be defined', () => { 316 | expect(useDialogWrapper).toBeDefined() 317 | }) 318 | 319 | 320 | it('should add Vue component to the DialogsStore', async () => { 321 | const simpleComponent = {} as Component 322 | const props = {} 323 | 324 | const wrapper = useSetup(() => { 325 | const { DialogsStore, addDialog } = useDialogWrapper() 326 | const { isRevealed, confirm, cancel } = useConfirmDialog() 327 | addDialog({ 328 | dialog: simpleComponent, 329 | isRevealed, 330 | confirm, 331 | cancel, 332 | props, 333 | id: 0, 334 | close: function (): void { 335 | throw new Error('Function not implemented.') 336 | }, 337 | revealed: ref(false) 338 | }) 339 | 340 | return { DialogsStore } 341 | }) 342 | 343 | expect(wrapper.DialogsStore[0].dialog).toBe(simpleComponent) 344 | 345 | clearDialogsStore() 346 | }) 347 | }) 348 | -------------------------------------------------------------------------------- /tests/utils/index.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ 2 | import { 3 | defineComponent, 4 | createApp, 5 | h, 6 | provide, 7 | ref, 8 | InjectionKey, 9 | Ref, 10 | } from 'vue-demi' 11 | 12 | type InstanceType = V extends { new (...arg: any[]): infer X } ? X : never 13 | type VM = InstanceType & { unmount(): void } 14 | 15 | export function mount(Comp: V) { 16 | const el = document.createElement('div') 17 | const app = createApp(Comp) 18 | 19 | // @ts-ignore 20 | const unmount = () => app.unmount(el) 21 | const comp = app.mount(el) as any as VM 22 | comp.unmount = unmount 23 | return comp 24 | } 25 | 26 | export function useSetup(setup: () => V) { 27 | const Comp = defineComponent({ 28 | setup, 29 | render() { 30 | return h('div', []) 31 | }, 32 | }) 33 | 34 | return mount(Comp) 35 | } 36 | 37 | export const Key: InjectionKey> = Symbol('num') 38 | 39 | export function useInjectedSetup(setup: () => V) { 40 | const Comp = defineComponent({ 41 | setup, 42 | render() { 43 | return h('div', []) 44 | }, 45 | }) 46 | 47 | const Provider = defineComponent({ 48 | components: Comp, 49 | setup() { 50 | provide(Key, ref(1)) 51 | }, 52 | render() { 53 | return h('div', []) 54 | }, 55 | }) 56 | 57 | return mount(Provider) 58 | } 59 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "module": "esnext", 5 | "strict": true, 6 | "jsx": "preserve", 7 | "importHelpers": true, 8 | "moduleResolution": "node", 9 | "skipLibCheck": true, 10 | "esModuleInterop": true, 11 | "allowSyntheticDefaultImports": true, 12 | "sourceMap": true, 13 | "baseUrl": "./src", 14 | "declaration": true, 15 | "declarationDir": "./dist", 16 | "typeRoots": ["src"], 17 | "outDir": "./dist", 18 | "rootDir": "./src", 19 | "paths": { 20 | "@/*": [ 21 | "src/*" 22 | ] 23 | }, 24 | "lib": [ 25 | "esnext", 26 | "dom", 27 | "dom.iterable", 28 | "scripthost" 29 | ] 30 | }, 31 | "include": [ 32 | "src/**/*.ts", 33 | "src/**/*.tsx", 34 | "src/**/*.vue", 35 | "src/**/*.d.ts", 36 | "tests/**/*.ts", 37 | "tests/**/*.tsx" 38 | ], 39 | "exclude": [ 40 | "node_modules", 41 | "./tests" 42 | ] 43 | } 44 | -------------------------------------------------------------------------------- /vite.config.js: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /* eslint-disable no-undef */ 4 | /* eslint-disable @typescript-eslint/no-var-requires */ 5 | import { defineConfig } from 'vite' 6 | 7 | // for Vue 3 use this: 8 | import vue from '@vitejs/plugin-vue' 9 | 10 | // for Vue 2 use this: 11 | // import { createVuePlugin as vue } from 'vite-plugin-vue2' 12 | 13 | const path = require('path') 14 | 15 | // https://vitejs.dev/config/ 16 | export default defineConfig({ 17 | plugins: [vue()], 18 | resolve: { 19 | alias: { 20 | '@': path.resolve(__dirname, './src'), 21 | }, 22 | }, 23 | optimizeDeps: { 24 | include: [ 25 | 'vue-demi' 26 | ] 27 | }, 28 | build: { 29 | lib: { 30 | entry: path.resolve(__dirname, 'src/index.ts'), 31 | name: 'vuejs-confirm-dialog', 32 | fileName: (format) => `vuejs-confirm-dialog.${format}.js`, 33 | }, 34 | rollupOptions: { 35 | external: ['vue'], 36 | output: { 37 | globals: { 38 | vue: 'Vue', 39 | }, 40 | }, 41 | }, 42 | commonjsOptions: { 43 | include: [/vue-demi/, /node_modules/] 44 | } 45 | }, 46 | test: { 47 | environment: 'happy-dom' 48 | } 49 | }) 50 | --------------------------------------------------------------------------------