-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
x-model.js
218 lines (184 loc) · 8.04 KB
/
x-model.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
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
import { evaluateLater } from '../evaluator'
import { directive } from '../directives'
import { mutateDom } from '../mutation'
import { nextTick } from '../nextTick'
import bind, { safeParseBoolean } from '../utils/bind'
import on from '../utils/on'
import { isCloning } from '../clone'
directive('model', (el, { modifiers, expression }, { effect, cleanup }) => {
let scopeTarget = el
if (modifiers.includes('parent')) {
scopeTarget = el.parentNode
}
let evaluateGet = evaluateLater(scopeTarget, expression)
let evaluateSet
if (typeof expression === 'string') {
evaluateSet = evaluateLater(scopeTarget, `${expression} = __placeholder`)
} else if (typeof expression === 'function' && typeof expression() === 'string') {
evaluateSet = evaluateLater(scopeTarget, `${expression()} = __placeholder`)
} else {
evaluateSet = () => {}
}
let getValue = () => {
let result
evaluateGet(value => result = value)
return isGetterSetter(result) ? result.get() : result
}
let setValue = value => {
let result
evaluateGet(value => result = value)
if (isGetterSetter(result)) {
result.set(value)
} else {
evaluateSet(() => {}, {
scope: { '__placeholder': value }
})
}
}
if (typeof expression === 'string' && 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.
mutateDom(() => {
if (! el.hasAttribute('name')) el.setAttribute('name', expression)
})
}
// 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'
// We only want to register the event listener when we're not cloning, since the
// mutation observer handles initializing the x-model directive already when
// the element is inserted into the DOM. Otherwise we register it twice.
let removeListener = isCloning ? () => {} : on(el, event, modifiers, (e) => {
setValue(getInputValue(el, modifiers, e, getValue()))
})
if (modifiers.includes('fill'))
if ([undefined, null, ''].includes(getValue())
|| (el.type === 'checkbox' && Array.isArray(getValue()))
|| (el.tagName.toLowerCase() === 'select' && el.multiple)) {
setValue(
getInputValue(el, modifiers, { target: el }, getValue())
);
}
// Register the listener removal callback on the element, so that
// in addition to the cleanup function, x-modelable may call it.
// Also, make this a keyed object if we decide to reintroduce
// "named modelables" some time in a future Alpine version.
if (! el._x_removeModelListeners) el._x_removeModelListeners = {}
el._x_removeModelListeners['default'] = removeListener
cleanup(() => el._x_removeModelListeners['default']())
// If the input/select/textarea element is linked to a form
// we listen for the reset event on the parent form (the event
// does not trigger on the single inputs) and update
// on nextTick so the page doesn't end up out of sync
if (el.form) {
let removeResetListener = on(el.form, 'reset', [], (e) => {
nextTick(() => el._x_model && el._x_model.set(getInputValue(el, modifiers, { target: el }, getValue())))
})
cleanup(() => removeResetListener())
}
// Allow programmatic overriding of x-model.
el._x_model = {
get() {
return getValue()
},
set(value) {
setValue(value)
},
}
el._x_forceModelUpdate = (value) => {
// If nested model key is undefined, set the default value to empty string.
if (value === undefined && typeof expression === 'string' && expression.match(/\./)) value = ''
// @todo: This is nasty
window.fromModel = true
mutateDom(() => bind(el, 'value', value))
delete window.fromModel
}
effect(() => {
// We need to make sure we're always "getting" the value up front,
// so that we don't run into a situation where because of the early
// the reactive value isn't gotten and therefore disables future reactions.
let value = getValue()
// Don't modify the value of the input if it's focused.
if (modifiers.includes('unintrusive') && document.activeElement.isSameNode(el)) return
el._x_forceModelUpdate(value)
})
})
function getInputValue(el, modifiers, event, currentValue) {
return mutateDom(() => {
// Check for event.detail due to an issue where IE11 handles other events as a CustomEvent.
// Safari autofill triggers event as CustomEvent and assigns value to target
// so we return event.target.value instead of event.detail
if (event instanceof CustomEvent && event.detail !== undefined)
return event.detail !== null && event.detail !== undefined ? event.detail : event.target.value
else if (el.type === 'checkbox') {
// If the data we are binding to is an array, toggle its value inside the array.
if (Array.isArray(currentValue)) {
let newValue = null;
if (modifiers.includes('number')) {
newValue = safeParseNumber(event.target.value)
} else if (modifiers.includes('boolean')) {
newValue = safeParseBoolean(event.target.value)
} else {
newValue = event.target.value
}
return event.target.checked
? (currentValue.includes(newValue) ? currentValue : currentValue.concat([newValue]))
: currentValue.filter(el => ! checkedAttrLooseCompare(el, newValue));
} else {
return event.target.checked
}
} else if (el.tagName.toLowerCase() === 'select' && el.multiple) {
if (modifiers.includes('number')) {
return Array.from(event.target.selectedOptions).map(option => {
let rawValue = option.value || option.text
return safeParseNumber(rawValue)
})
} else if (modifiers.includes('boolean')) {
return Array.from(event.target.selectedOptions).map(option => {
let rawValue = option.value || option.text
return safeParseBoolean(rawValue)
})
}
return Array.from(event.target.selectedOptions).map(option => {
return option.value || option.text
})
} else {
let newValue
if (el.type === 'radio') {
if (event.target.checked) {
newValue = event.target.value
} else {
newValue = currentValue
}
} else {
newValue = event.target.value
}
if (modifiers.includes('number')) {
return safeParseNumber(newValue)
} else if (modifiers.includes('boolean')) {
return safeParseBoolean(newValue)
} else if (modifiers.includes('trim')) {
return newValue.trim()
} else {
return newValue
}
}
})
}
function safeParseNumber(rawValue) {
let number = rawValue ? parseFloat(rawValue) : null
return isNumeric(number) ? number : rawValue
}
function checkedAttrLooseCompare(valueA, valueB) {
return valueA == valueB
}
function isNumeric(subject){
return ! Array.isArray(subject) && ! isNaN(subject)
}
function isGetterSetter(value) {
return value !== null && typeof value === 'object' && typeof value.get === 'function' && typeof value.set === 'function'
}