/
Eraser.ts
286 lines (231 loc) · 8.66 KB
/
Eraser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import { EditorEventType } from '../types';
import { KeyPressEvent, PointerEvt } from '../inputEvents';
import BaseTool from './BaseTool';
import Editor from '../Editor';
import { Point2, Vec2, LineSegment2, Color4, Rect2, Path } from '@js-draw/math';
import Erase from '../commands/Erase';
import AbstractComponent from '../components/AbstractComponent';
import { PointerDevice } from '../Pointer';
import RenderingStyle from '../rendering/RenderingStyle';
import { decreaseSizeKeyboardShortcutId, increaseSizeKeyboardShortcutId } from './keybindings';
import { MutableReactiveValue, ReactiveValue } from '../util/ReactiveValue';
import Command from '../commands/Command';
import EditorImage from '../image/EditorImage';
import uniteCommands from '../commands/uniteCommands';
import { pathToRenderable } from '../rendering/RenderablePathSpec';
export enum EraserMode {
PartialStroke = 'partial-stroke',
FullStroke = 'full-stroke',
}
export interface InitialEraserOptions {
thickness?: number;
mode?: EraserMode;
}
export default class Eraser extends BaseTool {
private lastPoint: Point2|null = null;
private isFirstEraseEvt: boolean = true;
private thickness: number;
private thicknessValue: MutableReactiveValue<number>;
private modeValue: MutableReactiveValue<EraserMode>;
private toRemove: AbstractComponent[];
private toAdd: AbstractComponent[];
// Commands that each remove one element
private eraseCommands: Erase[] = [];
private addCommands: Command[] = [];
public constructor(private editor: Editor, description: string, options?: InitialEraserOptions) {
super(editor.notifier, description);
this.thickness = options?.thickness ?? 10;
this.thicknessValue = ReactiveValue.fromInitialValue(this.thickness);
this.thicknessValue.onUpdate(value => {
this.thickness = value;
this.editor.notifier.dispatch(EditorEventType.ToolUpdated, {
kind: EditorEventType.ToolUpdated,
tool: this,
});
});
this.modeValue = ReactiveValue.fromInitialValue(options?.mode ?? EraserMode.FullStroke);
this.modeValue.onUpdate(_value => {
this.editor.notifier.dispatch(EditorEventType.ToolUpdated, {
kind: EditorEventType.ToolUpdated,
tool: this,
});
});
}
private clearPreview() {
this.editor.clearWetInk();
}
private getSizeOnCanvas() {
return this.thickness / this.editor.viewport.getScaleFactor();
}
private drawPreviewAt(point: Point2) {
this.clearPreview();
const size = this.getSizeOnCanvas();
const renderer = this.editor.display.getWetInkRenderer();
const rect = this.getEraserRect(point);
const rect2 = this.getEraserRect(this.lastPoint ?? point);
const fill: RenderingStyle = {
fill: Color4.transparent,
stroke: { width: size / 10, color: Color4.gray },
};
renderer.drawPath(pathToRenderable(Path.fromConvexHullOf([...rect.corners, ...rect2.corners]), fill));
}
/**
* @returns the eraser rectangle in canvas coordinates.
*
* For now, all erasers are rectangles or points.
*/
private getEraserRect(centerPoint: Point2) {
const size = this.getSizeOnCanvas();
const halfSize = Vec2.of(size / 2, size / 2);
return Rect2.fromCorners(centerPoint.minus(halfSize), centerPoint.plus(halfSize));
}
/** Erases in a line from the last point to the current. */
private eraseTo(currentPoint: Point2) {
if (!this.isFirstEraseEvt && currentPoint.distanceTo(this.lastPoint!) === 0) {
return;
}
this.isFirstEraseEvt = false;
// Currently only objects within eraserRect or that intersect a straight line
// from the center of the current rect to the previous are erased. TODO: Erase
// all objects as if there were pointerMove events between the two points.
const eraserRect = this.getEraserRect(currentPoint);
const line = new LineSegment2(this.lastPoint!, currentPoint);
const region = Rect2.union(line.bbox, eraserRect);
const intersectingElems = this.editor.image.getElementsIntersectingRegion(region).filter(component => {
return component.intersects(line) || component.intersectsRect(eraserRect);
});
// Only erase components that could be selected (and thus interacted with)
// by the user.
const eraseableElems = intersectingElems.filter(elem => elem.isSelectable());
if (this.modeValue.get() === EraserMode.FullStroke) {
// Remove any intersecting elements.
this.toRemove.push(...eraseableElems);
// Create new Erase commands for the now-to-be-erased elements and apply them.
const newPartialCommands = eraseableElems.map(elem => new Erase([ elem ]));
newPartialCommands.forEach(cmd => cmd.apply(this.editor));
this.eraseCommands.push(...newPartialCommands);
} else {
const toErase: AbstractComponent[] = [];
const toAdd: AbstractComponent[] = [];
for (const targetElem of eraseableElems) {
toErase.push(targetElem);
// Completely delete items that can't be divided.
if (!targetElem.withRegionErased) {
continue;
}
// Completely delete items that are completely or almost completely
// contained within the eraser.
const grownRect = eraserRect.grownBy(eraserRect.maxDimension / 3);
if (grownRect.containsRect(targetElem.getExactBBox())) {
continue;
}
// Join the current and previous rectangles so that points between events are also
// erased.
const erasePath = Path.fromConvexHullOf([
...eraserRect.corners, ...this.getEraserRect(this.lastPoint ?? currentPoint).corners
].map(p => this.editor.viewport.roundPoint(p)));
toAdd.push(
...targetElem.withRegionErased(
erasePath,
this.editor.viewport,
)
);
}
const eraseCommand = new Erase(toErase);
const newAddCommands = toAdd.map(elem => EditorImage.addElement(elem));
eraseCommand.apply(this.editor);
newAddCommands.forEach(command => command.apply(this.editor));
const finalToErase = [];
for (const item of toErase) {
if (this.toAdd.includes(item)) {
this.toAdd = this.toAdd.filter(i => i !== item);
} else {
finalToErase.push(item);
}
}
this.toRemove.push(...finalToErase);
this.toAdd.push(...toAdd);
this.eraseCommands.push(new Erase(finalToErase));
this.addCommands.push(...newAddCommands);
}
this.drawPreviewAt(currentPoint);
this.lastPoint = currentPoint;
}
public override onPointerDown(event: PointerEvt): boolean {
if (event.allPointers.length === 1 || event.current.device === PointerDevice.Eraser) {
this.lastPoint = event.current.canvasPos;
this.toRemove = [];
this.toAdd = [];
this.isFirstEraseEvt = true;
this.drawPreviewAt(event.current.canvasPos);
return true;
}
return false;
}
public override onPointerMove(event: PointerEvt): void {
const currentPoint = event.current.canvasPos;
this.eraseTo(currentPoint);
}
public override onPointerUp(event: PointerEvt): void {
this.eraseTo(event.current.canvasPos);
const commands: Command[] = [];
if (this.addCommands.length > 0) {
this.addCommands.forEach(cmd => cmd.unapply(this.editor));
commands.push(...this.toAdd.map(a => EditorImage.addElement(a)));
this.addCommands = [];
}
if (this.eraseCommands.length > 0) {
// Undo commands for each individual component and unite into a single command.
this.eraseCommands.forEach(cmd => cmd.unapply(this.editor));
this.eraseCommands = [];
const command = new Erase(this.toRemove);
commands.push(command);
}
if (commands.length === 1) {
this.editor.dispatch(commands[0]); // dispatch: Makes undo-able.
} else {
this.editor.dispatch(uniteCommands(commands));
}
this.clearPreview();
}
public override onGestureCancel(): void {
this.addCommands.forEach(cmd => cmd.unapply(this.editor));
this.eraseCommands.forEach(cmd => cmd.unapply(this.editor));
this.eraseCommands = [];
this.addCommands = [];
this.clearPreview();
}
public override onKeyPress(event: KeyPressEvent): boolean {
const shortcuts = this.editor.shortcuts;
let newThickness: number|undefined;
if (shortcuts.matchesShortcut(decreaseSizeKeyboardShortcutId, event)) {
newThickness = this.getThickness() * 2/3;
} else if (shortcuts.matchesShortcut(increaseSizeKeyboardShortcutId, event)) {
newThickness = this.getThickness() * 3/2;
}
if (newThickness !== undefined) {
newThickness = Math.min(Math.max(1, newThickness), 200);
this.setThickness(newThickness);
return true;
}
return false;
}
/** Returns the side-length of the tip of this eraser. */
public getThickness() {
return this.thickness;
}
/** Sets the side-length of this' tip. */
public setThickness(thickness: number) {
this.thicknessValue.set(thickness);
}
/**
* Returns a {@link MutableReactiveValue} that can be used to watch
* this tool's thickness.
*/
public getThicknessValue() {
return this.thicknessValue;
}
public getModeValue() {
return this.modeValue;
}
}