-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
96 lines (80 loc) Β· 2.12 KB
/
index.js
File metadata and controls
96 lines (80 loc) Β· 2.12 KB
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
const Popper = require('popper.js')
const UPDATE = 'update-popper'
let componentName
/**
* @param {Capsid} capsid The capsid object
* @param {string} [name] The name of the component. Default `popper`
*/
exports.install = (capsid, { name } = {}) => {
componentName = name || 'popper'
/**
* Popper component
*
* @example
* <div class="popper" data-popper-ref="#ref-el" data-popper-placement="left-start"></div>
*
* @see https://popper.js.org/popper-documentation.html#Popper.placements for available placements
*/
class PopperComponent {
__mount__() {
this.init()
}
parseJSON(json, propertyName) {
if (!json) {
return null
}
try {
return JSON.parse(json)
} catch (e) {
console.warn(
`Warning(capsid-popper): Can not parse the given json at ${propertyName}: ${json}`
)
return null
}
}
init() {
const { popperRef, popperPlacement, popperModifiers } = this.el.dataset
const parent = this.el.parentElement || document
const ref = parent.querySelector(popperRef)
const modifiers = this.parseJSON(popperModifiers, 'data-popper-modifiers')
if (!ref) {
throw new Error(
`popper reference not found: data-popper-ref="${popperRef}"`
)
}
if (!popperPlacement) {
throw new Error(
`popper placement is not specified: data-popper-placement="${popperPlacement}"`
)
}
this.popper = new Popper(ref, this.el, {
placement: popperPlacement,
modifiers
})
if (this.el.style.display === 'none') {
this.el.style.display = ''
}
}
@capsid.on(UPDATE)
update() {
if (this.popper) {
this.popper.destroy()
this.popper = null
}
this.init()
}
}
capsid.def(componentName, PopperComponent)
}
exports.UPDATE = UPDATE
/**
* Updates all the popper components.
*/
exports.updateAll = () => {
Array.prototype.forEach.call(
document.querySelectorAll(`.${componentName}`),
el => {
el.dispatchEvent(new CustomEvent(UPDATE))
}
)
}