-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathslot.js
83 lines (65 loc) · 1.78 KB
/
slot.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
80
81
82
83
/**
* External dependencies
*/
import { noop, map, isString, isFunction } from 'lodash';
/**
* WordPress dependencies
*/
import { Component, Children, cloneElement } from '@wordpress/element';
class Slot extends Component {
constructor() {
super( ...arguments );
this.bindNode = this.bindNode.bind( this );
}
componentDidMount() {
const { registerSlot = noop } = this.context;
registerSlot( this.props.name, this );
}
componentWillUnmount() {
const { unregisterSlot = noop } = this.context;
unregisterSlot( this.props.name, this );
}
componentDidUpdate( prevProps ) {
const { name } = this.props;
const {
unregisterSlot = noop,
registerSlot = noop,
} = this.context;
if ( prevProps.name !== name ) {
unregisterSlot( prevProps.name );
registerSlot( name, this );
}
}
bindNode( node ) {
this.node = node;
}
render() {
const { children, name, bubblesVirtually = false, fillProps = {} } = this.props;
const { getFills = noop } = this.context;
if ( bubblesVirtually ) {
return <div ref={ this.bindNode } />;
}
const fills = map( getFills( name ), ( fill ) => {
const fillKey = fill.occurrence;
const fillChildren = isFunction( fill.props.children ) ? fill.props.children( fillProps ) : fill.props.children;
return Children.map( fillChildren, ( child, childIndex ) => {
if ( ! child || isString( child ) ) {
return child;
}
const childKey = `${ fillKey }---${ child.key || childIndex }`;
return cloneElement( child, { key: childKey } );
} );
} );
return (
<div ref={ this.bindNode } role="presentation">
{ isFunction( children ) ? children( fills.filter( Boolean ) ) : fills }
</div>
);
}
}
Slot.contextTypes = {
registerSlot: noop,
unregisterSlot: noop,
getFills: noop,
};
export default Slot;