import { __ } from '@wordpress/i18n'; import { useEffect, useMemo, useState } from '@wordpress/element'; type TransparentColorPickerProps = { label: string; value: string; onChange: ( nextValue: string ) => void; }; const HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/; const isValidCssColor = ( value: string ): boolean => { const normalized = value.trim(); if ( normalized === '' ) { return false; } if ( HEX_COLOR_PATTERN.test( normalized ) ) { return true; } if ( typeof window !== 'undefined' && typeof window.CSS !== 'undefined' && typeof window.CSS.supports === 'function' ) { return window.CSS.supports( 'color', normalized ); } return false; }; const toNativeColorInputValue = ( value: string ): string => { const normalized = value.trim(); if ( /^#[0-9a-fA-F]{6}$/.test( normalized ) ) { return normalized; } if ( /^#[0-9a-fA-F]{3}$/.test( normalized ) ) { const [ r, g, b ] = normalized.slice( 1 ).split( '' ); return `#${ r }${ r }${ g }${ g }${ b }${ b }`; } if ( /^#[0-9a-fA-F]{8}$/.test( normalized ) ) { return `#${ normalized.slice( 1, 7 ) }`; } if ( /^#[0-9a-fA-F]{4}$/.test( normalized ) ) { const [ r, g, b ] = normalized.slice( 1, 4 ).split( '' ); return `#${ r }${ r }${ g }${ g }${ b }${ b }`; } return '#000000'; }; const TransparentColorPicker = ( { label, value, onChange }: TransparentColorPickerProps ) => { const [ draft, setDraft ] = useState( value ); useEffect( () => { setDraft( value ); }, [ value ] ); const nativeColorValue = useMemo( () => toNativeColorInputValue( value ), [ value ] ); const isTransparent = value.trim().toLowerCase() === 'transparent'; const handleTextChange = ( nextValue: string ) => { setDraft( nextValue ); if ( isValidCssColor( nextValue ) ) { onChange( nextValue.trim() ); } }; const handleTextBlur = () => { if ( ! isValidCssColor( draft ) ) { setDraft( value ); } }; return (