import { BaseCommand } from './base-command'; import { useLayerStore } from '@/store'; import { cloneCanvas } from '@/lib/canvas-utils'; /** * Command for drawing operations * Stores the before/after state of the canvas */ export class DrawCommand extends BaseCommand { private layerId: string; private beforeCanvas: HTMLCanvasElement | null = null; private afterCanvas: HTMLCanvasElement | null = null; constructor(layerId: string, toolName: string) { super(`Draw with ${toolName}`); this.layerId = layerId; // Store before state const layer = useLayerStore.getState().getLayer(layerId); if (layer?.canvas) { this.beforeCanvas = cloneCanvas(layer.canvas); } } /** * Call this after drawing is complete to capture the after state */ captureAfterState(): void { const layer = useLayerStore.getState().getLayer(this.layerId); if (layer?.canvas) { this.afterCanvas = cloneCanvas(layer.canvas); } } execute(): void { if (!this.afterCanvas) return; const layer = useLayerStore.getState().getLayer(this.layerId); if (!layer?.canvas) return; const ctx = layer.canvas.getContext('2d'); if (!ctx) return; ctx.clearRect(0, 0, layer.canvas.width, layer.canvas.height); ctx.drawImage(this.afterCanvas, 0, 0); // Trigger re-render by updating layer timestamp const { updateLayer } = useLayerStore.getState(); updateLayer(this.layerId, { updatedAt: Date.now() }); } undo(): void { if (!this.beforeCanvas) return; const layer = useLayerStore.getState().getLayer(this.layerId); if (!layer?.canvas) return; const ctx = layer.canvas.getContext('2d'); if (!ctx) return; ctx.clearRect(0, 0, layer.canvas.width, layer.canvas.height); ctx.drawImage(this.beforeCanvas, 0, 0); // Trigger re-render by updating layer timestamp const { updateLayer } = useLayerStore.getState(); updateLayer(this.layerId, { updatedAt: Date.now() }); } }