import type { HTMLAttributes } from 'react'; import { useEffect, useState } from 'react'; import { HexColorInput, HexColorPicker, setNonce } from 'react-colorful'; import { cn } from '../lib/utils'; import { Popover, PopoverContent, PopoverTrigger } from './popover'; export type ColorPickerProps = { disabled?: boolean; value: string; defaultValue?: string; onChange: (color: string) => void; nonce?: string; } & HTMLAttributes; export const ColorPicker = ({ className, disabled = false, value, defaultValue = '#000000', onChange, nonce, ...props }: ColorPickerProps) => { const [color, setColor] = useState(value || defaultValue); const [inputColor, setInputColor] = useState(value || defaultValue); const onColorChange = (newColor: string) => { setColor(newColor); setInputColor(newColor); onChange(newColor); }; const onInputChange = (newColor: string) => { setInputColor(newColor); }; const onInputBlur = () => { setColor(inputColor); onChange(inputColor); }; useEffect(() => { if (nonce) { setNonce(nonce); } }, [nonce]); return ( { if (e.key === 'Enter') { e.preventDefault(); onInputBlur(); } }} disabled={disabled} nonce={nonce} /> ); };