-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
79 lines (62 loc) · 1.59 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
79
/**
* External dependencies
*/
import { isString, includes, forOwn } from 'lodash';
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
function isWebComponent( tagName ) {
return isString( tagName ) && includes( tagName, '-' );
}
class ComponentInterop extends Component {
constructor() {
super( ...arguments );
this.bindNode = this.bindNode.bind( this );
}
componentDidMount() {
this.setWebComponentProps( this.props );
}
componentWillReceiveProps( nextProps ) {
this.setWebComponentProps( nextProps );
}
setWebComponentProps( props ) {
const { tagName, attributes, ...properties } = props;
if ( ! isWebComponent( tagName ) ) {
return;
}
let child = this.node.firstChild;
if ( ! child ) {
child = document.createElement( tagName );
this.node.appendChild( child );
}
forOwn( properties, ( value, key ) => {
child[ key ] = value;
} );
forOwn( attributes, ( value, key ) => {
child.setAttribute( key, value );
} );
}
shouldComponentUpdate() {
const { tagName } = this.props;
if ( isWebComponent( tagName ) ) {
return false;
}
if ( 'function' === typeof tagName &&
'function' === typeof tagName.prototype.shouldComponentUpdate ) {
return tagName.prototype.shouldComponentUpdate.apply( this, arguments );
}
return true;
}
bindNode( node ) {
this.node = node;
}
render() {
const { tagName: TagName, ...componentProps } = this.props;
if ( isWebComponent( TagName ) ) {
return <div ref={ this.bindNode } />;
}
return <TagName { ...componentProps } />;
}
}
export default ComponentInterop;