-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreact-element.js
73 lines (61 loc) · 1.88 KB
/
react-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
70
71
72
73
(function(){
function registerReactElement(elementName, ReactComponent){
document.registerElement(elementName, { prototype: customElement(ReactComponent) });
};
function customElement(ReactComponent) {
var prototype = Object.create(HTMLElement.prototype, {
props: {
get: function(){
return propTypedDataset(this.dataset, ReactComponent.propTypes);
}
}
});
prototype.attachedCallback = function(){
this._render();
};
prototype.detachedCallbkack = function(){
React.unmountComponentAtNode(this);
};
prototype.attributeChangedCallback = function(name, old, current) {
if(name.match(/^data\-/)) {
this._render();
}
};
prototype._render = function(){
React.renderComponent(ReactComponent(this.props), this);
};
return prototype;
};
function propTypedDataset(dataset, propTypes) {
if(!propTypes) return dataset;
var props = {};
Object.keys(dataset).forEach(function(key){
var stringifiedValue = dataset[key];
var propType = propTypes[key];
if(propType) {
switch(propType) {
// No need to parse strings
case React.PropTypes.string:
case React.PropTypes.string.isRequired:
props[key] = stringifiedValue;
break;
default:
// Assert, that JSON.parse does the job.
try{
props[key] = JSON.parse(stringifiedValue);
} catch(err) {
console.warn('Error parsing prop type', key, propType, stringifiedValue);
}
}
} else {
props[key] = stringifiedValue;
}
}.bind(this));
return props;
};
if('undefined' !== typeof module) {
module.exports = registerReactElement;
} else if('undefined' !== typeof document) {
document.registerReactElement = registerReactElement;
}
})();