-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent.js
84 lines (69 loc) · 1.9 KB
/
component.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
class Component extends HTMLElement {
constructor() {
super();
this.state = {};
this.shadow = this.attachShadow({ mode: 'open' });
this.mount = this.mount.bind(this);
}
componentRender() {
this.renderedComponent = this.render();
if (this.shadow.children.length) {
[...this.shadow.children].forEach((d, i) => {
if (d.tagName !== 'STYLE') {
this.shadow.removeChild(d);
}
});
}
this.shadow.appendChild(this.renderedComponent);
}
setState(newState = {}) {
this.state = {...this.state, ...newState};
this.componentRender();
}
attributeChangedCallback(name, oldValue, newValue) {
this.componentRender();
}
mergeProps(props = {}) {
const defaultProps = {
onClick: null,
className: '',
props: [],
};
return {...defaultProps, ...props};
}
setStyles(styles) {
const styleElement = document.createElement('style');
styleElement.textContent = styles;
this.shadow.appendChild(styleElement);
}
setProps(elem, props) {
if (props.onClick) {
elem.addEventListener('click', props.onClick);
}
if (props.className) {
elem.setAttribute('class', props.className);
}
if (props.props.length) {
props.props.forEach(prop => {
const [key, value] = Object.entries(prop)[0];
elem.setAttribute(key, value);
return false;
});
}
}
mount(...item) {
const [type, itemProps, childItem] = item;
const props = this.mergeProps(itemProps);
const elem = document.createElement(type);
this.setProps(elem, props);
const textContentTypes = ['string', 'number'];
if (textContentTypes.indexOf(typeof childItem) > -1) {
elem.textContent = childItem;
} else if (Array.isArray(childItem)) {
childItem.forEach(ci => elem.appendChild(ci));
} else {
elem.appendChild(childItem);
}
return elem;
}
}