1"use client"
2
3import React, { useEffect, useState } from "react"
4import { Check, ChevronDown } from "lucide-react"
5import { AnimatePresence, motion } from "motion/react"
6
7import { Button } from "@/components/ui/button"
8import { Input } from "@/components/ui/input"
9import { Label } from "@/components/ui/label"
10import {
11 Popover,
12 PopoverContent,
13 PopoverTrigger,
14} from "@/components/ui/popover"
15
16// Helper functions for color conversion
17const hslToHex = (h: number, s: number, l: number) => {
18 l /= 100
19 const a = (s * Math.min(l, 1 - l)) / 100
20 const f = (n: number) => {
21 const k = (n + h / 30) % 12
22 const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1)
23 return Math.round(255 * color)
24 .toString(16)
25 .padStart(2, "0")
26 }
27 return `#${f(0)}${f(8)}${f(4)}`
28}
29
30const hexToHsl = (hex: string): [number, number, number] => {
31 const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
32 if (!result) return [0, 0, 0]
33
34 let r = parseInt(result[1], 16) / 255
35 let g = parseInt(result[2], 16) / 255
36 let b = parseInt(result[3], 16) / 255
37
38 const max = Math.max(r, g, b)
39 const min = Math.min(r, g, b)
40 let h = 0
41 let s = 0
42 let l = (max + min) / 2
43
44 if (max !== min) {
45 const d = max - min
46 s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
47 switch (max) {
48 case r:
49 h = (g - b) / d + (g < b ? 6 : 0)
50 break
51 case g:
52 h = (b - r) / d + 2
53 break
54 case b:
55 h = (r - g) / d + 4
56 break
57 }
58 h /= 6
59 }
60
61 return [Math.round(h * 360), Math.round(s * 100), Math.round(l * 100)]
62}
63
64const normalizeColor = (color: string): string => {
65 if (color.startsWith("#")) {
66 return color.toUpperCase()
67 } else if (color.startsWith("hsl")) {
68 const [h, s, l] = color.match(/\d+(\.\d+)?/g)?.map(Number) || [0, 0, 0]
69 return `hsl(${Math.round(h)}, ${Math.round(s)}%, ${Math.round(l)}%)`
70 }
71 return color
72}
73
74const trimColorString = (color: string, maxLength: number = 20): string => {
75 if (color.length <= maxLength) return color
76 return `${color.slice(0, maxLength - 3)}...`
77}
78
79export function ColorPicker({
80 color,
81 onChange,
82}: {
83 color: string
84 onChange: (color: string) => void
85}) {
86 const [hsl, setHsl] = useState<[number, number, number]>([0, 0, 0])
87 const [colorInput, setColorInput] = useState(color)
88 const [isOpen, setIsOpen] = useState(false)
89
90 useEffect(() => {
91 handleColorChange(color)
92 }, [color])
93
94 const handleColorChange = (newColor: string) => {
95 const normalizedColor = normalizeColor(newColor)
96 setColorInput(normalizedColor)
97
98 let h, s, l
99 if (normalizedColor.startsWith("#")) {
100 ;[h, s, l] = hexToHsl(normalizedColor)
101 } else {
102 ;[h, s, l] = normalizedColor.match(/\d+(\.\d+)?/g)?.map(Number) || [
103 0, 0, 0,
104 ]
105 }
106
107 setHsl([h, s, l])
108 onChange(`hsl(${h.toFixed(1)}, ${s.toFixed(1)}%, ${l.toFixed(1)}%)`)
109 }
110
111 const handleHueChange = (hue: number) => {
112 const newHsl: [number, number, number] = [hue, hsl[1], hsl[2]]
113 setHsl(newHsl)
114 handleColorChange(`hsl(${newHsl[0]}, ${newHsl[1]}%, ${newHsl[2]}%)`)
115 }
116
117 const handleSaturationLightnessChange = (
118 event: React.MouseEvent<HTMLDivElement>
119 ) => {
120 const rect = event.currentTarget.getBoundingClientRect()
121 const x = event.clientX - rect.left
122 const y = event.clientY - rect.top
123 const s = Math.round((x / rect.width) * 100)
124 const l = Math.round(100 - (y / rect.height) * 100)
125 const newHsl: [number, number, number] = [hsl[0], s, l]
126 setHsl(newHsl)
127 handleColorChange(`hsl(${newHsl[0]}, ${newHsl[1]}%, ${newHsl[2]}%)`)
128 }
129
130 const handleColorInputChange = (
131 event: React.ChangeEvent<HTMLInputElement>
132 ) => {
133 const newColor = event.target.value
134 setColorInput(newColor)
135 if (
136 /^#[0-9A-Fa-f]{6}$/.test(newColor) ||
137 /^hsl$$\d+,\s*\d+%,\s*\d+%$$$/.test(newColor)
138 ) {
139 handleColorChange(newColor)
140 }
141 }
142
143 const colorPresets = [
144 "#FF3B30",
145 "#FF9500",
146 "#FFCC00",
147 "#4CD964",
148 "#5AC8FA",
149 "#007AFF",
150 "#5856D6",
151 "#FF2D55",
152 "#8E8E93",
153 "#EFEFF4",
154 "#E5E5EA",
155 "#D1D1D6",
156 ]
157
158 return (
159 <Popover open={isOpen} onOpenChange={setIsOpen}>
160 <PopoverTrigger asChild>
161 <Button
162 variant="outline"
163 className="w-[200px] justify-start text-left font-normal"
164 >
165 <div
166 className="w-4 h-4 rounded-full mr-2 shadow-sm"
167 style={{ backgroundColor: colorInput }}
168 />
169 <span className="flex-grow">{trimColorString(colorInput)}</span>
170 <ChevronDown className="h-4 w-4 opacity-50" />
171 </Button>
172 </PopoverTrigger>
173 <PopoverContent className="w-[240px] p-3">
174 <motion.div
175 initial={{ opacity: 0, scale: 0.95 }}
176 animate={{ opacity: 1, scale: 1 }}
177 exit={{ opacity: 0, scale: 0.95 }}
178 transition={{ duration: 0.2 }}
179 className="space-y-3"
180 >
181 <motion.div
182 className="w-full h-40 rounded-lg cursor-crosshair relative overflow-hidden"
183 style={{
184 background: `
185 linear-gradient(to top, rgba(0, 0, 0, 1), transparent),
186 linear-gradient(to right, rgba(255, 255, 255, 1), rgba(255, 0, 0, 0)),
187 hsl(${hsl[0]}, 100%, 50%)
188 `,
189 }}
190 onClick={handleSaturationLightnessChange}
191 >
192 <motion.div
193 className="w-4 h-4 rounded-full border-2 border-white absolute shadow-md"
194 style={{
195 left: `${hsl[1]}%`,
196 top: `${100 - hsl[2]}%`,
197 backgroundColor: `hsl(${hsl[0]}, ${hsl[1]}%, ${hsl[2]}%)`,
198 }}
199 whileHover={{ scale: 1.2 }}
200 whileTap={{ scale: 0.9 }}
201 />
202 </motion.div>
203 <motion.input
204 type="range"
205 min="0"
206 max="360"
207 value={hsl[0]}
208 onChange={(e) => handleHueChange(Number(e.target.value))}
209 className="w-full h-3 rounded-full appearance-none cursor-pointer"
210 style={{
211 background: `linear-gradient(to right,
212 hsl(0, 100%, 50%), hsl(60, 100%, 50%), hsl(120, 100%, 50%),
213 hsl(180, 100%, 50%), hsl(240, 100%, 50%), hsl(300, 100%, 50%), hsl(360, 100%, 50%)
214 )`,
215 }}
216 whileHover={{ scale: 1.05 }}
217 whileTap={{ scale: 0.95 }}
218 />
219 <div className="flex items-center space-x-2">
220 <Label htmlFor="color-input" className="sr-only">
221 Color
222 </Label>
223 <Input
224 id="color-input"
225 type="text"
226 value={colorInput}
227 onChange={handleColorInputChange}
228 className="flex-grow bg-white border border-gray-300 rounded-md text-sm h-8 px-2"
229 placeholder="#RRGGBB or hsl(h, s%, l%)"
230 />
231 <motion.div
232 className="w-8 h-8 rounded-md shadow-sm"
233 style={{ backgroundColor: colorInput }}
234 whileHover={{ scale: 1.1 }}
235 whileTap={{ scale: 0.9 }}
236 />
237 </div>
238 <div className="grid grid-cols-6 gap-2">
239 <AnimatePresence>
240 {colorPresets.map((preset) => (
241 <motion.button
242 key={preset}
243 className="w-8 h-8 rounded-full relative"
244 style={{ backgroundColor: preset }}
245 onClick={() => handleColorChange(preset)}
246 whileHover={{ scale: 1.2, zIndex: 1 }}
247 whileTap={{ scale: 0.9 }}
248 >
249 {colorInput === preset && (
250 <motion.div
251 initial={{ scale: 0 }}
252 animate={{ scale: 1 }}
253 exit={{ scale: 0 }}
254 transition={{ duration: 0.2 }}
255 >
256 <Check className="w-4 h-4 text-white absolute inset-0 m-auto" />
257 </motion.div>
258 )}
259 </motion.button>
260 ))}
261 </AnimatePresence>
262 </div>
263 </motion.div>
264 </PopoverContent>
265 </Popover>
266 )
267}
268
269export default ColorPicker
270