forked from alpinejs/alpine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
108 lines (89 loc) · 3.1 KB
/
index.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
import Component from './component'
import { domReady, isTesting } from './utils'
const Alpine = {
version: process.env.PKG_VERSION,
start: async function () {
if (! isTesting()) {
await domReady()
}
this.discoverComponents(el => {
this.initializeComponent(el)
})
// It's easier and more performant to just support Turbolinks than listen
// to MutationObserver mutations at the document level.
document.addEventListener("turbolinks:load", () => {
this.discoverUninitializedComponents(el => {
this.initializeComponent(el)
})
})
this.listenForNewUninitializedComponentsAtRunTime(el => {
this.initializeComponent(el)
})
},
discoverComponents: function (callback) {
const rootEls = document.querySelectorAll('[x-data]');
rootEls.forEach(rootEl => {
callback(rootEl)
})
},
discoverUninitializedComponents: function (callback, el = null) {
const rootEls = (el || document).querySelectorAll('[x-data]');
Array.from(rootEls)
.filter(el => el.__x === undefined)
.forEach(rootEl => {
callback(rootEl)
})
},
listenForNewUninitializedComponentsAtRunTime: function (callback) {
const targetNode = document.querySelector('body');
const observerOptions = {
childList: true,
attributes: true,
subtree: true,
}
const observer = new MutationObserver((mutations) => {
for (let i=0; i < mutations.length; i++){
if (mutations[i].addedNodes.length > 0) {
mutations[i].addedNodes.forEach(node => {
// Discard non-element nodes (like line-breaks)
if (node.nodeType !== 1) return
// Discard any changes happening within an existing component.
// They will take care of themselves.
if (node.parentElement && node.parentElement.closest('[x-data]')) return
this.discoverUninitializedComponents((el) => {
this.initializeComponent(el)
}, node.parentElement)
})
}
}
})
observer.observe(targetNode, observerOptions)
},
initializeComponent: function (el) {
if (! el.__x) {
try {
el.__x = new Component(el)
} catch (err) {
window.setTimeout(() => {
throw err;
}, 0);
}
}
},
clone: function (component, newEl) {
if (! newEl.__x) {
newEl.__x = new Component(newEl, component.getUnobservedData())
}
}
}
if (! isTesting()) {
window.Alpine = Alpine
if (window.deferLoadingAlpine) {
window.deferLoadingAlpine(function () {
window.Alpine.start()
})
} else {
window.Alpine.start()
}
}
export default Alpine