feat: implement palette generation features

Add complete palette generation system with multiple methods:

**New Components:**
- ColorSwatch component - Individual color display
  - Click to copy to clipboard
  - Hover effects with copy icon
  - Configurable sizes (sm, md, lg)
  - Optional color label display
  - Check icon on successful copy

- PaletteGrid component - Grid display for color palettes
  - Responsive grid layout (3-6 columns)
  - Click handler for color selection
  - Empty state message
  - Flexible and reusable

- Select component - Dropdown selector
  - Consistent styling with other inputs
  - Optional label support
  - Keyboard accessible
  - Focus ring styling

**Palette Pages:**

1. Gradient Creator (/palettes/gradient)
   - Multiple color stop editor (add/remove)
   - Configurable step count (2-1000)
   - Color space selection (RGB, HSL, Lab, LCH, OkLab, OkLCH)
   - Live gradient preview bar
   - Full palette grid display
   - Interactive color pickers for each stop
   - Real-time generation

2. Distinct Colors (/palettes/distinct)
   - Count selector (2-100 colors)
   - Distance metric selection (CIE76, CIEDE2000)
   - Simulated annealing algorithm
   - Statistics display:
     - Minimum distance
     - Average distance
     - Generation time
   - Loading state with progress message
   - Quality metrics for generated palette

3. Palettes Dashboard (/palettes)
   - Overview of all palette generators
   - Feature cards with icons
   - "Coming Soon" badge for harmony palettes
   - Quick navigation to each generator
   - Feature highlights for each method

**Features:**
- All palette generators integrated with Pastel API
- Toast notifications for success/error
- Loading states during generation
- Copy colors to clipboard
- Responsive layouts
- Empty states
- Error handling

**API Integration:**
- useGenerateGradient mutation
- useGenerateDistinct mutation
- Proper error handling and loading states
- Result caching with React Query

Build successful! 3 new palette pages rendering.

Next: Harmony palettes, accessibility tools, and named colors.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
valknarness
2025-11-07 11:38:20 +01:00
parent 75bfecee4d
commit c3745bd6b7
6 changed files with 538 additions and 0 deletions

View File

