This repository was archived by the owner on Sep 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathindex.js
78 lines (68 loc) · 2.26 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
73
74
75
76
77
78
import assign from 'object-assign';
import pascalCase from 'pascal-case';
import React from 'react';
import ReactDOM from 'react-dom';
const defaults = {
React,
ReactDOM,
};
function syncEvent(node, eventName, newEventHandler) {
const eventNameLc = eventName[0].toLowerCase() + eventName.substring(1);
const eventStore = node.__events || (node.__events = {});
const oldEventHandler = eventStore[eventNameLc];
// Remove old listener so they don't double up.
if (oldEventHandler) {
node.removeEventListener(eventNameLc, oldEventHandler);
}
// Bind new listener.
if (newEventHandler) {
node.addEventListener(eventNameLc, eventStore[eventNameLc] = function handler(e) {
newEventHandler.call(this, e);
});
}
}
export default function (CustomElement, opts) {
opts = assign({}, defaults, opts);
if (typeof CustomElement !== 'function') {
throw new Error('Given element is not a valid constructor');
}
const tagName = (new CustomElement()).tagName;
const displayName = pascalCase(tagName);
const { React, ReactDOM } = opts;
if (!React || !ReactDOM) {
throw new Error('React and ReactDOM must be dependencies, globally on your `window` object or passed via opts.');
}
class ReactComponent extends React.Component {
static get displayName() {
return displayName;
}
getNativeElement() {
return this._elementNode;
}
componentDidMount() {
this._elementNode = ReactDOM.findDOMNode(this);
this.componentWillReceiveProps(this.props);
}
componentWillReceiveProps(props) {
const node = this.getNativeElement();
Object.keys(props).forEach(name => {
if (name === 'children' || name === 'style') {
return;
}
if (name.indexOf('on') === 0 && name[2] === name[2].toUpperCase()) {
syncEvent(node, name.substring(2), props[name]);
} else {
node[name] = props[name];
}
});
}
render() {
return React.createElement(tagName, { style: this.props.style }, this.props.children);
}
}
const proto = CustomElement.prototype;
Object.getOwnPropertyNames(proto).forEach(prop => {
Object.defineProperty(ReactComponent.prototype, prop, Object.getOwnPropertyDescriptor(proto, prop));
});
return ReactComponent;
}