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

feat(image): add core editing features and UI enhancements

Augustus Otud3a639fc26f6
diff --git a/apps/image/src/components/editor/EditorInterface.tsx b/apps/image/src/components/editor/EditorInterface.tsx
index a6a1f5f4..1fdffe56 100644
--- a/apps/image/src/components/editor/EditorInterface.tsx
+++ b/apps/image/src/components/editor/EditorInterface.tsx
@@ -1,14 +1,22 @@
+import { useState } from 'react';
import { Toolbar } from './toolbar/Toolbar';
import { LeftPanel } from './panels/LeftPanel';
import { Canvas } from './canvas/Canvas';
import { Inspector } from './inspector/Inspector';
import { LayerPanel } from './layers/LayerPanel';
+import { HistoryPanel } from './panels/HistoryPanel';
+import { PagesBar } from './pages/PagesBar';
+import { ExportDialog } from './ExportDialog';
import { useUIStore } from '../../stores/ui-store';
import { useProjectStore } from '../../stores/project-store';
+import { Layers, History } from 'lucide-react';
+
+type BottomTab = 'layers' | 'history';
export function EditorInterface() {
- const { isPanelCollapsed, isInspectorCollapsed } = useUIStore();
+ const { isPanelCollapsed, isInspectorCollapsed, isExportDialogOpen, closeExportDialog } = useUIStore();
const { project } = useProjectStore();
+ const [bottomTab, setBottomTab] = useState<BottomTab>('layers');
if (!project) {
return (
@@ -30,7 +38,10 @@ export function EditorInterface() {
)}
<div className="flex-1 flex flex-col overflow-hidden">
- <Canvas />
+ <div className="flex-1 overflow-hidden">
+ <Canvas />
+ </div>
+ <PagesBar />
</div>
{!isInspectorCollapsed && (
@@ -38,12 +49,40 @@ export function EditorInterface() {
<div className="flex-1 overflow-y-auto">
<Inspector />
</div>
- <div className="h-64 border-t border-border">
- <LayerPanel />
+ <div className="h-64 border-t border-border flex flex-col">
+ <div className="flex border-b border-border">
+ <button
+ onClick={() => setBottomTab('layers')}
+ className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium transition-colors ${
+ bottomTab === 'layers'
+ ? 'text-foreground bg-background border-b-2 border-primary -mb-px'
+ : 'text-muted-foreground hover:text-foreground hover:bg-accent'
+ }`}
+ >
+ <Layers size={14} />
+ Layers
+ </button>
+ <button
+ onClick={() => setBottomTab('history')}
+ className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium transition-colors ${
+ bottomTab === 'history'
+ ? 'text-foreground bg-background border-b-2 border-primary -mb-px'
+ : 'text-muted-foreground hover:text-foreground hover:bg-accent'
+ }`}
+ >
+ <History size={14} />
+ History
+ </button>
+ </div>
+ <div className="flex-1 overflow-hidden">
+ {bottomTab === 'layers' ? <LayerPanel /> : <HistoryPanel />}
+ </div>
</div>
</div>
)}
</div>
+
+ <ExportDialog open={isExportDialogOpen} onClose={closeExportDialog} />
</div>
);
}
diff --git a/apps/image/src/components/editor/ExportDialog.tsx b/apps/image/src/components/editor/ExportDialog.tsx
new file mode 100644
index 00000000..7378bab2
--- /dev/null
+++ b/apps/image/src/components/editor/ExportDialog.tsx
@@ -0,0 +1,308 @@
+import { useState, useMemo } from 'react';
+import { Download, FileImage, Loader2 } from 'lucide-react';
+import { Dialog, DialogFooter } from '../ui/Dialog';
+import { useProjectStore } from '../../stores/project-store';
+import { useUIStore } from '../../stores/ui-store';
+import {
+ exportProject,
+ downloadBlob,
+ getExportFilename,
+ type ExportFormat,
+ type ExportQuality,
+ type ExportOptions,
+} from '../../services/export-service';
+
+interface ExportDialogProps {
+ open: boolean;
+ onClose: () => void;
+}
+
+type FormatInfo = {
+ id: ExportFormat;
+ name: string;
+ description: string;
+ supportsTransparency: boolean;
+ supportsQuality: boolean;
+};
+
+const FORMATS: FormatInfo[] = [
+ { id: 'png', name: 'PNG', description: 'Lossless, best for graphics', supportsTransparency: true, supportsQuality: false },
+ { id: 'jpg', name: 'JPG', description: 'Smaller size, photos', supportsTransparency: false, supportsQuality: true },
+ { id: 'webp', name: 'WebP', description: 'Modern, best compression', supportsTransparency: true, supportsQuality: true },
+];
+
+const QUALITY_PRESETS: { id: ExportQuality; name: string; value: number }[] = [
+ { id: 'low', name: 'Low', value: 60 },
+ { id: 'medium', name: 'Medium', value: 80 },
+ { id: 'high', name: 'High', value: 92 },
+ { id: 'max', name: 'Maximum', value: 100 },
+];
+
+const SCALE_OPTIONS = [
+ { value: 0.5, label: '0.5x' },
+ { value: 1, label: '1x' },
+ { value: 2, label: '2x' },
+ { value: 3, label: '3x' },
+ { value: 4, label: '4x' },
+];
+
+export function ExportDialog({ open, onClose }: ExportDialogProps) {
+ const { project, selectedArtboardId } = useProjectStore();
+ const { showNotification } = useUIStore();
+
+ const [format, setFormat] = useState<ExportFormat>('png');
+ const [quality, setQuality] = useState<ExportQuality>('high');
+ const [scale, setScale] = useState(1);
+ const [background, setBackground] = useState<'include' | 'transparent'>('include');
+ const [exportAll, setExportAll] = useState(false);
+ const [isExporting, setIsExporting] = useState(false);
+ const [progress, setProgress] = useState(0);
+ const [progressMessage, setProgressMessage] = useState('');
+
+ const currentFormat = FORMATS.find((f) => f.id === format)!;
+ const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);
+
+ const dimensions = useMemo(() => {
+ if (!artboard) return null;
+ return {
+ width: Math.round(artboard.size.width * scale),
+ height: Math.round(artboard.size.height * scale),
+ };
+ }, [artboard, scale]);
+
+ const estimatedSize = useMemo(() => {
+ if (!dimensions) return null;
+ const pixels = dimensions.width * dimensions.height;
+ const bytesPerPixel = format === 'png' ? 3 : format === 'jpg' ? 0.5 : 0.4;
+ const qualityMultiplier = QUALITY_PRESETS.find((q) => q.id === quality)?.value ?? 80;
+ const estimated = pixels * bytesPerPixel * (qualityMultiplier / 100);
+
+ if (estimated > 1024 * 1024) {
+ return `~${(estimated / (1024 * 1024)).toFixed(1)} MB`;
+ }
+ return `~${Math.round(estimated / 1024)} KB`;
+ }, [dimensions, format, quality]);
+
+ const handleExport = async () => {
+ if (!project) return;
+
+ setIsExporting(true);
+ setProgress(0);
+
+ try {
+ const options: ExportOptions = {
+ format,
+ quality,
+ scale,
+ background: currentFormat.supportsTransparency ? background : 'include',
+ artboardIds: exportAll ? undefined : selectedArtboardId ? [selectedArtboardId] : undefined,
+ };
+
+ const blobs = await exportProject(project, options, (p, msg) => {
+ setProgress(p);
+ setProgressMessage(msg);
+ });
+
+ const artboards = exportAll
+ ? project.artboards
+ : project.artboards.filter((a) => a.id === selectedArtboardId);
+
+ blobs.forEach((blob, index) => {
+ const artboardName = artboards[index]?.name ?? `artboard-${index + 1}`;
+ const filename = getExportFilename(project.name, artboardName, format);
+ downloadBlob(blob, filename);
+ });
+
+ showNotification('success', `Exported ${blobs.length} artboard${blobs.length > 1 ? 's' : ''}`);
+ onClose();
+ } catch (error) {
+ showNotification('error', 'Export failed. Please try again.');
+ } finally {
+ setIsExporting(false);
+ setProgress(0);
+ }
+ };
+
+ if (!project || !artboard) return null;
+
+ return (
+ <Dialog
+ open={open}
+ onClose={onClose}
+ title="Export Image"
+ description="Choose format and quality settings"
+ maxWidth="md"
+ >
+ <div className="space-y-6">
+ <div>
+ <label className="block text-xs font-medium text-muted-foreground uppercase tracking-wide mb-3">
+ Format
+ </label>
+ <div className="grid grid-cols-3 gap-2">
+ {FORMATS.map((f) => (
+ <button
+ key={f.id}
+ onClick={() => setFormat(f.id)}
+ className={`p-3 rounded-lg border text-left transition-all ${
+ format === f.id
+ ? 'border-primary bg-primary/5 ring-1 ring-primary'
+ : 'border-border hover:border-muted-foreground/50 hover:bg-secondary/50'
+ }`}
+ >
+ <div className="flex items-center gap-2 mb-1">
+ <FileImage size={16} className={format === f.id ? 'text-primary' : 'text-muted-foreground'} />
+ <span className="font-medium text-sm">{f.name}</span>
+ </div>
+ <p className="text-[11px] text-muted-foreground">{f.description}</p>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {currentFormat.supportsQuality && (
+ <div>
+ <label className="block text-xs font-medium text-muted-foreground uppercase tracking-wide mb-3">
+ Quality
+ </label>
+ <div className="grid grid-cols-4 gap-2">
+ {QUALITY_PRESETS.map((q) => (
+ <button
+ key={q.id}
+ onClick={() => setQuality(q.id)}
+ className={`px-3 py-2 rounded-lg border text-center transition-all ${
+ quality === q.id
+ ? 'border-primary bg-primary/5 ring-1 ring-primary'
+ : 'border-border hover:border-muted-foreground/50 hover:bg-secondary/50'
+ }`}
+ >
+ <span className="text-sm font-medium">{q.name}</span>
+ <span className="block text-[10px] text-muted-foreground">{q.value}%</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <div>
+ <label className="block text-xs font-medium text-muted-foreground uppercase tracking-wide mb-3">
+ Scale
+ </label>
+ <div className="flex gap-2">
+ {SCALE_OPTIONS.map((s) => (
+ <button
+ key={s.value}
+ onClick={() => setScale(s.value)}
+ className={`flex-1 px-3 py-2 rounded-lg border text-center text-sm font-medium transition-all ${
+ scale === s.value
+ ? 'border-primary bg-primary/5 ring-1 ring-primary'
+ : 'border-border hover:border-muted-foreground/50 hover:bg-secondary/50'
+ }`}
+ >
+ {s.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {currentFormat.supportsTransparency && (
+ <div>
+ <label className="block text-xs font-medium text-muted-foreground uppercase tracking-wide mb-3">
+ Background
+ </label>
+ <div className="grid grid-cols-2 gap-2">
+ <button
+ onClick={() => setBackground('include')}
+ className={`px-3 py-2.5 rounded-lg border text-sm font-medium transition-all ${
+ background === 'include'
+ ? 'border-primary bg-primary/5 ring-1 ring-primary'
+ : 'border-border hover:border-muted-foreground/50 hover:bg-secondary/50'
+ }`}
+ >
+ Include Background
+ </button>
+ <button
+ onClick={() => setBackground('transparent')}
+ className={`px-3 py-2.5 rounded-lg border text-sm font-medium transition-all ${
+ background === 'transparent'
+ ? 'border-primary bg-primary/5 ring-1 ring-primary'
+ : 'border-border hover:border-muted-foreground/50 hover:bg-secondary/50'
+ }`}
+ >
+ Transparent
+ </button>
+ </div>
+ </div>
+ )}
+
+ {project.artboards.length > 1 && (
+ <div>
+ <label className="flex items-center gap-3 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={exportAll}
+ onChange={(e) => setExportAll(e.target.checked)}
+ className="w-4 h-4 rounded border-border bg-background text-primary focus:ring-primary/50"
+ />
+ <span className="text-sm">Export all artboards ({project.artboards.length})</span>
+ </label>
+ </div>
+ )}
+
+ <div className="p-4 bg-secondary/50 rounded-lg space-y-2">
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">Dimensions</span>
+ <span className="font-medium">
+ {dimensions?.width} × {dimensions?.height} px
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">Estimated size</span>
+ <span className="font-medium">{estimatedSize}</span>
+ </div>
+ </div>
+
+ {isExporting && (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">{progressMessage}</span>
+ <span className="font-medium">{Math.round(progress)}%</span>
+ </div>
+ <div className="h-2 bg-secondary rounded-full overflow-hidden">
+ <div
+ className="h-full bg-primary transition-all duration-300"
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+
+ <DialogFooter>
+ <button
+ onClick={onClose}
+ disabled={isExporting}
+ className="px-4 py-2 rounded-lg text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleExport}
+ disabled={isExporting}
+ className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
+ >
+ {isExporting ? (
+ <>
+ <Loader2 size={16} className="animate-spin" />
+ Exporting...
+ </>
+ ) : (
+ <>
+ <Download size={16} />
+ Export
+ </>
+ )}
+ </button>
+ </DialogFooter>
+ </Dialog>
+ );
+}
diff --git a/apps/image/src/components/editor/canvas/Canvas.tsx b/apps/image/src/components/editor/canvas/Canvas.tsx
index 3e00c153..bdd05212 100644
--- a/apps/image/src/components/editor/canvas/Canvas.tsx
+++ b/apps/image/src/components/editor/canvas/Canvas.tsx
@@ -2,6 +2,7 @@ import { useEffect, useRef, useCallback } from 'react';
import { useProjectStore } from '../../../stores/project-store';
import { useUIStore } from '../../../stores/ui-store';
import { useCanvasStore } from '../../../stores/canvas-store';
+import { calculateSnap } from '../../../utils/snapping';
import type { Layer, ImageLayer, TextLayer, ShapeLayer } from '../../../types/project';
export function Canvas() {
@@ -9,8 +10,8 @@ export function Canvas() {
const canvasRef = useRef<HTMLCanvasElement>(null);
const { project, selectedLayerIds, selectedArtboardId, updateLayerTransform, selectLayer, deselectAllLayers } = useProjectStore();
- const { zoom, panX, panY, setPan, activeTool, showGrid, gridSize } = useUIStore();
- const { setCanvasRef, setContainerRef, startDrag, updateDrag, endDrag, isDragging, dragMode, dragCurrentX, dragCurrentY } = useCanvasStore();
+ const { zoom, panX, panY, setPan, activeTool, showGrid, gridSize, crop, snapToObjects, snapToGuides, snapToGrid } = useUIStore();
+ const { setCanvasRef, setContainerRef, startDrag, updateDrag, endDrag, isDragging, dragMode, dragCurrentX, dragCurrentY, guides, smartGuides, setSmartGuides, clearSmartGuides } = useCanvasStore();
const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);
@@ -128,8 +129,109 @@ export function Canvas() {
ctx.restore();
});
+ if (smartGuides.length > 0) {
+ ctx.save();
+ ctx.strokeStyle = '#f43f5e';
+ ctx.lineWidth = 1;
+ ctx.setLineDash([4, 4]);
+
+ smartGuides.forEach((guide) => {
+ ctx.beginPath();
+ if (guide.type === 'vertical') {
+ ctx.moveTo(artboardX + guide.position * zoom, artboardY + guide.start * zoom);
+ ctx.lineTo(artboardX + guide.position * zoom, artboardY + guide.end * zoom);
+ } else {
+ ctx.moveTo(artboardX + guide.start * zoom, artboardY + guide.position * zoom);
+ ctx.lineTo(artboardX + guide.end * zoom, artboardY + guide.position * zoom);
+ }
+ ctx.stroke();
+ });
+
+ ctx.restore();
+ }
+
+ if (crop.isActive && crop.layerId && crop.cropRect) {
+ const cropLayer = project.layers[crop.layerId];
+ if (cropLayer) {
+ const { x: layerX, y: layerY, width: layerW, height: layerH } = cropLayer.transform;
+ const { x: cropX, y: cropY, width: cropW, height: cropH } = crop.cropRect;
+
+ ctx.save();
+
+ ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';
+ ctx.fillRect(
+ artboardX + layerX * zoom,
+ artboardY + layerY * zoom,
+ layerW * zoom,
+ cropY * zoom
+ );
+ ctx.fillRect(
+ artboardX + layerX * zoom,
+ artboardY + (layerY + cropY + cropH) * zoom,
+ layerW * zoom,
+ (layerH - cropY - cropH) * zoom
+ );
+ ctx.fillRect(
+ artboardX + layerX * zoom,
+ artboardY + (layerY + cropY) * zoom,
+ cropX * zoom,
+ cropH * zoom
+ );
+ ctx.fillRect(
+ artboardX + (layerX + cropX + cropW) * zoom,
+ artboardY + (layerY + cropY) * zoom,
+ (layerW - cropX - cropW) * zoom,
+ cropH * zoom
+ );
+
+ const cX = artboardX + (layerX + cropX) * zoom;
+ const cY = artboardY + (layerY + cropY) * zoom;
+ const cW = cropW * zoom;
+ const cH = cropH * zoom;
+
+ ctx.strokeStyle = '#ffffff';
+ ctx.lineWidth = 2;
+ ctx.strokeRect(cX, cY, cW, cH);
+
+ ctx.strokeStyle = 'rgba(255, 255, 255, 0.4)';
+ ctx.lineWidth = 1;
+ for (let i = 1; i < 3; i++) {
+ ctx.beginPath();
+ ctx.moveTo(cX + (cW * i) / 3, cY);
+ ctx.lineTo(cX + (cW * i) / 3, cY + cH);
+ ctx.stroke();
+ ctx.beginPath();
+ ctx.moveTo(cX, cY + (cH * i) / 3);
+ ctx.lineTo(cX + cW, cY + (cH * i) / 3);
+ ctx.stroke();
+ }
+
+ const handleSize = 10;
+ const handlePositions = [
+ { x: cX, y: cY },
+ { x: cX + cW / 2, y: cY },
+ { x: cX + cW, y: cY },
+ { x: cX + cW, y: cY + cH / 2 },
+ { x: cX + cW, y: cY + cH },
+ { x: cX + cW / 2, y: cY + cH },
+ { x: cX, y: cY + cH },
+ { x: cX, y: cY + cH / 2 },
+ ];
+
+ ctx.fillStyle = '#ffffff';
+ ctx.strokeStyle = '#000000';
+ ctx.lineWidth = 1;
+ handlePositions.forEach((h) => {
+ ctx.fillRect(h.x - handleSize / 2, h.y - handleSize / 2, handleSize, handleSize);
+ ctx.strokeRect(h.x - handleSize / 2, h.y - handleSize / 2, handleSize, handleSize);
+ });
+
+ ctx.restore();
+ }
+ }
+
ctx.restore();
- }, [artboard, project, zoom, panX, panY, selectedLayerIds, showGrid, gridSize]);
+ }, [artboard, project, zoom, panX, panY, selectedLayerIds, showGrid, gridSize, crop, smartGuides]);
useEffect(() => {
render();
@@ -225,27 +327,53 @@ export function Canvas() {
const dx = e.clientX - dragCurrentX;
const dy = e.clientY - dragCurrentY;
setPan(panX + dx, panY + dy);
- } else if (dragMode === 'move' && selectedLayerIds.length > 0) {
+ } else if (dragMode === 'move' && selectedLayerIds.length > 0 && artboard) {
const dx = (e.clientX - dragCurrentX) / zoom;
const dy = (e.clientY - dragCurrentY) / zoom;
- selectedLayerIds.forEach((layerId) => {
- const layer = project?.layers[layerId];
- if (layer) {
- updateLayerTransform(layerId, {
- x: layer.transform.x + dx,
- y: layer.transform.y + dy,
- });
- }
- });
+ const firstLayerId = selectedLayerIds[0];
+ const firstLayer = project?.layers[firstLayerId];
+
+ if (firstLayer) {
+ const newX = firstLayer.transform.x + dx;
+ const newY = firstLayer.transform.y + dy;
+
+ const otherLayers = Object.values(project?.layers ?? {}).filter(
+ (l) => l && !selectedLayerIds.includes(l.id)
+ );
+
+ const snapResult = calculateSnap(
+ { x: newX, y: newY, width: firstLayer.transform.width, height: firstLayer.transform.height },
+ otherLayers as Layer[],
+ { x: 0, y: 0, width: artboard.size.width, height: artboard.size.height },
+ guides,
+ { snapToObjects, snapToGuides, snapToGrid, gridSize, threshold: 8 }
+ );
+
+ const adjustedDx = snapResult.x - firstLayer.transform.x;
+ const adjustedDy = snapResult.y - firstLayer.transform.y;
+
+ selectedLayerIds.forEach((layerId) => {
+ const layer = project?.layers[layerId];
+ if (layer) {
+ updateLayerTransform(layerId, {
+ x: layer.transform.x + adjustedDx,
+ y: layer.transform.y + adjustedDy,
+ });
+ }
+ });
+
+ setSmartGuides(snapResult.guides);
+ }
}
},
- [isDragging, dragMode, dragCurrentX, dragCurrentY, panX, panY, setPan, zoom, selectedLayerIds, project, updateLayerTransform, updateDrag]
+ [isDragging, dragMode, dragCurrentX, dragCurrentY, panX, panY, setPan, zoom, selectedLayerIds, project, updateLayerTransform, updateDrag, artboard, guides, snapToObjects, snapToGuides, snapToGrid, gridSize, setSmartGuides]
);
const handleMouseUp = useCallback(() => {
endDrag();
- }, [endDrag]);
+ clearSmartGuides();
+ }, [endDrag, clearSmartGuides]);
const handleWheel = useCallback(
(e: React.WheelEvent) => {
@@ -329,7 +457,32 @@ function renderImageLayer(
const img = new window.Image();
img.src = asset.dataUrl ?? asset.blobUrl ?? '';
if (img.complete) {
+ const { filters } = layer;
+ const filterParts: string[] = [];
+
+ if (filters.brightness !== 100) {
+ filterParts.push(`brightness(${filters.brightness}%)`);
+ }
+ if (filters.contrast !== 100) {
+ filterParts.push(`contrast(${filters.contrast}%)`);
+ }
+ if (filters.saturation !== 100) {
+ filterParts.push(`saturate(${filters.saturation}%)`);
+ }
+ if (filters.hue !== 0) {
+ filterParts.push(`hue-rotate(${filters.hue}deg)`);
+ }
+ if (filters.blur > 0) {
+ filterParts.push(`blur(${filters.blur}px)`);
+ }
+
+ if (filterParts.length > 0) {
+ ctx.filter = filterParts.join(' ');
+ }
+
ctx.drawImage(img, 0, 0, layer.transform.width, layer.transform.height);
+
+ ctx.filter = 'none';
}
}
diff --git a/apps/image/src/components/editor/inspector/AlignmentSection.tsx b/apps/image/src/components/editor/inspector/AlignmentSection.tsx
new file mode 100644
index 00000000..0d30fb57
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/AlignmentSection.tsx
@@ -0,0 +1,240 @@
+import { useProjectStore } from '../../../stores/project-store';
+import type { Layer } from '../../../types/project';
+import {
+ AlignHorizontalJustifyStart,
+ AlignHorizontalJustifyCenter,
+ AlignHorizontalJustifyEnd,
+ AlignVerticalJustifyStart,
+ AlignVerticalJustifyCenter,
+ AlignVerticalJustifyEnd,
+ AlignHorizontalSpaceBetween,
+ AlignVerticalSpaceBetween,
+} from 'lucide-react';
+
+interface Props {
+ layers: Layer[];
+}
+
+export function AlignmentSection({ layers }: Props) {
+ const { project, selectedArtboardId, updateLayerTransform } = useProjectStore();
+
+ const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);
+
+ if (!artboard || layers.length === 0) return null;
+
+ const alignLeft = () => {
+ if (layers.length === 1) {
+ updateLayerTransform(layers[0].id, { x: 0 });
+ } else {
+ const minX = Math.min(...layers.map((l) => l.transform.x));
+ layers.forEach((layer) => {
+ updateLayerTransform(layer.id, { x: minX });
+ });
+ }
+ };
+
+ const alignCenterH = () => {
+ if (layers.length === 1) {
+ const layer = layers[0];
+ updateLayerTransform(layer.id, {
+ x: (artboard.size.width - layer.transform.width) / 2,
+ });
+ } else {
+ const bounds = getBounds(layers);
+ const centerX = bounds.x + bounds.width / 2;
+ layers.forEach((layer) => {
+ updateLayerTransform(layer.id, {
+ x: centerX - layer.transform.width / 2,
+ });
+ });
+ }
+ };
+
+ const alignRight = () => {
+ if (layers.length === 1) {
+ const layer = layers[0];
+ updateLayerTransform(layer.id, {
+ x: artboard.size.width - layer.transform.width,
+ });
+ } else {
+ const maxRight = Math.max(...layers.map((l) => l.transform.x + l.transform.width));
+ layers.forEach((layer) => {
+ updateLayerTransform(layer.id, {
+ x: maxRight - layer.transform.width,
+ });
+ });
+ }
+ };
+
+ const alignTop = () => {
+ if (layers.length === 1) {
+ updateLayerTransform(layers[0].id, { y: 0 });
+ } else {
+ const minY = Math.min(...layers.map((l) => l.transform.y));
+ layers.forEach((layer) => {
+ updateLayerTransform(layer.id, { y: minY });
+ });
+ }
+ };
+
+ const alignCenterV = () => {
+ if (layers.length === 1) {
+ const layer = layers[0];
+ updateLayerTransform(layer.id, {
+ y: (artboard.size.height - layer.transform.height) / 2,
+ });
+ } else {
+ const bounds = getBounds(layers);
+ const centerY = bounds.y + bounds.height / 2;
+ layers.forEach((layer) => {
+ updateLayerTransform(layer.id, {
+ y: centerY - layer.transform.height / 2,
+ });
+ });
+ }
+ };
+
+ const alignBottom = () => {
+ if (layers.length === 1) {
+ const layer = layers[0];
+ updateLayerTransform(layer.id, {
+ y: artboard.size.height - layer.transform.height,
+ });
+ } else {
+ const maxBottom = Math.max(...layers.map((l) => l.transform.y + l.transform.height));
+ layers.forEach((layer) => {
+ updateLayerTransform(layer.id, {
+ y: maxBottom - layer.transform.height,
+ });
+ });
+ }
+ };
+
+ const distributeH = () => {
+ if (layers.length < 3) return;
+
+ const sorted = [...layers].sort((a, b) => a.transform.x - b.transform.x);
+ const first = sorted[0];
+ const last = sorted[sorted.length - 1];
+ const totalWidth = last.transform.x + last.transform.width - first.transform.x;
+ const layersWidth = sorted.reduce((sum, l) => sum + l.transform.width, 0);
+ const gap = (totalWidth - layersWidth) / (sorted.length - 1);
+
+ let x = first.transform.x;
+ sorted.forEach((layer) => {
+ updateLayerTransform(layer.id, { x });
+ x += layer.transform.width + gap;
+ });
+ };
+
+ const distributeV = () => {
+ if (layers.length < 3) return;
+
+ const sorted = [...layers].sort((a, b) => a.transform.y - b.transform.y);
+ const first = sorted[0];
+ const last = sorted[sorted.length - 1];
+ const totalHeight = last.transform.y + last.transform.height - first.transform.y;
+ const layersHeight = sorted.reduce((sum, l) => sum + l.transform.height, 0);
+ const gap = (totalHeight - layersHeight) / (sorted.length - 1);
+
+ let y = first.transform.y;
+ sorted.forEach((layer) => {
+ updateLayerTransform(layer.id, { y });
+ y += layer.transform.height + gap;
+ });
+ };
+
+ const isSingleLayer = layers.length === 1;
+
+ return (
+ <div className="space-y-3">
+ <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
+ Alignment
+ </h4>
+
+ <div className="grid grid-cols-6 gap-1">
+ <AlignButton
+ icon={<AlignHorizontalJustifyStart size={14} />}
+ onClick={alignLeft}
+ title={isSingleLayer ? 'Align to canvas left' : 'Align left edges'}
+ />
+ <AlignButton
+ icon={<AlignHorizontalJustifyCenter size={14} />}
+ onClick={alignCenterH}
+ title={isSingleLayer ? 'Center horizontally on canvas' : 'Align horizontal centers'}
+ />
+ <AlignButton
+ icon={<AlignHorizontalJustifyEnd size={14} />}
+ onClick={alignRight}
+ title={isSingleLayer ? 'Align to canvas right' : 'Align right edges'}
+ />
+ <AlignButton
+ icon={<AlignVerticalJustifyStart size={14} />}
+ onClick={alignTop}
+ title={isSingleLayer ? 'Align to canvas top' : 'Align top edges'}
+ />
+ <AlignButton
+ icon={<AlignVerticalJustifyCenter size={14} />}
+ onClick={alignCenterV}
+ title={isSingleLayer ? 'Center vertically on canvas' : 'Align vertical centers'}
+ />
+ <AlignButton
+ icon={<AlignVerticalJustifyEnd size={14} />}
+ onClick={alignBottom}
+ title={isSingleLayer ? 'Align to canvas bottom' : 'Align bottom edges'}
+ />
+ </div>
+
+ {layers.length >= 3 && (
+ <div className="grid grid-cols-2 gap-1 pt-2 border-t border-border">
+ <AlignButton
+ icon={<AlignHorizontalSpaceBetween size={14} />}
+ onClick={distributeH}
+ title="Distribute horizontally"
+ label="Distribute H"
+ />
+ <AlignButton
+ icon={<AlignVerticalSpaceBetween size={14} />}
+ onClick={distributeV}
+ title="Distribute vertically"
+ label="Distribute V"
+ />
+ </div>
+ )}
+ </div>
+ );
+}
+
+interface AlignButtonProps {
+ icon: React.ReactNode;
+ onClick: () => void;
+ title: string;
+ label?: string;
+}
+
+function AlignButton({ icon, onClick, title, label }: AlignButtonProps) {
+ return (
+ <button
+ onClick={onClick}
+ title={title}
+ className="flex items-center justify-center gap-1 p-2 rounded-md bg-secondary/50 text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
+ >
+ {icon}
+ {label && <span className="text-[9px]">{label}</span>}
+ </button>
+ );
+}
+
+function getBounds(layers: Layer[]): { x: number; y: number; width: number; height: number } {
+ const minX = Math.min(...layers.map((l) => l.transform.x));
+ const minY = Math.min(...layers.map((l) => l.transform.y));
+ const maxX = Math.max(...layers.map((l) => l.transform.x + l.transform.width));
+ const maxY = Math.max(...layers.map((l) => l.transform.y + l.transform.height));
+
+ return {
+ x: minX,
+ y: minY,
+ width: maxX - minX,
+ height: maxY - minY,
+ };
+}
diff --git a/apps/image/src/components/editor/inspector/BackgroundRemovalSection.tsx b/apps/image/src/components/editor/inspector/BackgroundRemovalSection.tsx
new file mode 100644
index 00000000..0284efa1
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/BackgroundRemovalSection.tsx
@@ -0,0 +1,198 @@
+import { useState } from 'react';
+import { Wand2, Loader2 } from 'lucide-react';
+import { Slider } from '@openreel/ui';
+import { useProjectStore } from '../../../stores/project-store';
+import type { ImageLayer } from '../../../types/project';
+import {
+ getBackgroundRemovalService,
+ BackgroundMode,
+ DEFAULT_OPTIONS,
+} from '../../../services/background-removal-service';
+
+interface Props {
+ layer: ImageLayer;
+}
+
+export function BackgroundRemovalSection({ layer }: Props) {
+ const { project, addAsset, updateLayer } = useProjectStore();
+ const [isProcessing, setIsProcessing] = useState(false);
+ const [progress, setProgress] = useState(0);
+ const [mode, setMode] = useState<BackgroundMode>('transparent');
+ const [threshold, setThreshold] = useState(DEFAULT_OPTIONS.threshold);
+ const [edgeBlur, setEdgeBlur] = useState(DEFAULT_OPTIONS.edgeBlur);
+ const [backgroundColor, setBackgroundColor] = useState(DEFAULT_OPTIONS.backgroundColor!);
+ const [blurAmount, setBlurAmount] = useState(DEFAULT_OPTIONS.blurAmount!);
+
+ const asset = project?.assets[layer.sourceId];
+
+ const handleRemoveBackground = async () => {
+ if (!asset?.dataUrl && !asset?.thumbnailUrl) return;
+
+ setIsProcessing(true);
+ setProgress(0);
+
+ try {
+ const service = getBackgroundRemovalService();
+ const imageUrl = asset.dataUrl || asset.thumbnailUrl;
+
+ const resultDataUrl = await service.removeBackground(
+ imageUrl,
+ {
+ mode,
+ threshold,
+ edgeBlur,
+ backgroundColor,
+ blurAmount,
+ },
+ setProgress
+ );
+
+ const newAssetId = `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
+ addAsset({
+ id: newAssetId,
+ name: `${asset.name} (no bg)`,
+ type: 'image',
+ mimeType: 'image/png',
+ size: 0,
+ width: asset.width,
+ height: asset.height,
+ thumbnailUrl: resultDataUrl,
+ dataUrl: resultDataUrl,
+ });
+
+ updateLayer<ImageLayer>(layer.id, { sourceId: newAssetId });
+ } catch (error) {
+ console.error('Background removal failed:', error);
+ } finally {
+ setIsProcessing(false);
+ setProgress(0);
+ }
+ };
+
+ return (
+ <div className="space-y-3">
+ <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
+ Background Removal
+ </h4>
+
+ <div className="p-3 space-y-4 bg-secondary/50 rounded-lg">
+ <div className="space-y-2">
+ <label className="text-[10px] text-muted-foreground">Mode</label>
+ <div className="grid grid-cols-3 gap-1">
+ {(['transparent', 'color', 'blur'] as BackgroundMode[]).map((m) => (
+ <button
+ key={m}
+ onClick={() => setMode(m)}
+ className={`px-2 py-1.5 text-[10px] font-medium rounded transition-colors ${
+ mode === m
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-background text-muted-foreground hover:text-foreground hover:bg-accent'
+ }`}
+ >
+ {m.charAt(0).toUpperCase() + m.slice(1)}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {mode === 'color' && (
+ <div className="flex items-center gap-2">
+ <label className="text-[10px] text-muted-foreground">Background</label>
+ <input
+ type="color"
+ value={backgroundColor}
+ onChange={(e) => setBackgroundColor(e.target.value)}
+ className="w-8 h-8 rounded border border-input cursor-pointer"
+ />
+ <input
+ type="text"
+ value={backgroundColor}
+ onChange={(e) => setBackgroundColor(e.target.value)}
+ className="flex-1 px-2 py-1 text-xs bg-background border border-input rounded-md font-mono"
+ />
+ </div>
+ )}
+
+ {mode === 'blur' && (
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Blur Amount</label>
+ <span className="text-[10px] text-muted-foreground">{blurAmount}px</span>
+ </div>
+ <Slider
+ value={[blurAmount]}
+ onValueChange={([v]) => setBlurAmount(v)}
+ min={5}
+ max={30}
+ step={1}
+ />
+ </div>
+ )}
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Sensitivity</label>
+ <span className="text-[10px] text-muted-foreground">{Math.round(threshold * 100)}%</span>
+ </div>
+ <Slider
+ value={[threshold * 100]}
+ onValueChange={([v]) => setThreshold(v / 100)}
+ min={10}
+ max={90}
+ step={5}
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Edge Smoothing</label>
+ <span className="text-[10px] text-muted-foreground">{edgeBlur}px</span>
+ </div>
+ <Slider
+ value={[edgeBlur]}
+ onValueChange={([v]) => setEdgeBlur(v)}
+ min={0}
+ max={10}
+ step={1}
+ />
+ </div>
+
+ {isProcessing && (
+ <div className="space-y-1.5">
+ <div className="h-1.5 bg-muted rounded-full overflow-hidden">
+ <div
+ className="h-full bg-primary transition-all duration-200"
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+ <p className="text-[10px] text-muted-foreground text-center">
+ Processing... {Math.round(progress)}%
+ </p>
+ </div>
+ )}
+
+ <button
+ onClick={handleRemoveBackground}
+ disabled={isProcessing}
+ className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-primary text-primary-foreground rounded-lg text-sm font-medium hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
+ >
+ {isProcessing ? (
+ <>
+ <Loader2 size={16} className="animate-spin" />
+ Processing...
+ </>
+ ) : (
+ <>
+ <Wand2 size={16} />
+ Remove Background
+ </>
+ )}
+ </button>
+
+ <p className="text-[9px] text-muted-foreground text-center">
+ Works best with solid color backgrounds
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/CropSection.tsx b/apps/image/src/components/editor/inspector/CropSection.tsx
new file mode 100644
index 00000000..44884996
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/CropSection.tsx
@@ -0,0 +1,251 @@
+import { useState, useCallback } 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';
+
+interface Props {
+ layer: ImageLayer;
+}
+
+const ASPECT_RATIOS: { value: CropAspectRatio; label: string; ratio?: number }[] = [
+ { value: 'free', label: 'Free' },
+ { value: 'original', label: 'Original' },
+ { value: '1:1', label: '1:1', ratio: 1 },
+ { value: '4:3', label: '4:3', ratio: 4 / 3 },
+ { value: '3:4', label: '3:4', ratio: 3 / 4 },
+ { value: '16:9', label: '16:9', ratio: 16 / 9 },
+ { value: '9:16', label: '9:16', ratio: 9 / 16 },
+ { value: '3:2', label: '3:2', ratio: 3 / 2 },
+ { value: '2:3', label: '2:3', ratio: 2 / 3 },
+];
+
+export function CropSection({ layer }: Props) {
+ const { updateLayer } = useProjectStore();
+ const { crop, startCrop, cancelCrop, applyCrop, setCropAspectRatio, updateCropRect } = useUIStore();
+ const [lockAspect, setLockAspect] = useState(false);
+
+ const isCropping = crop.isActive && crop.layerId === layer.id;
+
+ const handleStartCrop = useCallback(() => {
+ const initialRect = layer.cropRect ?? {
+ x: 0,
+ y: 0,
+ width: layer.transform.width,
+ height: layer.transform.height,
+ };
+ startCrop(layer.id, initialRect);
+ }, [layer, startCrop]);
+
+ const handleApplyCrop = useCallback(() => {
+ const result = applyCrop();
+ if (result) {
+ updateLayer<ImageLayer>(result.layerId, {
+ cropRect: result.cropRect,
+ });
+ }
+ }, [applyCrop, updateLayer]);
+
+ const handleResetCrop = useCallback(() => {
+ if (isCropping) {
+ updateCropRect({
+ x: 0,
+ y: 0,
+ width: layer.transform.width,
+ height: layer.transform.height,
+ });
+ } else {
+ updateLayer<ImageLayer>(layer.id, { cropRect: null });
+ }
+ }, [isCropping, layer, updateCropRect, updateLayer]);
+
+ const handleAspectRatioChange = useCallback(
+ (ratio: CropAspectRatio) => {
+ setCropAspectRatio(ratio);
+
+ if (!crop.cropRect) return;
+
+ const aspectConfig = ASPECT_RATIOS.find((r) => r.value === ratio);
+ if (!aspectConfig?.ratio) return;
+
+ const currentWidth = crop.cropRect.width;
+ const currentHeight = crop.cropRect.height;
+ const currentCenterX = crop.cropRect.x + currentWidth / 2;
+ const currentCenterY = crop.cropRect.y + currentHeight / 2;
+
+ let newWidth = currentWidth;
+ let newHeight = currentWidth / aspectConfig.ratio;
+
+ if (newHeight > layer.transform.height) {
+ newHeight = layer.transform.height;
+ newWidth = newHeight * aspectConfig.ratio;
+ }
+
+ if (newWidth > layer.transform.width) {
+ newWidth = layer.transform.width;
+ newHeight = newWidth / aspectConfig.ratio;
+ }
+
+ let newX = currentCenterX - newWidth / 2;
+ let newY = currentCenterY - newHeight / 2;
+
+ newX = Math.max(0, Math.min(newX, layer.transform.width - newWidth));
+ newY = Math.max(0, Math.min(newY, layer.transform.height - newHeight));
+
+ updateCropRect({
+ x: Math.round(newX),
+ y: Math.round(newY),
+ width: Math.round(newWidth),
+ height: Math.round(newHeight),
+ });
+ },
+ [crop.cropRect, layer.transform, setCropAspectRatio, updateCropRect]
+ );
+
+ const hasCrop = layer.cropRect !== null;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Crop</h4>
+ {hasCrop && !isCropping && (
+ <button
+ onClick={handleResetCrop}
+ className="text-[10px] text-muted-foreground hover:text-foreground transition-colors"
+ >
+ Reset
+ </button>
+ )}
+ </div>
+
+ {!isCropping ? (
+ <button
+ onClick={handleStartCrop}
+ className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-primary text-primary-foreground rounded-lg font-medium text-sm hover:bg-primary/90 transition-colors"
+ >
+ <Crop size={16} />
+ {hasCrop ? 'Adjust Crop' : 'Crop Image'}
+ </button>
+ ) : (
+ <div className="space-y-3 p-3 bg-secondary/30 rounded-lg border border-border/50">
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <label className="text-[11px] font-medium text-foreground">Aspect Ratio</label>
+ <button
+ onClick={() => setLockAspect(!lockAspect)}
+ className={`p-1 rounded transition-colors ${
+ lockAspect ? 'bg-primary text-primary-foreground' : 'bg-secondary text-muted-foreground hover:text-foreground'
+ }`}
+ >
+ {lockAspect ? <Lock size={12} /> : <Unlock size={12} />}
+ </button>
+ </div>
+ <div className="grid grid-cols-3 gap-1">
+ {ASPECT_RATIOS.map((ar) => (
+ <button
+ key={ar.value}
+ onClick={() => handleAspectRatioChange(ar.value)}
+ className={`px-2 py-1.5 text-[10px] font-medium rounded transition-colors ${
+ crop.aspectRatio === ar.value
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-muted-foreground hover:text-foreground hover:bg-secondary/80'
+ }`}
+ >
+ {ar.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {crop.cropRect && (
+ <div className="space-y-2">
+ <label className="text-[11px] font-medium text-foreground">Crop Area</label>
+ <div className="grid grid-cols-2 gap-2">
+ <div className="space-y-1">
+ <label className="text-[9px] text-muted-foreground">X</label>
+ <input
+ type="number"
+ value={Math.round(crop.cropRect.x)}
+ onChange={(e) =>
+ updateCropRect({
+ ...crop.cropRect!,
+ x: Math.max(0, Number(e.target.value)),
+ })
+ }
+ className="w-full px-2 py-1 text-[11px] bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+ <div className="space-y-1">
+ <label className="text-[9px] text-muted-foreground">Y</label>
+ <input
+ type="number"
+ value={Math.round(crop.cropRect.y)}
+ onChange={(e) =>
+ updateCropRect({
+ ...crop.cropRect!,
+ y: Math.max(0, Number(e.target.value)),
+ })
+ }
+ className="w-full px-2 py-1 text-[11px] bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+ <div className="space-y-1">
+ <label className="text-[9px] text-muted-foreground">Width</label>
+ <input
+ type="number"
+ value={Math.round(crop.cropRect.width)}
+ onChange={(e) =>
+ updateCropRect({
+ ...crop.cropRect!,
+ width: Math.max(1, Number(e.target.value)),
+ })
+ }
+ className="w-full px-2 py-1 text-[11px] bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+ <div className="space-y-1">
+ <label className="text-[9px] text-muted-foreground">Height</label>
+ <input
+ type="number"
+ value={Math.round(crop.cropRect.height)}
+ onChange={(e) =>
+ updateCropRect({
+ ...crop.cropRect!,
+ height: Math.max(1, Number(e.target.value)),
+ })
+ }
+ className="w-full px-2 py-1 text-[11px] bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+ </div>
+ </div>
+ )}
+
+ <div className="flex gap-2 pt-2">
+ <button
+ onClick={handleResetCrop}
+ className="flex-1 flex items-center justify-center gap-1 px-3 py-2 bg-secondary text-foreground rounded-lg font-medium text-[11px] hover:bg-secondary/80 transition-colors"
+ >
+ <RotateCcw size={12} />
+ Reset
+ </button>
+ <button
+ onClick={cancelCrop}
+ className="flex-1 flex items-center justify-center gap-1 px-3 py-2 bg-secondary text-foreground rounded-lg font-medium text-[11px] hover:bg-secondary/80 transition-colors"
+ >
+ <X size={12} />
+ Cancel
+ </button>
+ <button
+ onClick={handleApplyCrop}
+ className="flex-1 flex items-center justify-center gap-1 px-3 py-2 bg-primary text-primary-foreground rounded-lg font-medium text-[11px] hover:bg-primary/90 transition-colors"
+ >
+ <Check size={12} />
+ Apply
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/EffectsSection.tsx b/apps/image/src/components/editor/inspector/EffectsSection.tsx
new file mode 100644
index 00000000..0f8106bc
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/EffectsSection.tsx
@@ -0,0 +1,279 @@
+import { useProjectStore } from '../../../stores/project-store';
+import type { Layer, Shadow, 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 } from 'lucide-react';
+import { useState } from 'react';
+
+interface Props {
+ layer: Layer;
+}
+
+export function EffectsSection({ layer }: Props) {
+ const { updateLayer } = useProjectStore();
+ const [openSection, setOpenSection] = useState<'shadow' | 'stroke' | 'glow' | null>('shadow');
+
+ const handleShadowChange = (updates: Partial<Shadow>) => {
+ updateLayer(layer.id, {
+ shadow: { ...layer.shadow, ...updates },
+ });
+ };
+
+ const handleStrokeChange = (updates: Partial<Stroke>) => {
+ updateLayer(layer.id, {
+ stroke: { ...layer.stroke, ...updates },
+ });
+ };
+
+ const handleGlowChange = (updates: Partial<Glow>) => {
+ updateLayer(layer.id, {
+ glow: { ...layer.glow, ...updates },
+ });
+ };
+
+ return (
+ <div className="space-y-2">
+ <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
+ Effects
+ </h4>
+
+ <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 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>
+ <div className="flex items-center gap-2">
+ <input
+ type="color"
+ value={layer.shadow.color.startsWith('rgba') ? '#000000' : layer.shadow.color}
+ onChange={(e) => handleShadowChange({ color: e.target.value })}
+ className="w-8 h-8 rounded border border-input cursor-pointer"
+ disabled={!layer.shadow.enabled}
+ />
+ <input
+ type="text"
+ value={layer.shadow.color}
+ onChange={(e) => handleShadowChange({ color: e.target.value })}
+ className="flex-1 px-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary font-mono disabled:opacity-50"
+ disabled={!layer.shadow.enabled}
+ />
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Blur</label>
+ <span className="text-[10px] text-muted-foreground">{layer.shadow.blur}px</span>
+ </div>
+ <Slider
+ value={[layer.shadow.blur]}
+ onValueChange={([blur]) => handleShadowChange({ blur })}
+ min={0}
+ max={100}
+ step={1}
+ disabled={!layer.shadow.enabled}
+ />
+ </div>
+
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Offset X</label>
+ <span className="text-[10px] text-muted-foreground">{layer.shadow.offsetX}px</span>
+ </div>
+ <Slider
+ value={[layer.shadow.offsetX]}
+ onValueChange={([offsetX]) => handleShadowChange({ offsetX })}
+ min={-50}
+ max={50}
+ step={1}
+ disabled={!layer.shadow.enabled}
+ />
+ </div>
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Offset Y</label>
+ <span className="text-[10px] text-muted-foreground">{layer.shadow.offsetY}px</span>
+ </div>
+ <Slider
+ value={[layer.shadow.offsetY]}
+ onValueChange={([offsetY]) => handleShadowChange({ offsetY })}
+ min={-50}
+ max={50}
+ step={1}
+ disabled={!layer.shadow.enabled}
+ />
+ </div>
+ </div>
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+
+ <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 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>
+ <div className="flex items-center gap-2">
+ <input
+ type="color"
+ value={layer.stroke.color}
+ onChange={(e) => handleStrokeChange({ color: e.target.value })}
+ className="w-8 h-8 rounded border border-input cursor-pointer"
+ disabled={!layer.stroke.enabled}
+ />
+ <input
+ type="text"
+ value={layer.stroke.color}
+ onChange={(e) => handleStrokeChange({ color: e.target.value })}
+ className="flex-1 px-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary font-mono disabled:opacity-50"
+ disabled={!layer.stroke.enabled}
+ />
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Width</label>
+ <span className="text-[10px] text-muted-foreground">{layer.stroke.width}px</span>
+ </div>
+ <Slider
+ value={[layer.stroke.width]}
+ onValueChange={([width]) => handleStrokeChange({ width })}
+ min={1}
+ max={20}
+ step={1}
+ disabled={!layer.stroke.enabled}
+ />
+ </div>
+
+ <div>
+ <label className="block text-[10px] text-muted-foreground mb-1.5">Style</label>
+ <div className="grid grid-cols-3 gap-1">
+ {(['solid', 'dashed', 'dotted'] as const).map((style) => (
+ <button
+ key={style}
+ onClick={() => handleStrokeChange({ style })}
+ disabled={!layer.stroke.enabled}
+ className={`px-2 py-1.5 text-[10px] rounded capitalize transition-colors ${
+ layer.stroke.style === style
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-secondary-foreground hover:bg-accent disabled:opacity-50'
+ }`}
+ >
+ {style}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+
+ <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 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>
+ <div className="flex items-center gap-2">
+ <input
+ type="color"
+ value={layer.glow.color}
+ onChange={(e) => handleGlowChange({ color: e.target.value })}
+ className="w-8 h-8 rounded border border-input cursor-pointer"
+ disabled={!layer.glow.enabled}
+ />
+ <input
+ type="text"
+ value={layer.glow.color}
+ onChange={(e) => handleGlowChange({ color: e.target.value })}
+ className="flex-1 px-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary font-mono disabled:opacity-50"
+ disabled={!layer.glow.enabled}
+ />
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Blur</label>
+ <span className="text-[10px] text-muted-foreground">{layer.glow.blur}px</span>
+ </div>
+ <Slider
+ value={[layer.glow.blur]}
+ onValueChange={([blur]) => handleGlowChange({ blur })}
+ min={0}
+ max={100}
+ step={1}
+ disabled={!layer.glow.enabled}
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Intensity</label>
+ <span className="text-[10px] text-muted-foreground">{Math.round(layer.glow.intensity * 100)}%</span>
+ </div>
+ <Slider
+ value={[layer.glow.intensity]}
+ onValueChange={([intensity]) => handleGlowChange({ intensity })}
+ min={0}
+ max={2}
+ step={0.1}
+ disabled={!layer.glow.enabled}
+ />
+ </div>
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/FilterPresetsSection.tsx b/apps/image/src/components/editor/inspector/FilterPresetsSection.tsx
new file mode 100644
index 00000000..ac7311fd
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/FilterPresetsSection.tsx
@@ -0,0 +1,265 @@
+import { useState, useMemo } from 'react';
+import { useProjectStore } from '../../../stores/project-store';
+import type { ImageLayer, Filter } from '../../../types/project';
+import { Sparkles, Check } from 'lucide-react';
+
+interface Props {
+ layer: ImageLayer;
+}
+
+interface FilterPreset {
+ id: string;
+ name: string;
+ category: 'basic' | 'vintage' | 'cinematic' | 'mood';
+ filters: Filter;
+ thumbnail?: string;
+}
+
+const FILTER_PRESETS: FilterPreset[] = [
+ {
+ id: 'original',
+ name: 'Original',
+ category: 'basic',
+ filters: { brightness: 100, contrast: 100, saturation: 100, hue: 0, blur: 0, sharpen: 0 },
+ },
+ {
+ id: 'vivid',
+ name: 'Vivid',
+ category: 'basic',
+ filters: { brightness: 105, contrast: 115, saturation: 130, hue: 0, blur: 0, sharpen: 10 },
+ },
+ {
+ id: 'warm',
+ name: 'Warm',
+ category: 'mood',
+ filters: { brightness: 105, contrast: 105, saturation: 110, hue: 15, blur: 0, sharpen: 0 },
+ },
+ {
+ id: 'cool',
+ name: 'Cool',
+ category: 'mood',
+ filters: { brightness: 100, contrast: 105, saturation: 95, hue: -15, blur: 0, sharpen: 0 },
+ },
+ {
+ id: 'bw',
+ name: 'B&W',
+ category: 'basic',
+ filters: { brightness: 105, contrast: 115, saturation: 0, hue: 0, blur: 0, sharpen: 5 },
+ },
+ {
+ id: 'vintage',
+ name: 'Vintage',
+ category: 'vintage',
+ filters: { brightness: 95, contrast: 90, saturation: 75, hue: 20, blur: 0, sharpen: 0 },
+ },
+ {
+ id: 'fade',
+ name: 'Fade',
+ category: 'vintage',
+ filters: { brightness: 110, contrast: 85, saturation: 80, hue: 0, blur: 0, sharpen: 0 },
+ },
+ {
+ id: 'dramatic',
+ name: 'Dramatic',
+ category: 'cinematic',
+ filters: { brightness: 95, contrast: 130, saturation: 90, hue: 0, blur: 0, sharpen: 15 },
+ },
+ {
+ id: 'moody',
+ name: 'Moody',
+ category: 'mood',
+ filters: { brightness: 90, contrast: 110, saturation: 85, hue: -10, blur: 0, sharpen: 5 },
+ },
+ {
+ id: 'bright',
+ name: 'Bright',
+ category: 'basic',
+ filters: { brightness: 120, contrast: 105, saturation: 105, hue: 0, blur: 0, sharpen: 0 },
+ },
+ {
+ id: 'sepia',
+ name: 'Sepia',
+ category: 'vintage',
+ filters: { brightness: 105, contrast: 95, saturation: 40, hue: 35, blur: 0, sharpen: 0 },
+ },
+ {
+ id: 'cinematic',
+ name: 'Cinematic',
+ category: 'cinematic',
+ filters: { brightness: 95, contrast: 115, saturation: 95, hue: -5, blur: 0, sharpen: 10 },
+ },
+ {
+ id: 'pop',
+ name: 'Pop',
+ category: 'mood',
+ filters: { brightness: 110, contrast: 120, saturation: 140, hue: 5, blur: 0, sharpen: 5 },
+ },
+ {
+ id: 'matte',
+ name: 'Matte',
+ category: 'cinematic',
+ filters: { brightness: 105, contrast: 85, saturation: 90, hue: 0, blur: 0, sharpen: 0 },
+ },
+ {
+ id: 'retro',
+ name: 'Retro',
+ category: 'vintage',
+ filters: { brightness: 100, contrast: 95, saturation: 70, hue: 25, blur: 0, sharpen: 0 },
+ },
+ {
+ id: 'punch',
+ name: 'Punch',
+ category: 'basic',
+ filters: { brightness: 100, contrast: 125, saturation: 115, hue: 0, blur: 0, sharpen: 20 },
+ },
+];
+
+function filtersMatch(a: Filter, b: Filter): boolean {
+ return (
+ a.brightness === b.brightness &&
+ a.contrast === b.contrast &&
+ a.saturation === b.saturation &&
+ a.hue === b.hue &&
+ a.blur === b.blur &&
+ a.sharpen === b.sharpen
+ );
+}
+
+function interpolateFilters(target: Filter, intensity: number): Filter {
+ const lerp = (defaultVal: number, targetVal: number) => defaultVal + (targetVal - defaultVal) * (intensity / 100);
+ return {
+ brightness: Math.round(lerp(100, target.brightness)),
+ contrast: Math.round(lerp(100, target.contrast)),
+ saturation: Math.round(lerp(100, target.saturation)),
+ hue: Math.round(lerp(0, target.hue)),
+ blur: Math.round(lerp(0, target.blur)),
+ sharpen: Math.round(lerp(0, target.sharpen)),
+ };
+}
+
+export function FilterPresetsSection({ layer }: Props) {
+ const { updateLayer } = useProjectStore();
+ const [intensity, setIntensity] = useState(100);
+ const [activePresetId, setActivePresetId] = useState<string | null>(() => {
+ const match = FILTER_PRESETS.find((p) => filtersMatch(layer.filters, p.filters));
+ return match?.id ?? null;
+ });
+
+ const currentPreset = useMemo(
+ () => FILTER_PRESETS.find((p) => p.id === activePresetId),
+ [activePresetId]
+ );
+
+ const handlePresetSelect = (preset: FilterPreset) => {
+ setActivePresetId(preset.id);
+ const filters = intensity === 100 ? preset.filters : interpolateFilters(preset.filters, intensity);
+ updateLayer<ImageLayer>(layer.id, { filters });
+ };
+
+ const handleIntensityChange = (newIntensity: number) => {
+ setIntensity(newIntensity);
+ if (currentPreset) {
+ const filters = interpolateFilters(currentPreset.filters, newIntensity);
+ updateLayer<ImageLayer>(layer.id, { filters });
+ }
+ };
+
+ const isOriginal = activePresetId === 'original' || filtersMatch(layer.filters, FILTER_PRESETS[0].filters);
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
+ Filters
+ </h4>
+ {!isOriginal && (
+ <button
+ onClick={() => handlePresetSelect(FILTER_PRESETS[0])}
+ className="text-[10px] text-muted-foreground hover:text-foreground transition-colors"
+ >
+ Reset
+ </button>
+ )}
+ </div>
+
+ {activePresetId && activePresetId !== 'original' && (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <label className="text-[11px] font-medium text-foreground">Intensity</label>
+ <span className="text-[11px] font-mono text-muted-foreground">{intensity}%</span>
+ </div>
+ <input
+ type="range"
+ value={intensity}
+ min={0}
+ max={100}
+ onChange={(e) => handleIntensityChange(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
+ [&::-webkit-slider-thumb]:cursor-pointer"
+ />
+ </div>
+ )}
+
+ <div className="grid grid-cols-4 gap-2">
+ {FILTER_PRESETS.map((preset) => {
+ const isActive = activePresetId === preset.id;
+ const previewStyle = getFilterPreviewStyle(preset.filters);
+
+ return (
+ <button
+ key={preset.id}
+ onClick={() => handlePresetSelect(preset)}
+ className={`relative group flex flex-col items-center gap-1 p-2 rounded-lg transition-all ${
+ isActive
+ ? 'bg-primary/20 ring-2 ring-primary'
+ : 'bg-secondary/50 hover:bg-secondary'
+ }`}
+ >
+ <div
+ className="w-10 h-10 rounded-md bg-gradient-to-br from-gray-400 to-gray-600 flex items-center justify-center overflow-hidden"
+ style={previewStyle}
+ >
+ {preset.id === 'original' ? (
+ <Sparkles size={16} className="text-white/80" />
+ ) : isActive ? (
+ <Check size={14} className="text-primary" />
+ ) : null}
+ </div>
+ <span className={`text-[9px] font-medium truncate w-full text-center ${
+ isActive ? 'text-primary' : 'text-muted-foreground group-hover:text-foreground'
+ }`}>
+ {preset.name}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+function getFilterPreviewStyle(filters: Filter): React.CSSProperties {
+ const filterParts: string[] = [];
+
+ if (filters.brightness !== 100) {
+ filterParts.push(`brightness(${filters.brightness}%)`);
+ }
+ if (filters.contrast !== 100) {
+ filterParts.push(`contrast(${filters.contrast}%)`);
+ }
+ if (filters.saturation !== 100) {
+ filterParts.push(`saturate(${filters.saturation}%)`);
+ }
+ if (filters.hue !== 0) {
+ filterParts.push(`hue-rotate(${filters.hue}deg)`);
+ }
+
+ return {
+ filter: filterParts.length > 0 ? filterParts.join(' ') : undefined,
+ };
+}
diff --git a/apps/image/src/components/editor/inspector/ImageAdjustmentsSection.tsx b/apps/image/src/components/editor/inspector/ImageAdjustmentsSection.tsx
new file mode 100644
index 00000000..2cde5d86
--- /dev/null
+++ b/apps/image/src/components/editor/inspector/ImageAdjustmentsSection.tsx
@@ -0,0 +1,186 @@
+import { useProjectStore } from '../../../stores/project-store';
+import type { ImageLayer, Filter } from '../../../types/project';
+import { Sun, Contrast, Palette, Thermometer, Focus, Sparkles } from 'lucide-react';
+
+interface Props {
+ layer: ImageLayer;
+}
+
+interface AdjustmentSliderProps {
+ icon: React.ReactNode;
+ label: string;
+ value: number;
+ min: number;
+ max: number;
+ defaultValue: number;
+ onChange: (value: number) => void;
+ unit?: string;
+}
+
+function AdjustmentSlider({ icon, label, value, min, max, defaultValue, onChange, unit = '' }: AdjustmentSliderProps) {
+ const isModified = value !== defaultValue;
+ const percentage = ((value - min) / (max - min)) * 100;
+
+ return (
+ <div className="space-y-1.5">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-1.5">
+ <span className="text-muted-foreground">{icon}</span>
+ <label className="text-[11px] text-foreground font-medium">{label}</label>
+ </div>
+ <div className="flex items-center gap-1">
+ <span className={`text-[11px] font-mono ${isModified ? 'text-primary' : 'text-muted-foreground'}`}>
+ {value}{unit}
+ </span>
+ {isModified && (
+ <button
+ onClick={() => onChange(defaultValue)}
+ className="text-[9px] text-muted-foreground hover:text-foreground px-1 py-0.5 rounded hover:bg-secondary transition-colors"
+ >
+ Reset
+ </button>
+ )}
+ </div>
+ </div>
+ <div className="relative">
+ <input
+ type="range"
+ value={value}
+ min={min}
+ max={max}
+ onChange={(e) => onChange(Number(e.target.value))}
+ className="w-full h-1.5 appearance-none bg-secondary rounded-full cursor-pointer
+ [&::-webkit-slider-thumb]:appearance-none
+ [&::-webkit-slider-thumb]:w-3
+ [&::-webkit-slider-thumb]:h-3
+ [&::-webkit-slider-thumb]:rounded-full
+ [&::-webkit-slider-thumb]:bg-primary
+ [&::-webkit-slider-thumb]:shadow-sm
+ [&::-webkit-slider-thumb]:cursor-pointer
+ [&::-webkit-slider-thumb]:transition-transform
+ [&::-webkit-slider-thumb]:hover:scale-110"
+ style={{
+ background: `linear-gradient(to right, hsl(var(--primary)) 0%, hsl(var(--primary)) ${percentage}%, hsl(var(--secondary)) ${percentage}%, hsl(var(--secondary)) 100%)`
+ }}
+ />
+ </div>
+ </div>
+ );
+}
+
+export function ImageAdjustmentsSection({ layer }: Props) {
+ const { updateLayer } = useProjectStore();
+
+ const handleFilterChange = (key: keyof Filter, value: number) => {
+ updateLayer<ImageLayer>(layer.id, {
+ filters: { ...layer.filters, [key]: value },
+ });
+ };
+
+ const resetAllFilters = () => {
+ updateLayer<ImageLayer>(layer.id, {
+ filters: {
+ brightness: 100,
+ contrast: 100,
+ saturation: 100,
+ hue: 0,
+ blur: 0,
+ sharpen: 0,
+ },
+ });
+ };
+
+ const hasModifications =
+ layer.filters.brightness !== 100 ||
+ layer.filters.contrast !== 100 ||
+ layer.filters.saturation !== 100 ||
+ layer.filters.hue !== 0 ||
+ layer.filters.blur !== 0 ||
+ layer.filters.sharpen !== 0;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
+ Adjustments
+ </h4>
+ {hasModifications && (
+ <button
+ onClick={resetAllFilters}
+ className="text-[10px] text-muted-foreground hover:text-foreground transition-colors"
+ >
+ Reset All
+ </button>
+ )}
+ </div>
+
+ <div className="space-y-4 p-3 bg-secondary/30 rounded-lg border border-border/50">
+ <AdjustmentSlider
+ icon={<Sun size={12} />}
+ label="Brightness"
+ value={layer.filters.brightness}
+ min={0}
+ max={200}
+ defaultValue={100}
+ onChange={(v) => handleFilterChange('brightness', v)}
+ unit="%"
+ />
+
+ <AdjustmentSlider
+ icon={<Contrast size={12} />}
+ label="Contrast"
+ value={layer.filters.contrast}
+ min={0}
+ max={200}
+ defaultValue={100}
+ onChange={(v) => handleFilterChange('contrast', v)}
+ unit="%"
+ />
+
+ <AdjustmentSlider
+ icon={<Palette size={12} />}
+ label="Saturation"
+ value={layer.filters.saturation}
+ min={0}
+ max={200}
+ defaultValue={100}
+ onChange={(v) => handleFilterChange('saturation', v)}
+ unit="%"
+ />
+
+ <AdjustmentSlider
+ icon={<Thermometer size={12} />}
+ label="Temperature"
+ value={layer.filters.hue}
+ min={-180}
+ max={180}
+ defaultValue={0}
+ onChange={(v) => handleFilterChange('hue', v)}
+ unit="°"
+ />
+
+ <AdjustmentSlider
+ icon={<Focus size={12} />}
+ label="Blur"
+ value={layer.filters.blur}
+ min={0}
+ max={50}
+ defaultValue={0}
+ onChange={(v) => handleFilterChange('blur', v)}
+ unit="px"
+ />
+
+ <AdjustmentSlider
+ icon={<Sparkles size={12} />}
+ label="Sharpen"
+ value={layer.filters.sharpen}
+ min={0}
+ max={100}
+ defaultValue={0}
+ onChange={(v) => handleFilterChange('sharpen', v)}
+ unit="%"
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/inspector/Inspector.tsx b/apps/image/src/components/editor/inspector/Inspector.tsx
index dea31f0f..bacf9e03 100644
--- a/apps/image/src/components/editor/inspector/Inspector.tsx
+++ b/apps/image/src/components/editor/inspector/Inspector.tsx
@@ -1,17 +1,23 @@
import { useProjectStore } from '../../../stores/project-store';
import { TransformSection } from './TransformSection';
+import { AlignmentSection } from './AlignmentSection';
import { AppearanceSection } from './AppearanceSection';
+import { EffectsSection } from './EffectsSection';
+import { ImageAdjustmentsSection } from './ImageAdjustmentsSection';
+import { FilterPresetsSection } from './FilterPresetsSection';
+import { CropSection } from './CropSection';
+import { BackgroundRemovalSection } from './BackgroundRemovalSection';
import { TextSection } from './TextSection';
import { ShapeSection } from './ShapeSection';
import { ArtboardSection } from './ArtboardSection';
-import type { TextLayer, ShapeLayer } from '../../../types/project';
+import type { Layer, ImageLayer, TextLayer, ShapeLayer } from '../../../types/project';
export function Inspector() {
const { project, selectedLayerIds, selectedArtboardId } = useProjectStore();
const selectedLayers = selectedLayerIds
.map((id) => project?.layers[id])
- .filter(Boolean);
+ .filter((layer): layer is Layer => layer !== undefined);
const singleLayer = selectedLayers.length === 1 ? selectedLayers[0] : null;
@@ -37,15 +43,13 @@ export function Inspector() {
if (selectedLayers.length > 1) {
return (
- <div className="p-4">
- <div className="flex items-center justify-between mb-4">
+ <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>
- <p className="text-xs text-muted-foreground">
- Multiple selection editing coming soon
- </p>
+ <AlignmentSection layers={selectedLayers} />
</div>
);
}
@@ -63,8 +67,21 @@ export function Inspector() {
<TransformSection layer={singleLayer} />
+ <AlignmentSection layers={[singleLayer]} />
+
<AppearanceSection layer={singleLayer} />
+ <EffectsSection layer={singleLayer} />
+
+ {singleLayer.type === 'image' && (
+ <>
+ <CropSection layer={singleLayer as ImageLayer} />
+ <BackgroundRemovalSection layer={singleLayer as ImageLayer} />
+ <FilterPresetsSection layer={singleLayer as ImageLayer} />
+ <ImageAdjustmentsSection layer={singleLayer as ImageLayer} />
+ </>
+ )}
+
{singleLayer.type === 'text' && (
<TextSection layer={singleLayer as TextLayer} />
)}
diff --git a/apps/image/src/components/editor/inspector/ShapeSection.tsx b/apps/image/src/components/editor/inspector/ShapeSection.tsx
index aafede7a..9761fb23 100644
--- a/apps/image/src/components/editor/inspector/ShapeSection.tsx
+++ b/apps/image/src/components/editor/inspector/ShapeSection.tsx
@@ -1,5 +1,10 @@
+import { useState } from 'react';
import { useProjectStore } from '../../../stores/project-store';
-import type { ShapeLayer, ShapeStyle } from '../../../types/project';
+import type { ShapeLayer, ShapeStyle, Gradient, FillType } from '../../../types/project';
+import { Slider } from '@openreel/ui';
+import { GradientPicker } from '../../ui/GradientPicker';
+import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@openreel/ui';
+import { ChevronDown } from 'lucide-react';
interface Props {
layer: ShapeLayer;
@@ -7,6 +12,8 @@ interface Props {
export function ShapeSection({ layer }: Props) {
const { updateLayer } = useProjectStore();
+ const [isFillOpen, setIsFillOpen] = useState(true);
+ const [isStrokeOpen, setIsStrokeOpen] = useState(false);
const handleStyleChange = (updates: Partial<ShapeStyle>) => {
updateLayer<ShapeLayer>(layer.id, {
@@ -14,153 +21,230 @@ export function ShapeSection({ layer }: Props) {
});
};
+ const handleFillTypeChange = (fillType: FillType) => {
+ if (fillType === 'gradient' && !layer.shapeStyle.gradient) {
+ handleStyleChange({
+ fillType,
+ gradient: {
+ type: 'linear',
+ angle: 90,
+ stops: [
+ { offset: 0, color: layer.shapeStyle.fill ?? '#3b82f6' },
+ { offset: 1, color: '#8b5cf6' },
+ ],
+ },
+ });
+ } else {
+ handleStyleChange({ fillType });
+ }
+ };
+
+ const handleGradientChange = (gradient: Gradient) => {
+ handleStyleChange({ gradient });
+ };
+
return (
- <div className="space-y-4">
+ <div className="space-y-3">
<h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Shape
</h4>
- <div>
- <label className="block text-[10px] text-muted-foreground mb-1">Fill Color</label>
- <div className="flex items-center gap-2">
- <button
- onClick={() => handleStyleChange({ fill: layer.shapeStyle.fill ? null : '#3b82f6' })}
- className={`w-8 h-8 rounded border border-input flex items-center justify-center ${
- layer.shapeStyle.fill ? '' : 'bg-background'
- }`}
- style={{ backgroundColor: layer.shapeStyle.fill ?? undefined }}
- title={layer.shapeStyle.fill ? 'Remove fill' : 'Add fill'}
- >
- {!layer.shapeStyle.fill && (
- <span className="text-xs text-muted-foreground">∅</span>
- )}
- </button>
- {layer.shapeStyle.fill && (
- <>
- <input
- type="color"
- value={layer.shapeStyle.fill}
- onChange={(e) => handleStyleChange({ fill: e.target.value })}
- className="w-8 h-8 rounded border border-input cursor-pointer"
- />
- <input
- type="text"
- value={layer.shapeStyle.fill}
- onChange={(e) => handleStyleChange({ fill: e.target.value })}
- className="flex-1 px-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary font-mono"
+ <Collapsible open={isFillOpen} onOpenChange={setIsFillOpen}>
+ <CollapsibleTrigger asChild>
+ <button className="w-full flex items-center justify-between p-2 rounded-lg bg-secondary/50 hover:bg-secondary transition-colors">
+ <span className="text-xs font-medium">Fill</span>
+ <div className="flex items-center gap-2">
+ <div
+ className="w-5 h-5 rounded border border-input"
+ style={{
+ backgroundColor: layer.shapeStyle.fillType === 'solid' ? (layer.shapeStyle.fill ?? 'transparent') : undefined,
+ background: layer.shapeStyle.fillType === 'gradient' && layer.shapeStyle.gradient
+ ? layer.shapeStyle.gradient.type === 'linear'
+ ? `linear-gradient(${layer.shapeStyle.gradient.angle}deg, ${layer.shapeStyle.gradient.stops.map((s) => `${s.color} ${Math.round(s.offset * 100)}%`).join(', ')})`
+ : `radial-gradient(circle, ${layer.shapeStyle.gradient.stops.map((s) => `${s.color} ${Math.round(s.offset * 100)}%`).join(', ')})`
+ : undefined,
+ }}
/>
- </>
- )}
- </div>
- </div>
-
- {layer.shapeStyle.fill && (
- <div>
- <label className="block text-[10px] text-muted-foreground mb-1">Fill Opacity</label>
- <div className="flex items-center gap-2">
- <input
- type="range"
- value={layer.shapeStyle.fillOpacity * 100}
- onChange={(e) => handleStyleChange({ fillOpacity: Number(e.target.value) / 100 })}
- min={0}
- max={100}
- className="flex-1 h-1 accent-primary"
- />
- <span className="text-[10px] text-muted-foreground w-8 text-right">
- {Math.round(layer.shapeStyle.fillOpacity * 100)}%
- </span>
- </div>
- </div>
- )}
-
- <div>
- <label className="block text-[10px] text-muted-foreground mb-1">Stroke Color</label>
- <div className="flex items-center gap-2">
- <button
- onClick={() => handleStyleChange({ stroke: layer.shapeStyle.stroke ? null : '#000000' })}
- className={`w-8 h-8 rounded border-2 flex items-center justify-center ${
- layer.shapeStyle.stroke ? '' : 'border-input bg-background'
- }`}
- style={{ borderColor: layer.shapeStyle.stroke ?? undefined }}
- title={layer.shapeStyle.stroke ? 'Remove stroke' : 'Add stroke'}
- >
- {!layer.shapeStyle.stroke && (
- <span className="text-xs text-muted-foreground">∅</span>
- )}
+ <ChevronDown size={14} className={`text-muted-foreground transition-transform ${isFillOpen ? 'rotate-180' : ''}`} />
+ </div>
</button>
- {layer.shapeStyle.stroke && (
- <>
- <input
- type="color"
- value={layer.shapeStyle.stroke}
- onChange={(e) => handleStyleChange({ stroke: e.target.value })}
- className="w-8 h-8 rounded border border-input cursor-pointer"
- />
- <input
- type="text"
- value={layer.shapeStyle.stroke}
- onChange={(e) => handleStyleChange({ stroke: e.target.value })}
- className="flex-1 px-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary font-mono"
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <div className="p-3 space-y-3 bg-background/50 rounded-b-lg border border-t-0 border-border">
+ <div className="grid grid-cols-2 gap-1">
+ <button
+ onClick={() => handleFillTypeChange('solid')}
+ className={`px-3 py-1.5 text-xs rounded-md transition-colors ${
+ layer.shapeStyle.fillType === 'solid'
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-secondary-foreground hover:bg-accent'
+ }`}
+ >
+ Solid
+ </button>
+ <button
+ onClick={() => handleFillTypeChange('gradient')}
+ className={`px-3 py-1.5 text-xs rounded-md transition-colors ${
+ layer.shapeStyle.fillType === 'gradient'
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-secondary-foreground hover:bg-accent'
+ }`}
+ >
+ Gradient
+ </button>
+ </div>
+
+ {layer.shapeStyle.fillType === 'solid' ? (
+ <div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => handleStyleChange({ fill: layer.shapeStyle.fill ? null : '#3b82f6' })}
+ className={`w-8 h-8 rounded border border-input flex items-center justify-center ${
+ layer.shapeStyle.fill ? '' : 'bg-background'
+ }`}
+ style={{ backgroundColor: layer.shapeStyle.fill ?? undefined }}
+ title={layer.shapeStyle.fill ? 'Remove fill' : 'Add fill'}
+ >
+ {!layer.shapeStyle.fill && (
+ <span className="text-xs text-muted-foreground">∅</span>
+ )}
+ </button>
+ {layer.shapeStyle.fill && (
+ <>
+ <input
+ type="color"
+ value={layer.shapeStyle.fill}
+ onChange={(e) => handleStyleChange({ fill: e.target.value })}
+ className="w-8 h-8 rounded border border-input cursor-pointer"
+ />
+ <input
+ type="text"
+ value={layer.shapeStyle.fill}
+ onChange={(e) => handleStyleChange({ fill: e.target.value })}
+ className="flex-1 px-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary font-mono"
+ />
+ </>
+ )}
+ </div>
+ </div>
+ ) : (
+ <GradientPicker
+ value={layer.shapeStyle.gradient}
+ onChange={handleGradientChange}
/>
- </>
- )}
- </div>
- </div>
+ )}
- {layer.shapeStyle.stroke && (
- <>
- <div>
- <label className="block text-[10px] text-muted-foreground mb-1">Stroke Width</label>
- <div className="flex items-center gap-2">
- <input
- type="range"
- value={layer.shapeStyle.strokeWidth}
- onChange={(e) => handleStyleChange({ strokeWidth: Number(e.target.value) })}
- min={1}
- max={20}
- className="flex-1 h-1 accent-primary"
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Opacity</label>
+ <span className="text-[10px] text-muted-foreground">{Math.round(layer.shapeStyle.fillOpacity * 100)}%</span>
+ </div>
+ <Slider
+ value={[layer.shapeStyle.fillOpacity * 100]}
+ onValueChange={([opacity]) => handleStyleChange({ fillOpacity: opacity / 100 })}
+ min={0}
+ max={100}
+ step={1}
/>
- <span className="text-[10px] text-muted-foreground w-6 text-right">
- {layer.shapeStyle.strokeWidth}
- </span>
</div>
</div>
+ </CollapsibleContent>
+ </Collapsible>
- <div>
- <label className="block text-[10px] text-muted-foreground mb-1">Stroke Opacity</label>
+ <Collapsible open={isStrokeOpen} onOpenChange={setIsStrokeOpen}>
+ <CollapsibleTrigger asChild>
+ <button className="w-full flex items-center justify-between p-2 rounded-lg bg-secondary/50 hover:bg-secondary transition-colors">
+ <span className="text-xs font-medium">Stroke</span>
<div className="flex items-center gap-2">
- <input
- type="range"
- value={layer.shapeStyle.strokeOpacity * 100}
- onChange={(e) => handleStyleChange({ strokeOpacity: Number(e.target.value) / 100 })}
- min={0}
- max={100}
- className="flex-1 h-1 accent-primary"
+ <div
+ className="w-5 h-5 rounded border-2"
+ style={{ borderColor: layer.shapeStyle.stroke ?? '#71717a' }}
/>
- <span className="text-[10px] text-muted-foreground w-8 text-right">
- {Math.round(layer.shapeStyle.strokeOpacity * 100)}%
- </span>
+ <ChevronDown size={14} className={`text-muted-foreground transition-transform ${isStrokeOpen ? 'rotate-180' : ''}`} />
+ </div>
+ </button>
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <div className="p-3 space-y-3 bg-background/50 rounded-b-lg border border-t-0 border-border">
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => handleStyleChange({ stroke: layer.shapeStyle.stroke ? null : '#000000' })}
+ className={`w-8 h-8 rounded border-2 flex items-center justify-center ${
+ layer.shapeStyle.stroke ? '' : 'border-input bg-background'
+ }`}
+ style={{ borderColor: layer.shapeStyle.stroke ?? undefined }}
+ title={layer.shapeStyle.stroke ? 'Remove stroke' : 'Add stroke'}
+ >
+ {!layer.shapeStyle.stroke && (
+ <span className="text-xs text-muted-foreground">∅</span>
+ )}
+ </button>
+ {layer.shapeStyle.stroke && (
+ <>
+ <input
+ type="color"
+ value={layer.shapeStyle.stroke}
+ onChange={(e) => handleStyleChange({ stroke: e.target.value })}
+ className="w-8 h-8 rounded border border-input cursor-pointer"
+ />
+ <input
+ type="text"
+ value={layer.shapeStyle.stroke}
+ onChange={(e) => handleStyleChange({ stroke: e.target.value })}
+ className="flex-1 px-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary font-mono"
+ />
+ </>
+ )}
</div>
+
+ {layer.shapeStyle.stroke && (
+ <>
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Width</label>
+ <span className="text-[10px] text-muted-foreground">{layer.shapeStyle.strokeWidth}px</span>
+ </div>
+ <Slider
+ value={[layer.shapeStyle.strokeWidth]}
+ onValueChange={([width]) => handleStyleChange({ strokeWidth: width })}
+ min={1}
+ max={20}
+ step={1}
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Opacity</label>
+ <span className="text-[10px] text-muted-foreground">{Math.round(layer.shapeStyle.strokeOpacity * 100)}%</span>
+ </div>
+ <Slider
+ value={[layer.shapeStyle.strokeOpacity * 100]}
+ onValueChange={([opacity]) => handleStyleChange({ strokeOpacity: opacity / 100 })}
+ min={0}
+ max={100}
+ step={1}
+ />
+ </div>
+ </>
+ )}
</div>
- </>
- )}
+ </CollapsibleContent>
+ </Collapsible>
- {(layer.shapeType === 'rectangle') && (
- <div>
- <label className="block text-[10px] text-muted-foreground mb-1">Corner Radius</label>
- <div className="flex items-center gap-2">
- <input
- type="range"
- value={layer.shapeStyle.cornerRadius}
- onChange={(e) => handleStyleChange({ cornerRadius: Number(e.target.value) })}
- min={0}
- max={100}
- className="flex-1 h-1 accent-primary"
- />
- <span className="text-[10px] text-muted-foreground w-6 text-right">
- {layer.shapeStyle.cornerRadius}
- </span>
+ {layer.shapeType === 'rectangle' && (
+ <div className="p-3 space-y-2 bg-secondary/50 rounded-lg">
+ <div className="flex items-center justify-between mb-1">
+ <label className="text-[10px] text-muted-foreground">Corner Radius</label>
+ <span className="text-[10px] text-muted-foreground">{layer.shapeStyle.cornerRadius}px</span>
</div>
+ <Slider
+ value={[layer.shapeStyle.cornerRadius]}
+ onValueChange={([radius]) => handleStyleChange({ cornerRadius: radius })}
+ min={0}
+ max={100}
+ step={1}
+ />
</div>
)}
</div>
diff --git a/apps/image/src/components/editor/inspector/TextSection.tsx b/apps/image/src/components/editor/inspector/TextSection.tsx
index bbb02a28..ecd7a963 100644
--- a/apps/image/src/components/editor/inspector/TextSection.tsx
+++ b/apps/image/src/components/editor/inspector/TextSection.tsx
@@ -1,28 +1,12 @@
import { useProjectStore } from '../../../stores/project-store';
import type { TextLayer, TextStyle } from '../../../types/project';
import { AlignLeft, AlignCenter, AlignRight, Bold, Italic, Underline } from 'lucide-react';
+import { FontPicker } from '../../ui/FontPicker';
interface Props {
layer: TextLayer;
}
-const FONT_FAMILIES = [
- 'Inter',
- 'DM Sans',
- 'Poppins',
- 'Montserrat',
- 'Playfair Display',
- 'Roboto',
- 'Open Sans',
- 'Lato',
- 'Oswald',
- 'Bebas Neue',
- 'Pacifico',
- 'Lobster',
- 'Dancing Script',
- 'Great Vibes',
-];
-
const FONT_SIZES = [8, 10, 12, 14, 16, 18, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 96, 128];
export function TextSection({ layer }: Props) {
@@ -72,21 +56,15 @@ export function TextSection({ layer }: Props) {
/>
</div>
+ <div>
+ <label className="block text-[10px] text-muted-foreground mb-1">Font</label>
+ <FontPicker
+ value={layer.style.fontFamily}
+ onChange={(fontFamily) => handleStyleChange({ fontFamily })}
+ />
+ </div>
+
<div className="grid grid-cols-2 gap-2">
- <div>
- <label className="block text-[10px] text-muted-foreground mb-1">Font</label>
- <select
- value={layer.style.fontFamily}
- onChange={(e) => handleStyleChange({ fontFamily: e.target.value })}
- className="w-full px-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
- >
- {FONT_FAMILIES.map((font) => (
- <option key={font} value={font} style={{ fontFamily: font }}>
- {font}
- </option>
- ))}
- </select>
- </div>
<div>
<label className="block text-[10px] text-muted-foreground mb-1">Size</label>
<select
@@ -101,6 +79,20 @@ export function TextSection({ layer }: Props) {
))}
</select>
</div>
+ <div>
+ <label className="block text-[10px] text-muted-foreground mb-1">Weight</label>
+ <select
+ value={layer.style.fontWeight}
+ onChange={(e) => handleStyleChange({ fontWeight: Number(e.target.value) })}
+ className="w-full px-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
+ >
+ <option value={300}>Light</option>
+ <option value={400}>Regular</option>
+ <option value={500}>Medium</option>
+ <option value={600}>Semibold</option>
+ <option value={700}>Bold</option>
+ </select>
+ </div>
</div>
<div className="flex gap-1">
diff --git a/apps/image/src/components/editor/pages/PagesBar.tsx b/apps/image/src/components/editor/pages/PagesBar.tsx
new file mode 100644
index 00000000..b1efae32
--- /dev/null
+++ b/apps/image/src/components/editor/pages/PagesBar.tsx
@@ -0,0 +1,199 @@
+import { useState, useRef } from 'react';
+import { Plus, Trash2, Copy, MoreHorizontal, ChevronUp, ChevronDown } from 'lucide-react';
+import { useProjectStore } from '../../../stores/project-store';
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@openreel/ui';
+
+export function PagesBar() {
+ const {
+ project,
+ selectedArtboardId,
+ selectArtboard,
+ addArtboard,
+ removeArtboard,
+ updateArtboard,
+ } = useProjectStore();
+
+ const [isExpanded, setIsExpanded] = useState(true);
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ if (!project) return null;
+
+ const artboards = project.artboards;
+
+ const handleAddPage = () => {
+ const currentArtboard = artboards.find((a) => a.id === selectedArtboardId);
+ const size = currentArtboard?.size ?? { width: 1080, height: 1080 };
+ const newId = addArtboard(`Page ${artboards.length + 1}`, size);
+ selectArtboard(newId);
+ };
+
+ const handleDuplicatePage = (artboardId: string) => {
+ const artboard = artboards.find((a) => a.id === artboardId);
+ if (!artboard) return;
+ const newId = addArtboard(`${artboard.name} copy`, artboard.size);
+ selectArtboard(newId);
+ };
+
+ const handleDeletePage = (artboardId: string) => {
+ if (artboards.length <= 1) return;
+ removeArtboard(artboardId);
+ };
+
+ const handleRename = (artboardId: string, newName: string) => {
+ if (newName.trim()) {
+ updateArtboard(artboardId, { name: newName.trim() });
+ }
+ setEditingId(null);
+ };
+
+ const handleStartRename = (artboardId: string) => {
+ setEditingId(artboardId);
+ setTimeout(() => inputRef.current?.select(), 0);
+ };
+
+ return (
+ <div className="bg-card border-t border-border">
+ <div className="flex items-center justify-between px-3 py-1.5">
+ <button
+ onClick={() => setIsExpanded(!isExpanded)}
+ className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
+ >
+ {isExpanded ? <ChevronDown size={14} /> : <ChevronUp size={14} />}
+ <span>Pages</span>
+ <span className="text-[10px] bg-muted px-1.5 py-0.5 rounded-full">
+ {artboards.length}
+ </span>
+ </button>
+
+ <button
+ onClick={handleAddPage}
+ className="flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-accent rounded transition-colors"
+ >
+ <Plus size={14} />
+ <span>Add Page</span>
+ </button>
+ </div>
+
+ {isExpanded && (
+ <div className="px-3 pb-3 overflow-x-auto">
+ <div className="flex gap-2">
+ {artboards.map((artboard) => {
+ const isSelected = artboard.id === selectedArtboardId;
+ const aspectRatio = artboard.size.width / artboard.size.height;
+ const thumbHeight = 64;
+ const thumbWidth = Math.min(thumbHeight * aspectRatio, 100);
+
+ return (
+ <div
+ key={artboard.id}
+ className={`group relative flex-shrink-0 rounded-lg border-2 transition-all cursor-pointer ${
+ isSelected
+ ? 'border-primary ring-2 ring-primary/20'
+ : 'border-border hover:border-muted-foreground'
+ }`}
+ onClick={() => selectArtboard(artboard.id)}
+ >
+ <div
+ className="bg-muted rounded-md flex items-center justify-center overflow-hidden"
+ style={{ width: thumbWidth, height: thumbHeight }}
+ >
+ <div
+ className="rounded-sm"
+ style={{
+ width: thumbWidth - 8,
+ height: thumbHeight - 8,
+ backgroundColor:
+ artboard.background.type === 'color'
+ ? artboard.background.color
+ : artboard.background.type === 'transparent'
+ ? 'transparent'
+ : '#ffffff',
+ backgroundImage:
+ artboard.background.type === 'transparent'
+ ? 'linear-gradient(45deg, #ccc 25%, transparent 25%), linear-gradient(-45deg, #ccc 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #ccc 75%), linear-gradient(-45deg, transparent 75%, #ccc 75%)'
+ : undefined,
+ backgroundSize: '8px 8px',
+ backgroundPosition: '0 0, 0 4px, 4px -4px, -4px 0px',
+ }}
+ />
+ </div>
+
+ <div className="absolute -top-1 -right-1 opacity-0 group-hover:opacity-100 transition-opacity">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ onClick={(e) => e.stopPropagation()}
+ className="w-5 h-5 flex items-center justify-center bg-background border border-border rounded shadow-sm hover:bg-accent transition-colors"
+ >
+ <MoreHorizontal size={12} />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-40">
+ <DropdownMenuItem onClick={() => handleStartRename(artboard.id)}>
+ Rename
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => handleDuplicatePage(artboard.id)}>
+ <Copy size={14} className="mr-2" />
+ Duplicate
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => handleDeletePage(artboard.id)}
+ disabled={artboards.length <= 1}
+ className="text-destructive focus:text-destructive"
+ >
+ <Trash2 size={14} className="mr-2" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ <div className="absolute -bottom-5 left-0 right-0 text-center">
+ {editingId === artboard.id ? (
+ <input
+ ref={inputRef}
+ type="text"
+ defaultValue={artboard.name}
+ onBlur={(e) => handleRename(artboard.id, e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ handleRename(artboard.id, e.currentTarget.value);
+ } else if (e.key === 'Escape') {
+ setEditingId(null);
+ }
+ }}
+ onClick={(e) => e.stopPropagation()}
+ className="w-full text-[10px] text-center bg-transparent border-none focus:outline-none focus:ring-1 focus:ring-primary rounded px-1"
+ autoFocus
+ />
+ ) : (
+ <span
+ className={`text-[10px] truncate max-w-full inline-block ${
+ isSelected ? 'text-foreground font-medium' : 'text-muted-foreground'
+ }`}
+ onDoubleClick={(e) => {
+ e.stopPropagation();
+ handleStartRename(artboard.id);
+ }}
+ >
+ {artboard.name}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+ })}
+
+ <button
+ onClick={handleAddPage}
+ className="flex-shrink-0 w-16 h-16 flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-border hover:border-muted-foreground hover:bg-accent/50 transition-all"
+ >
+ <Plus size={20} className="text-muted-foreground" />
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/panels/HistoryPanel.tsx b/apps/image/src/components/editor/panels/HistoryPanel.tsx
new file mode 100644
index 00000000..e733c5fd
--- /dev/null
+++ b/apps/image/src/components/editor/panels/HistoryPanel.tsx
@@ -0,0 +1,125 @@
+import { History, Undo2, Redo2, Trash2, Clock } from 'lucide-react';
+import { useHistoryStore } from '../../../stores/history-store';
+import { useProjectStore } from '../../../stores/project-store';
+import { formatDistanceToNow } from '../../../utils/time';
+
+export function HistoryPanel() {
+ const { entries, currentIndex, clear, canUndo, canRedo } = useHistoryStore();
+ const { loadProject } = useProjectStore();
+ const undo = useHistoryStore((s) => s.undo);
+ const redo = useHistoryStore((s) => s.redo);
+
+ const handleUndo = () => {
+ const state = undo();
+ if (state) {
+ loadProject(state);
+ }
+ };
+
+ const handleRedo = () => {
+ const state = redo();
+ if (state) {
+ loadProject(state);
+ }
+ };
+
+ const handleJumpToState = (index: number) => {
+ if (index === currentIndex) return;
+
+ const entry = entries[index];
+ if (entry) {
+ const state = JSON.parse(entry.state);
+ loadProject(state);
+ useHistoryStore.setState({ currentIndex: index });
+ }
+ };
+
+ return (
+ <div className="h-full flex flex-col">
+ <div className="flex items-center justify-between p-3 border-b border-border">
+ <div className="flex items-center gap-2">
+ <History size={16} className="text-muted-foreground" />
+ <h3 className="text-sm font-medium text-foreground">History</h3>
+ <span className="text-[10px] bg-muted px-1.5 py-0.5 rounded-full text-muted-foreground">
+ {entries.length}
+ </span>
+ </div>
+
+ <div className="flex items-center gap-1">
+ <button
+ onClick={handleUndo}
+ disabled={!canUndo()}
+ className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent disabled:opacity-40 disabled:hover:bg-transparent disabled:cursor-not-allowed transition-colors"
+ title="Undo (Ctrl+Z)"
+ >
+ <Undo2 size={14} />
+ </button>
+ <button
+ onClick={handleRedo}
+ disabled={!canRedo()}
+ className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent disabled:opacity-40 disabled:hover:bg-transparent disabled:cursor-not-allowed transition-colors"
+ title="Redo (Ctrl+Shift+Z)"
+ >
+ <Redo2 size={14} />
+ </button>
+ <button
+ onClick={clear}
+ disabled={entries.length === 0}
+ className="p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 disabled:opacity-40 disabled:hover:bg-transparent disabled:cursor-not-allowed transition-colors"
+ title="Clear history"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ </div>
+
+ <div className="flex-1 overflow-y-auto">
+ {entries.length === 0 ? (
+ <div className="flex flex-col items-center justify-center h-full py-8 text-center">
+ <Clock size={32} className="text-muted-foreground/50 mb-3" />
+ <p className="text-xs text-muted-foreground">No history yet</p>
+ <p className="text-[10px] text-muted-foreground/70 mt-1">
+ Your actions will appear here
+ </p>
+ </div>
+ ) : (
+ <div className="py-1">
+ {[...entries].reverse().map((entry, reverseIndex) => {
+ const index = entries.length - 1 - reverseIndex;
+ const isCurrent = index === currentIndex;
+ const isFuture = index > currentIndex;
+
+ return (
+ <button
+ key={entry.id}
+ onClick={() => handleJumpToState(index)}
+ className={`w-full flex items-start gap-2 px-3 py-2 text-left transition-colors ${
+ isCurrent
+ ? 'bg-primary/10 border-l-2 border-primary'
+ : isFuture
+ ? 'opacity-50 hover:opacity-75 hover:bg-accent/50'
+ : 'hover:bg-accent'
+ }`}
+ >
+ <div className={`mt-0.5 w-2 h-2 rounded-full flex-shrink-0 ${
+ isCurrent ? 'bg-primary' : isFuture ? 'bg-muted-foreground/30' : 'bg-muted-foreground/50'
+ }`} />
+ <div className="min-w-0 flex-1">
+ <p className={`text-xs truncate ${
+ isCurrent ? 'font-medium text-foreground' : 'text-muted-foreground'
+ }`}>
+ {entry.description}
+ </p>
+ <p className="text-[9px] text-muted-foreground/70">
+ {formatDistanceToNow(entry.timestamp)}
+ </p>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/components/editor/panels/LeftPanel.tsx b/apps/image/src/components/editor/panels/LeftPanel.tsx
index d45fdc29..9f47de78 100644
--- a/apps/image/src/components/editor/panels/LeftPanel.tsx
+++ b/apps/image/src/components/editor/panels/LeftPanel.tsx
@@ -9,12 +9,56 @@ import {
Search,
Plus,
Folder,
+ Sparkles,
+ Star,
+ Heart,
+ Zap,
+ Cloud,
+ Sun,
+ Moon,
+ Circle,
+ Square,
+ Triangle,
+ Hexagon,
+ ArrowRight,
+ ArrowUp,
+ ArrowDown,
+ ArrowLeft,
+ Check,
+ X,
+ AlertCircle,
+ Info,
+ HelpCircle,
+ MapPin,
+ Home,
+ Settings,
+ User,
+ Users,
+ Mail,
+ Phone,
+ Camera,
+ Music,
+ Video,
+ Mic,
+ Bookmark,
+ Flag,
+ Award,
+ Gift,
+ Coffee,
} from 'lucide-react';
import { useUIStore, Panel } from '../../../stores/ui-store';
import { useProjectStore } from '../../../stores/project-store';
+import {
+ TEMPLATE_CATEGORIES,
+ getTemplatesByCategory,
+ getAllTemplates,
+ searchTemplates,
+ Template,
+} from '../../../services/templates-service';
const panels: { id: Panel; icon: React.ElementType; label: string }[] = [
{ id: 'layers', icon: Layers, label: 'Layers' },
+ { id: 'elements', icon: Sparkles, label: 'Elements' },
{ id: 'assets', icon: Image, label: 'Assets' },
{ id: 'templates', icon: LayoutTemplate, label: 'Templates' },
{ id: 'text', icon: Type, label: 'Text' },
@@ -50,6 +94,7 @@ export function LeftPanel() {
<div className="flex-1 overflow-hidden">
{activePanel === 'layers' && <LayersPanel />}
+ {activePanel === 'elements' && <ElementsPanel />}
{activePanel === 'assets' && <AssetsPanel />}
{activePanel === 'templates' && <TemplatesPanel />}
{activePanel === 'text' && <TextPanel />}
@@ -120,23 +165,127 @@ function AssetsPanel() {
}
function TemplatesPanel() {
+ const { createProject } = useProjectStore();
+ const { setCurrentView } = useUIStore();
+ const [searchQuery, setSearchQuery] = useState('');
+ const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
+
+ const categories = TEMPLATE_CATEGORIES;
+ const filteredTemplates = searchQuery
+ ? searchTemplates(searchQuery)
+ : selectedCategory
+ ? getTemplatesByCategory(selectedCategory)
+ : getAllTemplates();
+
+ const handleApplyTemplate = (template: Template) => {
+ createProject(template.name, template.size, template.background);
+ setCurrentView('editor');
+ };
+
+ const getGradientBackground = (template: Template): string => {
+ if (template.background.type === 'gradient' && template.background.gradient) {
+ const { type, angle, stops } = template.background.gradient;
+ const stopsStr = stops.map((s) => `${s.color} ${Math.round(s.offset * 100)}%`).join(', ');
+ return type === 'linear'
+ ? `linear-gradient(${angle}deg, ${stopsStr})`
+ : `radial-gradient(circle, ${stopsStr})`;
+ }
+ if (template.background.type === 'color') {
+ return template.background.color ?? '#ffffff';
+ }
+ return 'linear-gradient(45deg, #ccc 25%, transparent 25%), linear-gradient(-45deg, #ccc 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #ccc 75%), linear-gradient(-45deg, transparent 75%, #ccc 75%)';
+ };
+
return (
- <div className="p-3">
+ <div className="p-3 h-full overflow-y-auto">
<div className="mb-3">
<div className="relative">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
<input
type="text"
placeholder="Search templates..."
+ value={searchQuery}
+ onChange={(e) => {
+ setSearchQuery(e.target.value);
+ if (e.target.value) setSelectedCategory(null);
+ }}
className="w-full pl-9 pr-3 py-2 text-sm bg-background border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
/>
</div>
</div>
- <div className="text-center py-8">
- <LayoutTemplate size={32} className="mx-auto text-muted-foreground mb-2" />
- <p className="text-xs text-muted-foreground">Templates coming soon</p>
+ <div className="flex flex-wrap gap-1.5 mb-4">
+ <button
+ onClick={() => setSelectedCategory(null)}
+ className={`px-2.5 py-1 text-[10px] font-medium rounded-full transition-colors ${
+ !selectedCategory
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-secondary-foreground hover:bg-accent'
+ }`}
+ >
+ All
+ </button>
+ {categories.map((category) => (
+ <button
+ key={category.id}
+ onClick={() => {
+ setSelectedCategory(category.id);
+ setSearchQuery('');
+ }}
+ className={`px-2.5 py-1 text-[10px] font-medium rounded-full transition-colors ${
+ selectedCategory === category.id
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-secondary-foreground hover:bg-accent'
+ }`}
+ >
+ {category.name}
+ </button>
+ ))}
</div>
+
+ {filteredTemplates.length === 0 ? (
+ <div className="text-center py-8">
+ <LayoutTemplate size={32} className="mx-auto text-muted-foreground mb-2" />
+ <p className="text-xs text-muted-foreground">No templates found</p>
+ </div>
+ ) : (
+ <div className="grid grid-cols-2 gap-2">
+ {filteredTemplates.map((template) => {
+ const aspectRatio = template.size.width / template.size.height;
+ const thumbWidth = 100;
+ const thumbHeight = thumbWidth / aspectRatio;
+
+ return (
+ <button
+ key={template.id}
+ onClick={() => handleApplyTemplate(template)}
+ className="group text-left rounded-lg border border-border bg-background hover:border-primary hover:bg-primary/5 transition-all overflow-hidden"
+ >
+ <div className="p-2 flex items-center justify-center bg-muted/30">
+ <div
+ className="rounded shadow-sm"
+ style={{
+ width: Math.min(thumbWidth, 90),
+ height: Math.min(thumbHeight, 70),
+ maxHeight: 70,
+ background: getGradientBackground(template),
+ backgroundSize: template.background.type === 'transparent' ? '8px 8px' : undefined,
+ }}
+ />
+ </div>
+ <div className="p-2 border-t border-border/50">
+ <p className="text-[11px] font-medium text-foreground truncate group-hover:text-primary transition-colors">
+ {template.name}
+ </p>
+ <p className="text-[9px] text-muted-foreground">
+ {template.size.width} × {template.size.height}
+ </p>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ )}
</div>
);
}
@@ -205,6 +354,141 @@ function ShapesPanel() {
);
}
+const ELEMENT_CATEGORIES = [
+ {
+ name: 'Basic Shapes',
+ items: [
+ { icon: Circle, label: 'Circle', shapeType: 'ellipse' as const },
+ { icon: Square, label: 'Square', shapeType: 'rectangle' as const },
+ { icon: Triangle, label: 'Triangle', shapeType: 'triangle' as const },
+ { icon: Hexagon, label: 'Hexagon', shapeType: 'polygon' as const },
+ { icon: Star, label: 'Star', shapeType: 'star' as const },
+ ],
+ },
+ {
+ name: 'Arrows',
+ items: [
+ { icon: ArrowRight, label: 'Right' },
+ { icon: ArrowLeft, label: 'Left' },
+ { icon: ArrowUp, label: 'Up' },
+ { icon: ArrowDown, label: 'Down' },
+ ],
+ },
+ {
+ name: 'Status',
+ items: [
+ { icon: Check, label: 'Check' },
+ { icon: X, label: 'Cross' },
+ { icon: AlertCircle, label: 'Alert' },
+ { icon: Info, label: 'Info' },
+ { icon: HelpCircle, label: 'Help' },
+ ],
+ },
+ {
+ name: 'Icons',
+ items: [
+ { icon: Heart, label: 'Heart' },
+ { icon: Sparkles, label: 'Sparkle' },
+ { icon: Zap, label: 'Zap' },
+ { icon: Sun, label: 'Sun' },
+ { icon: Moon, label: 'Moon' },
+ { icon: Cloud, label: 'Cloud' },
+ { icon: MapPin, label: 'Pin' },
+ { icon: Home, label: 'Home' },
+ { icon: Settings, label: 'Settings' },
+ { icon: User, label: 'User' },
+ { icon: Users, label: 'Users' },
+ { icon: Mail, label: 'Mail' },
+ { icon: Phone, label: 'Phone' },
+ { icon: Camera, label: 'Camera' },
+ { icon: Music, label: 'Music' },
+ { icon: Video, label: 'Video' },
+ { icon: Mic, label: 'Mic' },
+ { icon: Bookmark, label: 'Bookmark' },
+ { icon: Flag, label: 'Flag' },
+ { icon: Award, label: 'Award' },
+ { icon: Gift, label: 'Gift' },
+ { icon: Coffee, label: 'Coffee' },
+ ],
+ },
+];
+
+function ElementsPanel() {
+ const { addShapeLayer } = useProjectStore();
+ const [searchQuery, setSearchQuery] = useState('');
+
+ const filteredCategories = ELEMENT_CATEGORIES.map((category) => ({
+ ...category,
+ items: category.items.filter((item) =>
+ item.label.toLowerCase().includes(searchQuery.toLowerCase())
+ ),
+ })).filter((category) => category.items.length > 0);
+
+ const handleAddElement = (item: typeof ELEMENT_CATEGORIES[0]['items'][0]) => {
+ if ('shapeType' in item && item.shapeType) {
+ addShapeLayer(item.shapeType);
+ }
+ };
+
+ return (
+ <div className="p-3 h-full overflow-y-auto">
+ <div className="mb-4">
+ <div className="relative">
+ <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
+ <input
+ type="text"
+ placeholder="Search elements..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="w-full pl-9 pr-3 py-2 text-sm bg-background border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
+ />
+ </div>
+ </div>
+
+ <div className="space-y-5">
+ {filteredCategories.map((category) => (
+ <div key={category.name}>
+ <h4 className="text-[10px] font-medium text-muted-foreground uppercase tracking-wide mb-2">
+ {category.name}
+ </h4>
+ <div className="grid grid-cols-4 gap-1.5">
+ {category.items.map((item) => {
+ const Icon = item.icon;
+ const isShape = 'shapeType' in item && item.shapeType;
+ return (
+ <button
+ key={item.label}
+ onClick={() => handleAddElement(item)}
+ className={`aspect-square flex flex-col items-center justify-center rounded-lg border transition-all ${
+ isShape
+ ? 'bg-background border-border hover:border-primary hover:bg-primary/5 cursor-pointer'
+ : 'bg-muted/30 border-transparent cursor-not-allowed opacity-50'
+ }`}
+ disabled={!isShape}
+ title={isShape ? `Add ${item.label}` : `${item.label} (coming soon)`}
+ >
+ <Icon size={20} className="text-muted-foreground mb-0.5" />
+ <span className="text-[9px] text-muted-foreground truncate max-w-full px-1">
+ {item.label}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+
+ {filteredCategories.length === 0 && (
+ <div className="text-center py-8">
+ <Search size={32} className="mx-auto text-muted-foreground mb-2" />
+ <p className="text-xs text-muted-foreground">No elements found</p>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
function UploadsPanel() {
const { addAsset } = useProjectStore();
const [isDragging, setIsDragging] = useState(false);
diff --git a/apps/image/src/components/editor/toolbar/Toolbar.tsx b/apps/image/src/components/editor/toolbar/Toolbar.tsx
index feba8b5a..9a332304 100644
--- a/apps/image/src/components/editor/toolbar/Toolbar.tsx
+++ b/apps/image/src/components/editor/toolbar/Toolbar.tsx
@@ -38,6 +38,7 @@ export function Toolbar() {
togglePanelCollapsed,
toggleInspectorCollapsed,
setCurrentView,
+ openExportDialog,
} = useUIStore();
const { project, setProjectName } = useProjectStore();
@@ -157,7 +158,7 @@ export function Toolbar() {
<div className="w-px h-6 bg-border mx-1" />
<button
- onClick={() => {}}
+ onClick={openExportDialog}
className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg text-sm font-medium hover:bg-primary/90 active:scale-[0.98] transition-all"
>
<Download size={16} />
diff --git a/apps/image/src/components/ui/ColorPicker.tsx b/apps/image/src/components/ui/ColorPicker.tsx
new file mode 100644
index 00000000..ce7f5fcc
--- /dev/null
+++ b/apps/image/src/components/ui/ColorPicker.tsx
@@ -0,0 +1,430 @@
+import { useState, useCallback, useRef, useEffect } from 'react';
+import { Pipette, Check } from 'lucide-react';
+
+interface ColorPickerProps {
+ color: string;
+ onChange: (color: string) => void;
+ showAlpha?: boolean;
+ recentColors?: string[];
+ onRecentColorAdd?: (color: string) => void;
+}
+
+interface HSV {
+ h: number;
+ s: number;
+ v: number;
+}
+
+interface RGB {
+ r: number;
+ g: number;
+ b: number;
+}
+
+function hexToRgb(hex: string): RGB {
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+ return result
+ ? {
+ r: parseInt(result[1], 16),
+ g: parseInt(result[2], 16),
+ b: parseInt(result[3], 16),
+ }
+ : { r: 0, g: 0, b: 0 };
+}
+
+function rgbToHex(r: number, g: number, b: number): string {
+ return '#' + [r, g, b].map((x) => x.toString(16).padStart(2, '0')).join('');
+}
+
+function rgbToHsv(r: number, g: number, b: number): HSV {
+ r /= 255;
+ g /= 255;
+ b /= 255;
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ const d = max - min;
+ let h = 0;
+ const s = max === 0 ? 0 : d / max;
+ const v = max;
+
+ if (max !== min) {
+ switch (max) {
+ case r:
+ h = (g - b) / d + (g < b ? 6 : 0);
+ break;
+ case g:
+ h = (b - r) / d + 2;
+ break;
+ case b:
+ h = (r - g) / d + 4;
+ break;
+ }
+ h /= 6;
+ }
+
+ return { h: h * 360, s: s * 100, v: v * 100 };
+}
+
+function hsvToRgb(h: number, s: number, v: number): RGB {
+ h /= 360;
+ s /= 100;
+ v /= 100;
+ let r = 0, g = 0, b = 0;
+ const i = Math.floor(h * 6);
+ const f = h * 6 - i;
+ const p = v * (1 - s);
+ const q = v * (1 - f * s);
+ const t = v * (1 - (1 - f) * s);
+ switch (i % 6) {
+ case 0: r = v; g = t; b = p; break;
+ case 1: r = q; g = v; b = p; break;
+ case 2: r = p; g = v; b = t; break;
+ case 3: r = p; g = q; b = v; break;
+ case 4: r = t; g = p; b = v; break;
+ case 5: r = v; g = p; b = q; break;
+ }
+ return {
+ r: Math.round(r * 255),
+ g: Math.round(g * 255),
+ b: Math.round(b * 255),
+ };
+}
+
+export function ColorPicker({
+ color,
+ onChange,
+ showAlpha = false,
+ recentColors = [],
+ onRecentColorAdd,
+}: ColorPickerProps) {
+ const [isPickingColor, setIsPickingColor] = useState(false);
+ const svPanelRef = useRef<HTMLDivElement>(null);
+ const hueSliderRef = useRef<HTMLDivElement>(null);
+ const alphaSliderRef = useRef<HTMLDivElement>(null);
+
+ const rgb = hexToRgb(color.slice(0, 7));
+ const hsv = rgbToHsv(rgb.r, rgb.g, rgb.b);
+ const alpha = color.length === 9 ? parseInt(color.slice(7, 9), 16) / 255 : 1;
+
+ const [localHsv, setLocalHsv] = useState<HSV>(hsv);
+ const [localAlpha, setLocalAlpha] = useState(alpha);
+ const [hexInput, setHexInput] = useState(color.slice(0, 7));
+ const [inputMode, setInputMode] = useState<'hex' | 'rgb'>('hex');
+
+ useEffect(() => {
+ const newRgb = hexToRgb(color.slice(0, 7));
+ const newHsv = rgbToHsv(newRgb.r, newRgb.g, newRgb.b);
+ setLocalHsv(newHsv);
+ setHexInput(color.slice(0, 7));
+ if (color.length === 9) {
+ setLocalAlpha(parseInt(color.slice(7, 9), 16) / 255);
+ }
+ }, [color]);
+
+ const updateColor = useCallback(
+ (h: number, s: number, v: number, a: number = localAlpha) => {
+ const newRgb = hsvToRgb(h, s, v);
+ let newColor = rgbToHex(newRgb.r, newRgb.g, newRgb.b);
+ if (showAlpha && a < 1) {
+ newColor += Math.round(a * 255).toString(16).padStart(2, '0');
+ }
+ onChange(newColor);
+ setLocalHsv({ h, s, v });
+ setLocalAlpha(a);
+ },
+ [onChange, showAlpha, localAlpha]
+ );
+
+ const handleSVPanelMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ const panel = svPanelRef.current;
+ if (!panel) return;
+
+ const updateFromEvent = (event: MouseEvent | React.MouseEvent) => {
+ const rect = panel.getBoundingClientRect();
+ const x = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width));
+ const y = Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height));
+ updateColor(localHsv.h, x * 100, (1 - y) * 100);
+ };
+
+ updateFromEvent(e);
+
+ const handleMouseMove = (event: MouseEvent) => updateFromEvent(event);
+ const handleMouseUp = () => {
+ document.removeEventListener('mousemove', handleMouseMove);
+ document.removeEventListener('mouseup', handleMouseUp);
+ };
+
+ document.addEventListener('mousemove', handleMouseMove);
+ document.addEventListener('mouseup', handleMouseUp);
+ },
+ [localHsv.h, updateColor]
+ );
+
+ const handleHueSliderMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ const slider = hueSliderRef.current;
+ if (!slider) return;
+
+ const updateFromEvent = (event: MouseEvent | React.MouseEvent) => {
+ const rect = slider.getBoundingClientRect();
+ const x = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width));
+ updateColor(x * 360, localHsv.s, localHsv.v);
+ };
+
+ updateFromEvent(e);
+
+ const handleMouseMove = (event: MouseEvent) => updateFromEvent(event);
+ const handleMouseUp = () => {
+ document.removeEventListener('mousemove', handleMouseMove);
+ document.removeEventListener('mouseup', handleMouseUp);
+ };
+
+ document.addEventListener('mousemove', handleMouseMove);
+ document.addEventListener('mouseup', handleMouseUp);
+ },
+ [localHsv.s, localHsv.v, updateColor]
+ );
+
+ const handleAlphaSliderMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ const slider = alphaSliderRef.current;
+ if (!slider) return;
+
+ const updateFromEvent = (event: MouseEvent | React.MouseEvent) => {
+ const rect = slider.getBoundingClientRect();
+ const x = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width));
+ updateColor(localHsv.h, localHsv.s, localHsv.v, x);
+ };
+
+ updateFromEvent(e);
+
+ const handleMouseMove = (event: MouseEvent) => updateFromEvent(event);
+ const handleMouseUp = () => {
+ document.removeEventListener('mousemove', handleMouseMove);
+ document.removeEventListener('mouseup', handleMouseUp);
+ };
+
+ document.addEventListener('mousemove', handleMouseMove);
+ document.addEventListener('mouseup', handleMouseUp);
+ },
+ [localHsv.h, localHsv.s, localHsv.v, updateColor]
+ );
+
+ const handleHexInputChange = (value: string) => {
+ setHexInput(value);
+ if (/^#[0-9a-fA-F]{6}$/.test(value)) {
+ const newRgb = hexToRgb(value);
+ const newHsv = rgbToHsv(newRgb.r, newRgb.g, newRgb.b);
+ updateColor(newHsv.h, newHsv.s, newHsv.v);
+ onRecentColorAdd?.(value);
+ }
+ };
+
+ const handleRgbInputChange = (channel: 'r' | 'g' | 'b', value: number) => {
+ const newRgb = { ...rgb, [channel]: Math.max(0, Math.min(255, value)) };
+ const newHsv = rgbToHsv(newRgb.r, newRgb.g, newRgb.b);
+ updateColor(newHsv.h, newHsv.s, newHsv.v);
+ };
+
+ const handleEyedropper = async () => {
+ if (!('EyeDropper' in window)) {
+ return;
+ }
+
+ setIsPickingColor(true);
+ try {
+ const eyeDropper = new (window as unknown as { EyeDropper: new () => { open: () => Promise<{ sRGBHex: string }> } }).EyeDropper();
+ const result = await eyeDropper.open();
+ const newRgb = hexToRgb(result.sRGBHex);
+ const newHsv = rgbToHsv(newRgb.r, newRgb.g, newRgb.b);
+ updateColor(newHsv.h, newHsv.s, newHsv.v);
+ onRecentColorAdd?.(result.sRGBHex);
+ } catch {
+ // User cancelled
+ } finally {
+ setIsPickingColor(false);
+ }
+ };
+
+ const hueColor = hsvToRgb(localHsv.h, 100, 100);
+ const currentRgb = hsvToRgb(localHsv.h, localHsv.s, localHsv.v);
+
+ return (
+ <div className="space-y-3">
+ <div
+ ref={svPanelRef}
+ className="relative w-full h-32 rounded-lg cursor-crosshair"
+ style={{
+ backgroundColor: rgbToHex(hueColor.r, hueColor.g, hueColor.b),
+ }}
+ onMouseDown={handleSVPanelMouseDown}
+ >
+ <div
+ className="absolute inset-0 rounded-lg"
+ style={{
+ background: 'linear-gradient(to right, white, transparent)',
+ }}
+ />
+ <div
+ className="absolute inset-0 rounded-lg"
+ style={{
+ background: 'linear-gradient(to top, black, transparent)',
+ }}
+ />
+ <div
+ className="absolute w-4 h-4 border-2 border-white rounded-full shadow-md -translate-x-1/2 -translate-y-1/2 pointer-events-none"
+ style={{
+ left: `${localHsv.s}%`,
+ top: `${100 - localHsv.v}%`,
+ backgroundColor: rgbToHex(currentRgb.r, currentRgb.g, currentRgb.b),
+ }}
+ />
+ </div>
+
+ <div
+ ref={hueSliderRef}
+ className="relative h-3 rounded-full cursor-pointer"
+ style={{
+ background: 'linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)',
+ }}
+ onMouseDown={handleHueSliderMouseDown}
+ >
+ <div
+ className="absolute w-4 h-4 border-2 border-white rounded-full shadow-md -translate-x-1/2 -translate-y-1/2 pointer-events-none"
+ style={{
+ left: `${(localHsv.h / 360) * 100}%`,
+ top: '50%',
+ backgroundColor: rgbToHex(hueColor.r, hueColor.g, hueColor.b),
+ }}
+ />
+ </div>
+
+ {showAlpha && (
+ <div
+ ref={alphaSliderRef}
+ className="relative h-3 rounded-full cursor-pointer"
+ style={{
+ background: `linear-gradient(to right, transparent, ${rgbToHex(currentRgb.r, currentRgb.g, currentRgb.b)}), url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8'%3E%3Crect fill='%23ccc' width='4' height='4'/%3E%3Crect fill='%23fff' x='4' width='4' height='4'/%3E%3Crect fill='%23fff' y='4' width='4' height='4'/%3E%3Crect fill='%23ccc' x='4' y='4' width='4' height='4'/%3E%3C/svg%3E")`,
+ }}
+ onMouseDown={handleAlphaSliderMouseDown}
+ >
+ <div
+ className="absolute w-4 h-4 border-2 border-white rounded-full shadow-md -translate-x-1/2 -translate-y-1/2 pointer-events-none"
+ style={{
+ left: `${localAlpha * 100}%`,
+ top: '50%',
+ backgroundColor: rgbToHex(currentRgb.r, currentRgb.g, currentRgb.b),
+ }}
+ />
+ </div>
+ )}
+
+ <div className="flex items-center gap-2">
+ <div
+ className="w-8 h-8 rounded-md border border-border shadow-inner"
+ style={{
+ backgroundColor: rgbToHex(currentRgb.r, currentRgb.g, currentRgb.b),
+ opacity: localAlpha,
+ }}
+ />
+
+ {'EyeDropper' in window && (
+ <button
+ onClick={handleEyedropper}
+ disabled={isPickingColor}
+ className={`p-2 rounded-md transition-colors ${
+ isPickingColor
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-muted-foreground hover:text-foreground'
+ }`}
+ >
+ <Pipette size={14} />
+ </button>
+ )}
+
+ <div className="flex-1">
+ <div className="flex gap-1 mb-1">
+ <button
+ onClick={() => setInputMode('hex')}
+ className={`px-2 py-0.5 text-[9px] font-medium rounded transition-colors ${
+ inputMode === 'hex' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'
+ }`}
+ >
+ HEX
+ </button>
+ <button
+ onClick={() => setInputMode('rgb')}
+ className={`px-2 py-0.5 text-[9px] font-medium rounded transition-colors ${
+ inputMode === 'rgb' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'
+ }`}
+ >
+ RGB
+ </button>
+ </div>
+
+ {inputMode === 'hex' ? (
+ <input
+ type="text"
+ value={hexInput}
+ onChange={(e) => handleHexInputChange(e.target.value)}
+ className="w-full px-2 py-1 text-[11px] font-mono bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
+ placeholder="#000000"
+ />
+ ) : (
+ <div className="flex gap-1">
+ <input
+ type="number"
+ value={rgb.r}
+ onChange={(e) => handleRgbInputChange('r', Number(e.target.value))}
+ min={0}
+ max={255}
+ className="w-full px-1 py-1 text-[11px] font-mono bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary text-center"
+ />
+ <input
+ type="number"
+ value={rgb.g}
+ onChange={(e) => handleRgbInputChange('g', Number(e.target.value))}
+ min={0}
+ max={255}
+ className="w-full px-1 py-1 text-[11px] font-mono bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary text-center"
+ />
+ <input
+ type="number"
+ value={rgb.b}
+ onChange={(e) => handleRgbInputChange('b', Number(e.target.value))}
+ min={0}
+ max={255}
+ className="w-full px-1 py-1 text-[11px] font-mono bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary text-center"
+ />
+ </div>
+ )}
+ </div>
+ </div>
+
+ {recentColors.length > 0 && (
+ <div className="space-y-1">
+ <label className="text-[9px] text-muted-foreground uppercase tracking-wide">Recent</label>
+ <div className="flex gap-1 flex-wrap">
+ {recentColors.slice(0, 10).map((c, i) => (
+ <button
+ key={`${c}-${i}`}
+ onClick={() => {
+ const newRgb = hexToRgb(c);
+ const newHsv = rgbToHsv(newRgb.r, newRgb.g, newRgb.b);
+ updateColor(newHsv.h, newHsv.s, newHsv.v);
+ }}
+ className="w-6 h-6 rounded-md border border-border hover:ring-2 hover:ring-primary transition-all relative group"
+ style={{ backgroundColor: c }}
+ >
+ {c === color.slice(0, 7) && (
+ <Check size={12} className="absolute inset-0 m-auto text-white drop-shadow-md" />
+ )}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/image/src/components/ui/Dialog.tsx b/apps/image/src/components/ui/Dialog.tsx
new file mode 100644
index 00000000..047c9005
--- /dev/null
+++ b/apps/image/src/components/ui/Dialog.tsx
@@ -0,0 +1,106 @@
+import { useEffect, useRef, type ReactNode } from 'react';
+import { X } from 'lucide-react';
+
+interface DialogProps {
+ open: boolean;
+ onClose: () => void;
+ children: ReactNode;
+ title?: string;
+ description?: string;
+ maxWidth?: 'sm' | 'md' | 'lg' | 'xl';
+}
+
+const MAX_WIDTH_CLASSES = {
+ sm: 'max-w-sm',
+ md: 'max-w-md',
+ lg: 'max-w-lg',
+ xl: 'max-w-xl',
+};
+
+export function Dialog({ open, onClose, children, title, description, maxWidth = 'md' }: DialogProps) {
+ const dialogRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!open) return;
+
+ const handleEscape = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ onClose();
+ }
+ };
+
+ const handleClickOutside = (e: MouseEvent) => {
+ if (dialogRef.current && !dialogRef.current.contains(e.target as Node)) {
+ onClose();
+ }
+ };
+
+ document.addEventListener('keydown', handleEscape);
+ document.addEventListener('mousedown', handleClickOutside);
+
+ return () => {
+ document.removeEventListener('keydown', handleEscape);
+ document.removeEventListener('mousedown', handleClickOutside);
+ };
+ }, [open, onClose]);
+
+ useEffect(() => {
+ if (open) {
+ document.body.style.overflow = 'hidden';
+ } else {
+ document.body.style.overflow = '';
+ }
+ return () => {
+ document.body.style.overflow = '';
+ };
+ }, [open]);
+
+ if (!open) return null;
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center">
+ <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
+ <div
+ ref={dialogRef}
+ className={`relative w-full ${MAX_WIDTH_CLASSES[maxWidth]} mx-4 bg-background border border-border rounded-xl shadow-2xl animate-in fade-in zoom-in-95 duration-200`}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={title ? 'dialog-title' : undefined}
+ >
+ {(title || description) && (
+ <div className="flex items-start justify-between p-5 border-b border-border">
+ <div>
+ {title && (
+ <h2 id="dialog-title" className="text-lg font-semibold text-foreground">
+ {title}
+ </h2>
+ )}
+ {description && (
+ <p className="mt-1 text-sm text-muted-foreground">{description}</p>
+ )}
+ </div>
+ <button
+ onClick={onClose}
+ className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors"
+ >
+ <X size={18} />
+ </button>
+ </div>
+ )}
+ <div className="p-5">{children}</div>
+ </div>
+ </div>
+ );
+}
+
+interface DialogFooterProps {
+ children: ReactNode;
+}
+
+export function DialogFooter({ children }: DialogFooterProps) {
+ return (
+ <div className="flex items-center justify-end gap-3 pt-4 mt-4 border-t border-border">
+ {children}
+ </div>
+ );
+}
diff --git a/apps/image/src/components/ui/FontPicker.tsx b/apps/image/src/components/ui/FontPicker.tsx
new file mode 100644
index 00000000..8495ebe3
--- /dev/null
+++ b/apps/image/src/components/ui/FontPicker.tsx
@@ -0,0 +1,170 @@
+import { useState, useEffect, useRef, useMemo } from 'react';
+import { Search, Check, ChevronDown, Loader2 } from 'lucide-react';
+import {
+ getPopularFonts,
+ filterFonts,
+ loadGoogleFont,
+ isFontLoaded,
+ FONT_CATEGORIES,
+ type GoogleFont,
+} from '../../services/fonts-service';
+
+interface FontPickerProps {
+ value: string;
+ onChange: (fontFamily: string) => void;
+}
+
+export function FontPicker({ value, onChange }: FontPickerProps) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [search, setSearch] = useState('');
+ const [category, setCategory] = useState('all');
+ const [loadingFont, setLoadingFont] = useState<string | null>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const listRef = useRef<HTMLDivElement>(null);
+
+ const fonts = useMemo(() => getPopularFonts(), []);
+ const filteredFonts = useMemo(() => filterFonts(fonts, category, search), [fonts, category, search]);
+
+ useEffect(() => {
+ loadGoogleFont(value);
+ }, [value]);
+
+ useEffect(() => {
+ if (!isOpen) return;
+
+ const handleClickOutside = (e: MouseEvent) => {
+ if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
+ setIsOpen(false);
+ }
+ };
+
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }, [isOpen]);
+
+ useEffect(() => {
+ if (isOpen && listRef.current) {
+ filteredFonts.slice(0, 10).forEach((font) => {
+ if (!isFontLoaded(font.family)) {
+ loadGoogleFont(font.family, ['400']);
+ }
+ });
+ }
+ }, [isOpen, filteredFonts]);
+
+ const handleSelect = async (font: GoogleFont) => {
+ setLoadingFont(font.family);
+ try {
+ await loadGoogleFont(font.family, font.variants.slice(0, 4));
+ onChange(font.family);
+ setIsOpen(false);
+ setSearch('');
+ } finally {
+ setLoadingFont(null);
+ }
+ };
+
+ const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
+ const container = e.currentTarget;
+ const scrollBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
+
+ if (scrollBottom < 200) {
+ const startIndex = Math.floor(container.scrollTop / 40);
+ const endIndex = Math.min(startIndex + 15, filteredFonts.length);
+ filteredFonts.slice(startIndex, endIndex).forEach((font) => {
+ if (!isFontLoaded(font.family)) {
+ loadGoogleFont(font.family, ['400']);
+ }
+ });
+ }
+ };
+
+ return (
+ <div ref={containerRef} className="relative">
+ <button
+ type="button"
+ onClick={() => setIsOpen(!isOpen)}
+ className="w-full flex items-center justify-between px-2 py-1.5 text-xs bg-background border border-input rounded-md hover:border-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary transition-colors"
+ >
+ <span style={{ fontFamily: value }} className="truncate">
+ {value}
+ </span>
+ <ChevronDown size={12} className={`text-muted-foreground transition-transform ${isOpen ? 'rotate-180' : ''}`} />
+ </button>
+
+ {isOpen && (
+ <div className="absolute z-50 top-full left-0 mt-1 w-64 bg-popover border border-border rounded-lg shadow-lg overflow-hidden animate-in fade-in slide-in-from-top-2 duration-150">
+ <div className="p-2 border-b border-border">
+ <div className="relative">
+ <Search size={14} className="absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground" />
+ <input
+ type="text"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search fonts..."
+ className="w-full pl-7 pr-2 py-1.5 text-xs bg-background border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
+ autoFocus
+ />
+ </div>
+ </div>
+
+ <div className="flex flex-wrap gap-1 p-2 border-b border-border">
+ {FONT_CATEGORIES.map((cat) => (
+ <button
+ key={cat.id}
+ onClick={() => setCategory(cat.id)}
+ className={`px-2 py-0.5 text-[10px] rounded-full transition-colors ${
+ category === cat.id
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-secondary-foreground hover:bg-accent'
+ }`}
+ >
+ {cat.name}
+ </button>
+ ))}
+ </div>
+
+ <div
+ ref={listRef}
+ onScroll={handleScroll}
+ className="max-h-64 overflow-y-auto"
+ >
+ {filteredFonts.length === 0 ? (
+ <div className="p-4 text-center text-xs text-muted-foreground">
+ No fonts found
+ </div>
+ ) : (
+ filteredFonts.map((font) => (
+ <button
+ key={font.family}
+ onClick={() => handleSelect(font)}
+ disabled={loadingFont === font.family}
+ className={`w-full flex items-center justify-between px-3 py-2 text-left hover:bg-accent transition-colors ${
+ value === font.family ? 'bg-accent/50' : ''
+ }`}
+ >
+ <div className="flex-1 min-w-0">
+ <span
+ style={{ fontFamily: font.family }}
+ className="block text-sm truncate"
+ >
+ {font.family}
+ </span>
+ <span className="text-[10px] text-muted-foreground capitalize">
+ {font.category}
+ </span>
+ </div>
+ {loadingFont === font.family ? (
+ <Loader2 size={14} className="animate-spin text-muted-foreground" />
+ ) : value === font.family ? (
+ <Check size={14} className="text-primary" />
+ ) : null}
+ </button>
+ ))
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/image/src/components/ui/GradientPicker.tsx b/apps/image/src/components/ui/GradientPicker.tsx
new file mode 100644
index 00000000..6af9611d
--- /dev/null
+++ b/apps/image/src/components/ui/GradientPicker.tsx
@@ -0,0 +1,218 @@
+import { useState, useCallback, useMemo } from 'react';
+import { Plus, Trash2, RotateCw } from 'lucide-react';
+import { Slider } from '@openreel/ui';
+import type { Gradient } from '../../types/project';
+
+interface GradientPickerProps {
+ value: Gradient | null;
+ onChange: (gradient: Gradient) => void;
+}
+
+const PRESET_GRADIENTS: Gradient[] = [
+ { type: 'linear', angle: 90, stops: [{ offset: 0, color: '#3b82f6' }, { offset: 1, color: '#8b5cf6' }] },
+ { type: 'linear', angle: 90, stops: [{ offset: 0, color: '#ec4899' }, { offset: 1, color: '#f97316' }] },
+ { type: 'linear', angle: 90, stops: [{ offset: 0, color: '#10b981' }, { offset: 1, color: '#06b6d4' }] },
+ { type: 'linear', angle: 180, stops: [{ offset: 0, color: '#fbbf24' }, { offset: 1, color: '#ef4444' }] },
+ { type: 'linear', angle: 135, stops: [{ offset: 0, color: '#1e293b' }, { offset: 1, color: '#475569' }] },
+ { type: 'radial', angle: 0, stops: [{ offset: 0, color: '#ffffff' }, { offset: 1, color: '#3b82f6' }] },
+];
+
+const DEFAULT_GRADIENT: Gradient = {
+ type: 'linear',
+ angle: 90,
+ stops: [
+ { offset: 0, color: '#3b82f6' },
+ { offset: 1, color: '#8b5cf6' },
+ ],
+};
+
+export function GradientPicker({ value, onChange }: GradientPickerProps) {
+ const gradient = value ?? DEFAULT_GRADIENT;
+ const [selectedStopIndex, setSelectedStopIndex] = useState(0);
+
+ const gradientString = useMemo(() => {
+ const stopsStr = gradient.stops
+ .map((s) => `${s.color} ${Math.round(s.offset * 100)}%`)
+ .join(', ');
+
+ return gradient.type === 'linear'
+ ? `linear-gradient(${gradient.angle}deg, ${stopsStr})`
+ : `radial-gradient(circle, ${stopsStr})`;
+ }, [gradient]);
+
+ const handleTypeChange = useCallback((type: 'linear' | 'radial') => {
+ onChange({ ...gradient, type });
+ }, [gradient, onChange]);
+
+ const handleAngleChange = useCallback((angle: number) => {
+ onChange({ ...gradient, angle });
+ }, [gradient, onChange]);
+
+ const handleStopColorChange = useCallback((index: number, color: string) => {
+ const newStops = [...gradient.stops];
+ newStops[index] = { ...newStops[index], color };
+ onChange({ ...gradient, stops: newStops });
+ }, [gradient, onChange]);
+
+ const handleStopOffsetChange = useCallback((index: number, offset: number) => {
+ const newStops = [...gradient.stops];
+ newStops[index] = { ...newStops[index], offset };
+ newStops.sort((a, b) => a.offset - b.offset);
+ const newIndex = newStops.findIndex((s) => s === newStops[index]);
+ setSelectedStopIndex(newIndex !== -1 ? newIndex : index);
+ onChange({ ...gradient, stops: newStops });
+ }, [gradient, onChange]);
+
+ const addStop = useCallback(() => {
+ if (gradient.stops.length >= 5) return;
+
+ const midOffset = gradient.stops.length > 1
+ ? (gradient.stops[0].offset + gradient.stops[gradient.stops.length - 1].offset) / 2
+ : 0.5;
+
+ const newStops = [...gradient.stops, { offset: midOffset, color: '#ffffff' }];
+ newStops.sort((a, b) => a.offset - b.offset);
+ onChange({ ...gradient, stops: newStops });
+ setSelectedStopIndex(newStops.length - 1);
+ }, [gradient, onChange]);
+
+ const removeStop = useCallback((index: number) => {
+ if (gradient.stops.length <= 2) return;
+
+ const newStops = gradient.stops.filter((_, i) => i !== index);
+ onChange({ ...gradient, stops: newStops });
+ setSelectedStopIndex(Math.min(selectedStopIndex, newStops.length - 1));
+ }, [gradient, onChange, selectedStopIndex]);
+
+ const selectPreset = useCallback((preset: Gradient) => {
+ onChange(preset);
+ setSelectedStopIndex(0);
+ }, [onChange]);
+
+ return (
+ <div className="space-y-3">
+ <div
+ className="h-10 rounded-lg border border-input cursor-pointer"
+ style={{ background: gradientString }}
+ />
+
+ <div className="flex gap-1">
+ {PRESET_GRADIENTS.map((preset, index) => {
+ const presetStr = preset.type === 'linear'
+ ? `linear-gradient(${preset.angle}deg, ${preset.stops.map((s) => `${s.color} ${Math.round(s.offset * 100)}%`).join(', ')})`
+ : `radial-gradient(circle, ${preset.stops.map((s) => `${s.color} ${Math.round(s.offset * 100)}%`).join(', ')})`;
+
+ return (
+ <button
+ key={index}
+ onClick={() => selectPreset(preset)}
+ className="w-8 h-8 rounded border border-input hover:border-primary transition-colors"
+ style={{ background: presetStr }}
+ />
+ );
+ })}
+ </div>
+
+ <div className="grid grid-cols-2 gap-2">
+ <button
+ onClick={() => handleTypeChange('linear')}
+ className={`px-3 py-1.5 text-xs rounded-md transition-colors ${
+ gradient.type === 'linear'
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-secondary-foreground hover:bg-accent'
+ }`}
+ >
+ Linear
+ </button>
+ <button
+ onClick={() => handleTypeChange('radial')}
+ className={`px-3 py-1.5 text-xs rounded-md transition-colors ${
+ gradient.type === 'radial'
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-secondary text-secondary-foreground hover:bg-accent'
+ }`}
+ >
+ Radial
+ </button>
+ </div>
+
+ {gradient.type === 'linear' && (
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <label className="text-[10px] text-muted-foreground">Angle</label>
+ <div className="flex items-center gap-1">
+ <span className="text-[10px] text-muted-foreground">{gradient.angle}°</span>
+ <button
+ onClick={() => handleAngleChange((gradient.angle + 45) % 360)}
+ className="p-0.5 rounded hover:bg-accent transition-colors"
+ >
+ <RotateCw size={12} className="text-muted-foreground" />
+ </button>
+ </div>
+ </div>
+ <Slider
+ value={[gradient.angle]}
+ onValueChange={([angle]) => handleAngleChange(angle)}
+ min={0}
+ max={360}
+ step={1}
+ />
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] text-muted-foreground">Color Stops</label>
+ <button
+ onClick={addStop}
+ disabled={gradient.stops.length >= 5}
+ className="p-1 rounded hover:bg-accent transition-colors disabled:opacity-50"
+ >
+ <Plus size={12} className="text-muted-foreground" />
+ </button>
+ </div>
+
+ <div className="space-y-2">
+ {gradient.stops.map((stop, index) => (
+ <div
+ key={index}
+ className={`flex items-center gap-2 p-2 rounded-lg transition-colors ${
+ selectedStopIndex === index ? 'bg-secondary' : 'hover:bg-secondary/50'
+ }`}
+ onClick={() => setSelectedStopIndex(index)}
+ >
+ <input
+ type="color"
+ value={stop.color}
+ onChange={(e) => handleStopColorChange(index, e.target.value)}
+ className="w-6 h-6 rounded border border-input cursor-pointer"
+ />
+ <div className="flex-1">
+ <Slider
+ value={[stop.offset * 100]}
+ onValueChange={([offset]) => handleStopOffsetChange(index, offset / 100)}
+ min={0}
+ max={100}
+ step={1}
+ />
+ </div>
+ <span className="text-[10px] text-muted-foreground w-8 text-right">
+ {Math.round(stop.offset * 100)}%
+ </span>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ removeStop(index);
+ }}
+ disabled={gradient.stops.length <= 2}
+ className="p-1 rounded hover:bg-destructive/20 transition-colors disabled:opacity-50"
+ >
+ <Trash2 size={12} className="text-muted-foreground" />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/image/src/services/background-removal-service.ts b/apps/image/src/services/background-removal-service.ts
new file mode 100644
index 00000000..822191c0
--- /dev/null
+++ b/apps/image/src/services/background-removal-service.ts
@@ -0,0 +1,289 @@
+export type BackgroundMode = 'transparent' | 'color' | 'blur';
+
+export interface BackgroundRemovalResult {
+ imageData: ImageData;
+ mask: ImageData;
+}
+
+export interface BackgroundRemovalOptions {
+ threshold: number;
+ edgeBlur: number;
+ mode: BackgroundMode;
+ backgroundColor?: string;
+ blurAmount?: number;
+}
+
+export const DEFAULT_OPTIONS: BackgroundRemovalOptions = {
+ threshold: 0.5,
+ edgeBlur: 2,
+ mode: 'transparent',
+ backgroundColor: '#ffffff',
+ blurAmount: 10,
+};
+
+export class BackgroundRemovalService {
+ private canvas: HTMLCanvasElement;
+ private ctx: CanvasRenderingContext2D;
+ private workCanvas: HTMLCanvasElement;
+ private workCtx: CanvasRenderingContext2D;
+
+ constructor() {
+ this.canvas = document.createElement('canvas');
+ this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })!;
+ this.workCanvas = document.createElement('canvas');
+ this.workCtx = this.workCanvas.getContext('2d', { willReadFrequently: true })!;
+ }
+
+ async removeBackground(
+ imageSource: HTMLImageElement | ImageBitmap | string,
+ options: Partial<BackgroundRemovalOptions> = {},
+ onProgress?: (progress: number) => void
+ ): Promise<string> {
+ const opts = { ...DEFAULT_OPTIONS, ...options };
+
+ onProgress?.(10);
+
+ let img: HTMLImageElement | ImageBitmap;
+ if (typeof imageSource === 'string') {
+ img = await this.loadImage(imageSource);
+ } else {
+ img = imageSource;
+ }
+
+ const width = img.width;
+ const height = img.height;
+
+ this.canvas.width = width;
+ this.canvas.height = height;
+ this.workCanvas.width = width;
+ this.workCanvas.height = height;
+
+ this.ctx.drawImage(img, 0, 0);
+ const imageData = this.ctx.getImageData(0, 0, width, height);
+
+ onProgress?.(30);
+
+ const mask = this.generateMask(imageData, opts.threshold);
+
+ onProgress?.(50);
+
+ if (opts.edgeBlur > 0) {
+ this.applyGaussianBlur(mask, opts.edgeBlur);
+ }
+
+ onProgress?.(70);
+
+ const result = this.applyMask(imageData, mask, opts);
+
+ onProgress?.(90);
+
+ this.ctx.putImageData(result, 0, 0);
+
+ onProgress?.(100);
+
+ return this.canvas.toDataURL('image/png');
+ }
+
+ private async loadImage(src: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.crossOrigin = 'anonymous';
+ img.onload = () => resolve(img);
+ img.onerror = reject;
+ img.src = src;
+ });
+ }
+
+ private generateMask(imageData: ImageData, threshold: number): ImageData {
+ const { data, width, height } = imageData;
+ const mask = new ImageData(width, height);
+
+ const edgeColors = this.detectEdgeColors(data, width, height);
+
+ for (let i = 0; i < data.length; i += 4) {
+ const r = data[i];
+ const g = data[i + 1];
+ const b = data[i + 2];
+
+ let isForeground = true;
+
+ for (const edgeColor of edgeColors) {
+ const distance = this.colorDistance(r, g, b, edgeColor.r, edgeColor.g, edgeColor.b);
+ if (distance < threshold * 255 * 3) {
+ isForeground = false;
+ break;
+ }
+ }
+
+ const alpha = isForeground ? 255 : 0;
+ mask.data[i] = alpha;
+ mask.data[i + 1] = alpha;
+ mask.data[i + 2] = alpha;
+ mask.data[i + 3] = 255;
+ }
+
+ return this.refineMask(mask, 2);
+ }
+
+ private detectEdgeColors(data: Uint8ClampedArray, width: number, height: number): { r: number; g: number; b: number }[] {
+ const samples: { r: number; g: number; b: number }[] = [];
+ const sampleSize = 10;
+
+ for (let x = 0; x < width; x += Math.floor(width / sampleSize)) {
+ const topIdx = x * 4;
+ samples.push({ r: data[topIdx], g: data[topIdx + 1], b: data[topIdx + 2] });
+
+ const bottomIdx = ((height - 1) * width + x) * 4;
+ samples.push({ r: data[bottomIdx], g: data[bottomIdx + 1], b: data[bottomIdx + 2] });
+ }
+
+ for (let y = 0; y < height; y += Math.floor(height / sampleSize)) {
+ const leftIdx = y * width * 4;
+ samples.push({ r: data[leftIdx], g: data[leftIdx + 1], b: data[leftIdx + 2] });
+
+ const rightIdx = (y * width + width - 1) * 4;
+ samples.push({ r: data[rightIdx], g: data[rightIdx + 1], b: data[rightIdx + 2] });
+ }
+
+ const colorCounts = new Map<string, { count: number; r: number; g: number; b: number }>();
+ for (const sample of samples) {
+ const quantized = {
+ r: Math.round(sample.r / 16) * 16,
+ g: Math.round(sample.g / 16) * 16,
+ b: Math.round(sample.b / 16) * 16,
+ };
+ const key = `${quantized.r},${quantized.g},${quantized.b}`;
+ const existing = colorCounts.get(key);
+ if (existing) {
+ existing.count++;
+ } else {
+ colorCounts.set(key, { count: 1, ...quantized });
+ }
+ }
+
+ return Array.from(colorCounts.values())
+ .sort((a, b) => b.count - a.count)
+ .slice(0, 3)
+ .map(({ r, g, b }) => ({ r, g, b }));
+ }
+
+ private colorDistance(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number): number {
+ return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
+ }
+
+ private refineMask(mask: ImageData, iterations: number): ImageData {
+ const { width, height } = mask;
+ const result = new ImageData(new Uint8ClampedArray(mask.data), width, height);
+
+ for (let iter = 0; iter < iterations; iter++) {
+ const temp = new Uint8ClampedArray(result.data);
+
+ for (let y = 1; y < height - 1; y++) {
+ for (let x = 1; x < width - 1; x++) {
+ const idx = (y * width + x) * 4;
+
+ let sum = 0;
+ let count = 0;
+
+ for (let dy = -1; dy <= 1; dy++) {
+ for (let dx = -1; dx <= 1; dx++) {
+ const nIdx = ((y + dy) * width + (x + dx)) * 4;
+ sum += temp[nIdx];
+ count++;
+ }
+ }
+
+ const avg = sum / count;
+ result.data[idx] = avg > 127 ? 255 : 0;
+ result.data[idx + 1] = result.data[idx];
+ result.data[idx + 2] = result.data[idx];
+ }
+ }
+ }
+
+ return result;
+ }
+
+ private applyGaussianBlur(mask: ImageData, radius: number): void {
+ const { data, width, height } = mask;
+ const temp = new Uint8ClampedArray(data);
+
+ for (let y = radius; y < height - radius; y++) {
+ for (let x = radius; x < width - radius; x++) {
+ const idx = (y * width + x) * 4;
+
+ let sum = 0;
+ let weightSum = 0;
+
+ for (let dy = -radius; dy <= radius; dy++) {
+ for (let dx = -radius; dx <= radius; dx++) {
+ const nIdx = ((y + dy) * width + (x + dx)) * 4;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const weight = Math.exp(-(distance * distance) / (2 * radius * radius));
+ sum += temp[nIdx] * weight;
+ weightSum += weight;
+ }
+ }
+
+ data[idx] = sum / weightSum;
+ data[idx + 1] = data[idx];
+ data[idx + 2] = data[idx];
+ }
+ }
+ }
+
+ private applyMask(imageData: ImageData, mask: ImageData, options: BackgroundRemovalOptions): ImageData {
+ const { width, height } = imageData;
+ const result = new ImageData(new Uint8ClampedArray(imageData.data), width, height);
+
+ if (options.mode === 'transparent') {
+ for (let i = 0; i < mask.data.length; i += 4) {
+ result.data[i + 3] = mask.data[i];
+ }
+ } else if (options.mode === 'color' && options.backgroundColor) {
+ const bgColor = this.hexToRgb(options.backgroundColor);
+ for (let i = 0; i < mask.data.length; i += 4) {
+ const alpha = mask.data[i] / 255;
+ result.data[i] = result.data[i] * alpha + bgColor.r * (1 - alpha);
+ result.data[i + 1] = result.data[i + 1] * alpha + bgColor.g * (1 - alpha);
+ result.data[i + 2] = result.data[i + 2] * alpha + bgColor.b * (1 - alpha);
+ result.data[i + 3] = 255;
+ }
+ } else if (options.mode === 'blur' && options.blurAmount) {
+ this.workCtx.filter = `blur(${options.blurAmount}px)`;
+ this.workCtx.drawImage(this.canvas, 0, 0);
+ this.workCtx.filter = 'none';
+ const blurredData = this.workCtx.getImageData(0, 0, width, height);
+
+ for (let i = 0; i < mask.data.length; i += 4) {
+ const alpha = mask.data[i] / 255;
+ result.data[i] = result.data[i] * alpha + blurredData.data[i] * (1 - alpha);
+ result.data[i + 1] = result.data[i + 1] * alpha + blurredData.data[i + 1] * (1 - alpha);
+ result.data[i + 2] = result.data[i + 2] * alpha + blurredData.data[i + 2] * (1 - alpha);
+ result.data[i + 3] = 255;
+ }
+ }
+
+ return result;
+ }
+
+ private hexToRgb(hex: string): { r: number; g: number; b: number } {
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+ return result
+ ? {
+ r: parseInt(result[1], 16),
+ g: parseInt(result[2], 16),
+ b: parseInt(result[3], 16),
+ }
+ : { r: 255, g: 255, b: 255 };
+ }
+}
+
+let serviceInstance: BackgroundRemovalService | null = null;
+
+export function getBackgroundRemovalService(): BackgroundRemovalService {
+ if (!serviceInstance) {
+ serviceInstance = new BackgroundRemovalService();
+ }
+ return serviceInstance;
+}
diff --git a/apps/image/src/services/fonts-service.ts b/apps/image/src/services/fonts-service.ts
new file mode 100644
index 00000000..f06caf97
--- /dev/null
+++ b/apps/image/src/services/fonts-service.ts
@@ -0,0 +1,129 @@
+export interface GoogleFont {
+ family: string;
+ category: 'sans-serif' | 'serif' | 'display' | 'handwriting' | 'monospace';
+ variants: string[];
+ subsets: string[];
+}
+
+export interface FontCategory {
+ id: string;
+ name: string;
+}
+
+export const FONT_CATEGORIES: FontCategory[] = [
+ { id: 'all', name: 'All' },
+ { id: 'sans-serif', name: 'Sans Serif' },
+ { id: 'serif', name: 'Serif' },
+ { id: 'display', name: 'Display' },
+ { id: 'handwriting', name: 'Handwriting' },
+ { id: 'monospace', name: 'Monospace' },
+];
+
+const POPULAR_FONTS: GoogleFont[] = [
+ { family: 'Inter', category: 'sans-serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Roboto', category: 'sans-serif', variants: ['400', '500', '700'], subsets: ['latin'] },
+ { family: 'Open Sans', category: 'sans-serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Montserrat', category: 'sans-serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Poppins', category: 'sans-serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Lato', category: 'sans-serif', variants: ['400', '700'], subsets: ['latin'] },
+ { family: 'Oswald', category: 'sans-serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Source Sans 3', category: 'sans-serif', variants: ['400', '600', '700'], subsets: ['latin'] },
+ { family: 'Raleway', category: 'sans-serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Nunito', category: 'sans-serif', variants: ['400', '600', '700'], subsets: ['latin'] },
+ { family: 'Work Sans', category: 'sans-serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'DM Sans', category: 'sans-serif', variants: ['400', '500', '700'], subsets: ['latin'] },
+ { family: 'Playfair Display', category: 'serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Merriweather', category: 'serif', variants: ['400', '700'], subsets: ['latin'] },
+ { family: 'Lora', category: 'serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'PT Serif', category: 'serif', variants: ['400', '700'], subsets: ['latin'] },
+ { family: 'Libre Baskerville', category: 'serif', variants: ['400', '700'], subsets: ['latin'] },
+ { family: 'Cormorant Garamond', category: 'serif', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Crimson Text', category: 'serif', variants: ['400', '600', '700'], subsets: ['latin'] },
+ { family: 'Bebas Neue', category: 'display', variants: ['400'], subsets: ['latin'] },
+ { family: 'Anton', category: 'display', variants: ['400'], subsets: ['latin'] },
+ { family: 'Archivo Black', category: 'display', variants: ['400'], subsets: ['latin'] },
+ { family: 'Righteous', category: 'display', variants: ['400'], subsets: ['latin'] },
+ { family: 'Alfa Slab One', category: 'display', variants: ['400'], subsets: ['latin'] },
+ { family: 'Monoton', category: 'display', variants: ['400'], subsets: ['latin'] },
+ { family: 'Bungee', category: 'display', variants: ['400'], subsets: ['latin'] },
+ { family: 'Pacifico', category: 'handwriting', variants: ['400'], subsets: ['latin'] },
+ { family: 'Dancing Script', category: 'handwriting', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Great Vibes', category: 'handwriting', variants: ['400'], subsets: ['latin'] },
+ { family: 'Lobster', category: 'handwriting', variants: ['400'], subsets: ['latin'] },
+ { family: 'Satisfy', category: 'handwriting', variants: ['400'], subsets: ['latin'] },
+ { family: 'Sacramento', category: 'handwriting', variants: ['400'], subsets: ['latin'] },
+ { family: 'Caveat', category: 'handwriting', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Kalam', category: 'handwriting', variants: ['400', '700'], subsets: ['latin'] },
+ { family: 'Indie Flower', category: 'handwriting', variants: ['400'], subsets: ['latin'] },
+ { family: 'Fira Code', category: 'monospace', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'JetBrains Mono', category: 'monospace', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Source Code Pro', category: 'monospace', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+ { family: 'Space Mono', category: 'monospace', variants: ['400', '700'], subsets: ['latin'] },
+ { family: 'Roboto Mono', category: 'monospace', variants: ['400', '500', '600', '700'], subsets: ['latin'] },
+];
+
+const loadedFonts = new Set<string>();
+
+export function getPopularFonts(): GoogleFont[] {
+ return POPULAR_FONTS;
+}
+
+export function filterFonts(fonts: GoogleFont[], category: string, search: string): GoogleFont[] {
+ let filtered = fonts;
+
+ if (category !== 'all') {
+ filtered = filtered.filter((f) => f.category === category);
+ }
+
+ if (search) {
+ const searchLower = search.toLowerCase();
+ filtered = filtered.filter((f) => f.family.toLowerCase().includes(searchLower));
+ }
+
+ return filtered;
+}
+
+export function loadGoogleFont(fontFamily: string, weights: string[] = ['400', '700']): Promise<void> {
+ const key = `${fontFamily}:${weights.join(',')}`;
+ if (loadedFonts.has(key)) {
+ return Promise.resolve();
+ }
+
+ return new Promise((resolve, reject) => {
+ const encodedFamily = encodeURIComponent(fontFamily);
+ const weightParam = weights.join(';');
+ const url = `https://fonts.googleapis.com/css2?family=${encodedFamily}:wght@${weightParam}&display=swap`;
+
+ const existingLink = document.querySelector(`link[href="${url}"]`);
+ if (existingLink) {
+ loadedFonts.add(key);
+ resolve();
+ return;
+ }
+
+ const link = document.createElement('link');
+ link.rel = 'stylesheet';
+ link.href = url;
+
+ link.onload = () => {
+ loadedFonts.add(key);
+ resolve();
+ };
+
+ link.onerror = () => {
+ reject(new Error(`Failed to load font: ${fontFamily}`));
+ };
+
+ document.head.appendChild(link);
+ });
+}
+
+export function preloadFonts(fonts: GoogleFont[]): void {
+ fonts.slice(0, 20).forEach((font) => {
+ loadGoogleFont(font.family, font.variants.slice(0, 2));
+ });
+}
+
+export function isFontLoaded(fontFamily: string): boolean {
+ return loadedFonts.has(`${fontFamily}:400,700`) || loadedFonts.has(`${fontFamily}:400`);
+}
diff --git a/apps/image/src/services/templates-service.ts b/apps/image/src/services/templates-service.ts
new file mode 100644
index 00000000..f475e988
--- /dev/null
+++ b/apps/image/src/services/templates-service.ts
@@ -0,0 +1,336 @@
+import { CanvasSize, CanvasBackground, Layer, TextLayer, ShapeLayer, DEFAULT_TRANSFORM, DEFAULT_BLEND_MODE, DEFAULT_SHADOW, DEFAULT_STROKE, DEFAULT_GLOW, DEFAULT_FILTER, DEFAULT_TEXT_STYLE, DEFAULT_SHAPE_STYLE } from '../types/project';
+
+export interface TemplateCategory {
+ id: string;
+ name: string;
+ templates: Template[];
+}
+
+export interface Template {
+ id: string;
+ name: string;
+ thumbnail: string;
+ category: string;
+ size: CanvasSize;
+ background: CanvasBackground;
+ layers: Partial<Layer>[];
+}
+
+const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
+
+const createTextLayer = (
+ content: string,
+ x: number,
+ y: number,
+ width: number,
+ fontSize: number,
+ fontWeight: number,
+ color: string,
+ textAlign: 'left' | 'center' | 'right' = 'center'
+): Partial<TextLayer> => ({
+ id: generateId(),
+ name: content.slice(0, 20),
+ type: 'text',
+ visible: true,
+ locked: false,
+ transform: { ...DEFAULT_TRANSFORM, x, y, width, height: fontSize * 1.5 },
+ blendMode: DEFAULT_BLEND_MODE,
+ shadow: DEFAULT_SHADOW,
+ stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
+ filters: DEFAULT_FILTER,
+ parentId: null,
+ content,
+ style: { ...DEFAULT_TEXT_STYLE, fontSize, fontWeight, color, textAlign },
+ autoSize: true,
+});
+
+const createShapeLayer = (
+ shapeType: ShapeLayer['shapeType'],
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ fill: string | null,
+ cornerRadius = 0
+): Partial<ShapeLayer> => ({
+ id: generateId(),
+ name: shapeType.charAt(0).toUpperCase() + shapeType.slice(1),
+ type: 'shape',
+ visible: true,
+ locked: false,
+ transform: { ...DEFAULT_TRANSFORM, x, y, width, height },
+ blendMode: DEFAULT_BLEND_MODE,
+ shadow: DEFAULT_SHADOW,
+ stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
+ filters: DEFAULT_FILTER,
+ parentId: null,
+ shapeType,
+ shapeStyle: { ...DEFAULT_SHAPE_STYLE, fill, cornerRadius },
+});
+
+export const TEMPLATE_CATEGORIES: TemplateCategory[] = [
+ {
+ id: 'social-media',
+ name: 'Social Media',
+ templates: [
+ {
+ id: 'instagram-post-minimal',
+ name: 'Minimal Quote',
+ thumbnail: '',
+ category: 'social-media',
+ size: { width: 1080, height: 1080 },
+ background: { type: 'color', color: '#1a1a2e' },
+ layers: [
+ createTextLayer('"Your inspiring quote goes here"', 90, 400, 900, 42, 500, '#ffffff', 'center'),
+ createTextLayer('— Author Name', 90, 520, 900, 24, 400, '#888888', 'center'),
+ createShapeLayer('rectangle', 440, 350, 200, 4, '#4a90d9'),
+ ],
+ },
+ {
+ id: 'instagram-post-gradient',
+ name: 'Gradient Announcement',
+ thumbnail: '',
+ category: 'social-media',
+ size: { width: 1080, height: 1080 },
+ background: {
+ type: 'gradient',
+ gradient: {
+ type: 'linear',
+ angle: 135,
+ stops: [
+ { offset: 0, color: '#667eea' },
+ { offset: 1, color: '#764ba2' },
+ ],
+ },
+ },
+ layers: [
+ createTextLayer('NEW', 90, 300, 900, 24, 700, '#ffffff', 'center'),
+ createTextLayer('Big Announcement', 90, 380, 900, 56, 700, '#ffffff', 'center'),
+ createTextLayer('Add your description here. Keep it short and engaging.', 140, 480, 800, 20, 400, 'rgba(255,255,255,0.8)', 'center'),
+ createShapeLayer('rectangle', 390, 600, 300, 56, '#ffffff', 28),
+ createTextLayer('Learn More', 390, 612, 300, 18, 600, '#667eea', 'center'),
+ ],
+ },
+ {
+ id: 'instagram-story-promo',
+ name: 'Story Promo',
+ thumbnail: '',
+ category: 'social-media',
+ size: { width: 1080, height: 1920 },
+ background: { type: 'color', color: '#0f0f0f' },
+ layers: [
+ createTextLayer('SALE', 90, 700, 900, 120, 900, '#ff3366', 'center'),
+ createTextLayer('UP TO 50% OFF', 90, 850, 900, 36, 600, '#ffffff', 'center'),
+ createTextLayer('Limited time only', 90, 920, 900, 20, 400, '#888888', 'center'),
+ createShapeLayer('rectangle', 340, 1100, 400, 64, '#ff3366', 32),
+ createTextLayer('Shop Now', 340, 1116, 400, 20, 600, '#ffffff', 'center'),
+ ],
+ },
+ {
+ id: 'youtube-thumbnail',
+ name: 'YouTube Thumbnail',
+ thumbnail: '',
+ category: 'social-media',
+ size: { width: 1280, height: 720 },
+ background: { type: 'color', color: '#1a1a2e' },
+ layers: [
+ createShapeLayer('rectangle', 0, 0, 1280, 720, '#000000'),
+ createTextLayer('VIDEO TITLE', 60, 280, 800, 72, 900, '#ffffff', 'left'),
+ createTextLayer('GOES HERE', 60, 370, 800, 72, 900, '#ffcc00', 'left'),
+ createShapeLayer('ellipse', 900, 200, 300, 300, '#ff0000'),
+ createTextLayer('NEW', 950, 310, 200, 48, 700, '#ffffff', 'center'),
+ ],
+ },
+ ],
+ },
+ {
+ id: 'business',
+ name: 'Business',
+ templates: [
+ {
+ id: 'presentation-title',
+ name: 'Presentation Title',
+ thumbnail: '',
+ category: 'business',
+ size: { width: 1920, height: 1080 },
+ background: { type: 'color', color: '#ffffff' },
+ layers: [
+ createTextLayer('Presentation Title', 120, 400, 1200, 64, 700, '#1a1a2e', 'left'),
+ createTextLayer('Subtitle or company name', 120, 490, 1200, 28, 400, '#666666', 'left'),
+ createShapeLayer('rectangle', 120, 560, 100, 6, '#4a90d9'),
+ ],
+ },
+ {
+ id: 'business-card',
+ name: 'Business Card',
+ thumbnail: '',
+ category: 'business',
+ size: { width: 1050, height: 600 },
+ background: { type: 'color', color: '#ffffff' },
+ layers: [
+ createShapeLayer('rectangle', 0, 0, 10, 600, '#2563eb'),
+ createTextLayer('JOHN DOE', 60, 180, 500, 32, 700, '#1a1a2e', 'left'),
+ createTextLayer('Creative Director', 60, 230, 500, 18, 400, '#666666', 'left'),
+ createTextLayer('[email protected]', 60, 320, 500, 14, 400, '#2563eb', 'left'),
+ createTextLayer('+1 (555) 123-4567', 60, 350, 500, 14, 400, '#666666', 'left'),
+ ],
+ },
+ ],
+ },
+ {
+ id: 'marketing',
+ name: 'Marketing',
+ templates: [
+ {
+ id: 'sale-banner',
+ name: 'Sale Banner',
+ thumbnail: '',
+ category: 'marketing',
+ size: { width: 1200, height: 628 },
+ background: {
+ type: 'gradient',
+ gradient: {
+ type: 'linear',
+ angle: 45,
+ stops: [
+ { offset: 0, color: '#f12711' },
+ { offset: 1, color: '#f5af19' },
+ ],
+ },
+ },
+ layers: [
+ createTextLayer('MEGA SALE', 100, 180, 1000, 96, 900, '#ffffff', 'center'),
+ createTextLayer('Save up to 70% on selected items', 100, 310, 1000, 28, 400, 'rgba(255,255,255,0.9)', 'center'),
+ createShapeLayer('rectangle', 450, 400, 300, 56, '#ffffff', 28),
+ createTextLayer('Shop Now', 450, 414, 300, 18, 600, '#f12711', 'center'),
+ ],
+ },
+ {
+ id: 'product-showcase',
+ name: 'Product Showcase',
+ thumbnail: '',
+ category: 'marketing',
+ size: { width: 1080, height: 1080 },
+ background: { type: 'color', color: '#f8f9fa' },
+ layers: [
+ createShapeLayer('rectangle', 140, 140, 800, 600, '#ffffff', 16),
+ createTextLayer('PRODUCT NAME', 190, 800, 700, 36, 700, '#1a1a2e', 'center'),
+ createTextLayer('$99.99', 190, 860, 700, 28, 600, '#2563eb', 'center'),
+ createTextLayer('Short product description goes here', 190, 920, 700, 16, 400, '#666666', 'center'),
+ ],
+ },
+ ],
+ },
+ {
+ id: 'personal',
+ name: 'Personal',
+ templates: [
+ {
+ id: 'birthday-card',
+ name: 'Birthday Card',
+ thumbnail: '',
+ category: 'personal',
+ size: { width: 1080, height: 1080 },
+ background: {
+ type: 'gradient',
+ gradient: {
+ type: 'linear',
+ angle: 180,
+ stops: [
+ { offset: 0, color: '#ff9a9e' },
+ { offset: 1, color: '#fecfef' },
+ ],
+ },
+ },
+ layers: [
+ createTextLayer('🎂', 440, 300, 200, 120, 400, '#ffffff', 'center'),
+ createTextLayer('Happy Birthday!', 90, 480, 900, 56, 700, '#ffffff', 'center'),
+ createTextLayer('Wishing you a wonderful day!', 90, 570, 900, 24, 400, 'rgba(255,255,255,0.9)', 'center'),
+ ],
+ },
+ {
+ id: 'thank-you',
+ name: 'Thank You Card',
+ thumbnail: '',
+ category: 'personal',
+ size: { width: 1080, height: 1080 },
+ background: { type: 'color', color: '#fff8e7' },
+ layers: [
+ createTextLayer('Thank You', 90, 420, 900, 72, 700, '#d4a574', 'center'),
+ createTextLayer('Your support means the world to us', 90, 530, 900, 22, 400, '#8b7355', 'center'),
+ createShapeLayer('rectangle', 440, 350, 200, 3, '#d4a574'),
+ ],
+ },
+ ],
+ },
+ {
+ id: 'blank',
+ name: 'Blank Canvas',
+ templates: [
+ {
+ id: 'blank-square',
+ name: 'Square (1:1)',
+ thumbnail: '',
+ category: 'blank',
+ size: { width: 1080, height: 1080 },
+ background: { type: 'color', color: '#ffffff' },
+ layers: [],
+ },
+ {
+ id: 'blank-landscape',
+ name: 'Landscape (16:9)',
+ thumbnail: '',
+ category: 'blank',
+ size: { width: 1920, height: 1080 },
+ background: { type: 'color', color: '#ffffff' },
+ layers: [],
+ },
+ {
+ id: 'blank-portrait',
+ name: 'Portrait (9:16)',
+ thumbnail: '',
+ category: 'blank',
+ size: { width: 1080, height: 1920 },
+ background: { type: 'color', color: '#ffffff' },
+ layers: [],
+ },
+ {
+ id: 'blank-a4',
+ name: 'A4 Portrait',
+ thumbnail: '',
+ category: 'blank',
+ size: { width: 2480, height: 3508 },
+ background: { type: 'color', color: '#ffffff' },
+ layers: [],
+ },
+ ],
+ },
+];
+
+export function getTemplateById(id: string): Template | null {
+ for (const category of TEMPLATE_CATEGORIES) {
+ const template = category.templates.find((t) => t.id === id);
+ if (template) return template;
+ }
+ return null;
+}
+
+export function getTemplatesByCategory(categoryId: string): Template[] {
+ const category = TEMPLATE_CATEGORIES.find((c) => c.id === categoryId);
+ return category?.templates ?? [];
+}
+
+export function getAllTemplates(): Template[] {
+ return TEMPLATE_CATEGORIES.flatMap((c) => c.templates);
+}
+
+export function searchTemplates(query: string): Template[] {
+ const lowerQuery = query.toLowerCase();
+ return getAllTemplates().filter(
+ (t) =>
+ t.name.toLowerCase().includes(lowerQuery) ||
+ t.category.toLowerCase().includes(lowerQuery)
+ );
+}
diff --git a/apps/image/src/stores/canvas-store.ts b/apps/image/src/stores/canvas-store.ts
index 49cd3436..5348b4d2 100644
--- a/apps/image/src/stores/canvas-store.ts
+++ b/apps/image/src/stores/canvas-store.ts
@@ -14,6 +14,19 @@ export interface SelectionRect {
height: number;
}
+export interface SmartGuide {
+ type: 'horizontal' | 'vertical';
+ position: number;
+ start: number;
+ end: number;
+}
+
+export interface SnapResult {
+ x: number;
+ y: number;
+ guides: SmartGuide[];
+}
+
export type DragMode = 'none' | 'move' | 'resize' | 'rotate' | 'marquee' | 'pan';
export type ResizeHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
@@ -43,6 +56,8 @@ interface CanvasState {
transformOriginY: number;
renderCount: number;
+
+ smartGuides: SmartGuide[];
}
interface CanvasActions {
@@ -70,6 +85,9 @@ interface CanvasActions {
setTransformOrigin: (x: number, y: number) => void;
requestRender: () => void;
+
+ setSmartGuides: (guides: SmartGuide[]) => void;
+ clearSmartGuides: () => void;
}
const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -102,6 +120,8 @@ export const useCanvasStore = create<CanvasState & CanvasActions>()(
renderCount: 0,
+ smartGuides: [],
+
setCanvasRef: (canvas) => {
set({
canvasRef: canvas,
@@ -212,5 +232,13 @@ export const useCanvasStore = create<CanvasState & CanvasActions>()(
requestRender: () => {
set((state) => ({ renderCount: state.renderCount + 1 }));
},
+
+ setSmartGuides: (guides) => {
+ set({ smartGuides: guides });
+ },
+
+ clearSmartGuides: () => {
+ set({ smartGuides: [] });
+ },
}))
);
diff --git a/apps/image/src/stores/project-store.ts b/apps/image/src/stores/project-store.ts
index 44ebc2dd..1b774a72 100644
--- a/apps/image/src/stores/project-store.ts
+++ b/apps/image/src/stores/project-store.ts
@@ -15,6 +15,7 @@ import {
DEFAULT_BLEND_MODE,
DEFAULT_SHADOW,
DEFAULT_STROKE,
+ DEFAULT_GLOW,
DEFAULT_FILTER,
DEFAULT_TEXT_STYLE,
DEFAULT_SHAPE_STYLE,
@@ -216,6 +217,7 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
blendMode: DEFAULT_BLEND_MODE,
shadow: DEFAULT_SHADOW,
stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
filters: DEFAULT_FILTER,
parentId: null,
sourceId,
@@ -257,6 +259,7 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
blendMode: DEFAULT_BLEND_MODE,
shadow: DEFAULT_SHADOW,
stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
filters: DEFAULT_FILTER,
parentId: null,
content,
@@ -297,6 +300,7 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
blendMode: DEFAULT_BLEND_MODE,
shadow: DEFAULT_SHADOW,
stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
filters: DEFAULT_FILTER,
parentId: null,
shapeType,
@@ -329,6 +333,7 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
blendMode: DEFAULT_BLEND_MODE,
shadow: DEFAULT_SHADOW,
stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
filters: DEFAULT_FILTER,
parentId: null,
childIds,
diff --git a/apps/image/src/stores/ui-store.ts b/apps/image/src/stores/ui-store.ts
index 18af7ae5..55bf60f3 100644
--- a/apps/image/src/stores/ui-store.ts
+++ b/apps/image/src/stores/ui-store.ts
@@ -2,8 +2,17 @@ import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
export type AppView = 'welcome' | 'editor';
-export type Tool = 'select' | 'hand' | 'text' | 'shape' | 'pen' | 'eyedropper' | 'zoom';
-export type Panel = 'layers' | 'assets' | 'templates' | 'text' | 'shapes' | 'uploads';
+export type Tool = 'select' | 'hand' | 'text' | 'shape' | 'pen' | 'eyedropper' | 'zoom' | 'crop';
+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';
+
+export interface CropState {
+ isActive: boolean;
+ layerId: string | null;
+ aspectRatio: CropAspectRatio;
+ cropRect: { x: number; y: number; width: number; height: number } | null;
+}
interface UIState {
currentView: AppView;
@@ -24,6 +33,8 @@ interface UIState {
isExporting: boolean;
exportProgress: number;
notification: { type: 'success' | 'error' | 'info'; message: string } | null;
+ crop: CropState;
+ isExportDialogOpen: boolean;
}
interface UIActions {
@@ -49,6 +60,13 @@ interface UIActions {
setExportProgress: (progress: number) => void;
showNotification: (type: 'success' | 'error' | 'info', message: string) => void;
clearNotification: () => void;
+ 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;
+ cancelCrop: () => void;
+ applyCrop: () => { layerId: string; cropRect: { x: number; y: number; width: number; height: number } } | null;
+ openExportDialog: () => void;
+ closeExportDialog: () => void;
}
const ZOOM_LEVELS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4, 5, 8];
@@ -73,6 +91,13 @@ export const useUIStore = create<UIState & UIActions>()(
isExporting: false,
exportProgress: 0,
notification: null,
+ crop: {
+ isActive: false,
+ layerId: null,
+ aspectRatio: 'free',
+ cropRect: null,
+ },
+ isExportDialogOpen: false,
setCurrentView: (view) => set({ currentView: view }),
setActiveTool: (tool) => set({ activeTool: tool }),
@@ -119,5 +144,59 @@ export const useUIStore = create<UIState & UIActions>()(
},
clearNotification: () => set({ notification: null }),
+
+ startCrop: (layerId, initialRect) =>
+ set({
+ crop: {
+ isActive: true,
+ layerId,
+ aspectRatio: 'free',
+ cropRect: initialRect,
+ },
+ activeTool: 'crop',
+ }),
+
+ updateCropRect: (rect) =>
+ set((s) => ({
+ crop: { ...s.crop, cropRect: rect },
+ })),
+
+ setCropAspectRatio: (ratio) =>
+ set((s) => ({
+ crop: { ...s.crop, aspectRatio: ratio },
+ })),
+
+ cancelCrop: () =>
+ set({
+ crop: {
+ isActive: false,
+ layerId: null,
+ aspectRatio: 'free',
+ cropRect: null,
+ },
+ activeTool: 'select',
+ }),
+
+ applyCrop: () => {
+ const { crop } = get();
+ if (!crop.isActive || !crop.layerId || !crop.cropRect) return null;
+
+ const result = { layerId: crop.layerId, cropRect: crop.cropRect };
+
+ set({
+ crop: {
+ isActive: false,
+ layerId: null,
+ aspectRatio: 'free',
+ cropRect: null,
+ },
+ activeTool: 'select',
+ });
+
+ return result;
+ },
+
+ openExportDialog: () => set({ isExportDialogOpen: true }),
+ closeExportDialog: () => set({ isExportDialogOpen: false }),
}))
);
diff --git a/apps/image/src/types/project.ts b/apps/image/src/types/project.ts
index 77468538..5d8dee49 100644
--- a/apps/image/src/types/project.ts
+++ b/apps/image/src/types/project.ts
@@ -30,6 +30,13 @@ export interface Stroke {
style: 'solid' | 'dashed' | 'dotted';
}
+export interface Glow {
+ enabled: boolean;
+ color: string;
+ blur: number;
+ intensity: number;
+}
+
export interface Filter {
brightness: number;
contrast: number;
@@ -49,6 +56,7 @@ export interface BaseLayer {
blendMode: BlendMode;
shadow: Shadow;
stroke: Stroke;
+ glow: Glow;
filters: Filter;
parentId: string | null;
}
@@ -84,8 +92,23 @@ export interface TextLayer extends BaseLayer {
export type ShapeType = 'rectangle' | 'ellipse' | 'triangle' | 'polygon' | 'star' | 'line' | 'arrow' | 'path';
+export interface GradientStop {
+ offset: number;
+ color: string;
+}
+
+export interface Gradient {
+ type: 'linear' | 'radial';
+ angle: number;
+ stops: GradientStop[];
+}
+
+export type FillType = 'solid' | 'gradient';
+
export interface ShapeStyle {
+ fillType: FillType;
fill: string | null;
+ gradient: Gradient | null;
fillOpacity: number;
stroke: string | null;
strokeWidth: number;
@@ -198,6 +221,13 @@ export const DEFAULT_STROKE: Stroke = {
style: 'solid',
};
+export const DEFAULT_GLOW: Glow = {
+ enabled: false,
+ color: '#ffffff',
+ blur: 20,
+ intensity: 1,
+};
+
export const DEFAULT_FILTER: Filter = {
brightness: 100,
contrast: 100,
@@ -222,7 +252,9 @@ export const DEFAULT_TEXT_STYLE: TextStyle = {
};
export const DEFAULT_SHAPE_STYLE: ShapeStyle = {
+ fillType: 'solid',
fill: '#3b82f6',
+ gradient: null,
fillOpacity: 1,
stroke: null,
strokeWidth: 2,
diff --git a/apps/image/src/utils/snapping.ts b/apps/image/src/utils/snapping.ts
new file mode 100644
index 00000000..e20b681f
--- /dev/null
+++ b/apps/image/src/utils/snapping.ts
@@ -0,0 +1,169 @@
+import type { Layer } from '../types/project';
+import type { SmartGuide, Guide } from '../stores/canvas-store';
+
+export interface SnapConfig {
+ snapToObjects: boolean;
+ snapToGuides: boolean;
+ snapToGrid: boolean;
+ gridSize: number;
+ threshold: number;
+}
+
+export interface BoundsRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export interface SnapPoint {
+ value: number;
+ type: 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom';
+}
+
+export function calculateSnap(
+ movingBounds: BoundsRect,
+ otherLayers: Layer[],
+ canvasBounds: BoundsRect,
+ guides: Guide[],
+ config: SnapConfig
+): { x: number; y: number; guides: SmartGuide[] } {
+ const threshold = config.threshold ?? 5;
+ const resultGuides: SmartGuide[] = [];
+
+ let snapX = movingBounds.x;
+ let snapY = movingBounds.y;
+
+ const movingLeft = movingBounds.x;
+ const movingCenterX = movingBounds.x + movingBounds.width / 2;
+ const movingRight = movingBounds.x + movingBounds.width;
+ const movingTop = movingBounds.y;
+ const movingCenterY = movingBounds.y + movingBounds.height / 2;
+ const movingBottom = movingBounds.y + movingBounds.height;
+
+ const horizontalSnapPoints: SnapPoint[] = [];
+ const verticalSnapPoints: SnapPoint[] = [];
+
+ if (config.snapToObjects) {
+ horizontalSnapPoints.push(
+ { value: canvasBounds.x, type: 'left' },
+ { value: canvasBounds.x + canvasBounds.width / 2, type: 'center' },
+ { value: canvasBounds.x + canvasBounds.width, type: 'right' }
+ );
+ verticalSnapPoints.push(
+ { value: canvasBounds.y, type: 'top' },
+ { value: canvasBounds.y + canvasBounds.height / 2, type: 'middle' },
+ { value: canvasBounds.y + canvasBounds.height, type: 'bottom' }
+ );
+
+ otherLayers.forEach((layer) => {
+ const { x, y, width, height } = layer.transform;
+ horizontalSnapPoints.push(
+ { value: x, type: 'left' },
+ { value: x + width / 2, type: 'center' },
+ { value: x + width, type: 'right' }
+ );
+ verticalSnapPoints.push(
+ { value: y, type: 'top' },
+ { value: y + height / 2, type: 'middle' },
+ { value: y + height, type: 'bottom' }
+ );
+ });
+ }
+
+ if (config.snapToGuides) {
+ guides.forEach((guide) => {
+ if (guide.type === 'vertical') {
+ horizontalSnapPoints.push({ value: guide.position, type: 'center' });
+ } else {
+ verticalSnapPoints.push({ value: guide.position, type: 'middle' });
+ }
+ });
+ }
+
+ if (config.snapToGrid && config.gridSize > 0) {
+ const gridSize = config.gridSize;
+ for (let gx = 0; gx <= canvasBounds.width; gx += gridSize) {
+ horizontalSnapPoints.push({ value: gx, type: 'left' });
+ }
+ for (let gy = 0; gy <= canvasBounds.height; gy += gridSize) {
+ verticalSnapPoints.push({ value: gy, type: 'top' });
+ }
+ }
+
+ let minDistX = threshold + 1;
+ let snappedX = false;
+
+ const checkXSnap = (moving: number, movingType: 'left' | 'center' | 'right') => {
+ for (const point of horizontalSnapPoints) {
+ const dist = Math.abs(moving - point.value);
+ if (dist < minDistX && dist <= threshold) {
+ minDistX = dist;
+ if (movingType === 'left') {
+ snapX = point.value;
+ } else if (movingType === 'center') {
+ snapX = point.value - movingBounds.width / 2;
+ } else {
+ snapX = point.value - movingBounds.width;
+ }
+ snappedX = true;
+
+ resultGuides.push({
+ type: 'vertical',
+ position: point.value,
+ start: Math.min(movingTop, 0),
+ end: Math.max(movingBottom, canvasBounds.height),
+ });
+ }
+ }
+ };
+
+ checkXSnap(movingLeft, 'left');
+ checkXSnap(movingCenterX, 'center');
+ checkXSnap(movingRight, 'right');
+
+ let minDistY = threshold + 1;
+ let snappedY = false;
+
+ const checkYSnap = (moving: number, movingType: 'top' | 'middle' | 'bottom') => {
+ for (const point of verticalSnapPoints) {
+ const dist = Math.abs(moving - point.value);
+ if (dist < minDistY && dist <= threshold) {
+ minDistY = dist;
+ if (movingType === 'top') {
+ snapY = point.value;
+ } else if (movingType === 'middle') {
+ snapY = point.value - movingBounds.height / 2;
+ } else {
+ snapY = point.value - movingBounds.height;
+ }
+ snappedY = true;
+
+ resultGuides.push({
+ type: 'horizontal',
+ position: point.value,
+ start: Math.min(movingLeft, 0),
+ end: Math.max(movingRight, canvasBounds.width),
+ });
+ }
+ }
+ };
+
+ checkYSnap(movingTop, 'top');
+ checkYSnap(movingCenterY, 'middle');
+ checkYSnap(movingBottom, 'bottom');
+
+ const uniqueGuides = resultGuides.filter(
+ (guide, index, self) =>
+ index ===
+ self.findIndex(
+ (g) => g.type === guide.type && g.position === guide.position
+ )
+ );
+
+ return {
+ x: snappedX ? snapX : movingBounds.x,
+ y: snappedY ? snapY : movingBounds.y,
+ guides: uniqueGuides,
+ };
+}
diff --git a/apps/image/src/utils/time.ts b/apps/image/src/utils/time.ts
new file mode 100644
index 00000000..dbca3aec
--- /dev/null
+++ b/apps/image/src/utils/time.ts
@@ -0,0 +1,27 @@
+export function formatDistanceToNow(timestamp: number): string {
+ const now = Date.now();
+ const diff = now - timestamp;
+
+ const seconds = Math.floor(diff / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (seconds < 5) return 'just now';
+ if (seconds < 60) return `${seconds}s ago`;
+ if (minutes < 60) return `${minutes}m ago`;
+ if (hours < 24) return `${hours}h ago`;
+ if (days === 1) return 'yesterday';
+ return `${days}d ago`;
+}
+
+export function formatDuration(ms: number): string {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+
+ if (hours > 0) {
+ return `${hours}:${String(minutes % 60).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
+ }
+ return `${minutes}:${String(seconds % 60).padStart(2, '0')}`;
+}