|
| 1 | +import { |
| 2 | + CommitModelAction, |
| 3 | + KeyListener, |
| 4 | + SModelElementImpl, |
| 5 | + isDeletable, |
| 6 | + isSelectable, |
| 7 | + SConnectableElementImpl, |
| 8 | + SChildElementImpl, |
| 9 | +} from "sprotty"; |
| 10 | +import { Action, DeleteElementAction } from "sprotty-protocol"; |
| 11 | +import { matchesKeystroke } from "sprotty/lib/utils/keyboard"; |
| 12 | + |
| 13 | +/** |
| 14 | + * Custom sprotty key listener that deletes all selected elements when the user presses the delete key. |
| 15 | + */ |
| 16 | +export class DeleteKeyListener extends KeyListener { |
| 17 | + override keyDown(element: SModelElementImpl, event: KeyboardEvent): Action[] { |
| 18 | + if (matchesKeystroke(event, "Delete")) { |
| 19 | + return this.deleteSelectedElements(element); |
| 20 | + } |
| 21 | + return []; |
| 22 | + } |
| 23 | + |
| 24 | + private deleteSelectedElements(element: SModelElementImpl): Action[] { |
| 25 | + const index = element.root.index; |
| 26 | + const selectedElements = Array.from( |
| 27 | + index |
| 28 | + .all() |
| 29 | + .filter((e) => isDeletable(e) && isSelectable(e) && e.selected) |
| 30 | + .filter((e) => e.id !== e.root.id), // Deleting the model root would be a bad idea |
| 31 | + ); |
| 32 | + |
| 33 | + const deleteElementIds = selectedElements.flatMap((e) => { |
| 34 | + const ids = [e.id]; |
| 35 | + |
| 36 | + if (e instanceof SConnectableElementImpl) { |
| 37 | + // This element can be connected to other elements, so we need to delete all edges connected to it as well. |
| 38 | + // Otherwise the edges would be left dangling in the graph. |
| 39 | + ids.push(...this.getEdgeIdsOfElement(e)); |
| 40 | + } |
| 41 | + if (e instanceof SChildElementImpl) { |
| 42 | + // Add all children and their edges to the list of elements to delete |
| 43 | + // This is needed when the edges are not connected to the element itself but to a port of the element. |
| 44 | + e.children.forEach((child) => { |
| 45 | + ids.push(child.id); |
| 46 | + if (child instanceof SConnectableElementImpl) { |
| 47 | + ids.push(...this.getEdgeIdsOfElement(child)); |
| 48 | + } |
| 49 | + }); |
| 50 | + } |
| 51 | + |
| 52 | + return ids; |
| 53 | + }); |
| 54 | + |
| 55 | + if (deleteElementIds.length > 0) { |
| 56 | + const uniqueIds = [...new Set(deleteElementIds)]; |
| 57 | + |
| 58 | + return [DeleteElementAction.create(uniqueIds), CommitModelAction.create()]; |
| 59 | + } else { |
| 60 | + return []; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private getEdgeIdsOfElement(element: SConnectableElementImpl): string[] { |
| 65 | + return [...element.incomingEdges.map((e) => e.id), ...element.outgoingEdges.map((e) => e.id)]; |
| 66 | + } |
| 67 | +} |
0 commit comments