/
color-panel.js
86 lines (76 loc) · 2.63 KB
/
color-panel.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
/**
* WordPress dependencies
*/
import { useState, useEffect } from '@wordpress/element';
/**
* Internal dependencies
*/
import ColorGradientSettingsDropdown from '../components/colors-gradients/dropdown';
import ContrastChecker from '../components/contrast-checker';
import InspectorControls from '../components/inspector-controls';
import useMultipleOriginColorsAndGradients from '../components/colors-gradients/use-multiple-origin-colors-and-gradients';
import { __unstableUseBlockRef as useBlockRef } from '../components/block-list/use-block-props/use-block-refs';
function getComputedStyle( node ) {
return node.ownerDocument.defaultView.getComputedStyle( node );
}
export default function ColorPanel( {
enableAlpha = false,
settings,
clientId,
enableContrastChecking = true,
} ) {
const [ detectedBackgroundColor, setDetectedBackgroundColor ] = useState();
const [ detectedColor, setDetectedColor ] = useState();
const [ detectedLinkColor, setDetectedLinkColor ] = useState();
const ref = useBlockRef( clientId );
const definedColors = settings.filter( ( setting ) => setting?.colorValue );
useEffect( () => {
if ( ! enableContrastChecking || ! definedColors.length ) {
return;
}
if ( ! ref.current ) {
return;
}
setDetectedColor( getComputedStyle( ref.current ).color );
const firstLinkElement = ref.current?.querySelector( 'a' );
if ( firstLinkElement && !! firstLinkElement.innerText ) {
setDetectedLinkColor( getComputedStyle( firstLinkElement ).color );
}
let backgroundColorNode = ref.current;
let backgroundColor =
getComputedStyle( backgroundColorNode ).backgroundColor;
while (
backgroundColor === 'rgba(0, 0, 0, 0)' &&
backgroundColorNode.parentNode &&
backgroundColorNode.parentNode.nodeType ===
backgroundColorNode.parentNode.ELEMENT_NODE
) {
backgroundColorNode = backgroundColorNode.parentNode;
backgroundColor =
getComputedStyle( backgroundColorNode ).backgroundColor;
}
setDetectedBackgroundColor( backgroundColor );
} );
const colorGradientSettings = useMultipleOriginColorsAndGradients();
return (
<InspectorControls __experimentalGroup="color">
<ColorGradientSettingsDropdown
enableAlpha={ enableAlpha }
panelId={ clientId }
settings={ settings }
__experimentalIsItemGroup={ false }
__experimentalHasMultipleOrigins
__experimentalIsRenderedInSidebar
{ ...colorGradientSettings }
/>
{ enableContrastChecking && (
<ContrastChecker
backgroundColor={ detectedBackgroundColor }
textColor={ detectedColor }
enableAlphaChecker={ enableAlpha }
linkColor={ detectedLinkColor }
/>
) }
</InspectorControls>
);
}