forked from reactive-elements/reactive-elements
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreactive-elements.js
More file actions
83 lines (67 loc) · 2.2 KB
/
Copy pathreactive-elements.js
File metadata and controls
83 lines (67 loc) · 2.2 KB
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
import * as utils from './utils';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
const getRenderRoot = (element, useShadowDom) =>
useShadowDom ? element.shadowRoot : element;
function reactiveElements(elementName, ReactComponent, options) {
const { useShadowDom = false } = options;
function create(parent, props) {
var element = React.createElement(ReactComponent, props);
parent.reactiveElement = element;
return ReactDOM.render(
element,
getRenderRoot(parent, useShadowDom),
props.onRender
);
}
function exposeDefaultMethods(reactComponent, customElement) {
customElement.forceUpdate = reactComponent.forceUpdate.bind(reactComponent);
}
function exposeMethods(reactComponent, customElement) {
utils.extend(customElement, reactComponent);
}
class CustomElement extends HTMLElement {
constructor() {
const self = super();
if (useShadowDom) self.attachShadow({ mode: 'open' });
const observer = new MutationObserver(() => {
ReactDOM.unmountComponentAtNode(getRenderRoot(self, useShadowDom));
const props = utils.getProps(self);
props.children = utils.getChildren(self);
create(self, props);
});
observer.observe(self, {
childList: true,
subtree: true,
characterData: true,
attributes: true,
});
}
connectedCallback() {
const props = utils.getProps(this);
props.children = utils.getChildren(this);
let reactElement = create(this, props);
if (reactElement !== null) {
exposeMethods(reactElement, reactElement.props.container);
exposeDefaultMethods(reactElement, reactElement.props.container);
utils.getterSetter(
this,
'props',
function() {
return reactElement.props;
},
function(props) {
reactElement = create(this, props);
}
);
}
}
disconnectedCallback() {
ReactDOM.unmountComponentAtNode(getRenderRoot(this, useShadowDom));
}
}
customElements.define(elementName, CustomElement);
return CustomElement;
}
reactiveElements.utils = utils;
export default reactiveElements;