-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathfill.js
91 lines (73 loc) · 1.76 KB
/
fill.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
84
85
86
87
88
89
90
91
/**
* External dependencies
*/
import { isFunction } from 'lodash';
/**
* WordPress dependencies
*/
import { Component, createPortal } from '@wordpress/element';
/**
* Internal dependencies
*/
import { Consumer } from './context';
let occurrences = 0;
class FillComponent extends Component {
constructor() {
super( ...arguments );
this.occurrence = ++occurrences;
}
componentDidMount() {
const { registerFill } = this.props;
registerFill( this.props.name, this );
}
componentWillUpdate() {
if ( ! this.occurrence ) {
this.occurrence = ++occurrences;
}
const { getSlot } = this.props;
const slot = getSlot( this.props.name );
if ( slot && ! slot.props.bubblesVirtually ) {
slot.forceUpdate();
}
}
componentWillUnmount() {
const { unregisterFill } = this.props;
unregisterFill( this.props.name, this );
}
componentDidUpdate( prevProps ) {
const { name, unregisterFill, registerFill } = this.props;
if ( prevProps.name !== name ) {
unregisterFill( prevProps.name, this );
registerFill( name, this );
}
}
resetOccurrence() {
this.occurrence = null;
}
render() {
const { name, getSlot } = this.props;
let { children } = this.props;
const slot = getSlot( name );
if ( ! slot || ! slot.props.bubblesVirtually ) {
return null;
}
// If a function is passed as a child, provide it with the fillProps.
if ( isFunction( children ) ) {
children = children( slot.props.fillProps );
}
return createPortal( children, slot.node );
}
}
const Fill = ( props ) => (
<Consumer>
{ ( { getSlot, registerFill, unregisterFill } ) => (
<FillComponent
{ ...props }
getSlot={ getSlot }
registerFill={ registerFill }
unregisterFill={ unregisterFill }
/>
) }
</Consumer>
);
export default Fill;