Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

fix(image): comprehensive paint tools and editor fixes

Augustus Otucb71e3de562d
diff --git a/apps/image/src/components/editor/canvas/Canvas.tsx b/apps/image/src/components/editor/canvas/Canvas.tsx
index 443070f1..0cc9ce51 100644
--- a/apps/image/src/components/editor/canvas/Canvas.tsx
+++ b/apps/image/src/components/editor/canvas/Canvas.tsx
@@ -7,6 +7,18 @@ import type { Layer, ImageLayer, TextLayer, ShapeLayer, GroupLayer } from '../..
import { Rulers } from './Rulers';
import { ContextMenu, type ContextMenuPosition, type ContextMenuType } from './ContextMenu';
import { hasActiveAdjustments, applyAllAdjustments, type LayerAdjustments } from '../../../utils/apply-adjustments';
+import { getToolCursor } from '../../../utils/cursors';
+import { floodFill, type FloodFillOptions } from '../../../utils/flood-fill';
+import { SmudgeTool } from '../../../tools/paint/smudge';
+import { BlurSharpenTool } from '../../../tools/paint/blur-sharpen';
+import { EraserTool } from '../../../tools/paint/eraser';
+import { BrushTool } from '../../../tools/paint/brush';
+import { DEFAULT_BRUSH_DYNAMICS } from '../../../tools/brush/brush-engine';
+import { DodgeBurnTool } from '../../../tools/retouch/dodge-burn';
+import { SpongeTool } from '../../../tools/retouch/sponge';
+import { CloneStampTool } from '../../../tools/retouch/clone-stamp';
+import { HealingBrushTool } from '../../../tools/retouch/healing-brush';
+import { SpotHealingTool } from '../../../tools/retouch/spot-healing';
const RULER_SIZE = 20;
const HANDLE_SIZE = 8;
@@ -46,8 +58,9 @@ function getLayerHash(
let contentHash = '';
if (layer.type === 'image') {
const imgLayer = layer as ImageLayer;
- const { filters } = imgLayer;
- contentHash = `img-${imgLayer.sourceId}-${filters.brightness}-${filters.contrast}-${filters.saturation}-${filters.hue}-${filters.blur}-${filters.blurType}-${filters.sepia}-${filters.invert}-${filters.exposure}-${filters.highlights}-${filters.shadows}-${filters.clarity}-${filters.vibrance}`;
+ const { filters, cropRect } = imgLayer;
+ const cropHash = cropRect ? `${cropRect.x}-${cropRect.y}-${cropRect.width}-${cropRect.height}` : 'no-crop';
+ contentHash = `img-${imgLayer.sourceId}-${cropHash}-${filters.brightness}-${filters.contrast}-${filters.saturation}-${filters.hue}-${filters.blur}-${filters.blurType}-${filters.sepia}-${filters.invert}-${filters.exposure}-${filters.highlights}-${filters.shadows}-${filters.clarity}-${filters.vibrance}`;
} else if (layer.type === 'text') {
const textLayer = layer as TextLayer;
const { style, content } = textLayer;
@@ -131,8 +144,11 @@ function clearLayerCache(layerIds?: Set<string>): void {
});
}
+const failedImages = new Set<string>();
+
function getCachedImage(src: string): HTMLImageElement | null {
if (!src) return null;
+ if (failedImages.has(src)) return null;
const cached = imageCache.get(src);
if (cached && cached.complete && cached.naturalWidth > 0) {
@@ -157,17 +173,26 @@ function getCachedImage(src: string): HTMLImageElement | null {
}
const img = new window.Image();
- img.src = src;
imageCache.set(src, img);
imageCacheOrder.push(src);
- if (!img.complete) {
- img.onload = () => {
- if (renderCallback) {
- renderCallback();
- }
- };
- }
+ img.onload = () => {
+ if (renderCallback) {
+ renderCallback();
+ }
+ };
+
+ img.onerror = () => {
+ failedImages.add(src);
+ imageCache.delete(src);
+ const idx = imageCacheOrder.indexOf(src);
+ if (idx > -1) {
+ imageCacheOrder.splice(idx, 1);
+ }
+ console.warn(`Failed to load image: ${src.substring(0, 100)}`);
+ };
+
+ img.src = src;
}
const img = imageCache.get(src);
@@ -253,7 +278,7 @@ export function Canvas() {
groupLayers,
ungroupLayers,
} = useProjectStore();
- const { zoom, panX, panY, setPan, setZoom, activeTool, showGrid, showRulers, toggleGrid, toggleRulers, gridSize, crop, snapToObjects, snapToGuides, snapToGrid, penSettings, drawing, startDrawing, addDrawingPoint, finishDrawing } = useUIStore();
+ const { zoom, panX, panY, setPan, setZoom, activeTool, showGrid, showRulers, toggleGrid, toggleRulers, gridSize, crop, snapToObjects, snapToGuides, snapToGrid, penSettings, brushSettings, eraserSettings, drawing, startDrawing, addDrawingPoint, finishDrawing, startCrop, updateCropRect, setBrushSettings, gradientSettings, paintBucketSettings, smudgeSettings, blurSharpenSettings, dodgeBurnSettings, spongeSettings, cloneStampSettings, healingBrushSettings, spotHealingSettings } = useUIStore();
const { setCanvasRef, setContainerRef, startDrag, updateDrag, endDrag, isDragging, dragMode, dragStartX, dragStartY, dragCurrentX, dragCurrentY, guides, smartGuides, setSmartGuides, clearSmartGuides, isMarqueeSelecting, marqueeRect, startMarqueeSelect, updateMarqueeSelect, endMarqueeSelect, activeResizeHandle, setActiveResizeHandle } = useCanvasStore();
const [cursorStyle, setCursorStyle] = useState('default');
const initialTransformRef = useRef<{ x: number; y: number; width: number; height: number; rotation: number } | null>(null);
@@ -263,6 +288,26 @@ export function Canvas() {
type: ContextMenuType;
} | null>(null);
+ const [gradientDrag, setGradientDrag] = useState<{
+ startX: number;
+ startY: number;
+ endX: number;
+ endY: number;
+ layerId: string;
+ } | null>(null);
+
+ const smudgeToolRef = useRef<SmudgeTool | null>(null);
+ const blurSharpenToolRef = useRef<BlurSharpenTool | null>(null);
+ const eraserToolRef = useRef<EraserTool | null>(null);
+ const brushToolRef = useRef<BrushTool | null>(null);
+ const dodgeBurnToolRef = useRef<DodgeBurnTool | null>(null);
+ const spongeToolRef = useRef<SpongeTool | null>(null);
+ const cloneStampToolRef = useRef<CloneStampTool | null>(null);
+ const healingBrushToolRef = useRef<HealingBrushTool | null>(null);
+ const spotHealingToolRef = useRef<SpotHealingTool | null>(null);
+ const paintCanvasRef = useRef<OffscreenCanvas | null>(null);
+ const paintLayerIdRef = useRef<string | null>(null);
+
const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);
useEffect(() => {
@@ -285,7 +330,9 @@ export function Canvas() {
canvas.height = container.clientHeight;
}
- const renderHash = `${zoom}-${panX}-${panY}-${selectedLayerIds.join(',')}-${project.updatedAt}-${showGrid}-${drawing.isDrawing}-${isMarqueeSelecting}`;
+ const marqueeHash = marqueeRect ? `${marqueeRect.x}-${marqueeRect.y}-${marqueeRect.width}-${marqueeRect.height}` : 'none';
+ const gradientHash = gradientDrag ? `${gradientDrag.startX}-${gradientDrag.startY}-${gradientDrag.endX}-${gradientDrag.endY}` : 'none';
+ const renderHash = `${zoom}-${panX}-${panY}-${selectedLayerIds.join(',')}-${project.updatedAt}-${showGrid}-${drawing.isDrawing}-${drawing.currentPath?.length ?? 0}-${isMarqueeSelecting}-${marqueeHash}-${gradientHash}`;
if (renderHash === lastRenderHashRef.current && !forceRenderRef.current) {
return;
}
@@ -415,11 +462,17 @@ export function Canvas() {
if (drawing.isDrawing && drawing.currentPath.length > 1) {
ctx.save();
- ctx.strokeStyle = penSettings.color;
- ctx.lineWidth = penSettings.width;
+ if (activeTool === 'brush') {
+ ctx.strokeStyle = brushSettings.color;
+ ctx.lineWidth = brushSettings.size;
+ ctx.globalAlpha = brushSettings.opacity;
+ } else {
+ ctx.strokeStyle = penSettings.color;
+ ctx.lineWidth = penSettings.width;
+ ctx.globalAlpha = penSettings.opacity;
+ }
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
- ctx.globalAlpha = penSettings.opacity;
ctx.beginPath();
ctx.moveTo(
@@ -438,6 +491,62 @@ export function Canvas() {
ctx.restore();
}
+ if (gradientDrag && activeTool === 'gradient') {
+ ctx.save();
+
+ const gStartX = artboardX + gradientDrag.startX * zoom;
+ const gStartY = artboardY + gradientDrag.startY * zoom;
+ const gEndX = artboardX + gradientDrag.endX * zoom;
+ const gEndY = artboardY + gradientDrag.endY * zoom;
+
+ const colors = gradientSettings.reverse
+ ? [...gradientSettings.colors].reverse()
+ : gradientSettings.colors;
+
+ const minX = Math.min(gStartX, gEndX);
+ const minY = Math.min(gStartY, gEndY);
+ const maxX = Math.max(gStartX, gEndX);
+ const maxY = Math.max(gStartY, gEndY);
+ const previewWidth = Math.max(maxX - minX, 50);
+ const previewHeight = Math.max(maxY - minY, 50);
+
+ let gradient: CanvasGradient;
+ if (gradientSettings.type === 'radial') {
+ const centerX = (gStartX + gEndX) / 2;
+ const centerY = (gStartY + gEndY) / 2;
+ const radius = Math.sqrt(previewWidth ** 2 + previewHeight ** 2) / 2;
+ gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
+ } else {
+ gradient = ctx.createLinearGradient(gStartX, gStartY, gEndX, gEndY);
+ }
+
+ colors.forEach((color, i) => {
+ gradient.addColorStop(i / Math.max(colors.length - 1, 1), color);
+ });
+
+ ctx.fillStyle = gradient;
+ ctx.globalAlpha = gradientSettings.opacity;
+ ctx.fillRect(minX, minY, previewWidth, previewHeight);
+
+ ctx.setLineDash([4, 4]);
+ ctx.strokeStyle = '#ffffff';
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.moveTo(gStartX, gStartY);
+ ctx.lineTo(gEndX, gEndY);
+ ctx.stroke();
+
+ ctx.fillStyle = '#ffffff';
+ ctx.beginPath();
+ ctx.arc(gStartX, gStartY, 4, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.beginPath();
+ ctx.arc(gEndX, gEndY, 4, 0, Math.PI * 2);
+ ctx.fill();
+
+ ctx.restore();
+ }
+
if (smartGuides.length > 0) {
ctx.save();
ctx.strokeStyle = '#f43f5e';
@@ -557,7 +666,7 @@ export function Canvas() {
}
ctx.restore();
- }, [artboard, project, zoom, panX, panY, selectedLayerIds, showGrid, gridSize, crop, smartGuides, drawing, penSettings, isMarqueeSelecting, marqueeRect]);
+ }, [artboard, project, zoom, panX, panY, selectedLayerIds, showGrid, gridSize, crop, smartGuides, drawing, penSettings, brushSettings, activeTool, isMarqueeSelecting, marqueeRect]);
const scheduleRender = useCallback(() => {
if (renderScheduledRef.current) return;
@@ -747,6 +856,487 @@ export function Canvas() {
return;
}
+ if (activeTool === 'marquee-rect' || activeTool === 'marquee-ellipse') {
+ deselectAllLayers();
+ startMarqueeSelect(x, y);
+ startDrag('marquee', e.clientX, e.clientY);
+ return;
+ }
+
+ if (activeTool === 'lasso' || activeTool === 'lasso-polygon' || activeTool === 'magic-wand') {
+ const layerId = findLayerAtPoint(x, y);
+ if (layerId) {
+ selectLayer(layerId);
+ } else {
+ deselectAllLayers();
+ }
+ return;
+ }
+
+ if (activeTool === 'free-transform' || activeTool === 'warp' || activeTool === 'perspective' || activeTool === 'liquify') {
+ const handleHit = getHandleAtPoint(canvasX, canvasY);
+ if (handleHit) {
+ const layer = project?.layers[handleHit.layerId];
+ if (layer) {
+ initialTransformRef.current = {
+ x: layer.transform.x,
+ y: layer.transform.y,
+ width: layer.transform.width,
+ height: layer.transform.height,
+ rotation: layer.transform.rotation,
+ };
+ if (handleHit.handle === 'rotate') {
+ startDrag('rotate', e.clientX, e.clientY);
+ } else {
+ setActiveResizeHandle(handleHit.handle);
+ startDrag('resize', e.clientX, e.clientY);
+ }
+ return;
+ }
+ }
+
+ const layerId = findLayerAtPoint(x, y);
+ if (layerId) {
+ if (!selectedLayerIds.includes(layerId)) {
+ selectLayer(layerId);
+ }
+ startDrag('move', e.clientX, e.clientY);
+ }
+ return;
+ }
+
+ if (activeTool === 'brush') {
+ const layerId = findLayerAtPoint(x, y);
+ if (layerId && project) {
+ const layer = project.layers[layerId];
+ if (layer?.type === 'image') {
+ const imageLayer = layer as ImageLayer;
+ const asset = project.assets[imageLayer.sourceId];
+ const src = asset?.blobUrl ?? asset?.dataUrl;
+ if (src) {
+ const img = getCachedImage(src);
+ if (img && img.complete && img.naturalWidth > 0) {
+ const tempCanvas = new OffscreenCanvas(img.naturalWidth, img.naturalHeight);
+ const tempCtx = tempCanvas.getContext('2d', { willReadFrequently: true });
+ if (tempCtx) {
+ tempCtx.drawImage(img, 0, 0);
+ paintCanvasRef.current = tempCanvas;
+ paintLayerIdRef.current = layerId;
+
+ const localX = (x - layer.transform.x) * (img.naturalWidth / layer.transform.width);
+ const localY = (y - layer.transform.y) * (img.naturalHeight / layer.transform.height);
+
+ const tool = new BrushTool({
+ size: brushSettings.size * (img.naturalWidth / layer.transform.width),
+ hardness: brushSettings.hardness,
+ opacity: brushSettings.opacity,
+ flow: brushSettings.flow,
+ color: brushSettings.color,
+ blendMode: brushSettings.blendMode,
+ });
+ tool.setCanvas(tempCanvas);
+ tool.startStroke(localX, localY, 1);
+ brushToolRef.current = tool;
+
+ if (!selectedLayerIds.includes(layerId)) {
+ selectLayer(layerId);
+ }
+ startDrag('paint', e.clientX, e.clientY);
+ }
+ }
+ }
+ }
+ } else {
+ startDrawing({ x, y });
+ }
+ return;
+ }
+
+ if (activeTool === 'eraser') {
+ const layerId = findLayerAtPoint(x, y);
+ if (layerId && project) {
+ const layer = project.layers[layerId];
+ if (layer?.type === 'image') {
+ const imageLayer = layer as ImageLayer;
+ const asset = project.assets[imageLayer.sourceId];
+ const src = asset?.blobUrl ?? asset?.dataUrl;
+ if (src) {
+ const img = getCachedImage(src);
+ if (img && img.complete && img.naturalWidth > 0) {
+ const tempCanvas = new OffscreenCanvas(img.naturalWidth, img.naturalHeight);
+ const tempCtx = tempCanvas.getContext('2d', { willReadFrequently: true });
+ if (tempCtx) {
+ tempCtx.drawImage(img, 0, 0);
+ paintCanvasRef.current = tempCanvas;
+ paintLayerIdRef.current = layerId;
+
+ const localX = (x - layer.transform.x) * (img.naturalWidth / layer.transform.width);
+ const localY = (y - layer.transform.y) * (img.naturalHeight / layer.transform.height);
+
+ const tool = new EraserTool({
+ size: eraserSettings.size * (img.naturalWidth / layer.transform.width),
+ hardness: eraserSettings.hardness,
+ opacity: eraserSettings.opacity,
+ flow: eraserSettings.flow,
+ mode: eraserSettings.mode,
+ spacing: 25,
+ sizeDynamics: { ...DEFAULT_BRUSH_DYNAMICS },
+ opacityDynamics: { ...DEFAULT_BRUSH_DYNAMICS },
+ flowDynamics: { ...DEFAULT_BRUSH_DYNAMICS },
+ });
+ tool.startErase(localX, localY, 1);
+ eraserToolRef.current = tool;
+
+ if (!selectedLayerIds.includes(layerId)) {
+ selectLayer(layerId);
+ }
+ startDrag('paint', e.clientX, e.clientY);
+ }
+ }
+ }
+ }
+ }
+ return;
+ }
+
+ if (activeTool === 'gradient') {
+ setGradientDrag({
+ startX: x,
+ startY: y,
+ endX: x,
+ endY: y,
+ layerId: selectedLayerIds[0] ?? '',
+ });
+ startDrag('paint', e.clientX, e.clientY);
+ return;
+ }
+
+ if (activeTool === 'paint-bucket') {
+ const layerId = findLayerAtPoint(x, y);
+ if (layerId && project) {
+ const layer = project.layers[layerId];
+ if (layer?.type === 'image') {
+ const imageLayer = layer as ImageLayer;
+ const asset = project.assets[imageLayer.sourceId];
+ const src = asset?.blobUrl ?? asset?.dataUrl;
+ if (src) {
+ const img = getCachedImage(src);
+ if (img && img.complete && img.naturalWidth > 0) {
+ const localX = x - layer.transform.x;
+ const localY = y - layer.transform.y;
+ const scaleX = img.naturalWidth / layer.transform.width;
+ const scaleY = img.naturalHeight / layer.transform.height;
+ const imgX = Math.floor(localX * scaleX);
+ const imgY = Math.floor(localY * scaleY);
+
+ const tempCanvas = document.createElement('canvas');
+ tempCanvas.width = img.naturalWidth;
+ tempCanvas.height = img.naturalHeight;
+ const tempCtx = tempCanvas.getContext('2d');
+ if (tempCtx) {
+ tempCtx.drawImage(img, 0, 0);
+ const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
+
+ const fillOptions: FloodFillOptions = {
+ tolerance: paintBucketSettings.tolerance,
+ contiguous: paintBucketSettings.contiguous,
+ antiAlias: paintBucketSettings.antiAlias,
+ opacity: paintBucketSettings.opacity,
+ };
+
+ const filledData = floodFill(imageData, imgX, imgY, paintBucketSettings.color, fillOptions);
+ tempCtx.putImageData(filledData, 0, 0);
+
+ const oldBlobUrl = asset?.blobUrl;
+ tempCanvas.toBlob((blob) => {
+ if (blob) {
+ if (oldBlobUrl?.startsWith('blob:')) {
+ URL.revokeObjectURL(oldBlobUrl);
+ }
+ const newBlobUrl = URL.createObjectURL(blob);
+ const newAssetId = `asset-${Date.now()}`;
+ useProjectStore.getState().addAsset({
+ id: newAssetId,
+ name: `filled-${imageLayer.name || 'image'}`,
+ type: 'image',
+ mimeType: 'image/png',
+ size: blob.size,
+ width: tempCanvas.width,
+ height: tempCanvas.height,
+ thumbnailUrl: newBlobUrl,
+ blobUrl: newBlobUrl,
+ });
+ useProjectStore.getState().updateLayer(layerId, { sourceId: newAssetId });
+ forceRender();
+ }
+ }, 'image/png');
+ }
+ }
+ }
+ } else if (layer?.type === 'shape') {
+ updateLayer(layerId, {
+ shapeStyle: {
+ ...(layer as ShapeLayer).shapeStyle,
+ fill: paintBucketSettings.color,
+ fillOpacity: paintBucketSettings.opacity,
+ },
+ } as Partial<ShapeLayer>);
+ }
+ }
+ return;
+ }
+
+ if (activeTool === 'smudge' || activeTool === 'blur' || activeTool === 'sharpen') {
+ const layerId = findLayerAtPoint(x, y);
+ if (layerId && project) {
+ const layer = project.layers[layerId];
+ if (layer?.type === 'image') {
+ const imageLayer = layer as ImageLayer;
+ const asset = project.assets[imageLayer.sourceId];
+ const src = asset?.blobUrl ?? asset?.dataUrl;
+ if (src) {
+ const img = getCachedImage(src);
+ if (img && img.complete && img.naturalWidth > 0) {
+ const tempCanvas = new OffscreenCanvas(img.naturalWidth, img.naturalHeight);
+ const tempCtx = tempCanvas.getContext('2d', { willReadFrequently: true });
+ if (tempCtx) {
+ tempCtx.drawImage(img, 0, 0);
+ paintCanvasRef.current = tempCanvas;
+ paintLayerIdRef.current = layerId;
+
+ const localX = (x - layer.transform.x) * (img.naturalWidth / layer.transform.width);
+ const localY = (y - layer.transform.y) * (img.naturalHeight / layer.transform.height);
+
+ if (activeTool === 'smudge') {
+ const tool = new SmudgeTool({
+ size: smudgeSettings.size * (img.naturalWidth / layer.transform.width),
+ hardness: 50,
+ strength: smudgeSettings.strength,
+ fingerPainting: smudgeSettings.fingerPainting,
+ sampleAllLayers: smudgeSettings.sampleAllLayers,
+ fingerColor: brushSettings.color,
+ });
+ tool.setCanvas(tempCanvas);
+ tool.startStroke(localX, localY, 1);
+ smudgeToolRef.current = tool;
+ blurSharpenToolRef.current = null;
+ } else {
+ const tool = new BlurSharpenTool({
+ size: blurSharpenSettings.size * (img.naturalWidth / layer.transform.width),
+ hardness: 50,
+ strength: blurSharpenSettings.strength,
+ mode: activeTool === 'blur' ? 'blur' : 'sharpen',
+ sampleAllLayers: blurSharpenSettings.sampleAllLayers,
+ });
+ tool.setCanvas(tempCanvas);
+ tool.startStroke(localX, localY, 1);
+ blurSharpenToolRef.current = tool;
+ smudgeToolRef.current = null;
+ }
+
+ if (!selectedLayerIds.includes(layerId)) {
+ selectLayer(layerId);
+ }
+ startDrag('paint', e.clientX, e.clientY);
+ }
+ }
+ }
+ }
+ }
+ return;
+ }
+
+ if (activeTool === 'dodge' || activeTool === 'burn' || activeTool === 'sponge' || activeTool === 'spot-healing') {
+ const layerId = findLayerAtPoint(x, y);
+ if (layerId && project) {
+ const layer = project.layers[layerId];
+ if (layer?.type === 'image') {
+ const imageLayer = layer as ImageLayer;
+ const asset = project.assets[imageLayer.sourceId];
+ const src = asset?.blobUrl ?? asset?.dataUrl;
+ if (src) {
+ const img = getCachedImage(src);
+ if (img && img.complete && img.naturalWidth > 0) {
+ const tempCanvas = new OffscreenCanvas(img.naturalWidth, img.naturalHeight);
+ const tempCtx = tempCanvas.getContext('2d', { willReadFrequently: true });
+ if (tempCtx) {
+ tempCtx.drawImage(img, 0, 0);
+ paintCanvasRef.current = tempCanvas;
+ paintLayerIdRef.current = layerId;
+
+ const localX = (x - layer.transform.x) * (img.naturalWidth / layer.transform.width);
+ const localY = (y - layer.transform.y) * (img.naturalHeight / layer.transform.height);
+
+ if (activeTool === 'dodge' || activeTool === 'burn') {
+ const tool = new DodgeBurnTool({
+ size: dodgeBurnSettings.size * (img.naturalWidth / layer.transform.width),
+ type: activeTool,
+ range: dodgeBurnSettings.range,
+ exposure: dodgeBurnSettings.exposure,
+ });
+ tool.setCanvas(tempCanvas);
+ tool.startStroke(localX, localY, 1);
+ tool.apply(tempCtx, localX, localY, 1);
+ dodgeBurnToolRef.current = tool;
+ } else if (activeTool === 'sponge') {
+ const tool = new SpongeTool({
+ size: spongeSettings.size * (img.naturalWidth / layer.transform.width),
+ mode: spongeSettings.mode,
+ flow: spongeSettings.flow,
+ });
+ tool.setCanvas(tempCanvas);
+ tool.startStroke(localX, localY, 1);
+ tool.apply(tempCtx, localX, localY, 1);
+ spongeToolRef.current = tool;
+ } else if (activeTool === 'spot-healing') {
+ const tool = new SpotHealingTool({
+ size: spotHealingSettings.size * (img.naturalWidth / layer.transform.width),
+ type: spotHealingSettings.type,
+ sampleAllLayers: spotHealingSettings.sampleAllLayers,
+ });
+ tool.setCanvas(tempCanvas);
+ tool.heal(tempCtx, localX, localY);
+ spotHealingToolRef.current = tool;
+ }
+
+ if (!selectedLayerIds.includes(layerId)) {
+ selectLayer(layerId);
+ }
+ startDrag('paint', e.clientX, e.clientY);
+ }
+ }
+ }
+ }
+ }
+ return;
+ }
+
+ if (activeTool === 'clone-stamp' || activeTool === 'healing-brush') {
+ const layerId = findLayerAtPoint(x, y);
+ if (layerId && project) {
+ const layer = project.layers[layerId];
+ if (layer?.type === 'image') {
+ const imageLayer = layer as ImageLayer;
+ const asset = project.assets[imageLayer.sourceId];
+ const src = asset?.blobUrl ?? asset?.dataUrl;
+ if (src) {
+ const img = getCachedImage(src);
+ if (img && img.complete && img.naturalWidth > 0) {
+ const tempCanvas = new OffscreenCanvas(img.naturalWidth, img.naturalHeight);
+ const tempCtx = tempCanvas.getContext('2d', { willReadFrequently: true });
+ if (tempCtx) {
+ tempCtx.drawImage(img, 0, 0);
+ paintCanvasRef.current = tempCanvas;
+ paintLayerIdRef.current = layerId;
+
+ const localX = (x - layer.transform.x) * (img.naturalWidth / layer.transform.width);
+ const localY = (y - layer.transform.y) * (img.naturalHeight / layer.transform.height);
+
+ if (e.altKey) {
+ if (activeTool === 'clone-stamp') {
+ if (!cloneStampToolRef.current) {
+ cloneStampToolRef.current = new CloneStampTool({
+ size: cloneStampSettings.size * (img.naturalWidth / layer.transform.width),
+ hardness: cloneStampSettings.hardness,
+ opacity: cloneStampSettings.opacity,
+ flow: cloneStampSettings.flow,
+ aligned: cloneStampSettings.aligned,
+ });
+ }
+ cloneStampToolRef.current.setSourceCanvas(tempCanvas);
+ cloneStampToolRef.current.setSource(localX, localY, layerId);
+ } else {
+ if (!healingBrushToolRef.current) {
+ healingBrushToolRef.current = new HealingBrushTool({
+ size: healingBrushSettings.size * (img.naturalWidth / layer.transform.width),
+ hardness: healingBrushSettings.hardness,
+ aligned: healingBrushSettings.aligned,
+ });
+ }
+ healingBrushToolRef.current.setCanvases(tempCanvas, tempCanvas);
+ healingBrushToolRef.current.setSource(localX, localY, layerId);
+ }
+ return;
+ }
+
+ if (activeTool === 'clone-stamp' && cloneStampToolRef.current?.hasSource()) {
+ cloneStampToolRef.current.updateSettings({
+ size: cloneStampSettings.size * (img.naturalWidth / layer.transform.width),
+ hardness: cloneStampSettings.hardness,
+ opacity: cloneStampSettings.opacity,
+ flow: cloneStampSettings.flow,
+ aligned: cloneStampSettings.aligned,
+ });
+ cloneStampToolRef.current.setSourceCanvas(tempCanvas);
+ cloneStampToolRef.current.startClone(localX, localY);
+ cloneStampToolRef.current.clone(tempCtx, localX, localY);
+ } else if (activeTool === 'healing-brush' && healingBrushToolRef.current?.hasSource()) {
+ healingBrushToolRef.current.updateSettings({
+ size: healingBrushSettings.size * (img.naturalWidth / layer.transform.width),
+ hardness: healingBrushSettings.hardness,
+ aligned: healingBrushSettings.aligned,
+ });
+ healingBrushToolRef.current.setCanvases(tempCanvas, tempCanvas);
+ healingBrushToolRef.current.startHeal(localX, localY);
+ healingBrushToolRef.current.heal(tempCtx, localX, localY);
+ } else {
+ return;
+ }
+
+ if (!selectedLayerIds.includes(layerId)) {
+ selectLayer(layerId);
+ }
+ startDrag('paint', e.clientX, e.clientY);
+ }
+ }
+ }
+ }
+ }
+ return;
+ }
+
+ if (activeTool === 'zoom') {
+ if (e.shiftKey || e.altKey) {
+ setZoom(Math.max(0.1, zoom / 1.5));
+ } else {
+ setZoom(Math.min(32, zoom * 1.5));
+ }
+ return;
+ }
+
+ if (activeTool === 'eyedropper') {
+ const canvas = canvasRef.current;
+ const ctx = canvas?.getContext('2d');
+ if (ctx && canvas) {
+ const rect = canvas.getBoundingClientRect();
+ const pixelX = Math.floor((e.clientX - rect.left) * (canvas.width / rect.width));
+ const pixelY = Math.floor((e.clientY - rect.top) * (canvas.height / rect.height));
+ const pixel = ctx.getImageData(pixelX, pixelY, 1, 1).data;
+ const hex = `#${pixel[0].toString(16).padStart(2, '0')}${pixel[1].toString(16).padStart(2, '0')}${pixel[2].toString(16).padStart(2, '0')}`;
+ setBrushSettings({ color: hex });
+ }
+ return;
+ }
+
+ if (activeTool === 'crop') {
+ const layerId = findLayerAtPoint(x, y);
+ if (layerId) {
+ const layer = project?.layers[layerId];
+ if (layer) {
+ selectLayer(layerId);
+ startCrop(layerId, {
+ x: 0,
+ y: 0,
+ width: layer.transform.width,
+ height: layer.transform.height,
+ });
+ startMarqueeSelect(x, y);
+ startDrag('crop', e.clientX, e.clientY);
+ }
+ }
+ return;
+ }
+
if (activeTool === 'select') {
const handleHit = getHandleAtPoint(canvasX, canvasY);
if (handleHit) {
@@ -784,7 +1374,7 @@ export function Canvas() {
}
}
},
- [activeTool, screenToCanvas, findLayerAtPoint, selectLayer, deselectAllLayers, startDrag, selectedLayerIds, startDrawing, startMarqueeSelect, getHandleAtPoint, project, setActiveResizeHandle]
+ [activeTool, screenToCanvas, findLayerAtPoint, selectLayer, deselectAllLayers, startDrag, selectedLayerIds, startDrawing, startMarqueeSelect, getHandleAtPoint, project, setActiveResizeHandle, zoom, setZoom, startCrop, setBrushSettings, eraserSettings]
);
const handleMouseMove = useCallback(
@@ -798,7 +1388,166 @@ export function Canvas() {
return;
}
- if (!isDragging && canvas && activeTool === 'select' && selectedLayerIds.length === 1) {
+ if (gradientDrag && activeTool === 'gradient') {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ setGradientDrag({ ...gradientDrag, endX: x, endY: y });
+ scheduleRender();
+ return;
+ }
+
+ if (isDragging && dragMode === 'paint' && paintLayerIdRef.current && paintCanvasRef.current) {
+ if (activeTool === 'smudge' && smudgeToolRef.current) {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ const layer = project?.layers[paintLayerIdRef.current];
+ if (layer) {
+ const scale = paintCanvasRef.current.width / layer.transform.width;
+ const localX = (x - layer.transform.x) * scale;
+ const localY = (y - layer.transform.y) * scale;
+ smudgeToolRef.current.continueStroke(localX, localY, 1);
+ }
+ return;
+ }
+
+ if (activeTool === 'eraser' && eraserToolRef.current) {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ const layer = project?.layers[paintLayerIdRef.current];
+ if (layer && paintCanvasRef.current) {
+ const scale = paintCanvasRef.current.width / layer.transform.width;
+ const localX = (x - layer.transform.x) * scale;
+ const localY = (y - layer.transform.y) * scale;
+ eraserToolRef.current.continueErase(localX, localY, 1);
+
+ const ctx = paintCanvasRef.current.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ const stroke = eraserToolRef.current.endErase();
+ if (stroke) {
+ eraserToolRef.current.applyErase(ctx, stroke);
+ eraserToolRef.current.startErase(localX, localY, 1);
+ }
+ }
+ }
+ scheduleRender();
+ return;
+ }
+
+ if (activeTool === 'brush' && brushToolRef.current) {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ const layer = project?.layers[paintLayerIdRef.current];
+ if (layer && paintCanvasRef.current) {
+ const scale = paintCanvasRef.current.width / layer.transform.width;
+ const localX = (x - layer.transform.x) * scale;
+ const localY = (y - layer.transform.y) * scale;
+
+ const ctx = paintCanvasRef.current.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ brushToolRef.current.apply(ctx, localX, localY, 1);
+ }
+ }
+ scheduleRender();
+ return;
+ }
+
+ if ((activeTool === 'blur' || activeTool === 'sharpen') && blurSharpenToolRef.current) {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ const layer = project?.layers[paintLayerIdRef.current];
+ if (layer && paintCanvasRef.current) {
+ const scale = paintCanvasRef.current.width / layer.transform.width;
+ const localX = (x - layer.transform.x) * scale;
+ const localY = (y - layer.transform.y) * scale;
+ blurSharpenToolRef.current.continueStroke(localX, localY, 1);
+
+ const ctx = paintCanvasRef.current.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ blurSharpenToolRef.current.apply(ctx, localX, localY, 1);
+ }
+ }
+ return;
+ }
+
+ if ((activeTool === 'dodge' || activeTool === 'burn') && dodgeBurnToolRef.current) {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ const layer = project?.layers[paintLayerIdRef.current];
+ if (layer && paintCanvasRef.current) {
+ const scale = paintCanvasRef.current.width / layer.transform.width;
+ const localX = (x - layer.transform.x) * scale;
+ const localY = (y - layer.transform.y) * scale;
+ dodgeBurnToolRef.current.continueStroke(localX, localY, 1);
+
+ const ctx = paintCanvasRef.current.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ dodgeBurnToolRef.current.apply(ctx, localX, localY, 1);
+ }
+ }
+ return;
+ }
+
+ if (activeTool === 'sponge' && spongeToolRef.current) {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ const layer = project?.layers[paintLayerIdRef.current];
+ if (layer && paintCanvasRef.current) {
+ const scale = paintCanvasRef.current.width / layer.transform.width;
+ const localX = (x - layer.transform.x) * scale;
+ const localY = (y - layer.transform.y) * scale;
+ spongeToolRef.current.continueStroke(localX, localY, 1);
+
+ const ctx = paintCanvasRef.current.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ spongeToolRef.current.apply(ctx, localX, localY, 1);
+ }
+ }
+ return;
+ }
+
+ if (activeTool === 'spot-healing' && spotHealingToolRef.current) {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ const layer = project?.layers[paintLayerIdRef.current];
+ if (layer && paintCanvasRef.current) {
+ const scale = paintCanvasRef.current.width / layer.transform.width;
+ const localX = (x - layer.transform.x) * scale;
+ const localY = (y - layer.transform.y) * scale;
+
+ const ctx = paintCanvasRef.current.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ spotHealingToolRef.current.heal(ctx, localX, localY);
+ }
+ }
+ return;
+ }
+
+ if (activeTool === 'clone-stamp' && cloneStampToolRef.current?.hasSource()) {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ const layer = project?.layers[paintLayerIdRef.current];
+ if (layer && paintCanvasRef.current) {
+ const scale = paintCanvasRef.current.width / layer.transform.width;
+ const localX = (x - layer.transform.x) * scale;
+ const localY = (y - layer.transform.y) * scale;
+
+ const ctx = paintCanvasRef.current.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ cloneStampToolRef.current.clone(ctx, localX, localY);
+ }
+ }
+ return;
+ }
+
+ if (activeTool === 'healing-brush' && healingBrushToolRef.current?.hasSource()) {
+ const { x, y } = screenToCanvas(e.clientX, e.clientY);
+ const layer = project?.layers[paintLayerIdRef.current];
+ if (layer && paintCanvasRef.current) {
+ const scale = paintCanvasRef.current.width / layer.transform.width;
+ const localX = (x - layer.transform.x) * scale;
+ const localY = (y - layer.transform.y) * scale;
+
+ const ctx = paintCanvasRef.current.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ healingBrushToolRef.current.heal(ctx, localX, localY);
+ }
+ }
+ return;
+ }
+ }
+
+ if (!isDragging && canvas && (activeTool === 'select' || activeTool === 'free-transform') && selectedLayerIds.length === 1) {
const rect = canvas.getBoundingClientRect();
const canvasX = e.clientX - rect.left;
const canvasY = e.clientY - rect.top;
@@ -811,9 +1560,34 @@ export function Canvas() {
updateDrag(e.clientX, e.clientY);
- if (dragMode === 'marquee') {
+ if (dragMode === 'marquee' || dragMode === 'crop') {
const { x, y } = screenToCanvas(e.clientX, e.clientY);
updateMarqueeSelect(x, y);
+ if (dragMode === 'crop' && crop.layerId && marqueeRect) {
+ const layer = project?.layers[crop.layerId];
+ if (layer) {
+ const relX = marqueeRect.x - layer.transform.x;
+ const relY = marqueeRect.y - layer.transform.y;
+ let width = Math.min(marqueeRect.width, layer.transform.width - relX);
+ let height = Math.min(marqueeRect.height, layer.transform.height - relY);
+
+ if (crop.lockAspect && crop.initialAspectRatio) {
+ const currentAspect = width / height;
+ if (currentAspect > crop.initialAspectRatio) {
+ width = height * crop.initialAspectRatio;
+ } else {
+ height = width / crop.initialAspectRatio;
+ }
+ }
+
+ updateCropRect({
+ x: Math.max(0, relX),
+ y: Math.max(0, relY),
+ width,
+ height,
+ });
+ }
+ }
scheduleRender();
return;
}
@@ -1009,7 +1783,7 @@ export function Canvas() {
}
}
},
- [isDragging, dragMode, dragCurrentX, dragCurrentY, dragStartX, dragStartY, panX, panY, setPan, zoom, selectedLayerIds, project, updateLayerTransform, updateDrag, artboard, guides, snapToObjects, snapToGuides, snapToGrid, gridSize, setSmartGuides, drawing.isDrawing, screenToCanvas, addDrawingPoint, scheduleRender, updateMarqueeSelect, activeResizeHandle, activeTool, getHandleAtPoint]
+ [isDragging, dragMode, dragCurrentX, dragCurrentY, dragStartX, dragStartY, panX, panY, setPan, zoom, selectedLayerIds, project, updateLayerTransform, updateDrag, artboard, guides, snapToObjects, snapToGuides, snapToGrid, gridSize, setSmartGuides, drawing.isDrawing, screenToCanvas, addDrawingPoint, scheduleRender, updateMarqueeSelect, activeResizeHandle, activeTool, getHandleAtPoint, updateCropRect, crop, marqueeRect, gradientDrag]
);
const findLayersInRect = useCallback(
@@ -1047,18 +1821,186 @@ export function Canvas() {
if (drawing.isDrawing) {
const path = finishDrawing();
if (path && path.length > 1) {
- addPathLayer(path, penSettings.color, penSettings.width);
+ if (activeTool === 'brush') {
+ addPathLayer(path, brushSettings.color, brushSettings.size);
+ } else {
+ addPathLayer(path, penSettings.color, penSettings.width);
+ }
+ }
+ scheduleRender();
+ return;
+ }
+
+ if (gradientDrag && activeTool === 'gradient') {
+ const dx = gradientDrag.endX - gradientDrag.startX;
+ const dy = gradientDrag.endY - gradientDrag.startY;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+
+ if (distance > 5 && artboard) {
+ const minX = Math.min(gradientDrag.startX, gradientDrag.endX);
+ const minY = Math.min(gradientDrag.startY, gradientDrag.endY);
+ const maxX = Math.max(gradientDrag.startX, gradientDrag.endX);
+ const maxY = Math.max(gradientDrag.startY, gradientDrag.endY);
+
+ const width = Math.max(maxX - minX, 50);
+ const height = Math.max(maxY - minY, 50);
+
+ const angle = Math.atan2(dy, dx) * (180 / Math.PI);
+
+ const colors = gradientSettings.reverse
+ ? [...gradientSettings.colors].reverse()
+ : gradientSettings.colors;
+
+ const stops = colors.map((color, i) => ({
+ offset: i / Math.max(colors.length - 1, 1),
+ color,
+ }));
+
+ addShapeLayer('rectangle', {
+ x: minX,
+ y: minY,
+ width,
+ height,
+ });
+
+ const newLayerId = Object.keys(project?.layers ?? {}).find(
+ (id) => !selectedLayerIds.includes(id) && project?.layers[id]?.name === 'Rectangle'
+ );
+
+ if (newLayerId) {
+ updateLayer(newLayerId, {
+ name: 'Gradient Fill',
+ shapeStyle: {
+ fill: null,
+ stroke: null,
+ strokeWidth: 0,
+ fillOpacity: gradientSettings.opacity,
+ strokeOpacity: 1,
+ cornerRadius: 0,
+ fillType: 'gradient',
+ gradient: {
+ type: gradientSettings.type,
+ angle: gradientSettings.type === 'linear' ? angle : 0,
+ stops,
+ },
+ },
+ } as Partial<ShapeLayer>);
+ }
}
+
+ setGradientDrag(null);
+ endDrag();
scheduleRender();
return;
}
+ if (dragMode === 'paint' && paintLayerIdRef.current && paintCanvasRef.current) {
+ const hasActiveTool =
+ (activeTool === 'smudge' && smudgeToolRef.current) ||
+ ((activeTool === 'blur' || activeTool === 'sharpen') && blurSharpenToolRef.current) ||
+ ((activeTool === 'dodge' || activeTool === 'burn') && dodgeBurnToolRef.current) ||
+ (activeTool === 'sponge' && spongeToolRef.current) ||
+ (activeTool === 'spot-healing' && spotHealingToolRef.current) ||
+ (activeTool === 'clone-stamp' && cloneStampToolRef.current) ||
+ (activeTool === 'healing-brush' && healingBrushToolRef.current) ||
+ (activeTool === 'eraser' && eraserToolRef.current) ||
+ (activeTool === 'brush' && brushToolRef.current);
+
+ if (hasActiveTool) {
+ if (smudgeToolRef.current) {
+ smudgeToolRef.current.endStroke();
+ }
+ if (blurSharpenToolRef.current) {
+ blurSharpenToolRef.current.endStroke();
+ }
+ if (dodgeBurnToolRef.current) {
+ dodgeBurnToolRef.current.endStroke();
+ }
+ if (spongeToolRef.current) {
+ spongeToolRef.current.endStroke();
+ }
+ if (cloneStampToolRef.current) {
+ cloneStampToolRef.current.endClone();
+ }
+ if (healingBrushToolRef.current) {
+ healingBrushToolRef.current.endHeal();
+ }
+ if (eraserToolRef.current && paintCanvasRef.current) {
+ const ctx = paintCanvasRef.current.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ const stroke = eraserToolRef.current.endErase();
+ if (stroke) {
+ eraserToolRef.current.applyErase(ctx, stroke);
+ }
+ }
+ }
+ if (brushToolRef.current) {
+ brushToolRef.current.endStroke();
+ }
+
+ const tempCanvas = paintCanvasRef.current;
+ const layerId = paintLayerIdRef.current;
+
+ const currentLayer = project?.layers[layerId] as ImageLayer | undefined;
+ const oldSourceId = currentLayer?.sourceId;
+ const oldAsset = oldSourceId ? project?.assets[oldSourceId] : undefined;
+ const oldBlobUrl = oldAsset?.blobUrl;
+
+ const canvas = document.createElement('canvas');
+ canvas.width = tempCanvas.width;
+ canvas.height = tempCanvas.height;
+ const ctx = canvas.getContext('2d');
+ if (ctx) {
+ ctx.drawImage(tempCanvas, 0, 0);
+ canvas.toBlob((blob) => {
+ if (blob) {
+ if (oldBlobUrl?.startsWith('blob:')) {
+ URL.revokeObjectURL(oldBlobUrl);
+ }
+ const newBlobUrl = URL.createObjectURL(blob);
+ const newAssetId = `asset-${Date.now()}`;
+ useProjectStore.getState().addAsset({
+ id: newAssetId,
+ name: `${activeTool}-edited`,
+ type: 'image',
+ mimeType: 'image/png',
+ size: blob.size,
+ width: canvas.width,
+ height: canvas.height,
+ thumbnailUrl: newBlobUrl,
+ blobUrl: newBlobUrl,
+ });
+ useProjectStore.getState().updateLayer(layerId, { sourceId: newAssetId });
+ forceRender();
+ }
+ }, 'image/png');
+ }
+
+ smudgeToolRef.current = null;
+ blurSharpenToolRef.current = null;
+ dodgeBurnToolRef.current = null;
+ spongeToolRef.current = null;
+ spotHealingToolRef.current = null;
+ eraserToolRef.current = null;
+ brushToolRef.current = null;
+ paintCanvasRef.current = null;
+ paintLayerIdRef.current = null;
+ }
+
+ endDrag();
+ return;
+ }
+
if (dragMode === 'marquee') {
const rect = endMarqueeSelect();
if (rect && rect.width > 5 && rect.height > 5) {
- const layerIds = findLayersInRect(rect);
- if (layerIds.length > 0) {
- selectLayers(layerIds);
+ if (activeTool === 'marquee-rect' || activeTool === 'marquee-ellipse') {
+ // Keep selection visible for marquee tools - don't select layers
+ } else {
+ const layerIds = findLayersInRect(rect);
+ if (layerIds.length > 0) {
+ selectLayers(layerIds);
+ }
}
}
endDrag();
@@ -1066,11 +2008,18 @@ export function Canvas() {
return;
}
+ if (dragMode === 'crop') {
+ endMarqueeSelect();
+ endDrag();
+ scheduleRender();
+ return;
+ }
+
initialTransformRef.current = null;
setActiveResizeHandle(null);
endDrag();
clearSmartGuides();
- }, [endDrag, clearSmartGuides, drawing.isDrawing, finishDrawing, addPathLayer, penSettings, scheduleRender, dragMode, endMarqueeSelect, findLayersInRect, selectLayers, setActiveResizeHandle]);
+ }, [endDrag, clearSmartGuides, drawing.isDrawing, finishDrawing, addPathLayer, penSettings, brushSettings, scheduleRender, dragMode, endMarqueeSelect, findLayersInRect, selectLayers, setActiveResizeHandle, activeTool, gradientDrag, gradientSettings, artboard, addShapeLayer, updateLayer, project, selectedLayerIds]);
const handleContextMenu = useCallback(
(e: React.MouseEvent) => {
@@ -1254,11 +2203,12 @@ export function Canvas() {
[zoom, panX, panY, setPan]
);
- const effectiveCursor = activeTool === 'hand'
- ? 'grab'
- : activeTool === 'select'
- ? (cursorStyle !== 'default' ? cursorStyle : 'default')
- : 'crosshair';
+ const effectiveCursor = (() => {
+ if ((activeTool === 'select' || activeTool === 'free-transform') && cursorStyle !== 'default') {
+ return cursorStyle;
+ }
+ return getToolCursor(activeTool, isDragging, dragMode);
+ })();
return (
<div
@@ -1286,6 +2236,7 @@ export function Canvas() {
left: showRulers ? RULER_SIZE : 0,
width: showRulers ? `calc(100% - ${RULER_SIZE}px)` : '100%',
height: showRulers ? `calc(100% - ${RULER_SIZE}px)` : '100%',
+ cursor: effectiveCursor,
}}
/>
@@ -1658,6 +2609,21 @@ function applyRadialBlur(
ctx.globalAlpha = 1;
}
+function drawImageWithCrop(
+ ctx: RenderContext,
+ img: HTMLImageElement,
+ layerWidth: number,
+ layerHeight: number,
+ cropRect: { x: number; y: number; width: number; height: number } | null
+) {
+ if (!cropRect) {
+ ctx.drawImage(img, 0, 0, layerWidth, layerHeight);
+ return;
+ }
+
+ ctx.drawImage(img, cropRect.x, cropRect.y, cropRect.width, cropRect.height, 0, 0, layerWidth, layerHeight);
+}
+
function renderImageLayerInternal(
ctx: RenderContext,
layer: ImageLayer,
@@ -1691,6 +2657,7 @@ function renderImageLayerInternal(
const flipH = layer.flipHorizontal ?? false;
const flipV = layer.flipVertical ?? false;
+ const { cropRect } = layer;
const adjustments: LayerAdjustments = {
levels: layer.levels,
@@ -1785,7 +2752,7 @@ function renderImageLayerInternal(
} else if (filters.blur > 0 && filters.blurType === 'radial') {
applyRadialBlur(tempCtx, img, width, height, filters.blur);
} else {
- tempCtx.drawImage(img, 0, 0, width, height);
+ drawImageWithCrop(tempCtx, img, width, height, cropRect);
}
tempCtx.filter = 'none';
@@ -1806,7 +2773,7 @@ function renderImageLayerInternal(
} else if (filters.blur > 0 && filters.blurType === 'radial') {
applyRadialBlur(ctx, img, layer.transform.width, layer.transform.height, filters.blur);
} else {
- ctx.drawImage(img, 0, 0, layer.transform.width, layer.transform.height);
+ drawImageWithCrop(ctx, img, layer.transform.width, layer.transform.height, cropRect);
}
ctx.filter = 'none';
diff --git a/apps/image/src/components/editor/inspector/AppearanceSection.tsx b/apps/image/src/components/editor/inspector/AppearanceSection.tsx
index 6f30cd05..cc28b18f 100644
--- a/apps/image/src/components/editor/inspector/AppearanceSection.tsx
+++ b/apps/image/src/components/editor/inspector/AppearanceSection.tsx
@@ -53,10 +53,6 @@ export function AppearanceSection({ layer }: Props) {
return (
<div className="space-y-4">
- <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
- Appearance
- </h4>
-
<div>
<label className="block text-[10px] text-muted-foreground mb-1">Blend Mode</label>
<select
diff --git a/apps/image/src/components/editor/inspector/BlurSharpenToolPanel.tsx b/apps/image/src/components/editor/inspector/BlurSharpenToolPanel.tsx
new file mode 100644
index 00000000..b96efa60
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/BlurSharpenToolPanel.tsx
@@ -0,0 +1,121 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { Droplets, RotateCcw } from 'lucide-react';
+
+export function BlurSharpenToolPanel() {
+ const { blurSharpenSettings, setBlurSharpenSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setBlurSharpenSettings({
+ size: 30,
+ strength: 50,
+ mode: 'blur',
+ sampleAllLayers: false,
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Droplets size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">
+ {blurSharpenSettings.mode === 'blur' ? 'Blur' : 'Sharpen'} Tool
+ </h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ {blurSharpenSettings.mode === 'blur'
+ ? 'Paint to blur and soften areas.'
+ : 'Paint to sharpen and enhance details.'}
+ </p>
+
+ <div className="space-y-3">
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Mode</span>
+ <div className="grid grid-cols-2 gap-1">
+ <button
+ onClick={() => setBlurSharpenSettings({ mode: 'blur' })}
+ className={`px-3 py-2 text-xs rounded transition-colors ${
+ blurSharpenSettings.mode === 'blur'
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ >
+ Blur
+ </button>
+ <button
+ onClick={() => setBlurSharpenSettings({ mode: 'sharpen' })}
+ className={`px-3 py-2 text-xs rounded transition-colors ${
+ blurSharpenSettings.mode === 'sharpen'
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ >
+ Sharpen
+ </button>
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Size</span>
+ <span className="text-xs font-mono text-muted-foreground">{blurSharpenSettings.size}px</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={500}
+ value={blurSharpenSettings.size}
+ onChange={(e) => setBlurSharpenSettings({ size: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Strength</span>
+ <span className="text-xs font-mono text-muted-foreground">{blurSharpenSettings.strength}%</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={100}
+ value={blurSharpenSettings.strength}
+ onChange={(e) => setBlurSharpenSettings({ strength: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div className="pt-2 border-t border-border">
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={blurSharpenSettings.sampleAllLayers}
+ onChange={(e) => setBlurSharpenSettings({ sampleAllLayers: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Sample All Layers
+ </label>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/BrushToolPanel.tsx b/apps/image/src/components/editor/inspector/BrushToolPanel.tsx
new file mode 100644
index 00000000..7416d956
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/BrushToolPanel.tsx
@@ -0,0 +1,156 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { Paintbrush, RotateCcw } from 'lucide-react';
+
+export function BrushToolPanel() {
+ const { brushSettings, setBrushSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setBrushSettings({
+ size: 20,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ color: '#000000',
+ blendMode: 'normal',
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Paintbrush size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Brush</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <div className="space-y-3">
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Color</span>
+ </div>
+ <div className="flex gap-2">
+ <input
+ type="color"
+ value={brushSettings.color}
+ onChange={(e) => setBrushSettings({ color: e.target.value })}
+ className="w-10 h-10 rounded border border-border cursor-pointer"
+ />
+ <input
+ type="text"
+ value={brushSettings.color}
+ onChange={(e) => setBrushSettings({ color: e.target.value })}
+ className="flex-1 px-2 py-1 text-xs font-mono bg-secondary/50 border border-border rounded"
+ />
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Size</span>
+ <span className="text-xs font-mono text-muted-foreground">{brushSettings.size}px</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={500}
+ value={brushSettings.size}
+ onChange={(e) => setBrushSettings({ size: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Hardness</span>
+ <span className="text-xs font-mono text-muted-foreground">{brushSettings.hardness}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={brushSettings.hardness}
+ onChange={(e) => setBrushSettings({ hardness: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Opacity</span>
+ <span className="text-xs font-mono text-muted-foreground">{Math.round(brushSettings.opacity * 100)}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={brushSettings.opacity * 100}
+ onChange={(e) => setBrushSettings({ opacity: Number(e.target.value) / 100 })}
+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer
+ [&::-webkit-slider-thumb]:appearance-none
+ [&::-webkit-slider-thumb]:w-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Flow</span>
+ <span className="text-xs font-mono text-muted-foreground">{Math.round(brushSettings.flow * 100)}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={brushSettings.flow * 100}
+ onChange={(e) => setBrushSettings({ flow: Number(e.target.value) / 100 })}
+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer
+ [&::-webkit-slider-thumb]:appearance-none
+ [&::-webkit-slider-thumb]:w-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Blend Mode</span>
+ <div className="grid grid-cols-2 gap-1">
+ {(['normal', 'multiply', 'screen', 'overlay'] as const).map((mode) => (
+ <button
+ key={mode}
+ onClick={() => setBrushSettings({ blendMode: mode })}
+ className={`px-2 py-1.5 text-xs rounded transition-colors capitalize ${
+ brushSettings.blendMode === mode
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ >
+ {mode}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/CloneStampToolPanel.tsx b/apps/image/src/components/editor/inspector/CloneStampToolPanel.tsx
new file mode 100644
index 00000000..0e9e4fdb
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/CloneStampToolPanel.tsx
@@ -0,0 +1,149 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { Stamp, RotateCcw } from 'lucide-react';
+
+export function CloneStampToolPanel() {
+ const { cloneStampSettings, setCloneStampSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setCloneStampSettings({
+ size: 30,
+ hardness: 50,
+ opacity: 1,
+ flow: 1,
+ aligned: true,
+ sampleAllLayers: false,
+ sourcePoint: null,
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Stamp size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Clone Stamp</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ Hold Alt/Option and click to set source point, then paint to clone.
+ </p>
+
+ {cloneStampSettings.sourcePoint && (
+ <div className="text-xs text-muted-foreground bg-secondary/50 p-2 rounded">
+ Source: ({Math.round(cloneStampSettings.sourcePoint.x)}, {Math.round(cloneStampSettings.sourcePoint.y)})
+ </div>
+ )}
+
+ <div className="space-y-3">
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Size</span>
+ <span className="text-xs font-mono text-muted-foreground">{cloneStampSettings.size}px</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={500}
+ value={cloneStampSettings.size}
+ onChange={(e) => setCloneStampSettings({ size: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Hardness</span>
+ <span className="text-xs font-mono text-muted-foreground">{cloneStampSettings.hardness}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={cloneStampSettings.hardness}
+ onChange={(e) => setCloneStampSettings({ hardness: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Opacity</span>
+ <span className="text-xs font-mono text-muted-foreground">{Math.round(cloneStampSettings.opacity * 100)}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={cloneStampSettings.opacity * 100}
+ onChange={(e) => setCloneStampSettings({ opacity: Number(e.target.value) / 100 })}
+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer
+ [&::-webkit-slider-thumb]:appearance-none
+ [&::-webkit-slider-thumb]:w-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Flow</span>
+ <span className="text-xs font-mono text-muted-foreground">{Math.round(cloneStampSettings.flow * 100)}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={cloneStampSettings.flow * 100}
+ onChange={(e) => setCloneStampSettings({ flow: Number(e.target.value) / 100 })}
+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer
+ [&::-webkit-slider-thumb]:appearance-none
+ [&::-webkit-slider-thumb]:w-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div className="flex flex-col gap-2 pt-2 border-t border-border">
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={cloneStampSettings.aligned}
+ onChange={(e) => setCloneStampSettings({ aligned: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Aligned
+ </label>
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={cloneStampSettings.sampleAllLayers}
+ onChange={(e) => setCloneStampSettings({ sampleAllLayers: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Sample All Layers
+ </label>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/CropSection.tsx b/apps/image/src/components/editor/inspector/CropSection.tsx
index 44884996..998e1f31 100644
--- a/apps/image/src/components/editor/inspector/CropSection.tsx
+++ b/apps/image/src/components/editor/inspector/CropSection.tsx
@@ -1,9 +1,19 @@
-import { useState, useCallback } from 'react';
+import { useCallback, useMemo } from 'react';
import { useProjectStore } from '../../../stores/project-store';
import { useUIStore, CropAspectRatio } from '../../../stores/ui-store';
import type { ImageLayer } from '../../../types/project';
import { Crop, Check, X, RotateCcw, Lock, Unlock } from 'lucide-react';
+const imageCache = new Map<string, HTMLImageElement>();
+function getCachedImage(src: string): HTMLImageElement | null {
+ if (!src) return null;
+ if (imageCache.has(src)) return imageCache.get(src)!;
+ const img = new Image();
+ img.src = src;
+ imageCache.set(src, img);
+ return img;
+}
+
interface Props {
layer: ImageLayer;
}
@@ -21,12 +31,27 @@ const ASPECT_RATIOS: { value: CropAspectRatio; label: string; ratio?: number }[]
];
export function CropSection({ layer }: Props) {
- const { updateLayer } = useProjectStore();
- const { crop, startCrop, cancelCrop, applyCrop, setCropAspectRatio, updateCropRect } = useUIStore();
- const [lockAspect, setLockAspect] = useState(false);
+ const { updateLayer, project } = useProjectStore();
+ const { crop, startCrop, cancelCrop, applyCrop, setCropAspectRatio, updateCropRect, setCropLockAspect } = useUIStore();
+
+ const lockAspect = crop.lockAspect;
+ const setLockAspect = setCropLockAspect;
const isCropping = crop.isActive && crop.layerId === layer.id;
+ const imageDimensions = useMemo(() => {
+ if (!project) return null;
+ const asset = project.assets[layer.sourceId];
+ if (!asset) return null;
+ const src = asset.blobUrl ?? asset.dataUrl;
+ if (!src) return null;
+ const img = getCachedImage(src);
+ if (img && img.complete && img.naturalWidth > 0) {
+ return { width: img.naturalWidth, height: img.naturalHeight };
+ }
+ return asset.width && asset.height ? { width: asset.width, height: asset.height } : null;
+ }, [project, layer.sourceId]);
+
const handleStartCrop = useCallback(() => {
const initialRect = layer.cropRect ?? {
x: 0,
@@ -39,12 +64,44 @@ export function CropSection({ layer }: Props) {
const handleApplyCrop = useCallback(() => {
const result = applyCrop();
- if (result) {
+ if (result && result.cropRect) {
+ const existingCropRect = layer.cropRect;
+ let finalCropRect: { x: number; y: number; width: number; height: number };
+
+ if (existingCropRect) {
+ const scaleX = existingCropRect.width / layer.transform.width;
+ const scaleY = existingCropRect.height / layer.transform.height;
+ finalCropRect = {
+ x: existingCropRect.x + result.cropRect.x * scaleX,
+ y: existingCropRect.y + result.cropRect.y * scaleY,
+ width: result.cropRect.width * scaleX,
+ height: result.cropRect.height * scaleY,
+ };
+ } else if (imageDimensions) {
+ const scaleX = imageDimensions.width / layer.transform.width;
+ const scaleY = imageDimensions.height / layer.transform.height;
+ finalCropRect = {
+ x: result.cropRect.x * scaleX,
+ y: result.cropRect.y * scaleY,
+ width: result.cropRect.width * scaleX,
+ height: result.cropRect.height * scaleY,
+ };
+ } else {
+ finalCropRect = result.cropRect;
+ }
+
updateLayer<ImageLayer>(result.layerId, {
- cropRect: result.cropRect,
+ cropRect: finalCropRect,
+ transform: {
+ ...layer.transform,
+ x: layer.transform.x + result.cropRect.x,
+ y: layer.transform.y + result.cropRect.y,
+ width: result.cropRect.width,
+ height: result.cropRect.height,
+ },
});
}
- }, [applyCrop, updateLayer]);
+ }, [applyCrop, updateLayer, layer, imageDimensions]);
const handleResetCrop = useCallback(() => {
if (isCropping) {
diff --git a/apps/image/src/components/editor/inspector/EffectsSection.tsx b/apps/image/src/components/editor/inspector/EffectsSection.tsx
index 10b5e4f2..82d6c3cc 100644
--- a/apps/image/src/components/editor/inspector/EffectsSection.tsx
+++ b/apps/image/src/components/editor/inspector/EffectsSection.tsx
@@ -1,8 +1,6 @@
import { useProjectStore } from '../../../stores/project-store';
import type { Layer, Shadow, InnerShadow, Stroke, Glow } from '../../../types/project';
import { Slider } from '@openreel/ui';
-import { Switch } from '@openreel/ui';
-import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@openreel/ui';
import { ChevronDown, Droplets, Pencil, Sparkles, CircleDot } from 'lucide-react';
import { useState } from 'react';
@@ -12,6 +10,43 @@ interface Props {
type EffectSection = 'shadow' | 'innerShadow' | 'stroke' | 'glow' | null;
+interface EffectHeaderProps {
+ icon: React.ElementType;
+ label: string;
+ enabled: boolean;
+ isOpen: boolean;
+ onToggle: () => void;
+ onEnabledChange: (enabled: boolean) => void;
+}
+
+function EffectHeader({ icon: Icon, label, enabled, isOpen, onToggle, onEnabledChange }: EffectHeaderProps) {
+ return (
+ <div className="w-full flex items-center justify-between p-2 rounded-lg bg-secondary/50 hover:bg-secondary transition-colors">
+ <button
+ onClick={onToggle}
+ className="flex items-center gap-2 flex-1 text-left"
+ >
+ <Icon size={14} className="text-muted-foreground" />
+ <span className="text-xs font-medium">{label}</span>
+ </button>
+ <div className="flex items-center gap-2">
+ <label className="relative inline-flex items-center cursor-pointer">
+ <input
+ type="checkbox"
+ checked={enabled}
+ onChange={(e) => onEnabledChange(e.target.checked)}
+ className="sr-only peer"
+ />
+ <div className="w-8 h-4 bg-muted rounded-full peer peer-checked:bg-primary transition-colors after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:after:translate-x-4" />
+ </label>
+ <button onClick={onToggle} className="p-0.5">
+ <ChevronDown size={14} className={`text-muted-foreground transition-transform ${isOpen ? 'rotate-180' : ''}`} />
+ </button>
+ </div>
+ </div>
+ );
+}
+
export function EffectsSection({ layer }: Props) {
const { updateLayer } = useProjectStore();
const [openSection, setOpenSection] = useState<EffectSection>('shadow');
@@ -40,30 +75,23 @@ export function EffectsSection({ layer }: Props) {
});
};
+ const toggleSection = (section: EffectSection) => {
+ setOpenSection(openSection === section ? null : section);
+ };
+
return (
- <div className="space-y-2">
- <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
- Effects
- </h4>
+ <div className="px-4 space-y-2">
- <Collapsible open={openSection === 'shadow'} onOpenChange={(open) => setOpenSection(open ? 'shadow' : null)}>
- <CollapsibleTrigger asChild>
- <button className="w-full flex items-center justify-between p-2 rounded-lg bg-secondary/50 hover:bg-secondary transition-colors">
- <div className="flex items-center gap-2">
- <Droplets size={14} className="text-muted-foreground" />
- <span className="text-xs font-medium">Drop Shadow</span>
- </div>
- <div className="flex items-center gap-2">
- <Switch
- checked={layer.shadow.enabled}
- onCheckedChange={(enabled) => handleShadowChange({ enabled })}
- onClick={(e) => e.stopPropagation()}
- />
- <ChevronDown size={14} className={`text-muted-foreground transition-transform ${openSection === 'shadow' ? 'rotate-180' : ''}`} />
- </div>
- </button>
- </CollapsibleTrigger>
- <CollapsibleContent>
+ <div>
+ <EffectHeader
+ icon={Droplets}
+ label="Drop Shadow"
+ enabled={layer.shadow.enabled}
+ isOpen={openSection === 'shadow'}
+ onToggle={() => toggleSection('shadow')}
+ onEnabledChange={(enabled) => handleShadowChange({ enabled })}
+ />
+ {openSection === 'shadow' && (
<div className="p-3 space-y-3 bg-background/50 rounded-b-lg border border-t-0 border-border">
<div>
<label className="block text-[10px] text-muted-foreground mb-1.5">Color</label>
@@ -131,27 +159,19 @@ export function EffectsSection({ layer }: Props) {
</div>
</div>
</div>
- </CollapsibleContent>
- </Collapsible>
+ )}
+ </div>
- <Collapsible open={openSection === 'innerShadow'} onOpenChange={(open) => setOpenSection(open ? 'innerShadow' : null)}>
- <CollapsibleTrigger asChild>
- <button className="w-full flex items-center justify-between p-2 rounded-lg bg-secondary/50 hover:bg-secondary transition-colors">
- <div className="flex items-center gap-2">
- <CircleDot size={14} className="text-muted-foreground" />
- <span className="text-xs font-medium">Inner Shadow</span>
- </div>
- <div className="flex items-center gap-2">
- <Switch
- checked={layer.innerShadow?.enabled ?? false}
- onCheckedChange={(enabled) => handleInnerShadowChange({ enabled })}
- onClick={(e) => e.stopPropagation()}
- />
- <ChevronDown size={14} className={`text-muted-foreground transition-transform ${openSection === 'innerShadow' ? 'rotate-180' : ''}`} />
- </div>
- </button>
- </CollapsibleTrigger>
- <CollapsibleContent>
+ <div>
+ <EffectHeader
+ icon={CircleDot}
+ label="Inner Shadow"
+ enabled={layer.innerShadow?.enabled ?? false}
+ isOpen={openSection === 'innerShadow'}
+ onToggle={() => toggleSection('innerShadow')}
+ onEnabledChange={(enabled) => handleInnerShadowChange({ enabled })}
+ />
+ {openSection === 'innerShadow' && (
<div className="p-3 space-y-3 bg-background/50 rounded-b-lg border border-t-0 border-border">
<div>
<label className="block text-[10px] text-muted-foreground mb-1.5">Color</label>
@@ -219,27 +239,19 @@ export function EffectsSection({ layer }: Props) {
</div>
</div>
</div>
- </CollapsibleContent>
- </Collapsible>
+ )}
+ </div>
- <Collapsible open={openSection === 'stroke'} onOpenChange={(open) => setOpenSection(open ? 'stroke' : null)}>
- <CollapsibleTrigger asChild>
- <button className="w-full flex items-center justify-between p-2 rounded-lg bg-secondary/50 hover:bg-secondary transition-colors">
- <div className="flex items-center gap-2">
- <Pencil size={14} className="text-muted-foreground" />
- <span className="text-xs font-medium">Stroke</span>
- </div>
- <div className="flex items-center gap-2">
- <Switch
- checked={layer.stroke.enabled}
- onCheckedChange={(enabled) => handleStrokeChange({ enabled })}
- onClick={(e) => e.stopPropagation()}
- />
- <ChevronDown size={14} className={`text-muted-foreground transition-transform ${openSection === 'stroke' ? 'rotate-180' : ''}`} />
- </div>
- </button>
- </CollapsibleTrigger>
- <CollapsibleContent>
+ <div>
+ <EffectHeader
+ icon={Pencil}
+ label="Stroke"
+ enabled={layer.stroke.enabled}
+ isOpen={openSection === 'stroke'}
+ onToggle={() => toggleSection('stroke')}
+ onEnabledChange={(enabled) => handleStrokeChange({ enabled })}
+ />
+ {openSection === 'stroke' && (
<div className="p-3 space-y-3 bg-background/50 rounded-b-lg border border-t-0 border-border">
<div>
<label className="block text-[10px] text-muted-foreground mb-1.5">Color</label>
@@ -296,27 +308,19 @@ export function EffectsSection({ layer }: Props) {
</div>
</div>
</div>
- </CollapsibleContent>
- </Collapsible>
+ )}
+ </div>
- <Collapsible open={openSection === 'glow'} onOpenChange={(open) => setOpenSection(open ? 'glow' : null)}>
- <CollapsibleTrigger asChild>
- <button className="w-full flex items-center justify-between p-2 rounded-lg bg-secondary/50 hover:bg-secondary transition-colors">
- <div className="flex items-center gap-2">
- <Sparkles size={14} className="text-muted-foreground" />
- <span className="text-xs font-medium">Outer Glow</span>
- </div>
- <div className="flex items-center gap-2">
- <Switch
- checked={layer.glow.enabled}
- onCheckedChange={(enabled) => handleGlowChange({ enabled })}
- onClick={(e) => e.stopPropagation()}
- />
- <ChevronDown size={14} className={`text-muted-foreground transition-transform ${openSection === 'glow' ? 'rotate-180' : ''}`} />
- </div>
- </button>
- </CollapsibleTrigger>
- <CollapsibleContent>
+ <div>
+ <EffectHeader
+ icon={Sparkles}
+ label="Outer Glow"
+ enabled={layer.glow.enabled}
+ isOpen={openSection === 'glow'}
+ onToggle={() => toggleSection('glow')}
+ onEnabledChange={(enabled) => handleGlowChange({ enabled })}
+ />
+ {openSection === 'glow' && (
<div className="p-3 space-y-3 bg-background/50 rounded-b-lg border border-t-0 border-border">
<div>
<label className="block text-[10px] text-muted-foreground mb-1.5">Color</label>
@@ -368,8 +372,8 @@ export function EffectsSection({ layer }: Props) {
/>
</div>
</div>
- </CollapsibleContent>
- </Collapsible>
+ )}
+ </div>
</div>
);
}
diff --git a/apps/image/src/components/editor/inspector/GradientToolPanel.tsx b/apps/image/src/components/editor/inspector/GradientToolPanel.tsx
new file mode 100644
index 00000000..371c7a63
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/GradientToolPanel.tsx
@@ -0,0 +1,176 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { SquareStack, RotateCcw, X, Plus } from 'lucide-react';
+
+const gradientTypes = [
+ { id: 'linear', label: 'Linear' },
+ { id: 'radial', label: 'Radial' },
+ { id: 'angle', label: 'Angle' },
+ { id: 'reflected', label: 'Reflected' },
+ { id: 'diamond', label: 'Diamond' },
+] as const;
+
+export function GradientToolPanel() {
+ const { gradientSettings, setGradientSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setGradientSettings({
+ type: 'linear',
+ colors: ['#000000', '#ffffff'],
+ opacity: 1,
+ reverse: false,
+ dither: true,
+ });
+ };
+
+ const updateColor = (index: number, color: string) => {
+ const newColors = [...gradientSettings.colors];
+ newColors[index] = color;
+ setGradientSettings({ colors: newColors });
+ };
+
+ const addColor = () => {
+ if (gradientSettings.colors.length >= 5) return;
+ const newColors = [...gradientSettings.colors, '#808080'];
+ setGradientSettings({ colors: newColors });
+ };
+
+ const removeColor = (index: number) => {
+ if (gradientSettings.colors.length <= 2) return;
+ const newColors = gradientSettings.colors.filter((_, i) => i !== index);
+ setGradientSettings({ colors: newColors });
+ };
+
+ const gradientStyle = `linear-gradient(to right, ${gradientSettings.colors.join(', ')})`;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <SquareStack size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Gradient</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ Click and drag on canvas to create gradient.
+ </p>
+
+ <div className="space-y-3">
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Type</span>
+ <div className="grid grid-cols-5 gap-1">
+ {gradientTypes.map((type) => (
+ <button
+ key={type.id}
+ onClick={() => setGradientSettings({ type: type.id })}
+ className={`px-1 py-1.5 text-[10px] rounded transition-colors ${
+ gradientSettings.type === type.id
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ >
+ {type.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Preview</span>
+ <div
+ className="h-6 rounded border border-border"
+ style={{ background: gradientStyle }}
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Colors</span>
+ {gradientSettings.colors.length < 5 && (
+ <button
+ onClick={addColor}
+ className="p-0.5 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ >
+ <Plus size={12} />
+ </button>
+ )}
+ </div>
+ <div className="space-y-1.5">
+ {gradientSettings.colors.map((color, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <input
+ type="color"
+ value={color}
+ onChange={(e) => updateColor(index, e.target.value)}
+ className="w-8 h-8 rounded border border-border cursor-pointer"
+ />
+ <input
+ type="text"
+ value={color}
+ onChange={(e) => updateColor(index, e.target.value)}
+ className="flex-1 px-2 py-1 text-xs font-mono bg-secondary/50 border border-border rounded"
+ />
+ {gradientSettings.colors.length > 2 && (
+ <button
+ onClick={() => removeColor(index)}
+ className="p-1 text-muted-foreground hover:text-destructive rounded hover:bg-secondary transition-colors"
+ >
+ <X size={12} />
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Opacity</span>
+ <span className="text-xs font-mono text-muted-foreground">{Math.round(gradientSettings.opacity * 100)}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={gradientSettings.opacity * 100}
+ onChange={(e) => setGradientSettings({ opacity: Number(e.target.value) / 100 })}
+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer
+ [&::-webkit-slider-thumb]:appearance-none
+ [&::-webkit-slider-thumb]:w-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div className="flex gap-4 pt-2 border-t border-border">
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={gradientSettings.reverse}
+ onChange={(e) => setGradientSettings({ reverse: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Reverse
+ </label>
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={gradientSettings.dither}
+ onChange={(e) => setGradientSettings({ dither: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Dither
+ </label>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/HealingBrushToolPanel.tsx b/apps/image/src/components/editor/inspector/HealingBrushToolPanel.tsx
new file mode 100644
index 00000000..0926af8f
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/HealingBrushToolPanel.tsx
@@ -0,0 +1,117 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { Bandage, RotateCcw } from 'lucide-react';
+
+export function HealingBrushToolPanel() {
+ const { healingBrushSettings, setHealingBrushSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setHealingBrushSettings({
+ size: 30,
+ hardness: 50,
+ mode: 'normal',
+ sourcePoint: null,
+ aligned: true,
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Bandage size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Healing Brush</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ Hold Alt/Option and click to set source, then paint to heal while matching texture and lighting.
+ </p>
+
+ {healingBrushSettings.sourcePoint && (
+ <div className="text-xs text-muted-foreground bg-secondary/50 p-2 rounded">
+ Source: ({Math.round(healingBrushSettings.sourcePoint.x)}, {Math.round(healingBrushSettings.sourcePoint.y)})
+ </div>
+ )}
+
+ <div className="space-y-3">
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Size</span>
+ <span className="text-xs font-mono text-muted-foreground">{healingBrushSettings.size}px</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={500}
+ value={healingBrushSettings.size}
+ onChange={(e) => setHealingBrushSettings({ size: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Hardness</span>
+ <span className="text-xs font-mono text-muted-foreground">{healingBrushSettings.hardness}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={healingBrushSettings.hardness}
+ onChange={(e) => setHealingBrushSettings({ hardness: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Mode</span>
+ <div className="grid grid-cols-2 gap-1">
+ {(['normal', 'replace', 'multiply', 'screen'] as const).map((mode) => (
+ <button
+ key={mode}
+ onClick={() => setHealingBrushSettings({ mode })}
+ className={`px-2 py-1.5 text-xs rounded transition-colors capitalize ${
+ healingBrushSettings.mode === mode
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ >
+ {mode}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="pt-2 border-t border-border">
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={healingBrushSettings.aligned}
+ onChange={(e) => setHealingBrushSettings({ aligned: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Aligned
+ </label>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/Inspector.tsx b/apps/image/src/components/editor/inspector/Inspector.tsx
index 7868af27..984a90b9 100644
--- a/apps/image/src/components/editor/inspector/Inspector.tsx
+++ b/apps/image/src/components/editor/inspector/Inspector.tsx
@@ -1,4 +1,4 @@
-import { memo, lazy, Suspense } from 'react';
+import { memo, lazy, Suspense, useState, createContext, useContext, ReactNode, JSX } from 'react';
import { useProjectStore } from '../../../stores/project-store';
import { useUIStore } from '../../../stores/ui-store';
import { TransformSection } from './TransformSection';
@@ -8,7 +8,18 @@ import { EffectsSection } from './EffectsSection';
import { ArtboardSection } from './ArtboardSection';
import { PenSettingsSection } from './PenSettingsSection';
import { ColorHarmonySection } from './ColorHarmonySection';
+import { ChevronRight, Sliders, Palette, Wand2, Sparkles, Image as ImageIcon, Layers } from 'lucide-react';
+import { ScrollArea } from '@openreel/ui';
import type { Layer, ImageLayer, TextLayer, ShapeLayer } from '../../../types/project';
+import type { Tool } from '../../../stores/ui-store';
+
+const TOOL_FOCUSED_TOOLS = new Set<Tool>([
+ 'pen', 'brush', 'eraser', 'gradient', 'paint-bucket',
+ 'dodge', 'burn', 'sponge', 'blur', 'sharpen', 'smudge',
+ 'clone-stamp', 'healing-brush', 'spot-healing', 'liquify',
+ 'marquee-rect', 'marquee-ellipse', 'lasso', 'lasso-polygon', 'magic-wand',
+ 'free-transform', 'warp', 'perspective', 'crop'
+]);
const ImageAdjustmentsSection = lazy(() => import('./ImageAdjustmentsSection').then(m => ({ default: m.ImageAdjustmentsSection })));
const FilterPresetsSection = lazy(() => import('./FilterPresetsSection').then(m => ({ default: m.FilterPresetsSection })));
@@ -31,173 +42,425 @@ const MaskSection = lazy(() => import('./MaskSection').then(m => ({ default: m.M
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 })));
+const CloneStampToolPanel = lazy(() => import('./CloneStampToolPanel').then(m => ({ default: m.CloneStampToolPanel })));
+const HealingBrushToolPanel = lazy(() => import('./HealingBrushToolPanel').then(m => ({ default: m.HealingBrushToolPanel })));
+const SpotHealingToolPanel = lazy(() => import('./SpotHealingToolPanel').then(m => ({ default: m.SpotHealingToolPanel })));
+const SpongeToolPanel = lazy(() => import('./SpongeToolPanel').then(m => ({ default: m.SpongeToolPanel })));
+const LiquifyToolPanel = lazy(() => import('./LiquifyToolPanel').then(m => ({ default: m.LiquifyToolPanel })));
+const TransformToolPanel = lazy(() => import('./TransformToolPanel').then(m => ({ default: m.TransformToolPanel })));
+const BrushToolPanel = lazy(() => import('./BrushToolPanel').then(m => ({ default: m.BrushToolPanel })));
+const BlurSharpenToolPanel = lazy(() => import('./BlurSharpenToolPanel').then(m => ({ default: m.BlurSharpenToolPanel })));
+const SmudgeToolPanel = lazy(() => import('./SmudgeToolPanel').then(m => ({ default: m.SmudgeToolPanel })));
+const GradientToolPanel = lazy(() => import('./GradientToolPanel').then(m => ({ default: m.GradientToolPanel })));
+const PaintBucketToolPanel = lazy(() => import('./PaintBucketToolPanel').then(m => ({ default: m.PaintBucketToolPanel })));
function SectionLoader() {
- return <div className="h-8 animate-pulse bg-muted/30 rounded" />;
+ return (
+ <div className="px-4 py-3">
+ <div className="h-4 w-24 animate-pulse bg-muted/40 rounded mb-3" />
+ <div className="space-y-2">
+ <div className="h-8 animate-pulse bg-muted/30 rounded" />
+ <div className="h-8 animate-pulse bg-muted/30 rounded" />
+ </div>
+ </div>
+ );
}
-function InspectorContent() {
- const { project, selectedLayerIds, selectedArtboardId } = useProjectStore();
- const { activeTool } = useUIStore();
+type AccordionContextType = {
+ openItems: string[];
+ toggle: (id: string) => void;
+};
- const selectedLayers = selectedLayerIds
- .map((id) => project?.layers[id])
- .filter((layer): layer is Layer => layer !== undefined);
+const AccordionContext = createContext<AccordionContextType | null>(null);
- const singleLayer = selectedLayers.length === 1 ? selectedLayers[0] : null;
+interface AccordionProps {
+ children: ReactNode;
+ defaultOpen?: string[];
+}
- const isSelectionTool = [
- 'marquee-rect',
- 'marquee-ellipse',
- 'lasso',
- 'lasso-polygon',
- 'magic-wand',
- ].includes(activeTool);
+function Accordion({ children, defaultOpen = [] }: AccordionProps) {
+ const [openItems, setOpenItems] = useState<string[]>(defaultOpen);
- if (selectedLayers.length === 0) {
- if (activeTool === 'pen') {
- return (
- <div className="p-4">
- <PenSettingsSection />
+ const toggle = (id: string) => {
+ setOpenItems(prev =>
+ prev.includes(id)
+ ? prev.filter(item => item !== id)
+ : [...prev, id]
+ );
+ };
+
+ return (
+ <AccordionContext.Provider value={{ openItems, toggle }}>
+ <div className="divide-y divide-border">{children}</div>
+ </AccordionContext.Provider>
+ );
+}
+
+interface AccordionItemProps {
+ id: string;
+ icon?: React.ElementType;
+ title: string;
+ children: ReactNode;
+ badge?: number;
+}
+
+function AccordionItem({ id, icon: Icon, title, children, badge }: AccordionItemProps) {
+ const context = useContext(AccordionContext);
+ if (!context) return null;
+
+ const { openItems, toggle } = context;
+ const isOpen = openItems.includes(id);
+
+ return (
+ <div>
+ <button
+ onClick={() => toggle(id)}
+ className="w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-muted/30 transition-colors"
+ >
+ <ChevronRight
+ size={14}
+ className={`text-muted-foreground shrink-0 transition-transform duration-200 ${isOpen ? 'rotate-90' : ''}`}
+ />
+ {Icon && <Icon size={16} className="text-muted-foreground shrink-0" />}
+ <span className="text-sm font-medium text-foreground flex-1">{title}</span>
+ {badge !== undefined && badge > 0 && (
+ <span className="text-[10px] font-medium text-primary bg-primary/10 px-1.5 py-0.5 rounded-full">
+ {badge}
+ </span>
+ )}
+ </button>
+ {isOpen && (
+ <div className="pb-4">
+ {children}
</div>
- );
- }
+ )}
+ </div>
+ );
+}
+
+function renderToolPanel(tool: Tool, imageLayer?: ImageLayer): JSX.Element | null {
+ const SELECTION_TOOLS = ['marquee-rect', 'marquee-ellipse', 'lasso', 'lasso-polygon', 'magic-wand'];
+ const TRANSFORM_TOOLS = ['free-transform', 'warp', 'perspective'];
+
+ if (SELECTION_TOOLS.includes(tool)) {
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <SelectionToolsPanel />
+ </Suspense>
+ );
+ }
+
+ if (TRANSFORM_TOOLS.includes(tool)) {
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <TransformToolPanel />
+ </Suspense>
+ );
+ }
- if (isSelectionTool) {
+ switch (tool) {
+ case 'pen':
+ return <PenSettingsSection />;
+ case 'brush':
return (
- <div className="p-4">
- <Suspense fallback={<SectionLoader />}>
- <SelectionToolsPanel />
- </Suspense>
- </div>
+ <Suspense fallback={<SectionLoader />}>
+ <BrushToolPanel />
+ </Suspense>
);
- }
-
- if (activeTool === 'eraser') {
+ case 'eraser':
return (
- <div className="p-4">
+ <Suspense fallback={<SectionLoader />}>
+ <EraserToolPanel />
+ </Suspense>
+ );
+ case 'gradient':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <GradientToolPanel />
+ </Suspense>
+ );
+ case 'dodge':
+ case 'burn':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <DodgeBurnToolPanel />
+ </Suspense>
+ );
+ case 'sponge':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <SpongeToolPanel />
+ </Suspense>
+ );
+ case 'blur':
+ case 'sharpen':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <BlurSharpenToolPanel />
+ </Suspense>
+ );
+ case 'smudge':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <SmudgeToolPanel />
+ </Suspense>
+ );
+ case 'clone-stamp':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <CloneStampToolPanel />
+ </Suspense>
+ );
+ case 'healing-brush':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <HealingBrushToolPanel />
+ </Suspense>
+ );
+ case 'spot-healing':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <SpotHealingToolPanel />
+ </Suspense>
+ );
+ case 'liquify':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <LiquifyToolPanel />
+ </Suspense>
+ );
+ case 'paint-bucket':
+ return (
+ <Suspense fallback={<SectionLoader />}>
+ <PaintBucketToolPanel />
+ </Suspense>
+ );
+ case 'crop':
+ if (imageLayer) {
+ return (
<Suspense fallback={<SectionLoader />}>
- <EraserToolPanel />
+ <CropSection layer={imageLayer} />
</Suspense>
- </div>
+ );
+ }
+ return null;
+ default:
+ return null;
+ }
+}
+
+function InspectorContent() {
+ const { project, selectedLayerIds, selectedArtboardId } = useProjectStore();
+ const { activeTool } = useUIStore();
+
+ const selectedLayers = selectedLayerIds
+ .map((id) => project?.layers[id])
+ .filter((layer): layer is Layer => layer !== undefined);
+
+ const singleLayer = selectedLayers.length === 1 ? selectedLayers[0] : null;
+ const imageLayer = singleLayer?.type === 'image' ? (singleLayer as ImageLayer) : undefined;
+
+ if (TOOL_FOCUSED_TOOLS.has(activeTool)) {
+ const toolPanel = renderToolPanel(activeTool, imageLayer);
+ if (toolPanel) {
+ return (
+ <ScrollArea className="h-full">
+ <div className="p-4">
+ {toolPanel}
+ </div>
+ </ScrollArea>
);
}
+ }
- if (activeTool === 'dodge' || activeTool === 'burn') {
- return (
+ if (selectedLayers.length > 1) {
+ return (
+ <ScrollArea className="h-full">
<div className="p-4">
- <Suspense fallback={<SectionLoader />}>
- <DodgeBurnToolPanel />
- </Suspense>
+ <div className="flex items-center gap-2 mb-6">
+ <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center">
+ <Layers size={16} className="text-primary" />
+ </div>
+ <div>
+ <h3 className="text-sm font-semibold text-foreground">
+ {selectedLayers.length} layers
+ </h3>
+ <p className="text-xs text-muted-foreground">Multiple selection</p>
+ </div>
+ </div>
+ <AlignmentSection layers={selectedLayers} />
</div>
- );
- }
+ </ScrollArea>
+ );
+ }
+ if (!singleLayer) {
const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);
if (artboard) {
return (
- <div className="p-4">
- <h3 className="text-sm font-medium text-foreground mb-4">Artboard</h3>
- <ArtboardSection artboard={artboard} />
- </div>
+ <ScrollArea className="h-full">
+ <div className="p-4">
+ <h3 className="text-sm font-semibold text-foreground mb-4">Artboard</h3>
+ <ArtboardSection artboard={artboard} />
+ </div>
+ </ScrollArea>
);
}
return (
- <div className="p-4 text-center">
- <p className="text-sm text-muted-foreground">
- Select a layer to edit its properties
- </p>
- </div>
- );
- }
-
- if (selectedLayers.length > 1) {
- return (
- <div className="p-4 space-y-6">
- <div className="flex items-center justify-between">
- <h3 className="text-sm font-medium text-foreground">
- {selectedLayers.length} layers selected
- </h3>
+ <div className="h-full flex items-center justify-center p-6">
+ <div className="text-center">
+ <div className="w-12 h-12 mx-auto mb-3 rounded-full bg-muted/50 flex items-center justify-center">
+ <Layers size={20} className="text-muted-foreground" />
+ </div>
+ <p className="text-sm text-muted-foreground">
+ Select a layer to view<br />and edit its properties
+ </p>
</div>
- <AlignmentSection layers={selectedLayers} />
</div>
);
}
- if (!singleLayer) return null;
+ const getLayerIcon = () => {
+ switch (singleLayer.type) {
+ case 'image': return ImageIcon;
+ case 'text': return () => <span className="text-sm font-bold">T</span>;
+ case 'shape': return () => <span className="text-sm">◆</span>;
+ default: return Layers;
+ }
+ };
+
+ const LayerIcon = getLayerIcon();
return (
- <div className="p-4 space-y-6">
- <div>
- <h3 className="text-sm font-medium text-foreground mb-1 truncate">
- {singleLayer.name}
- </h3>
- <p className="text-xs text-muted-foreground capitalize">{singleLayer.type} layer</p>
- </div>
+ <ScrollArea className="h-full">
+ <div className="pb-8">
+ <div className="px-4 py-4 border-b border-border bg-card/50">
+ <div className="flex items-center gap-3">
+ <div className="w-10 h-10 rounded-lg bg-muted/50 flex items-center justify-center shrink-0">
+ <LayerIcon size={18} className="text-muted-foreground" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <h3 className="text-sm font-semibold text-foreground truncate">
+ {singleLayer.name}
+ </h3>
+ <p className="text-xs text-muted-foreground capitalize">{singleLayer.type} layer</p>
+ </div>
+ </div>
+ </div>
- <TransformSection layer={singleLayer} />
+ <Accordion defaultOpen={['transform', 'appearance', 'quick-filters', 'basic-adjustments']}>
+ <AccordionItem id="transform" icon={Sliders} title="Transform & Position">
+ <div className="px-4 space-y-4">
+ <TransformSection layer={singleLayer} />
+ <div className="pt-2">
+ <AlignmentSection layers={[singleLayer]} />
+ </div>
+ </div>
+ </AccordionItem>
- <AlignmentSection layers={[singleLayer]} />
+ <AccordionItem id="appearance" icon={Palette} title="Appearance">
+ <div className="px-4">
+ <AppearanceSection layer={singleLayer} />
+ </div>
+ </AccordionItem>
- <AppearanceSection layer={singleLayer} />
+ <AccordionItem id="effects" icon={Sparkles} title="Effects">
+ <EffectsSection layer={singleLayer} />
+ </AccordionItem>
- <EffectsSection layer={singleLayer} />
+ {singleLayer.type === 'image' && (
+ <Suspense fallback={<SectionLoader />}>
+ <AccordionItem id="image-controls" icon={ImageIcon} title="Image Controls">
+ <div className="px-4 space-y-4">
+ <ImageControlsSection layer={singleLayer as ImageLayer} />
+ <CropSection layer={singleLayer as ImageLayer} />
+ <BackgroundRemovalSection layer={singleLayer as ImageLayer} />
+ </div>
+ </AccordionItem>
- {singleLayer.type === 'image' && (
- <Suspense fallback={<SectionLoader />}>
- <ImageControlsSection layer={singleLayer as ImageLayer} />
- <CropSection layer={singleLayer as ImageLayer} />
- <BackgroundRemovalSection layer={singleLayer as ImageLayer} />
- <FilterPresetsSection layer={singleLayer as ImageLayer} />
- <ImageAdjustmentsSection layer={singleLayer as ImageLayer} />
- <LevelsSection layer={singleLayer} />
- <CurvesSection layer={singleLayer} />
- <ColorBalanceSection layer={singleLayer} />
- <SelectiveColorSection layer={singleLayer} />
- <BlackWhiteSection layer={singleLayer} />
- <PhotoFilterSection layer={singleLayer} />
- <ChannelMixerSection layer={singleLayer} />
- <GradientMapSection layer={singleLayer} />
- <PosterizeSection layer={singleLayer} />
- <ThresholdSection layer={singleLayer} />
- </Suspense>
- )}
+ <AccordionItem id="quick-filters" icon={Wand2} title="Quick Filters">
+ <FilterPresetsSection layer={singleLayer as ImageLayer} />
+ </AccordionItem>
- <Suspense fallback={<SectionLoader />}>
- <MaskSection layer={singleLayer} />
- </Suspense>
+ <AccordionItem id="basic-adjustments" icon={Sliders} title="Basic Adjustments">
+ <ImageAdjustmentsSection layer={singleLayer as ImageLayer} />
+ </AccordionItem>
- {singleLayer.type === 'text' && (
- <Suspense fallback={<SectionLoader />}>
- <TextSection layer={singleLayer as TextLayer} />
- <ColorHarmonySection
- baseColor={(singleLayer as TextLayer).style.color}
- onColorSelect={(color) => {
- useProjectStore.getState().updateLayer<TextLayer>(singleLayer.id, {
- style: { ...(singleLayer as TextLayer).style, color },
- });
- }}
- />
- </Suspense>
- )}
+ <AccordionItem id="tonal" icon={Sliders} title="Tonal Adjustments">
+ <div className="space-y-0">
+ <LevelsSection layer={singleLayer} />
+ <CurvesSection layer={singleLayer} />
+ <PosterizeSection layer={singleLayer} />
+ <ThresholdSection layer={singleLayer} />
+ </div>
+ </AccordionItem>
- {singleLayer.type === 'shape' && (
- <Suspense fallback={<SectionLoader />}>
- <ShapeSection layer={singleLayer as ShapeLayer} />
- {(singleLayer as ShapeLayer).shapeStyle.fill && (
- <ColorHarmonySection
- baseColor={(singleLayer as ShapeLayer).shapeStyle.fill!}
- onColorSelect={(color) => {
- useProjectStore.getState().updateLayer<ShapeLayer>(singleLayer.id, {
- shapeStyle: { ...(singleLayer as ShapeLayer).shapeStyle, fill: color },
- });
- }}
- />
+ <AccordionItem id="color" icon={Palette} title="Color Adjustments">
+ <div className="space-y-0">
+ <ColorBalanceSection layer={singleLayer} />
+ <SelectiveColorSection layer={singleLayer} />
+ <PhotoFilterSection layer={singleLayer} />
+ <ChannelMixerSection layer={singleLayer} />
+ <GradientMapSection layer={singleLayer} />
+ <BlackWhiteSection layer={singleLayer} />
+ </div>
+ </AccordionItem>
+
+ <AccordionItem id="mask" icon={Layers} title="Mask">
+ <MaskSection layer={singleLayer} />
+ </AccordionItem>
+ </Suspense>
)}
- </Suspense>
- )}
- </div>
+
+ {singleLayer.type === 'text' && (
+ <Suspense fallback={<SectionLoader />}>
+ <AccordionItem id="text-settings" title="Text Settings">
+ <div className="px-4">
+ <TextSection layer={singleLayer as TextLayer} />
+ </div>
+ </AccordionItem>
+ <AccordionItem id="color-harmony" icon={Palette} title="Color Harmony">
+ <div className="px-4">
+ <ColorHarmonySection
+ baseColor={(singleLayer as TextLayer).style.color}
+ onColorSelect={(color) => {
+ useProjectStore.getState().updateLayer<TextLayer>(singleLayer.id, {
+ style: { ...(singleLayer as TextLayer).style, color },
+ });
+ }}
+ />
+ </div>
+ </AccordionItem>
+ </Suspense>
+ )}
+
+ {singleLayer.type === 'shape' && (
+ <Suspense fallback={<SectionLoader />}>
+ <AccordionItem id="shape-settings" title="Shape Settings">
+ <div className="px-4">
+ <ShapeSection layer={singleLayer as ShapeLayer} />
+ </div>
+ </AccordionItem>
+ {(singleLayer as ShapeLayer).shapeStyle.fill && (
+ <AccordionItem id="color-harmony" icon={Palette} title="Color Harmony">
+ <div className="px-4">
+ <ColorHarmonySection
+ baseColor={(singleLayer as ShapeLayer).shapeStyle.fill!}
+ onColorSelect={(color) => {
+ useProjectStore.getState().updateLayer<ShapeLayer>(singleLayer.id, {
+ shapeStyle: { ...(singleLayer as ShapeLayer).shapeStyle, fill: color },
+ });
+ }}
+ />
+ </div>
+ </AccordionItem>
+ )}
+ </Suspense>
+ )}
+ </Accordion>
+ </div>
+ </ScrollArea>
);
}
diff --git a/apps/image/src/components/editor/inspector/LiquifyToolPanel.tsx b/apps/image/src/components/editor/inspector/LiquifyToolPanel.tsx
new file mode 100644
index 00000000..2bf770d3
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/LiquifyToolPanel.tsx
@@ -0,0 +1,152 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { Waves, RotateCcw, ArrowRight, Undo2, Sparkles, RotateCw, RotateCcw as Counterclockwise, Minus, Plus, ArrowLeft, Snowflake, Flame } from 'lucide-react';
+
+const liquifyTools = [
+ { id: 'forward-warp', label: 'Forward Warp', icon: ArrowRight },
+ { id: 'reconstruct', label: 'Reconstruct', icon: Undo2 },
+ { id: 'smooth', label: 'Smooth', icon: Sparkles },
+ { id: 'twirl-clockwise', label: 'Twirl CW', icon: RotateCw },
+ { id: 'twirl-counterclockwise', label: 'Twirl CCW', icon: Counterclockwise },
+ { id: 'pucker', label: 'Pucker', icon: Minus },
+ { id: 'bloat', label: 'Bloat', icon: Plus },
+ { id: 'push-left', label: 'Push Left', icon: ArrowLeft },
+ { id: 'freeze', label: 'Freeze', icon: Snowflake },
+ { id: 'thaw', label: 'Thaw', icon: Flame },
+] as const;
+
+export function LiquifyToolPanel() {
+ const { liquifySettings, setLiquifySettings } = useUIStore();
+
+ const resetSettings = () => {
+ setLiquifySettings({
+ brushSize: 100,
+ brushDensity: 50,
+ brushPressure: 100,
+ brushRate: 80,
+ tool: 'forward-warp',
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Waves size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Liquify</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <div className="space-y-3">
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Tool</span>
+ <div className="grid grid-cols-5 gap-1">
+ {liquifyTools.map((tool) => {
+ const Icon = tool.icon;
+ return (
+ <button
+ key={tool.id}
+ onClick={() => setLiquifySettings({ tool: tool.id })}
+ className={`p-2 rounded transition-colors ${
+ liquifySettings.tool === tool.id
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ title={tool.label}
+ >
+ <Icon size={14} />
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Brush Size</span>
+ <span className="text-xs font-mono text-muted-foreground">{liquifySettings.brushSize}px</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={1500}
+ value={liquifySettings.brushSize}
+ onChange={(e) => setLiquifySettings({ brushSize: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Density</span>
+ <span className="text-xs font-mono text-muted-foreground">{liquifySettings.brushDensity}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={liquifySettings.brushDensity}
+ onChange={(e) => setLiquifySettings({ brushDensity: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Pressure</span>
+ <span className="text-xs font-mono text-muted-foreground">{liquifySettings.brushPressure}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={liquifySettings.brushPressure}
+ onChange={(e) => setLiquifySettings({ brushPressure: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Rate</span>
+ <span className="text-xs font-mono text-muted-foreground">{liquifySettings.brushRate}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={liquifySettings.brushRate}
+ onChange={(e) => setLiquifySettings({ brushRate: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/PaintBucketToolPanel.tsx b/apps/image/src/components/editor/inspector/PaintBucketToolPanel.tsx
new file mode 100644
index 00000000..46ec658a
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/PaintBucketToolPanel.tsx
@@ -0,0 +1,120 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { PaintBucket, RotateCcw } from 'lucide-react';
+
+export function PaintBucketToolPanel() {
+ const { paintBucketSettings, setPaintBucketSettings, brushSettings, setBrushSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setPaintBucketSettings({
+ color: '#000000',
+ tolerance: 32,
+ contiguous: true,
+ antiAlias: true,
+ opacity: 1,
+ fillType: 'foreground',
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <PaintBucket size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Paint Bucket</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ Click on canvas to fill area with color.
+ </p>
+
+ <div className="space-y-3">
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Fill Color</span>
+ <div className="flex items-center gap-2">
+ <input
+ type="color"
+ value={brushSettings.color}
+ onChange={(e) => setBrushSettings({ color: e.target.value })}
+ className="w-10 h-10 rounded border border-border cursor-pointer"
+ />
+ <input
+ type="text"
+ value={brushSettings.color}
+ onChange={(e) => setBrushSettings({ color: e.target.value })}
+ className="flex-1 px-2 py-1.5 text-xs font-mono bg-secondary/50 border border-border rounded"
+ />
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Tolerance</span>
+ <span className="text-xs font-mono text-muted-foreground">{paintBucketSettings.tolerance}</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={255}
+ value={paintBucketSettings.tolerance}
+ onChange={(e) => setPaintBucketSettings({ tolerance: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Opacity</span>
+ <span className="text-xs font-mono text-muted-foreground">{Math.round(paintBucketSettings.opacity * 100)}%</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={paintBucketSettings.opacity * 100}
+ onChange={(e) => setPaintBucketSettings({ opacity: Number(e.target.value) / 100 })}
+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer
+ [&::-webkit-slider-thumb]:appearance-none
+ [&::-webkit-slider-thumb]:w-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div className="space-y-2 pt-2 border-t border-border">
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={paintBucketSettings.contiguous}
+ onChange={(e) => setPaintBucketSettings({ contiguous: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Contiguous
+ </label>
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={paintBucketSettings.antiAlias}
+ onChange={(e) => setPaintBucketSettings({ antiAlias: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Anti-alias
+ </label>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/SelectionToolsPanel.tsx b/apps/image/src/components/editor/inspector/SelectionToolsPanel.tsx
index 7aa9e18b..bc9f909c 100644
--- a/apps/image/src/components/editor/inspector/SelectionToolsPanel.tsx
+++ b/apps/image/src/components/editor/inspector/SelectionToolsPanel.tsx
@@ -1,3 +1,4 @@
+import { useState } from 'react';
import { useUIStore } from '../../../stores/ui-store';
import { useSelectionStore } from '../../../stores/selection-store';
import { useProjectStore } from '../../../stores/project-store';
@@ -14,6 +15,8 @@ import {
RotateCcw,
Download,
Upload,
+ ChevronDown,
+ X,
} from 'lucide-react';
interface SliderProps {
@@ -71,13 +74,19 @@ export function SelectionToolsPanel() {
const {
active: selection,
+ saved: savedSelections,
clearSelection,
invertSelection,
featherSelection,
expandSelection,
contractSelection,
+ saveSelection,
+ loadSelection,
+ deleteSelection,
} = useSelectionStore();
+ const [showLoadMenu, setShowLoadMenu] = useState(false);
+
const { project } = useProjectStore();
const artboard = project?.artboards?.find((a) => a.id === project.activeArtboardId);
const canvasBounds = artboard
@@ -256,21 +265,56 @@ export function SelectionToolsPanel() {
<div className="flex gap-1.5">
<button
- onClick={() => {}}
+ onClick={() => saveSelection(`Selection ${savedSelections.length + 1}`)}
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 className="flex-1 relative">
+ <button
+ onClick={() => setShowLoadMenu(!showLoadMenu)}
+ disabled={savedSelections.length === 0}
+ className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-[10px] rounded bg-secondary hover:bg-secondary/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ title="Load Selection"
+ >
+ <Upload size={10} />
+ Load
+ {savedSelections.length > 0 && (
+ <ChevronDown size={8} className={`transition-transform ${showLoadMenu ? 'rotate-180' : ''}`} />
+ )}
+ </button>
+ {showLoadMenu && savedSelections.length > 0 && (
+ <div className="absolute top-full left-0 right-0 mt-1 bg-popover border border-border rounded-md shadow-lg z-10 max-h-32 overflow-y-auto">
+ {savedSelections.map((sel, idx) => (
+ <div
+ key={sel.id}
+ className="flex items-center justify-between px-2 py-1.5 hover:bg-secondary/50 group"
+ >
+ <button
+ onClick={() => {
+ loadSelection(sel.id);
+ setShowLoadMenu(false);
+ }}
+ className="flex-1 text-left text-[10px] text-foreground truncate"
+ >
+ Selection {idx + 1}
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ deleteSelection(sel.id);
+ }}
+ className="p-0.5 text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"
+ >
+ <X size={10} />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
</div>
</div>
)}
diff --git a/apps/image/src/components/editor/inspector/SmudgeToolPanel.tsx b/apps/image/src/components/editor/inspector/SmudgeToolPanel.tsx
new file mode 100644
index 00000000..2d5338da
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/SmudgeToolPanel.tsx
@@ -0,0 +1,100 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { Blend, RotateCcw } from 'lucide-react';
+
+export function SmudgeToolPanel() {
+ const { smudgeSettings, setSmudgeSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setSmudgeSettings({
+ size: 30,
+ strength: 50,
+ fingerPainting: false,
+ sampleAllLayers: false,
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Blend size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Smudge Tool</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ Drag to smudge and blend colors together.
+ </p>
+
+ <div className="space-y-3">
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Size</span>
+ <span className="text-xs font-mono text-muted-foreground">{smudgeSettings.size}px</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={500}
+ value={smudgeSettings.size}
+ onChange={(e) => setSmudgeSettings({ size: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Strength</span>
+ <span className="text-xs font-mono text-muted-foreground">{smudgeSettings.strength}%</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={100}
+ value={smudgeSettings.strength}
+ onChange={(e) => setSmudgeSettings({ strength: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div className="flex flex-col gap-2 pt-2 border-t border-border">
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={smudgeSettings.fingerPainting}
+ onChange={(e) => setSmudgeSettings({ fingerPainting: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Finger Painting
+ </label>
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={smudgeSettings.sampleAllLayers}
+ onChange={(e) => setSmudgeSettings({ sampleAllLayers: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Sample All Layers
+ </label>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/SpongeToolPanel.tsx b/apps/image/src/components/editor/inspector/SpongeToolPanel.tsx
new file mode 100644
index 00000000..672e88b9
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/SpongeToolPanel.tsx
@@ -0,0 +1,104 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { Droplet, RotateCcw } from 'lucide-react';
+
+export function SpongeToolPanel() {
+ const { spongeSettings, setSpongeSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setSpongeSettings({
+ size: 30,
+ flow: 50,
+ mode: 'desaturate',
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Droplet size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Sponge Tool</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ Paint to saturate or desaturate color in specific areas.
+ </p>
+
+ <div className="space-y-3">
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Mode</span>
+ <div className="grid grid-cols-2 gap-1">
+ <button
+ onClick={() => setSpongeSettings({ mode: 'desaturate' })}
+ className={`px-3 py-2 text-xs rounded transition-colors ${
+ spongeSettings.mode === 'desaturate'
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ >
+ Desaturate
+ </button>
+ <button
+ onClick={() => setSpongeSettings({ mode: 'saturate' })}
+ className={`px-3 py-2 text-xs rounded transition-colors ${
+ spongeSettings.mode === 'saturate'
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ >
+ Saturate
+ </button>
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Size</span>
+ <span className="text-xs font-mono text-muted-foreground">{spongeSettings.size}px</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={500}
+ value={spongeSettings.size}
+ onChange={(e) => setSpongeSettings({ size: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Flow</span>
+ <span className="text-xs font-mono text-muted-foreground">{spongeSettings.flow}%</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={100}
+ value={spongeSettings.flow}
+ onChange={(e) => setSpongeSettings({ flow: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/SpotHealingToolPanel.tsx b/apps/image/src/components/editor/inspector/SpotHealingToolPanel.tsx
new file mode 100644
index 00000000..79dc7776
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/SpotHealingToolPanel.tsx
@@ -0,0 +1,93 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { Bandage, RotateCcw } from 'lucide-react';
+
+export function SpotHealingToolPanel() {
+ const { spotHealingSettings, setSpotHealingSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setSpotHealingSettings({
+ size: 30,
+ type: 'content-aware',
+ sampleAllLayers: false,
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Bandage size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Spot Healing Brush</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ Paint over blemishes or imperfections to automatically remove them.
+ </p>
+
+ <div className="space-y-3">
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-xs text-muted-foreground">Size</span>
+ <span className="text-xs font-mono text-muted-foreground">{spotHealingSettings.size}px</span>
+ </div>
+ <input
+ type="range"
+ min={1}
+ max={500}
+ value={spotHealingSettings.size}
+ onChange={(e) => setSpotHealingSettings({ size: 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-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary"
+ />
+ </div>
+
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Type</span>
+ <div className="flex flex-col gap-1">
+ {([
+ { id: 'content-aware', label: 'Content-Aware' },
+ { id: 'proximity-match', label: 'Proximity Match' },
+ { id: 'create-texture', label: 'Create Texture' },
+ ] as const).map((option) => (
+ <button
+ key={option.id}
+ onClick={() => setSpotHealingSettings({ type: option.id })}
+ className={`px-3 py-2 text-xs rounded transition-colors text-left ${
+ spotHealingSettings.type === option.id
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="pt-2 border-t border-border">
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={spotHealingSettings.sampleAllLayers}
+ onChange={(e) => setSpotHealingSettings({ sampleAllLayers: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Sample All Layers
+ </label>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/TransformToolPanel.tsx b/apps/image/src/components/editor/inspector/TransformToolPanel.tsx
new file mode 100644
index 00000000..80a2bef2
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/TransformToolPanel.tsx
@@ -0,0 +1,103 @@
+import { useUIStore } from '../../../stores/ui-store';
+import { Move, RotateCcw, Scale, RotateCw, ArrowUpDown, Maximize2, Grid3x3 } from 'lucide-react';
+
+const transformModes = [
+ { id: 'free', label: 'Free', icon: Move },
+ { id: 'scale', label: 'Scale', icon: Scale },
+ { id: 'rotate', label: 'Rotate', icon: RotateCw },
+ { id: 'skew', label: 'Skew', icon: ArrowUpDown },
+ { id: 'distort', label: 'Distort', icon: Maximize2 },
+ { id: 'perspective', label: 'Perspective', icon: Maximize2 },
+ { id: 'warp', label: 'Warp', icon: Grid3x3 },
+] as const;
+
+export function TransformToolPanel() {
+ const { transformSettings, setTransformSettings } = useUIStore();
+
+ const resetSettings = () => {
+ setTransformSettings({
+ mode: 'free',
+ maintainAspectRatio: false,
+ interpolation: 'bicubic',
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Move size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium">Transform</h3>
+ </div>
+ <button
+ onClick={resetSettings}
+ className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-secondary transition-colors"
+ title="Reset"
+ >
+ <RotateCcw size={14} />
+ </button>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ Select a layer and use handles to transform. Press Enter to apply, Escape to cancel.
+ </p>
+
+ <div className="space-y-3">
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Mode</span>
+ <div className="grid grid-cols-4 gap-1">
+ {transformModes.map((mode) => {
+ const Icon = mode.icon;
+ return (
+ <button
+ key={mode.id}
+ onClick={() => setTransformSettings({ mode: mode.id })}
+ className={`flex flex-col items-center gap-1 p-2 rounded transition-colors ${
+ transformSettings.mode === mode.id
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ title={mode.label}
+ >
+ <Icon size={14} />
+ <span className="text-[9px]">{mode.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ <div>
+ <span className="text-xs text-muted-foreground mb-1.5 block">Interpolation</span>
+ <div className="grid grid-cols-3 gap-1">
+ {(['nearest', 'bilinear', 'bicubic'] as const).map((interp) => (
+ <button
+ key={interp}
+ onClick={() => setTransformSettings({ interpolation: interp })}
+ className={`px-2 py-1.5 text-xs rounded transition-colors capitalize ${
+ transformSettings.interpolation === interp
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary'
+ }`}
+ >
+ {interp}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="pt-2 border-t border-border">
+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={transformSettings.maintainAspectRatio}
+ onChange={(e) => setTransformSettings({ maintainAspectRatio: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-border"
+ />
+ Maintain Aspect Ratio (Shift)
+ </label>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/toolbar/Toolbar.tsx b/apps/image/src/components/editor/toolbar/Toolbar.tsx
index f9bf5b5a..d9a86da3 100644
--- a/apps/image/src/components/editor/toolbar/Toolbar.tsx
+++ b/apps/image/src/components/editor/toolbar/Toolbar.tsx
@@ -1,3 +1,4 @@
+import { useState, useRef, useEffect } from 'react';
import {
MousePointer2,
Hand,
@@ -14,22 +15,228 @@ import {
PanelRightClose,
Home,
ChevronDown,
+ SquareDashed,
+ Circle,
+ Lasso,
+ Wand2,
+ Crop,
+ Eraser,
+ Paintbrush,
+ PaintBucket,
+ Stamp,
+ Bandage,
+ Droplet,
+ Droplets,
+ Blend,
+ Move,
+ Maximize2,
+ Grid3x3,
+ Waves,
+ Sun,
+ Moon,
+ Spline,
+ SquareStack,
} from 'lucide-react';
import { useUIStore, Tool } from '../../../stores/ui-store';
import { useProjectStore } from '../../../stores/project-store';
import { useHistoryStore } from '../../../stores/history-store';
import { ZoomControl } from './ZoomControl';
-const tools: { id: Tool; icon: React.ElementType; label: string; shortcut: string }[] = [
- { id: 'select', icon: MousePointer2, label: 'Select', shortcut: 'V' },
- { id: 'hand', icon: Hand, label: 'Hand', shortcut: 'H' },
- { id: 'text', icon: Type, label: 'Text', shortcut: 'T' },
- { id: 'shape', icon: Square, label: 'Shape', shortcut: 'S' },
- { id: 'pen', icon: PenTool, label: 'Pen', shortcut: 'P' },
- { id: 'eyedropper', icon: Pipette, label: 'Eyedropper', shortcut: 'I' },
- { id: 'zoom', icon: ZoomIn, label: 'Zoom', shortcut: 'Z' },
+interface ToolItem {
+ id: Tool;
+ icon: React.ElementType;
+ label: string;
+ shortcut?: string;
+}
+
+interface ToolGroup {
+ id: string;
+ label: string;
+ tools: ToolItem[];
+}
+
+const toolGroups: ToolGroup[] = [
+ {
+ id: 'navigation',
+ label: 'Navigation',
+ tools: [
+ { id: 'select', icon: MousePointer2, label: 'Move', shortcut: 'V' },
+ { id: 'hand', icon: Hand, label: 'Hand', shortcut: 'H' },
+ { id: 'zoom', icon: ZoomIn, label: 'Zoom', shortcut: 'Z' },
+ ],
+ },
+ {
+ id: 'selection',
+ label: 'Selection',
+ tools: [
+ { id: 'marquee-rect', icon: SquareDashed, label: 'Rectangular Marquee', shortcut: 'M' },
+ { id: 'marquee-ellipse', icon: Circle, label: 'Elliptical Marquee', shortcut: 'M' },
+ { id: 'lasso', icon: Lasso, label: 'Lasso', shortcut: 'L' },
+ { id: 'lasso-polygon', icon: Spline, label: 'Polygon Lasso', shortcut: 'L' },
+ { id: 'magic-wand', icon: Wand2, label: 'Magic Wand', shortcut: 'W' },
+ ],
+ },
+ {
+ id: 'crop-transform',
+ label: 'Crop & Transform',
+ tools: [
+ { id: 'crop', icon: Crop, label: 'Crop', shortcut: 'C' },
+ { id: 'free-transform', icon: Move, label: 'Free Transform', shortcut: 'T' },
+ { id: 'perspective', icon: Maximize2, label: 'Perspective', shortcut: '' },
+ { id: 'warp', icon: Grid3x3, label: 'Warp', shortcut: '' },
+ { id: 'liquify', icon: Waves, label: 'Liquify', shortcut: '' },
+ ],
+ },
+ {
+ id: 'paint',
+ label: 'Paint',
+ tools: [
+ { id: 'brush', icon: Paintbrush, label: 'Brush', shortcut: 'B' },
+ { id: 'eraser', icon: Eraser, label: 'Eraser', shortcut: 'E' },
+ { id: 'paint-bucket', icon: PaintBucket, label: 'Paint Bucket', shortcut: 'G' },
+ { id: 'gradient', icon: SquareStack, label: 'Gradient', shortcut: 'G' },
+ ],
+ },
+ {
+ id: 'retouch',
+ label: 'Retouch',
+ tools: [
+ { id: 'clone-stamp', icon: Stamp, label: 'Clone Stamp', shortcut: 'S' },
+ { id: 'healing-brush', icon: Bandage, label: 'Healing Brush', shortcut: 'J' },
+ { id: 'spot-healing', icon: Bandage, label: 'Spot Healing', shortcut: 'J' },
+ ],
+ },
+ {
+ id: 'adjust',
+ label: 'Adjust',
+ tools: [
+ { id: 'dodge', icon: Sun, label: 'Dodge', shortcut: 'O' },
+ { id: 'burn', icon: Moon, label: 'Burn', shortcut: 'O' },
+ { id: 'sponge', icon: Droplet, label: 'Sponge', shortcut: 'O' },
+ { id: 'blur', icon: Droplets, label: 'Blur', shortcut: 'R' },
+ { id: 'sharpen', icon: Droplets, label: 'Sharpen', shortcut: 'R' },
+ { id: 'smudge', icon: Blend, label: 'Smudge', shortcut: 'R' },
+ ],
+ },
+ {
+ id: 'draw',
+ label: 'Draw',
+ tools: [
+ { id: 'pen', icon: PenTool, label: 'Pen', shortcut: 'P' },
+ { id: 'shape', icon: Square, label: 'Shape', shortcut: 'U' },
+ { id: 'text', icon: Type, label: 'Text', shortcut: 'T' },
+ ],
+ },
+ {
+ id: 'sample',
+ label: 'Sample',
+ tools: [{ id: 'eyedropper', icon: Pipette, label: 'Eyedropper', shortcut: 'I' }],
+ },
];
+function ToolGroupButton({
+ group,
+ activeTool,
+ onSelectTool,
+}: {
+ group: ToolGroup;
+ activeTool: Tool;
+ onSelectTool: (tool: Tool) => void;
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [selectedIndex, setSelectedIndex] = useState(0);
+ const menuRef = useRef<HTMLDivElement>(null);
+
+ const isGroupActive = group.tools.some((t) => t.id === activeTool);
+ const currentTool = group.tools.find((t) => t.id === activeTool) || group.tools[selectedIndex];
+ const Icon = currentTool.icon;
+
+ useEffect(() => {
+ const handleClickOutside = (e: MouseEvent) => {
+ if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
+ setIsOpen(false);
+ }
+ };
+
+ if (isOpen) {
+ document.addEventListener('mousedown', handleClickOutside);
+ }
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }, [isOpen]);
+
+ const handleToolSelect = (tool: ToolItem, index: number) => {
+ setSelectedIndex(index);
+ onSelectTool(tool.id);
+ setIsOpen(false);
+ };
+
+ if (group.tools.length === 1) {
+ return (
+ <button
+ onClick={() => onSelectTool(group.tools[0].id)}
+ className={`p-2 rounded-md transition-all ${
+ isGroupActive
+ ? 'bg-primary text-primary-foreground shadow-sm'
+ : 'text-muted-foreground hover:text-foreground hover:bg-accent'
+ }`}
+ title={`${currentTool.label}${currentTool.shortcut ? ` (${currentTool.shortcut})` : ''}`}
+ >
+ <Icon size={18} />
+ </button>
+ );
+ }
+
+ return (
+ <div ref={menuRef} className="relative">
+ <button
+ onClick={() => onSelectTool(currentTool.id)}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ setIsOpen(!isOpen);
+ }}
+ className={`relative p-2 rounded-md transition-all group ${
+ isGroupActive
+ ? 'bg-primary text-primary-foreground shadow-sm'
+ : 'text-muted-foreground hover:text-foreground hover:bg-accent'
+ }`}
+ title={`${currentTool.label}${currentTool.shortcut ? ` (${currentTool.shortcut})` : ''} - Right-click for more`}
+ >
+ <Icon size={18} />
+ <span
+ className={`absolute bottom-0.5 right-0.5 w-0 h-0 border-l-[4px] border-l-transparent border-b-[4px] ${
+ isGroupActive ? 'border-b-primary-foreground/60' : 'border-b-muted-foreground/40'
+ }`}
+ />
+ </button>
+
+ {isOpen && (
+ <div className="absolute left-full top-0 ml-1 z-50 py-1 bg-popover border border-border rounded-lg shadow-lg min-w-[180px]">
+ {group.tools.map((tool, index) => {
+ const ToolIcon = tool.icon;
+ return (
+ <button
+ key={tool.id}
+ onClick={() => handleToolSelect(tool, index)}
+ className={`w-full flex items-center gap-3 px-3 py-2 text-sm transition-colors ${
+ activeTool === tool.id
+ ? 'bg-accent text-foreground'
+ : 'text-muted-foreground hover:text-foreground hover:bg-accent/50'
+ }`}
+ >
+ <ToolIcon size={16} />
+ <span className="flex-1 text-left">{tool.label}</span>
+ {tool.shortcut && (
+ <span className="text-xs text-muted-foreground/60">{tool.shortcut}</span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
+
export function Toolbar() {
const {
activeTool,
@@ -102,24 +309,15 @@ export function Toolbar() {
<div className="flex-1" />
- <div className="flex items-center gap-1 bg-secondary/50 rounded-lg p-1">
- {tools.map((tool) => {
- const Icon = tool.icon;
- return (
- <button
- key={tool.id}
- onClick={() => setActiveTool(tool.id)}
- className={`p-2 rounded-md transition-all ${
- activeTool === tool.id
- ? 'bg-primary text-primary-foreground shadow-sm'
- : 'text-muted-foreground hover:text-foreground hover:bg-accent'
- }`}
- title={`${tool.label} (${tool.shortcut})`}
- >
- <Icon size={18} />
- </button>
- );
- })}
+ <div className="flex items-center gap-0.5 bg-secondary/50 rounded-lg p-1">
+ {toolGroups.map((group, idx) => (
+ <div key={group.id} className="flex items-center">
+ <ToolGroupButton group={group} activeTool={activeTool} onSelectTool={setActiveTool} />
+ {idx < toolGroups.length - 1 && idx % 2 === 1 && (
+ <div className="w-px h-5 bg-border/50 mx-0.5" />
+ )}
+ </div>
+ ))}
</div>
<div className="flex-1" />
diff --git a/apps/image/src/stores/canvas-store.ts b/apps/image/src/stores/canvas-store.ts
index 255604a9..aad76d86 100644
--- a/apps/image/src/stores/canvas-store.ts
+++ b/apps/image/src/stores/canvas-store.ts
@@ -27,7 +27,7 @@ export interface SnapResult {
guides: SmartGuide[];
}
-export type DragMode = 'none' | 'move' | 'resize' | 'rotate' | 'marquee' | 'pan';
+export type DragMode = 'none' | 'move' | 'resize' | 'rotate' | 'marquee' | 'pan' | 'paint' | 'crop';
export type ResizeHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
interface CanvasState {
diff --git a/apps/image/src/stores/ui-store.ts b/apps/image/src/stores/ui-store.ts
index f4cac453..bcca82e5 100644
--- a/apps/image/src/stores/ui-store.ts
+++ b/apps/image/src/stores/ui-store.ts
@@ -18,7 +18,21 @@ export type Tool =
| 'magic-wand'
| 'eraser'
| 'dodge'
- | 'burn';
+ | 'burn'
+ | 'brush'
+ | 'clone-stamp'
+ | 'healing-brush'
+ | 'spot-healing'
+ | 'sponge'
+ | 'smudge'
+ | 'blur'
+ | 'sharpen'
+ | 'gradient'
+ | 'paint-bucket'
+ | 'free-transform'
+ | 'warp'
+ | 'perspective'
+ | 'liquify';
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';
@@ -28,6 +42,8 @@ export interface CropState {
layerId: string | null;
aspectRatio: CropAspectRatio;
cropRect: { x: number; y: number; width: number; height: number } | null;
+ lockAspect: boolean;
+ initialAspectRatio: number | null;
}
export interface PenSettings {
@@ -64,6 +80,90 @@ export interface DodgeBurnSettings {
size: number;
}
+export interface BrushSettings {
+ size: number;
+ hardness: number;
+ opacity: number;
+ flow: number;
+ color: string;
+ blendMode: 'normal' | 'multiply' | 'screen' | 'overlay';
+}
+
+export interface CloneStampSettings {
+ size: number;
+ hardness: number;
+ opacity: number;
+ flow: number;
+ aligned: boolean;
+ sampleAllLayers: boolean;
+ sourcePoint: { x: number; y: number } | null;
+}
+
+export interface HealingBrushSettings {
+ size: number;
+ hardness: number;
+ mode: 'normal' | 'replace' | 'multiply' | 'screen';
+ sourcePoint: { x: number; y: number } | null;
+ aligned: boolean;
+}
+
+export interface SpotHealingSettings {
+ size: number;
+ type: 'proximity-match' | 'create-texture' | 'content-aware';
+ sampleAllLayers: boolean;
+}
+
+export interface SpongeSettings {
+ size: number;
+ flow: number;
+ mode: 'desaturate' | 'saturate';
+}
+
+export interface SmudgeSettings {
+ size: number;
+ strength: number;
+ fingerPainting: boolean;
+ sampleAllLayers: boolean;
+}
+
+export interface BlurSharpenSettings {
+ size: number;
+ strength: number;
+ mode: 'blur' | 'sharpen';
+ sampleAllLayers: boolean;
+}
+
+export interface GradientSettings {
+ type: 'linear' | 'radial' | 'angle' | 'reflected' | 'diamond';
+ colors: string[];
+ opacity: number;
+ reverse: boolean;
+ dither: boolean;
+}
+
+export interface PaintBucketSettings {
+ color: string;
+ tolerance: number;
+ contiguous: boolean;
+ antiAlias: boolean;
+ opacity: number;
+ fillType: 'foreground' | 'pattern';
+}
+
+export interface TransformSettings {
+ mode: 'free' | 'scale' | 'rotate' | 'skew' | 'distort' | 'perspective' | 'warp';
+ maintainAspectRatio: boolean;
+ interpolation: 'nearest' | 'bilinear' | 'bicubic';
+}
+
+export interface LiquifySettings {
+ brushSize: number;
+ brushDensity: number;
+ brushPressure: number;
+ brushRate: number;
+ tool: 'forward-warp' | 'reconstruct' | 'smooth' | 'twirl-clockwise' | 'twirl-counterclockwise' | 'pucker' | 'bloat' | 'push-left' | 'freeze' | 'thaw';
+}
+
export interface DrawingState {
isDrawing: boolean;
currentPath: { x: number; y: number }[];
@@ -98,6 +198,17 @@ interface UIState {
selectionToolSettings: SelectionToolSettings;
magicWandSettings: MagicWandSettings;
dodgeBurnSettings: DodgeBurnSettings;
+ brushSettings: BrushSettings;
+ cloneStampSettings: CloneStampSettings;
+ healingBrushSettings: HealingBrushSettings;
+ spotHealingSettings: SpotHealingSettings;
+ spongeSettings: SpongeSettings;
+ smudgeSettings: SmudgeSettings;
+ blurSharpenSettings: BlurSharpenSettings;
+ gradientSettings: GradientSettings;
+ paintBucketSettings: PaintBucketSettings;
+ transformSettings: TransformSettings;
+ liquifySettings: LiquifySettings;
}
interface UIActions {
@@ -126,6 +237,7 @@ interface UIActions {
startCrop: (layerId: string, initialRect: { x: number; y: number; width: number; height: number }) => void;
updateCropRect: (rect: { x: number; y: number; width: number; height: number }) => void;
setCropAspectRatio: (ratio: CropAspectRatio) => void;
+ setCropLockAspect: (locked: boolean) => void;
cancelCrop: () => void;
applyCrop: () => { layerId: string; cropRect: { x: number; y: number; width: number; height: number } } | null;
openExportDialog: () => void;
@@ -142,6 +254,17 @@ interface UIActions {
setSelectionToolSettings: (settings: Partial<SelectionToolSettings>) => void;
setMagicWandSettings: (settings: Partial<MagicWandSettings>) => void;
setDodgeBurnSettings: (settings: Partial<DodgeBurnSettings>) => void;
+ setBrushSettings: (settings: Partial<BrushSettings>) => void;
+ setCloneStampSettings: (settings: Partial<CloneStampSettings>) => void;
+ setHealingBrushSettings: (settings: Partial<HealingBrushSettings>) => void;
+ setSpotHealingSettings: (settings: Partial<SpotHealingSettings>) => void;
+ setSpongeSettings: (settings: Partial<SpongeSettings>) => void;
+ setSmudgeSettings: (settings: Partial<SmudgeSettings>) => void;
+ setBlurSharpenSettings: (settings: Partial<BlurSharpenSettings>) => void;
+ setGradientSettings: (settings: Partial<GradientSettings>) => void;
+ setPaintBucketSettings: (settings: Partial<PaintBucketSettings>) => void;
+ setTransformSettings: (settings: Partial<TransformSettings>) => void;
+ setLiquifySettings: (settings: Partial<LiquifySettings>) => void;
}
const ZOOM_LEVELS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4, 5, 8];
@@ -171,6 +294,8 @@ export const useUIStore = create<UIState & UIActions>()(
layerId: null,
aspectRatio: 'free',
cropRect: null,
+ lockAspect: false,
+ initialAspectRatio: null,
},
isExportDialogOpen: false,
showShortcutsPanel: false,
@@ -208,9 +333,94 @@ export const useUIStore = create<UIState & UIActions>()(
exposure: 50,
size: 30,
},
+ brushSettings: {
+ size: 20,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ color: '#000000',
+ blendMode: 'normal',
+ },
+ cloneStampSettings: {
+ size: 30,
+ hardness: 50,
+ opacity: 1,
+ flow: 1,
+ aligned: true,
+ sampleAllLayers: false,
+ sourcePoint: null,
+ },
+ healingBrushSettings: {
+ size: 30,
+ hardness: 50,
+ mode: 'normal',
+ sourcePoint: null,
+ aligned: true,
+ },
+ spotHealingSettings: {
+ size: 30,
+ type: 'content-aware',
+ sampleAllLayers: false,
+ },
+ spongeSettings: {
+ size: 30,
+ flow: 50,
+ mode: 'desaturate',
+ },
+ smudgeSettings: {
+ size: 30,
+ strength: 50,
+ fingerPainting: false,
+ sampleAllLayers: false,
+ },
+ blurSharpenSettings: {
+ size: 30,
+ strength: 50,
+ mode: 'blur',
+ sampleAllLayers: false,
+ },
+ gradientSettings: {
+ type: 'linear',
+ colors: ['#000000', '#ffffff'],
+ opacity: 1,
+ reverse: false,
+ dither: true,
+ },
+ paintBucketSettings: {
+ color: '#000000',
+ tolerance: 32,
+ contiguous: true,
+ antiAlias: true,
+ opacity: 1,
+ fillType: 'foreground',
+ },
+ transformSettings: {
+ mode: 'free',
+ maintainAspectRatio: false,
+ interpolation: 'bicubic',
+ },
+ liquifySettings: {
+ brushSize: 100,
+ brushDensity: 50,
+ brushPressure: 100,
+ brushRate: 80,
+ tool: 'forward-warp',
+ },
setCurrentView: (view) => set({ currentView: view }),
- setActiveTool: (tool) => set({ activeTool: tool }),
+ setActiveTool: (tool) => {
+ const updates: Partial<UIState> = { activeTool: tool };
+ if (tool === 'blur') {
+ updates.blurSharpenSettings = { ...get().blurSharpenSettings, mode: 'blur' };
+ } else if (tool === 'sharpen') {
+ updates.blurSharpenSettings = { ...get().blurSharpenSettings, mode: 'sharpen' };
+ } else if (tool === 'dodge') {
+ updates.dodgeBurnSettings = { ...get().dodgeBurnSettings, type: 'dodge' };
+ } else if (tool === 'burn') {
+ updates.dodgeBurnSettings = { ...get().dodgeBurnSettings, type: 'burn' };
+ }
+ set(updates);
+ },
setActivePanel: (panel) => set({ activePanel: panel }),
togglePanelCollapsed: () => set((s) => ({ isPanelCollapsed: !s.isPanelCollapsed })),
toggleInspectorCollapsed: () => set((s) => ({ isInspectorCollapsed: !s.isInspectorCollapsed })),
@@ -262,6 +472,8 @@ export const useUIStore = create<UIState & UIActions>()(
layerId,
aspectRatio: 'free',
cropRect: initialRect,
+ lockAspect: false,
+ initialAspectRatio: initialRect.width / initialRect.height,
},
activeTool: 'crop',
}),
@@ -276,6 +488,17 @@ export const useUIStore = create<UIState & UIActions>()(
crop: { ...s.crop, aspectRatio: ratio },
})),
+ setCropLockAspect: (locked) =>
+ set((s) => ({
+ crop: {
+ ...s.crop,
+ lockAspect: locked,
+ initialAspectRatio: locked && s.crop.cropRect
+ ? s.crop.cropRect.width / s.crop.cropRect.height
+ : s.crop.initialAspectRatio,
+ },
+ })),
+
cancelCrop: () =>
set({
crop: {
@@ -283,6 +506,8 @@ export const useUIStore = create<UIState & UIActions>()(
layerId: null,
aspectRatio: 'free',
cropRect: null,
+ lockAspect: false,
+ initialAspectRatio: null,
},
activeTool: 'select',
}),
@@ -299,6 +524,8 @@ export const useUIStore = create<UIState & UIActions>()(
layerId: null,
aspectRatio: 'free',
cropRect: null,
+ lockAspect: false,
+ initialAspectRatio: null,
},
activeTool: 'select',
});
@@ -374,5 +601,60 @@ export const useUIStore = create<UIState & UIActions>()(
set((s) => ({
dodgeBurnSettings: { ...s.dodgeBurnSettings, ...settings },
})),
+
+ setBrushSettings: (settings) =>
+ set((s) => ({
+ brushSettings: { ...s.brushSettings, ...settings },
+ })),
+
+ setCloneStampSettings: (settings) =>
+ set((s) => ({
+ cloneStampSettings: { ...s.cloneStampSettings, ...settings },
+ })),
+
+ setHealingBrushSettings: (settings) =>
+ set((s) => ({
+ healingBrushSettings: { ...s.healingBrushSettings, ...settings },
+ })),
+
+ setSpotHealingSettings: (settings) =>
+ set((s) => ({
+ spotHealingSettings: { ...s.spotHealingSettings, ...settings },
+ })),
+
+ setSpongeSettings: (settings) =>
+ set((s) => ({
+ spongeSettings: { ...s.spongeSettings, ...settings },
+ })),
+
+ setSmudgeSettings: (settings) =>
+ set((s) => ({
+ smudgeSettings: { ...s.smudgeSettings, ...settings },
+ })),
+
+ setBlurSharpenSettings: (settings) =>
+ set((s) => ({
+ blurSharpenSettings: { ...s.blurSharpenSettings, ...settings },
+ })),
+
+ setGradientSettings: (settings) =>
+ set((s) => ({
+ gradientSettings: { ...s.gradientSettings, ...settings },
+ })),
+
+ setPaintBucketSettings: (settings) =>
+ set((s) => ({
+ paintBucketSettings: { ...s.paintBucketSettings, ...settings },
+ })),
+
+ setTransformSettings: (settings) =>
+ set((s) => ({
+ transformSettings: { ...s.transformSettings, ...settings },
+ })),
+
+ setLiquifySettings: (settings) =>
+ set((s) => ({
+ liquifySettings: { ...s.liquifySettings, ...settings },
+ })),
}))
);
diff --git a/apps/image/src/tools/paint/blur-sharpen.ts b/apps/image/src/tools/paint/blur-sharpen.ts
new file mode 100644
index 00000000..4ebf00a6
--- /dev/null
+++ b/apps/image/src/tools/paint/blur-sharpen.ts
@@ -0,0 +1,264 @@
+import { BrushSettings, DEFAULT_BRUSH_SETTINGS } from '../brush/brush-engine';
+
+export type BlurSharpenMode = 'blur' | 'sharpen';
+
+export interface BlurSharpenSettings extends Omit<BrushSettings, 'color'> {
+ mode: BlurSharpenMode;
+ strength: number;
+ sampleAllLayers: boolean;
+}
+
+export const DEFAULT_BLUR_SHARPEN_SETTINGS: BlurSharpenSettings = {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 30,
+ hardness: 50,
+ mode: 'blur',
+ strength: 0.5,
+ sampleAllLayers: false,
+};
+
+export interface BlurSharpenStroke {
+ points: Array<{
+ x: number;
+ y: number;
+ pressure: number;
+ }>;
+ settings: BlurSharpenSettings;
+}
+
+export class BlurSharpenTool {
+ private settings: BlurSharpenSettings;
+ private canvas: OffscreenCanvas | null = null;
+ private ctx: OffscreenCanvasRenderingContext2D | null = null;
+ private isActive: boolean = false;
+ private currentStroke: BlurSharpenStroke | null = null;
+
+ constructor(settings: Partial<BlurSharpenSettings> = {}) {
+ this.settings = { ...DEFAULT_BLUR_SHARPEN_SETTINGS, ...settings };
+ }
+
+ setCanvas(canvas: OffscreenCanvas): void {
+ this.canvas = canvas;
+ this.ctx = canvas.getContext('2d', { willReadFrequently: true });
+ }
+
+ startStroke(x: number, y: number, pressure: number = 1): void {
+ this.isActive = true;
+ this.currentStroke = {
+ points: [{ x, y, pressure }],
+ settings: { ...this.settings },
+ };
+ }
+
+ continueStroke(x: number, y: number, pressure: number = 1): void {
+ if (!this.isActive || !this.currentStroke) return;
+ this.currentStroke.points.push({ x, y, pressure });
+ }
+
+ endStroke(): BlurSharpenStroke | null {
+ this.isActive = false;
+ const stroke = this.currentStroke;
+ this.currentStroke = null;
+ return stroke;
+ }
+
+ apply(
+ outputCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ x: number,
+ y: number,
+ pressure: number = 1
+ ): void {
+ if (!this.canvas || !this.ctx) return;
+
+ const size = Math.ceil(this.settings.size);
+ const halfSize = size / 2;
+
+ const targetX = Math.floor(x - halfSize);
+ const targetY = Math.floor(y - halfSize);
+
+ if (
+ targetX < 0 ||
+ targetY < 0 ||
+ targetX + size > this.canvas.width ||
+ targetY + size > this.canvas.height
+ ) {
+ return;
+ }
+
+ const imageData = this.ctx.getImageData(targetX, targetY, size, size);
+ const processedData = this.settings.mode === 'blur'
+ ? this.applyBlur(imageData, pressure)
+ : this.applySharpen(imageData, pressure);
+
+ this.applyBrushMask(processedData, size, this.settings.hardness);
+
+ const tempCanvas = new OffscreenCanvas(size, size);
+ const tempCtx = tempCanvas.getContext('2d')!;
+ tempCtx.putImageData(processedData, 0, 0);
+
+ outputCtx.save();
+ outputCtx.globalAlpha = this.settings.opacity;
+ outputCtx.drawImage(tempCanvas, targetX, targetY);
+ outputCtx.restore();
+ }
+
+ private applyBlur(imageData: ImageData, pressure: number): ImageData {
+ const { width, height, data } = imageData;
+ const result = new ImageData(new Uint8ClampedArray(data), width, height);
+ const strength = this.settings.strength * pressure;
+ const kernelSize = Math.max(3, Math.floor(strength * 7));
+ const halfKernel = Math.floor(kernelSize / 2);
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ let r = 0, g = 0, b = 0, count = 0;
+
+ for (let ky = -halfKernel; ky <= halfKernel; ky++) {
+ for (let kx = -halfKernel; kx <= halfKernel; kx++) {
+ const px = x + kx;
+ const py = y + ky;
+
+ if (px >= 0 && px < width && py >= 0 && py < height) {
+ const idx = (py * width + px) * 4;
+ r += data[idx];
+ g += data[idx + 1];
+ b += data[idx + 2];
+ count++;
+ }
+ }
+ }
+
+ const idx = (y * width + x) * 4;
+ const blend = strength;
+ result.data[idx] = Math.round(data[idx] * (1 - blend) + (r / count) * blend);
+ result.data[idx + 1] = Math.round(data[idx + 1] * (1 - blend) + (g / count) * blend);
+ result.data[idx + 2] = Math.round(data[idx + 2] * (1 - blend) + (b / count) * blend);
+ result.data[idx + 3] = data[idx + 3];
+ }
+ }
+
+ return result;
+ }
+
+ private applySharpen(imageData: ImageData, pressure: number): ImageData {
+ const { width, height, data } = imageData;
+ const result = new ImageData(new Uint8ClampedArray(data), width, height);
+ const strength = this.settings.strength * pressure * 2;
+
+ const kernel = [
+ 0, -1, 0,
+ -1, 5, -1,
+ 0, -1, 0,
+ ];
+
+ for (let y = 1; y < height - 1; y++) {
+ for (let x = 1; x < width - 1; x++) {
+ let r = 0, g = 0, b = 0;
+
+ for (let ky = -1; ky <= 1; ky++) {
+ for (let kx = -1; kx <= 1; kx++) {
+ const px = x + kx;
+ const py = y + ky;
+ const idx = (py * width + px) * 4;
+ const ki = (ky + 1) * 3 + (kx + 1);
+ r += data[idx] * kernel[ki];
+ g += data[idx + 1] * kernel[ki];
+ b += data[idx + 2] * kernel[ki];
+ }
+ }
+
+ const idx = (y * width + x) * 4;
+ result.data[idx] = Math.round(
+ data[idx] * (1 - strength) + Math.max(0, Math.min(255, r)) * strength
+ );
+ result.data[idx + 1] = Math.round(
+ data[idx + 1] * (1 - strength) + Math.max(0, Math.min(255, g)) * strength
+ );
+ result.data[idx + 2] = Math.round(
+ data[idx + 2] * (1 - strength) + Math.max(0, Math.min(255, b)) * strength
+ );
+ result.data[idx + 3] = data[idx + 3];
+ }
+ }
+
+ return result;
+ }
+
+ private applyBrushMask(imageData: ImageData, size: number, hardness: number): void {
+ const data = imageData.data;
+ const center = size / 2;
+ const radius = size / 2;
+ const hardnessNorm = hardness / 100;
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const dx = x - center;
+ const dy = y - center;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const normalizedDist = distance / radius;
+
+ let alpha = 1;
+ if (normalizedDist > hardnessNorm) {
+ alpha = 1 - (normalizedDist - hardnessNorm) / (1 - hardnessNorm);
+ alpha = Math.max(0, Math.min(1, alpha));
+ }
+ if (normalizedDist > 1) {
+ alpha = 0;
+ }
+
+ const idx = (y * size + x) * 4;
+ data[idx + 3] = Math.round(data[idx + 3] * alpha);
+ }
+ }
+ }
+
+ applyStroke(
+ outputCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ stroke: BlurSharpenStroke
+ ): void {
+ const { points, settings } = stroke;
+ if (points.length < 1) return;
+
+ const originalSettings = { ...this.settings };
+ this.settings = { ...settings };
+
+ const spacingPx = Math.max(1, (settings.size * settings.spacing) / 100);
+
+ for (let i = 0; i < points.length; i++) {
+ const point = points[i];
+
+ if (i > 0) {
+ const prev = points[i - 1];
+ const dx = point.x - prev.x;
+ const dy = point.y - prev.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const steps = Math.ceil(distance / spacingPx);
+
+ for (let step = 0; step < steps; step++) {
+ const t = step / steps;
+ const interpX = prev.x + dx * t;
+ const interpY = prev.y + dy * t;
+ const interpPressure = prev.pressure + (point.pressure - prev.pressure) * t;
+
+ this.apply(outputCtx, interpX, interpY, interpPressure);
+ }
+ }
+
+ this.apply(outputCtx, point.x, point.y, point.pressure);
+ }
+
+ this.settings = originalSettings;
+ }
+
+ getSettings(): BlurSharpenSettings {
+ return { ...this.settings };
+ }
+
+ updateSettings(settings: Partial<BlurSharpenSettings>): void {
+ this.settings = { ...this.settings, ...settings };
+ }
+
+ isActiveStroke(): boolean {
+ return this.isActive;
+ }
+}
diff --git a/apps/image/src/tools/paint/brush.ts b/apps/image/src/tools/paint/brush.ts
new file mode 100644
index 00000000..9c1c4664
--- /dev/null
+++ b/apps/image/src/tools/paint/brush.ts
@@ -0,0 +1,125 @@
+import { BrushEngine, BrushSettings, DEFAULT_BRUSH_SETTINGS, BrushStroke } from '../brush/brush-engine';
+
+export interface SimpleBrushSettings {
+ size: number;
+ hardness: number;
+ opacity: number;
+ flow: number;
+ color: string;
+ blendMode: 'normal' | 'multiply' | 'screen' | 'overlay';
+}
+
+export const DEFAULT_SIMPLE_BRUSH_SETTINGS: SimpleBrushSettings = {
+ size: 20,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ color: '#000000',
+ blendMode: 'normal',
+};
+
+export class BrushTool {
+ private settings: SimpleBrushSettings;
+ private engine: BrushEngine;
+ private isPainting: boolean = false;
+ private currentStroke: BrushStroke | null = null;
+
+ constructor(settings: Partial<SimpleBrushSettings> = {}) {
+ this.settings = { ...DEFAULT_SIMPLE_BRUSH_SETTINGS, ...settings };
+ this.engine = new BrushEngine(1920, 1080);
+ }
+
+ setCanvas(canvas: OffscreenCanvas): void {
+ this.engine.resize(canvas.width, canvas.height);
+ }
+
+ startStroke(x: number, y: number, pressure: number = 1): void {
+ this.isPainting = true;
+ this.currentStroke = {
+ points: [{ x, y, pressure, tilt: { x: 0, y: 0 }, timestamp: Date.now() }],
+ color: this.settings.color,
+ settings: this.convertToFullSettings(),
+ };
+ }
+
+ continueStroke(x: number, y: number, pressure: number = 1): void {
+ if (!this.isPainting || !this.currentStroke) return;
+ this.currentStroke.points.push({ x, y, pressure, tilt: { x: 0, y: 0 }, timestamp: Date.now() });
+ }
+
+ endStroke(): BrushStroke | null {
+ this.isPainting = false;
+ const stroke = this.currentStroke;
+ this.currentStroke = null;
+ return stroke;
+ }
+
+ apply(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ x: number,
+ y: number,
+ pressure: number = 1
+ ): void {
+ if (!this.currentStroke) return;
+
+ const startIndex = Math.max(0, this.currentStroke.points.length - 2);
+ this.currentStroke.points.push({ x, y, pressure, tilt: { x: 0, y: 0 }, timestamp: Date.now() });
+
+ ctx.save();
+
+ const blendModeMap: Record<string, GlobalCompositeOperation> = {
+ 'normal': 'source-over',
+ 'multiply': 'multiply',
+ 'screen': 'screen',
+ 'overlay': 'overlay',
+ };
+ ctx.globalCompositeOperation = blendModeMap[this.settings.blendMode] ?? 'source-over';
+
+ this.engine.drawStroke(ctx, this.currentStroke, startIndex);
+ ctx.restore();
+ }
+
+ applyFullStroke(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ stroke: BrushStroke
+ ): void {
+ ctx.save();
+
+ const blendModeMap: Record<string, GlobalCompositeOperation> = {
+ 'normal': 'source-over',
+ 'multiply': 'multiply',
+ 'screen': 'screen',
+ 'overlay': 'overlay',
+ };
+ ctx.globalCompositeOperation = blendModeMap[this.settings.blendMode] ?? 'source-over';
+
+ this.engine.drawStroke(ctx, stroke);
+ ctx.restore();
+ }
+
+ private convertToFullSettings(): BrushSettings {
+ return {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: this.settings.size,
+ hardness: this.settings.hardness,
+ opacity: this.settings.opacity,
+ flow: this.settings.flow,
+ };
+ }
+
+ getSettings(): SimpleBrushSettings {
+ return { ...this.settings };
+ }
+
+ updateSettings(settings: Partial<SimpleBrushSettings>): void {
+ this.settings = { ...this.settings, ...settings };
+ if (this.currentStroke) {
+ this.currentStroke.color = this.settings.color;
+ this.currentStroke.settings = this.convertToFullSettings();
+ }
+ }
+
+ isActive(): boolean {
+ return this.isPainting;
+ }
+}
diff --git a/apps/image/src/tools/paint/smudge.ts b/apps/image/src/tools/paint/smudge.ts
new file mode 100644
index 00000000..c9ded2df
--- /dev/null
+++ b/apps/image/src/tools/paint/smudge.ts
@@ -0,0 +1,226 @@
+import { BrushSettings, DEFAULT_BRUSH_SETTINGS } from '../brush/brush-engine';
+
+export interface SmudgeSettings extends Omit<BrushSettings, 'color'> {
+ strength: number;
+ fingerPainting: boolean;
+ sampleAllLayers: boolean;
+ fingerColor: string;
+}
+
+export const DEFAULT_SMUDGE_SETTINGS: SmudgeSettings = {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 30,
+ hardness: 50,
+ strength: 0.5,
+ fingerPainting: false,
+ sampleAllLayers: false,
+ fingerColor: '#000000',
+};
+
+export interface SmudgeStroke {
+ points: Array<{
+ x: number;
+ y: number;
+ pressure: number;
+ }>;
+ settings: SmudgeSettings;
+}
+
+export class SmudgeTool {
+ private settings: SmudgeSettings;
+ private canvas: OffscreenCanvas | null = null;
+ private ctx: OffscreenCanvasRenderingContext2D | null = null;
+ private isActive: boolean = false;
+ private currentStroke: SmudgeStroke | null = null;
+ private sampleBuffer: ImageData | null = null;
+ private lastX: number = 0;
+ private lastY: number = 0;
+
+ constructor(settings: Partial<SmudgeSettings> = {}) {
+ this.settings = { ...DEFAULT_SMUDGE_SETTINGS, ...settings };
+ }
+
+ setCanvas(canvas: OffscreenCanvas): void {
+ this.canvas = canvas;
+ this.ctx = canvas.getContext('2d', { willReadFrequently: true });
+ }
+
+ startStroke(x: number, y: number, pressure: number = 1): void {
+ if (!this.canvas || !this.ctx) return;
+
+ this.isActive = true;
+ this.lastX = x;
+ this.lastY = y;
+ this.currentStroke = {
+ points: [{ x, y, pressure }],
+ settings: { ...this.settings },
+ };
+
+ this.sampleAtPoint(x, y);
+ }
+
+ private sampleAtPoint(x: number, y: number): void {
+ if (!this.ctx || !this.canvas) return;
+
+ const size = Math.ceil(this.settings.size);
+ const halfSize = Math.floor(size / 2);
+
+ const sampleX = Math.max(0, Math.floor(x - halfSize));
+ const sampleY = Math.max(0, Math.floor(y - halfSize));
+ const sampleW = Math.min(size, this.canvas.width - sampleX);
+ const sampleH = Math.min(size, this.canvas.height - sampleY);
+
+ if (sampleW <= 0 || sampleH <= 0) return;
+
+ if (this.settings.fingerPainting && this.sampleBuffer === null) {
+ const tempCanvas = new OffscreenCanvas(size, size);
+ const tempCtx = tempCanvas.getContext('2d')!;
+ tempCtx.fillStyle = this.settings.fingerColor;
+ tempCtx.beginPath();
+ tempCtx.arc(size / 2, size / 2, size / 2, 0, Math.PI * 2);
+ tempCtx.fill();
+ this.sampleBuffer = tempCtx.getImageData(0, 0, size, size);
+ } else {
+ this.sampleBuffer = this.ctx.getImageData(sampleX, sampleY, sampleW, sampleH);
+ }
+ }
+
+ continueStroke(x: number, y: number, pressure: number = 1): void {
+ if (!this.isActive || !this.currentStroke || !this.ctx || !this.sampleBuffer) return;
+
+ this.currentStroke.points.push({ x, y, pressure });
+
+ const dx = x - this.lastX;
+ const dy = y - this.lastY;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+
+ if (distance < 1) return;
+
+ const steps = Math.ceil(distance);
+ for (let i = 1; i <= steps; i++) {
+ const t = i / steps;
+ const interpX = this.lastX + dx * t;
+ const interpY = this.lastY + dy * t;
+ this.applySmudge(interpX, interpY, pressure);
+ }
+
+ this.lastX = x;
+ this.lastY = y;
+ }
+
+ private applySmudge(x: number, y: number, pressure: number): void {
+ if (!this.ctx || !this.canvas || !this.sampleBuffer) return;
+
+ const size = this.sampleBuffer.width;
+ const halfSize = Math.floor(size / 2);
+
+ const targetX = Math.floor(x - halfSize);
+ const targetY = Math.floor(y - halfSize);
+
+ if (
+ targetX < 0 ||
+ targetY < 0 ||
+ targetX + size > this.canvas.width ||
+ targetY + size > this.canvas.height
+ ) {
+ return;
+ }
+
+ const targetData = this.ctx.getImageData(targetX, targetY, size, size);
+ const strength = this.settings.strength * pressure;
+
+ const center = size / 2;
+ const radius = size / 2;
+ const hardnessNorm = this.settings.hardness / 100;
+
+ for (let py = 0; py < size; py++) {
+ for (let px = 0; px < size; px++) {
+ const pxDist = Math.sqrt((px - center) ** 2 + (py - center) ** 2);
+ const normalizedDist = pxDist / radius;
+
+ if (normalizedDist > 1) continue;
+
+ let brushAlpha = 1;
+ if (normalizedDist > hardnessNorm) {
+ brushAlpha = 1 - (normalizedDist - hardnessNorm) / (1 - hardnessNorm);
+ brushAlpha = Math.max(0, Math.min(1, brushAlpha));
+ }
+
+ const idx = (py * size + px) * 4;
+ const blendStrength = strength * brushAlpha;
+
+ const sampleIdx = Math.min(idx, this.sampleBuffer.data.length - 4);
+
+ targetData.data[idx] = Math.round(
+ targetData.data[idx] * (1 - blendStrength) +
+ this.sampleBuffer.data[sampleIdx] * blendStrength
+ );
+ targetData.data[idx + 1] = Math.round(
+ targetData.data[idx + 1] * (1 - blendStrength) +
+ this.sampleBuffer.data[sampleIdx + 1] * blendStrength
+ );
+ targetData.data[idx + 2] = Math.round(
+ targetData.data[idx + 2] * (1 - blendStrength) +
+ this.sampleBuffer.data[sampleIdx + 2] * blendStrength
+ );
+ }
+ }
+
+ this.ctx.putImageData(targetData, targetX, targetY);
+
+ this.sampleBuffer = this.ctx.getImageData(targetX, targetY, size, size);
+ }
+
+ endStroke(): SmudgeStroke | null {
+ this.isActive = false;
+ const stroke = this.currentStroke;
+ this.currentStroke = null;
+ this.sampleBuffer = null;
+ return stroke;
+ }
+
+ applyStroke(
+ outputCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ stroke: SmudgeStroke
+ ): void {
+ const { points, settings } = stroke;
+ if (points.length < 2) return;
+
+ const originalSettings = { ...this.settings };
+ this.settings = { ...settings };
+
+ const tempCanvas = new OffscreenCanvas(
+ outputCtx.canvas.width,
+ outputCtx.canvas.height
+ );
+ const tempCtx = tempCanvas.getContext('2d', { willReadFrequently: true })!;
+ tempCtx.drawImage(outputCtx.canvas, 0, 0);
+
+ this.canvas = tempCanvas;
+ this.ctx = tempCtx;
+
+ this.lastX = points[0].x;
+ this.lastY = points[0].y;
+ this.sampleAtPoint(points[0].x, points[0].y);
+
+ for (let i = 1; i < points.length; i++) {
+ const point = points[i];
+ this.continueStroke(point.x, point.y, point.pressure);
+ }
+
+ outputCtx.drawImage(tempCanvas, 0, 0);
+ this.settings = originalSettings;
+ }
+
+ getSettings(): SmudgeSettings {
+ return { ...this.settings };
+ }
+
+ updateSettings(settings: Partial<SmudgeSettings>): void {
+ this.settings = { ...this.settings, ...settings };
+ }
+
+ isActiveStroke(): boolean {
+ return this.isActive;
+ }
+}
diff --git a/apps/image/src/utils/cursors.ts b/apps/image/src/utils/cursors.ts
new file mode 100644
index 00000000..818b519b
--- /dev/null
+++ b/apps/image/src/utils/cursors.ts
@@ -0,0 +1,104 @@
+const createSvgCursor = (svg: string, hotspotX: number, hotspotY: number): string => {
+ const encoded = encodeURIComponent(svg);
+ return `url("data:image/svg+xml,${encoded}") ${hotspotX} ${hotspotY}, crosshair`;
+};
+
+const brushSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z"/></g></svg>`;
+
+const eraserSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></g></svg>`;
+
+const bucketSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="m19 11-8-8-8.6 8.6a2 2 0 0 0 0 2.8l5.2 5.2c.8.8 2 .8 2.8 0L19 11Z"/><path d="m5 2 5 5"/><path d="M2 13h12"/><path d="M22 20a2 2 0 1 1-4 0c0-1.6 1.7-2.4 2-4 .3 1.6 2 2.4 2 4Z"/></g></svg>`;
+
+const gradientSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M3 15h18"/><path d="M9 3v18"/><path d="M15 3v18"/></g></svg>`;
+
+const stampSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M5 22h14"/><path d="M19.27 13.73A2.5 2.5 0 0 0 17.5 13h-11A2.5 2.5 0 0 0 4 15.5V17a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-1.5c0-.66-.26-1.3-.73-1.77Z"/><path d="M14 13V8.5C14 7 15 7 15 5a3 3 0 0 0-6 0c0 2 1 2 1 3.5V13"/></g></svg>`;
+
+const healingSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M18 11h-4a1 1 0 0 0-1 1v.5c0 .3.1.5.2.7l2.3 2.3c.2.2.5.4.8.4H18c1.1 0 2-.9 2-2v-1c0-1.1-.9-2-2-2z"/><path d="M6 13h4a1 1 0 0 1 1 1v.5c0 .3-.1.5-.2.7l-2.3 2.3c-.2.2-.5.4-.8.4H6c-1.1 0-2-.9-2-2v-1c0-1.1.9-2 2-2z"/><path d="M12 2v4"/><path d="M12 18v4"/><circle cx="12" cy="12" r="2"/></g></svg>`;
+
+const spotHealSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><circle cx="12" cy="12" r="10"/><path d="M12 8v8"/><path d="M8 12h8"/></g></svg>`;
+
+const dodgeSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></g></svg>`;
+
+const burnSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/></g></svg>`;
+
+const spongeSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z"/></g></svg>`;
+
+const blurSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><circle cx="12" cy="12" r="10" opacity="0.3"/><circle cx="12" cy="12" r="6" opacity="0.6"/><circle cx="12" cy="12" r="2"/></g></svg>`;
+
+const sharpenSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><polygon points="12 2 19 21 12 17 5 21 12 2"/></g></svg>`;
+
+const smudgeSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2"/><path d="M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2"/><path d="M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8"/><path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"/></g></svg>`;
+
+const eyedropperSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z"/></g></svg>`;
+
+const wandSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72"/><path d="m14 7 3 3"/><path d="M5 6v4"/><path d="M19 14v4"/><path d="M10 2v2"/><path d="M7 8H3"/><path d="M21 16h-4"/><path d="M11 3H9"/></g></svg>`;
+
+const lassoSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M7 22a5 5 0 0 1-2-4"/><path d="M7 16.93c.96.43 1.96.74 2.99.91"/><path d="M3.34 14A6.8 6.8 0 0 1 2 10c0-4.42 4.48-8 10-8s10 3.58 10 8a7.19 7.19 0 0 1-.33 2"/><path d="M5 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"/><path d="M14.33 22h-.09a.35.35 0 0 1-.24-.32v-10a.34.34 0 0 1 .33-.34c.08 0 .15.03.21.08l7.34 6a.33.33 0 0 1-.21.59h-4.49l-2.57 3.85a.35.35 0 0 1-.28.14z"/></g></svg>`;
+
+const cropSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M6 2v14a2 2 0 0 0 2 2h14"/><path d="M18 22V8a2 2 0 0 0-2-2H2"/></g></svg>`;
+
+const moveSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M12 2v20M2 12h20M5 5l2 2M5 19l2-2M19 5l-2 2M19 19l-2-2"/></g></svg>`;
+
+const warpSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M3 9h18"/><path d="M3 15h18"/><path d="M9 3v18"/><path d="M15 3v18"/></g></svg>`;
+
+const perspectiveSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M4 4l4 16h8l4-16z"/><path d="M6 8h12"/><path d="M7 12h10"/><path d="M8 16h8"/></g></svg>`;
+
+const liquifySvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"/><path d="M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"/><path d="M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"/></g></svg>`;
+
+const penSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><path d="m12 19 7-7 3 3-7 7-3-3z"/><path d="m18 13-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="m2 2 7.586 7.586"/><circle cx="11" cy="11" r="2"/></g></svg>`;
+
+const textSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" x2="15" y1="20" y2="20"/><line x1="12" x2="12" y1="4" y2="20"/></g></svg>`;
+
+const shapeSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><rect width="14" height="14" x="5" y="5" rx="2"/></g></svg>`;
+
+const zoomInSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><circle cx="11" cy="11" r="8"/><line x1="21" x2="16.65" y1="21" y2="16.65"/><line x1="11" x2="11" y1="8" y2="14"/><line x1="8" x2="14" y1="11" y2="11"/></g></svg>`;
+
+const marqueeSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><rect x="3" y="3" width="18" height="18" rx="2" stroke-dasharray="4 2"/></g></svg>`;
+
+const ellipseMarqueeSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><filter id="s"><feDropShadow dx="0" dy="0" stdDeviation="0.5" flood-color="white" flood-opacity="1"/></filter><g filter="url(#s)"><ellipse cx="12" cy="12" rx="9" ry="7" stroke-dasharray="4 2"/></g></svg>`;
+
+export const toolCursors: Record<string, string> = {
+ 'select': 'default',
+ 'hand': 'grab',
+ 'hand-grabbing': 'grabbing',
+ 'zoom': createSvgCursor(zoomInSvg, 11, 11),
+ 'eyedropper': createSvgCursor(eyedropperSvg, 1, 22),
+ 'text': createSvgCursor(textSvg, 12, 14),
+ 'pen': createSvgCursor(penSvg, 2, 22),
+ 'shape': createSvgCursor(shapeSvg, 12, 12),
+ 'crop': createSvgCursor(cropSvg, 6, 6),
+ 'marquee-rect': createSvgCursor(marqueeSvg, 12, 12),
+ 'marquee-ellipse': createSvgCursor(ellipseMarqueeSvg, 12, 12),
+ 'lasso': createSvgCursor(lassoSvg, 5, 18),
+ 'lasso-polygon': createSvgCursor(lassoSvg, 5, 18),
+ 'magic-wand': createSvgCursor(wandSvg, 5, 5),
+ 'brush': createSvgCursor(brushSvg, 4, 20),
+ 'eraser': createSvgCursor(eraserSvg, 4, 20),
+ 'paint-bucket': createSvgCursor(bucketSvg, 14, 20),
+ 'gradient': createSvgCursor(gradientSvg, 12, 12),
+ 'clone-stamp': createSvgCursor(stampSvg, 12, 18),
+ 'healing-brush': createSvgCursor(healingSvg, 12, 12),
+ 'spot-healing': createSvgCursor(spotHealSvg, 12, 12),
+ 'dodge': createSvgCursor(dodgeSvg, 12, 12),
+ 'burn': createSvgCursor(burnSvg, 12, 12),
+ 'sponge': createSvgCursor(spongeSvg, 12, 20),
+ 'blur': createSvgCursor(blurSvg, 12, 12),
+ 'sharpen': createSvgCursor(sharpenSvg, 12, 4),
+ 'smudge': createSvgCursor(smudgeSvg, 8, 2),
+ 'free-transform': createSvgCursor(moveSvg, 12, 12),
+ 'warp': createSvgCursor(warpSvg, 12, 12),
+ 'perspective': createSvgCursor(perspectiveSvg, 12, 12),
+ 'liquify': createSvgCursor(liquifySvg, 12, 12),
+};
+
+export const getToolCursor = (tool: string, isDragging?: boolean, dragMode?: string): string => {
+ if (tool === 'hand') {
+ return isDragging && dragMode === 'pan' ? 'grabbing' : 'grab';
+ }
+
+ if (isDragging && dragMode === 'paint') {
+ return toolCursors[tool] || 'crosshair';
+ }
+
+ return toolCursors[tool] || 'crosshair';
+};
diff --git a/apps/image/src/utils/flood-fill.ts b/apps/image/src/utils/flood-fill.ts
new file mode 100644
index 00000000..907e860e
--- /dev/null
+++ b/apps/image/src/utils/flood-fill.ts
@@ -0,0 +1,156 @@
+export interface FloodFillOptions {
+ tolerance: number;
+ contiguous: boolean;
+ antiAlias: boolean;
+ opacity: number;
+}
+
+function colorDistance(r1: number, g1: number, b1: number, a1: number, r2: number, g2: number, b2: number, a2: number): number {
+ return Math.sqrt(
+ Math.pow(r1 - r2, 2) +
+ Math.pow(g1 - g2, 2) +
+ Math.pow(b1 - b2, 2) +
+ Math.pow(a1 - a2, 2)
+ );
+}
+
+function hexToRgba(hex: string): [number, number, number, number] {
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+ if (result) {
+ return [
+ parseInt(result[1], 16),
+ parseInt(result[2], 16),
+ parseInt(result[3], 16),
+ 255
+ ];
+ }
+ return [0, 0, 0, 255];
+}
+
+export function floodFill(
+ imageData: ImageData,
+ startX: number,
+ startY: number,
+ fillColor: string,
+ options: FloodFillOptions
+): ImageData {
+ const { width, height, data } = imageData;
+ const result = new ImageData(new Uint8ClampedArray(data), width, height);
+ const resultData = result.data;
+
+ const [fillR, fillG, fillB] = hexToRgba(fillColor);
+ const fillA = Math.round(options.opacity * 255);
+
+ const x = Math.floor(startX);
+ const y = Math.floor(startY);
+
+ if (x < 0 || x >= width || y < 0 || y >= height) {
+ return result;
+ }
+
+ const startIdx = (y * width + x) * 4;
+ const targetR = data[startIdx];
+ const targetG = data[startIdx + 1];
+ const targetB = data[startIdx + 2];
+ const targetA = data[startIdx + 3];
+
+ const threshold = options.tolerance * Math.sqrt(4);
+
+ if (
+ colorDistance(targetR, targetG, targetB, targetA, fillR, fillG, fillB, fillA) < 1
+ ) {
+ return result;
+ }
+
+ const visited = new Uint8Array(width * height);
+
+ function matchesTarget(idx: number): boolean {
+ const r = data[idx];
+ const g = data[idx + 1];
+ const b = data[idx + 2];
+ const a = data[idx + 3];
+ return colorDistance(r, g, b, a, targetR, targetG, targetB, targetA) <= threshold;
+ }
+
+ function fillPixel(idx: number, strength: number = 1) {
+ const blendAlpha = fillA * strength;
+ const srcAlpha = resultData[idx + 3];
+ const outAlpha = blendAlpha + srcAlpha * (1 - blendAlpha / 255);
+
+ if (outAlpha > 0) {
+ resultData[idx] = (fillR * blendAlpha + resultData[idx] * srcAlpha * (1 - blendAlpha / 255)) / outAlpha;
+ resultData[idx + 1] = (fillG * blendAlpha + resultData[idx + 1] * srcAlpha * (1 - blendAlpha / 255)) / outAlpha;
+ resultData[idx + 2] = (fillB * blendAlpha + resultData[idx + 2] * srcAlpha * (1 - blendAlpha / 255)) / outAlpha;
+ resultData[idx + 3] = Math.round(outAlpha);
+ }
+ }
+
+ if (options.contiguous) {
+ const stack: [number, number][] = [[x, y]];
+
+ while (stack.length > 0) {
+ const [cx, cy] = stack.pop()!;
+ const pixelIdx = cy * width + cx;
+
+ if (visited[pixelIdx]) continue;
+ visited[pixelIdx] = 1;
+
+ const idx = pixelIdx * 4;
+ if (!matchesTarget(idx)) continue;
+
+ fillPixel(idx);
+
+ if (cx > 0) stack.push([cx - 1, cy]);
+ if (cx < width - 1) stack.push([cx + 1, cy]);
+ if (cy > 0) stack.push([cx, cy - 1]);
+ if (cy < height - 1) stack.push([cx, cy + 1]);
+ }
+
+ if (options.antiAlias) {
+ for (let py = 0; py < height; py++) {
+ for (let px = 0; px < width; px++) {
+ const pixelIdx = py * width + px;
+ if (!visited[pixelIdx]) continue;
+
+ const neighbors = [
+ px > 0 ? visited[pixelIdx - 1] : 1,
+ px < width - 1 ? visited[pixelIdx + 1] : 1,
+ py > 0 ? visited[pixelIdx - width] : 1,
+ py < height - 1 ? visited[pixelIdx + width] : 1,
+ ];
+
+ const filledNeighbors = neighbors.filter(n => n === 1).length;
+ if (filledNeighbors < 4) {
+ const idx = pixelIdx * 4;
+ const edgeStrength = 0.5 + filledNeighbors * 0.125;
+ fillPixel(idx, edgeStrength);
+ }
+ }
+ }
+ }
+ } else {
+ for (let py = 0; py < height; py++) {
+ for (let px = 0; px < width; px++) {
+ const idx = (py * width + px) * 4;
+ if (matchesTarget(idx)) {
+ fillPixel(idx);
+ }
+ }
+ }
+ }
+
+ return result;
+}
+
+export function applyFloodFillToCanvas(
+ canvas: HTMLCanvasElement,
+ ctx: CanvasRenderingContext2D,
+ x: number,
+ y: number,
+ fillColor: string,
+ options: FloodFillOptions
+): void {
+ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const filledData = floodFill(imageData, x, y, fillColor, options);
+ ctx.putImageData(filledData, 0, 0);
+}