-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathqboard.ts
308 lines (265 loc) · 8.67 KB
/
qboard.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import { fabric } from "fabric";
import { Network } from "@mehra/ts";
import instantiateTools, { Tool, Tools } from "./tools";
import Page from "./page";
import Pages from "./pages";
import HistoryHandler from "./history";
import FileHandler, { JSONReader } from "./files";
import ClipboardHandler from "./clipboard";
import StyleHandler, { Dash, Fill, Stroke, Style } from "./styles";
import ActionHandler from "./action";
import KeyboardHandler, { KeyMap } from "./keyboard";
import { HTMLChildElement } from "../types/html";
import {
FabricIEvent,
GuaranteedIObjectOptions,
isFabricCollection,
PathEvent,
} from "../types/fabric";
type Async<T = void> = T | Promise<T>;
type FabricHandler<T extends fabric.IEvent = fabric.IEvent> = (e: T) => Async;
import AssertType from "../types/assert";
export interface QBoardState {
dragActive: boolean;
currentPage: number;
totalPages: number;
currentStyle: Style;
canUndo: boolean;
canRedo: boolean;
keyMap: KeyMap;
}
export default class QBoard {
baseCanvas: Page;
canvas: Page;
pages: Pages;
files: FileHandler;
history: HistoryHandler;
clipboard: ClipboardHandler;
style: StyleHandler;
action: ActionHandler;
keyboard: KeyboardHandler;
tools: Tools;
activeTool: Tool;
currentStyle: Style = {
dash: Dash.Solid,
stroke: Stroke.Black,
fill: Fill.Transparent,
};
readonly drawerOptions: GuaranteedIObjectOptions = {
fill: "transparent",
stroke: "#000000",
strokeWidth: 4,
selectable: false,
strokeDashArray: [0, 0],
strokeUniform: true,
};
resizeCooldown: NodeJS.Timeout | undefined;
currentObject: fabric.Object | undefined;
dragActive = false;
isDown = false;
strict = false;
callback: ((state: QBoardState) => void) | undefined;
/**
* Intentionally mutable global state object
*/
public globalState: {
/**
* A ref to the global input element used for file input
*/
fileInputRef?: React.RefObject<HTMLInputElement>;
toggleHelpModal?: () => void;
} = {};
constructor(
public canvasElement: HTMLCanvasElement & HTMLChildElement,
public baseCanvasElement: HTMLCanvasElement & HTMLChildElement,
public canvasWidth: number,
public canvasHeight: number
) {
const queryParams = new URLSearchParams(window.location.search);
this.baseCanvas = new Page(baseCanvasElement, {
backgroundColor: "white",
renderOnAddRemove: false,
selection: false,
targetFindTolerance: 15,
});
this.canvas = new Page(canvasElement, {
renderOnAddRemove: false,
selection: false,
});
this.pages = new Pages(
this.baseCanvas,
this.canvasWidth,
this.canvasHeight,
this.updateState
);
{
const jsonLink = queryParams.get("json");
if (jsonLink !== null)
Network.loadJSON(jsonLink)
.then(JSONReader.readParsed)
.then(this.pages.overwritePages)
// eslint-disable-next-line no-console
.catch(console.error);
}
this.history = new HistoryHandler(
this.baseCanvas,
this.pages,
this.updateState
);
this.files = new FileHandler(this.pages, this.history);
this.clipboard = new ClipboardHandler(
this.baseCanvas,
this.pages,
this.files,
this.history,
this.canvasWidth,
this.canvasHeight
);
this.style = new StyleHandler(
this.currentStyle,
this.drawerOptions,
this.baseCanvas.freeDrawingBrush as fabric.BaseBrush,
this.updateState
);
this.tools = instantiateTools(
this.baseCanvas,
this.history,
this.clipboard
);
this.action = new ActionHandler(
this.switchTool,
this.tools,
this.currentStyle,
this.pages,
this.files,
this.history,
this.clipboard,
this.style.set,
this.globalState
);
this.keyboard = new KeyboardHandler(
this.action.doAction,
(strict: boolean) => (this.strict = strict),
this.updateState
);
// an instance which has no effect (deactivate method is trivial)
this.activeTool = new Tool(this.baseCanvas, this.history, this.clipboard);
void this.switchTool();
void this.windowResize();
window.onresize = this.windowResize;
window.onbeforeunload = () => this.baseCanvas.modified || null;
{
/* eslint-disable @typescript-eslint/ban-ts-comment */
this.canvas.on("mouse:down", this.mouseDown);
this.canvas.on("mouse:move", this.mouseMove);
this.canvas.on("mouse:up", this.mouseUp);
this.baseCanvas.on("dragenter", () => this.setDragActive(true));
this.baseCanvas.on("dragleave", () => this.setDragActive(false));
this.baseCanvas.on("drop", this.drop);
// @ts-ignore
this.baseCanvas.on("path:created", this.pathCreated);
// @ts-ignore
this.baseCanvas.on("selection:created", this.selectionCreated);
// @ts-ignore
this.baseCanvas.on("object:modified", this.objectModified);
this.baseCanvas.on("mouse:move", this.updateCursor);
/* eslint-enable @typescript-eslint/ban-ts-comment */
}
}
updateState = (): void => {
this?.callback?.({
dragActive: this.dragActive,
currentPage: this.pages.currentIndex + 1,
totalPages: this.pages.pagesJSON.length,
currentStyle: this.currentStyle,
canUndo: this.history.history.length > 0,
canRedo: this.history.redoStack.length > 0,
keyMap: this.keyboard.keyMap,
});
};
/**
* Assumes no two instances are the same tool
*/
switchTool = async (tool: Tool = this.tools.Move): Promise<void> => {
// Reference equality because of assumption
if (tool === this.activeTool || !(await tool.activate())) return;
this.activeTool.deactivate();
if (tool.isBrush() || tool.requiresBase()) {
this.baseCanvas.activateSelection();
this.canvasElement.parentElement.style.display = "none";
} else {
this.baseCanvas.deactivateSelection();
this.canvasElement.parentElement.style.display = "block";
}
if (tool.isBrush()) {
await tool.setBrush(
this.baseCanvas.freeDrawingBrush as fabric.BaseBrush,
this.drawerOptions
);
}
this.activeTool = tool;
this.baseCanvas.isDrawingMode = this.activeTool.isBrush();
this.updateState();
};
windowResize = (): void => {
if (this.resizeCooldown !== undefined) clearTimeout(this.resizeCooldown);
this.resizeCooldown = setTimeout(() => {
this.canvas.fitToWindow(this.canvasWidth, this.canvasHeight);
this.baseCanvas.fitToWindow(this.canvasWidth, this.canvasHeight);
}, 100);
};
mouseDown: FabricHandler = async (e) => {
if (!this.activeTool.isDrawing()) return;
const { x, y } = this.canvas.getPointer(e.e);
this.isDown = true;
this.currentObject = await this.activeTool.draw(x, y, this.drawerOptions);
this.canvas.add(this.currentObject);
this.canvas.requestRenderAll();
};
mouseMove: FabricHandler = async (e) => {
if (!(this.activeTool.isDrawing() && this.isDown)) return;
const { x, y } = this.canvas.getPointer(e.e);
if (this.currentObject !== undefined)
await this.activeTool.resize?.(this.currentObject, x, y, this.strict);
this.canvas.requestRenderAll();
};
mouseUp: FabricHandler = () => {
if (!this.activeTool.isDrawing()) return;
this.isDown = false;
this.baseCanvas.add(fabric.util.object.clone(this.currentObject));
this.baseCanvas.requestRenderAll();
AssertType<fabric.Object>(this.currentObject); // can do this because mouseDown sets this
this.canvas.remove(this.currentObject);
this.canvas.requestRenderAll();
this.history.add([this.currentObject]);
};
setDragActive = (state: boolean): void => {
this.dragActive = state;
this.updateState();
};
drop: FabricHandler = async (iEvent) => {
iEvent.e.stopPropagation();
iEvent.e.preventDefault();
await this.updateCursor(iEvent);
this.setDragActive(false);
await this.files.processFiles((iEvent.e as DragEvent).dataTransfer!.files);
};
pathCreated: FabricHandler<PathEvent> = (e) => {
if (this.activeTool.isBrush()) this.activeTool.pathCreated(e);
};
selectionCreated: FabricHandler<FabricIEvent> = (e) => {
if (this.history.locked) return;
return this.history.store(e.selected);
};
objectModified: FabricHandler<FabricIEvent> = (e) => {
const objects = isFabricCollection(e.target)
? e.target.getObjects()
: [e.target];
this.history.modify(objects); // old selection was replaced with this selection
this.history.store(objects); // new state of selection
};
updateCursor: FabricHandler = (iEvent) => {
const { x, y } = this.baseCanvas.getPointer(iEvent.e);
this.baseCanvas.cursor = { x, y };
};
}