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 (
<>
setIsOpen(!isOpen)}
>
{name}
{isOpen && (
setIsOpen(false)}
>
)}
>
);
};
export default ColorControl;