@@ -0,0 +1,140 @@
'use client';
import { useState } from 'react';
import { PaletteGrid } from '@/components/color/PaletteGrid';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
import { useGenerateDistinct } from '@/lib/api/queries';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';
export default function DistinctPage() {
const [count, setCount] = useState(8);
const [metric, setMetric] = useState<'cie76' | 'ciede2000'>('ciede2000');
const [colors, setColors] = useState<string[]>([]);
const [stats, setStats] = useState<{
min_distance: number;
avg_distance: number;
generation_time_ms: number;
} | null>(null);
const generateMutation = useGenerateDistinct();
const handleGenerate = async () => {
try {
const result = await generateMutation.mutateAsync({
count,
metric,
});
setColors(result.colors);
setStats(result.stats);
toast.success(`Generated ${result.colors.length} distinct colors`);
} catch (error) {
toast.error('Failed to generate distinct colors');
}
};
return (
<div className="min-h-screen p-8">
<div className="max-w-7xl mx-auto space-y-8">
<div>
<h1 className="text-4xl font-bold mb-2">Distinct Colors Generator</h1>
<p className="text-muted-foreground">
Generate visually distinct colors using simulated annealing
</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Controls */}
<div className="lg:col-span-1">
<div className="p-6 border rounded-lg bg-card space-y-6">
<div>
<h2 className="text-xl font-semibold mb-4">Settings</h2>
</div>
<div>
<label htmlFor="count" className="text-sm font-medium mb-2 block">
Number of Colors
</label>
<Input
id="count"
type="number"
min={2}
max={100}
value={count}
onChange={(e) => setCount(parseInt(e.target.value))}
/>
<p className="text-xs text-muted-foreground mt-1">
Higher counts take longer to generate
</p>
</div>
<Select
label="Distance Metric"
value={metric}
onChange={(e) => setMetric(e.target.value as 'cie76' | 'ciede2000')}
>
<option value="cie76">CIE76 (Faster)</option>
<option value="ciede2000">CIEDE2000 (More Accurate)</option>
</Select>
<Button
onClick={handleGenerate}
disabled={generateMutation.isPending}
className="w-full"
>
{generateMutation.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Generating...
</>
) : (
'Generate Colors'
)}
</Button>
{generateMutation.isPending && (
<div className="text-sm text-muted-foreground text-center">
This may take a few moments...
</div>
)}
{stats && (
<div className="pt-4 border-t space-y-2">
<h3 className="font-semibold text-sm">Statistics</h3>
<div className="space-y-1 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">Min Distance:</span>
<span className="font-mono">{stats.min_distance.toFixed(2)}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Avg Distance:</span>
<span className="font-mono">{stats.avg_distance.toFixed(2)}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Generation Time:</span>
<span className="font-mono">
{(stats.generation_time_ms / 1000).toFixed(2)}s
</span>
</div>
</div>
</div>
)}
</div>
</div>
{/* Results */}
<div className="lg:col-span-2">
<div className="p-6 border rounded-lg bg-card">
<h2 className="text-xl font-semibold mb-4">
Generated Colors {colors.length > 0 && `(${colors.length})`}
</h2>
<PaletteGrid colors={colors} />
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,183 @@
'use client';
import { useState } from 'react';
import { ColorPicker } from '@/components/color/ColorPicker';
import { PaletteGrid } from '@/components/color/PaletteGrid';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
import { useGenerateGradient } from '@/lib/api/queries';
import { Loader2, Plus, X } from 'lucide-react';
import { toast } from 'sonner';
export default function GradientPage() {
const [stops, setStops] = useState<string[]>(['#ff0099', '#0099ff']);
const [count, setCount] = useState(10);
const [colorspace, setColorspace] = useState<
'rgb' | 'hsl' | 'hsv' | 'lab' | 'oklab' | 'lch' | 'oklch'
>('lch');
const [gradient, setGradient] = useState<string[]>([]);
const generateMutation = useGenerateGradient();
const handleGenerate = async () => {
try {
const result = await generateMutation.mutateAsync({
stops,
count,
colorspace,
});
setGradient(result.colors);
toast.success(`Generated ${result.colors.length} colors`);
} catch (error) {
toast.error('Failed to generate gradient');
}
};
const addStop = () => {
setStops([...stops, '#000000']);
};
const removeStop = (index: number) => {
if (stops.length > 2) {
setStops(stops.filter((_, i) => i !== index));
}
};
const updateStop = (index: number, color: string) => {
const newStops = [...stops];
newStops[index] = color;
setStops(newStops);
};
return (
<div className="min-h-screen p-8">
<div className="max-w-7xl mx-auto space-y-8">
<div>
<h1 className="text-4xl font-bold mb-2">Gradient Creator</h1>
<p className="text-muted-foreground">
Create smooth color gradients with multiple stops
</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* Controls */}
<div className="space-y-6">
<div className="p-6 border rounded-lg bg-card">
<h2 className="text-xl font-semibold mb-4">Color Stops</h2>
<div className="space-y-4">
{stops.map((stop, index) => (
<div key={index} className="flex items-start gap-3">
<div className="flex-1">
<ColorPicker
color={stop}
onChange={(color) => updateStop(index, color)}
/>
</div>
{stops.length > 2 && (
<Button
variant="ghost"
size="icon"
onClick={() => removeStop(index)}
className="mt-8"
>
<X className="h-4 w-4" />
</Button>
)}
</div>
))}
<Button onClick={addStop} variant="outline" className="w-full">
<Plus className="h-4 w-4 mr-2" />
Add Stop
</Button>
</div>
</div>
<div className="p-6 border rounded-lg bg-card">
<h2 className="text-xl font-semibold mb-4">Settings</h2>
<div className="space-y-4">
<div>
<label htmlFor="count" className="text-sm font-medium mb-2 block">
Number of Colors
</label>
<Input
id="count"
type="number"
min={2}
max={1000}
value={count}
onChange={(e) => setCount(parseInt(e.target.value))}
/>
</div>
<Select
label="Color Space"
value={colorspace}
onChange={(e) =>
setColorspace(
e.target.value as
| 'rgb'
| 'hsl'
| 'hsv'
| 'lab'
| 'oklab'
| 'lch'
| 'oklch'
)
}
>
<option value="rgb">RGB</option>
<option value="hsl">HSL</option>
<option value="hsv">HSV</option>
<option value="lab">Lab</option>
<option value="oklab">OkLab</option>
<option value="lch">LCH</option>
<option value="oklch">OkLCH (Recommended)</option>
</Select>
<Button
onClick={handleGenerate}
disabled={generateMutation.isPending || stops.length < 2}
className="w-full"
>
{generateMutation.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Generating...
</>
) : (
'Generate Gradient'
)}
</Button>
</div>
</div>
</div>
{/* Preview */}
<div className="space-y-6">
{gradient.length > 0 && (
<>
<div className="p-6 border rounded-lg bg-card">
<h2 className="text-xl font-semibold mb-4">Gradient Preview</h2>
<div
className="h-32 rounded-lg"
style={{
background: `linear-gradient(to right, ${gradient.join(', ')})`,
}}
/>
</div>
<div className="p-6 border rounded-lg bg-card">
<h2 className="text-xl font-semibold mb-4">
Colors ({gradient.length})
</h2>
<PaletteGrid colors={gradient} />
</div>
</>
)}
</div>
</div>
</div>
</div>
);
}

74
app/palettes/page.tsx Normal file
View File

