forked from alpinejs/alpine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.js
More file actions
410 lines (327 loc) · 14.9 KB
/
Copy pathcomponent.js
File metadata and controls
410 lines (327 loc) · 14.9 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import { walkSkippingNestedComponents, kebabCase, saferEval, saferEvalNoReturn, getXAttrs, debounce } from './utils'
export default class Component {
constructor(el) {
this.el = el
const rawData = saferEval(this.el.getAttribute('x-data'), {})
this.data = this.wrapDataInObservable(rawData)
this.initialize()
this.listenForNewElementsToInitialize()
}
wrapDataInObservable(data) {
this.concernedData = []
var self = this
const proxyHandler = keyPrefix => ({
set(obj, property, value) {
const propertyName = keyPrefix ? `${keyPrefix}.${property}` : property
const setWasSuccessful = Reflect.set(obj, property, value)
if (self.concernedData.indexOf(propertyName) === -1) {
self.concernedData.push(propertyName)
}
self.refresh()
return setWasSuccessful
},
get(target, key) {
if (typeof target[key] === 'object' && target[key] !== null) {
const propertyName = keyPrefix ? `${keyPrefix}.${key}` : key
return new Proxy(target[key], proxyHandler(propertyName))
}
return target[key]
}
})
return new Proxy(data, proxyHandler())
}
initialize() {
walkSkippingNestedComponents(this.el, el => {
this.initializeElement(el)
})
}
initializeElement(el) {
getXAttrs(el).forEach(({ type, value, modifiers, expression }) => {
switch (type) {
case 'on':
var event = value
this.registerListener(el, event, modifiers, expression)
break;
case 'model':
// If the element we are binding to is a select, a radio, or checkbox
// we'll listen for the change event instead of the "input" event.
var event = (el.tagName.toLowerCase() === 'select')
|| ['checkbox', 'radio'].includes(el.type)
|| modifiers.includes('lazy')
? 'change' : 'input'
const listenerExpression = this.generateExpressionForXModelListener(el, modifiers, expression)
this.registerListener(el, event, modifiers, listenerExpression)
var attrName = 'value'
var { output } = this.evaluateReturnExpression(expression)
this.updateAttributeValue(el, attrName, output)
break;
case 'bind':
var attrName = value
var { output } = this.evaluateReturnExpression(expression)
this.updateAttributeValue(el, attrName, output)
break;
case 'text':
var { output } = this.evaluateReturnExpression(expression)
this.updateTextValue(el, output)
break;
case 'show':
var { output } = this.evaluateReturnExpression(expression)
this.updateVisibility(el, output)
break;
case 'if':
var { output } = this.evaluateReturnExpression(expression)
this.updatePresence(el, output)
break;
case 'cloak':
el.removeAttribute('x-cloak')
break;
default:
break;
}
})
}
listenForNewElementsToInitialize() {
const targetNode = this.el
const observerOptions = {
childList: true,
attributes: true,
subtree: true,
}
const observer = new MutationObserver((mutations) => {
for (let i=0; i < mutations.length; i++){
// Filter out mutations triggered from child components.
if (! mutations[i].target.closest('[x-data]').isSameNode(this.el)) return
if (mutations[i].type === 'attributes' && mutations[i].attributeName === 'x-data') {
const rawData = saferEval(mutations[i].target.getAttribute('x-data'), {})
Object.keys(rawData).forEach(key => {
if (this.data[key] !== rawData[key]) {
this.data[key] = rawData[key]
}
})
}
if (mutations[i].addedNodes.length > 0) {
mutations[i].addedNodes.forEach(node => {
if (node.nodeType !== 1) return
if (node.matches('[x-data]')) return
if (getXAttrs(node).length > 0) {
this.initializeElement(node)
}
})
}
}
})
observer.observe(targetNode, observerOptions);
}
refresh() {
var self = this
const actionByDirectiveType = {
'model': ({el, output}) => { self.updateAttributeValue(el, 'value', output) },
'bind': ({el, attrName, output}) => { self.updateAttributeValue(el, attrName, output) },
'text': ({el, output}) => { self.updateTextValue(el, output) },
'show': ({el, output}) => { self.updateVisibility(el, output) },
'if': ({el, output}) => { self.updatePresence(el, output) },
}
const walkThenClearDependancyTracker = (rootEl, callback) => {
walkSkippingNestedComponents(rootEl, callback)
self.concernedData = []
}
debounce(walkThenClearDependancyTracker, 5)(this.el, function (el) {
getXAttrs(el).forEach(({ type, value, expression }) => {
if (! actionByDirectiveType[type]) return
var { output, deps } = self.evaluateReturnExpression(expression)
if (self.concernedData.filter(i => deps.includes(i)).length > 0) {
(actionByDirectiveType[type])({ el, attrName: value, output })
}
})
})
}
generateExpressionForXModelListener(el, modifiers, dataKey) {
var rightSideOfExpression = ''
if (el.type === 'checkbox') {
// If the data we are binding to is an array, toggle it's value inside the array.
if (Array.isArray(this.data[dataKey])) {
rightSideOfExpression = `$event.target.checked ? ${dataKey}.concat([$event.target.value]) : ${dataKey}.filter(i => i !== $event.target.value)`
} else {
rightSideOfExpression = `$event.target.checked`
}
} else if (el.tagName.toLowerCase() === 'select' && el.multiple) {
rightSideOfExpression = modifiers.includes('number')
? 'Array.from($event.target.selectedOptions).map(option => { return parseFloat(option.value || option.text) })'
: 'Array.from($event.target.selectedOptions).map(option => { return option.value || option.text })'
} else {
rightSideOfExpression = modifiers.includes('number')
? 'parseFloat($event.target.value)'
: (modifiers.includes('trim') ? '$event.target.value.trim()' : '$event.target.value')
}
if (el.type === 'radio') {
// Radio buttons only work properly when they share a name attribute.
// People might assume we take care of that for them, because
// they already set a shared "x-model" attribute.
if (! el.hasAttribute('name')) el.setAttribute('name', dataKey)
}
return `${dataKey} = ${rightSideOfExpression}`
}
registerListener(el, event, modifiers, expression) {
if (modifiers.includes('away')) {
const handler = e => {
// Don't do anything if the click came form the element or within it.
if (el.contains(e.target)) return
// Don't do anything if this element isn't currently visible.
if (el.offsetWidth < 1 && el.offsetHeight < 1) return
// Now that we are sure the element is visible, AND the click
// is from outside it, let's run the expression.
this.runListenerHandler(expression, e)
if (modifiers.includes('once')) {
document.removeEventListener(event, handler)
}
}
// Listen for this event at the root level.
document.addEventListener(event, handler)
} else {
const listenerTarget = modifiers.includes('window') ? window : el
const handler = e => {
const modifiersWithoutWindow = modifiers.filter(i => i !== 'window')
if (event === 'keydown' && modifiersWithoutWindow.length > 0 && ! modifiersWithoutWindow.includes(kebabCase(e.key))) return
if (modifiers.includes('prevent')) e.preventDefault()
if (modifiers.includes('stop')) e.stopPropagation()
this.runListenerHandler(expression, e)
if (modifiers.includes('once')) {
listenerTarget.removeEventListener(event, handler)
}
}
listenerTarget.addEventListener(event, handler)
}
}
runListenerHandler(expression, e) {
this.evaluateCommandExpression(expression, {
'$event': e,
'$refs': this.getRefsProxy(),
})
}
evaluateReturnExpression(expression) {
var affectedDataKeys = []
const proxyHandler = prefix => ({
get(object, prop) {
// Sometimes non-proxyable values are accessed. These are of type "symbol".
// We can ignore them.
if (typeof prop === 'symbol') return
const propertyName = prefix ? `${prefix}.${prop}` : prop
// If we are accessing an object prop, we'll make this proxy recursive to build
// a nested dependancy key.
if (typeof object[prop] === 'object' && object[prop] !== null && ! Array.isArray(object[prop])) {
return new Proxy(object[prop], proxyHandler(propertyName))
}
affectedDataKeys.push(propertyName)
return object[prop]
}
})
const proxiedData = new Proxy(this.data, proxyHandler())
const result = saferEval(expression, proxiedData)
return {
output: result,
deps: affectedDataKeys
}
}
evaluateCommandExpression(expression, extraData) {
saferEvalNoReturn(expression, this.data, extraData)
}
updateTextValue(el, value) {
el.innerText = value
}
updateVisibility(el, value) {
if (! value) {
el.style.display = 'none'
} else {
if (el.style.length === 1 && el.style.display !== '') {
el.removeAttribute('style')
} else {
el.style.removeProperty('display')
}
}
}
updatePresence(el, expressionResult) {
if (el.nodeName.toLowerCase() !== 'template') console.warn(`Alpine: [x-if] directive should only be added to <template> tags.`)
const elementHasAlreadyBeenAdded = el.nextElementSibling && el.nextElementSibling.__x_inserted_me === true
if (expressionResult && ! elementHasAlreadyBeenAdded) {
const clone = document.importNode(el.content, true);
el.parentElement.insertBefore(clone, el.nextElementSibling)
el.nextElementSibling.__x_inserted_me = true
} else if (! expressionResult && elementHasAlreadyBeenAdded) {
el.nextElementSibling.remove()
}
}
updateAttributeValue(el, attrName, value) {
if (attrName === 'value') {
if (el.type === 'radio') {
el.checked = el.value == value
} else if (el.type === 'checkbox') {
if (Array.isArray(value)) {
// I'm purposely not using Array.includes here because it's
// strict, and because of Numeric/String mis-casting, I
// want the "includes" to be "fuzzy".
let valueFound = false
value.forEach(val => {
if (val == el.value) {
valueFound = true
}
})
el.checked = valueFound
} else {
el.checked = !! value
}
} else if (el.tagName === 'SELECT') {
this.updateSelect(el, value)
} else {
el.value = value
}
} else if (attrName === 'class') {
if (Array.isArray(value)) {
el.setAttribute('class', value.join(' '))
} else {
// Use the class object syntax that vue uses to toggle them.
Object.keys(value).forEach(classNames => {
if (value[classNames]) {
classNames.split(' ').forEach(className => el.classList.add(className))
} else {
classNames.split(' ').forEach(className => el.classList.remove(className))
}
})
}
} else if (['disabled', 'readonly', 'required', 'checked', 'hidden'].includes(attrName)) {
// Boolean attributes have to be explicitly added and removed, not just set.
if (!! value) {
el.setAttribute(attrName, '')
} else {
el.removeAttribute(attrName)
}
} else {
el.setAttribute(attrName, value)
}
}
updateSelect(el, value) {
const arrayWrappedValue = [].concat(value).map(value => { return value + '' })
Array.from(el.options).forEach(option => {
option.selected = arrayWrappedValue.includes(option.value || option.text)
})
}
getRefsProxy() {
var self = this
// One of the goals of this is to not hold elements in memory, but rather re-evaluate
// the DOM when the system needs something from it. This way, the framework is flexible and
// friendly to outside DOM changes from libraries like Vue/Livewire.
// For this reason, I'm using an "on-demand" proxy to fake a "$refs" object.
return new Proxy({}, {
get(object, property) {
var ref
// We can't just query the DOM because it's hard to filter out refs in
// nested components.
walkSkippingNestedComponents(self.el, el => {
if (el.hasAttribute('x-ref') && el.getAttribute('x-ref') === property) {
ref = el
}
})
return ref
}
})
}
}