-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlit-react-wrapper.js
More file actions
92 lines (81 loc) · 2.44 KB
/
lit-react-wrapper.js
File metadata and controls
92 lines (81 loc) · 2.44 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
84
85
86
87
88
89
90
91
92
import { html, LitElement } from "lit";
import * as ReactDOM from "react-dom";
import * as React from "react";
import * as retargetEvents from "react-shadow-dom-retarget-events";
import { StylesProvider, jssPreset } from "@material-ui/styles";
import { create } from "jss";
export class LitReactWrapper extends LitElement {
static get properties() {
return {
mountPoint: Object,
props: Object,
element: Object,
styles: Array,
_styleElement: Object,
_reactRef: Object,
_reactElement: Object,
};
}
constructor() {
super();
this.props = {};
this.styles = [];
this._styleElement = null;
this._reactRef = React.createRef();
}
render() {
return html` <div id="mountPoint"></div> `;
}
createElement() {
const props = this.props || {};
if (!props.mountContainer) props.mountContainer = this.mountPoint;
if (!props.mountDocument) props.mountDocument = this.shadowRoot || document;
this._reactElement = React.createElement(this.element, { ...props, ref: this._reactRef }, React.createElement("slot"));
return this._reactElement;
}
getRef() {
return this._reactRef;
}
injectStyles() {
if (this._styleElement && this.shadowRoot.contains(this._styleElement)) {
this.shadowRoot.removeChild(this._styleElement);
}
let styleContent = "";
if (Array.isArray(this.styles)) {
styleContent = this.styles.join("\n");
} else if (typeof this.styles === "string") {
styleContent = this.styles;
}
if (styleContent) {
this._styleElement = document.createElement("style");
this._styleElement.textContent = styleContent;
this.shadowRoot.insertBefore(this._styleElement, this.mountPoint);
}
}
renderElement() {
const jss = create({
...jssPreset(),
insertionPoint: this.mountPoint,
});
ReactDOM.render(
<StylesProvider jss={jss} sheetsManager={new Map()}>
{this.createElement()}
</StylesProvider>,
this.mountPoint
);
}
firstUpdated() {
this.mountPoint = this.shadowRoot.getElementById("mountPoint");
this.renderElement();
retargetEvents(this.shadowRoot);
}
updated(changedProperties) {
if (changedProperties.has("styles")) {
this.injectStyles();
}
if (changedProperties.has("props") || changedProperties.has("element")) {
this.renderElement();
}
}
}
window.customElements.define("lit-react-wrapper", LitReactWrapper);