Completed
Push — master ( e9cdde...e60414 )
by Ajeh
33s
created

src/plugin/js/index.js   A

Complexity

Total Complexity 12
Complexity/F 1.2

Size

Lines of Code 86
Function Count 10

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 0
wmc 12
c 3
b 1
f 0
nc 4
mnd 1
bc 12
fnc 10
dl 0
loc 86
rs 10
bpm 1.2
cpm 1.2
noi 0

7 Functions

Rating   Name   Duplication   Size   Complexity  
A index.js ➔ Plugin 0 6 1
A Plugin.open 0 12 1
A Plugin.install 0 17 1
A Plugin.mountIfNotMounted 0 15 2
A Plugin.destroy 0 11 2
A Plugin.confirm 0 4 1
A Plugin.alert 0 4 1
1
'use strict'
2
3
import Promise from 'promise-polyfill'
4
import DialogComponent from '../components/dialog.vue'
5
import {DIALOG_TYPES, DEFAULT_OPTIONS} from './constants'
6
import Directives from './directives'
7
import {mergeObjs} from './utilities'
8
9
10
let Plugin = function(Vue, globalOptions = {}){
11
	this.Vue = Vue
12
	this.mounted = false
13
	this.$root = {} // The root component
14
    this.globalOptions = mergeObjs(DEFAULT_OPTIONS, globalOptions)
15
}
16
17
Plugin.prototype.mountIfNotMounted = function(){
18
	if(this.mounted === true){
19
		return
20
	}
21
22
	this.$root = (() => {
23
		let DialogConstructor = this.Vue.extend(DialogComponent)
24
		let node = document.createElement("div")
25
		document.querySelector('body').appendChild(node)
26
27
		return (new DialogConstructor()).$mount(node)
28
	})()
29
30
	this.mounted = true
31
}
32
33
Plugin.prototype.destroy = function(){
34
	if(this.mounted === true){
35
        this.$root.forceCloseAll()
36
37
        let elem = this.$root.$el
38
        this.$root.$destroy()
39
        this.$root.$off()
40
        elem.remove()
41
        this.mounted = false
42
	}
43
}
44
45
Plugin.prototype.alert = function(message = null, options = {}){
46
	message && (options.message = message)
47
	return this.open(DIALOG_TYPES.ALERT, options)
48
}
49
50
Plugin.prototype.confirm = function(message = null, options = {}){
51
    message && (options.message = message)
52
    return this.open(DIALOG_TYPES.CONFIRM, options)
53
}
54
55
Plugin.prototype.open = function(type, localOptions = {}){
56
	this.mountIfNotMounted()
57
	return new Promise((resolve, reject) => {
58
59
        localOptions.id = 'dialog.' + Date.now()
60
        localOptions.window = type
61
        localOptions.promiseResolver = resolve
62
        localOptions.promiseRejecter = reject
63
64
		this.$root.commit(mergeObjs(this.globalOptions, localOptions))
65
	})
66
}
67
68
Plugin.install = function (Vue, options) {
69
70
    let DirectivesObj = new Directives(Vue)
71
72
	Vue.directive('confirm', DirectivesObj.confirmDefinition)
73
74
	Vue.dialog = new Plugin(Vue, options)
75
76
	Object.defineProperties(Vue.prototype, {
77
		$dialog: {
78
			get () {
79
				return Vue.dialog
80
			}
81
		}
82
	})
83
84
}
85
86
export default Plugin