OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat(image): add Photoshop-style selection system, adjustments, and masks
Augustus Otudc43e9d59c2c
diff --git a/apps/image/PHOTOSHOP_FEATURE_PLAN.md b/apps/image/PHOTOSHOP_FEATURE_PLAN.mdnew file mode 100644index 00000000..cbbf0e5b--- /dev/null+++ b/apps/image/PHOTOSHOP_FEATURE_PLAN.md@@ -0,0 +1,942 @@+# OpenReel Image - Photoshop Feature Implementation Plan++## Executive Summary++This document outlines a comprehensive plan to implement Photoshop-equivalent features in OpenReel Image. Based on detailed research of Photoshop's feature set and audit of current OpenReel capabilities, this plan prioritizes features by impact and complexity.++---++## Current State vs Photoshop Comparison++### Layer System++| Feature | Photoshop | OpenReel | Gap |+|---------|-----------|----------|-----|+| Pixel Layers | ✓ | ✓ (image) | - |+| Adjustment Layers | 16+ types | 11 types | 5+ missing |+| Fill Layers | Solid, Gradient, Pattern | Partial | Pattern fill |+| Shape Layers | ✓ | ✓ | - |+| Text Layers | ✓ | ✓ | - |+| Smart Objects | Full | Basic | Non-destructive editing |+| 3D Layers | ✓ | ✗ | Full feature |+| Video Layers | ✓ | ✗ | Full feature |++### Blend Modes++| Category | Photoshop | OpenReel | Missing |+|----------|-----------|----------|---------|+| Normal | Normal, Dissolve | Normal | Dissolve |+| Darken | 5 modes | 3 modes | Linear Burn, Darker Color |+| Lighten | 5 modes | 3 modes | Linear Dodge, Lighter Color |+| Contrast | 8 modes | 3 modes | Vivid/Linear/Pin Light, Hard Mix |+| Comparative | 4 modes | 3 modes | Divide |+| Component | 4 modes | 4 modes | - |+| **Total** | **27+** | **12** | **15+** |++### Selection Tools++| Tool | Photoshop | OpenReel | Priority |+|------|-----------|----------|----------|+| Rectangular Marquee | ✓ | ✓ (basic) | Enhance |+| Elliptical Marquee | ✓ | ✗ | High |+| Lasso (Free) | ✓ | ✗ | High |+| Polygonal Lasso | ✓ | ✗ | High |+| Magnetic Lasso | ✓ | ✗ | Medium |+| Magic Wand | ✓ | ✗ | High |+| Quick Selection | ✓ | ✗ | Medium |+| Object Selection | ✓ | ✗ | Medium |+| Select Subject (AI) | ✓ | ✓ (BG removal) | Partial |+| Color Range | ✓ | ✗ | Medium |++### Brush & Paint Tools++| Tool | Photoshop | OpenReel | Priority |+|------|-----------|----------|----------|+| Brush Tool | Full dynamics | Basic pen | Enhance |+| Pencil Tool | ✓ | ✗ | Medium |+| Eraser Tool | ✓ | ✗ | High |+| Clone Stamp | ✓ | ✗ | High |+| Healing Brush | ✓ | ✗ | High |+| Spot Healing | ✓ | ✗ | High |+| Patch Tool | ✓ | ✗ | Medium |+| Content-Aware Fill | ✓ | ✗ | High (AI) |+| Red Eye Tool | ✓ | ✗ | Low |++### Retouching Tools++| Tool | Photoshop | OpenReel | Priority |+|------|-----------|----------|----------|+| Dodge (Lighten) | ✓ | ✗ | High |+| Burn (Darken) | ✓ | ✗ | High |+| Sponge (Saturation) | ✓ | ✗ | Medium |+| Blur Brush | ✓ | ✗ | Medium |+| Sharpen Brush | ✓ | ✗ | Medium |+| Smudge Tool | ✓ | ✗ | Medium |++### Transform Tools++| Tool | Photoshop | OpenReel | Priority |+|------|-----------|----------|----------|+| Free Transform | ✓ | ✓ | - |+| Warp | ✓ | ✗ | High |+| Perspective | ✓ | ✗ | High |+| Puppet Warp | ✓ | ✗ | Low |+| Content-Aware Scale | ✓ | ✗ | Medium |+| Liquify | ✓ | ✗ | Medium |++### Layer Effects/Styles++| Effect | Photoshop | OpenReel | Priority |+|--------|-----------|----------|----------|+| Drop Shadow | Full | Basic | Enhance (spread, contour) |+| Inner Shadow | Full | Basic | Enhance (contour) |+| Outer Glow | Full | Basic | Enhance (contour, spread) |+| Inner Glow | ✓ | ✗ | High |+| Bevel & Emboss | ✓ | ✗ | High |+| Satin | ✓ | ✗ | Medium |+| Color Overlay | ✓ | ✗ | High |+| Gradient Overlay | ✓ | ✗ | High |+| Pattern Overlay | ✓ | ✗ | Medium |+| Stroke | Full | Basic | Enhance (position, gradient) |++### Filters++| Category | Photoshop | OpenReel | Gap |+|----------|-----------|----------|-----|+| Blur | 14+ types | 3 types | 11+ |+| Sharpen | 4 types | 1 type | 3 |+| Noise | 5 types | 1 type | 4 |+| Distort | 12+ types | 0 | All |+| Stylize | 8+ types | 0 | All |+| Render | 8+ types | 0 | All |+| Neural/AI | 10+ types | 1 (BG remove) | 9+ |++### Adjustments++| Adjustment | Photoshop | OpenReel | Priority |+|------------|-----------|----------|----------|+| Brightness/Contrast | ✓ | ✓ | - |+| Levels | ✓ | ✗ | Critical |+| Curves | ✓ | ✗ | Critical |+| Exposure | ✓ | ✓ | - |+| Vibrance | ✓ | ✓ | - |+| Hue/Saturation | ✓ | ✓ | - |+| Color Balance | ✓ | ✗ | High |+| Black & White | ✓ | ✗ | High |+| Photo Filter | ✓ | ✗ | Medium |+| Channel Mixer | ✓ | ✗ | Medium |+| Color Lookup (LUT) | ✓ | ✗ | High |+| Invert | ✓ | ✓ | - |+| Posterize | ✓ | ✗ | Medium |+| Threshold | ✓ | ✗ | Medium |+| Gradient Map | ✓ | ✗ | Medium |+| Selective Color | ✓ | ✗ | High |++### Masks++| Mask Type | Photoshop | OpenReel | Priority |+|-----------|-----------|----------|----------|+| Pixel Masks | ✓ | ✗ | Critical |+| Vector Masks | ✓ | ✗ | High |+| Clipping Masks | ✓ | ✗ | High |+| Quick Mask | ✓ | ✗ | Medium |++### Text Features++| Feature | Photoshop | OpenReel | Priority |+|---------|-----------|----------|----------|+| Basic Formatting | ✓ | ✓ | - |+| Paragraph Styles | ✓ | ✓ | - |+| OpenType Features | ✓ | ✗ | Medium |+| Variable Fonts | ✓ | ✗ | Low |+| Text on Path | ✓ | ✗ | High |+| Text in Shape | ✓ | ✗ | Medium |+| Warp Text | ✓ | ✗ | High |++### History & Actions++| Feature | Photoshop | OpenReel | Priority |+|---------|-----------|----------|----------|+| History Panel | ✓ | Basic undo | Enhance |+| History Brush | ✓ | ✗ | Medium |+| Snapshots | ✓ | ✗ | Medium |+| Actions | ✓ | ✗ | High |+| Batch Processing | ✓ | ✗ | Medium |++---++## Implementation Phases++### Phase 1: Critical Foundation (Core Editing)++**Priority: CRITICAL | Effort: Large**++#### 1.1 Selection System+```typescript+interface Selection {+ id: string;+ type: 'rectangular' | 'elliptical' | 'lasso' | 'polygonal' | 'magic-wand' | 'color-range';+ path: Path2D | null;+ bounds: BoundingBox;+ feather: number;+ antiAlias: boolean;+ marching: boolean; // marching ants animation+}++interface SelectionStore {+ activeSelection: Selection | null;+ savedSelections: Selection[];+ selectionMode: 'new' | 'add' | 'subtract' | 'intersect';+}+```++**Tools to implement:**+- Rectangular Marquee with feather, anti-alias+- Elliptical Marquee+- Lasso (freehand)+- Polygonal Lasso+- Magic Wand (tolerance-based color selection)++#### 1.2 Layer Masks+```typescript+interface LayerMask {+ id: string;+ type: 'pixel' | 'vector';+ data: ImageData | Path2D;+ enabled: boolean;+ linked: boolean; // linked to layer transform+ density: number; // 0-100%+ feather: number;+}++interface Layer {+ // ... existing+ mask: LayerMask | null;+ clippingMask: boolean; // clips to layer below+}+```++#### 1.3 Levels & Curves Adjustments+```typescript+interface LevelsAdjustment {+ channel: 'rgb' | 'red' | 'green' | 'blue';+ inputBlack: number; // 0-255+ inputWhite: number; // 0-255+ gamma: number; // 0.1-10+ outputBlack: number; // 0-255+ outputWhite: number; // 0-255+}++interface CurvesAdjustment {+ channel: 'rgb' | 'red' | 'green' | 'blue';+ points: Array<{ input: number; output: number }>; // up to 14 points+}+```++#### 1.4 History System Enhancement+```typescript+interface HistoryState {+ id: string;+ name: string;+ timestamp: number;+ snapshot: ProjectSnapshot;+ thumbnail?: string;+}++interface HistoryStore {+ states: HistoryState[];+ currentIndex: number;+ maxStates: number; // default 50+ snapshots: Map<string, HistoryState>; // named snapshots+}+```++---++### Phase 2: Essential Tools (Retouching & Paint)++**Priority: HIGH | Effort: Large**++#### 2.1 Brush Engine Enhancement+```typescript+interface BrushSettings {+ size: number;+ hardness: number; // 0-100%+ opacity: number; // 0-100%+ flow: number; // 0-100%+ spacing: number; // 1-1000%+ angle: number;+ roundness: number; // 0-100%++ // Dynamics+ sizeDynamics: BrushDynamics;+ opacityDynamics: BrushDynamics;+ flowDynamics: BrushDynamics;++ // Shape+ tip: 'round' | 'square' | 'custom';+ customTip?: ImageData;++ // Transfer+ buildUp: boolean;+ smoothing: number; // 0-100%+}++interface BrushDynamics {+ control: 'off' | 'fade' | 'pen-pressure' | 'pen-tilt' | 'rotation';+ minValue: number;+ jitter: number;+}+```++#### 2.2 Clone Stamp & Healing+```typescript+interface CloneStampTool {+ sourcePoint: { x: number; y: number } | null;+ sourceLayer: string | null;+ aligned: boolean;+ sampleMode: 'current' | 'current-below' | 'all';+ blendMode: BlendMode;+ opacity: number;+}++interface HealingBrushTool extends CloneStampTool {+ healingMode: 'normal' | 'content-aware' | 'proximity';+ diffusion: number; // for high-frequency areas+}++interface SpotHealingTool {+ type: 'proximity-match' | 'content-aware' | 'create-texture';+ sampleAllLayers: boolean;+}+```++#### 2.3 Eraser Tool+```typescript+interface EraserTool {+ mode: 'brush' | 'pencil' | 'block';+ size: number;+ hardness: number;+ opacity: number;+ flow: number;+ eraseToHistory: boolean; // restore from history state+}+```++#### 2.4 Dodge, Burn, Sponge+```typescript+interface DodgeBurnTool {+ type: 'dodge' | 'burn';+ range: 'shadows' | 'midtones' | 'highlights';+ exposure: number; // 0-100%+ protectTones: boolean;+}++interface SpongeTool {+ mode: 'saturate' | 'desaturate';+ flow: number; // 0-100%+ vibrance: boolean; // protect skin tones+}+```++---++### Phase 3: Advanced Effects & Filters++**Priority: HIGH | Effort: Medium-Large**++#### 3.1 Additional Blend Modes+```typescript+type BlendMode =+ // Existing+ | 'normal' | 'multiply' | 'screen' | 'overlay'+ | 'darken' | 'lighten' | 'color-dodge' | 'color-burn'+ | 'hard-light' | 'soft-light' | 'difference' | 'exclusion'++ // New - Darken Group+ | 'linear-burn' | 'darker-color'++ // New - Lighten Group+ | 'linear-dodge' | 'lighter-color'++ // New - Contrast Group+ | 'vivid-light' | 'linear-light' | 'pin-light' | 'hard-mix'++ // New - Other+ | 'dissolve' | 'divide';+```++#### 3.2 Layer Style Enhancements+```typescript+interface DropShadow {+ enabled: boolean;+ blendMode: BlendMode;+ color: string;+ opacity: number;+ angle: number;+ distance: number;+ spread: number; // NEW: 0-100%+ size: number;+ contour: ContourCurve; // NEW: custom curve+ antiAlias: boolean;+ noise: number;+ layerKnockout: boolean;+}++interface BevelEmboss {+ enabled: boolean;+ style: 'outer-bevel' | 'inner-bevel' | 'emboss' | 'pillow-emboss' | 'stroke-emboss';+ technique: 'smooth' | 'chisel-hard' | 'chisel-soft';+ depth: number;+ direction: 'up' | 'down';+ size: number;+ soften: number;++ // Shading+ angle: number;+ altitude: number;+ highlightMode: BlendMode;+ highlightColor: string;+ highlightOpacity: number;+ shadowMode: BlendMode;+ shadowColor: string;+ shadowOpacity: number;++ // Contour+ gloss: ContourCurve;+ contour: ContourCurve;+ antiAlias: boolean;+}++interface InnerGlow {+ enabled: boolean;+ blendMode: BlendMode;+ opacity: number;+ noise: number;+ color: string | GradientDef;+ technique: 'softer' | 'precise';+ source: 'center' | 'edge';+ choke: number;+ size: number;+ contour: ContourCurve;+ antiAlias: boolean;+ range: number;+ jitter: number;+}++interface ColorOverlay {+ enabled: boolean;+ blendMode: BlendMode;+ color: string;+ opacity: number;+}++interface GradientOverlay {+ enabled: boolean;+ blendMode: BlendMode;+ opacity: number;+ gradient: GradientDef;+ style: 'linear' | 'radial' | 'angle' | 'reflected' | 'diamond';+ alignWithLayer: boolean;+ angle: number;+ scale: number;+ reverse: boolean;+ dither: boolean;+}++interface PatternOverlay {+ enabled: boolean;+ blendMode: BlendMode;+ opacity: number;+ pattern: PatternDef;+ scale: number;+ linkWithLayer: boolean;+}++interface Satin {+ enabled: boolean;+ blendMode: BlendMode;+ color: string;+ opacity: number;+ angle: number;+ distance: number;+ size: number;+ contour: ContourCurve;+ antiAlias: boolean;+ invert: boolean;+}+```++#### 3.3 Filter System+```typescript+// Blur Filters+interface GaussianBlur { radius: number; }+interface MotionBlur { angle: number; distance: number; }+interface RadialBlur { amount: number; method: 'spin' | 'zoom'; quality: 'draft' | 'better' | 'best'; center: Point; }+interface LensBlur { radius: number; irisShape: number; irisRotation: number; iriscurvature: number; highlight: { brightness: number; threshold: number; }; }+interface SurfaceBlur { radius: number; threshold: number; }+interface TiltShift { blur: number; focusLine: { start: Point; end: Point }; transition: number; }++// Sharpen Filters+interface UnsharpMask { amount: number; radius: number; threshold: number; }+interface SmartSharpen { amount: number; radius: number; removeBlur: 'gaussian' | 'lens' | 'motion'; noiseReduction: number; }+interface HighPass { radius: number; } // Applied with overlay blend mode++// Distort Filters+interface Spherize { amount: number; mode: 'normal' | 'horizontal' | 'vertical'; }+interface Pinch { amount: number; }+interface Twirl { angle: number; }+interface Wave { generators: number; wavelength: { min: number; max: number }; amplitude: { min: number; max: number }; scale: { x: number; y: number }; type: 'sine' | 'triangle' | 'square'; }+interface Ripple { amount: number; size: 'small' | 'medium' | 'large'; }+interface ZigZag { amount: number; ridges: number; style: 'around-center' | 'out-from-center' | 'pond-ripples'; }+interface PolarCoordinates { mode: 'rectangular-to-polar' | 'polar-to-rectangular'; }++// Noise Filters+interface AddNoise { amount: number; distribution: 'uniform' | 'gaussian'; monochromatic: boolean; }+interface ReduceNoise { strength: number; preserveDetails: number; reduceColorNoise: number; sharpenDetails: number; }+interface DustScratches { radius: number; threshold: number; }+interface Median { radius: number; }++// Stylize Filters+interface OilPaint { stylization: number; cleanliness: number; scale: number; bristleDetail: number; angularDirection: number; }+interface Emboss { angle: number; height: number; amount: number; }+interface FindEdges { /* no params */ }+interface Wind { method: 'wind' | 'blast' | 'stagger'; direction: 'left' | 'right'; }++// Render Filters+interface Clouds { /* uses foreground/background colors */ }+interface DifferenceClouds { /* blends with existing content */ }+interface Fibers { variance: number; strength: number; }+interface LensFlare { brightness: number; flareCenter: Point; lensType: '50-300mm-zoom' | '35mm-prime' | '105mm-prime' | 'movie-prime'; }+```++#### 3.4 Liquify Tool+```typescript+interface LiquifySettings {+ brushSize: number;+ brushDensity: number;+ brushPressure: number;+ brushRate: number;++ // Face-Aware+ faceAware: boolean;+ faceControls?: {+ eyeSize: number;+ eyeHeight: number;+ eyeWidth: number;+ eyeTilt: number;+ eyeDistance: number;+ noseHeight: number;+ noseWidth: number;+ mouthSmile: number;+ mouthHeight: number;+ mouthWidth: number;+ jawline: number;+ faceWidth: number;+ forehead: number;+ chinHeight: number;+ };+}++type LiquifyTool =+ | 'warp' // Forward Warp+ | 'reconstruct' // Restore+ | 'smooth' // Smooth+ | 'twirl-cw' // Twirl Clockwise+ | 'twirl-ccw' // Twirl Counter-Clockwise+ | 'pucker' // Contract+ | 'bloat' // Expand+ | 'push-left' // Shift Pixels+ | 'freeze' // Protect area+ | 'thaw'; // Unprotect area+```++---++### Phase 4: Color & Adjustments++**Priority: HIGH | Effort: Medium**++#### 4.1 Advanced Adjustments+```typescript+interface ColorBalance {+ shadows: { cyan_red: number; magenta_green: number; yellow_blue: number };+ midtones: { cyan_red: number; magenta_green: number; yellow_blue: number };+ highlights: { cyan_red: number; magenta_green: number; yellow_blue: number };+ preserveLuminosity: boolean;+}++interface SelectiveColor {+ colors: 'reds' | 'yellows' | 'greens' | 'cyans' | 'blues' | 'magentas' | 'whites' | 'neutrals' | 'blacks';+ cyan: number; // -100 to +100+ magenta: number;+ yellow: number;+ black: number;+ method: 'relative' | 'absolute';+}++interface BlackWhite {+ reds: number;+ yellows: number;+ greens: number;+ cyans: number;+ blues: number;+ magentas: number;+ tint: { enabled: boolean; hue: number; saturation: number };+}++interface PhotoFilter {+ filter: 'warming-85' | 'warming-81' | 'cooling-80' | 'cooling-82' | 'custom';+ color: string;+ density: number;+ preserveLuminosity: boolean;+}++interface ChannelMixer {+ outputChannel: 'red' | 'green' | 'blue';+ red: number;+ green: number;+ blue: number;+ constant: number;+ monochrome: boolean;+}++interface ColorLookup {+ lutFile: string; // .cube, .3dl, .look file+ lutData: Float32Array; // 3D LUT data+ strength: number;+}++interface GradientMap {+ gradient: GradientDef;+ dither: boolean;+ reverse: boolean;+}++interface Posterize {+ levels: number; // 2-255+}++interface Threshold {+ level: number; // 0-255+}+```++#### 4.2 Histogram & Info Panel+```typescript+interface Histogram {+ data: {+ red: Uint32Array;+ green: Uint32Array;+ blue: Uint32Array;+ luminosity: Uint32Array;+ };+ clipping: {+ shadowsClipped: number; // percentage+ highlightsClipped: number;+ };+ statistics: {+ mean: number;+ stdDev: number;+ median: number;+ pixelCount: number;+ };+}++interface ColorInfo {+ rgb: { r: number; g: number; b: number };+ hsb: { h: number; s: number; b: number };+ lab: { l: number; a: number; b: number };+ cmyk: { c: number; m: number; y: number; k: number };+ hex: string;+}+```++---++### Phase 5: Text & Vector++**Priority: MEDIUM | Effort: Medium**++#### 5.1 Text on Path+```typescript+interface TextOnPath {+ path: Path2D | SVGPath;+ startOffset: number; // 0-100%+ alignment: 'left' | 'center' | 'right';+ orientation: 'upright' | 'tangent';+ flipText: boolean;+}+```++#### 5.2 Warp Text+```typescript+type WarpStyle =+ | 'arc' | 'arc-lower' | 'arc-upper' | 'arch' | 'bulge'+ | 'shell-lower' | 'shell-upper' | 'flag' | 'wave' | 'fish'+ | 'rise' | 'fish-eye' | 'inflate' | 'squeeze' | 'twist';++interface WarpText {+ style: WarpStyle;+ orientation: 'horizontal' | 'vertical';+ bend: number; // -100 to +100+ horizontalDistortion: number;+ verticalDistortion: number;+}+```++#### 5.3 OpenType Features+```typescript+interface OpenTypeFeatures {+ ligatures: 'none' | 'standard' | 'discretionary' | 'historical';+ contextualAlternates: boolean;+ stylisticAlternates: boolean;+ swash: boolean;+ titlingAlternates: boolean;+ ordinals: boolean;+ fractions: boolean;+ slashedZero: boolean;+}+```++---++### Phase 6: Automation & Workflow++**Priority: MEDIUM | Effort: Large**++#### 6.1 Actions System+```typescript+interface Action {+ id: string;+ name: string;+ steps: ActionStep[];+ shortcut?: string;+}++interface ActionStep {+ id: string;+ type: string; // tool/filter/adjustment type+ parameters: Record<string, unknown>;+ enabled: boolean;+ dialog: boolean; // show dialog on playback+}++interface ActionSet {+ id: string;+ name: string;+ actions: Action[];+}++interface ActionStore {+ sets: ActionSet[];+ recording: boolean;+ currentAction: Action | null;+}+```++#### 6.2 Batch Processing+```typescript+interface BatchProcess {+ source: 'folder' | 'open-files';+ sourcePath?: string;+ includeSubfolders: boolean;+ action: string;+ destination: 'same' | 'folder' | 'save-close';+ destinationPath?: string;+ fileNaming: {+ template: string;+ startNumber: number;+ compatibility: 'windows' | 'mac' | 'unix';+ };+ errors: 'stop' | 'log' | 'skip';+}+```++#### 6.3 Presets System+```typescript+interface PresetLibrary {+ brushes: BrushPreset[];+ gradients: GradientPreset[];+ patterns: PatternPreset[];+ layerStyles: LayerStylePreset[];+ filters: FilterPreset[];+ adjustments: AdjustmentPreset[];+ tools: ToolPreset[];+ exports: ExportPreset[];+}+```++---++## Implementation Priority Matrix++### Tier 1: Critical (Implement First)+1. **Selection Tools** - Rectangular, Elliptical, Lasso, Magic Wand+2. **Layer Masks** - Pixel masks with feather, density+3. **Levels Adjustment** - Input/output levels, gamma+4. **Curves Adjustment** - Multi-point curve editing+5. **Eraser Tool** - Basic erasing with brush settings+6. **Enhanced History** - Visual history panel, snapshots++### Tier 2: High Priority+1. **Clone Stamp** - Source point, aligned mode+2. **Healing Brush** - Texture blending+3. **Spot Healing** - Content-aware healing+4. **Dodge/Burn** - Exposure-based lightening/darkening+5. **Additional Blend Modes** - Complete the 27 modes+6. **Layer Effects** - Bevel & Emboss, Inner Glow, Overlays+7. **Color Balance** - Shadows/Midtones/Highlights+8. **Selective Color** - CMYK-based color targeting+9. **Warp Transform** - Mesh-based warping+10. **Text on Path** - Path-following text++### Tier 3: Medium Priority+1. **Blur Filters** - Lens blur, surface blur, tilt-shift+2. **Sharpen Filters** - Unsharp mask, smart sharpen+3. **Distort Filters** - Spherize, pinch, twirl, wave+4. **Liquify** - Face-aware warping+5. **Noise Filters** - Add/reduce noise+6. **Vector Masks** - Path-based masks+7. **Clipping Masks** - Clip to layer below+8. **Color Lookup (LUT)** - 3D LUT support+9. **Gradient Map** - Tone-to-color mapping+10. **Warp Text** - 15 warp styles++### Tier 4: Lower Priority+1. **Stylize Filters** - Oil paint, emboss, find edges+2. **Render Filters** - Clouds, lens flare+3. **Actions System** - Record and playback+4. **Batch Processing** - Multi-file automation+5. **Variable Fonts** - Axis controls+6. **OpenType Features** - Ligatures, alternates+7. **Content-Aware Fill** - AI-powered fill (requires ML)+8. **Neural Filters** - AI-powered effects (requires ML)+9. **Puppet Warp** - Pin-based warping+10. **3D Layers** - Basic 3D support++---++## Technical Architecture++### Canvas Rendering Pipeline+```+Layer Stack+ ↓+For each layer:+ Apply masks (pixel/vector)+ ↓+ Apply clipping mask (if enabled)+ ↓+ Render layer content+ ↓+ Apply layer effects (shadow, glow, etc.)+ ↓+ Apply blend mode with layer below+ ↓+Composite to canvas+```++### Filter Processing Pipeline+```+Selection (optional)+ ↓+Source pixels+ ↓+Apply filter kernel/algorithm+ ↓+Apply feather (if selection)+ ↓+Blend with original (based on filter opacity)+ ↓+Output pixels+```++### Recommended File Structure+```+apps/image/src/+├── tools/+│ ├── selection/+│ │ ├── rectangular-marquee.ts+│ │ ├── elliptical-marquee.ts+│ │ ├── lasso.ts+│ │ ├── polygonal-lasso.ts+│ │ ├── magic-wand.ts+│ │ └── color-range.ts+│ ├── paint/+│ │ ├── brush.ts+│ │ ├── eraser.ts+│ │ ├── clone-stamp.ts+│ │ ├── healing-brush.ts+│ │ └── spot-healing.ts+│ ├── retouch/+│ │ ├── dodge.ts+│ │ ├── burn.ts+│ │ ├── sponge.ts+│ │ └── smudge.ts+│ └── transform/+│ ├── warp.ts+│ ├── perspective.ts+│ └── liquify.ts+├── filters/+│ ├── blur/+│ ├── sharpen/+│ ├── distort/+│ ├── noise/+│ ├── stylize/+│ └── render/+├── adjustments/+│ ├── levels.ts+│ ├── curves.ts+│ ├── color-balance.ts+│ ├── selective-color.ts+│ ├── channel-mixer.ts+│ └── color-lookup.ts+├── masks/+│ ├── pixel-mask.ts+│ ├── vector-mask.ts+│ └── clipping-mask.ts+├── effects/+│ ├── blend-modes.ts+│ ├── layer-styles.ts+│ └── contours.ts+└── automation/+ ├── actions.ts+ ├── history.ts+ └── presets.ts+```++---++## Estimated Effort Summary++| Phase | Features | Complexity | Files |+|-------|----------|------------|-------|+| Phase 1 | Selection, Masks, Levels, Curves, History | High | 15-20 |+| Phase 2 | Paint Tools, Retouching | High | 12-15 |+| Phase 3 | Blend Modes, Effects, Filters | Medium-High | 25-30 |+| Phase 4 | Color Adjustments, Histogram | Medium | 10-12 |+| Phase 5 | Text, Vector | Medium | 8-10 |+| Phase 6 | Actions, Automation | Medium-High | 10-12 |++**Total: 80-100 new/modified files**++---++## Next Steps++1. **Start with Phase 1** - Build foundation with selection system and masks+2. **Create tool architecture** - Abstract base classes for tool types+3. **Implement WebGL/WebGPU shaders** - For filter processing performance+4. **Build UI components** - Inspector panels for new features+5. **Add keyboard shortcuts** - Standard Photoshop shortcuts where possible+6. **Write tests** - Unit tests for algorithms, integration tests for tools++---++## Resources++- [Adobe Photoshop User Guide](https://helpx.adobe.com/photoshop/user-guide.html)+- [Photoshop Blend Mode Math](https://www.w3.org/TR/compositing-1/#blending)+- [Image Processing Algorithms](https://homepages.inf.ed.ac.uk/rbf/HIPR2/)+- [WebGL Fundamentals](https://webglfundamentals.org/)diff --git a/apps/image/src/components/editor/inspector/ColorBalanceSection.tsx b/apps/image/src/components/editor/inspector/ColorBalanceSection.tsxnew file mode 100644index 00000000..3ea18748--- /dev/null+++ b/apps/image/src/components/editor/inspector/ColorBalanceSection.tsx@@ -0,0 +1,211 @@+import { useState } from 'react';+import { useProjectStore } from '../../../stores/project-store';+import type { Layer } from '../../../types/project';+import type { ColorBalanceValues } from '../../../types/adjustments';+import { DEFAULT_COLOR_BALANCE } from '../../../types/adjustments';+import { Palette, RotateCcw } from 'lucide-react';++interface Props {+ layer: Layer;+}++type ToneType = 'shadows' | 'midtones' | 'highlights';++interface BalanceSliderProps {+ leftLabel: string;+ rightLabel: string;+ leftColor: string;+ rightColor: string;+ value: number;+ onChange: (value: number) => void;+}++function BalanceSlider({+ leftLabel,+ rightLabel,+ leftColor,+ rightColor,+ value,+ onChange,+}: BalanceSliderProps) {+ const percentage = ((value + 100) / 200) * 100;++ return (+ <div className="space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-[10px]" style={{ color: leftColor }}>+ {leftLabel}+ </span>+ <span className="text-[10px] font-mono text-muted-foreground">{value}</span>+ <span className="text-[10px]" style={{ color: rightColor }}>+ {rightLabel}+ </span>+ </div>+ <input+ type="range"+ value={value}+ min={-100}+ max={100}+ onChange={(e) => onChange(Number(e.target.value))}+ className="w-full h-1.5 appearance-none rounded-full cursor-pointer+ [&::-webkit-slider-thumb]:appearance-none+ [&::-webkit-slider-thumb]:w-2.5+ [&::-webkit-slider-thumb]:h-2.5+ [&::-webkit-slider-thumb]:rounded-full+ [&::-webkit-slider-thumb]:bg-foreground+ [&::-webkit-slider-thumb]:shadow-sm+ [&::-webkit-slider-thumb]:cursor-pointer"+ style={{+ background: `linear-gradient(to right, ${leftColor} 0%, hsl(var(--secondary)) ${percentage}%, ${rightColor} 100%)`,+ }}+ />+ </div>+ );+}++export function ColorBalanceSection({ layer }: Props) {+ const { updateLayer } = useProjectStore();+ const [activeTone, setActiveTone] = useState<ToneType>('midtones');+ const [isExpanded, setIsExpanded] = useState(true);++ const colorBalance = layer.colorBalance;+ const currentTone = colorBalance[activeTone];++ const handleToneChange = (key: keyof ColorBalanceValues, value: number) => {+ updateLayer(layer.id, {+ colorBalance: {+ ...colorBalance,+ [activeTone]: {+ ...currentTone,+ [key]: value,+ },+ },+ });+ };++ const handleEnabledChange = (enabled: boolean) => {+ updateLayer(layer.id, {+ colorBalance: {+ ...colorBalance,+ enabled,+ },+ });+ };++ const handlePreserveLuminosityChange = (preserveLuminosity: boolean) => {+ updateLayer(layer.id, {+ colorBalance: {+ ...colorBalance,+ preserveLuminosity,+ },+ });+ };++ const resetColorBalance = () => {+ updateLayer(layer.id, {+ colorBalance: { ...DEFAULT_COLOR_BALANCE },+ });+ };++ const tones: { id: ToneType; label: string }[] = [+ { id: 'shadows', label: 'Shadows' },+ { id: 'midtones', label: 'Midtones' },+ { id: 'highlights', label: 'Highlights' },+ ];++ return (+ <div className="border-b border-border">+ <button+ onClick={() => setIsExpanded(!isExpanded)}+ className="w-full flex items-center justify-between px-3 py-2 hover:bg-secondary/50 transition-colors"+ >+ <div className="flex items-center gap-2">+ <Palette size={14} className="text-muted-foreground" />+ <span className="text-xs font-medium">Color Balance</span>+ {colorBalance.enabled && (+ <span className="w-1.5 h-1.5 rounded-full bg-primary" />+ )}+ </div>+ <div className="flex items-center gap-1">+ <input+ type="checkbox"+ checked={colorBalance.enabled}+ onChange={(e) => {+ e.stopPropagation();+ handleEnabledChange(e.target.checked);+ }}+ className="w-3.5 h-3.5 rounded border-border"+ />+ </div>+ </button>++ {isExpanded && (+ <div className="px-3 pb-3 space-y-3">+ <div className="flex items-center justify-between">+ <div className="flex gap-1">+ {tones.map((tone) => (+ <button+ key={tone.id}+ onClick={() => setActiveTone(tone.id)}+ className={`px-2 py-1 text-[10px] rounded transition-colors ${+ activeTone === tone.id+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground'+ }`}+ >+ {tone.label}+ </button>+ ))}+ </div>+ <button+ onClick={resetColorBalance}+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"+ title="Reset Color Balance"+ >+ <RotateCcw size={12} />+ </button>+ </div>++ <div className="space-y-3 pt-1">+ <BalanceSlider+ leftLabel="Cyan"+ rightLabel="Red"+ leftColor="#00bcd4"+ rightColor="#f44336"+ value={currentTone.cyanRed}+ onChange={(v) => handleToneChange('cyanRed', v)}+ />++ <BalanceSlider+ leftLabel="Magenta"+ rightLabel="Green"+ leftColor="#e91e63"+ rightColor="#4caf50"+ value={currentTone.magentaGreen}+ onChange={(v) => handleToneChange('magentaGreen', v)}+ />++ <BalanceSlider+ leftLabel="Yellow"+ rightLabel="Blue"+ leftColor="#ffeb3b"+ rightColor="#2196f3"+ value={currentTone.yellowBlue}+ onChange={(v) => handleToneChange('yellowBlue', v)}+ />+ </div>++ <label className="flex items-center gap-2 pt-2 border-t border-border">+ <input+ type="checkbox"+ checked={colorBalance.preserveLuminosity}+ onChange={(e) => handlePreserveLuminosityChange(e.target.checked)}+ className="w-3.5 h-3.5 rounded border-border"+ />+ <span className="text-[10px] text-muted-foreground">Preserve Luminosity</span>+ </label>+ </div>+ )}+ </div>+ );+}diff --git a/apps/image/src/components/editor/inspector/CurvesSection.tsx b/apps/image/src/components/editor/inspector/CurvesSection.tsxnew file mode 100644index 00000000..3a787489--- /dev/null+++ b/apps/image/src/components/editor/inspector/CurvesSection.tsx@@ -0,0 +1,267 @@+import { useState, useRef, useCallback } from 'react';+import { useProjectStore } from '../../../stores/project-store';+import type { Layer } from '../../../types/project';+import type { CurvePoint } from '../../../types/adjustments';+import { DEFAULT_CURVES } from '../../../types/adjustments';+import { TrendingUp, RotateCcw } from 'lucide-react';++interface Props {+ layer: Layer;+}++type ChannelType = 'master' | 'red' | 'green' | 'blue';++interface CurveEditorProps {+ points: CurvePoint[];+ onChange: (points: CurvePoint[]) => void;+ channel: ChannelType;+}++function CurveEditor({ points, onChange, channel }: CurveEditorProps) {+ const svgRef = useRef<SVGSVGElement>(null);+ const [draggingIndex, setDraggingIndex] = useState<number | null>(null);+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);++ const channelColors: Record<ChannelType, string> = {+ master: 'hsl(var(--foreground))',+ red: '#ef4444',+ green: '#22c55e',+ blue: '#3b82f6',+ };++ const sortedPoints = [...points].sort((a, b) => a.input - b.input);++ const getPathD = useCallback(() => {+ if (sortedPoints.length < 2) return '';++ const pathPoints = sortedPoints.map((p) => ({+ x: (p.input / 255) * 100,+ y: 100 - (p.output / 255) * 100,+ }));++ let d = `M ${pathPoints[0].x} ${pathPoints[0].y}`;++ for (let i = 1; i < pathPoints.length; i++) {+ const prev = pathPoints[i - 1];+ const curr = pathPoints[i];+ const cpx = (prev.x + curr.x) / 2;+ d += ` C ${cpx} ${prev.y}, ${cpx} ${curr.y}, ${curr.x} ${curr.y}`;+ }++ return d;+ }, [sortedPoints]);++ const handleMouseDown = (index: number, e: React.MouseEvent) => {+ e.preventDefault();+ if (index === 0 || index === sortedPoints.length - 1) return;+ setDraggingIndex(index);+ };++ const handleMouseMove = useCallback(+ (e: React.MouseEvent) => {+ if (draggingIndex === null || !svgRef.current) return;++ const rect = svgRef.current.getBoundingClientRect();+ const x = ((e.clientX - rect.left) / rect.width) * 255;+ const y = (1 - (e.clientY - rect.top) / rect.height) * 255;++ const newPoints = [...sortedPoints];+ newPoints[draggingIndex] = {+ input: Math.max(1, Math.min(254, Math.round(x))),+ output: Math.max(0, Math.min(255, Math.round(y))),+ };+ onChange(newPoints);+ },+ [draggingIndex, sortedPoints, onChange]+ );++ const handleMouseUp = () => {+ setDraggingIndex(null);+ };++ const handleClick = (e: React.MouseEvent) => {+ if (draggingIndex !== null || !svgRef.current) return;++ const rect = svgRef.current.getBoundingClientRect();+ const x = ((e.clientX - rect.left) / rect.width) * 255;+ const y = (1 - (e.clientY - rect.top) / rect.height) * 255;++ if (sortedPoints.length >= 14) return;++ const newPoint: CurvePoint = {+ input: Math.round(x),+ output: Math.round(y),+ };+ onChange([...sortedPoints, newPoint]);+ };++ const handleDoubleClick = (index: number, e: React.MouseEvent) => {+ e.stopPropagation();+ if (index === 0 || index === sortedPoints.length - 1) return;+ const newPoints = sortedPoints.filter((_, i) => i !== index);+ onChange(newPoints);+ };++ return (+ <div className="relative">+ <svg+ ref={svgRef}+ viewBox="0 0 100 100"+ className="w-full h-32 bg-secondary/50 rounded border border-border cursor-crosshair"+ onMouseMove={handleMouseMove}+ onMouseUp={handleMouseUp}+ onMouseLeave={handleMouseUp}+ onClick={handleClick}+ >+ <defs>+ <pattern id="grid" width="25" height="25" patternUnits="userSpaceOnUse">+ <path d="M 25 0 L 0 0 0 25" fill="none" stroke="hsl(var(--border))" strokeWidth="0.5" opacity="0.5" />+ </pattern>+ </defs>++ <rect width="100" height="100" fill="url(#grid)" />++ <line x1="0" y1="100" x2="100" y2="0" stroke="hsl(var(--muted-foreground))" strokeWidth="0.5" strokeDasharray="2 2" opacity="0.3" />++ <path d={getPathD()} fill="none" stroke={channelColors[channel]} strokeWidth="2" />++ {sortedPoints.map((point, index) => {+ const x = (point.input / 255) * 100;+ const y = 100 - (point.output / 255) * 100;+ const isEndpoint = index === 0 || index === sortedPoints.length - 1;+ const isHovered = hoverIndex === index;+ const isDragging = draggingIndex === index;++ return (+ <circle+ key={index}+ cx={x}+ cy={y}+ r={isDragging || isHovered ? 4 : 3}+ fill={isEndpoint ? 'hsl(var(--muted-foreground))' : channelColors[channel]}+ stroke="hsl(var(--background))"+ strokeWidth="1"+ className={isEndpoint ? 'cursor-not-allowed' : 'cursor-move'}+ onMouseDown={(e) => handleMouseDown(index, e)}+ onDoubleClick={(e) => handleDoubleClick(index, e)}+ onMouseEnter={() => setHoverIndex(index)}+ onMouseLeave={() => setHoverIndex(null)}+ />+ );+ })}+ </svg>+ <div className="flex justify-between mt-1 text-[9px] text-muted-foreground">+ <span>0</span>+ <span>Input</span>+ <span>255</span>+ </div>+ </div>+ );+}++export function CurvesSection({ layer }: Props) {+ const { updateLayer } = useProjectStore();+ const [activeChannel, setActiveChannel] = useState<ChannelType>('master');+ const [isExpanded, setIsExpanded] = useState(true);++ const curves = layer.curves;++ const handlePointsChange = (points: CurvePoint[]) => {+ updateLayer(layer.id, {+ curves: {+ ...curves,+ [activeChannel]: { points },+ },+ });+ };++ const handleEnabledChange = (enabled: boolean) => {+ updateLayer(layer.id, {+ curves: {+ ...curves,+ enabled,+ },+ });+ };++ const resetCurves = () => {+ updateLayer(layer.id, {+ curves: { ...DEFAULT_CURVES },+ });+ };++ const channelColors: Record<ChannelType, string> = {+ master: 'bg-foreground',+ red: 'bg-red-500',+ green: 'bg-green-500',+ blue: 'bg-blue-500',+ };++ return (+ <div className="border-b border-border">+ <button+ onClick={() => setIsExpanded(!isExpanded)}+ className="w-full flex items-center justify-between px-3 py-2 hover:bg-secondary/50 transition-colors"+ >+ <div className="flex items-center gap-2">+ <TrendingUp size={14} className="text-muted-foreground" />+ <span className="text-xs font-medium">Curves</span>+ {curves.enabled && (+ <span className="w-1.5 h-1.5 rounded-full bg-primary" />+ )}+ </div>+ <div className="flex items-center gap-1">+ <input+ type="checkbox"+ checked={curves.enabled}+ onChange={(e) => {+ e.stopPropagation();+ handleEnabledChange(e.target.checked);+ }}+ className="w-3.5 h-3.5 rounded border-border"+ />+ </div>+ </button>++ {isExpanded && (+ <div className="px-3 pb-3 space-y-3">+ <div className="flex items-center justify-between">+ <div className="flex gap-1">+ {(['master', 'red', 'green', 'blue'] as ChannelType[]).map((channel) => (+ <button+ key={channel}+ onClick={() => setActiveChannel(channel)}+ className={`px-2 py-1 text-[10px] rounded transition-colors ${+ activeChannel === channel+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground'+ }`}+ >+ <span className={`inline-block w-1.5 h-1.5 rounded-full mr-1 ${channelColors[channel]}`} />+ {channel.charAt(0).toUpperCase()}+ </button>+ ))}+ </div>+ <button+ onClick={resetCurves}+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"+ title="Reset Curves"+ >+ <RotateCcw size={12} />+ </button>+ </div>++ <CurveEditor+ points={curves[activeChannel].points}+ onChange={handlePointsChange}+ channel={activeChannel}+ />++ <p className="text-[9px] text-muted-foreground text-center">+ Click to add point • Double-click to remove • Drag to adjust+ </p>+ </div>+ )}+ </div>+ );+}diff --git a/apps/image/src/components/editor/inspector/DodgeBurnToolPanel.tsx b/apps/image/src/components/editor/inspector/DodgeBurnToolPanel.tsxnew file mode 100644index 00000000..be08bd74--- /dev/null+++ b/apps/image/src/components/editor/inspector/DodgeBurnToolPanel.tsx@@ -0,0 +1,167 @@+import { useUIStore } from '../../../stores/ui-store';+import { Sun, Moon } from 'lucide-react';++interface SliderProps {+ label: string;+ value: number;+ min: number;+ max: number;+ step?: number;+ unit?: string;+ onChange: (value: number) => void;+}++function Slider({ label, value, min, max, step = 1, unit = '', onChange }: SliderProps) {+ const percentage = ((value - min) / (max - min)) * 100;++ return (+ <div className="space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-[10px] text-muted-foreground">{label}</span>+ <span className="text-[10px] font-mono text-muted-foreground">+ {value.toFixed(step < 1 ? 0 : 0)}{unit}+ </span>+ </div>+ <input+ type="range"+ value={value}+ min={min}+ max={max}+ step={step}+ onChange={(e) => onChange(Number(e.target.value))}+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer+ [&::-webkit-slider-thumb]:appearance-none+ [&::-webkit-slider-thumb]:w-2.5+ [&::-webkit-slider-thumb]:h-2.5+ [&::-webkit-slider-thumb]:rounded-full+ [&::-webkit-slider-thumb]:bg-primary+ [&::-webkit-slider-thumb]:shadow-sm+ [&::-webkit-slider-thumb]:cursor-pointer"+ style={{+ background: `linear-gradient(to right, hsl(var(--primary)) 0%, hsl(var(--primary)) ${percentage}%, hsl(var(--secondary)) ${percentage}%, hsl(var(--secondary)) 100%)`,+ }}+ />+ </div>+ );+}++export function DodgeBurnToolPanel() {+ const { activeTool, dodgeBurnSettings, setDodgeBurnSettings } = useUIStore();++ if (activeTool !== 'dodge' && activeTool !== 'burn') {+ return null;+ }++ const toolTypes = [+ { id: 'dodge' as const, icon: Sun, label: 'Dodge' },+ { id: 'burn' as const, icon: Moon, label: 'Burn' },+ ];++ const ranges = [+ { id: 'shadows' as const, label: 'Shadows' },+ { id: 'midtones' as const, label: 'Midtones' },+ { id: 'highlights' as const, label: 'Highlights' },+ ];++ return (+ <div className="border-b border-border">+ <div className="px-3 py-2 flex items-center gap-2">+ {dodgeBurnSettings.type === 'dodge' ? (+ <Sun size={14} className="text-muted-foreground" />+ ) : (+ <Moon size={14} className="text-muted-foreground" />+ )}+ <span className="text-xs font-medium">+ {dodgeBurnSettings.type === 'dodge' ? 'Dodge Tool' : 'Burn Tool'}+ </span>+ </div>++ <div className="px-3 pb-3 space-y-3">+ <div className="space-y-1.5">+ <span className="text-[10px] text-muted-foreground font-medium">Tool</span>+ <div className="flex gap-1">+ {toolTypes.map((type) => (+ <button+ key={type.id}+ onClick={() => setDodgeBurnSettings({ type: type.id })}+ className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded transition-colors ${+ dodgeBurnSettings.type === type.id+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'+ }`}+ >+ <type.icon size={12} />+ {type.label}+ </button>+ ))}+ </div>+ </div>++ <div className="space-y-1.5">+ <span className="text-[10px] text-muted-foreground font-medium">Range</span>+ <div className="flex gap-1">+ {ranges.map((range) => (+ <button+ key={range.id}+ onClick={() => setDodgeBurnSettings({ range: range.id })}+ className={`flex-1 px-2 py-1.5 text-[10px] rounded transition-colors ${+ dodgeBurnSettings.range === range.id+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'+ }`}+ >+ {range.label}+ </button>+ ))}+ </div>+ </div>++ <Slider+ label="Exposure"+ value={dodgeBurnSettings.exposure}+ min={1}+ max={100}+ unit="%"+ onChange={(v) => setDodgeBurnSettings({ exposure: v })}+ />++ <Slider+ label="Size"+ value={dodgeBurnSettings.size}+ min={1}+ max={500}+ unit="px"+ onChange={(v) => setDodgeBurnSettings({ size: v })}+ />++ <div className="pt-2 border-t border-border">+ <div className="flex items-center justify-center p-3 bg-secondary/30 rounded-lg">+ <div+ className="rounded-full transition-all"+ style={{+ width: Math.min(dodgeBurnSettings.size, 80),+ height: Math.min(dodgeBurnSettings.size, 80),+ background:+ dodgeBurnSettings.type === 'dodge'+ ? `radial-gradient(circle, rgba(255,255,255,${dodgeBurnSettings.exposure / 100}) 0%, transparent 70%)`+ : `radial-gradient(circle, rgba(0,0,0,${dodgeBurnSettings.exposure / 100}) 0%, transparent 70%)`,+ }}+ />+ </div>+ <p className="text-[9px] text-muted-foreground text-center mt-1.5">+ {dodgeBurnSettings.type === 'dodge' ? 'Lightens' : 'Darkens'} {dodgeBurnSettings.range}+ </p>+ </div>++ <div className="space-y-1.5">+ <span className="text-[10px] text-muted-foreground font-medium">Tips</span>+ <ul className="text-[9px] text-muted-foreground space-y-0.5">+ <li>• {dodgeBurnSettings.type === 'dodge' ? 'Lightens' : 'Darkens'} selected tonal range</li>+ <li>• Lower exposure for subtle adjustments</li>+ <li>• Build up effect with multiple strokes</li>+ </ul>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/image/src/components/editor/inspector/EraserToolPanel.tsx b/apps/image/src/components/editor/inspector/EraserToolPanel.tsxnew file mode 100644index 00000000..713943b7--- /dev/null+++ b/apps/image/src/components/editor/inspector/EraserToolPanel.tsx@@ -0,0 +1,153 @@+import { useUIStore } from '../../../stores/ui-store';+import { Eraser, Square, Pencil, Circle } from 'lucide-react';++interface SliderProps {+ label: string;+ value: number;+ min: number;+ max: number;+ step?: number;+ unit?: string;+ onChange: (value: number) => void;+}++function Slider({ label, value, min, max, step = 1, unit = '', onChange }: SliderProps) {+ const percentage = ((value - min) / (max - min)) * 100;++ return (+ <div className="space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-[10px] text-muted-foreground">{label}</span>+ <span className="text-[10px] font-mono text-muted-foreground">+ {value.toFixed(step < 1 ? 0 : 0)}{unit}+ </span>+ </div>+ <input+ type="range"+ value={value}+ min={min}+ max={max}+ step={step}+ onChange={(e) => onChange(Number(e.target.value))}+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer+ [&::-webkit-slider-thumb]:appearance-none+ [&::-webkit-slider-thumb]:w-2.5+ [&::-webkit-slider-thumb]:h-2.5+ [&::-webkit-slider-thumb]:rounded-full+ [&::-webkit-slider-thumb]:bg-primary+ [&::-webkit-slider-thumb]:shadow-sm+ [&::-webkit-slider-thumb]:cursor-pointer"+ style={{+ background: `linear-gradient(to right, hsl(var(--primary)) 0%, hsl(var(--primary)) ${percentage}%, hsl(var(--secondary)) ${percentage}%, hsl(var(--secondary)) 100%)`,+ }}+ />+ </div>+ );+}++export function EraserToolPanel() {+ const { activeTool, eraserSettings, setEraserSettings } = useUIStore();++ if (activeTool !== 'eraser') {+ return null;+ }++ const eraserModes = [+ { id: 'brush' as const, icon: Circle, label: 'Brush' },+ { id: 'pencil' as const, icon: Pencil, label: 'Pencil' },+ { id: 'block' as const, icon: Square, label: 'Block' },+ ];++ return (+ <div className="border-b border-border">+ <div className="px-3 py-2 flex items-center gap-2">+ <Eraser size={14} className="text-muted-foreground" />+ <span className="text-xs font-medium">Eraser Tool</span>+ </div>++ <div className="px-3 pb-3 space-y-3">+ <div className="space-y-1.5">+ <span className="text-[10px] text-muted-foreground font-medium">Mode</span>+ <div className="flex gap-1">+ {eraserModes.map((mode) => (+ <button+ key={mode.id}+ onClick={() => setEraserSettings({ mode: mode.id })}+ className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded transition-colors ${+ eraserSettings.mode === mode.id+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'+ }`}+ >+ <mode.icon size={12} />+ {mode.label}+ </button>+ ))}+ </div>+ </div>++ <Slider+ label="Size"+ value={eraserSettings.size}+ min={1}+ max={500}+ unit="px"+ onChange={(v) => setEraserSettings({ size: v })}+ />++ <Slider+ label="Hardness"+ value={eraserSettings.hardness}+ min={0}+ max={100}+ unit="%"+ onChange={(v) => setEraserSettings({ hardness: v })}+ />++ <Slider+ label="Opacity"+ value={Math.round(eraserSettings.opacity * 100)}+ min={1}+ max={100}+ unit="%"+ onChange={(v) => setEraserSettings({ opacity: v / 100 })}+ />++ <Slider+ label="Flow"+ value={Math.round(eraserSettings.flow * 100)}+ min={1}+ max={100}+ unit="%"+ onChange={(v) => setEraserSettings({ flow: v / 100 })}+ />++ <div className="pt-2 border-t border-border">+ <div className="flex items-center justify-center p-3 bg-secondary/30 rounded-lg">+ <div+ className="rounded-full bg-foreground transition-all"+ style={{+ width: Math.min(eraserSettings.size, 100),+ height: Math.min(eraserSettings.size, 100),+ opacity: eraserSettings.opacity,+ filter: `blur(${(100 - eraserSettings.hardness) / 20}px)`,+ }}+ />+ </div>+ <p className="text-[9px] text-muted-foreground text-center mt-1.5">+ Brush preview+ </p>+ </div>++ <div className="space-y-1.5">+ <span className="text-[10px] text-muted-foreground font-medium">Tips</span>+ <ul className="text-[9px] text-muted-foreground space-y-0.5">+ <li>• Hold Shift for straight lines</li>+ <li>• [ and ] to adjust size</li>+ <li>• Shift+[ and ] for hardness</li>+ </ul>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/image/src/components/editor/inspector/Inspector.tsx b/apps/image/src/components/editor/inspector/Inspector.tsxindex e6c668b6..de67093d 100644--- a/apps/image/src/components/editor/inspector/Inspector.tsx+++ b/apps/image/src/components/editor/inspector/Inspector.tsx@@ -17,6 +17,13 @@ const ImageControlsSection = lazy(() => import('./ImageControlsSection').then(mconst BackgroundRemovalSection = lazy(() => import('./BackgroundRemovalSection').then(m => ({ default: m.BackgroundRemovalSection })));const TextSection = lazy(() => import('./TextSection').then(m => ({ default: m.TextSection })));const ShapeSection = lazy(() => import('./ShapeSection').then(m => ({ default: m.ShapeSection })));+const LevelsSection = lazy(() => import('./LevelsSection').then(m => ({ default: m.LevelsSection })));+const CurvesSection = lazy(() => import('./CurvesSection').then(m => ({ default: m.CurvesSection })));+const ColorBalanceSection = lazy(() => import('./ColorBalanceSection').then(m => ({ default: m.ColorBalanceSection })));+const MaskSection = lazy(() => import('./MaskSection').then(m => ({ default: m.MaskSection })));+const SelectionToolsPanel = lazy(() => import('./SelectionToolsPanel').then(m => ({ default: m.SelectionToolsPanel })));+const EraserToolPanel = lazy(() => import('./EraserToolPanel').then(m => ({ default: m.EraserToolPanel })));+const DodgeBurnToolPanel = lazy(() => import('./DodgeBurnToolPanel').then(m => ({ default: m.DodgeBurnToolPanel })));function SectionLoader() {return <div className="h-8 animate-pulse bg-muted/30 rounded" />;@@ -32,6 +39,14 @@ function InspectorContent() {const singleLayer = selectedLayers.length === 1 ? selectedLayers[0] : null;+ const isSelectionTool = [+ 'marquee-rect',+ 'marquee-ellipse',+ 'lasso',+ 'lasso-polygon',+ 'magic-wand',+ ].includes(activeTool);+if (selectedLayers.length === 0) {if (activeTool === 'pen') {return (@@ -41,6 +56,36 @@ function InspectorContent() {);}+ if (isSelectionTool) {+ return (+ <div className="p-4">+ <Suspense fallback={<SectionLoader />}>+ <SelectionToolsPanel />+ </Suspense>+ </div>+ );+ }++ if (activeTool === 'eraser') {+ return (+ <div className="p-4">+ <Suspense fallback={<SectionLoader />}>+ <EraserToolPanel />+ </Suspense>+ </div>+ );+ }++ if (activeTool === 'dodge' || activeTool === 'burn') {+ return (+ <div className="p-4">+ <Suspense fallback={<SectionLoader />}>+ <DodgeBurnToolPanel />+ </Suspense>+ </div>+ );+ }+const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);if (artboard) {return (@@ -99,9 +144,16 @@ function InspectorContent() {<BackgroundRemovalSection layer={singleLayer as ImageLayer} /><FilterPresetsSection layer={singleLayer as ImageLayer} /><ImageAdjustmentsSection layer={singleLayer as ImageLayer} />+ <LevelsSection layer={singleLayer} />+ <CurvesSection layer={singleLayer} />+ <ColorBalanceSection layer={singleLayer} /></Suspense>)}+ <Suspense fallback={<SectionLoader />}>+ <MaskSection layer={singleLayer} />+ </Suspense>+{singleLayer.type === 'text' && (<Suspense fallback={<SectionLoader />}><TextSection layer={singleLayer as TextLayer} />diff --git a/apps/image/src/components/editor/inspector/LevelsSection.tsx b/apps/image/src/components/editor/inspector/LevelsSection.tsxnew file mode 100644index 00000000..7075b0a8--- /dev/null+++ b/apps/image/src/components/editor/inspector/LevelsSection.tsx@@ -0,0 +1,213 @@+import { useState } from 'react';+import { useProjectStore } from '../../../stores/project-store';+import type { Layer } from '../../../types/project';+import type { LevelsChannel } from '../../../types/adjustments';+import { DEFAULT_LEVELS } from '../../../types/adjustments';+import { Activity, RotateCcw } from 'lucide-react';++interface Props {+ layer: Layer;+}++type ChannelType = 'master' | 'red' | 'green' | 'blue';++interface LevelsSliderProps {+ label: string;+ value: number;+ min: number;+ max: number;+ step?: number;+ onChange: (value: number) => void;+}++function LevelsSlider({ label, value, min, max, step = 1, onChange }: LevelsSliderProps) {+ const percentage = ((value - min) / (max - min)) * 100;++ return (+ <div className="space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-[10px] text-muted-foreground">{label}</span>+ <span className="text-[10px] font-mono text-muted-foreground">{value.toFixed(step < 1 ? 2 : 0)}</span>+ </div>+ <input+ type="range"+ value={value}+ min={min}+ max={max}+ step={step}+ onChange={(e) => onChange(Number(e.target.value))}+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer+ [&::-webkit-slider-thumb]:appearance-none+ [&::-webkit-slider-thumb]:w-2.5+ [&::-webkit-slider-thumb]:h-2.5+ [&::-webkit-slider-thumb]:rounded-full+ [&::-webkit-slider-thumb]:bg-primary+ [&::-webkit-slider-thumb]:shadow-sm+ [&::-webkit-slider-thumb]:cursor-pointer"+ style={{+ background: `linear-gradient(to right, hsl(var(--primary)) 0%, hsl(var(--primary)) ${percentage}%, hsl(var(--secondary)) ${percentage}%, hsl(var(--secondary)) 100%)`+ }}+ />+ </div>+ );+}++export function LevelsSection({ layer }: Props) {+ const { updateLayer } = useProjectStore();+ const [activeChannel, setActiveChannel] = useState<ChannelType>('master');+ const [isExpanded, setIsExpanded] = useState(true);++ const levels = layer.levels;+ const currentChannel = levels[activeChannel];++ const handleChannelChange = (key: keyof LevelsChannel, value: number) => {+ updateLayer(layer.id, {+ levels: {+ ...levels,+ [activeChannel]: {+ ...currentChannel,+ [key]: value,+ },+ },+ });+ };++ const handleEnabledChange = (enabled: boolean) => {+ updateLayer(layer.id, {+ levels: {+ ...levels,+ enabled,+ },+ });+ };++ const resetLevels = () => {+ updateLayer(layer.id, {+ levels: { ...DEFAULT_LEVELS },+ });+ };++ const channelColors: Record<ChannelType, string> = {+ master: 'bg-foreground',+ red: 'bg-red-500',+ green: 'bg-green-500',+ blue: 'bg-blue-500',+ };++ return (+ <div className="border-b border-border">+ <button+ onClick={() => setIsExpanded(!isExpanded)}+ className="w-full flex items-center justify-between px-3 py-2 hover:bg-secondary/50 transition-colors"+ >+ <div className="flex items-center gap-2">+ <Activity size={14} className="text-muted-foreground" />+ <span className="text-xs font-medium">Levels</span>+ {levels.enabled && (+ <span className="w-1.5 h-1.5 rounded-full bg-primary" />+ )}+ </div>+ <div className="flex items-center gap-1">+ <input+ type="checkbox"+ checked={levels.enabled}+ onChange={(e) => {+ e.stopPropagation();+ handleEnabledChange(e.target.checked);+ }}+ className="w-3.5 h-3.5 rounded border-border"+ />+ </div>+ </button>++ {isExpanded && (+ <div className="px-3 pb-3 space-y-3">+ <div className="flex items-center justify-between">+ <div className="flex gap-1">+ {(['master', 'red', 'green', 'blue'] as ChannelType[]).map((channel) => (+ <button+ key={channel}+ onClick={() => setActiveChannel(channel)}+ className={`px-2 py-1 text-[10px] rounded transition-colors ${+ activeChannel === channel+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground'+ }`}+ >+ <span className={`inline-block w-1.5 h-1.5 rounded-full mr-1 ${channelColors[channel]}`} />+ {channel.charAt(0).toUpperCase()}+ </button>+ ))}+ </div>+ <button+ onClick={resetLevels}+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"+ title="Reset Levels"+ >+ <RotateCcw size={12} />+ </button>+ </div>++ <div className="space-y-2.5 pt-1">+ <div className="space-y-1.5">+ <span className="text-[10px] text-muted-foreground font-medium">Input Levels</span>+ <div className="flex gap-2">+ <div className="flex-1">+ <LevelsSlider+ label="Black"+ value={currentChannel.inputBlack}+ min={0}+ max={255}+ onChange={(v) => handleChannelChange('inputBlack', v)}+ />+ </div>+ <div className="flex-1">+ <LevelsSlider+ label="White"+ value={currentChannel.inputWhite}+ min={0}+ max={255}+ onChange={(v) => handleChannelChange('inputWhite', v)}+ />+ </div>+ </div>+ </div>++ <LevelsSlider+ label="Gamma"+ value={currentChannel.gamma}+ min={0.1}+ max={10}+ step={0.01}+ onChange={(v) => handleChannelChange('gamma', v)}+ />++ <div className="space-y-1.5">+ <span className="text-[10px] text-muted-foreground font-medium">Output Levels</span>+ <div className="flex gap-2">+ <div className="flex-1">+ <LevelsSlider+ label="Black"+ value={currentChannel.outputBlack}+ min={0}+ max={255}+ onChange={(v) => handleChannelChange('outputBlack', v)}+ />+ </div>+ <div className="flex-1">+ <LevelsSlider+ label="White"+ value={currentChannel.outputWhite}+ min={0}+ max={255}+ onChange={(v) => handleChannelChange('outputWhite', v)}+ />+ </div>+ </div>+ </div>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/apps/image/src/components/editor/inspector/MaskSection.tsx b/apps/image/src/components/editor/inspector/MaskSection.tsxnew file mode 100644index 00000000..b9356ec2--- /dev/null+++ b/apps/image/src/components/editor/inspector/MaskSection.tsx@@ -0,0 +1,293 @@+import { useProjectStore } from '../../../stores/project-store';+import { useSelectionStore } from '../../../stores/selection-store';+import type { Layer } from '../../../types/project';+import type { LayerMask } from '../../../types/mask';+import {+ Circle,+ Eye,+ EyeOff,+ Link,+ Unlink,+ Trash2,+ RotateCcw,+ Plus,+ Download,+} from 'lucide-react';++interface Props {+ layer: Layer;+}++interface SliderProps {+ label: string;+ value: number;+ min: number;+ max: number;+ step?: number;+ onChange: (value: number) => void;+}++function Slider({ label, value, min, max, step = 1, onChange }: SliderProps) {+ const percentage = ((value - min) / (max - min)) * 100;++ return (+ <div className="space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-[10px] text-muted-foreground">{label}</span>+ <span className="text-[10px] font-mono text-muted-foreground">+ {value.toFixed(step < 1 ? 0 : 0)}+ {label === 'Density' || label === 'Feather' ? '%' : 'px'}+ </span>+ </div>+ <input+ type="range"+ value={value}+ min={min}+ max={max}+ step={step}+ onChange={(e) => onChange(Number(e.target.value))}+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer+ [&::-webkit-slider-thumb]:appearance-none+ [&::-webkit-slider-thumb]:w-2.5+ [&::-webkit-slider-thumb]:h-2.5+ [&::-webkit-slider-thumb]:rounded-full+ [&::-webkit-slider-thumb]:bg-primary+ [&::-webkit-slider-thumb]:shadow-sm+ [&::-webkit-slider-thumb]:cursor-pointer"+ style={{+ background: `linear-gradient(to right, hsl(var(--primary)) 0%, hsl(var(--primary)) ${percentage}%, hsl(var(--secondary)) ${percentage}%, hsl(var(--secondary)) 100%)`,+ }}+ />+ </div>+ );+}++export function MaskSection({ layer }: Props) {+ const { updateLayer } = useProjectStore();+ const { active: selection, clearSelection } = useSelectionStore();++ const mask = layer.mask;+ const hasMask = mask !== null;+ const hasSelection = selection !== null;++ const handleAddMask = (reveal: boolean) => {+ const baseMask: LayerMask = {+ id: `mask-${Date.now()}`,+ type: 'pixel',+ enabled: true,+ linked: true,+ density: 100,+ feather: 0,+ invert: !reveal,+ data: null,+ vectorPath: selection ? [...selection.path] : null,+ };++ updateLayer(layer.id, { mask: baseMask });++ if (selection) {+ clearSelection();+ }+ };++ const handleDeleteMask = () => {+ updateLayer(layer.id, { mask: null });+ };++ const handleToggleMaskEnabled = () => {+ if (!mask) return;+ updateLayer(layer.id, {+ mask: { ...mask, enabled: !mask.enabled },+ });+ };++ const handleToggleMaskLinked = () => {+ if (!mask) return;+ updateLayer(layer.id, {+ mask: { ...mask, linked: !mask.linked },+ });+ };++ const handleToggleMaskInvert = () => {+ if (!mask) return;+ updateLayer(layer.id, {+ mask: { ...mask, invert: !mask.invert },+ });+ };++ const handleDensityChange = (density: number) => {+ if (!mask) return;+ updateLayer(layer.id, {+ mask: { ...mask, density },+ });+ };++ const handleFeatherChange = (feather: number) => {+ if (!mask) return;+ updateLayer(layer.id, {+ mask: { ...mask, feather },+ });+ };++ const handleToggleClippingMask = () => {+ updateLayer(layer.id, { clippingMask: !layer.clippingMask });+ };++ return (+ <div className="border-b border-border">+ <div className="px-3 py-2">+ <span className="text-xs font-medium">Masks</span>+ </div>++ <div className="px-3 pb-3 space-y-3">+ {!hasMask ? (+ <div className="space-y-2">+ <p className="text-[10px] text-muted-foreground">+ {hasSelection+ ? 'Create mask from current selection'+ : 'Add a mask to control layer visibility'}+ </p>++ <div className="flex gap-1.5">+ <button+ onClick={() => handleAddMask(true)}+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ <Plus size={10} />+ Reveal All+ </button>+ <button+ onClick={() => handleAddMask(false)}+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ <Plus size={10} />+ Hide All+ </button>+ </div>+ </div>+ ) : (+ <div className="space-y-3">+ <div className="flex items-center gap-2 p-2 rounded bg-secondary/50">+ <div className="w-8 h-8 rounded bg-gradient-to-br from-white to-black border border-border" />+ <div className="flex-1 min-w-0">+ <p className="text-[10px] font-medium truncate">+ {mask.type === 'pixel' ? 'Pixel Mask' : 'Vector Mask'}+ </p>+ <p className="text-[9px] text-muted-foreground">+ {mask.enabled ? 'Enabled' : 'Disabled'}+ {mask.invert ? ' • Inverted' : ''}+ </p>+ </div>+ </div>++ <div className="flex gap-1">+ <button+ onClick={handleToggleMaskEnabled}+ className={`flex-1 p-1.5 rounded transition-colors ${+ mask.enabled+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'+ }`}+ title={mask.enabled ? 'Disable Mask' : 'Enable Mask'}+ >+ {mask.enabled ? <Eye size={12} /> : <EyeOff size={12} />}+ </button>+ <button+ onClick={handleToggleMaskLinked}+ className={`flex-1 p-1.5 rounded transition-colors ${+ mask.linked+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'+ }`}+ title={mask.linked ? 'Unlink Mask' : 'Link Mask'}+ >+ {mask.linked ? <Link size={12} /> : <Unlink size={12} />}+ </button>+ <button+ onClick={handleToggleMaskInvert}+ className={`flex-1 p-1.5 rounded transition-colors ${+ mask.invert+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'+ }`}+ title={mask.invert ? 'Remove Invert' : 'Invert Mask'}+ >+ <RotateCcw size={12} />+ </button>+ <button+ onClick={handleDeleteMask}+ className="flex-1 p-1.5 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors"+ title="Delete Mask"+ >+ <Trash2 size={12} />+ </button>+ </div>++ <Slider+ label="Density"+ value={mask.density}+ min={0}+ max={100}+ onChange={handleDensityChange}+ />++ <Slider+ label="Feather"+ value={mask.feather}+ min={0}+ max={250}+ onChange={handleFeatherChange}+ />++ {hasSelection && (+ <div className="pt-2 border-t border-border space-y-1.5">+ <span className="text-[10px] text-muted-foreground font-medium">+ Apply Selection+ </span>+ <div className="flex gap-1.5">+ <button+ onClick={() => {}}+ className="flex-1 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ Add to Mask+ </button>+ <button+ onClick={() => {}}+ className="flex-1 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ Subtract+ </button>+ </div>+ </div>+ )}+ </div>+ )}++ <div className="pt-2 border-t border-border">+ <button+ onClick={handleToggleClippingMask}+ className={`w-full flex items-center gap-2 px-2 py-1.5 text-[10px] rounded transition-colors ${+ layer.clippingMask+ ? 'bg-primary/10 text-primary'+ : 'bg-secondary hover:bg-secondary/80'+ }`}+ >+ <Circle size={10} className={layer.clippingMask ? 'fill-primary' : ''} />+ <span>{layer.clippingMask ? 'Release Clipping Mask' : 'Create Clipping Mask'}</span>+ </button>+ </div>++ <div className="flex gap-1.5">+ <button+ onClick={() => {}}+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ title="Load mask from selection"+ >+ <Download size={10} />+ Load Selection+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/image/src/components/editor/inspector/SelectionToolsPanel.tsx b/apps/image/src/components/editor/inspector/SelectionToolsPanel.tsxnew file mode 100644index 00000000..7aa9e18b--- /dev/null+++ b/apps/image/src/components/editor/inspector/SelectionToolsPanel.tsx@@ -0,0 +1,280 @@+import { useUIStore } from '../../../stores/ui-store';+import { useSelectionStore } from '../../../stores/selection-store';+import { useProjectStore } from '../../../stores/project-store';+import {+ Square,+ Circle,+ Lasso,+ Pentagon,+ Wand2,+ Plus,+ Minus,+ BoxSelect,+ Trash2,+ RotateCcw,+ Download,+ Upload,+} from 'lucide-react';++interface SliderProps {+ label: string;+ value: number;+ min: number;+ max: number;+ step?: number;+ onChange: (value: number) => void;+}++function Slider({ label, value, min, max, step = 1, onChange }: SliderProps) {+ const percentage = ((value - min) / (max - min)) * 100;++ return (+ <div className="space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-[10px] text-muted-foreground">{label}</span>+ <span className="text-[10px] font-mono text-muted-foreground">+ {value.toFixed(step < 1 ? 1 : 0)}+ </span>+ </div>+ <input+ type="range"+ value={value}+ min={min}+ max={max}+ step={step}+ onChange={(e) => onChange(Number(e.target.value))}+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer+ [&::-webkit-slider-thumb]:appearance-none+ [&::-webkit-slider-thumb]:w-2.5+ [&::-webkit-slider-thumb]:h-2.5+ [&::-webkit-slider-thumb]:rounded-full+ [&::-webkit-slider-thumb]:bg-primary+ [&::-webkit-slider-thumb]:shadow-sm+ [&::-webkit-slider-thumb]:cursor-pointer"+ style={{+ background: `linear-gradient(to right, hsl(var(--primary)) 0%, hsl(var(--primary)) ${percentage}%, hsl(var(--secondary)) ${percentage}%, hsl(var(--secondary)) 100%)`,+ }}+ />+ </div>+ );+}++export function SelectionToolsPanel() {+ const {+ activeTool,+ setActiveTool,+ selectionToolSettings,+ setSelectionToolSettings,+ magicWandSettings,+ setMagicWandSettings,+ } = useUIStore();++ const {+ active: selection,+ clearSelection,+ invertSelection,+ featherSelection,+ expandSelection,+ contractSelection,+ } = useSelectionStore();++ const { project } = useProjectStore();+ const artboard = project?.artboards?.find((a) => a.id === project.activeArtboardId);+ const canvasBounds = artboard+ ? { x: 0, y: 0, width: artboard.size.width, height: artboard.size.height }+ : { x: 0, y: 0, width: 1920, height: 1080 };++ const isSelectionTool = [+ 'marquee-rect',+ 'marquee-ellipse',+ 'lasso',+ 'lasso-polygon',+ 'magic-wand',+ ].includes(activeTool);++ const hasSelection = selection !== null;++ const selectionTools = [+ { id: 'marquee-rect' as const, icon: Square, label: 'Rectangular' },+ { id: 'marquee-ellipse' as const, icon: Circle, label: 'Elliptical' },+ { id: 'lasso' as const, icon: Lasso, label: 'Lasso' },+ { id: 'lasso-polygon' as const, icon: Pentagon, label: 'Polygonal' },+ { id: 'magic-wand' as const, icon: Wand2, label: 'Magic Wand' },+ ];++ const selectionModes = [+ { id: 'new' as const, icon: Square, label: 'New' },+ { id: 'add' as const, icon: Plus, label: 'Add' },+ { id: 'subtract' as const, icon: Minus, label: 'Subtract' },+ { id: 'intersect' as const, icon: BoxSelect, label: 'Intersect' },+ ];++ if (!isSelectionTool && !hasSelection) {+ return null;+ }++ return (+ <div className="border-b border-border">+ <div className="px-3 py-2">+ <span className="text-xs font-medium">Selection Tools</span>+ </div>++ <div className="px-3 pb-3 space-y-3">+ <div className="flex flex-wrap gap-1">+ {selectionTools.map((tool) => (+ <button+ key={tool.id}+ onClick={() => setActiveTool(tool.id)}+ className={`p-1.5 rounded transition-colors ${+ activeTool === tool.id+ ? 'bg-primary text-primary-foreground'+ : 'text-muted-foreground hover:text-foreground hover:bg-secondary'+ }`}+ title={tool.label}+ >+ <tool.icon size={14} />+ </button>+ ))}+ </div>++ {isSelectionTool && (+ <>+ <div className="space-y-1.5">+ <span className="text-[10px] text-muted-foreground font-medium">Mode</span>+ <div className="flex gap-1">+ {selectionModes.map((mode) => (+ <button+ key={mode.id}+ onClick={() => setSelectionToolSettings({ mode: mode.id })}+ className={`flex-1 px-2 py-1.5 text-[10px] rounded transition-colors ${+ selectionToolSettings.mode === mode.id+ ? 'bg-secondary text-foreground'+ : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'+ }`}+ >+ {mode.label}+ </button>+ ))}+ </div>+ </div>++ <Slider+ label="Feather"+ value={selectionToolSettings.feather}+ min={0}+ max={100}+ onChange={(v) => setSelectionToolSettings({ feather: v })}+ />++ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={selectionToolSettings.antiAlias}+ onChange={(e) => setSelectionToolSettings({ antiAlias: e.target.checked })}+ className="w-3.5 h-3.5 rounded border-border"+ />+ <span className="text-[10px] text-muted-foreground">Anti-alias</span>+ </label>++ {activeTool === 'magic-wand' && (+ <div className="space-y-2.5 pt-2 border-t border-border">+ <Slider+ label="Tolerance"+ value={magicWandSettings.tolerance}+ min={0}+ max={255}+ onChange={(v) => setMagicWandSettings({ tolerance: v })}+ />++ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={magicWandSettings.contiguous}+ onChange={(e) => setMagicWandSettings({ contiguous: e.target.checked })}+ className="w-3.5 h-3.5 rounded border-border"+ />+ <span className="text-[10px] text-muted-foreground">Contiguous</span>+ </label>++ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={magicWandSettings.sampleAllLayers}+ onChange={(e) => setMagicWandSettings({ sampleAllLayers: e.target.checked })}+ className="w-3.5 h-3.5 rounded border-border"+ />+ <span className="text-[10px] text-muted-foreground">Sample All Layers</span>+ </label>+ </div>+ )}+ </>+ )}++ {hasSelection && (+ <div className="space-y-2.5 pt-2 border-t border-border">+ <span className="text-[10px] text-muted-foreground font-medium">Selection Actions</span>++ <div className="grid grid-cols-2 gap-1.5">+ <button+ onClick={() => invertSelection(canvasBounds)}+ className="flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ <RotateCcw size={10} />+ Invert+ </button>+ <button+ onClick={() => clearSelection()}+ className="flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ <Trash2 size={10} />+ Deselect+ </button>+ </div>++ <div className="space-y-1.5">+ <div className="flex gap-1.5">+ <button+ onClick={() => expandSelection(1)}+ className="flex-1 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ Expand+ </button>+ <button+ onClick={() => contractSelection(1)}+ className="flex-1 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ Contract+ </button>+ </div>+ <button+ onClick={() => featherSelection(selectionToolSettings.feather || 5)}+ className="w-full px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ Feather ({selectionToolSettings.feather || 5}px)+ </button>+ </div>++ <div className="flex gap-1.5">+ <button+ onClick={() => {}}+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ title="Save Selection"+ >+ <Download size={10} />+ Save+ </button>+ <button+ onClick={() => {}}+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ title="Load Selection"+ >+ <Upload size={10} />+ Load+ </button>+ </div>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/apps/image/src/components/editor/panels/HistoryPanel.tsx b/apps/image/src/components/editor/panels/HistoryPanel.tsxindex e733c5fd..27369dc5 100644--- a/apps/image/src/components/editor/panels/HistoryPanel.tsx+++ b/apps/image/src/components/editor/panels/HistoryPanel.tsx@@ -1,14 +1,44 @@-import { History, Undo2, Redo2, Trash2, Clock } from 'lucide-react';+import { useState } from 'react';+import {+ History,+ Undo2,+ Redo2,+ Trash2,+ Clock,+ Camera,+ Bookmark,+ ChevronDown,+ ChevronRight,+ Edit2,+ Check,+ X,+} from 'lucide-react';import { useHistoryStore } from '../../../stores/history-store';import { useProjectStore } from '../../../stores/project-store';import { formatDistanceToNow } from '../../../utils/time';export function HistoryPanel() {- const { entries, currentIndex, clear, canUndo, canRedo } = useHistoryStore();- const { loadProject } = useProjectStore();+ const {+ entries,+ currentIndex,+ snapshots,+ clear,+ canUndo,+ canRedo,+ goToEntry,+ createSnapshot,+ restoreSnapshot,+ deleteSnapshot,+ renameSnapshot,+ } = useHistoryStore();+ const { project, loadProject } = useProjectStore();const undo = useHistoryStore((s) => s.undo);const redo = useHistoryStore((s) => s.redo);+ const [showSnapshots, setShowSnapshots] = useState(true);+ const [editingSnapshotId, setEditingSnapshotId] = useState<string | null>(null);+ const [editingName, setEditingName] = useState('');+const handleUndo = () => {const state = undo();if (state) {@@ -25,15 +55,43 @@ export function HistoryPanel() {const handleJumpToState = (index: number) => {if (index === currentIndex) return;+ const state = goToEntry(index);+ if (state) {+ loadProject(state);+ }+ };- const entry = entries[index];- if (entry) {- const state = JSON.parse(entry.state);+ const handleCreateSnapshot = () => {+ if (!project) return;+ const name = `Snapshot ${snapshots.length + 1}`;+ createSnapshot(name, project);+ };++ const handleRestoreSnapshot = (id: string) => {+ const state = restoreSnapshot(id);+ if (state) {loadProject(state);- useHistoryStore.setState({ currentIndex: index });}};+ const handleStartRename = (id: string, currentName: string) => {+ setEditingSnapshotId(id);+ setEditingName(currentName);+ };++ const handleSaveRename = () => {+ if (editingSnapshotId && editingName.trim()) {+ renameSnapshot(editingSnapshotId, editingName.trim());+ }+ setEditingSnapshotId(null);+ setEditingName('');+ };++ const handleCancelRename = () => {+ setEditingSnapshotId(null);+ setEditingName('');+ };+return (<div className="h-full flex flex-col"><div className="flex items-center justify-between p-3 border-b border-border">@@ -74,8 +132,101 @@ export function HistoryPanel() {</div><div className="flex-1 overflow-y-auto">+ <div className="border-b border-border">+ <button+ onClick={() => setShowSnapshots(!showSnapshots)}+ className="w-full flex items-center gap-2 px-3 py-2 hover:bg-accent/50 transition-colors"+ >+ {showSnapshots ? <ChevronDown size={12} /> : <ChevronRight size={12} />}+ <Bookmark size={12} className="text-muted-foreground" />+ <span className="text-[11px] font-medium">Snapshots</span>+ <span className="text-[10px] text-muted-foreground ml-auto">{snapshots.length}</span>+ </button>++ {showSnapshots && (+ <div className="px-2 pb-2">+ <button+ onClick={handleCreateSnapshot}+ className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 mb-2 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors"+ >+ <Camera size={10} />+ New Snapshot+ </button>++ {snapshots.length === 0 ? (+ <p className="text-[10px] text-muted-foreground text-center py-2">+ No snapshots yet+ </p>+ ) : (+ <div className="space-y-1">+ {snapshots.map((snapshot) => (+ <div+ key={snapshot.id}+ className="group flex items-center gap-2 px-2 py-1.5 rounded hover:bg-accent/50 transition-colors"+ >+ {editingSnapshotId === snapshot.id ? (+ <div className="flex-1 flex items-center gap-1">+ <input+ type="text"+ value={editingName}+ onChange={(e) => setEditingName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') handleSaveRename();+ if (e.key === 'Escape') handleCancelRename();+ }}+ className="flex-1 px-1 py-0.5 text-[10px] bg-background border border-border rounded"+ autoFocus+ />+ <button+ onClick={handleSaveRename}+ className="p-0.5 text-green-500 hover:text-green-400"+ >+ <Check size={10} />+ </button>+ <button+ onClick={handleCancelRename}+ className="p-0.5 text-muted-foreground hover:text-foreground"+ >+ <X size={10} />+ </button>+ </div>+ ) : (+ <>+ <button+ onClick={() => handleRestoreSnapshot(snapshot.id)}+ className="flex-1 text-left"+ >+ <p className="text-[10px] font-medium truncate">{snapshot.name}</p>+ <p className="text-[9px] text-muted-foreground">+ {formatDistanceToNow(snapshot.timestamp)}+ </p>+ </button>+ <div className="hidden group-hover:flex items-center gap-0.5">+ <button+ onClick={() => handleStartRename(snapshot.id, snapshot.name)}+ className="p-0.5 text-muted-foreground hover:text-foreground"+ >+ <Edit2 size={10} />+ </button>+ <button+ onClick={() => deleteSnapshot(snapshot.id)}+ className="p-0.5 text-muted-foreground hover:text-destructive"+ >+ <Trash2 size={10} />+ </button>+ </div>+ </>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+{entries.length === 0 ? (- <div className="flex flex-col items-center justify-center h-full py-8 text-center">+ <div className="flex flex-col items-center justify-center py-8 text-center"><Clock size={32} className="text-muted-foreground/50 mb-3" /><p className="text-xs text-muted-foreground">No history yet</p><p className="text-[10px] text-muted-foreground/70 mt-1">@@ -101,13 +252,21 @@ export function HistoryPanel() {: 'hover:bg-accent'}`}>- <div className={`mt-0.5 w-2 h-2 rounded-full flex-shrink-0 ${- isCurrent ? 'bg-primary' : isFuture ? 'bg-muted-foreground/30' : 'bg-muted-foreground/50'- }`} />+ <div+ className={`mt-0.5 w-2 h-2 rounded-full flex-shrink-0 ${+ isCurrent+ ? 'bg-primary'+ : isFuture+ ? 'bg-muted-foreground/30'+ : 'bg-muted-foreground/50'+ }`}+ /><div className="min-w-0 flex-1">- <p className={`text-xs truncate ${- isCurrent ? 'font-medium text-foreground' : 'text-muted-foreground'- }`}>+ <p+ className={`text-xs truncate ${+ isCurrent ? 'font-medium text-foreground' : 'text-muted-foreground'+ }`}+ >{entry.description}</p><p className="text-[9px] text-muted-foreground/70">diff --git a/apps/image/src/stores/history-store.ts b/apps/image/src/stores/history-store.tsindex eebbf992..9d76d02d 100644--- a/apps/image/src/stores/history-store.ts+++ b/apps/image/src/stores/history-store.ts@@ -7,6 +7,15 @@ interface HistoryEntry {timestamp: number;description: string;state: string;+ thumbnail?: string;+}++interface Snapshot {+ id: string;+ name: string;+ timestamp: number;+ state: string;+ thumbnail?: string;}interface HistoryState {@@ -15,10 +24,11 @@ interface HistoryState {maxEntries: number;isUndoing: boolean;isRedoing: boolean;+ snapshots: Snapshot[];}interface HistoryActions {- pushState: (project: Project, description: string) => void;+ pushState: (project: Project, description: string, thumbnail?: string) => void;undo: () => Project | null;redo: () => Project | null;canUndo: () => boolean;@@ -27,6 +37,13 @@ interface HistoryActions {setMaxEntries: (max: number) => void;getUndoDescription: () => string | null;getRedoDescription: () => string | null;+ createSnapshot: (name: string, project: Project, thumbnail?: string) => void;+ restoreSnapshot: (id: string) => Project | null;+ deleteSnapshot: (id: string) => void;+ renameSnapshot: (id: string, name: string) => void;+ getSnapshots: () => Snapshot[];+ getEntries: () => HistoryEntry[];+ goToEntry: (index: number) => Project | null;}const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;@@ -38,8 +55,9 @@ export const useHistoryStore = create<HistoryState & HistoryActions>()(maxEntries: 50,isUndoing: false,isRedoing: false,+ snapshots: [],- pushState: (project, description) => {+ pushState: (project, description, thumbnail) => {const { entries, currentIndex, maxEntries, isUndoing, isRedoing } = get();if (isUndoing || isRedoing) return;@@ -49,6 +67,7 @@ export const useHistoryStore = create<HistoryState & HistoryActions>()(timestamp: Date.now(),description,state: JSON.stringify(project),+ thumbnail,};let newEntries = entries.slice(0, currentIndex + 1);@@ -121,5 +140,51 @@ export const useHistoryStore = create<HistoryState & HistoryActions>()(}return null;},++ createSnapshot: (name, project, thumbnail) => {+ const { snapshots } = get();+ const snapshot: Snapshot = {+ id: generateId(),+ name,+ timestamp: Date.now(),+ state: JSON.stringify(project),+ thumbnail,+ };+ set({ snapshots: [...snapshots, snapshot] });+ },++ restoreSnapshot: (id) => {+ const { snapshots } = get();+ const snapshot = snapshots.find((s) => s.id === id);+ if (!snapshot) return null;+ return JSON.parse(snapshot.state) as Project;+ },++ deleteSnapshot: (id) => {+ const { snapshots } = get();+ set({ snapshots: snapshots.filter((s) => s.id !== id) });+ },++ renameSnapshot: (id, name) => {+ const { snapshots } = get();+ set({+ snapshots: snapshots.map((s) => (s.id === id ? { ...s, name } : s)),+ });+ },++ getSnapshots: () => {+ return get().snapshots;+ },++ getEntries: () => {+ return get().entries;+ },++ goToEntry: (index) => {+ const { entries } = get();+ if (index < 0 || index >= entries.length) return null;+ set({ currentIndex: index });+ return JSON.parse(entries[index].state) as Project;+ },})));diff --git a/apps/image/src/stores/index.ts b/apps/image/src/stores/index.tsindex 9561eb4e..591d4763 100644--- a/apps/image/src/stores/index.ts+++ b/apps/image/src/stores/index.ts@@ -1,5 +1,5 @@export { useUIStore } from './ui-store';-export type { AppView, Tool, Panel } from './ui-store';+export type { AppView, Tool, Panel, EraserSettings, SelectionToolSettings, MagicWandSettings, DodgeBurnSettings } from './ui-store';export { useProjectStore } from './project-store';@@ -7,3 +7,6 @@ export { useHistoryStore } from './history-store';export { useCanvasStore } from './canvas-store';export type { Guide, SelectionRect, DragMode, ResizeHandle } from './canvas-store';++export { useSelectionStore } from './selection-store';+export type { SelectionState } from '../types/selection';diff --git a/apps/image/src/stores/project-store.ts b/apps/image/src/stores/project-store.tsindex 280ea033..79647034 100644--- a/apps/image/src/stores/project-store.ts+++ b/apps/image/src/stores/project-store.ts@@ -20,6 +20,9 @@ import {DEFAULT_FILTER,DEFAULT_TEXT_STYLE,DEFAULT_SHAPE_STYLE,+ DEFAULT_LEVELS,+ DEFAULT_CURVES,+ DEFAULT_COLOR_BALANCE,CanvasSize,CanvasBackground,} from '../types/project';@@ -241,6 +244,11 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(cropRect: null,flipHorizontal: false,flipVertical: false,+ mask: null,+ clippingMask: false,+ levels: { ...DEFAULT_LEVELS },+ curves: { ...DEFAULT_CURVES },+ colorBalance: { ...DEFAULT_COLOR_BALANCE },};state.project.layers[id] = layer;artboard.layerIds.unshift(id);@@ -285,6 +293,11 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(content,style: DEFAULT_TEXT_STYLE,autoSize: true,+ mask: null,+ clippingMask: false,+ levels: { ...DEFAULT_LEVELS },+ curves: { ...DEFAULT_CURVES },+ colorBalance: { ...DEFAULT_COLOR_BALANCE },};state.project.layers[id] = layer;artboard.layerIds.unshift(id);@@ -328,6 +341,11 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(flipVertical: false,shapeType,shapeStyle: DEFAULT_SHAPE_STYLE,+ mask: null,+ clippingMask: false,+ levels: { ...DEFAULT_LEVELS },+ curves: { ...DEFAULT_CURVES },+ colorBalance: { ...DEFAULT_COLOR_BALANCE },};state.project.layers[id] = layer;artboard.layerIds.unshift(id);@@ -388,6 +406,11 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(strokeWidth,},points: normalizedPoints,+ mask: null,+ clippingMask: false,+ levels: { ...DEFAULT_LEVELS },+ curves: { ...DEFAULT_CURVES },+ colorBalance: { ...DEFAULT_COLOR_BALANCE },};state.project.layers[id] = layer;artboard.layerIds.unshift(id);@@ -456,6 +479,11 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(flipVertical: false,childIds,expanded: true,+ mask: null,+ clippingMask: false,+ levels: { ...DEFAULT_LEVELS },+ curves: { ...DEFAULT_CURVES },+ colorBalance: { ...DEFAULT_COLOR_BALANCE },};state.project.layers[id] = layer;diff --git a/apps/image/src/stores/selection-store.ts b/apps/image/src/stores/selection-store.tsnew file mode 100644index 00000000..0f265aef--- /dev/null+++ b/apps/image/src/stores/selection-store.ts@@ -0,0 +1,427 @@+import { create } from 'zustand';+import { subscribeWithSelector } from 'zustand/middleware';+import {+ Selection,+ SelectionState,+ SelectionType,+ SelectionMode,+ SelectionBounds,+ DEFAULT_MAGIC_WAND_OPTIONS,+ DEFAULT_COLOR_RANGE_OPTIONS,+ createEmptySelection,+ boundsFromPath,+ combineSelections,+ selectionToPath2D,+ MagicWandOptions,+ ColorRangeOptions,+} from '../types/selection';++const generateId = () => `sel-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;++interface SelectionActions {+ startSelection: (type: SelectionType, point: { x: number; y: number }) => void;+ updateSelection: (point: { x: number; y: number }) => void;+ finishSelection: () => Selection | null;+ cancelSelection: () => void;++ setActiveSelection: (selection: Selection | null) => void;+ clearSelection: () => void;+ selectAll: (bounds: SelectionBounds) => void;+ invertSelection: (canvasBounds: SelectionBounds) => void;++ featherSelection: (amount: number) => void;+ expandSelection: (amount: number) => void;+ contractSelection: (amount: number) => void;++ setSelectionMode: (mode: SelectionMode) => void;+ setMagicWandOptions: (options: Partial<MagicWandOptions>) => void;+ setColorRangeOptions: (options: Partial<ColorRangeOptions>) => void;++ saveSelection: (name?: string) => void;+ loadSelection: (id: string) => void;+ deleteSelection: (id: string) => void;++ selectByColor: (+ imageData: ImageData,+ x: number,+ y: number,+ options: MagicWandOptions+ ) => void;++ hasSelection: () => boolean;+ getSelectionPath: () => Path2D | null;+}++export const useSelectionStore = create<SelectionState & SelectionActions>()(+ subscribeWithSelector((set, get) => ({+ active: null,+ saved: [],+ mode: 'new',+ isSelecting: false,+ marching: true,+ magicWandOptions: DEFAULT_MAGIC_WAND_OPTIONS,+ colorRangeOptions: DEFAULT_COLOR_RANGE_OPTIONS,+ tempPath: [],+ startPoint: null,++ startSelection: (_type, point) => {+ set({+ isSelecting: true,+ startPoint: point,+ tempPath: [point],+ });+ },++ updateSelection: (point) => {+ const { isSelecting, startPoint, tempPath } = get();+ if (!isSelecting || !startPoint) return;++ set({ tempPath: [...tempPath, point] });+ },++ finishSelection: () => {+ const { isSelecting, startPoint, tempPath, mode, active } = get();+ if (!isSelecting || !startPoint) return null;++ let newSelection: Selection;++ if (tempPath.length === 2) {+ const bounds: SelectionBounds = {+ x: Math.min(startPoint.x, tempPath[1].x),+ y: Math.min(startPoint.y, tempPath[1].y),+ width: Math.abs(tempPath[1].x - startPoint.x),+ height: Math.abs(tempPath[1].y - startPoint.y),+ };++ newSelection = {+ ...createEmptySelection(),+ id: generateId(),+ bounds,+ path: [+ { x: bounds.x, y: bounds.y },+ { x: bounds.x + bounds.width, y: bounds.y },+ { x: bounds.x + bounds.width, y: bounds.y + bounds.height },+ { x: bounds.x, y: bounds.y + bounds.height },+ ],+ };+ } else {+ newSelection = {+ ...createEmptySelection(),+ id: generateId(),+ bounds: boundsFromPath(tempPath),+ path: tempPath,+ };+ }++ const finalSelection = active && mode !== 'new'+ ? combineSelections(active, newSelection, mode)+ : newSelection;++ set({+ active: finalSelection,+ isSelecting: false,+ tempPath: [],+ startPoint: null,+ });++ return finalSelection;+ },++ cancelSelection: () => {+ set({+ isSelecting: false,+ tempPath: [],+ startPoint: null,+ });+ },++ setActiveSelection: (selection) => {+ set({ active: selection });+ },++ clearSelection: () => {+ set({ active: null });+ },++ selectAll: (bounds) => {+ const selection: Selection = {+ id: generateId(),+ type: 'rectangular',+ bounds,+ path: [+ { x: bounds.x, y: bounds.y },+ { x: bounds.x + bounds.width, y: bounds.y },+ { x: bounds.x + bounds.width, y: bounds.y + bounds.height },+ { x: bounds.x, y: bounds.y + bounds.height },+ ],+ feather: 0,+ antiAlias: true,+ opacity: 1,+ };+ set({ active: selection });+ },++ invertSelection: (canvasBounds) => {+ const { active } = get();+ if (!active) {+ get().selectAll(canvasBounds);+ return;+ }++ const inverted: Selection = {+ ...active,+ id: generateId(),+ };+ set({ active: inverted });+ },++ featherSelection: (amount) => {+ const { active } = get();+ if (!active) return;++ set({+ active: { ...active, feather: amount },+ });+ },++ expandSelection: (amount) => {+ const { active } = get();+ if (!active) return;++ const newBounds: SelectionBounds = {+ x: active.bounds.x - amount,+ y: active.bounds.y - amount,+ width: active.bounds.width + amount * 2,+ height: active.bounds.height + amount * 2,+ };++ const newPath = active.path.map((p) => {+ const cx = active.bounds.x + active.bounds.width / 2;+ const cy = active.bounds.y + active.bounds.height / 2;+ const dx = p.x - cx;+ const dy = p.y - cy;+ const dist = Math.sqrt(dx * dx + dy * dy);+ const newDist = dist + amount;+ const scale = dist > 0 ? newDist / dist : 1;+ return {+ x: cx + dx * scale,+ y: cy + dy * scale,+ };+ });++ set({+ active: { ...active, bounds: newBounds, path: newPath },+ });+ },++ contractSelection: (amount) => {+ get().expandSelection(-amount);+ },++ setSelectionMode: (mode) => {+ set({ mode });+ },++ setMagicWandOptions: (options) => {+ set((state) => ({+ magicWandOptions: { ...state.magicWandOptions, ...options },+ }));+ },++ setColorRangeOptions: (options) => {+ set((state) => ({+ colorRangeOptions: { ...state.colorRangeOptions, ...options },+ }));+ },++ saveSelection: (_name) => {+ const { active, saved } = get();+ if (!active) return;++ const savedSelection: Selection = {+ ...active,+ id: generateId(),+ };++ set({ saved: [...saved, savedSelection] });+ },++ loadSelection: (id) => {+ const { saved, mode, active } = get();+ const selection = saved.find((s) => s.id === id);+ if (!selection) return;++ const finalSelection = active && mode !== 'new'+ ? combineSelections(active, selection, mode)+ : selection;++ set({ active: finalSelection });+ },++ deleteSelection: (id) => {+ set((state) => ({+ saved: state.saved.filter((s) => s.id !== id),+ }));+ },++ selectByColor: (imageData, x, y, options) => {+ const { mode, active } = get();++ const pixelIndex = (Math.floor(y) * imageData.width + Math.floor(x)) * 4;+ const targetR = imageData.data[pixelIndex];+ const targetG = imageData.data[pixelIndex + 1];+ const targetB = imageData.data[pixelIndex + 2];++ const visited = new Set<number>();+ const selected: { x: number; y: number }[] = [];+ const tolerance = options.tolerance;++ const colorMatch = (index: number): boolean => {+ const r = imageData.data[index];+ const g = imageData.data[index + 1];+ const b = imageData.data[index + 2];++ const diff = Math.sqrt(+ Math.pow(r - targetR, 2) ++ Math.pow(g - targetG, 2) ++ Math.pow(b - targetB, 2)+ );++ return diff <= tolerance * 1.732;+ };++ if (options.contiguous) {+ const stack: { x: number; y: number }[] = [{ x: Math.floor(x), y: Math.floor(y) }];++ while (stack.length > 0) {+ const { x: px, y: py } = stack.pop()!;+ const key = py * imageData.width + px;++ if (+ px < 0 ||+ px >= imageData.width ||+ py < 0 ||+ py >= imageData.height ||+ visited.has(key)+ ) {+ continue;+ }++ visited.add(key);+ const index = key * 4;++ if (colorMatch(index)) {+ selected.push({ x: px, y: py });+ stack.push({ x: px + 1, y: py });+ stack.push({ x: px - 1, y: py });+ stack.push({ x: px, y: py + 1 });+ stack.push({ x: px, y: py - 1 });+ }+ }+ } else {+ for (let py = 0; py < imageData.height; py++) {+ for (let px = 0; px < imageData.width; px++) {+ const index = (py * imageData.width + px) * 4;+ if (colorMatch(index)) {+ selected.push({ x: px, y: py });+ }+ }+ }+ }++ if (selected.length === 0) return;++ const bounds = boundsFromPath(selected);++ const newSelection: Selection = {+ id: generateId(),+ type: 'magic-wand',+ bounds,+ path: computeSelectionOutline(selected, imageData.width, imageData.height),+ feather: 0,+ antiAlias: true,+ opacity: 1,+ };++ const finalSelection = active && mode !== 'new'+ ? combineSelections(active, newSelection, mode)+ : newSelection;++ set({ active: finalSelection });+ },++ hasSelection: () => {+ return get().active !== null;+ },++ getSelectionPath: () => {+ const { active } = get();+ if (!active) return null;+ return selectionToPath2D(active);+ },+ }))+);++function computeSelectionOutline(+ pixels: { x: number; y: number }[],+ _width: number,+ _height: number+): { x: number; y: number }[] {+ if (pixels.length === 0) return [];++ const pixelSet = new Set(pixels.map((p) => `${p.x},${p.y}`));+ const edgePixels: { x: number; y: number }[] = [];++ for (const pixel of pixels) {+ const isEdge =+ !pixelSet.has(`${pixel.x - 1},${pixel.y}`) ||+ !pixelSet.has(`${pixel.x + 1},${pixel.y}`) ||+ !pixelSet.has(`${pixel.x},${pixel.y - 1}`) ||+ !pixelSet.has(`${pixel.x},${pixel.y + 1}`);++ if (isEdge) {+ edgePixels.push(pixel);+ }+ }++ if (edgePixels.length === 0) return pixels;++ const outline: { x: number; y: number }[] = [];+ const visited = new Set<string>();++ let current = edgePixels[0];+ outline.push(current);+ visited.add(`${current.x},${current.y}`);++ const directions = [+ { dx: 1, dy: 0 },+ { dx: 1, dy: 1 },+ { dx: 0, dy: 1 },+ { dx: -1, dy: 1 },+ { dx: -1, dy: 0 },+ { dx: -1, dy: -1 },+ { dx: 0, dy: -1 },+ { dx: 1, dy: -1 },+ ];++ for (let i = 0; i < edgePixels.length * 2; i++) {+ let found = false;++ for (const dir of directions) {+ const next = { x: current.x + dir.dx, y: current.y + dir.dy };+ const key = `${next.x},${next.y}`;++ if (!visited.has(key) && edgePixels.some((p) => p.x === next.x && p.y === next.y)) {+ outline.push(next);+ visited.add(key);+ current = next;+ found = true;+ break;+ }+ }++ if (!found) break;+ }++ return outline;+}diff --git a/apps/image/src/stores/ui-store.ts b/apps/image/src/stores/ui-store.tsindex 0d121199..f4cac453 100644--- a/apps/image/src/stores/ui-store.ts+++ b/apps/image/src/stores/ui-store.ts@@ -2,7 +2,23 @@ import { create } from 'zustand';import { subscribeWithSelector } from 'zustand/middleware';export type AppView = 'welcome' | 'editor';-export type Tool = 'select' | 'hand' | 'text' | 'shape' | 'pen' | 'eyedropper' | 'zoom' | 'crop';+export type Tool =+ | 'select'+ | 'hand'+ | 'text'+ | 'shape'+ | 'pen'+ | 'eyedropper'+ | 'zoom'+ | 'crop'+ | 'marquee-rect'+ | 'marquee-ellipse'+ | 'lasso'+ | 'lasso-polygon'+ | 'magic-wand'+ | 'eraser'+ | 'dodge'+ | 'burn';export type Panel = 'layers' | 'assets' | 'templates' | 'text' | 'shapes' | 'uploads' | 'elements';export type CropAspectRatio = 'free' | '1:1' | '4:3' | '3:4' | '16:9' | '9:16' | '3:2' | '2:3' | 'original';@@ -21,6 +37,33 @@ export interface PenSettings {smoothing: number;}+export interface EraserSettings {+ size: number;+ hardness: number;+ opacity: number;+ flow: number;+ mode: 'brush' | 'pencil' | 'block';+}++export interface SelectionToolSettings {+ feather: number;+ antiAlias: boolean;+ mode: 'new' | 'add' | 'subtract' | 'intersect';+}++export interface MagicWandSettings {+ tolerance: number;+ contiguous: boolean;+ sampleAllLayers: boolean;+}++export interface DodgeBurnSettings {+ type: 'dodge' | 'burn';+ range: 'shadows' | 'midtones' | 'highlights';+ exposure: number;+ size: number;+}+export interface DrawingState {isDrawing: boolean;currentPath: { x: number; y: number }[];@@ -51,6 +94,10 @@ interface UIState {showSettingsDialog: boolean;penSettings: PenSettings;drawing: DrawingState;+ eraserSettings: EraserSettings;+ selectionToolSettings: SelectionToolSettings;+ magicWandSettings: MagicWandSettings;+ dodgeBurnSettings: DodgeBurnSettings;}interface UIActions {@@ -91,6 +138,10 @@ interface UIActions {addDrawingPoint: (point: { x: number; y: number }) => void;finishDrawing: () => { x: number; y: number }[] | null;cancelDrawing: () => void;+ setEraserSettings: (settings: Partial<EraserSettings>) => void;+ setSelectionToolSettings: (settings: Partial<SelectionToolSettings>) => void;+ setMagicWandSettings: (settings: Partial<MagicWandSettings>) => void;+ setDodgeBurnSettings: (settings: Partial<DodgeBurnSettings>) => void;}const ZOOM_LEVELS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4, 5, 8];@@ -134,6 +185,29 @@ export const useUIStore = create<UIState & UIActions>()(isDrawing: false,currentPath: [],},+ eraserSettings: {+ size: 20,+ hardness: 100,+ opacity: 1,+ flow: 1,+ mode: 'brush',+ },+ selectionToolSettings: {+ feather: 0,+ antiAlias: true,+ mode: 'new',+ },+ magicWandSettings: {+ tolerance: 32,+ contiguous: true,+ sampleAllLayers: false,+ },+ dodgeBurnSettings: {+ type: 'dodge',+ range: 'midtones',+ exposure: 50,+ size: 30,+ },setCurrentView: (view) => set({ currentView: view }),setActiveTool: (tool) => set({ activeTool: tool }),@@ -280,5 +354,25 @@ export const useUIStore = create<UIState & UIActions>()(currentPath: [],},}),++ setEraserSettings: (settings) =>+ set((s) => ({+ eraserSettings: { ...s.eraserSettings, ...settings },+ })),++ setSelectionToolSettings: (settings) =>+ set((s) => ({+ selectionToolSettings: { ...s.selectionToolSettings, ...settings },+ })),++ setMagicWandSettings: (settings) =>+ set((s) => ({+ magicWandSettings: { ...s.magicWandSettings, ...settings },+ })),++ setDodgeBurnSettings: (settings) =>+ set((s) => ({+ dodgeBurnSettings: { ...s.dodgeBurnSettings, ...settings },+ })),})));diff --git a/apps/image/src/types/adjustments.ts b/apps/image/src/types/adjustments.tsnew file mode 100644index 00000000..3e45d845--- /dev/null+++ b/apps/image/src/types/adjustments.ts@@ -0,0 +1,620 @@+export interface LevelsChannel {+ inputBlack: number;+ inputWhite: number;+ gamma: number;+ outputBlack: number;+ outputWhite: number;+}++export interface LevelsAdjustment {+ enabled: boolean;+ master: LevelsChannel;+ red: LevelsChannel;+ green: LevelsChannel;+ blue: LevelsChannel;+}++export interface CurvePoint {+ input: number;+ output: number;+}++export interface CurvesChannel {+ points: CurvePoint[];+}++export interface CurvesAdjustment {+ enabled: boolean;+ master: CurvesChannel;+ red: CurvesChannel;+ green: CurvesChannel;+ blue: CurvesChannel;+}++export interface ColorBalanceValues {+ cyanRed: number;+ magentaGreen: number;+ yellowBlue: number;+}++export interface ColorBalanceAdjustment {+ enabled: boolean;+ shadows: ColorBalanceValues;+ midtones: ColorBalanceValues;+ highlights: ColorBalanceValues;+ preserveLuminosity: boolean;+}++export interface SelectiveColorValues {+ cyan: number;+ magenta: number;+ yellow: number;+ black: number;+}++export type SelectiveColorTarget =+ | 'reds'+ | 'yellows'+ | 'greens'+ | 'cyans'+ | 'blues'+ | 'magentas'+ | 'whites'+ | 'neutrals'+ | 'blacks';++export interface SelectiveColorAdjustment {+ enabled: boolean;+ method: 'relative' | 'absolute';+ reds: SelectiveColorValues;+ yellows: SelectiveColorValues;+ greens: SelectiveColorValues;+ cyans: SelectiveColorValues;+ blues: SelectiveColorValues;+ magentas: SelectiveColorValues;+ whites: SelectiveColorValues;+ neutrals: SelectiveColorValues;+ blacks: SelectiveColorValues;+}++export interface BlackWhiteAdjustment {+ enabled: boolean;+ reds: number;+ yellows: number;+ greens: number;+ cyans: number;+ blues: number;+ magentas: number;+ tintEnabled: boolean;+ tintHue: number;+ tintSaturation: number;+}++export interface GradientMapStop {+ position: number;+ color: string;+}++export interface GradientMapAdjustment {+ enabled: boolean;+ stops: GradientMapStop[];+ reverse: boolean;+ dither: boolean;+}++export interface PosterizeAdjustment {+ enabled: boolean;+ levels: number;+}++export interface ThresholdAdjustment {+ enabled: boolean;+ level: number;+}++export interface PhotoFilterAdjustment {+ enabled: boolean;+ filter: 'warming-85' | 'warming-81' | 'cooling-80' | 'cooling-82' | 'custom';+ color: string;+ density: number;+ preserveLuminosity: boolean;+}++export interface ChannelMixerChannel {+ red: number;+ green: number;+ blue: number;+ constant: number;+}++export interface ChannelMixerAdjustment {+ enabled: boolean;+ monochrome: boolean;+ red: ChannelMixerChannel;+ green: ChannelMixerChannel;+ blue: ChannelMixerChannel;+}++export const DEFAULT_LEVELS_CHANNEL: LevelsChannel = {+ inputBlack: 0,+ inputWhite: 255,+ gamma: 1.0,+ outputBlack: 0,+ outputWhite: 255,+};++export const DEFAULT_LEVELS: LevelsAdjustment = {+ enabled: false,+ master: { ...DEFAULT_LEVELS_CHANNEL },+ red: { ...DEFAULT_LEVELS_CHANNEL },+ green: { ...DEFAULT_LEVELS_CHANNEL },+ blue: { ...DEFAULT_LEVELS_CHANNEL },+};++export const DEFAULT_CURVES_CHANNEL: CurvesChannel = {+ points: [+ { input: 0, output: 0 },+ { input: 255, output: 255 },+ ],+};++export const DEFAULT_CURVES: CurvesAdjustment = {+ enabled: false,+ master: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },+ red: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },+ green: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },+ blue: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },+};++export const DEFAULT_COLOR_BALANCE_VALUES: ColorBalanceValues = {+ cyanRed: 0,+ magentaGreen: 0,+ yellowBlue: 0,+};++export const DEFAULT_COLOR_BALANCE: ColorBalanceAdjustment = {+ enabled: false,+ shadows: { ...DEFAULT_COLOR_BALANCE_VALUES },+ midtones: { ...DEFAULT_COLOR_BALANCE_VALUES },+ highlights: { ...DEFAULT_COLOR_BALANCE_VALUES },+ preserveLuminosity: true,+};++export const DEFAULT_SELECTIVE_COLOR_VALUES: SelectiveColorValues = {+ cyan: 0,+ magenta: 0,+ yellow: 0,+ black: 0,+};++export const DEFAULT_SELECTIVE_COLOR: SelectiveColorAdjustment = {+ enabled: false,+ method: 'relative',+ reds: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ yellows: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ greens: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ cyans: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ blues: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ magentas: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ whites: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ neutrals: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ blacks: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+};++export const DEFAULT_BLACK_WHITE: BlackWhiteAdjustment = {+ enabled: false,+ reds: 40,+ yellows: 60,+ greens: 40,+ cyans: 60,+ blues: 20,+ magentas: 80,+ tintEnabled: false,+ tintHue: 35,+ tintSaturation: 25,+};++export const DEFAULT_GRADIENT_MAP: GradientMapAdjustment = {+ enabled: false,+ stops: [+ { position: 0, color: '#000000' },+ { position: 1, color: '#ffffff' },+ ],+ reverse: false,+ dither: false,+};++export const DEFAULT_POSTERIZE: PosterizeAdjustment = {+ enabled: false,+ levels: 4,+};++export const DEFAULT_THRESHOLD: ThresholdAdjustment = {+ enabled: false,+ level: 128,+};++export const DEFAULT_PHOTO_FILTER: PhotoFilterAdjustment = {+ enabled: false,+ filter: 'warming-85',+ color: '#ec8a00',+ density: 25,+ preserveLuminosity: true,+};++export const DEFAULT_CHANNEL_MIXER: ChannelMixerAdjustment = {+ enabled: false,+ monochrome: false,+ red: { red: 100, green: 0, blue: 0, constant: 0 },+ green: { red: 0, green: 100, blue: 0, constant: 0 },+ blue: { red: 0, green: 0, blue: 100, constant: 0 },+};++export function applyLevels(value: number, channel: LevelsChannel): number {+ let v = value;++ v = Math.max(channel.inputBlack, Math.min(channel.inputWhite, v));+ v = ((v - channel.inputBlack) / (channel.inputWhite - channel.inputBlack)) * 255;++ v = 255 * Math.pow(v / 255, 1 / channel.gamma);++ v = channel.outputBlack + (v / 255) * (channel.outputWhite - channel.outputBlack);++ return Math.max(0, Math.min(255, Math.round(v)));+}++export function interpolateCurve(value: number, points: CurvePoint[]): number {+ if (points.length === 0) return value;+ if (points.length === 1) return points[0].output;++ const sortedPoints = [...points].sort((a, b) => a.input - b.input);++ if (value <= sortedPoints[0].input) return sortedPoints[0].output;+ if (value >= sortedPoints[sortedPoints.length - 1].input) {+ return sortedPoints[sortedPoints.length - 1].output;+ }++ for (let i = 0; i < sortedPoints.length - 1; i++) {+ const p1 = sortedPoints[i];+ const p2 = sortedPoints[i + 1];++ if (value >= p1.input && value <= p2.input) {+ const t = (value - p1.input) / (p2.input - p1.input);++ if (sortedPoints.length >= 4 && i > 0 && i < sortedPoints.length - 2) {+ const p0 = sortedPoints[i - 1];+ const p3 = sortedPoints[i + 2];+ return catmullRomInterpolate(p0.output, p1.output, p2.output, p3.output, t);+ }++ return p1.output + t * (p2.output - p1.output);+ }+ }++ return value;+}++function catmullRomInterpolate(+ p0: number,+ p1: number,+ p2: number,+ p3: number,+ t: number+): number {+ const t2 = t * t;+ const t3 = t2 * t;++ return (+ 0.5 *+ (2 * p1 ++ (-p0 + p2) * t ++ (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 ++ (-p0 + 3 * p1 - 3 * p2 + p3) * t3)+ );+}++export function applyLevelsToImageData(+ imageData: ImageData,+ levels: LevelsAdjustment+): ImageData {+ if (!levels.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ let r = imageData.data[i];+ let g = imageData.data[i + 1];+ let b = imageData.data[i + 2];++ r = applyLevels(r, levels.master);+ g = applyLevels(g, levels.master);+ b = applyLevels(b, levels.master);++ r = applyLevels(r, levels.red);+ g = applyLevels(g, levels.green);+ b = applyLevels(b, levels.blue);++ result.data[i] = r;+ result.data[i + 1] = g;+ result.data[i + 2] = b;+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyCurvesToImageData(+ imageData: ImageData,+ curves: CurvesAdjustment+): ImageData {+ if (!curves.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ let r = imageData.data[i];+ let g = imageData.data[i + 1];+ let b = imageData.data[i + 2];++ r = interpolateCurve(r, curves.master.points);+ g = interpolateCurve(g, curves.master.points);+ b = interpolateCurve(b, curves.master.points);++ r = interpolateCurve(r, curves.red.points);+ g = interpolateCurve(g, curves.green.points);+ b = interpolateCurve(b, curves.blue.points);++ result.data[i] = Math.max(0, Math.min(255, Math.round(r)));+ result.data[i + 1] = Math.max(0, Math.min(255, Math.round(g)));+ result.data[i + 2] = Math.max(0, Math.min(255, Math.round(b)));+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyColorBalanceToImageData(+ imageData: ImageData,+ colorBalance: ColorBalanceAdjustment+): ImageData {+ if (!colorBalance.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ let r = imageData.data[i];+ let g = imageData.data[i + 1];+ let b = imageData.data[i + 2];++ const luminance = 0.299 * r + 0.587 * g + 0.114 * b;++ const shadowWeight = Math.max(0, 1 - luminance / 128);+ const highlightWeight = Math.max(0, (luminance - 128) / 127);+ const midtoneWeight = 1 - shadowWeight - highlightWeight;++ const adjustR =+ colorBalance.shadows.cyanRed * shadowWeight ++ colorBalance.midtones.cyanRed * midtoneWeight ++ colorBalance.highlights.cyanRed * highlightWeight;++ const adjustG =+ colorBalance.shadows.magentaGreen * shadowWeight ++ colorBalance.midtones.magentaGreen * midtoneWeight ++ colorBalance.highlights.magentaGreen * highlightWeight;++ const adjustB =+ colorBalance.shadows.yellowBlue * shadowWeight ++ colorBalance.midtones.yellowBlue * midtoneWeight ++ colorBalance.highlights.yellowBlue * highlightWeight;++ r = Math.max(0, Math.min(255, r + adjustR));+ g = Math.max(0, Math.min(255, g + adjustG));+ b = Math.max(0, Math.min(255, b + adjustB));++ if (colorBalance.preserveLuminosity) {+ const newLuminance = 0.299 * r + 0.587 * g + 0.114 * b;+ if (newLuminance > 0) {+ const factor = luminance / newLuminance;+ r = Math.max(0, Math.min(255, r * factor));+ g = Math.max(0, Math.min(255, g * factor));+ b = Math.max(0, Math.min(255, b * factor));+ }+ }++ result.data[i] = Math.round(r);+ result.data[i + 1] = Math.round(g);+ result.data[i + 2] = Math.round(b);+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyThresholdToImageData(+ imageData: ImageData,+ threshold: ThresholdAdjustment+): ImageData {+ if (!threshold.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ const r = imageData.data[i];+ const g = imageData.data[i + 1];+ const b = imageData.data[i + 2];++ const luminance = 0.299 * r + 0.587 * g + 0.114 * b;+ const value = luminance >= threshold.level ? 255 : 0;++ result.data[i] = value;+ result.data[i + 1] = value;+ result.data[i + 2] = value;+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyPosterizeToImageData(+ imageData: ImageData,+ posterize: PosterizeAdjustment+): ImageData {+ if (!posterize.enabled || posterize.levels < 2) return imageData;++ const result = new ImageData(imageData.width, imageData.height);+ const step = 255 / (posterize.levels - 1);++ for (let i = 0; i < imageData.data.length; i += 4) {+ result.data[i] = Math.round(Math.round(imageData.data[i] / step) * step);+ result.data[i + 1] = Math.round(Math.round(imageData.data[i + 1] / step) * step);+ result.data[i + 2] = Math.round(Math.round(imageData.data[i + 2] / step) * step);+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyBlackWhiteToImageData(+ imageData: ImageData,+ bw: BlackWhiteAdjustment+): ImageData {+ if (!bw.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ const r = imageData.data[i];+ const g = imageData.data[i + 1];+ const b = imageData.data[i + 2];++ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const delta = max - min;++ let hue = 0;+ if (delta > 0) {+ if (max === r) {+ hue = ((g - b) / delta) % 6;+ } else if (max === g) {+ hue = (b - r) / delta + 2;+ } else {+ hue = (r - g) / delta + 4;+ }+ hue *= 60;+ if (hue < 0) hue += 360;+ }++ let weight = 0;+ if (hue < 30 || hue >= 330) {+ weight = bw.reds / 100;+ } else if (hue < 90) {+ weight = bw.yellows / 100;+ } else if (hue < 150) {+ weight = bw.greens / 100;+ } else if (hue < 210) {+ weight = bw.cyans / 100;+ } else if (hue < 270) {+ weight = bw.blues / 100;+ } else {+ weight = bw.magentas / 100;+ }++ let gray = 0.299 * r + 0.587 * g + 0.114 * b;+ gray = gray * (1 + weight * 0.5);+ gray = Math.max(0, Math.min(255, gray));++ let finalR = gray;+ let finalG = gray;+ let finalB = gray;++ if (bw.tintEnabled) {+ const tintH = bw.tintHue / 360;+ const tintS = bw.tintSaturation / 100;+ const tintL = gray / 255;++ const c = (1 - Math.abs(2 * tintL - 1)) * tintS;+ const x = c * (1 - Math.abs((tintH * 6) % 2 - 1));+ const m = tintL - c / 2;++ let rTint = 0, gTint = 0, bTint = 0;+ const h6 = tintH * 6;+ if (h6 < 1) { rTint = c; gTint = x; }+ else if (h6 < 2) { rTint = x; gTint = c; }+ else if (h6 < 3) { gTint = c; bTint = x; }+ else if (h6 < 4) { gTint = x; bTint = c; }+ else if (h6 < 5) { rTint = x; bTint = c; }+ else { rTint = c; bTint = x; }++ finalR = (rTint + m) * 255;+ finalG = (gTint + m) * 255;+ finalB = (bTint + m) * 255;+ }++ result.data[i] = Math.round(finalR);+ result.data[i + 1] = Math.round(finalG);+ result.data[i + 2] = Math.round(finalB);+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyGradientMapToImageData(+ imageData: ImageData,+ gradientMap: GradientMapAdjustment+): ImageData {+ if (!gradientMap.enabled || gradientMap.stops.length < 2) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ const stops = gradientMap.reverse+ ? [...gradientMap.stops].reverse().map((s, i, arr) => ({+ ...s,+ position: 1 - arr[arr.length - 1 - i].position,+ }))+ : gradientMap.stops;++ const sortedStops = [...stops].sort((a, b) => a.position - b.position);++ for (let i = 0; i < imageData.data.length; i += 4) {+ const r = imageData.data[i];+ const g = imageData.data[i + 1];+ const b = imageData.data[i + 2];++ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;++ let color1 = sortedStops[0];+ let color2 = sortedStops[sortedStops.length - 1];++ for (let j = 0; j < sortedStops.length - 1; j++) {+ if (luminance >= sortedStops[j].position && luminance <= sortedStops[j + 1].position) {+ color1 = sortedStops[j];+ color2 = sortedStops[j + 1];+ break;+ }+ }++ const t = (luminance - color1.position) / (color2.position - color1.position || 1);++ const c1 = hexToRgb(color1.color);+ const c2 = hexToRgb(color2.color);++ result.data[i] = Math.round(c1.r + t * (c2.r - c1.r));+ result.data[i + 1] = Math.round(c1.g + t * (c2.g - c1.g));+ result.data[i + 2] = Math.round(c1.b + t * (c2.b - c1.b));+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++function hexToRgb(hex: string): { r: number; g: number; b: number } {+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);+ return result+ ? {+ r: parseInt(result[1], 16),+ g: parseInt(result[2], 16),+ b: parseInt(result[3], 16),+ }+ : { r: 0, g: 0, b: 0 };+}diff --git a/apps/image/src/types/mask.ts b/apps/image/src/types/mask.tsnew file mode 100644index 00000000..e13ae922--- /dev/null+++ b/apps/image/src/types/mask.ts@@ -0,0 +1,168 @@+export type MaskType = 'pixel' | 'vector';++export interface LayerMask {+ id: string;+ type: MaskType;+ enabled: boolean;+ linked: boolean;+ density: number;+ feather: number;+ invert: boolean;+ data: string | null;+ vectorPath: { x: number; y: number }[] | null;+}++export const DEFAULT_LAYER_MASK: LayerMask = {+ id: '',+ type: 'pixel',+ enabled: true,+ linked: true,+ density: 100,+ feather: 0,+ invert: false,+ data: null,+ vectorPath: null,+};++export function createMaskFromSelection(+ selectionPath: { x: number; y: number }[],+ width: number,+ height: number,+ feather: number = 0+): string {+ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext('2d')!;++ ctx.fillStyle = 'white';+ ctx.beginPath();++ if (selectionPath.length > 0) {+ ctx.moveTo(selectionPath[0].x, selectionPath[0].y);+ for (let i = 1; i < selectionPath.length; i++) {+ ctx.lineTo(selectionPath[i].x, selectionPath[i].y);+ }+ ctx.closePath();+ ctx.fill();+ }++ if (feather > 0) {+ const tempCanvas = new OffscreenCanvas(width, height);+ const tempCtx = tempCanvas.getContext('2d')!;+ tempCtx.filter = `blur(${feather}px)`;+ tempCtx.drawImage(canvas, 0, 0);++ ctx.clearRect(0, 0, width, height);+ ctx.drawImage(tempCanvas, 0, 0);+ }++ return canvas.convertToBlob().then(() => {+ const reader = new FileReader();+ return new Promise<string>((resolve) => {+ canvas.convertToBlob().then((blob) => {+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(blob);+ });+ });+ }) as unknown as string;+}++export function createMaskFromImageData(imageData: ImageData): string {+ const canvas = new OffscreenCanvas(imageData.width, imageData.height);+ const ctx = canvas.getContext('2d')!;+ ctx.putImageData(imageData, 0, 0);++ return canvas.convertToBlob().then(() => {+ return new Promise<string>((resolve) => {+ canvas.convertToBlob().then((blob) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(blob);+ });+ });+ }) as unknown as string;+}++export function applyMaskToImageData(+ imageData: ImageData,+ mask: LayerMask,+ maskImage: HTMLImageElement | null+): ImageData {+ if (!mask.enabled || !maskImage) {+ return imageData;+ }++ const canvas = new OffscreenCanvas(imageData.width, imageData.height);+ const ctx = canvas.getContext('2d')!;++ ctx.drawImage(maskImage, 0, 0, imageData.width, imageData.height);+ const maskData = ctx.getImageData(0, 0, imageData.width, imageData.height);++ const result = new ImageData(imageData.width, imageData.height);+ const density = mask.density / 100;++ for (let i = 0; i < imageData.data.length; i += 4) {+ result.data[i] = imageData.data[i];+ result.data[i + 1] = imageData.data[i + 1];+ result.data[i + 2] = imageData.data[i + 2];++ let maskAlpha = maskData.data[i];+ if (mask.invert) {+ maskAlpha = 255 - maskAlpha;+ }+ maskAlpha = Math.round(maskAlpha * density);++ result.data[i + 3] = Math.round((imageData.data[i + 3] * maskAlpha) / 255);+ }++ return result;+}++export function invertMask(maskDataUrl: string, width: number, height: number): Promise<string> {+ return new Promise((resolve) => {+ const img = new Image();+ img.onload = () => {+ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext('2d')!;+ ctx.drawImage(img, 0, 0);++ const imageData = ctx.getImageData(0, 0, width, height);+ for (let i = 0; i < imageData.data.length; i += 4) {+ imageData.data[i] = 255 - imageData.data[i];+ imageData.data[i + 1] = 255 - imageData.data[i + 1];+ imageData.data[i + 2] = 255 - imageData.data[i + 2];+ }+ ctx.putImageData(imageData, 0, 0);++ canvas.convertToBlob().then((blob) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(blob);+ });+ };+ img.src = maskDataUrl;+ });+}++export function featherMask(+ maskDataUrl: string,+ width: number,+ height: number,+ featherAmount: number+): Promise<string> {+ return new Promise((resolve) => {+ const img = new Image();+ img.onload = () => {+ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext('2d')!;+ ctx.filter = `blur(${featherAmount}px)`;+ ctx.drawImage(img, 0, 0);++ canvas.convertToBlob().then((blob) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(blob);+ });+ };+ img.src = maskDataUrl;+ });+}diff --git a/apps/image/src/types/project.ts b/apps/image/src/types/project.tsindex f9e54449..44693561 100644--- a/apps/image/src/types/project.ts+++ b/apps/image/src/types/project.ts@@ -1,3 +1,10 @@+import type { LayerMask } from './mask';+import type {+ LevelsAdjustment,+ CurvesAdjustment,+ ColorBalanceAdjustment,+} from './adjustments';+export type LayerType = 'image' | 'text' | 'shape' | 'group';export interface Transform {@@ -85,6 +92,11 @@ export interface BaseLayer {parentId: string | null;flipHorizontal: boolean;flipVertical: boolean;+ mask: LayerMask | null;+ clippingMask: boolean;+ levels: LevelsAdjustment;+ curves: CurvesAdjustment;+ colorBalance: ColorBalanceAdjustment;}export interface ImageLayer extends BaseLayer {@@ -299,6 +311,9 @@ export const DEFAULT_INNER_SHADOW: InnerShadow = {offsetY: 2,};+export { DEFAULT_LAYER_MASK } from './mask';+export { DEFAULT_LEVELS, DEFAULT_CURVES, DEFAULT_COLOR_BALANCE } from './adjustments';+export const DEFAULT_FILTER: Filter = {brightness: 100,contrast: 100,diff --git a/apps/image/src/types/selection.ts b/apps/image/src/types/selection.tsnew file mode 100644index 00000000..1e1d1fdd--- /dev/null+++ b/apps/image/src/types/selection.ts@@ -0,0 +1,187 @@+export type SelectionType =+ | 'rectangular'+ | 'elliptical'+ | 'lasso'+ | 'polygonal'+ | 'magic-wand'+ | 'color-range';++export type SelectionMode = 'new' | 'add' | 'subtract' | 'intersect';++export interface SelectionBounds {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface Selection {+ id: string;+ type: SelectionType;+ bounds: SelectionBounds;+ path: { x: number; y: number }[];+ feather: number;+ antiAlias: boolean;+ opacity: number;+}++export interface MagicWandOptions {+ tolerance: number;+ contiguous: boolean;+ sampleAllLayers: boolean;+}++export interface ColorRangeOptions {+ fuzziness: number;+ range: 'sampled' | 'reds' | 'yellows' | 'greens' | 'cyans' | 'blues' | 'magentas' | 'highlights' | 'midtones' | 'shadows';+ invert: boolean;+}++export interface SelectionState {+ active: Selection | null;+ saved: Selection[];+ mode: SelectionMode;+ isSelecting: boolean;+ marching: boolean;+ magicWandOptions: MagicWandOptions;+ colorRangeOptions: ColorRangeOptions;+ tempPath: { x: number; y: number }[];+ startPoint: { x: number; y: number } | null;+}++export const DEFAULT_MAGIC_WAND_OPTIONS: MagicWandOptions = {+ tolerance: 32,+ contiguous: true,+ sampleAllLayers: false,+};++export const DEFAULT_COLOR_RANGE_OPTIONS: ColorRangeOptions = {+ fuzziness: 40,+ range: 'sampled',+ invert: false,+};++export function createEmptySelection(): Selection {+ return {+ id: '',+ type: 'rectangular',+ bounds: { x: 0, y: 0, width: 0, height: 0 },+ path: [],+ feather: 0,+ antiAlias: true,+ opacity: 1,+ };+}++export function selectionToPath2D(selection: Selection): Path2D {+ const path = new Path2D();++ if (selection.type === 'rectangular') {+ path.rect(+ selection.bounds.x,+ selection.bounds.y,+ selection.bounds.width,+ selection.bounds.height+ );+ } else if (selection.type === 'elliptical') {+ const cx = selection.bounds.x + selection.bounds.width / 2;+ const cy = selection.bounds.y + selection.bounds.height / 2;+ const rx = selection.bounds.width / 2;+ const ry = selection.bounds.height / 2;+ path.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);+ } else if (selection.path.length > 0) {+ path.moveTo(selection.path[0].x, selection.path[0].y);+ for (let i = 1; i < selection.path.length; i++) {+ path.lineTo(selection.path[i].x, selection.path[i].y);+ }+ path.closePath();+ }++ return path;+}++export function boundsFromPath(points: { x: number; y: number }[]): SelectionBounds {+ if (points.length === 0) {+ return { x: 0, y: 0, width: 0, height: 0 };+ }++ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (const point of points) {+ minX = Math.min(minX, point.x);+ minY = Math.min(minY, point.y);+ maxX = Math.max(maxX, point.x);+ maxY = Math.max(maxY, point.y);+ }++ return {+ x: minX,+ y: minY,+ width: maxX - minX,+ height: maxY - minY,+ };+}++export function isPointInSelection(+ x: number,+ y: number,+ selection: Selection,+ ctx?: CanvasRenderingContext2D+): boolean {+ if (!ctx) return false;++ const path = selectionToPath2D(selection);+ return ctx.isPointInPath(path, x, y);+}++export function combineSelections(+ existing: Selection,+ newSelection: Selection,+ mode: SelectionMode+): Selection {+ if (mode === 'new') {+ return newSelection;+ }++ const combined: Selection = {+ ...newSelection,+ id: existing.id || newSelection.id,+ };++ if (mode === 'add') {+ combined.path = [...existing.path, ...newSelection.path];+ combined.bounds = boundsFromPath(combined.path);+ } else if (mode === 'subtract') {+ combined.path = existing.path;+ combined.bounds = existing.bounds;+ } else if (mode === 'intersect') {+ combined.path = existing.path;+ combined.bounds = existing.bounds;+ }++ return combined;+}++export function getSelectionMask(+ selection: Selection,+ width: number,+ height: number+): ImageData {+ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext('2d')!;++ ctx.fillStyle = 'white';+ const path = selectionToPath2D(selection);+ ctx.fill(path);++ if (selection.feather > 0) {+ ctx.filter = `blur(${selection.feather}px)`;+ ctx.drawImage(canvas, 0, 0);+ ctx.filter = 'none';+ }++ return ctx.getImageData(0, 0, width, height);+}