/
margin.js
91 lines (77 loc) · 2.26 KB
/
margin.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
/**
* WordPress dependencies
*/
import { useState, useRef, useEffect } from '@wordpress/element';
import isShallowEqual from '@wordpress/is-shallow-equal';
/**
* Internal dependencies
*/
import BlockPopover from '../components/block-popover';
import { __unstableUseBlockElement as useBlockElement } from '../components/block-list/use-block-props/use-block-refs';
function getComputedCSS( element, property ) {
return element.ownerDocument.defaultView
.getComputedStyle( element )
.getPropertyValue( property );
}
export function MarginVisualizer( { clientId, attributes, forceShow } ) {
const blockElement = useBlockElement( clientId );
const [ style, setStyle ] = useState();
const margin = attributes?.style?.spacing?.margin;
useEffect( () => {
if (
! blockElement ||
null === blockElement.ownerDocument.defaultView
) {
return;
}
const top = getComputedCSS( blockElement, 'margin-top' );
const right = getComputedCSS( blockElement, 'margin-right' );
const bottom = getComputedCSS( blockElement, 'margin-bottom' );
const left = getComputedCSS( blockElement, 'margin-left' );
setStyle( {
borderTopWidth: top,
borderRightWidth: right,
borderBottomWidth: bottom,
borderLeftWidth: left,
top: top ? `-${ top }` : 0,
right: right ? `-${ right }` : 0,
bottom: bottom ? `-${ bottom }` : 0,
left: left ? `-${ left }` : 0,
} );
}, [ blockElement, margin ] );
const [ isActive, setIsActive ] = useState( false );
const valueRef = useRef( margin );
const timeoutRef = useRef();
const clearTimer = () => {
if ( timeoutRef.current ) {
window.clearTimeout( timeoutRef.current );
}
};
useEffect( () => {
if ( ! isShallowEqual( margin, valueRef.current ) && ! forceShow ) {
setIsActive( true );
valueRef.current = margin;
timeoutRef.current = setTimeout( () => {
setIsActive( false );
}, 400 );
}
return () => {
setIsActive( false );
clearTimer();
};
}, [ margin, forceShow ] );
if ( ! isActive && ! forceShow ) {
return null;
}
return (
<BlockPopover
clientId={ clientId }
__unstableCoverTarget
__unstableRefreshSize={ margin }
__unstablePopoverSlot="block-toolbar"
shift={ false }
>
<div className="block-editor__padding-visualizer" style={ style } />
</BlockPopover>
);
}