-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-element.js
69 lines (65 loc) · 1.81 KB
/
create-element.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
import React from 'react';
export function createStyleObject(classNames, elementStyle = {}, stylesheet) {
return classNames.reduce((styleObject, className) => {
return { ...styleObject, ...stylesheet[className] };
}, elementStyle);
}
export function createClassNameString(classNames) {
return classNames.join(' ');
}
export function createChildren(stylesheet, useInlineStyles) {
let childrenCount = 0;
return children => {
childrenCount += 1;
return children.map((child, i) =>
createElement({
node: child,
stylesheet,
useInlineStyles,
key: `code-segment-${childrenCount}-${i}`
})
);
};
}
export default function createElement({
node,
stylesheet,
style = {},
useInlineStyles,
key
}) {
const { properties, type, tagName: TagName, value } = node;
if (type === 'text') {
return value;
} else if (TagName) {
const childrenCreator = createChildren(stylesheet, useInlineStyles);
const nonStylesheetClassNames =
useInlineStyles &&
properties.className &&
properties.className.filter(className => !stylesheet[className]);
const className =
nonStylesheetClassNames && nonStylesheetClassNames.length
? nonStylesheetClassNames
: undefined;
const props = useInlineStyles
? {
...properties,
...{ className: className && createClassNameString(className) },
style: createStyleObject(
properties.className,
Object.assign({}, properties.style, style),
stylesheet
)
}
: {
...properties,
className: createClassNameString(properties.className)
};
const children = childrenCreator(node.children);
return (
<TagName key={key} {...props}>
{children}
</TagName>
);
}
}