forked from cjquines/qboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclipboard.ts
91 lines (83 loc) · 2.29 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { fabric } from "fabric";
import { Page } from "./pages";
import { HistoryHandler } from "./history";
export class ClipboardHandler {
clipboard: fabric.Object;
constructor(
public canvas: Page,
public history: HistoryHandler,
public canvasWidth: number,
public canvasHeight: number
) {
window.addEventListener("paste", this.pasteExternal);
}
copy = async (): Promise<any> => {
const objects = this.canvas.getActiveObject();
if (!objects) return null;
objects.clone((clone) => {
this.clipboard = clone;
});
return objects;
};
cut = async (): Promise<boolean> => {
const objects = await this.copy();
if (!objects) return false;
this.canvas.discardActiveObject();
if (objects.type === "activeSelection") {
objects.forEachObject((object) => {
this.canvas.remove(object);
});
this.history.remove(objects._objects);
} else {
this.canvas.remove(objects);
this.history.remove([objects]);
}
this.canvas.requestRenderAll();
return true;
};
paste = async (): Promise<void> => {
if (!this.clipboard) return;
this.clipboard.clone(async (clone) => {
await this.placeObject(clone);
});
};
pasteExternal = async (e: ClipboardEvent): Promise<void> => {
for (const file of e.clipboardData.files) {
if (!file.type.includes("image")) continue;
const url = window.URL.createObjectURL(file);
fabric.Image.fromURL(url, async (obj: any) => {
await this.placeObject(obj);
});
return;
}
await this.paste();
};
placeObject = async (obj: any): Promise<void> => {
const { x, y } = this.canvas.cursor;
this.canvas.discardActiveObject();
await this.canvas.getNextId().then((id) => {
obj.set({
id,
left: x,
top: y,
originX: "center",
originY: "center",
});
});
if (obj._objects) {
obj.canvas = this.canvas;
await obj.forEachObject((object) => {
this.canvas.getNextId().then((id) => {
object.id = id;
this.canvas.add(object);
});
});
obj.setCoords();
} else {
this.canvas.add(obj);
}
this.canvas.setActiveObject(obj);
this.history.add(obj._objects || [obj]);
this.canvas.requestRenderAll();
};
}