Initial
This commit is contained in:
83
ColorControl.js
Normal file
83
ColorControl.js
Normal file
@ -0,0 +1,83 @@
|
||||
import { useState, useRef } from '@wordpress/element';
|
||||
import { Popover, ToolbarButton, ColorPalette, __experimentalHStack as HStack } from '@wordpress/components';
|
||||
|
||||
const ColorControl = ({ name, colors = [], value, onChange, className }) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const buttonRef = useRef();
|
||||
|
||||
// Resolve what to show as the swatch color
|
||||
const resolveColorValue = (val) => {
|
||||
if (!val) return '';
|
||||
if (val.startsWith('var(')) {
|
||||
// Convert var(--wp--preset--color--primary) → #hex from the palette
|
||||
const match = colors.find(c => val.includes(c.slug));
|
||||
return match?.color || val;
|
||||
}
|
||||
return val;
|
||||
};
|
||||
|
||||
const selectedColor = resolveColorValue(value);
|
||||
|
||||
const handleChange = (colorValue) => {
|
||||
// Find if it matches a theme color
|
||||
const match = colors.find(c => c.color === colorValue);
|
||||
|
||||
let finalValue = colorValue;
|
||||
if (match?.slug) {
|
||||
// Store CSS variable instead of raw color code
|
||||
finalValue = `var(--wp--preset--color--${match.slug})`;
|
||||
}
|
||||
|
||||
if (onChange) onChange(finalValue);
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ToolbarButton
|
||||
ref={buttonRef}
|
||||
className={className ? className : ''}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
width: '20px',
|
||||
height: '20px',
|
||||
borderRadius: '50%',
|
||||
backgroundColor: selectedColor,
|
||||
border: '1px solid #ccc',
|
||||
marginRight: '8px',
|
||||
}}
|
||||
/>
|
||||
{name}
|
||||
</ToolbarButton>
|
||||
|
||||
{isOpen && (
|
||||
<Popover
|
||||
anchorRef={buttonRef}
|
||||
placement="bottom-start"
|
||||
onClose={() => setIsOpen(false)}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
padding: '16px',
|
||||
background: '#f9f9f9',
|
||||
borderRadius: '8px',
|
||||
minWidth: '250px',
|
||||
}}
|
||||
>
|
||||
<ColorPalette
|
||||
colors={colors}
|
||||
value={selectedColor}
|
||||
onChange={handleChange}
|
||||
enableAlpha
|
||||
/>
|
||||
</div>
|
||||
</Popover>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ColorControl;
|
||||
Reference in New Issue
Block a user