-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathcustomizable-content.js
123 lines (114 loc) · 2.67 KB
/
customizable-content.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/**
* External dependencies
*/
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import { throttle } from 'lodash';
/**
* WordPress dependencies
*/
import { useRef, useState, useEffect, useCallback } from '@wordpress/element';
/**
* Internal dependencies
*/
import BlockToolbarContents from '../block-toolbar-contents';
export default function CustomizableBlockToolbarContent( {
children,
className,
} ) {
return (
<BlockToolbarContents.Slot>
{ ( fills ) => (
<CustomizableBlockToolbarContentChildren
className={ className }
fills={ fills }
>
{ children }
</CustomizableBlockToolbarContentChildren>
) }
</BlockToolbarContents.Slot>
);
}
function CustomizableBlockToolbarContentChildren( {
fills,
className = '',
children,
} ) {
const containerRef = useRef();
const fillsRef = useRef();
const toolbarRef = useRef();
const [ dimensions, setDimensions ] = useState( {} );
const fillsPropRef = useRef();
fillsPropRef.current = fills;
const resize = useCallback(
throttle( ( elem ) => {
if ( ! elem ) {
elem = fillsPropRef.current.length
? fillsRef.current
: toolbarRef.current;
}
if ( ! elem ) {
return;
}
elem.style.position = 'absolute';
elem.style.width = 'auto';
const css = window.getComputedStyle( elem, null );
setDimensions( {
width: css.getPropertyValue( 'width' ),
height: css.getPropertyValue( 'height' ),
} );
elem.style.position = '';
elem.style.width = '';
}, 100 ),
[]
);
useEffect( () => {
// Create an observer instance linked to the callback function
const observer = new window.MutationObserver( function (
mutationsList
) {
const hasChildList = mutationsList.find(
( { type } ) => type === 'childList'
);
if ( hasChildList ) {
resize();
}
} );
// Start observing the target node for configured mutations
observer.observe( containerRef.current, {
childList: true,
subtree: true,
} );
return () => observer.disconnect();
}, [] );
return (
<div
className="block-editor-block-toolbar-width-container"
ref={ containerRef }
style={ dimensions }
>
<TransitionGroup>
{ fills.length ? (
<CSSTransition
key="fills"
timeout={ 300 }
classNames="block-editor-block-toolbar-content"
>
<div className={ className } ref={ fillsRef }>
{ fills }
</div>
</CSSTransition>
) : (
<CSSTransition
key="default"
timeout={ 300 }
classNames="block-editor-block-toolbar-content"
>
<div className={ className } ref={ toolbarRef }>
{ children }
</div>
</CSSTransition>
) }
</TransitionGroup>
</div>
);
}