-
Notifications
You must be signed in to change notification settings - Fork 0
/
hyperscript.js
106 lines (84 loc) · 2.68 KB
/
hyperscript.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
'use strict';
window.h = (function(React) {
var classIdSplit = /([\.#]?[a-zA-Z0-9_:-]+)/;
var notClassId = /^\.|#/;
return h;
function h(componentOrTag, properties, children) {
// If a child array or text node are passed as the second argument, shift them
if (!children && isChildren(properties)) {
children = properties;
properties = {};
} else if (arguments.length === 2) {
// If no children were passed, we don't want to pass "undefined"
// and potentially overwrite the `children` prop
children = [];
}
properties = properties ? Object.assign({}, properties) : {};
// Supported nested dataset attributes
if (properties.dataset) {
Object.keys(properties.dataset).forEach(function unnest(attrName) {
var dashedAttr = attrName.replace(/([a-z])([A-Z])/, function dash(
match
) {
return match[0] + '-' + match[1].toLowerCase();
});
properties['data-' + dashedAttr] = properties.dataset[attrName];
});
properties.dataset = undefined;
}
// Support nested attributes
if (properties.attributes) {
Object.keys(properties.attributes).forEach(function unnest(attrName) {
properties[attrName] = properties.attributes[attrName];
});
properties.attributes = undefined;
}
// When a selector, parse the tag name and fill out the properties object
if (typeof componentOrTag === 'string') {
componentOrTag = parseTag(componentOrTag, properties);
}
// Create the element
var args = [componentOrTag, properties].concat(children);
return React.createElement.apply(React, args);
}
function isChildren(x) {
return typeof x === 'string' || typeof x === 'number' || Array.isArray(x);
}
function parseTag(tag, props) {
if (!tag) {
return 'div';
}
var noId = !('id' in props);
var tagParts = tag.split(classIdSplit);
var tagName = null;
if (notClassId.test(tagParts[1])) {
tagName = 'div';
}
var classes;
var part;
var type;
var i;
for (i = 0; i < tagParts.length; i++) {
part = tagParts[i];
if (!part) {
continue;
}
type = part.charAt(0);
if (!tagName) {
tagName = part;
} else if (type === '.') {
classes = classes || [];
classes.push(part.substring(1, part.length));
} else if (type === '#' && noId) {
props.id = part.substring(1, part.length);
}
}
if (classes) {
if (props.className) {
classes.push(props.className);
}
props.className = classes.join(' ');
}
return tagName ? tagName.toLowerCase() : 'div';
}
})(window.React);