-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
fill.js
76 lines (62 loc) · 1.48 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
/**
* External dependencies
*/
import { isFunction } from 'lodash';
/**
* WordPress dependencies
*/
import { createPortal, useLayoutEffect, useRef } from '@wordpress/element';
/**
* Internal dependencies
*/
import { Consumer, useSlot } from './context';
let occurrences = 0;
function FillComponent( { name, children, registerFill, unregisterFill } ) {
const slot = useSlot( name );
const ref = useRef( {
name,
children,
} );
if ( ! ref.current.occurrence ) {
ref.current.occurrence = ++occurrences;
}
useLayoutEffect( () => {
registerFill( name, ref.current );
return () => unregisterFill( name, ref.current );
}, [] );
useLayoutEffect( () => {
ref.current.children = children;
if ( slot ) {
slot.forceUpdate();
}
}, [ children ] );
useLayoutEffect( () => {
if ( name === ref.current.name ) {
// ignore initial effect
return;
}
unregisterFill( ref.current.name, ref.current );
ref.current.name = name;
registerFill( name, ref.current );
}, [ name ] );
if ( ! slot || ! slot.node ) {
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>
{ ( { registerFill, unregisterFill } ) => (
<FillComponent
{ ...props }
registerFill={ registerFill }
unregisterFill={ unregisterFill }
/>
) }
</Consumer>
);
export default Fill;