forked from nullstack/nullstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbindable.js
More file actions
56 lines (52 loc) · 1.9 KB
/
bindable.js
File metadata and controls
56 lines (52 loc) · 1.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
function attachEvent(node) {
const target = node.attributes.source;
let eventName = 'oninput';
let valueName = 'value';
if (node.attributes.type === 'checkbox' || node.attributes.type === 'radio') {
eventName = 'onclick';
valueName = 'checked';
} else if (node.type !== 'input' && node.type !== 'textarea') {
eventName = 'onchange';
}
const originalEvent = node.attributes[eventName];
node.attributes[eventName] = ({ event, value }) => {
if (valueName == 'checked') {
target[node.attributes.bind] = event.target[valueName];
} else if (target[node.attributes.bind] === true || target[node.attributes.bind] === false) {
target[node.attributes.bind] = event ? (event.target[valueName] == 'true') : value;
} else if (typeof target[node.attributes.bind] === 'number') {
target[node.attributes.bind] = parseFloat(event ? event.target[valueName] : value) || 0;
} else {
target[node.attributes.bind] = event ? event.target[valueName] : value;
}
if (originalEvent !== undefined) {
setTimeout(() => {
originalEvent({ ...node.attributes, event, value });
}, 0);
}
}
}
function match(node) {
return (
node !== undefined &&
node.attributes !== undefined &&
node.attributes.bind !== undefined &&
node.attributes.source !== undefined
)
}
function transform({ node, environment }) {
if (!match(node)) return;
const target = node.attributes.source;
if (node.type === 'textarea') {
node.children = [target[node.attributes.bind]];
} else if (node.type === 'input' && node.attributes.type === 'checkbox') {
node.attributes.checked = target[node.attributes.bind];
} else {
node.attributes.value = target[node.attributes.bind] || '';
}
node.attributes.name = node.attributes.name || node.attributes.bind;
if (environment.client) {
attachEvent(node);
}
}
export default { transform, client: true, server: true }