forked from euvl/vue-js-modal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPluginCore.js
121 lines (102 loc) · 2.65 KB
/
PluginCore.js
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import { UNSUPPORTED_ARGUMENT_ERROR } from './utils/errors'
import { createDivInBody } from './utils'
import ModalsContainer from './components/ModalsContainer.vue'
import emitter from 'tiny-emitter/instance'
import { createVNode, render } from 'vue'
const PluginCore = (app, options = {}) => {
const subscription = {
$on: (...args) => emitter.on(...args),
$once: (...args) => emitter.once(...args),
$off: (...args) => emitter.off(...args),
$emit: (...args) => emitter.emit(...args)
}
const context = {
root: null,
componentName: options.componentName || 'Modal'
}
subscription.$on('set-modal-container', (container) => {
context.root.__modalContainer = container
})
const showStaticModal = (name, params) => {
subscription.$emit('toggle', name, true, params)
}
const showDynamicModal = (
component,
componentProps,
componentSlots,
modalProps = componentSlots || {},
modalEvents
) => {
const container = context.root?.__modalContainer
const defaults = options.dynamicDefaults || {}
if (!container) {
console.warn(
'Modal container not found. Make sure the dynamic modal container is set.'
)
return
}
container.add(
component,
componentProps,
componentSlots,
{ ...defaults, ...modalProps },
modalEvents
)
}
/**
* Creates a container for modals in the root Vue component.
*
* @param {Vue} parent
* @param {Vue} app
*/
const setDynamicModalContainer = (root) => {
context.root = root
if (!root) {
console.warn(
'Root component is undefined. Make sure the root instance is passed correctly.'
)
return
}
const element = createDivInBody()
const vnode = createVNode(ModalsContainer)
vnode.appContext = root.$.appContext
try {
return render(vnode, element)
} catch (error) {
console.error('Error rendering vnode:', error)
}
}
const show = (...args) => {
const [modal] = args
switch (typeof modal) {
case 'string':
showStaticModal(...args)
break
case 'object':
case 'function':
showDynamicModal(...args)
break
default:
console.warn(UNSUPPORTED_ARGUMENT_ERROR, modal)
}
}
const hide = (name, params) => {
subscription.$emit('toggle', name, false, params)
}
const hideAll = () => {
subscription.$emit('hide-all')
}
const toggle = (name, params) => {
subscription.$emit('toggle', name, undefined, params)
}
return {
context,
subscription,
show,
hide,
hideAll,
toggle,
setDynamicModalContainer
}
}
export default PluginCore