-
-
Notifications
You must be signed in to change notification settings - Fork 927
/
hyperscript.js
66 lines (60 loc) · 2.43 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
"use strict"
var Vnode = require("../render/vnode")
var selectorParser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[(.+?)(?:\s*=\s*("|'|)((?:\\["'\]]|.)*?)\5)?\])/g
var selectorCache = {}
function hyperscript(selector) {
if (typeof selector === "string") {
if (selectorCache[selector] === undefined) {
var match, tag, classes = [], attributes = {}
while (match = selectorParser.exec(selector)) {
var type = match[1], value = match[2]
if (type === "" && value !== "") tag = value
else if (type === "#") attributes.id = value
else if (type === ".") classes.push(value)
else if (match[3][0] === "[") {
var attrValue = match[6]
if (attrValue) attrValue = attrValue.replace(/\\(["'])/g, "$1").replace(/\\\\/g, "\\")
attributes[match[4]] = attrValue || true
}
}
if (classes.length > 0) attributes.className = classes.join(" ")
selectorCache[selector] = function(attrs, children) {
var hasAttrs = false, childList, text
var className = attrs.className || attrs.class
for (var key in attributes) attrs[key] = attributes[key]
if (className !== undefined) {
if (attrs.class !== undefined) {
attrs.class = undefined
attrs.className = className
}
if (attributes.className !== undefined) attrs.className = attributes.className + " " + className
}
for (var key in attrs) {
if (key !== "key") {
hasAttrs = true
break
}
}
if (children instanceof Array && children.length == 1 && children[0] != null && children[0].tag === "#") text = children[0].children
else childList = children
return Vnode(tag || "div", attrs.key, hasAttrs ? attrs : undefined, childList, text, undefined)
}
}
}
var attrs, children, childrenIndex
if (arguments[1] == null || typeof arguments[1] === "object" && arguments[1].tag === undefined && !(arguments[1] instanceof Array)) {
attrs = arguments[1]
childrenIndex = 2
}
else childrenIndex = 1
if (arguments.length === childrenIndex + 1) {
children = arguments[childrenIndex] instanceof Array ? arguments[childrenIndex] : [arguments[childrenIndex]]
}
else {
children = []
for (var i = childrenIndex; i < arguments.length; i++) children.push(arguments[i])
}
if (typeof selector === "string") return selectorCache[selector](attrs || {}, Vnode.normalizeChildren(children))
return Vnode(selector, attrs && attrs.key, attrs || {}, Vnode.normalizeChildren(children), undefined, undefined)
}
module.exports = hyperscript