1"use client";
2
3import Color from "color";
4import { PipetteIcon } from "lucide-react";
5import { Slider } from "radix-ui";
6import {
7 type ComponentProps,
8 createContext,
9 type HTMLAttributes,
10 memo,
11 useCallback,
12 useContext,
13 useEffect,
14 useMemo,
15 useRef,
16 useState,
17} from "react";
18import { Button } from "@/components/ui/button";
19import { Input } from "@/components/ui/input";
20import {
21 Select,
22 SelectContent,
23 SelectItem,
24 SelectTrigger,
25 SelectValue,
26} from "@/components/ui/select";
27import { cn } from "@/lib/utils";
28
29type ColorPickerContextValue = {
30 hue: number;
31 saturation: number;
32 lightness: number;
33 alpha: number;
34 mode: string;
35 setHue: (hue: number) => void;
36 setSaturation: (saturation: number) => void;
37 setLightness: (lightness: number) => void;
38 setAlpha: (alpha: number) => void;
39 setMode: (mode: string) => void;
40};
41
42const ColorPickerContext = createContext<ColorPickerContextValue | undefined>(
43 undefined
44);
45
46export const useColorPicker = () => {
47 const context = useContext(ColorPickerContext);
48
49 if (!context) {
50 throw new Error("useColorPicker must be used within a ColorPickerProvider");
51 }
52
53 return context;
54};
55
56export type ColorPickerProps = HTMLAttributes<HTMLDivElement> & {
57 value?: Parameters<typeof Color>[0];
58 defaultValue?: Parameters<typeof Color>[0];
59 onChange?: (value: Parameters<typeof Color.rgb>[0]) => void;
60};
61
62export const ColorPicker = ({
63 value,
64 defaultValue = "#000000",
65 onChange,
66 className,
67 ...props
68}: ColorPickerProps) => {
69 const selectedColor = Color(value);
70 const defaultColor = Color(defaultValue);
71
72 const [hue, setHue] = useState(
73 selectedColor.hue() || defaultColor.hue() || 0
74 );
75 const [saturation, setSaturation] = useState(
76 selectedColor.saturationl() || defaultColor.saturationl() || 100
77 );
78 const [lightness, setLightness] = useState(
79 selectedColor.lightness() || defaultColor.lightness() || 50
80 );
81 const [alpha, setAlpha] = useState(
82 selectedColor.alpha() * 100 || defaultColor.alpha() * 100
83 );
84 const [mode, setMode] = useState("hex");
85
86 // Update color when controlled value changes
87 useEffect(() => {
88 if (value) {
89 const color = Color.rgb(value).rgb().object();
90
91 setHue(color.r);
92 setSaturation(color.g);
93 setLightness(color.b);
94 setAlpha(color.a);
95 }
96 }, [value]);
97
98 // Notify parent of changes
99 useEffect(() => {
100 if (onChange) {
101 const color = Color.hsl(hue, saturation, lightness).alpha(alpha / 100);
102 const rgba = color.rgb().array();
103
104 onChange([rgba[0], rgba[1], rgba[2], alpha / 100]);
105 }
106 }, [hue, saturation, lightness, alpha, onChange]);
107
108 return (
109 <ColorPickerContext.Provider
110 value={{
111 hue,
112 saturation,
113 lightness,
114 alpha,
115 mode,
116 setHue,
117 setSaturation,
118 setLightness,
119 setAlpha,
120 setMode,
121 }}
122 >
123 <div
124 className={cn("flex size-full flex-col gap-4", className)}
125 {...props}
126 />
127 </ColorPickerContext.Provider>
128 );
129};
130
131export type ColorPickerSelectionProps = HTMLAttributes<HTMLDivElement>;
132
133export const ColorPickerSelection = memo(
134 ({ className, ...props }: ColorPickerSelectionProps) => {
135 const containerRef = useRef<HTMLDivElement>(null);
136 const [isDragging, setIsDragging] = useState(false);
137 const [positionX, setPositionX] = useState(0);
138 const [positionY, setPositionY] = useState(0);
139 const { hue, setSaturation, setLightness } = useColorPicker();
140
141 const backgroundGradient = useMemo(() => {
142 return `linear-gradient(0deg, rgba(0,0,0,1), rgba(0,0,0,0)),
143 linear-gradient(90deg, rgba(255,255,255,1), rgba(255,255,255,0)),
144 hsl(${hue}, 100%, 50%)`;
145 }, [hue]);
146
147 const handlePointerMove = useCallback(
148 (event: PointerEvent) => {
149 if (!(isDragging && containerRef.current)) {
150 return;
151 }
152 const rect = containerRef.current.getBoundingClientRect();
153 const x = Math.max(
154 0,
155 Math.min(1, (event.clientX - rect.left) / rect.width)
156 );
157 const y = Math.max(
158 0,
159 Math.min(1, (event.clientY - rect.top) / rect.height)
160 );
161 setPositionX(x);
162 setPositionY(y);
163 setSaturation(x * 100);
164 const topLightness = x < 0.01 ? 100 : 50 + 50 * (1 - x);
165 const lightness = topLightness * (1 - y);
166
167 setLightness(lightness);
168 },
169 [isDragging, setSaturation, setLightness]
170 );
171
172 useEffect(() => {
173 const handlePointerUp = () => setIsDragging(false);
174
175 if (isDragging) {
176 window.addEventListener("pointermove", handlePointerMove);
177 window.addEventListener("pointerup", handlePointerUp);
178 }
179
180 return () => {
181 window.removeEventListener("pointermove", handlePointerMove);
182 window.removeEventListener("pointerup", handlePointerUp);
183 };
184 }, [isDragging, handlePointerMove]);
185
186 return (
187 <div
188 className={cn("relative size-full cursor-crosshair rounded", className)}
189 onPointerDown={(e) => {
190 e.preventDefault();
191 setIsDragging(true);
192 handlePointerMove(e.nativeEvent);
193 }}
194 ref={containerRef}
195 style={{
196 background: backgroundGradient,
197 }}
198 {...props}
199 >
200 <div
201 className="-translate-x-1/2 -translate-y-1/2 pointer-events-none absolute h-4 w-4 rounded-full border-2 border-white"
202 style={{
203 left: `${positionX * 100}%`,
204 top: `${positionY * 100}%`,
205 boxShadow: "0 0 0 1px rgba(0,0,0,0.5)",
206 }}
207 />
208 </div>
209 );
210 }
211);
212
213ColorPickerSelection.displayName = "ColorPickerSelection";
214
215export type ColorPickerHueProps = ComponentProps<typeof Slider.Root>;
216
217export const ColorPickerHue = ({
218 className,
219 ...props
220}: ColorPickerHueProps) => {
221 const { hue, setHue } = useColorPicker();
222
223 return (
224 <Slider.Root
225 className={cn("relative flex h-4 w-full touch-none", className)}
226 max={360}
227 onValueChange={([hue]) => setHue(hue)}
228 step={1}
229 value={[hue]}
230 {...props}
231 >
232 <Slider.Track className="relative my-0.5 h-3 w-full grow rounded-full bg-[linear-gradient(90deg,#FF0000,#FFFF00,#00FF00,#00FFFF,#0000FF,#FF00FF,#FF0000)]">
233 <Slider.Range className="absolute h-full" />
234 </Slider.Track>
235 <Slider.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
236 </Slider.Root>
237 );
238};
239
240export type ColorPickerAlphaProps = ComponentProps<typeof Slider.Root>;
241
242export const ColorPickerAlpha = ({
243 className,
244 ...props
245}: ColorPickerAlphaProps) => {
246 const { alpha, setAlpha } = useColorPicker();
247
248 return (
249 <Slider.Root
250 className={cn("relative flex h-4 w-full touch-none", className)}
251 max={100}
252 onValueChange={([alpha]) => setAlpha(alpha)}
253 step={1}
254 value={[alpha]}
255 {...props}
256 >
257 <Slider.Track className="relative my-0.5 h-3 w-full grow rounded-full bg-[url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==')] bg-center bg-repeat-x dark:bg-[url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAALklEQVR4nGP8+vWrCAMewM3N/QafPBM+SWLAqAGDwQBGQgoIpZOB98KoAVQwAADxzQcSVIRCfQAAAABJRU5ErkJggg==')]">
258 <div className="absolute inset-0 rounded-full bg-gradient-to-r from-transparent to-black/50 dark:to-white/50" />
259 <Slider.Range className="absolute h-full rounded-full bg-transparent" />
260 </Slider.Track>
261 <Slider.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
262 </Slider.Root>
263 );
264};
265
266export type ColorPickerEyeDropperProps = ComponentProps<typeof Button>;
267
268export const ColorPickerEyeDropper = ({
269 className,
270 ...props
271}: ColorPickerEyeDropperProps) => {
272 const { setHue, setSaturation, setLightness, setAlpha } = useColorPicker();
273
274 const handleEyeDropper = async () => {
275 try {
276 // @ts-expect-error - EyeDropper API is experimental
277 const eyeDropper = new EyeDropper();
278 const result = await eyeDropper.open();
279 const color = Color(result.sRGBHex);
280 const [h, s, l] = color.hsl().array();
281
282 setHue(h);
283 setSaturation(s);
284 setLightness(l);
285 setAlpha(100);
286 } catch (error) {
287 console.error("EyeDropper failed:", error);
288 }
289 };
290
291 return (
292 <Button
293 className={cn("shrink-0 text-muted-foreground", className)}
294 onClick={handleEyeDropper}
295 size="icon"
296 type="button"
297 variant="outline"
298 {...props}
299 >
300 <PipetteIcon size={16} />
301 </Button>
302 );
303};
304
305export type ColorPickerOutputProps = ComponentProps<typeof SelectTrigger>;
306
307const formats = ["hex", "rgb", "css", "hsl"];
308
309export const ColorPickerOutput = ({
310 className,
311 ...props
312}: ColorPickerOutputProps) => {
313 const { mode, setMode } = useColorPicker();
314
315 return (
316 <Select onValueChange={setMode} value={mode}>
317 <SelectTrigger className="h-8 w-20 shrink-0 text-xs" {...props}>
318 <SelectValue placeholder="Mode" />
319 </SelectTrigger>
320 <SelectContent>
321 {formats.map((format) => (
322 <SelectItem className="text-xs" key={format} value={format}>
323 {format.toUpperCase()}
324 </SelectItem>
325 ))}
326 </SelectContent>
327 </Select>
328 );
329};
330
331type PercentageInputProps = ComponentProps<typeof Input>;
332
333const PercentageInput = ({ className, ...props }: PercentageInputProps) => {
334 return (
335 <div className="relative">
336 <Input
337 readOnly
338 type="text"
339 {...props}
340 className={cn(
341 "h-8 w-[3.25rem] rounded-l-none bg-secondary px-2 text-xs shadow-none",
342 className
343 )}
344 />
345 <span className="-translate-y-1/2 absolute top-1/2 right-2 text-muted-foreground text-xs">
346 %
347 </span>
348 </div>
349 );
350};
351
352export type ColorPickerFormatProps = HTMLAttributes<HTMLDivElement>;
353
354export const ColorPickerFormat = ({
355 className,
356 ...props
357}: ColorPickerFormatProps) => {
358 const { hue, saturation, lightness, alpha, mode } = useColorPicker();
359 const color = Color.hsl(hue, saturation, lightness, alpha / 100);
360
361 if (mode === "hex") {
362 const hex = color.hex();
363
364 return (
365 <div
366 className={cn(
367 "-space-x-px relative flex w-full items-center rounded-md shadow-sm",
368 className
369 )}
370 {...props}
371 >
372 <Input
373 className="h-8 rounded-r-none bg-secondary px-2 text-xs shadow-none"
374 readOnly
375 type="text"
376 value={hex}
377 />
378 <PercentageInput value={alpha} />
379 </div>
380 );
381 }
382
383 if (mode === "rgb") {
384 const rgb = color
385 .rgb()
386 .array()
387 .map((value) => Math.round(value));
388
389 return (
390 <div
391 className={cn(
392 "-space-x-px flex items-center rounded-md shadow-sm",
393 className
394 )}
395 {...props}
396 >
397 {rgb.map((value, index) => (
398 <Input
399 className={cn(
400 "h-8 rounded-r-none bg-secondary px-2 text-xs shadow-none",
401 index && "rounded-l-none",
402 className
403 )}
404 key={index}
405 readOnly
406 type="text"
407 value={value}
408 />
409 ))}
410 <PercentageInput value={alpha} />
411 </div>
412 );
413 }
414
415 if (mode === "css") {
416 const rgb = color
417 .rgb()
418 .array()
419 .map((value) => Math.round(value));
420
421 return (
422 <div className={cn("w-full rounded-md shadow-sm", className)} {...props}>
423 <Input
424 className="h-8 w-full bg-secondary px-2 text-xs shadow-none"
425 readOnly
426 type="text"
427 value={`rgba(${rgb.join(", ")}, ${alpha}%)`}
428 {...props}
429 />
430 </div>
431 );
432 }
433
434 if (mode === "hsl") {
435 const hsl = color
436 .hsl()
437 .array()
438 .map((value) => Math.round(value));
439
440 return (
441 <div
442 className={cn(
443 "-space-x-px flex items-center rounded-md shadow-sm",
444 className
445 )}
446 {...props}
447 >
448 {hsl.map((value, index) => (
449 <Input
450 className={cn(
451 "h-8 rounded-r-none bg-secondary px-2 text-xs shadow-none",
452 index && "rounded-l-none",
453 className
454 )}
455 key={index}
456 readOnly
457 type="text"
458 value={value}
459 />
460 ))}
461 <PercentageInput value={alpha} />
462 </div>
463 );
464 }
465
466 return null;
467};
468