import React from 'react'; import { Shape } from 'remixed/model/l33t'; import { Command, CommandContext } from '.'; export class DeleteVertexCommand implements Command { private oldShapes: { [id: string]: Shape } | null = null; private oldSelectedPoint: { shapeId: string; pointIndex: number } | null = null; private oldSelectedShape: Shape | null = null; constructor( private context: CommandContext, private selectedPoint: { shapeId: string; pointIndex: number } | null, ) {} execute() { const { shapes, setShapes, setSelectedPoint, setSelectedShape } = this.context; if (this.selectedPoint) { this.oldShapes = { ...shapes }; this.oldSelectedPoint = this.selectedPoint; this.oldSelectedShape = shapes[this.selectedPoint.shapeId] || null; setShapes(prevShapes => { const newShapes = { ...prevShapes }; const shape = newShapes[this.selectedPoint!.shapeId]; if (shape) { const newPoints = shape.points.filter((_, index) => index !== this.selectedPoint!.pointIndex); if (newPoints.length > 0) { newShapes[this.selectedPoint!.shapeId] = { ...shape, points: newPoints }; } else { delete newShapes[this.selectedPoint!.shapeId]; } } return newShapes; }); setSelectedPoint(null); setSelectedShape(null); } } undo() { const { setShapes, setSelectedPoint, setSelectedShape } = this.context; if (this.oldShapes) { setShapes(this.oldShapes); setSelectedPoint(this.oldSelectedPoint); setSelectedShape(this.oldSelectedShape); } } }