refactor: refactor color tool to match calculate blueprint

Rewrites all color components to use the glass panel design language,
fixed-height two-panel layout, and tab-based navigation.

- ColorManipulation: lg:grid-cols-5 split — left 2/5 shows ColorPicker
  + ColorInfo always; right 3/5 has Info/Adjust/Harmony/Gradient tabs;
  mobile 'Pick | Explore' switcher
- ColorPicker: removes shadcn Input/Label, native input with dynamic
  contrast color matching the picked hue
- ColorInfo: removes shadcn Button, native copy buttons on hover,
  metadata chips with bg-primary/5 background
- ManipulationPanel: keeps Slider, replaces Button with glass action
  buttons, tighter spacing and muted labels
- ExportMenu: keeps Select, replaces Buttons with glass action buttons,
  code preview in dark terminal box (#06060e)
- ColorSwatch: rectangular full-width design for palette grids,
  hover reveals copy icon, hex label at bottom
- PaletteGrid: denser grid (4→5 cols), smaller swatch height

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-01 08:15:33 +01:00
parent 50dc009fdf
commit 0727ec7675
7 changed files with 496 additions and 652 deletions

View File

@@ -1,7 +1,6 @@
'use client'; 'use client';
import { ColorInfo as ColorInfoType } from '@/lib/color/api/types'; import { ColorInfo as ColorInfoType } from '@/lib/color/api/types';
import { Button } from '@/components/ui/button';
import { Copy } from 'lucide-react'; import { Copy } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { cn } from '@/lib/utils/cn'; import { cn } from '@/lib/utils/cn';
@@ -12,79 +11,70 @@ interface ColorInfoProps {
} }
export function ColorInfo({ info, className }: ColorInfoProps) { export function ColorInfo({ info, className }: ColorInfoProps) {
const copyToClipboard = (value: string, label: string) => { const copy = (value: string, label: string) => {
navigator.clipboard.writeText(value); navigator.clipboard.writeText(value);
toast.success(`Copied ${label} to clipboard`); toast.success(`Copied ${label}`);
}; };
const formatRgb = (rgb: { r: number; g: number; b: number; a?: number }) => { const formatRgb = (rgb: { r: number; g: number; b: number; a?: number }) =>
if (rgb.a !== undefined && rgb.a < 1) { rgb.a !== undefined && rgb.a < 1
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${rgb.a})`; ? `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${rgb.a})`
} : `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
return `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
};
const formatHsl = (hsl: { h: number; s: number; l: number; a?: number }) => { const formatHsl = (hsl: { h: number; s: number; l: number; a?: number }) =>
if (hsl.a !== undefined && hsl.a < 1) { hsl.a !== undefined && hsl.a < 1
return `hsla(${Math.round(hsl.h)}°, ${Math.round(hsl.s * 100)}%, ${Math.round(hsl.l * 100)}%, ${hsl.a})`; ? `hsla(${Math.round(hsl.h)}°, ${Math.round(hsl.s * 100)}%, ${Math.round(hsl.l * 100)}%, ${hsl.a})`
} : `hsl(${Math.round(hsl.h)}°, ${Math.round(hsl.s * 100)}%, ${Math.round(hsl.l * 100)}%)`;
return `hsl(${Math.round(hsl.h)}°, ${Math.round(hsl.s * 100)}%, ${Math.round(hsl.l * 100)}%)`;
};
const formatLab = (lab: { l: number; a: number; b: number }) => {
return `lab(${lab.l.toFixed(1)} ${lab.a.toFixed(1)} ${lab.b.toFixed(1)})`;
};
const formatOkLab = (oklab: { l: number; a: number; b: number }) => {
return `oklab(${(oklab.l * 100).toFixed(1)}% ${oklab.a.toFixed(3)} ${oklab.b.toFixed(3)})`;
};
const formats = [ const formats = [
{ label: 'Hex', value: info.hex }, { label: 'HEX', value: info.hex },
{ label: 'RGB', value: formatRgb(info.rgb) }, { label: 'RGB', value: formatRgb(info.rgb) },
{ label: 'HSL', value: formatHsl(info.hsl) }, { label: 'HSL', value: formatHsl(info.hsl) },
{ label: 'Lab', value: formatLab(info.lab) }, { label: 'Lab', value: `lab(${info.lab.l.toFixed(1)} ${info.lab.a.toFixed(1)} ${info.lab.b.toFixed(1)})` },
{ label: 'OkLab', value: formatOkLab(info.oklab) }, { label: 'OkLab', value: `oklab(${(info.oklab.l * 100).toFixed(1)}% ${info.oklab.a.toFixed(3)} ${info.oklab.b.toFixed(3)})` },
]; ];
return ( return (
<div className={cn('space-y-3', className)}> <div className={cn('space-y-3', className)}>
<div className="grid grid-cols-1 gap-1.5"> {/* Format rows */}
{formats.map((format) => ( <div className="space-y-1">
{formats.map((fmt) => (
<div <div
key={format.label} key={fmt.label}
className="flex items-center justify-between px-3 py-2 bg-muted/50 rounded-md group" className="group flex items-center justify-between px-2.5 py-1.5 rounded-lg border border-transparent hover:border-border/30 hover:bg-primary/5 transition-all"
> >
<div className="flex items-baseline gap-2 min-w-0 flex-1"> <div className="flex items-baseline gap-2 min-w-0 flex-1">
<span className="text-[10px] uppercase tracking-wider text-muted-foreground w-10 shrink-0">{format.label}</span> <span className="text-[10px] font-semibold text-muted-foreground/50 uppercase tracking-widest w-9 shrink-0">
<span className="font-mono text-xs truncate">{format.value}</span> {fmt.label}
</span>
<span className="font-mono text-xs text-foreground/80 truncate">{fmt.value}</span>
</div> </div>
<Button <button
size="icon-xs" onClick={() => copy(fmt.value, fmt.label)}
variant="ghost" aria-label={`Copy ${fmt.label}`}
onClick={() => copyToClipboard(format.value, format.label)} className="shrink-0 ml-2 p-1 rounded text-muted-foreground/30 hover:text-primary opacity-0 group-hover:opacity-100 transition-all"
aria-label={`Copy ${format.label} value`}
className="opacity-0 group-hover:opacity-100 transition-opacity"
> >
<Copy className="h-3 w-3" /> <Copy className="w-3 h-3" />
</Button> </button>
</div> </div>
))} ))}
</div> </div>
<div className="grid grid-cols-3 gap-3 pt-2 border-t text-xs"> {/* Metadata row */}
<div> <div className="grid grid-cols-3 gap-2 pt-2 border-t border-border/25">
<div className="text-muted-foreground mb-0.5">Brightness</div> {[
<div className="font-medium">{(info.brightness * 100).toFixed(1)}%</div> { label: 'Brightness', value: `${(info.brightness * 100).toFixed(1)}%` },
</div> { label: 'Luminance', value: `${(info.luminance * 100).toFixed(1)}%` },
<div> {
<div className="text-muted-foreground mb-0.5">Luminance</div> label: info.name && typeof info.name === 'string' ? 'Name' : 'Type',
<div className="font-medium">{(info.luminance * 100).toFixed(1)}%</div> value: info.name && typeof info.name === 'string' ? info.name : (info.is_light ? 'Light' : 'Dark'),
</div> },
<div> ].map((m) => (
<div className="text-muted-foreground mb-0.5">{info.name && typeof info.name === 'string' ? 'Name' : 'Type'}</div> <div key={m.label} className="px-2.5 py-2 rounded-lg bg-primary/5 border border-border/20">
<div className="font-medium">{info.name && typeof info.name === 'string' ? info.name : (info.is_light ? 'Light' : 'Dark')}</div> <div className="text-[10px] text-muted-foreground/40 font-mono mb-0.5">{m.label}</div>
<div className="text-xs font-mono font-medium text-foreground/75 truncate">{m.value}</div>
</div> </div>
))}
</div> </div>
</div> </div>
); );

View File

@@ -7,27 +7,32 @@ import { ColorInfo } from '@/components/color/ColorInfo';
import { ManipulationPanel } from '@/components/color/ManipulationPanel'; import { ManipulationPanel } from '@/components/color/ManipulationPanel';
import { PaletteGrid } from '@/components/color/PaletteGrid'; import { PaletteGrid } from '@/components/color/PaletteGrid';
import { ExportMenu } from '@/components/color/ExportMenu'; import { ExportMenu } from '@/components/color/ExportMenu';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useColorInfo, useGeneratePalette, useGenerateGradient } from '@/lib/color/api/queries'; import { useColorInfo, useGeneratePalette, useGenerateGradient } from '@/lib/color/api/queries';
import { Loader2, Share2, Palette, Plus, X, Layers } from 'lucide-react'; import { Loader2, Share2, Plus, X, Palette, Layers } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { cn } from '@/lib/utils';
type HarmonyType = type HarmonyType = 'monochromatic' | 'analogous' | 'complementary' | 'triadic' | 'tetradic';
| 'monochromatic' type RightTab = 'info' | 'adjust' | 'harmony' | 'gradient';
| 'analogous' type MobileTab = 'pick' | 'explore';
| 'complementary'
| 'triadic' const HARMONY_OPTS: { value: HarmonyType; label: string; desc: string }[] = [
| 'tetradic'; { value: 'monochromatic', label: 'Mono', desc: 'Single hue, varied lightness' },
{ value: 'analogous', label: 'Analogous', desc: 'Adjacent colors ±30°' },
{ value: 'complementary', label: 'Complement', desc: 'Opposite on wheel 180°' },
{ value: 'triadic', label: 'Triadic', desc: 'Three equal 120° steps' },
{ value: 'tetradic', label: 'Tetradic', desc: 'Four equal 90° steps' },
];
const RIGHT_TABS: { value: RightTab; label: string }[] = [
{ value: 'info', label: 'Info' },
{ value: 'adjust', label: 'Adjust' },
{ value: 'harmony', label: 'Harmony' },
{ value: 'gradient', label: 'Gradient' },
];
const actionBtn =
'flex items-center gap-1 px-2.5 py-1 text-xs glass rounded-md border border-border/30 text-muted-foreground hover:text-primary hover:border-primary/30 hover:bg-primary/10 transition-all disabled:opacity-40 disabled:cursor-not-allowed';
function ColorManipulationContent() { function ColorManipulationContent() {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
@@ -37,24 +42,23 @@ function ColorManipulationContent() {
return urlColor ? `#${urlColor.replace('#', '')}` : '#ff0099'; return urlColor ? `#${urlColor.replace('#', '')}` : '#ff0099';
}); });
// Harmony state const [rightTab, setRightTab] = useState<RightTab>('info');
const [mobileTab, setMobileTab] = useState<MobileTab>('pick');
// Harmony
const [harmonyType, setHarmonyType] = useState<HarmonyType>('complementary'); const [harmonyType, setHarmonyType] = useState<HarmonyType>('complementary');
const [palette, setPalette] = useState<string[]>([]); const [palette, setPalette] = useState<string[]>([]);
const paletteMutation = useGeneratePalette(); const paletteMutation = useGeneratePalette();
// Gradient state // Gradient
const [stops, setStops] = useState<string[]>(['#ff0099', '#0099ff']); const [stops, setStops] = useState<string[]>(['#ff0099', '#0099ff']);
const [gradientCount, setGradientCount] = useState(10); const [gradientCount, setGradientCount] = useState(10);
const [gradientResult, setGradientResult] = useState<string[]>([]); const [gradientResult, setGradientResult] = useState<string[]>([]);
const gradientMutation = useGenerateGradient(); const gradientMutation = useGenerateGradient();
const { data, isLoading, isError, error } = useColorInfo({ const { data, isLoading } = useColorInfo({ colors: [color] });
colors: [color],
});
const colorInfo = data?.colors[0]; const colorInfo = data?.colors[0];
// Update URL when color changes
useEffect(() => { useEffect(() => {
const hex = color.replace('#', ''); const hex = color.replace('#', '');
if (hex.length === 6 || hex.length === 3) { if (hex.length === 6 || hex.length === 3) {
@@ -64,301 +68,289 @@ function ColorManipulationContent() {
// Sync first gradient stop with active color // Sync first gradient stop with active color
useEffect(() => { useEffect(() => {
const newStops = [...stops]; setStops((prev) => [color, ...prev.slice(1)]);
newStops[0] = color;
setStops(newStops);
}, [color]); }, [color]);
const handleShare = () => { const handleShare = () => {
const url = `${window.location.origin}/color?color=${color.replace('#', '')}`; navigator.clipboard.writeText(`${window.location.origin}/color?color=${color.replace('#', '')}`);
navigator.clipboard.writeText(url); toast.success('Link copied!');
toast.success('Link copied to clipboard!');
}; };
const generateHarmony = async () => { const generateHarmony = async () => {
try { try {
const result = await paletteMutation.mutateAsync({ const result = await paletteMutation.mutateAsync({ base: color, scheme: harmonyType });
base: color, setPalette([result.palette.primary, ...result.palette.secondary]);
scheme: harmonyType, toast.success(`Generated ${harmonyType} palette`);
}); } catch { toast.error('Failed to generate palette'); }
const colors = [result.palette.primary, ...result.palette.secondary];
setPalette(colors);
toast.success(`Generated ${harmonyType} harmony palette`);
} catch (error) {
toast.error('Failed to generate harmony palette');
console.error(error);
}
}; };
const generateGradient = async () => { const generateGradient = async () => {
try { try {
const result = await gradientMutation.mutateAsync({ const result = await gradientMutation.mutateAsync({ stops, count: gradientCount });
stops,
count: gradientCount,
});
setGradientResult(result.gradient); setGradientResult(result.gradient);
toast.success(`Generated ${result.gradient.length} colors`); toast.success(`Generated ${result.gradient.length} colors`);
} catch (error) { } catch { toast.error('Failed to generate gradient'); }
toast.error('Failed to generate gradient');
}
}; };
const addStop = () => { const updateStop = (i: number, v: string) => {
setStops([...stops, '#000000']); const next = [...stops];
}; next[i] = v;
setStops(next);
const removeStop = (index: number) => { if (i === 0) setColor(v);
if (index === 0) return;
if (stops.length > 2) {
setStops(stops.filter((_, i) => i !== index));
}
};
const updateStop = (index: number, colorValue: string) => {
const newStops = [...stops];
newStops[index] = colorValue;
setStops(newStops);
if (index === 0) setColor(colorValue);
};
const harmonyDescriptions: Record<HarmonyType, string> = {
monochromatic: 'Single color with variations',
analogous: 'Colors adjacent on the color wheel (±30°)',
complementary: 'Colors opposite on the color wheel (180°)',
triadic: 'Three colors evenly spaced on the color wheel (120°)',
tetradic: 'Four colors evenly spaced on the color wheel (90°)',
}; };
return ( return (
<div className="space-y-6"> <div className="flex flex-col gap-4">
{/* Row 1: Workspace */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-stretch"> {/* ── Mobile tab switcher ────────────────────────────────── */}
{/* Main Workspace: Color Picker and Information */} <div className="flex lg:hidden glass rounded-xl p-1 gap-1">
<div className="lg:col-span-2"> {(['pick', 'explore'] as MobileTab[]).map((t) => (
<Card className="h-full"> <button
<CardHeader className="flex flex-row items-center justify-between space-y-0"> key={t}
<CardTitle>Color Picker</CardTitle> onClick={() => setMobileTab(t)}
<Button onClick={handleShare} variant="outline" size="xs"> className={cn(
<Share2 className="h-3 w-3 mr-1" /> 'flex-1 py-2.5 rounded-lg text-sm font-medium capitalize transition-all',
Share mobileTab === t
</Button> ? 'bg-primary text-primary-foreground shadow-sm'
</CardHeader> : 'text-muted-foreground hover:text-foreground'
<CardContent> )}
<div className="flex flex-col md:flex-row gap-8"> >
<div className="flex-shrink-0 mx-auto md:mx-0"> {t === 'pick' ? 'Pick' : 'Explore'}
</button>
))}
</div>
{/* ── Main layout ────────────────────────────────────────── */}
<div
className="grid grid-cols-1 lg:grid-cols-5 gap-4"
style={{ height: 'calc(100svh - 220px)', minHeight: '620px' }}
>
{/* Left panel: Picker + ColorInfo */}
<div
className={cn(
'lg:col-span-2 flex flex-col gap-3 overflow-hidden',
mobileTab !== 'pick' && 'hidden lg:flex'
)}
>
{/* Color picker card */}
<div className="glass rounded-xl p-4 shrink-0">
<div className="flex items-center justify-between mb-3">
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
Color
</span>
<button onClick={handleShare} className={actionBtn}>
<Share2 className="w-3 h-3" /> Share
</button>
</div>
<ColorPicker color={color} onChange={setColor} /> <ColorPicker color={color} onChange={setColor} />
</div> </div>
<div className="flex-1 min-w-0"> {/* Color info card */}
{isLoading && ( <div className="glass rounded-xl p-4 flex flex-col flex-1 min-h-0 overflow-hidden">
<div className="flex items-center justify-center py-12"> <span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest block mb-3 shrink-0">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /> Info
</span>
<div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin scrollbar-thumb-primary/20 scrollbar-track-transparent">
{isLoading ? (
<div className="flex justify-center py-8">
<Loader2 className="w-4 w-4 animate-spin text-muted-foreground/40" />
</div> </div>
) : colorInfo ? (
<ColorInfo info={colorInfo} />
) : null}
</div>
</div>
</div>
{/* Right panel: tabbed tools */}
<div
className={cn(
'lg:col-span-3 flex flex-col overflow-hidden',
mobileTab !== 'explore' && 'hidden lg:flex'
)} )}
{isError && (
<div className="p-3 bg-destructive/10 text-destructive rounded-lg text-sm">
<p className="font-medium">Error loading color information</p>
<p className="mt-1">{error?.message || 'Unknown error'}</p>
</div>
)}
{colorInfo && <ColorInfo info={colorInfo} />}
</div>
</div>
</CardContent>
</Card>
</div>
{/* Sidebar: Color Manipulation */}
<div className="lg:col-span-1">
<Card className="h-full">
<CardHeader>
<CardTitle>Adjustments</CardTitle>
</CardHeader>
<CardContent>
<ManipulationPanel color={color} onColorChange={setColor} />
</CardContent>
</Card>
</div>
</div>
{/* Row 2: Harmony Generator */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-stretch">
{/* Harmony Controls */}
<div className="lg:col-span-1">
<Card className="h-full">
<CardHeader>
<CardTitle>Harmony</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<Select
value={harmonyType}
onValueChange={(value) => setHarmonyType(value as HarmonyType)}
> >
<SelectTrigger className="w-full"> <div className="glass rounded-xl p-4 flex flex-col flex-1 min-h-0 overflow-hidden">
<SelectValue placeholder="Select harmony" />
</SelectTrigger>
<SelectContent>
<SelectItem value="monochromatic">Monochromatic</SelectItem>
<SelectItem value="analogous">Analogous</SelectItem>
<SelectItem value="complementary">Complementary</SelectItem>
<SelectItem value="triadic">Triadic</SelectItem>
<SelectItem value="tetradic">Tetradic (Square)</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground"> {/* Tab switcher */}
{harmonyDescriptions[harmonyType]} <div className="flex glass rounded-lg p-0.5 gap-0.5 mb-4 shrink-0">
{RIGHT_TABS.map(({ value, label }) => (
<button
key={value}
onClick={() => setRightTab(value)}
className={cn(
'flex-1 py-1.5 rounded-md text-xs font-medium transition-all',
rightTab === value
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'
)}
>
{label}
</button>
))}
</div>
{/* Tab content */}
<div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin scrollbar-thumb-primary/20 scrollbar-track-transparent pr-0.5">
{/* ── Info tab ─────────────────────────────── */}
{rightTab === 'info' && (
<div className="space-y-3">
{/* Large color preview */}
<div
className="w-full rounded-xl border border-white/8 transition-colors duration-300"
style={{ height: '140px', background: color }}
/>
{isLoading ? (
<div className="flex justify-center py-6">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground/40" />
</div>
) : colorInfo ? (
<ColorInfo info={colorInfo} />
) : null}
</div>
)}
{/* ── Adjust tab ───────────────────────────── */}
{rightTab === 'adjust' && (
<ManipulationPanel color={color} onColorChange={setColor} />
)}
{/* ── Harmony tab ──────────────────────────── */}
{rightTab === 'harmony' && (
<div className="space-y-4">
{/* Scheme selector */}
<div className="space-y-2">
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
Scheme
</span>
<div className="flex flex-wrap gap-1.5">
{HARMONY_OPTS.map((opt) => (
<button
key={opt.value}
onClick={() => setHarmonyType(opt.value)}
className={cn(
'px-2.5 py-1 rounded-lg border text-xs font-mono transition-all',
harmonyType === opt.value
? 'bg-primary/10 border-primary/40 text-primary'
: 'border-border/30 text-muted-foreground hover:border-primary/30 hover:text-foreground'
)}
>
{opt.label}
</button>
))}
</div>
<p className="text-[10px] text-muted-foreground/50 font-mono">
{HARMONY_OPTS.find((o) => o.value === harmonyType)?.desc}
</p> </p>
</div>
<Button <button
onClick={generateHarmony} onClick={generateHarmony}
disabled={paletteMutation.isPending} disabled={paletteMutation.isPending}
className="w-full" className={cn(actionBtn, 'w-full justify-center py-2')}
> >
{paletteMutation.isPending ? ( {paletteMutation.isPending
<> ? <><Loader2 className="w-3 h-3 animate-spin" /> Generating</>
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" /> : <><Palette className="w-3 h-3" /> Generate Palette</>
Generating... }
</> </button>
) : (
'Generate'
)}
</Button>
</CardContent>
</Card>
</div>
{/* Harmony Results */} {palette.length > 0 && (
<div className="lg:col-span-2"> <div className="space-y-4">
<Card className="h-full">
<CardHeader>
<CardTitle>
Palette {palette.length > 0 && <span className="text-muted-foreground font-normal text-sm ml-1">({palette.length})</span>}
</CardTitle>
</CardHeader>
<CardContent>
{palette.length > 0 ? (
<div className="space-y-5">
<PaletteGrid colors={palette} onColorClick={setColor} /> <PaletteGrid colors={palette} onColorClick={setColor} />
<div className="pt-3 border-t"> <div className="border-t border-border/25 pt-4">
<ExportMenu colors={palette} /> <ExportMenu colors={palette} />
</div> </div>
</div> </div>
) : ( )}
<div className="py-8 text-center text-muted-foreground text-xs">
<Palette className="h-8 w-8 mx-auto mb-2 opacity-20" />
<p>Generate a harmony palette from the current color</p>
</div> </div>
)} )}
</CardContent>
</Card>
</div>
</div>
{/* Row 3: Gradient Generator */} {/* ── Gradient tab ─────────────────────────── */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-stretch"> {rightTab === 'gradient' && (
{/* Gradient Controls */} <div className="space-y-4">
<div className="lg:col-span-1"> {/* Color stops */}
<Card className="h-full">
<CardHeader>
<CardTitle>Gradient</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<Label className="text-xs">Color Stops</Label> <span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
{stops.map((stop, index) => ( Stops
<div key={index} className="flex items-center gap-2"> </span>
<Input {stops.map((stop, i) => (
<div key={i} className="flex items-center gap-2">
<input
type="color" type="color"
value={stop} value={stop}
onChange={(e) => updateStop(index, e.target.value)} onChange={(e) => updateStop(i, e.target.value)}
className="w-9 h-9 p-1 shrink-0 cursor-pointer" className="w-8 h-8 rounded-lg cursor-pointer border border-border/40 bg-transparent shrink-0 p-0.5"
/> />
<Input <input
type="text" type="text"
value={stop} value={stop}
onChange={(e) => updateStop(index, e.target.value)} onChange={(e) => updateStop(i, e.target.value)}
className="font-mono text-xs flex-1" className="flex-1 bg-transparent border border-border/40 rounded-lg px-2.5 py-1.5 text-xs font-mono outline-none focus:border-primary/50 transition-colors"
/> />
{index !== 0 && stops.length > 2 && ( {i !== 0 && stops.length > 2 && (
<Button <button
variant="ghost" onClick={() => setStops(stops.filter((_, idx) => idx !== i))}
size="icon-xs" className="shrink-0 text-muted-foreground/35 hover:text-destructive transition-colors"
onClick={() => removeStop(index)}
> >
<X className="h-3.5 w-3.5" /> <X className="w-3.5 h-3.5" />
</Button> </button>
)} )}
</div> </div>
))} ))}
<Button onClick={addStop} variant="outline" className="w-full"> <button
<Plus className="h-3.5 w-3.5 mr-1.5" /> onClick={() => setStops([...stops, '#000000'])}
Add Stop className="w-full py-1.5 rounded-lg border border-dashed border-border/30 text-xs text-muted-foreground/40 hover:text-foreground hover:border-primary/30 transition-all flex items-center justify-center gap-1"
</Button> >
<Plus className="w-3 h-3" /> Add stop
</button>
</div> </div>
<div className="space-y-2"> {/* Steps */}
<Label className="text-xs">Steps</Label> <div className="flex items-center gap-3">
<Input <span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest shrink-0">
Steps
</span>
<input
type="number" type="number"
min={2} min={2}
max={100} max={100}
value={gradientCount} value={gradientCount}
onChange={(e) => setGradientCount(parseInt(e.target.value))} onChange={(e) => setGradientCount(parseInt(e.target.value))}
className="w-20 bg-transparent border border-border/40 rounded-lg px-2.5 py-1.5 text-xs font-mono text-center outline-none focus:border-primary/50 transition-colors"
/> />
</div> </div>
<Button <button
onClick={generateGradient} onClick={generateGradient}
disabled={gradientMutation.isPending} disabled={gradientMutation.isPending}
className="w-full" className={cn(actionBtn, 'w-full justify-center py-2')}
> >
{gradientMutation.isPending ? ( {gradientMutation.isPending
<> ? <><Loader2 className="w-3 h-3 animate-spin" /> Generating</>
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" /> : <><Layers className="w-3 h-3" /> Generate Gradient</>
Generating... }
</> </button>
) : (
'Generate'
)}
</Button>
</CardContent>
</Card>
</div>
{/* Gradient Results */} {gradientResult.length > 0 && (
<div className="lg:col-span-2"> <div className="space-y-4">
<Card className="h-full"> {/* Gradient preview bar */}
<CardHeader>
<CardTitle>
Gradient {gradientResult.length > 0 && <span className="text-muted-foreground font-normal text-sm ml-1">({gradientResult.length})</span>}
</CardTitle>
</CardHeader>
<CardContent>
{gradientResult.length > 0 ? (
<div className="space-y-5">
<div <div
className="h-16 w-full rounded-lg border" className="h-12 w-full rounded-xl border border-white/8"
style={{ style={{ background: `linear-gradient(to right, ${gradientResult.join(', ')})` }}
background: `linear-gradient(to right, ${gradientResult.join(', ')})`,
}}
/> />
<PaletteGrid colors={gradientResult} onColorClick={setColor} /> <PaletteGrid colors={gradientResult} onColorClick={setColor} />
<div className="pt-3 border-t"> <div className="border-t border-border/25 pt-4">
<ExportMenu colors={gradientResult} /> <ExportMenu colors={gradientResult} />
</div> </div>
</div> </div>
) : ( )}
<div className="py-8 text-center text-muted-foreground text-xs">
<Layers className="h-8 w-8 mx-auto mb-2 opacity-20" />
<p>Add color stops and generate a smooth gradient</p>
</div> </div>
)} )}
</CardContent>
</Card> </div>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -369,7 +361,7 @@ export function ColorManipulation() {
return ( return (
<Suspense fallback={ <Suspense fallback={
<div className="flex items-center justify-center py-12"> <div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /> <Loader2 className="h-8 w-8 animate-spin text-muted-foreground/40" />
</div> </div>
}> }>
<ColorManipulationContent /> <ColorManipulationContent />

View File

@@ -1,8 +1,6 @@
'use client'; 'use client';
import { HexColorPicker } from 'react-colorful'; import { HexColorPicker } from 'react-colorful';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils/cn'; import { cn } from '@/lib/utils/cn';
import { hexToRgb } from '@/lib/color/utils/color'; import { hexToRgb } from '@/lib/color/utils/color';
@@ -13,45 +11,23 @@ interface ColorPickerProps {
} }
export function ColorPicker({ color, onChange, className }: ColorPickerProps) { export function ColorPicker({ color, onChange, className }: ColorPickerProps) {
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { const rgb = hexToRgb(color);
const value = e.target.value; const brightness = rgb ? (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000 : 0;
// Allow partial input while typing const textColor = brightness > 128 ? '#000000' : '#ffffff';
onChange(value); const borderColor = brightness > 128 ? 'rgba(0,0,0,0.12)' : 'rgba(255,255,255,0.2)';
};
// Determine text color based on background brightness
const getContrastColor = (hex: string) => {
const rgb = hexToRgb(hex);
if (!rgb) return 'inherit';
const brightness = (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
return brightness > 128 ? '#000000' : '#ffffff';
};
const textColor = getContrastColor(color);
return ( return (
<div className={cn('flex flex-col items-center justify-center space-y-3', className)}> <div className={cn('flex flex-col gap-3', className)}>
<div className="w-full max-w-[200px] space-y-3">
<HexColorPicker color={color} onChange={onChange} className="!w-full" /> <HexColorPicker color={color} onChange={onChange} className="!w-full" />
<div className="space-y-1.5"> <input
<Label htmlFor="color-input" className="text-xs">
Hex Value
</Label>
<Input
id="color-input"
type="text" type="text"
value={color} value={color}
onChange={handleInputChange} onChange={(e) => onChange(e.target.value)}
placeholder="#ff0099" placeholder="#ff0099"
className="font-mono text-xs transition-colors duration-200" className="w-full font-mono text-xs rounded-lg px-3 py-2 outline-none transition-colors duration-200 border"
style={{ style={{ backgroundColor: color, color: textColor, borderColor }}
backgroundColor: color, spellCheck={false}
color: textColor,
borderColor: textColor === '#000000' ? 'rgba(0,0,0,0.1)' : 'rgba(255,255,255,0.2)'
}}
/> />
</div> </div>
</div>
</div>
); );
} }

View File

@@ -13,54 +13,43 @@ interface ColorSwatchProps {
className?: string; className?: string;
} }
export function ColorSwatch({ export function ColorSwatch({ color, size = 'md', showLabel = true, onClick, className }: ColorSwatchProps) {
color,
size = 'md',
showLabel = true,
onClick,
className,
}: ColorSwatchProps) {
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
const sizeClasses = { const handleClick = () => {
sm: 'h-12 w-12', if (onClick) { onClick(); return; }
md: 'h-16 w-16',
lg: 'h-24 w-24',
};
const handleCopy = (e: React.MouseEvent) => {
e.stopPropagation();
navigator.clipboard.writeText(color); navigator.clipboard.writeText(color);
setCopied(true); setCopied(true);
toast.success(`Copied ${color}`); toast.success(`Copied ${color}`);
setTimeout(() => setCopied(false), 2000); setTimeout(() => setCopied(false), 1500);
}; };
return ( return (
<div className={cn('flex flex-col items-center gap-2', className)}>
<button <button
onClick={handleClick}
title={color}
aria-label={`Color ${color}`}
className={cn( className={cn(
'relative rounded-lg ring-2 ring-border transition-all duration-200', 'group relative w-full rounded-lg overflow-hidden border border-white/8 transition-all',
'hover:scale-110 hover:ring-primary hover:shadow-lg', 'hover:scale-[1.04] hover:border-white/20 hover:shadow-lg hover:shadow-black/20',
'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2', size === 'sm' && 'h-10',
'group active:scale-95', size === 'md' && 'h-14',
sizeClasses[size] size === 'lg' && 'h-20',
className
)} )}
style={{ backgroundColor: color }} style={{ backgroundColor: color }}
onClick={onClick || handleCopy}
aria-label={`Color ${color}`}
> >
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-200 bg-black/30 rounded-lg backdrop-blur-sm"> <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/25">
{copied ? ( {copied
<Check className="h-5 w-5 text-white animate-scale-in" /> ? <Check className="w-3.5 h-3.5 text-white drop-shadow" />
) : ( : <Copy className="w-3.5 h-3.5 text-white drop-shadow" />
<Copy className="h-5 w-5 text-white" /> }
)}
</div> </div>
</button>
{showLabel && ( {showLabel && (
<span className="text-xs font-mono text-muted-foreground">{color}</span> <div className="absolute bottom-0 inset-x-0 px-1 py-0.5 text-[9px] font-mono text-white/70 bg-black/25 truncate text-center leading-tight">
)} {color}
</div> </div>
)}
</button>
); );
} }

View File

@@ -1,6 +1,6 @@
'use client'; 'use client';
import { Button } from '@/components/ui/button'; import { useState, useEffect } from 'react';
import { import {
Select, Select,
SelectContent, SelectContent,
@@ -8,7 +8,6 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from '@/components/ui/select'; } from '@/components/ui/select';
import { useState, useEffect } from 'react';
import { Download, Copy, Check, Loader2 } from 'lucide-react'; import { Download, Copy, Check, Loader2 } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { import {
@@ -21,6 +20,7 @@ import {
type ExportColor, type ExportColor,
} from '@/lib/color/utils/export'; } from '@/lib/color/utils/export';
import { colorAPI } from '@/lib/color/api/client'; import { colorAPI } from '@/lib/color/api/client';
import { cn } from '@/lib/utils/cn';
interface ExportMenuProps { interface ExportMenuProps {
colors: string[]; colors: string[];
@@ -30,6 +30,9 @@ interface ExportMenuProps {
type ExportFormat = 'css' | 'scss' | 'tailwind' | 'json' | 'javascript'; type ExportFormat = 'css' | 'scss' | 'tailwind' | 'json' | 'javascript';
type ColorSpace = 'hex' | 'rgb' | 'hsl' | 'lab' | 'oklab' | 'lch' | 'oklch'; type ColorSpace = 'hex' | 'rgb' | 'hsl' | 'lab' | 'oklab' | 'lch' | 'oklch';
const actionBtn =
'flex items-center gap-1.5 px-3 py-1.5 text-xs glass rounded-md border border-border/30 text-muted-foreground hover:text-primary hover:border-primary/30 hover:bg-primary/10 transition-all disabled:opacity-40 disabled:cursor-not-allowed';
export function ExportMenu({ colors, className }: ExportMenuProps) { export function ExportMenu({ colors, className }: ExportMenuProps) {
const [format, setFormat] = useState<ExportFormat>('css'); const [format, setFormat] = useState<ExportFormat>('css');
const [colorSpace, setColorSpace] = useState<ColorSpace>('hex'); const [colorSpace, setColorSpace] = useState<ColorSpace>('hex');
@@ -39,152 +42,105 @@ export function ExportMenu({ colors, className }: ExportMenuProps) {
useEffect(() => { useEffect(() => {
async function convertColors() { async function convertColors() {
if (colorSpace === 'hex') { if (colorSpace === 'hex') { setConvertedColors(colors); return; }
setConvertedColors(colors);
return;
}
setIsConverting(true); setIsConverting(true);
try { try {
const response = await colorAPI.convertFormat({ const response = await colorAPI.convertFormat({ colors, format: colorSpace });
colors,
format: colorSpace,
});
if (response.success) { if (response.success) {
setConvertedColors(response.data.conversions.map(c => c.output)); setConvertedColors(response.data.conversions.map((c) => c.output));
} }
} catch (error) { } catch {
console.error('Failed to convert colors:', error); toast.error('Failed to convert colors');
toast.error('Failed to convert colors to selected space');
} finally { } finally {
setIsConverting(false); setIsConverting(false);
} }
} }
convertColors(); convertColors();
}, [colors, colorSpace]); }, [colors, colorSpace]);
const exportColors: ExportColor[] = convertedColors.map((value) => ({ value })); const exportColors: ExportColor[] = convertedColors.map((value) => ({ value }));
const getExportContent = (): string => { const getContent = (): string => {
switch (format) { switch (format) {
case 'css': case 'css': return exportAsCSS(exportColors);
return exportAsCSS(exportColors); case 'scss': return exportAsSCSS(exportColors);
case 'scss': case 'tailwind': return exportAsTailwind(exportColors);
return exportAsSCSS(exportColors); case 'json': return exportAsJSON(exportColors);
case 'tailwind': case 'javascript': return exportAsJavaScript(exportColors);
return exportAsTailwind(exportColors);
case 'json':
return exportAsJSON(exportColors);
case 'javascript':
return exportAsJavaScript(exportColors);
} }
}; };
const getFileExtension = (): string => { const getExt = () => ({ css: 'css', scss: 'scss', tailwind: 'js', json: 'json', javascript: 'js' }[format]);
switch (format) {
case 'css':
return 'css';
case 'scss':
return 'scss';
case 'tailwind':
return 'js';
case 'json':
return 'json';
case 'javascript':
return 'js';
}
};
const handleCopy = () => { const handleCopy = () => {
const content = getExportContent(); navigator.clipboard.writeText(getContent());
navigator.clipboard.writeText(content);
setCopied(true); setCopied(true);
toast.success('Copied to clipboard!'); toast.success('Copied!');
setTimeout(() => setCopied(false), 2000); setTimeout(() => setCopied(false), 2000);
}; };
const handleDownload = () => { const handleDownload = () => {
const content = getExportContent(); downloadAsFile(getContent(), `palette.${getExt()}`, 'text/plain');
const extension = getFileExtension();
downloadAsFile(content, `palette.${extension}`, 'text/plain');
toast.success('Downloaded!'); toast.success('Downloaded!');
}; };
if (colors.length === 0) { if (colors.length === 0) return null;
return null;
}
return ( return (
<div className={className}> <div className={cn('space-y-3', className)}>
<div className="space-y-3"> <span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">Export</span>
<div className="flex flex-col md:flex-row gap-3">
<Select {/* Selectors */}
value={format} <div className="flex gap-2">
onValueChange={(value) => setFormat(value as ExportFormat)} <Select value={format} onValueChange={(v) => setFormat(v as ExportFormat)}>
> <SelectTrigger className="flex-1 h-7 text-xs border-border/30 bg-transparent hover:border-primary/30 transition-colors">
<SelectTrigger className="w-full md:flex-1"> <SelectValue />
<SelectValue placeholder="Format" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="css">CSS Variables</SelectItem> <SelectItem value="css">CSS Vars</SelectItem>
<SelectItem value="scss">SCSS Variables</SelectItem> <SelectItem value="scss">SCSS</SelectItem>
<SelectItem value="tailwind">Tailwind Config</SelectItem> <SelectItem value="tailwind">Tailwind</SelectItem>
<SelectItem value="json">JSON</SelectItem> <SelectItem value="json">JSON</SelectItem>
<SelectItem value="javascript">JavaScript Array</SelectItem> <SelectItem value="javascript">JS Array</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<Select value={colorSpace} onValueChange={(v) => setColorSpace(v as ColorSpace)}>
<Select <SelectTrigger className="flex-1 h-7 text-xs border-border/30 bg-transparent hover:border-primary/30 transition-colors">
value={colorSpace} <SelectValue />
onValueChange={(value) => setColorSpace(value as ColorSpace)}
>
<SelectTrigger className="w-full md:flex-1">
<SelectValue placeholder="Space" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="hex">Hex</SelectItem> {['hex', 'rgb', 'hsl', 'lab', 'oklab', 'lch', 'oklch'].map((s) => (
<SelectItem value="rgb">RGB</SelectItem> <SelectItem key={s} value={s} className="font-mono text-xs">{s}</SelectItem>
<SelectItem value="hsl">HSL</SelectItem> ))}
<SelectItem value="lab">Lab</SelectItem>
<SelectItem value="oklab">OkLab</SelectItem>
<SelectItem value="lch">LCH</SelectItem>
<SelectItem value="oklch">OkLCH</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="p-3 bg-muted/50 rounded-lg relative min-h-[80px]"> {/* Code preview */}
{isConverting ? ( <div
<div className="absolute inset-0 flex items-center justify-center bg-muted/50 backdrop-blur-sm rounded-lg z-10"> className="relative rounded-xl overflow-hidden border border-white/5 min-h-[80px]"
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /> style={{ background: '#06060e' }}
>
{isConverting && (
<div className="absolute inset-0 flex items-center justify-center z-10 bg-black/30">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div> </div>
) : null} )}
<pre className="text-[11px] overflow-x-auto leading-relaxed"> <pre className="p-3 text-[10px] font-mono text-white/60 overflow-x-auto leading-relaxed">
<code>{getExportContent()}</code> <code>{getContent()}</code>
</pre> </pre>
</div> </div>
<div className="flex flex-col md:flex-row gap-3"> {/* Actions */}
<Button onClick={handleCopy} variant="outline" className="w-full md:flex-1" disabled={isConverting}> <div className="flex gap-2">
{copied ? ( <button onClick={handleCopy} disabled={isConverting} className={cn(actionBtn, 'flex-1 justify-center')}>
<> {copied ? <Check className="w-3 h-3" /> : <Copy className="w-3 h-3" />}
<Check className="h-3.5 w-3.5 mr-1.5" /> {copied ? 'Copied' : 'Copy'}
Copied </button>
</> <button onClick={handleDownload} disabled={isConverting} className={cn(actionBtn, 'flex-1 justify-center')}>
) : ( <Download className="w-3 h-3" />
<>
<Copy className="h-3.5 w-3.5 mr-1.5" />
Copy
</>
)}
</Button>
<Button onClick={handleDownload} variant="default" className="w-full md:flex-1" disabled={isConverting}>
<Download className="h-3.5 w-3.5 mr-1.5" />
Download Download
</Button> </button>
</div>
</div> </div>
</div> </div>
); );

View File

@@ -2,34 +2,25 @@
import { useState } from 'react'; import { useState } from 'react';
import { Slider } from '@/components/ui/slider'; import { Slider } from '@/components/ui/slider';
import { Button } from '@/components/ui/button';
import { import {
useLighten, useLighten,
useDarken, useDarken,
useSaturate, useSaturate,
useDesaturate, useDesaturate,
useRotate, useRotate,
useComplement useComplement,
} from '@/lib/color/api/queries'; } from '@/lib/color/api/queries';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { Sun, Moon, Droplets, Droplet, RotateCcw, ArrowLeftRight } from 'lucide-react'; import { Sun, Moon, Droplets, Droplet, RotateCcw, ArrowLeftRight } from 'lucide-react';
import { cn } from '@/lib/utils/cn';
interface ManipulationPanelProps { interface ManipulationPanelProps {
color: string; color: string;
onColorChange: (color: string) => void; onColorChange: (color: string) => void;
} }
interface ManipulationRow { const actionBtn =
label: string; 'shrink-0 px-3 py-1 text-[10px] font-mono glass rounded-md border border-border/30 text-muted-foreground hover:text-primary hover:border-primary/30 hover:bg-primary/10 transition-all disabled:opacity-40 disabled:cursor-not-allowed';
icon: React.ReactNode;
value: number;
setValue: (v: number) => void;
format: (v: number) => string;
min: number;
max: number;
step: number;
onApply: () => Promise<void>;
}
export function ManipulationPanel({ color, onColorChange }: ManipulationPanelProps) { export function ManipulationPanel({ color, onColorChange }: ManipulationPanelProps) {
const [lightenAmount, setLightenAmount] = useState(0.2); const [lightenAmount, setLightenAmount] = useState(0.2);
@@ -53,150 +44,104 @@ export function ManipulationPanel({ color, onColorChange }: ManipulationPanelPro
rotateMutation.isPending || rotateMutation.isPending ||
complementMutation.isPending; complementMutation.isPending;
const handleMutation = async ( const applyMutation = async (
mutationFn: (params: any) => Promise<any>, // eslint-disable-next-line @typescript-eslint/no-explicit-any
mutationFn: (p: any) => Promise<{ colors: { output: string }[] }>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
params: any, params: any,
successMsg: string, msg: string
errorMsg: string
) => { ) => {
try { try {
const result = await mutationFn(params); const result = await mutationFn(params);
if (result.colors[0]) { if (result.colors[0]) {
onColorChange(result.colors[0].output); onColorChange(result.colors[0].output);
toast.success(successMsg); toast.success(msg);
} }
} catch { } catch {
toast.error(errorMsg); toast.error('Failed to apply');
} }
}; };
const rows: ManipulationRow[] = [ const rows = [
{ {
label: 'Lighten', label: 'Lighten', icon: <Sun className="w-3 h-3" />,
icon: <Sun className="h-3.5 w-3.5" />, value: lightenAmount, setValue: setLightenAmount,
value: lightenAmount, display: `${(lightenAmount * 100).toFixed(0)}%`,
setValue: setLightenAmount,
format: (v) => `${(v * 100).toFixed(0)}%`,
min: 0, max: 1, step: 0.05, min: 0, max: 1, step: 0.05,
onApply: () => handleMutation( onApply: () => applyMutation(lightenMutation.mutateAsync, { colors: [color], amount: lightenAmount }, `Lightened ${(lightenAmount * 100).toFixed(0)}%`),
lightenMutation.mutateAsync,
{ colors: [color], amount: lightenAmount },
`Lightened by ${(lightenAmount * 100).toFixed(0)}%`,
'Failed to lighten color'
),
}, },
{ {
label: 'Darken', label: 'Darken', icon: <Moon className="w-3 h-3" />,
icon: <Moon className="h-3.5 w-3.5" />, value: darkenAmount, setValue: setDarkenAmount,
value: darkenAmount, display: `${(darkenAmount * 100).toFixed(0)}%`,
setValue: setDarkenAmount,
format: (v) => `${(v * 100).toFixed(0)}%`,
min: 0, max: 1, step: 0.05, min: 0, max: 1, step: 0.05,
onApply: () => handleMutation( onApply: () => applyMutation(darkenMutation.mutateAsync, { colors: [color], amount: darkenAmount }, `Darkened ${(darkenAmount * 100).toFixed(0)}%`),
darkenMutation.mutateAsync,
{ colors: [color], amount: darkenAmount },
`Darkened by ${(darkenAmount * 100).toFixed(0)}%`,
'Failed to darken color'
),
}, },
{ {
label: 'Saturate', label: 'Saturate', icon: <Droplets className="w-3 h-3" />,
icon: <Droplets className="h-3.5 w-3.5" />, value: saturateAmount, setValue: setSaturateAmount,
value: saturateAmount, display: `${(saturateAmount * 100).toFixed(0)}%`,
setValue: setSaturateAmount,
format: (v) => `${(v * 100).toFixed(0)}%`,
min: 0, max: 1, step: 0.05, min: 0, max: 1, step: 0.05,
onApply: () => handleMutation( onApply: () => applyMutation(saturateMutation.mutateAsync, { colors: [color], amount: saturateAmount }, `Saturated ${(saturateAmount * 100).toFixed(0)}%`),
saturateMutation.mutateAsync,
{ colors: [color], amount: saturateAmount },
`Saturated by ${(saturateAmount * 100).toFixed(0)}%`,
'Failed to saturate color'
),
}, },
{ {
label: 'Desaturate', label: 'Desaturate', icon: <Droplet className="w-3 h-3" />,
icon: <Droplet className="h-3.5 w-3.5" />, value: desaturateAmount, setValue: setDesaturateAmount,
value: desaturateAmount, display: `${(desaturateAmount * 100).toFixed(0)}%`,
setValue: setDesaturateAmount,
format: (v) => `${(v * 100).toFixed(0)}%`,
min: 0, max: 1, step: 0.05, min: 0, max: 1, step: 0.05,
onApply: () => handleMutation( onApply: () => applyMutation(desaturateMutation.mutateAsync, { colors: [color], amount: desaturateAmount }, `Desaturated ${(desaturateAmount * 100).toFixed(0)}%`),
desaturateMutation.mutateAsync,
{ colors: [color], amount: desaturateAmount },
`Desaturated by ${(desaturateAmount * 100).toFixed(0)}%`,
'Failed to desaturate color'
),
}, },
{ {
label: 'Rotate', label: 'Rotate Hue', icon: <RotateCcw className="w-3 h-3" />,
icon: <RotateCcw className="h-3.5 w-3.5" />, value: rotateAmount, setValue: setRotateAmount,
value: rotateAmount, display: `${rotateAmount}°`,
setValue: setRotateAmount,
format: (v) => `${v}°`,
min: -180, max: 180, step: 5, min: -180, max: 180, step: 5,
onApply: () => handleMutation( onApply: () => applyMutation(rotateMutation.mutateAsync, { colors: [color], amount: rotateAmount }, `Rotated ${rotateAmount}°`),
rotateMutation.mutateAsync,
{ colors: [color], amount: rotateAmount },
`Rotated hue by ${rotateAmount}°`,
'Failed to rotate hue'
),
}, },
]; ];
const handleComplement = async () => {
try {
const result = await complementMutation.mutateAsync([color]);
if (result.colors[0]) {
onColorChange(result.colors[0].output);
toast.success('Generated complementary color');
}
} catch {
toast.error('Failed to generate complement');
}
};
return ( return (
<div className="space-y-4"> <div className="space-y-4">
{rows.map((row) => ( {rows.map((row) => (
<div key={row.label} className="space-y-2"> <div key={row.label} className="space-y-1.5">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-1.5 text-xs font-medium"> <div className="flex items-center gap-1.5 text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
{row.icon} {row.icon}
<span>{row.label}</span> <span>{row.label}</span>
</div> </div>
<span className="text-[10px] text-muted-foreground tabular-nums">{row.format(row.value)}</span> <span className="text-[10px] text-muted-foreground/40 font-mono tabular-nums">{row.display}</span>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Slider <Slider
min={row.min} min={row.min} max={row.max} step={row.step}
max={row.max}
step={row.step}
value={[row.value]} value={[row.value]}
onValueChange={(vals) => row.setValue(vals[0])} onValueChange={(vals) => row.setValue(vals[0])}
className="flex-1" className="flex-1"
/> />
<Button <button onClick={row.onApply} disabled={isLoading} className={actionBtn}>
onClick={row.onApply}
disabled={isLoading}
variant="outline"
className="shrink-0 w-16"
>
Apply Apply
</Button> </button>
</div> </div>
</div> </div>
))} ))}
<div className="pt-3 border-t"> <div className="pt-3 border-t border-border/25">
<Button <button
onClick={handleComplement} onClick={async () => {
try {
const result = await complementMutation.mutateAsync([color]);
if (result.colors[0]) {
onColorChange(result.colors[0].output);
toast.success('Complementary color applied');
}
} catch { toast.error('Failed'); }
}}
disabled={isLoading} disabled={isLoading}
variant="outline" className={cn(actionBtn, 'w-full justify-center flex items-center gap-1.5 py-2')}
className="w-full"
> >
<ArrowLeftRight className="h-3.5 w-3.5 mr-1.5" /> <ArrowLeftRight className="w-3 h-3" />
Complementary Color Complementary Color
</Button> </button>
</div> </div>
</div> </div>
); );

View File

@@ -19,16 +19,12 @@ export function PaletteGrid({ colors, onColorClick, className }: PaletteGridProp
} }
return ( return (
<div <div className={cn('grid grid-cols-4 sm:grid-cols-5 gap-2', className)}>
className={cn(
'grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-4',
className
)}
>
{colors.map((color, index) => ( {colors.map((color, index) => (
<ColorSwatch <ColorSwatch
key={`${color}-${index}`} key={`${color}-${index}`}
color={color} color={color}
size="sm"
onClick={onColorClick ? () => onColorClick(color) : undefined} onClick={onColorClick ? () => onColorClick(color) : undefined}
/> />
))} ))}