import { useEffect, useRef, useState } from 'react' // Declare iro for TypeScript declare global { interface Window { iro: any } } interface EnhancedColorPickerProps { color: string onChange: (color: string) => void label?: string } export function EnhancedColorPicker({ color, onChange, label }: EnhancedColorPickerProps) { const [isOpen, setIsOpen] = useState(false) const [currentColor, setCurrentColor] = useState(color) const containerRef = useRef(null) const pickerRef = useRef(null) const pickerInstanceRef = useRef(null) useEffect(() => { setCurrentColor(color) if (pickerInstanceRef.current) { pickerInstanceRef.current.color.hexString = color } }, [color]) useEffect(() => { if (isOpen && pickerRef.current && !pickerInstanceRef.current) { // Load iro.js if not already loaded if (!window.iro) { const script = document.createElement('script') script.src = 'https://cdn.jsdelivr.net/npm/@jaames/iro@5' script.onload = () => initializePicker() document.head.appendChild(script) } else { initializePicker() } } return () => { if (pickerInstanceRef.current) { // Cleanup if needed } } }, [isOpen]) const initializePicker = () => { if (pickerRef.current && window.iro && !pickerInstanceRef.current) { pickerInstanceRef.current = new window.iro.ColorPicker(pickerRef.current, { width: 200, color: currentColor, layout: [ { component: window.iro.ui.Wheel, options: {} }, { component: window.iro.ui.Slider, options: { sliderType: 'value' } } ] }) pickerInstanceRef.current.on('color:change', (color: any) => { setCurrentColor(color.hexString) onChange(color.hexString) }) } } useEffect(() => { const handleClickOutside = (e: MouseEvent) => { if (containerRef.current && !containerRef.current.contains(e.target as Node)) { setIsOpen(false) } } if (isOpen) { document.addEventListener('mousedown', handleClickOutside) return () => document.removeEventListener('mousedown', handleClickOutside) } }, [isOpen]) return (
{label && (
{label}
)} {isOpen && (
e.stopPropagation()} >
)}
) }