all files / src/ main.ts

91.43% Statements 32/35
38.46% Branches 5/13
92.31% Functions 12/13
93.94% Lines 31/33
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91              13× 13× 13× 13× 13× 13× 13× 13× 13×       14× 14× 14× 14× 14× 14× 14×                                                                                                    
import { DIALOG_TYPES, DEFAULT_OPTIONS, GlobalOptions } from './constants'
import { createVm, VueDialogXComponent } from './utils'
 
interface VueDialogXComponentObject {
  [index: string]: VueDialogXComponent
}
I
interface OpenOpt extends GlobalOptions {
  id?: number,
  resolve?: Function,
  reject?: Function
}
 
export class VueDialogX {
  Vue: any
  $root: VueDialogXComponentObject
  globalOptions: GlobalOptions
  constructor (Vue: any, globalOptions?: GlobalOptions) {
    this.Vue = Vue
    this.$root = {}
    if (globalOptions) this.globalOptions = globalOptions
  }
 
  open (opt: OpenOpt, dialogType: DIALOG_TYPES): Promise<void> {
    let id: number = this.mountIfNotMounted(opt.id)
    let _DEFAULT_OPTIONS: GlobalOptions = JSON.parse(JSON.stringify(DEFAULT_OPTIONS))
    let _opt: GlobalOptions = Object.assign(_DEFAULT_OPTIONS, this.globalOptions)
    return new Promise((resolve, reject) => {
      opt.resolve = resolve
      opt.reject = reject
      opt.dialogType = dialogType
      const options: GlobalOptions = Object.assign(_opt, opt)
      this.$root[id].commit(options)
    })
  }
 
  mountIfNotMounted (_id?: number): number {
    let vm: VueDialogXComponent = createVm(this.Vue)
    let id: number = 0
    _id ? id = _id : id = new Date().valueOf()
    this.$root[id] = vm
    vm.$on('confirm', () => this.remove(id))
    vm.$on('cancel', () => this.remove(id))
    return id
  }
 
  remove (id: number): void {
    this.$root[id].$off()
    this.$root[id].$destroy()
    this.$root[id].$el.remove()
    delete this.$root[id]
  }
 
  
  confirm (opt: OpenOpt = DEFAULT_OPTIONS) {
I    return this.open(opt, DIALOG_TYPES.CONFIRM)
  }
 
  alert (opt: OpenOpt = DEFAULT_OPTIONS) {
    return this.open(opt, DIALOG_TYPES.ALERT)
  }
 
  prompt (opt: OpenOpt = DEFAULT_OPTIONS) {
    return this.open(opt, DIALOG_TYPES.PROMPT)
  }
 
  actions (opt: OpenOpt = DEFAULT_OPTIONS) {
    return this.open(opt, DIALOG_TYPES.ACTIONS)
  }
 
  dialog (opt: OpenOpt = DEFAULT_OPTIONS) {
    return this.open(opt, DIALOG_TYPES.DIALOG)
  }
 
}
 
 
 
const install = (Vue: any, options?: GlobalOptions) => {
  Vue.prototype.$dialog = new VueDialogX(Vue, options)
}
 
if (typeof window !== 'undefined' && window.Vue) {
  window.VueDialogX = VueDialogX
}
 
export default {
  install,
  VueDialogX
}