import { Shape, Point, ShapeType } from 'remixed/model/l33t'; import { Command, CommandContext } from '.'; export class AddPointCommand implements Command { private newShape: Shape | null = null; private updatedShape: Shape | null = null; private oldShapes: { [id: string]: Shape } | null = null; constructor( private context: CommandContext, private point: Point, private drawMode: ShapeType, private currentShape: Shape | null ) {} execute() { const { shapes, setShapes, setCurrentShape, setSelectedPoint } = this.context; this.oldShapes = { ...shapes }; if (!this.currentShape) { this.newShape = { id: Date.now().toString(), type: this.drawMode, points: [this.point], isClosed: false }; setCurrentShape(this.newShape); setSelectedPoint({ shapeId: this.newShape.id, pointIndex: 0 }); } else { this.updatedShape = { ...this.currentShape, points: [...this.currentShape.points, this.point] }; if (this.drawMode === 'line' && this.updatedShape.points.length === 2) { setShapes((prevShapes) => ({ ...prevShapes, [this.updatedShape!.id]: this.updatedShape! })); setCurrentShape(null); setSelectedPoint({ shapeId: this.updatedShape.id, pointIndex: 1 }); } else if (this.drawMode === 'polygon') { setCurrentShape(this.updatedShape); setSelectedPoint({ shapeId: this.updatedShape.id, pointIndex: this.updatedShape.points.length - 1 }); } } } undo() { const { setShapes, setCurrentShape, setSelectedPoint } = this.context; if (this.oldShapes) { setShapes(this.oldShapes); setCurrentShape(this.currentShape); if (this.currentShape) { setSelectedPoint({ shapeId: this.currentShape.id, pointIndex: this.currentShape.points.length - 1 }); } else { setSelectedPoint(null); } } } }