-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (74 loc) · 2.18 KB
/
index.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
// Generated by CoffeeScript 2.3.2
// 
// # h
// ###### 0.3 kB Virtual Dom Producer
// ## Installation
// ```sh
// npm install --save @playframe/h
// ```
// ## Usage
// ```js
// import h from '@playframe/h'
// // directly
// h('a', {href: 'https://github.com/playframe/h'}, 'PlayFrame/h')
// // JSX
// const link = ()=>
// <a href="https://github.com/playframe/h"> PlayFrame/h </a>
// ```
// ## Annotated Source
// Creating a unique Symbol for distinction between Virtual Nodes
// and plain Arrays
var VNODE, _registry, h, invoke;
VNODE = Symbol('VNODE');
_registry = {};
// Our Virtual Node is produced from a list of arguments passed
// to `h` function. Children are passed as tail of arguments,
// but any of them could be wrapped in Array
// ```js
// h('div', {class: 's'}, child1, [ child2, child3 ], child4)`)
// ```
// To achieve no runtime overhead we will avoid creating a new object
// for Virtual Node and new Array for children. We will just mark array
// of passed arguments as a `VNODE` and return it as is.
// This is compensated by a more advenced child walker used in
// [@playframe/dom](https://github.com/playframe/dom)
module.exports = h = (...a) => {
var component, name;
if (typeof (name = a[0]) === 'function') {
return invoke(...a);
} else if (component = _registry[name]) {
a[0] = component;
return invoke(...a);
} else {
a[VNODE] = true;
return a;
}
};
h.VNODE = VNODE;
// Registering custom components like
// `h.use({'my-component': MyComponent})`
h.use = (components) => {
var k, v;
for (k in components) {
v = components[k];
_registry[k] = v;
}
};
// If the first argument of `h` function is a not a `'div'` but
// your Component function, we will flatten the children and attach
// them to `props`
invoke = (Component, props, ...children) => {
var child, flat, i, len;
if (children[0]) {
flat = props.children = [];
for (i = 0, len = children.length; i < len; i++) {
child = children[i];
if (!child[VNODE] && Array.isArray(child)) {
flat.push(...child);
} else {
flat.push(child);
}
}
}
return Component(props);
};