-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
72 lines (61 loc) · 1.84 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
/**
* Module dependencies.
*/
var slice = require('sliced')
var flatten = require('array-flatten')
/**
* This function lets us create virtual nodes using a simple
* syntax. It is compatible with JSX transforms so you can use
* JSX to write nodes that will compile to this function.
*
* let node = element('div', { id: 'foo' }, [
* element('a', { href: 'http://google.com' }, 'Google')
* ])
*
* You can leave out the attributes or the children if either
* of them aren't needed and it will figure out what you're
* trying to do.
*/
module.exports = element
/**
* Create virtual trees of components.
*
* This creates the nicer API for the user.
* It translates that friendly API into an actual tree of nodes.
*
* @param {*} type
* @param {Object} attributes
* @param {Array} children
* @return {Object}
* @api public
*/
function element (type, attributes, children) {
// Default to div with no args
if (!type) {
throw new TypeError('element() needs a type.')
}
// Skipped adding attributes and we're passing
// in children instead.
if (arguments.length === 2 && (typeof attributes === 'string' || Array.isArray(attributes))) {
children = [ attributes ]
attributes = {}
}
// Account for JSX putting the children as multiple arguments.
// This is essentially just the ES6 rest param
if (arguments.length > 2) {
children = slice(arguments, 2)
}
children = children || []
attributes = attributes || {}
// Flatten nested child arrays. This is how JSX compiles some nodes.
children = flatten(children, 2)
// Filter out any `undefined` elements
children = children.filter(function (i) { return typeof i !== 'undefined' })
// if you pass in a function, it's a `Component` constructor.
// otherwise it's an element.
return {
type: type,
children: children,
attributes: attributes
}
}