-
Notifications
You must be signed in to change notification settings - Fork 9
/
clipboard.ts
72 lines (59 loc) · 1.8 KB
/
clipboard.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
import { fabric } from "fabric";
import { FabricObject, isFabricCollection } from "../types/fabric";
import AssertType from "../types/assert";
import Page from "./page";
import Pages from "./pages";
import FileHandler from "./files";
import HistoryHandler from "./history";
export default class ClipboardHandler {
clipboard?: FabricObject;
constructor(
public canvas: Page,
public pages: Pages,
public files: FileHandler,
public history: HistoryHandler,
public canvasWidth: number,
public canvasHeight: number
) {
document.addEventListener("paste", this.pasteExternal);
}
copy = (): fabric.Object | null => {
const activeObject = this.canvas.getActiveObject();
if (!activeObject) return null;
// Add missing type information
AssertType<FabricObject>(activeObject);
activeObject.clone((clone) => {
this.clipboard = clone;
});
return activeObject;
};
/**
* Cuts currently selected objects, if any
* @return Whether there were objects to cut
*/
cut = (): boolean => {
const activeObject = this.copy();
if (!activeObject) return false;
this.canvas.discardActiveObject();
if (isFabricCollection(activeObject)) {
activeObject.forEachObject((object) => {
this.canvas.remove(object);
});
this.history.remove(activeObject.getObjects());
} else {
this.canvas.remove(activeObject);
this.history.remove([activeObject]);
}
this.canvas.requestRenderAll();
return true;
};
paste = (): void => {
if (this.clipboard === undefined) return;
return this.clipboard.clone((clone) =>
this.history.add(this.canvas.placeObject(clone))
);
};
pasteExternal = async (e: ClipboardEvent): Promise<void> => {
await this.files.processFiles(e.clipboardData!.files);
};
}