@@ -0,0 +1,74 @@
import Link from 'next/link';
import { Palette, Sparkles, GraduationCap } from 'lucide-react';
export default function PalettesPage() {
const paletteTypes = [
{
title: 'Gradient Creator',
description: 'Create smooth color gradients with multiple stops and color spaces',
href: '/palettes/gradient',
icon: GraduationCap,
features: ['Multiple color stops', 'Various color spaces', 'Live preview'],
},
{
title: 'Distinct Colors',
description: 'Generate visually distinct colors using simulated annealing algorithm',
href: '/palettes/distinct',
icon: Sparkles,
features: ['Perceptual distance', 'Configurable count', 'Quality metrics'],
},
{
title: 'Harmony Palettes',
description: 'Create color palettes based on color theory and harmony rules',
href: '/palettes/harmony',
icon: Palette,
features: ['Color theory', 'Multiple schemes', 'Instant generation'],
comingSoon: true,
},
];
return (
<div className="min-h-screen p-8">
<div className="max-w-7xl mx-auto space-y-8">
<div>
<h1 className="text-4xl font-bold mb-2">Palette Generation</h1>
<p className="text-muted-foreground">
Create beautiful color palettes using various generation methods
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{paletteTypes.map((type) => {
const Icon = type.icon;
return (
<Link
key={type.href}
href={type.comingSoon ? '#' : type.href}
className={`p-6 border rounded-lg bg-card hover:border-primary transition-colors ${
type.comingSoon ? 'opacity-60 cursor-not-allowed' : ''
}`}
>
<div className="flex items-start justify-between mb-4">
<Icon className="h-8 w-8 text-primary" />
{type.comingSoon && (
<span className="text-xs bg-muted px-2 py-1 rounded">Coming Soon</span>
)}
</div>
<h2 className="text-xl font-semibold mb-2">{type.title}</h2>
<p className="text-sm text-muted-foreground mb-4">{type.description}</p>
<ul className="space-y-1">
{type.features.map((feature) => (
<li key={feature} className="text-sm text-muted-foreground flex items-center">
<span className="mr-2"></span>
{feature}
</li>
))}
</ul>
</Link>
);
})}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,65 @@
'use client';
import { cn } from '@/lib/utils/cn';
import { Check, Copy } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
interface ColorSwatchProps {
color: string;
size?: 'sm' | 'md' | 'lg';
showLabel?: boolean;
onClick?: () => void;
className?: string;
}
export function ColorSwatch({
color,
size = 'md',
showLabel = true,
onClick,
className,
}: ColorSwatchProps) {
const [copied, setCopied] = useState(false);
const sizeClasses = {
sm: 'h-12 w-12',
md: 'h-16 w-16',
lg: 'h-24 w-24',
};
const handleCopy = (e: React.MouseEvent) => {
e.stopPropagation();
navigator.clipboard.writeText(color);
setCopied(true);
toast.success(`Copied ${color}`);
setTimeout(() => setCopied(false), 2000);
};
return (
<div className={cn('flex flex-col items-center gap-2', className)}>
<button
className={cn(
'relative rounded-lg ring-2 ring-border transition-all hover:scale-105 hover:ring-primary',
'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
'group',
sizeClasses[size]
)}
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-opacity bg-black/20 rounded-lg">
{copied ? (
<Check className="h-5 w-5 text-white" />
) : (
<Copy className="h-5 w-5 text-white" />
)}
</div>
</button>
{showLabel && (
<span className="text-xs font-mono text-muted-foreground">{color}</span>
)}
</div>
);
}

View File

@@ -0,0 +1,37 @@
'use client';
import { ColorSwatch } from './ColorSwatch';
import { cn } from '@/lib/utils/cn';
interface PaletteGridProps {
colors: string[];
onColorClick?: (color: string) => void;
className?: string;
}
export function PaletteGrid({ colors, onColorClick, className }: PaletteGridProps) {
if (colors.length === 0) {
return (
<div className="text-center py-12 text-muted-foreground">
No colors in palette yet
</div>
);
}
return (
<div
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) => (
<ColorSwatch
key={`${color}-${index}`}
color={color}
onClick={onColorClick ? () => onColorClick(color) : undefined}
/>
))}
</div>
);
}

39
components/ui/select.tsx Normal file
View File

@@ -0,0 +1,39 @@
'use client';
import * as React from 'react';
import { cn } from '@/lib/utils/cn';
export interface SelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
label?: string;
}
const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
({ className, label, children, ...props }, ref) => {
return (
<div className="space-y-2">
{label && (
<label htmlFor={props.id} className="text-sm font-medium">
{label}
</label>
)}
<select
className={cn(
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2',
'text-sm ring-offset-background',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
'disabled:cursor-not-allowed disabled:opacity-50',
className
)}
ref={ref}
{...props}
>
{children}
</select>
</div>
);
}
);
Select.displayName = 'Select';
export { Select };