@daasboard/embed 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +5 -0
- package/README.md +971 -2
- package/THIRD_PARTY_NOTICES.md +32 -0
- package/dist/assets/assetServiceStore.d.ts +51 -0
- package/dist/assets/assetServiceStore.js +658 -0
- package/dist/assets/clipboardAssets.d.ts +6 -0
- package/dist/assets/clipboardAssets.js +23 -0
- package/dist/boardUi.d.ts +34 -0
- package/dist/boardUi.js +122 -0
- package/dist/builtins.d.ts +19 -0
- package/dist/builtins.js +198 -0
- package/dist/contextMenu.d.ts +24 -0
- package/dist/contextMenu.js +114 -0
- package/dist/coordinates.d.ts +11 -0
- package/dist/coordinates.js +30 -0
- package/dist/createBoard.d.ts +2 -0
- package/dist/createBoard.js +1333 -0
- package/dist/document.d.ts +7 -0
- package/dist/document.js +86 -0
- package/dist/images/BoardImages.d.ts +53 -0
- package/dist/images/BoardImages.js +241 -0
- package/dist/images/preprocess.d.ts +27 -0
- package/dist/images/preprocess.js +196 -0
- package/dist/images/types.d.ts +90 -0
- package/dist/images/types.js +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/types.d.ts +49 -0
- package/dist/types.js +1 -0
- package/dist/uiHost.d.ts +42 -0
- package/dist/uiHost.js +273 -0
- package/package.json +33 -3
|
@@ -0,0 +1,1333 @@
|
|
|
1
|
+
import { createCanvasKitRenderer, loadCanvasKit, FontRegistry, fetchFontBytes, SceneStore, TextLayoutCache, ChunkPictures, FramePipeline, FrameScheduler, IdleQueue, browserTimers, dropLargeCaches, repaintOnFontArrival, renderBounds, hitTest, visibleWorldRect, inPlaceFrame, ImageCache, repaintOnImageArrival, decodeThumbHash, } from "@daasboard/render-core";
|
|
2
|
+
import { SelectionModel, keepSelectionInDocument, builtinProperties, canHaveText, PropertyController, ToolManager, InteractionLayer, TextEditSession, InputSink, isMacPlatform, watchSessionFocus, caretWhileFocused, CameraInput, listenTrackpadGestures, createObjectClipboard, clipboardImageFiles, pasteOffset, TouchInput, normalizeTouchOptions, pointerHit, zoomAbout, visiblePart, revealCaret, } from "@daasboard/editor";
|
|
3
|
+
import { mountUi } from "@daasboard/ui";
|
|
4
|
+
import { clipboardCommand, clipboardDataOf, clipboardProxy, ContextPress, readSystemClipboard } from "./contextMenu.js";
|
|
5
|
+
import { BoardImages } from "./images/BoardImages.js";
|
|
6
|
+
import { createBoardDocument } from "./document.js";
|
|
7
|
+
import { boardCoordinates } from "./coordinates.js";
|
|
8
|
+
import { createEmbedUiHost } from "./uiHost.js";
|
|
9
|
+
import { BoardUiWiring, FocusLanding, mountOptions } from "./boardUi.js";
|
|
10
|
+
import { createBuiltinPolicy } from "./builtins.js";
|
|
11
|
+
let firstCanvasKitWasm;
|
|
12
|
+
const PAN_USES_GESTURE = false;
|
|
13
|
+
export async function createBoard(options) {
|
|
14
|
+
const { container, signal } = options;
|
|
15
|
+
if (signal?.aborted)
|
|
16
|
+
throw signal.reason;
|
|
17
|
+
const dom = container.ownerDocument;
|
|
18
|
+
const win = dom.defaultView;
|
|
19
|
+
if (!win || dom !== document)
|
|
20
|
+
throw new Error("createBoard: container must belong to the document that loaded @daasboard/embed");
|
|
21
|
+
if (!options.assets.canvasKitWasm || typeof options.assets.fontUrl !== "function")
|
|
22
|
+
throw new Error("createBoard: explicit wasm and font URLs are required");
|
|
23
|
+
if (options.images?.store.touch && !options.images.room)
|
|
24
|
+
throw new Error("createBoard: images.room is required for a store with touch");
|
|
25
|
+
const touchSettings = normalizeTouchOptions(options.touch);
|
|
26
|
+
const readOnly = options.readOnly ?? false;
|
|
27
|
+
const uiOptions = mountOptions(options.ui);
|
|
28
|
+
let session = null;
|
|
29
|
+
let sink = null;
|
|
30
|
+
let wiring;
|
|
31
|
+
let clipboard;
|
|
32
|
+
const builtins = createBuiltinPolicy(options.disableBuiltins, () => wiring?.options ?? uiOptions, (event) => !!session?.active && event.target === sink?.element, isMacPlatform());
|
|
33
|
+
const cleanups = [];
|
|
34
|
+
const mountAbort = new AbortController();
|
|
35
|
+
let rejectAbort;
|
|
36
|
+
const cancelled = new Promise((_, reject) => { rejectAbort = reject; });
|
|
37
|
+
const onAbort = () => { mountAbort.abort(signal.reason); rejectAbort(signal.reason); };
|
|
38
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
39
|
+
cleanups.push(() => signal?.removeEventListener("abort", onAbort));
|
|
40
|
+
const pending = (promise) => Promise.race([promise, cancelled]);
|
|
41
|
+
let disposed = false;
|
|
42
|
+
const dispose = () => {
|
|
43
|
+
if (disposed)
|
|
44
|
+
return;
|
|
45
|
+
disposed = true;
|
|
46
|
+
mountAbort.abort();
|
|
47
|
+
const errors = [];
|
|
48
|
+
for (const cleanup of cleanups.reverse())
|
|
49
|
+
try {
|
|
50
|
+
cleanup();
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
errors.push(error);
|
|
54
|
+
}
|
|
55
|
+
cleanups.length = 0;
|
|
56
|
+
if (errors.length)
|
|
57
|
+
throw new AggregateError(errors, "createBoard disposal failed");
|
|
58
|
+
};
|
|
59
|
+
const listen = (target, type, listener, opts) => {
|
|
60
|
+
target.addEventListener(type, listener, opts);
|
|
61
|
+
cleanups.push(() => target.removeEventListener(type, listener, opts));
|
|
62
|
+
};
|
|
63
|
+
try {
|
|
64
|
+
const element = dom.createElement("div");
|
|
65
|
+
element.setAttribute("data-daas-board", "");
|
|
66
|
+
element.style.cssText = "all:initial;display:block;position:relative;width:100%;height:100%;min-width:0;min-height:0;isolation:isolate";
|
|
67
|
+
const root = element.attachShadow({ mode: "open" });
|
|
68
|
+
const viewport = dom.createElement("div");
|
|
69
|
+
viewport.style.cssText = "all:initial;display:block;position:relative;width:100%;height:100%;overflow:hidden;direction:ltr";
|
|
70
|
+
const canvas = dom.createElement("canvas");
|
|
71
|
+
canvas.tabIndex = 0;
|
|
72
|
+
canvas.setAttribute("aria-label", readOnly ? "Board (read only)" : "Board");
|
|
73
|
+
canvas.style.cssText = "all:initial;display:block;position:absolute;inset:0;width:100%;height:100%;box-sizing:border-box;touch-action:none;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;outline:none";
|
|
74
|
+
viewport.append(canvas);
|
|
75
|
+
root.append(viewport);
|
|
76
|
+
container.append(element);
|
|
77
|
+
cleanups.push(() => element.remove());
|
|
78
|
+
const coords = boardCoordinates(viewport);
|
|
79
|
+
let typing = false;
|
|
80
|
+
for (const type of ["keydown", "keyup", "keypress", "beforeinput", "input", "compositionstart", "compositionupdate", "compositionend", "copy", "cut", "paste"]) {
|
|
81
|
+
listen(viewport, type, (e) => { typing = true; if (builtins.allows(e))
|
|
82
|
+
e.stopPropagation(); });
|
|
83
|
+
}
|
|
84
|
+
listen(viewport, "pointerdown", () => { typing = false; }, { capture: true });
|
|
85
|
+
const wasm = new URL(options.assets.canvasKitWasm, dom.baseURI).href;
|
|
86
|
+
if (firstCanvasKitWasm === undefined)
|
|
87
|
+
firstCanvasKitWasm = wasm;
|
|
88
|
+
else if (firstCanvasKitWasm !== wasm)
|
|
89
|
+
console.warn(`createBoard: CanvasKit is shared by this page. The first board requested ${firstCanvasKitWasm}; this board requested ${wasm}. A loaded module keeps its original wasm.`);
|
|
90
|
+
const renderer = await pending(createCanvasKitRenderer({ canvas, width: 1, height: 1, backend: options.backend ?? "gpu" }, () => loadCanvasKit({ locateFile: () => wasm }).catch((error) => {
|
|
91
|
+
if (firstCanvasKitWasm === wasm)
|
|
92
|
+
firstCanvasKitWasm = undefined;
|
|
93
|
+
throw error;
|
|
94
|
+
})).then((renderer) => {
|
|
95
|
+
if (disposed || mountAbort.signal.aborted) {
|
|
96
|
+
renderer.dispose();
|
|
97
|
+
throw mountAbort.signal.reason;
|
|
98
|
+
}
|
|
99
|
+
cleanups.push(() => renderer.dispose());
|
|
100
|
+
return renderer;
|
|
101
|
+
}));
|
|
102
|
+
const recovery = {};
|
|
103
|
+
let restorePending = false;
|
|
104
|
+
const retryContextRestore = () => {
|
|
105
|
+
if (disposed || !restorePending)
|
|
106
|
+
return;
|
|
107
|
+
try {
|
|
108
|
+
if (!(recovery.pipeline ?? renderer).handleContextRestored()) {
|
|
109
|
+
throw new Error("createBoard: WebGL context restoration failed");
|
|
110
|
+
}
|
|
111
|
+
restorePending = false;
|
|
112
|
+
recovery.images?.handleContextRestored();
|
|
113
|
+
recovery.idle?.invalidate();
|
|
114
|
+
recovery.loop?.setHidden(dom.hidden);
|
|
115
|
+
recovery.loop?.invalidate();
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
win.reportError(error);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
listen(canvas, "webglcontextlost", (event) => {
|
|
122
|
+
if (renderer.backend !== "gpu")
|
|
123
|
+
return;
|
|
124
|
+
event.preventDefault();
|
|
125
|
+
restorePending = false;
|
|
126
|
+
try {
|
|
127
|
+
try {
|
|
128
|
+
(recovery.pipeline ?? renderer).handleContextLost();
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
try {
|
|
132
|
+
recovery.images?.handleContextLost();
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
recovery.loop?.setHidden(true);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
win.reportError(error);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
listen(canvas, "webglcontextrestored", () => {
|
|
144
|
+
if (!renderer.contextLost)
|
|
145
|
+
return;
|
|
146
|
+
restorePending = true;
|
|
147
|
+
retryContextRestore();
|
|
148
|
+
});
|
|
149
|
+
listen(viewport, "pointerdown", retryContextRestore, { capture: true });
|
|
150
|
+
listen(dom, "visibilitychange", () => {
|
|
151
|
+
recovery.visibilityChanged?.();
|
|
152
|
+
if (!dom.hidden)
|
|
153
|
+
retryContextRestore();
|
|
154
|
+
recovery.loop?.setHidden(dom.hidden || renderer.contextLost);
|
|
155
|
+
});
|
|
156
|
+
renderer.setTextSliceBudget(4096);
|
|
157
|
+
const fonts = new FontRegistry(renderer, fetchFontBytes, { url: options.assets.fontUrl });
|
|
158
|
+
cleanups.push(() => fonts.dispose());
|
|
159
|
+
await pending(fonts.ready());
|
|
160
|
+
await pending(Promise.all((options.fonts ?? []).flatMap((family) => family.faces.map(async (face) => {
|
|
161
|
+
let bytes;
|
|
162
|
+
if (typeof face === "string") {
|
|
163
|
+
const request = new AbortController();
|
|
164
|
+
const abortRequest = () => request.abort(mountAbort.signal.reason);
|
|
165
|
+
if (mountAbort.signal.aborted)
|
|
166
|
+
abortRequest();
|
|
167
|
+
else
|
|
168
|
+
mountAbort.signal.addEventListener("abort", abortRequest, { once: true });
|
|
169
|
+
const timer = win.setTimeout(() => request.abort(new DOMException("Font request timed out", "TimeoutError")), 15_000);
|
|
170
|
+
try {
|
|
171
|
+
bytes = await fetchFontBytes(face, request.signal);
|
|
172
|
+
}
|
|
173
|
+
catch (cause) {
|
|
174
|
+
if (mountAbort.signal.aborted)
|
|
175
|
+
throw mountAbort.signal.reason;
|
|
176
|
+
const timedOut = request.signal.aborted && request.signal.reason?.name === "TimeoutError";
|
|
177
|
+
const error = new Error(`createBoard: font face ${face} ${timedOut ? "timed out" : "failed"}`, { cause });
|
|
178
|
+
if (timedOut)
|
|
179
|
+
error.name = "TimeoutError";
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
win.clearTimeout(timer);
|
|
184
|
+
mountAbort.signal.removeEventListener("abort", abortRequest);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
else
|
|
188
|
+
bytes = face;
|
|
189
|
+
if (mountAbort.signal.aborted)
|
|
190
|
+
throw mountAbort.signal.reason;
|
|
191
|
+
fonts.registerBytes(family.family, bytes);
|
|
192
|
+
}))));
|
|
193
|
+
const borrowed = createBoardDocument(options.document, readOnly);
|
|
194
|
+
const { doc, scene } = borrowed;
|
|
195
|
+
cleanups.push(() => borrowed.dispose());
|
|
196
|
+
const store = new SceneStore(scene);
|
|
197
|
+
const texts = new TextLayoutCache(renderer, fonts);
|
|
198
|
+
cleanups.push(() => texts.clear());
|
|
199
|
+
const chunks = new ChunkPictures(renderer, store, texts, 100);
|
|
200
|
+
cleanups.push(() => chunks.dispose());
|
|
201
|
+
const selection = new SelectionModel();
|
|
202
|
+
cleanups.push(keepSelectionInDocument(selection, doc));
|
|
203
|
+
const ctrl = new PropertyController(doc, builtinProperties(), selection);
|
|
204
|
+
cleanups.push(() => ctrl.dispose());
|
|
205
|
+
let imageInteraction = 0;
|
|
206
|
+
const noteImageInteraction = () => { imageInteraction++; };
|
|
207
|
+
cleanups.push(selection.onChange(noteImageInteraction), ctrl.subscribe(noteImageInteraction));
|
|
208
|
+
listen(viewport, "pointerdown", noteImageInteraction, { capture: true });
|
|
209
|
+
listen(viewport, "keydown", noteImageInteraction, { capture: true });
|
|
210
|
+
listen(viewport, "wheel", noteImageInteraction, { capture: true, passive: true });
|
|
211
|
+
const cam = { x: 0, y: 0, zoom: 1 };
|
|
212
|
+
const sameCamera = (a, b) => a.x === b.x && a.y === b.y && a.zoom === b.zoom;
|
|
213
|
+
let requestedCamera = { ...cam }, presentedCamera = { ...cam };
|
|
214
|
+
const translateCamera = (change) => {
|
|
215
|
+
const before = { ...cam };
|
|
216
|
+
if (sameCamera(cam, presentedCamera))
|
|
217
|
+
Object.assign(cam, requestedCamera);
|
|
218
|
+
const start = { ...cam };
|
|
219
|
+
change();
|
|
220
|
+
requestedCamera = { ...cam };
|
|
221
|
+
if (sameCamera(cam, start))
|
|
222
|
+
Object.assign(cam, before);
|
|
223
|
+
};
|
|
224
|
+
const pixelRatio = () => Math.min(4, Math.min(win.devicePixelRatio || 1, 2) * Math.max(1, coords.scale()));
|
|
225
|
+
let dpr = pixelRatio(), width = 1, height = 1;
|
|
226
|
+
let loop;
|
|
227
|
+
let touchInput;
|
|
228
|
+
const invalidate = () => { if (!disposed)
|
|
229
|
+
loop?.invalidate(); };
|
|
230
|
+
const idle = recovery.idle = new IdleQueue({ store, chunks, texts, onLayout: invalidate, settleMs: 150,
|
|
231
|
+
onPlan: (viewport, zoom) => images.updateDemand(store, viewport, zoom),
|
|
232
|
+
});
|
|
233
|
+
cleanups.push(() => idle.clear());
|
|
234
|
+
cleanups.push(repaintOnFontArrival({ fonts, texts, chunks, store, onChange: () => { idle.invalidate(); invalidate(); } }));
|
|
235
|
+
let blinkTimer;
|
|
236
|
+
let ui;
|
|
237
|
+
let landing;
|
|
238
|
+
let intentionalEnd = false;
|
|
239
|
+
let escape = false;
|
|
240
|
+
let keyGraceUntil = 0;
|
|
241
|
+
const tools = new ToolManager(store, selection, ctrl, {
|
|
242
|
+
reparentOnDrop: options.document.carriesDescendants === true,
|
|
243
|
+
onCreated: (id, kind) => { if (kind === "text")
|
|
244
|
+
startTextEdit(id, undefined, true); },
|
|
245
|
+
});
|
|
246
|
+
cleanups.push(tools.onToolChange(noteImageInteraction));
|
|
247
|
+
const overlay = new InteractionLayer(store, selection, ctrl, texts);
|
|
248
|
+
let excluded = new Set(), textExcluded = new Set();
|
|
249
|
+
const syncExcluded = () => {
|
|
250
|
+
const drag = overlay.previewIds(), text = overlay.textEditIds();
|
|
251
|
+
const diff = (a, b) => [...a].filter((id) => !b.has(id)).concat([...b].filter((id) => !a.has(id)));
|
|
252
|
+
const changed = [...diff(drag, excluded), ...diff(text, textExcluded)];
|
|
253
|
+
if (changed.length) {
|
|
254
|
+
for (const id of changed) {
|
|
255
|
+
const o = scene.objects.get(id);
|
|
256
|
+
if (o)
|
|
257
|
+
store.addDamage(renderBounds(o));
|
|
258
|
+
}
|
|
259
|
+
chunks.setExcluded(drag);
|
|
260
|
+
chunks.setTextExcluded(text);
|
|
261
|
+
store.setDamageSuppressed(text);
|
|
262
|
+
excluded = drag;
|
|
263
|
+
textExcluded = text;
|
|
264
|
+
idle.invalidate();
|
|
265
|
+
}
|
|
266
|
+
invalidate();
|
|
267
|
+
};
|
|
268
|
+
cleanups.push(ctrl.subscribe(syncExcluded));
|
|
269
|
+
cleanups.push(selection.onChange(invalidate));
|
|
270
|
+
cleanups.push(doc.subscribe((cs) => {
|
|
271
|
+
store.apply(cs);
|
|
272
|
+
const refreshed = store.takeRefreshedConnectors();
|
|
273
|
+
if (cs.reordered)
|
|
274
|
+
chunks.rebuild();
|
|
275
|
+
else if (cs.added.length)
|
|
276
|
+
chunks.add(cs.added.map((o) => o.id));
|
|
277
|
+
chunks.invalidate([...cs.added.map((o) => o.id), ...cs.updated.map((o) => o.id), ...cs.removed, ...refreshed]);
|
|
278
|
+
idle.invalidate();
|
|
279
|
+
invalidate();
|
|
280
|
+
}));
|
|
281
|
+
const visible = () => visibleWorldRect(cam, dpr, width, height);
|
|
282
|
+
const imageNotice = dom.createElement("div");
|
|
283
|
+
imageNotice.setAttribute("role", "status");
|
|
284
|
+
imageNotice.style.cssText = "position:absolute;bottom:12px;left:12px;background:white;color:#222;padding:6px 10px;font:13px sans-serif;pointer-events:none;z-index:2";
|
|
285
|
+
imageNotice.hidden = true;
|
|
286
|
+
viewport.append(imageNotice);
|
|
287
|
+
const notifyImage = (message) => { imageNotice.textContent = message; imageNotice.hidden = !message; };
|
|
288
|
+
let scaledNotice = "";
|
|
289
|
+
const uploadPreviews = new Map();
|
|
290
|
+
const positionUploads = () => {
|
|
291
|
+
for (const [placement, preview] of uploadPreviews) {
|
|
292
|
+
preview.element.style.left = `${(placement.at.x - preview.w / 2 - cam.x) * cam.zoom}px`;
|
|
293
|
+
preview.element.style.top = `${(placement.at.y - preview.h / 2 - cam.y) * cam.zoom}px`;
|
|
294
|
+
preview.element.style.width = `${preview.w * cam.zoom}px`;
|
|
295
|
+
preview.element.style.height = `${preview.h * cam.zoom}px`;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
let waitingReferences = 0;
|
|
299
|
+
const imageOps = new BoardImages({ document: doc,
|
|
300
|
+
...(options.images ? { images: options.images } : {}),
|
|
301
|
+
canWrite: () => !readOnly && !disposed && !dom.hidden,
|
|
302
|
+
commit: (refs, placement) => ctrl.insertImages(refs, placement),
|
|
303
|
+
onError: (hash, rung, reason) => { notifyImage(`Image unavailable: ${reason}`); options.onImageError?.(hash, rung, reason); },
|
|
304
|
+
onScaled: (facts) => { scaledNotice = `Image scaled to ${facts.width} × ${facts.height}`; notifyImage(scaledNotice); options.onImageScaled?.(facts); },
|
|
305
|
+
onPrepared: (prepared, placement) => {
|
|
306
|
+
const thumb = decodeThumbHash(prepared.thumb);
|
|
307
|
+
if (!thumb)
|
|
308
|
+
return;
|
|
309
|
+
uploadPreviews.get(placement)?.element.remove();
|
|
310
|
+
const preview = dom.createElement("canvas");
|
|
311
|
+
preview.width = thumb.w;
|
|
312
|
+
preview.height = thumb.h;
|
|
313
|
+
preview.setAttribute("aria-label", "Storing image. Press Escape to cancel.");
|
|
314
|
+
preview.style.cssText = "position:absolute;pointer-events:none;opacity:.7;outline:1px dashed #6574cd";
|
|
315
|
+
preview.getContext("2d")?.putImageData(new ImageData(new Uint8ClampedArray(thumb.rgba), thumb.w, thumb.h), 0, 0);
|
|
316
|
+
const scale = Math.min(1, placement.visible.w / prepared.w, placement.visible.h / prepared.h);
|
|
317
|
+
uploadPreviews.set(placement, { element: preview, w: prepared.w * scale, h: prepared.h * scale });
|
|
318
|
+
viewport.append(preview);
|
|
319
|
+
positionUploads();
|
|
320
|
+
notifyImage("Storing image. Press Escape to cancel.");
|
|
321
|
+
},
|
|
322
|
+
onProgress: (sent, total) => notifyImage(`Storing image: ${total ? Math.round(sent / total * 100) : 0}%`),
|
|
323
|
+
onReferencePending: () => {
|
|
324
|
+
waitingReferences++;
|
|
325
|
+
notifyImage("Waiting for images. Press Escape to cancel.");
|
|
326
|
+
return () => {
|
|
327
|
+
waitingReferences--;
|
|
328
|
+
if (!waitingReferences && imageNotice.textContent?.startsWith("Waiting for images"))
|
|
329
|
+
notifyImage("");
|
|
330
|
+
};
|
|
331
|
+
},
|
|
332
|
+
});
|
|
333
|
+
cleanups.push(() => imageOps.dispose());
|
|
334
|
+
let imageCancels = 0;
|
|
335
|
+
const cancelImageInserts = () => {
|
|
336
|
+
imageCancels++;
|
|
337
|
+
imageOps.cancel();
|
|
338
|
+
for (const preview of uploadPreviews.values())
|
|
339
|
+
preview.element.remove();
|
|
340
|
+
uploadPreviews.clear();
|
|
341
|
+
if (/^(Storing image|Waiting for images)/.test(imageNotice.textContent ?? ""))
|
|
342
|
+
notifyImage("");
|
|
343
|
+
};
|
|
344
|
+
const idleForImageSelection = () => !session && !ctrl.hasPreview() && !loop?.gestureActive && !loop?.cameraMoving
|
|
345
|
+
&& pointer === null && !touchInput?.active && tools.active === "select" && tools.select.state().mode === "idle";
|
|
346
|
+
const imageContext = () => ({ revision: imageInteraction, maySelect: idleForImageSelection() });
|
|
347
|
+
const unchangedSince = (since) => since.maySelect && since.revision === imageInteraction && idleForImageSelection();
|
|
348
|
+
let pasteSince = null;
|
|
349
|
+
const insertImagesSince = async (files, at, since) => {
|
|
350
|
+
scaledNotice = "";
|
|
351
|
+
const v = visible();
|
|
352
|
+
const placement = { at: at ?? { x: v.x + v.w / 2, y: v.y + v.h / 2 }, visible: v };
|
|
353
|
+
try {
|
|
354
|
+
return await imageOps.insert(files, placement, (refs, target) => ctrl.insertImages(refs, {
|
|
355
|
+
...target, select: unchangedSince(since),
|
|
356
|
+
}));
|
|
357
|
+
}
|
|
358
|
+
finally {
|
|
359
|
+
uploadPreviews.get(placement)?.element.remove();
|
|
360
|
+
uploadPreviews.delete(placement);
|
|
361
|
+
if (imageNotice.textContent?.startsWith("Storing image"))
|
|
362
|
+
notifyImage(scaledNotice);
|
|
363
|
+
invalidate();
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
const insertImages = (files, at) => insertImagesSince(files, at, imageContext());
|
|
367
|
+
const picker = dom.createElement("input");
|
|
368
|
+
picker.type = "file";
|
|
369
|
+
picker.multiple = true;
|
|
370
|
+
picker.hidden = true;
|
|
371
|
+
picker.accept = ["image/png", "image/jpeg", "image/gif", "image/webp", ...(options.images?.store.renders ?? [])].join(",");
|
|
372
|
+
viewport.append(picker);
|
|
373
|
+
listen(picker, "change", () => { const files = [...(picker.files ?? [])]; picker.value = ""; void insertImages(files); });
|
|
374
|
+
const pickImages = () => { if (!disposed && !readOnly && options.images)
|
|
375
|
+
picker.click(); };
|
|
376
|
+
const images = recovery.images = new ImageCache({ renderer, onWork: invalidate, load: (hash, rung, opts) => imageOps.get(hash, rung, opts),
|
|
377
|
+
...(options.images?.store.refreshUrl ? { refreshUrl: imageOps.refreshUrl.bind(imageOps) } : {}),
|
|
378
|
+
canDecode: () => !disposed && !dom.hidden && !loop?.gestureActive && !loop?.cameraMoving && loop?.tier !== "deep",
|
|
379
|
+
...(options.memory?.images === undefined ? {} : { budgetBytes: options.memory.images }),
|
|
380
|
+
onError: (hash, rung, reason) => imageOps.report(hash, rung, reason === "unavailable" ? "network" : reason),
|
|
381
|
+
});
|
|
382
|
+
chunks.setImages(images);
|
|
383
|
+
overlay.setImages(images);
|
|
384
|
+
images.setSuspended(dom.hidden);
|
|
385
|
+
cleanups.push(() => images.dispose());
|
|
386
|
+
const imageArrivals = repaintOnImageArrival({ images, chunks, store, defer: true, onChange: invalidate });
|
|
387
|
+
cleanups.push(imageArrivals);
|
|
388
|
+
const handleClipboard = (e) => {
|
|
389
|
+
if (disposed || session?.active || e.defaultPrevented || !builtins.allows(e) || !e.clipboardData || !clipboard)
|
|
390
|
+
return false;
|
|
391
|
+
if (e.type === "paste" && !readOnly && options.images) {
|
|
392
|
+
const files = clipboardImageFiles(e.clipboardData, dom);
|
|
393
|
+
if (files.length) {
|
|
394
|
+
e.preventDefault();
|
|
395
|
+
void insertImages(files);
|
|
396
|
+
return true;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
const pasted = e.type === "paste" ? clipboard.paste(e.clipboardData) : null;
|
|
400
|
+
const handled = e.type === "copy" ? clipboard.copy(e.clipboardData) !== null
|
|
401
|
+
: e.type === "cut" ? clipboard.cut(e.clipboardData) !== null
|
|
402
|
+
: !!pasted && (pasted.ids.length > 0 || pasted.pending !== null);
|
|
403
|
+
if (handled)
|
|
404
|
+
e.preventDefault();
|
|
405
|
+
return handled;
|
|
406
|
+
};
|
|
407
|
+
let hides = 0;
|
|
408
|
+
const proxy = clipboardProxy(dom);
|
|
409
|
+
viewport.append(proxy);
|
|
410
|
+
const menuCommand = (op) => {
|
|
411
|
+
if (disposed || !builtins.enabled(op) || (readOnly && op === "cut"))
|
|
412
|
+
return;
|
|
413
|
+
if (session?.active) {
|
|
414
|
+
if (sink)
|
|
415
|
+
clipboardCommand(dom, op, sink);
|
|
416
|
+
}
|
|
417
|
+
else
|
|
418
|
+
clipboardCommand(dom, op, proxy, () => { if (root.activeElement === proxy)
|
|
419
|
+
proxy.blur(); });
|
|
420
|
+
};
|
|
421
|
+
const menuClipboard = {
|
|
422
|
+
canCopy: () => session?.active ? !session.state.selection.empty : ctrl.targets().length > 0,
|
|
423
|
+
canPaste: () => typeof win.navigator.clipboard?.read === "function",
|
|
424
|
+
copy: () => menuCommand("copy"),
|
|
425
|
+
cut: () => menuCommand("cut"),
|
|
426
|
+
paste(at) {
|
|
427
|
+
if (disposed || readOnly || !builtins.enabled("paste"))
|
|
428
|
+
return;
|
|
429
|
+
const target = session?.active ? session : null;
|
|
430
|
+
const picked = target?.state, hidden = hides, cancels = imageCancels, since = imageContext();
|
|
431
|
+
const point = at && !target ? { x: cam.x + at.x / cam.zoom, y: cam.y + at.y / cam.zoom } : null;
|
|
432
|
+
void readSystemClipboard(win.navigator).then((content) => {
|
|
433
|
+
if (!content || disposed || dom.hidden || hides !== hidden)
|
|
434
|
+
return;
|
|
435
|
+
if (target ? session !== target || !target.active || target.state !== picked : session?.active || imageCancels !== cancels)
|
|
436
|
+
return;
|
|
437
|
+
if (target)
|
|
438
|
+
target.pasteClipboard({ html: content.html, text: content.text, richText: "" });
|
|
439
|
+
else {
|
|
440
|
+
const files = options.images ? clipboardImageFiles(clipboardDataOf(content), dom) : [];
|
|
441
|
+
if (files.length)
|
|
442
|
+
void insertImagesSince(files, point ?? undefined, since);
|
|
443
|
+
else {
|
|
444
|
+
pasteSince = since;
|
|
445
|
+
try {
|
|
446
|
+
if (point)
|
|
447
|
+
clipboard?.pasteAt(point, content);
|
|
448
|
+
else
|
|
449
|
+
clipboard?.paste(content);
|
|
450
|
+
}
|
|
451
|
+
finally {
|
|
452
|
+
pasteSince = null;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
invalidate();
|
|
457
|
+
});
|
|
458
|
+
},
|
|
459
|
+
};
|
|
460
|
+
const host = createEmbedUiHost({
|
|
461
|
+
ctrl, tools, selection, store, cam, canvas, size: () => ({ width: viewport.clientWidth, height: viewport.clientHeight }),
|
|
462
|
+
ids: () => scene.objects.keys(), sink: () => sink, invalidate, readOnly,
|
|
463
|
+
...(options.fonts ? { fonts: options.fonts } : {}), ...(options.lookupLink ? {
|
|
464
|
+
lookupLink: (url) => imageOps.lookupLink(() => options.lookupLink(url)),
|
|
465
|
+
} : {}), ...(options.images ? { insertImages: pickImages } : {}),
|
|
466
|
+
gradientHandles: { show: (target, events, opts) => tools.select.showGradientHandles(target, events, opts), hits: (e) => onGradientHandle(e) },
|
|
467
|
+
allowsKey: (e) => builtins.allows(e), handleClipboard,
|
|
468
|
+
allows: (operation) => builtins.enabled(operation), clipboard: menuClipboard,
|
|
469
|
+
});
|
|
470
|
+
cleanups.push(() => host.dispose());
|
|
471
|
+
const endTextEdit = () => {
|
|
472
|
+
intentionalEnd = true;
|
|
473
|
+
try {
|
|
474
|
+
session?.end();
|
|
475
|
+
}
|
|
476
|
+
finally {
|
|
477
|
+
intentionalEnd = false;
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
const shown = () => {
|
|
481
|
+
if (!coords.axisAligned())
|
|
482
|
+
return null;
|
|
483
|
+
const v = win.visualViewport;
|
|
484
|
+
const a = v && coords.local({ x: v.offsetLeft, y: v.offsetTop }), b = v && coords.local({ x: v.offsetLeft + v.width, y: v.offsetTop + v.height });
|
|
485
|
+
return visiblePart({ x: 0, y: 0, w: viewport.clientWidth, h: viewport.clientHeight }, a && b && { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), w: Math.abs(b.x - a.x), h: Math.abs(b.y - a.y) });
|
|
486
|
+
};
|
|
487
|
+
let viewChanged = false;
|
|
488
|
+
let caretKey = null;
|
|
489
|
+
const onView = () => { viewChanged = true; invalidate(); };
|
|
490
|
+
const viewListeners = (on) => { for (const type of ["resize", "scroll"])
|
|
491
|
+
win.visualViewport?.[on ? "addEventListener" : "removeEventListener"](type, onView); };
|
|
492
|
+
function startTextEdit(id, at, fresh = false) {
|
|
493
|
+
if (readOnly || disposed || !builtins.enabled("textEditing"))
|
|
494
|
+
return;
|
|
495
|
+
if (session?.objectId === id && session.active)
|
|
496
|
+
return;
|
|
497
|
+
endTextEdit();
|
|
498
|
+
const object = doc.get(id);
|
|
499
|
+
if (!object || !canHaveText(object))
|
|
500
|
+
return;
|
|
501
|
+
const s = new TextEditSession({
|
|
502
|
+
objectId: id, doc, renderer, texts, fallbacks: () => fonts.fallbacks, selection,
|
|
503
|
+
toClient: (p) => ({ x: (p.x - cam.x) * cam.zoom, y: (p.y - cam.y) * cam.zoom }),
|
|
504
|
+
onChange: invalidate, now: () => win.performance.now(), discardIfUntouched: fresh,
|
|
505
|
+
onEnd: () => {
|
|
506
|
+
if (session !== s)
|
|
507
|
+
return;
|
|
508
|
+
session = null;
|
|
509
|
+
viewListeners(false);
|
|
510
|
+
caretKey = null;
|
|
511
|
+
win.clearInterval(blinkTimer);
|
|
512
|
+
blinkTimer = undefined;
|
|
513
|
+
const heldKeyboard = root.activeElement === sink?.element;
|
|
514
|
+
sink?.detach();
|
|
515
|
+
sink = null;
|
|
516
|
+
overlay.setTextSession(null);
|
|
517
|
+
tools.setTextEditing(null);
|
|
518
|
+
ctrl.setTextTarget(null);
|
|
519
|
+
if (!intentionalEnd && !escape)
|
|
520
|
+
keyGraceUntil = win.performance.now() + 1000;
|
|
521
|
+
if (heldKeyboard && !disposed)
|
|
522
|
+
canvas.focus({ preventScroll: true });
|
|
523
|
+
invalidate();
|
|
524
|
+
},
|
|
525
|
+
});
|
|
526
|
+
session = s;
|
|
527
|
+
const sinkOptions = {
|
|
528
|
+
handleEvent: (event) => builtins.allows(event),
|
|
529
|
+
createElement: () => dom.createElement("div"),
|
|
530
|
+
isActiveElement: (el) => root.activeElement === el,
|
|
531
|
+
keepsSession: (to) => (ui?.owns(to) ?? false) || (landing?.waits(to) ?? false),
|
|
532
|
+
local: (p) => coords.local(p),
|
|
533
|
+
bounds: shown,
|
|
534
|
+
};
|
|
535
|
+
const own = sink = new InputSink(viewport, s, sinkOptions);
|
|
536
|
+
sink.element.style.cssText += ";position:absolute";
|
|
537
|
+
sink.attach();
|
|
538
|
+
sink.focus();
|
|
539
|
+
viewListeners(true);
|
|
540
|
+
overlay.setTextSession(caretWhileFocused(s, () => root.activeElement === own.element));
|
|
541
|
+
tools.setTextEditing(id);
|
|
542
|
+
ctrl.setTextTarget(s);
|
|
543
|
+
if (at) {
|
|
544
|
+
s.pointer(at, "down");
|
|
545
|
+
s.pointer(at, "up");
|
|
546
|
+
}
|
|
547
|
+
blinkTimer = win.setInterval(() => { own.poll(); invalidate(); }, 500);
|
|
548
|
+
invalidate();
|
|
549
|
+
}
|
|
550
|
+
tools.select.onEditText = startTextEdit;
|
|
551
|
+
cleanups.push(endTextEdit);
|
|
552
|
+
if (uiOptions) {
|
|
553
|
+
const mounted = ui = mountUi(viewport, host, uiOptions);
|
|
554
|
+
cleanups.push(() => mounted.dispose());
|
|
555
|
+
const settle = landing = new FocusLanding({
|
|
556
|
+
places: () => [viewport, ...(wiring?.containers ?? [])],
|
|
557
|
+
inside: (el) => el === sink?.element || mounted.owns(el),
|
|
558
|
+
end: () => session?.blur(),
|
|
559
|
+
timers: { setTimeout: (fn, ms) => win.setTimeout(fn, ms), clearTimeout: (id) => win.clearTimeout(id) },
|
|
560
|
+
});
|
|
561
|
+
cleanups.push(() => settle.dispose());
|
|
562
|
+
const owns = (t) => mounted.owns(t) || settle.waits(t);
|
|
563
|
+
const focused = () => settle.focused();
|
|
564
|
+
cleanups.push(watchSessionFocus({ container: viewport, session: () => session, sink: () => sink?.element, owns, activeElement: focused, onChange: invalidate }));
|
|
565
|
+
const live = wiring = new BoardUiWiring(mounted, uiOptions, (container) => watchSessionFocus({
|
|
566
|
+
container, session: () => session, sink: () => sink?.element, owns, activeElement: focused,
|
|
567
|
+
}), (v) => v instanceof win.HTMLElement);
|
|
568
|
+
cleanups.push(() => live.dispose());
|
|
569
|
+
listen(canvas, "focus", () => { if (session)
|
|
570
|
+
endTextEdit(); });
|
|
571
|
+
}
|
|
572
|
+
listen(viewport, "keydown", (e) => {
|
|
573
|
+
escape = builtins.allows(e) && e.key === "Escape" && e.target === sink?.element;
|
|
574
|
+
}, { capture: true });
|
|
575
|
+
listen(viewport, "keydown", () => { escape = false; });
|
|
576
|
+
clipboard = createObjectClipboard({
|
|
577
|
+
controller: ctrl, viewport: visible, ownerDocument: dom,
|
|
578
|
+
readOnly: () => readOnly || disposed, activeText: () => !!session?.active || disposed,
|
|
579
|
+
onError: (error) => win.reportError(error),
|
|
580
|
+
share: (hash) => options.images?.store.share?.(hash) ?? null,
|
|
581
|
+
insert: (objects, placement, commit, assets) => {
|
|
582
|
+
const since = pasteSince ?? imageContext();
|
|
583
|
+
let deferred = pasteSince !== null;
|
|
584
|
+
const parents = Object.values(placement.parents ?? {}).filter((id) => !!id);
|
|
585
|
+
const result = imageOps.withReferences(objects, (ready) => commit(ready, {
|
|
586
|
+
select: !deferred || unchangedSince(since),
|
|
587
|
+
}), { valid: () => parents.every((id) => !!doc.get(id)), ...(assets ? { assets } : {}) });
|
|
588
|
+
if (!(result instanceof Promise))
|
|
589
|
+
return result;
|
|
590
|
+
deferred = true;
|
|
591
|
+
const offset = pasteOffset(objects, placement);
|
|
592
|
+
const previews = [];
|
|
593
|
+
for (const object of objects) {
|
|
594
|
+
const ref = object.image ?? object.embed?.preview ?? object.embed?.icon;
|
|
595
|
+
if (!ref)
|
|
596
|
+
continue;
|
|
597
|
+
const thumb = decodeThumbHash(ref.thumb);
|
|
598
|
+
const preview = dom.createElement("canvas");
|
|
599
|
+
preview.width = thumb?.w ?? 1;
|
|
600
|
+
preview.height = thumb?.h ?? 1;
|
|
601
|
+
preview.setAttribute("aria-label", "Waiting for images. Press Escape to cancel.");
|
|
602
|
+
preview.style.cssText = "position:absolute;pointer-events:none;opacity:.7;background:#e5e7eb;outline:1px dashed #6574cd";
|
|
603
|
+
if (thumb)
|
|
604
|
+
preview.getContext("2d")?.putImageData(new ImageData(new Uint8ClampedArray(thumb.rgba), thumb.w, thumb.h), 0, 0);
|
|
605
|
+
const target = { at: { x: object.x + offset.x + object.w / 2, y: object.y + offset.y + object.h / 2 }, visible: visible() };
|
|
606
|
+
previews.push(target);
|
|
607
|
+
uploadPreviews.set(target, { element: preview, w: object.w, h: object.h });
|
|
608
|
+
viewport.append(preview);
|
|
609
|
+
}
|
|
610
|
+
positionUploads();
|
|
611
|
+
return result.finally(() => {
|
|
612
|
+
for (const target of previews) {
|
|
613
|
+
uploadPreviews.get(target)?.element.remove();
|
|
614
|
+
uploadPreviews.delete(target);
|
|
615
|
+
}
|
|
616
|
+
invalidate();
|
|
617
|
+
});
|
|
618
|
+
},
|
|
619
|
+
parentAt: (point, excludedIds) => options.document.carriesDescendants === true
|
|
620
|
+
? hitTest(store, point.x, point.y).find((object) => !excludedIds.has(object.id)
|
|
621
|
+
&& (object.kind === "frame" || object.kind === "section"))?.id ?? null : null,
|
|
622
|
+
measureText: (object) => {
|
|
623
|
+
try {
|
|
624
|
+
return texts.measureHeight(object);
|
|
625
|
+
}
|
|
626
|
+
finally {
|
|
627
|
+
texts.invalidate(object.id);
|
|
628
|
+
}
|
|
629
|
+
},
|
|
630
|
+
});
|
|
631
|
+
for (const type of ["copy", "cut", "paste"])
|
|
632
|
+
listen(canvas, type, handleClipboard);
|
|
633
|
+
for (const type of ["copy", "cut"])
|
|
634
|
+
listen(proxy, type, handleClipboard);
|
|
635
|
+
const pipeline = recovery.pipeline = new FramePipeline({ renderer, store, background: [0.95, 0.96, 0.97, 1], width, height, dpr,
|
|
636
|
+
paintWorld: (ctx, world, variant, zoom) => chunks.draw(ctx, world, variant, zoom).drawn,
|
|
637
|
+
});
|
|
638
|
+
cleanups.push(() => pipeline.dispose());
|
|
639
|
+
const resize = () => {
|
|
640
|
+
if (disposed)
|
|
641
|
+
return;
|
|
642
|
+
dpr = pixelRatio();
|
|
643
|
+
width = Math.max(1, Math.floor(viewport.clientWidth * dpr));
|
|
644
|
+
height = Math.max(1, Math.floor(viewport.clientHeight * dpr));
|
|
645
|
+
renderer.resize(width, height);
|
|
646
|
+
pipeline.resize(width, height, dpr);
|
|
647
|
+
invalidate();
|
|
648
|
+
};
|
|
649
|
+
const observer = new ResizeObserver(resize);
|
|
650
|
+
observer.observe(container);
|
|
651
|
+
cleanups.push(() => observer.disconnect());
|
|
652
|
+
let resolution;
|
|
653
|
+
let watchedDpr = win.devicePixelRatio || 1;
|
|
654
|
+
const watchResolution = () => {
|
|
655
|
+
resolution?.removeEventListener("change", onResolution);
|
|
656
|
+
watchedDpr = win.devicePixelRatio || 1;
|
|
657
|
+
resolution = win.matchMedia(`(resolution: ${watchedDpr}dppx)`);
|
|
658
|
+
resolution.addEventListener("change", onResolution);
|
|
659
|
+
};
|
|
660
|
+
const onResolution = () => { if (!disposed) {
|
|
661
|
+
watchResolution();
|
|
662
|
+
resize();
|
|
663
|
+
} };
|
|
664
|
+
watchResolution();
|
|
665
|
+
cleanups.push(() => resolution.removeEventListener("change", onResolution));
|
|
666
|
+
resize();
|
|
667
|
+
const timers = browserTimers();
|
|
668
|
+
const loopTimers = { ...timers, requestFrame: (cb) => timers.requestFrame((ts) => { touchInput?.flush(); cb(ts); }) };
|
|
669
|
+
loop = recovery.loop = new FrameScheduler((frame) => {
|
|
670
|
+
if (renderer.contextLost)
|
|
671
|
+
return;
|
|
672
|
+
imageArrivals.flush();
|
|
673
|
+
if (dpr !== pixelRatio())
|
|
674
|
+
resize();
|
|
675
|
+
const s = mode || touchInput?.active ? null : session;
|
|
676
|
+
if (s) {
|
|
677
|
+
const key = s.preedit()?.to ?? s.state;
|
|
678
|
+
const c = (viewChanged || (typing && key !== caretKey)) && s.caretClientRect(), v = c && shown();
|
|
679
|
+
const d = c && v ? revealCaret(c, v) : null;
|
|
680
|
+
if (d && (d.x || d.y))
|
|
681
|
+
translateCamera(() => { cam.x -= d.x / cam.zoom; cam.y -= d.y / cam.zoom; });
|
|
682
|
+
caretKey = key;
|
|
683
|
+
viewChanged = false;
|
|
684
|
+
}
|
|
685
|
+
positionUploads();
|
|
686
|
+
if (!sameCamera(cam, presentedCamera))
|
|
687
|
+
requestedCamera = { ...cam };
|
|
688
|
+
pipeline.render(cam, { gesture: frame.gesture, variant: frame.variant,
|
|
689
|
+
inPlace: inPlaceFrame(overlay.inPlace(), cam.zoom * dpr, store, texts, chunks),
|
|
690
|
+
overlay: (ctx) => overlay.draw(ctx, tools.state(), { zoom: cam.zoom * dpr, viewport: visible(), now: win.performance.now(), previewsInPlace: true, textHandles: lastPress === "touch" ? dpr : 0 }),
|
|
691
|
+
});
|
|
692
|
+
presentedCamera = { ...cam };
|
|
693
|
+
sink?.updatePosition();
|
|
694
|
+
host.syncCamera();
|
|
695
|
+
if (!frame.gesture)
|
|
696
|
+
idle.setViewport(visible(), cam.zoom * dpr);
|
|
697
|
+
}, { timers: loopTimers });
|
|
698
|
+
cleanups.push(() => loop?.stop());
|
|
699
|
+
loop.setIdleWork((budget) => {
|
|
700
|
+
if (renderer.contextLost)
|
|
701
|
+
return false;
|
|
702
|
+
imageArrivals.flush();
|
|
703
|
+
const pendingImages = images.runIdle();
|
|
704
|
+
return (loop.gestureActive || loop.cameraMoving ? idle.runVisible(budget) : idle.run(budget)) || pendingImages;
|
|
705
|
+
});
|
|
706
|
+
cleanups.push(loop.onTier((tier) => {
|
|
707
|
+
images.setSuspended(dom.hidden || tier === "deep");
|
|
708
|
+
if (tier === "deep")
|
|
709
|
+
dropLargeCaches({ chunks, keep: visible(), raster: pipeline.raster, texts, keepTexts: textExcluded, renderer, idle });
|
|
710
|
+
}));
|
|
711
|
+
cleanups.push(host.onGestureSources((sources) => {
|
|
712
|
+
if (sources.size)
|
|
713
|
+
noteImageInteraction();
|
|
714
|
+
const moving = sources.has("pan") || sources.has("fling") || sources.has("scroll");
|
|
715
|
+
loop?.setCameraMoving(moving);
|
|
716
|
+
loop?.forceGesture(sources.has("tool") || sources.has("zoom") || sources.has("wheel") || (PAN_USES_GESTURE && moving));
|
|
717
|
+
}));
|
|
718
|
+
const local = (e) => coords.local({ x: e.clientX, y: e.clientY });
|
|
719
|
+
const cameraInput = new CameraInput({
|
|
720
|
+
camera: cam,
|
|
721
|
+
local: (x, y) => coords.local({ x, y }),
|
|
722
|
+
size: () => ({ width: viewport.clientWidth, height: viewport.clientHeight }),
|
|
723
|
+
onChange: (kind) => { host.wheel(kind); invalidate(); },
|
|
724
|
+
timers: browserTimers(),
|
|
725
|
+
});
|
|
726
|
+
cleanups.push(() => cameraInput.dispose());
|
|
727
|
+
const world = (e) => { const p = local(e); return { x: cam.x + p.x / cam.zoom, y: cam.y + p.y / cam.zoom }; };
|
|
728
|
+
listen(viewport, "dragover", (e) => {
|
|
729
|
+
if (!readOnly && options.images && e.dataTransfer?.types.includes("Files")) {
|
|
730
|
+
e.preventDefault();
|
|
731
|
+
e.dataTransfer.dropEffect = "copy";
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
listen(viewport, "drop", (e) => {
|
|
735
|
+
if (readOnly || !options.images || !e.dataTransfer?.files.length)
|
|
736
|
+
return;
|
|
737
|
+
e.preventDefault();
|
|
738
|
+
void insertImages([...e.dataTransfer.files], world(e));
|
|
739
|
+
});
|
|
740
|
+
const info = (e) => {
|
|
741
|
+
const type = e.pointerType ?? e.pointer;
|
|
742
|
+
return { ...world(e), shift: e.shiftKey, alt: e.altKey, snapOff: isMacPlatform() ? e.metaKey : e.ctrlKey, tolerance: 4 / cam.zoom, zoom: cam.zoom * dpr, ...(type === "touch" || type === "pen" ? { pointer: type } : {}) };
|
|
743
|
+
};
|
|
744
|
+
const insideSession = (e) => !!session && pointerHit(store, info(e))?.id === session.objectId;
|
|
745
|
+
const onGradientHandleAt = (e) => !space && !session && !readOnly && tools.active === "select" && tools.select.gradientHandleAt(info(e)) !== null;
|
|
746
|
+
const onGradientHandle = (e) => e.target === canvas && e.button === 0 && onGradientHandleAt(e);
|
|
747
|
+
let pointer = null;
|
|
748
|
+
const contextPress = new ContextPress((at) => ui?.openContextMenu(at) ?? false);
|
|
749
|
+
const menuOn = () => !!ui && (wiring?.options ?? uiOptions)?.contextMenu !== false;
|
|
750
|
+
let mode = null;
|
|
751
|
+
let grabbed = null;
|
|
752
|
+
let wordTap = 0;
|
|
753
|
+
let space = false, last = { x: 0, y: 0 }, lastMove = 0, velocity = { x: 0, y: 0 };
|
|
754
|
+
let flingFrame;
|
|
755
|
+
const stopFling = () => { if (flingFrame !== undefined)
|
|
756
|
+
win.cancelAnimationFrame(flingFrame); flingFrame = undefined; host.gesture("fling", false); };
|
|
757
|
+
const fling = () => {
|
|
758
|
+
let at = win.performance.now();
|
|
759
|
+
host.gesture("fling", true);
|
|
760
|
+
const step = () => {
|
|
761
|
+
const now = win.performance.now(), dt = Math.min(50, now - at);
|
|
762
|
+
at = now;
|
|
763
|
+
translateCamera(() => { cam.x -= velocity.x * dt / cam.zoom; cam.y -= velocity.y * dt / cam.zoom; });
|
|
764
|
+
velocity.x *= Math.pow(0.995, dt);
|
|
765
|
+
velocity.y *= Math.pow(0.995, dt);
|
|
766
|
+
invalidate();
|
|
767
|
+
if (Math.abs(velocity.x) > 0.01 || Math.abs(velocity.y) > 0.01)
|
|
768
|
+
flingFrame = win.requestAnimationFrame(step);
|
|
769
|
+
else
|
|
770
|
+
stopFling();
|
|
771
|
+
};
|
|
772
|
+
flingFrame = win.requestAnimationFrame(step);
|
|
773
|
+
};
|
|
774
|
+
cleanups.push(stopFling);
|
|
775
|
+
const cursor = () => { canvas.style.cursor = mode === "pan" ? "grabbing" : space || tools.active === "hand" ? "grab" : readOnly ? "default" : tools.cursor(); };
|
|
776
|
+
const release = () => {
|
|
777
|
+
const id = pointer;
|
|
778
|
+
pointer = null;
|
|
779
|
+
mode = null;
|
|
780
|
+
if (id !== null && canvas.hasPointerCapture(id))
|
|
781
|
+
canvas.releasePointerCapture(id);
|
|
782
|
+
host.gesture("tool", false);
|
|
783
|
+
host.gesture("pan", false);
|
|
784
|
+
cursor();
|
|
785
|
+
};
|
|
786
|
+
const cancel = () => {
|
|
787
|
+
touchInput?.cancel();
|
|
788
|
+
if (mode === "tool")
|
|
789
|
+
tools.cancel();
|
|
790
|
+
if (mode === "gradient")
|
|
791
|
+
tools.select.cancel();
|
|
792
|
+
if (mode === "text")
|
|
793
|
+
session?.pointer(worldFromLocal(last), "up");
|
|
794
|
+
if (contextPress.held)
|
|
795
|
+
contextPress.cancel();
|
|
796
|
+
space = false;
|
|
797
|
+
stopFling();
|
|
798
|
+
cameraInput.stop();
|
|
799
|
+
release();
|
|
800
|
+
invalidate();
|
|
801
|
+
};
|
|
802
|
+
const worldFromLocal = (p) => ({ x: cam.x + p.x / cam.zoom, y: cam.y + p.y / cam.zoom });
|
|
803
|
+
cleanups.push(cancel);
|
|
804
|
+
cleanups.push(tools.onToolChange(() => { cursor(); invalidate(); }));
|
|
805
|
+
let click = { at: -Infinity, x: 0, y: 0, count: 0 };
|
|
806
|
+
let sessionPress = false;
|
|
807
|
+
const contextSelect = (e) => {
|
|
808
|
+
if (session && insideSession(e))
|
|
809
|
+
return;
|
|
810
|
+
sink?.commitComposition();
|
|
811
|
+
endTextEdit();
|
|
812
|
+
const hit = pointerHit(store, info(e));
|
|
813
|
+
if (!hit)
|
|
814
|
+
selection.clear();
|
|
815
|
+
else if (!selection.has(hit.id))
|
|
816
|
+
selection.set([hit.id]);
|
|
817
|
+
invalidate();
|
|
818
|
+
};
|
|
819
|
+
const stalePress = () => { mode = null; touchInput?.cancel(); };
|
|
820
|
+
const touchHost = {
|
|
821
|
+
target(p) {
|
|
822
|
+
if (space || tools.active === "hand")
|
|
823
|
+
return "pan";
|
|
824
|
+
const w = world(p), handle = session && p.pointer === "touch" && overlay.selectionHandleAt(w, 1 / cam.zoom);
|
|
825
|
+
if (handle)
|
|
826
|
+
return { target: "handle", hit: { handle: session.objectId, end: handle.end, x: handle.at.x - w.x, y: handle.at.y - w.y } };
|
|
827
|
+
if (session && insideSession(p))
|
|
828
|
+
return { target: "text", hit: { session: session.objectId } };
|
|
829
|
+
if (readOnly) {
|
|
830
|
+
const hit = pointerHit(store, info(p));
|
|
831
|
+
return { target: !hit ? "canvas" : selection.has(hit.id) ? "selected" : "object", hit: { read: hit?.id ?? null } };
|
|
832
|
+
}
|
|
833
|
+
const press = tools.capturePress(info(p));
|
|
834
|
+
const s = press.select;
|
|
835
|
+
return { target: !s ? "tool" : s.kind === "object" ? (s.selected ? "selected" : "object") : s.kind === "endpoint" ? "handle" : s.kind, hit: { tool: press } };
|
|
836
|
+
},
|
|
837
|
+
press(p, clicks, hit) {
|
|
838
|
+
const h = hit;
|
|
839
|
+
sessionPress = false;
|
|
840
|
+
last = local(p);
|
|
841
|
+
if (h && "handle" in h) {
|
|
842
|
+
if (session?.objectId !== h.handle)
|
|
843
|
+
return stalePress();
|
|
844
|
+
wordTap = clicks >= 2 && insideSession(p) ? clicks : 0;
|
|
845
|
+
mode = "handle";
|
|
846
|
+
grabbed = h;
|
|
847
|
+
sessionPress = true;
|
|
848
|
+
sink?.focus();
|
|
849
|
+
invalidate();
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
const press = h && "tool" in h ? h.tool : undefined;
|
|
853
|
+
if (h ? !session && press?.select?.kind === "gradient" : onGradientHandleAt(p)) {
|
|
854
|
+
mode = "gradient";
|
|
855
|
+
if (!tools.select.pointerDown(info(p), press?.select))
|
|
856
|
+
return stalePress();
|
|
857
|
+
cursor();
|
|
858
|
+
invalidate();
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
if (h ? "session" in h : session && insideSession(p)) {
|
|
862
|
+
if (!session || (h && "session" in h && session.objectId !== h.session))
|
|
863
|
+
return stalePress();
|
|
864
|
+
mode = "text";
|
|
865
|
+
sessionPress = session.pointer(world(p), "down", p.shiftKey, clicks);
|
|
866
|
+
sink?.focus();
|
|
867
|
+
invalidate();
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
sink?.commitComposition();
|
|
871
|
+
if (readOnly) {
|
|
872
|
+
const id = h && "read" in h ? h.read : pointerHit(store, info(p))?.id ?? null;
|
|
873
|
+
const o = id === null ? null : store.scene.objects.get(id);
|
|
874
|
+
if (id !== null && (!o || o.hidden))
|
|
875
|
+
return stalePress();
|
|
876
|
+
if (id !== null) {
|
|
877
|
+
if (p.shiftKey)
|
|
878
|
+
selection.toggle(id);
|
|
879
|
+
else
|
|
880
|
+
selection.set([id]);
|
|
881
|
+
}
|
|
882
|
+
else
|
|
883
|
+
selection.clear();
|
|
884
|
+
}
|
|
885
|
+
else {
|
|
886
|
+
mode = "tool";
|
|
887
|
+
intentionalEnd = true;
|
|
888
|
+
let taken = false;
|
|
889
|
+
try {
|
|
890
|
+
taken = tools.pointerDown(info(p), press);
|
|
891
|
+
if (taken)
|
|
892
|
+
session?.end();
|
|
893
|
+
}
|
|
894
|
+
finally {
|
|
895
|
+
intentionalEnd = false;
|
|
896
|
+
}
|
|
897
|
+
if (!taken)
|
|
898
|
+
return stalePress();
|
|
899
|
+
}
|
|
900
|
+
canvas.focus({ preventScroll: true });
|
|
901
|
+
invalidate();
|
|
902
|
+
},
|
|
903
|
+
move(p) {
|
|
904
|
+
if (mode === "handle") {
|
|
905
|
+
wordTap = 0;
|
|
906
|
+
const w = world(p);
|
|
907
|
+
session?.moveSelectionEnd(grabbed.end, { x: w.x + grabbed.x, y: w.y + grabbed.y });
|
|
908
|
+
invalidate();
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
if (mode === "gradient") {
|
|
912
|
+
tools.select.pointerMove(info(p));
|
|
913
|
+
cursor();
|
|
914
|
+
invalidate();
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
if (mode === "text") {
|
|
918
|
+
session?.pointer(world(p), "move", p.shiftKey);
|
|
919
|
+
last = local(p);
|
|
920
|
+
invalidate();
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
if (mode === "tool") {
|
|
924
|
+
if (!readOnly)
|
|
925
|
+
tools.pointerMove(info(p));
|
|
926
|
+
host.gesture("tool", true);
|
|
927
|
+
invalidate();
|
|
928
|
+
}
|
|
929
|
+
},
|
|
930
|
+
release(p) {
|
|
931
|
+
const ended = mode;
|
|
932
|
+
mode = null;
|
|
933
|
+
host.gesture("tool", false);
|
|
934
|
+
if (ended === "text")
|
|
935
|
+
session?.pointer(world(p), "up");
|
|
936
|
+
else if (ended === "handle" && wordTap) {
|
|
937
|
+
session?.pointer(world(p), "down", p.shiftKey, wordTap);
|
|
938
|
+
session?.pointer(world(p), "up");
|
|
939
|
+
}
|
|
940
|
+
else if (ended === "gradient")
|
|
941
|
+
tools.select.pointerUp(info(p));
|
|
942
|
+
else if (ended === "tool" && !readOnly)
|
|
943
|
+
tools.pointerUp(info(p));
|
|
944
|
+
cursor();
|
|
945
|
+
invalidate();
|
|
946
|
+
},
|
|
947
|
+
cancel() {
|
|
948
|
+
if (mode === "tool")
|
|
949
|
+
tools.cancel();
|
|
950
|
+
if (mode === "gradient")
|
|
951
|
+
tools.select.cancel();
|
|
952
|
+
if (mode === "text")
|
|
953
|
+
session?.pointer(worldFromLocal(last), "up");
|
|
954
|
+
mode = null;
|
|
955
|
+
host.gesture("tool", false);
|
|
956
|
+
cursor();
|
|
957
|
+
invalidate();
|
|
958
|
+
},
|
|
959
|
+
doubleTap(p) {
|
|
960
|
+
if (!builtins.enabled("textEditing") || !builtins.enabled(`tool:${tools.active}`))
|
|
961
|
+
return;
|
|
962
|
+
if (readOnly || space || sessionPress || insideSession(p))
|
|
963
|
+
return;
|
|
964
|
+
tools.doubleClick(info(p));
|
|
965
|
+
},
|
|
966
|
+
hover(p) {
|
|
967
|
+
if (!builtins.enabled(`tool:${tools.active}`))
|
|
968
|
+
return;
|
|
969
|
+
if (!readOnly)
|
|
970
|
+
tools.pointerMove(info(p));
|
|
971
|
+
cursor();
|
|
972
|
+
},
|
|
973
|
+
longPress(p) {
|
|
974
|
+
const s = session && insideSession(p) ? session : null;
|
|
975
|
+
if (!s)
|
|
976
|
+
return contextSelect(p);
|
|
977
|
+
s.moveSelectionEnd("caret", world(p));
|
|
978
|
+
if (s.active && !s.composing)
|
|
979
|
+
s.selectWordAt(s.state.selection.head, s.view.affinity);
|
|
980
|
+
invalidate();
|
|
981
|
+
},
|
|
982
|
+
menu(p) { if (menuOn())
|
|
983
|
+
contextPress.openAt(local(p)); },
|
|
984
|
+
secondary(p) {
|
|
985
|
+
if (!menuOn())
|
|
986
|
+
return;
|
|
987
|
+
contextPress.down(p.pointerId);
|
|
988
|
+
contextSelect(p);
|
|
989
|
+
},
|
|
990
|
+
pan(dx, dy) { translateCamera(() => { cam.x -= dx / cam.zoom; cam.y -= dy / cam.zoom; }); invalidate(); },
|
|
991
|
+
zoom(ln, at) { zoomAbout(cam, ln, at); host.wheel("zoom"); invalidate(); },
|
|
992
|
+
motion(kind, active) { host.gesture(kind, active); },
|
|
993
|
+
stopMotion() {
|
|
994
|
+
const moving = flingFrame !== undefined || cameraInput.kinetic;
|
|
995
|
+
stopFling();
|
|
996
|
+
cameraInput.stop();
|
|
997
|
+
return moving;
|
|
998
|
+
},
|
|
999
|
+
enabled(feature) {
|
|
1000
|
+
if (feature === "menu")
|
|
1001
|
+
return builtins.enabled("contextMenu") && menuOn();
|
|
1002
|
+
return builtins.enabled(feature === "tool" ? `tool:${tools.active}` : feature);
|
|
1003
|
+
},
|
|
1004
|
+
};
|
|
1005
|
+
const touch = touchInput = new TouchInput({ host: touchHost, local: (x, y) => coords.local({ x, y }), touch: touchSettings, timers: browserTimers() });
|
|
1006
|
+
cleanups.push(() => touch.dispose());
|
|
1007
|
+
cleanups.push(tools.onToolChange(() => touch.cancelPress()));
|
|
1008
|
+
const touchEvent = (e) => e.pointerType === "touch" || e.pointerType === "pen";
|
|
1009
|
+
let lastPress = "mouse";
|
|
1010
|
+
listen(canvas, "pointerdown", (e) => {
|
|
1011
|
+
if (!touchEvent(e))
|
|
1012
|
+
return;
|
|
1013
|
+
if (pointer !== null || contextPress.held)
|
|
1014
|
+
return;
|
|
1015
|
+
lastPress = e.pointerType;
|
|
1016
|
+
if (!touch.pointerDown(e))
|
|
1017
|
+
return;
|
|
1018
|
+
e.preventDefault();
|
|
1019
|
+
if (e.pointerType === "pen")
|
|
1020
|
+
canvas.setPointerCapture(e.pointerId);
|
|
1021
|
+
});
|
|
1022
|
+
listen(canvas, "pointerdown", (e) => {
|
|
1023
|
+
if (touchEvent(e))
|
|
1024
|
+
return;
|
|
1025
|
+
cameraInput.stop();
|
|
1026
|
+
if (pointer !== null || touch.active)
|
|
1027
|
+
return;
|
|
1028
|
+
lastPress = "mouse";
|
|
1029
|
+
touch.stop();
|
|
1030
|
+
sessionPress = false;
|
|
1031
|
+
if (e.button === 2 || (e.button === 0 && e.ctrlKey && isMacPlatform())) {
|
|
1032
|
+
if (!builtins.enabled("contextMenu"))
|
|
1033
|
+
return;
|
|
1034
|
+
e.preventDefault();
|
|
1035
|
+
stopFling();
|
|
1036
|
+
if (!menuOn())
|
|
1037
|
+
return;
|
|
1038
|
+
contextPress.down(e.pointerId);
|
|
1039
|
+
canvas.setPointerCapture(e.pointerId);
|
|
1040
|
+
contextSelect(e);
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
const pans = e.button === 1 || space || (e.button === 0 && tools.active === "hand");
|
|
1044
|
+
if ((pans && !builtins.enabled("pan")) || (e.button === 0 && !space && !builtins.enabled(`tool:${tools.active}`)))
|
|
1045
|
+
return;
|
|
1046
|
+
stopFling();
|
|
1047
|
+
pointer = e.pointerId;
|
|
1048
|
+
canvas.setPointerCapture(pointer);
|
|
1049
|
+
last = local(e);
|
|
1050
|
+
velocity = { x: 0, y: 0 };
|
|
1051
|
+
lastMove = win.performance.now();
|
|
1052
|
+
e.preventDefault();
|
|
1053
|
+
if (onGradientHandle(e)) {
|
|
1054
|
+
mode = "gradient";
|
|
1055
|
+
tools.select.pointerDown(info(e));
|
|
1056
|
+
cursor();
|
|
1057
|
+
invalidate();
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
const handles = tools.select.gradientHandleTarget() !== null;
|
|
1061
|
+
if (e.button === 1 || space || (e.button === 0 && tools.active === "hand")) {
|
|
1062
|
+
mode = "pan";
|
|
1063
|
+
if (!session && !handles)
|
|
1064
|
+
canvas.focus({ preventScroll: true });
|
|
1065
|
+
host.gesture("pan", true);
|
|
1066
|
+
host.gesture("wheel", false);
|
|
1067
|
+
cursor();
|
|
1068
|
+
return;
|
|
1069
|
+
}
|
|
1070
|
+
if (e.button !== 0) {
|
|
1071
|
+
release();
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
if (session && insideSession(e)) {
|
|
1075
|
+
const same = e.timeStamp - click.at < 400 && Math.hypot(e.clientX - click.x, e.clientY - click.y) < 5;
|
|
1076
|
+
click = { at: e.timeStamp, x: e.clientX, y: e.clientY, count: same ? click.count + 1 : 1 };
|
|
1077
|
+
mode = "text";
|
|
1078
|
+
sessionPress = session.pointer(world(e), "down", e.shiftKey, click.count);
|
|
1079
|
+
sink?.focus();
|
|
1080
|
+
invalidate();
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
sink?.commitComposition();
|
|
1084
|
+
if (readOnly) {
|
|
1085
|
+
const hit = pointerHit(store, info(e));
|
|
1086
|
+
if (hit) {
|
|
1087
|
+
if (e.shiftKey)
|
|
1088
|
+
selection.toggle(hit.id);
|
|
1089
|
+
else
|
|
1090
|
+
selection.set([hit.id]);
|
|
1091
|
+
}
|
|
1092
|
+
else
|
|
1093
|
+
selection.clear();
|
|
1094
|
+
}
|
|
1095
|
+
else {
|
|
1096
|
+
mode = "tool";
|
|
1097
|
+
intentionalEnd = true;
|
|
1098
|
+
try {
|
|
1099
|
+
tools.pointerDown(info(e));
|
|
1100
|
+
session?.end();
|
|
1101
|
+
}
|
|
1102
|
+
finally {
|
|
1103
|
+
intentionalEnd = false;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
canvas.focus({ preventScroll: true });
|
|
1107
|
+
invalidate();
|
|
1108
|
+
});
|
|
1109
|
+
listen(canvas, "pointermove", (e) => {
|
|
1110
|
+
cameraInput.pointerMove(e.clientX, e.clientY);
|
|
1111
|
+
if (touchEvent(e)) {
|
|
1112
|
+
if (pointer === null)
|
|
1113
|
+
touch.pointerMove(e);
|
|
1114
|
+
return;
|
|
1115
|
+
}
|
|
1116
|
+
if (touch.active)
|
|
1117
|
+
return;
|
|
1118
|
+
if (pointer !== null && pointer !== e.pointerId)
|
|
1119
|
+
return;
|
|
1120
|
+
if (pointer === null && !builtins.enabled(`tool:${tools.active}`))
|
|
1121
|
+
return;
|
|
1122
|
+
const p = local(e);
|
|
1123
|
+
if (mode === "gradient") {
|
|
1124
|
+
tools.select.pointerMove(info(e));
|
|
1125
|
+
cursor();
|
|
1126
|
+
invalidate();
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
if (mode === "text") {
|
|
1130
|
+
session?.pointer(world(e), "move", e.shiftKey);
|
|
1131
|
+
last = p;
|
|
1132
|
+
invalidate();
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
if (mode === "pan") {
|
|
1136
|
+
const now = win.performance.now(), dt = Math.max(1, now - lastMove);
|
|
1137
|
+
velocity = { x: (p.x - last.x) / dt, y: (p.y - last.y) / dt };
|
|
1138
|
+
translateCamera(() => { cam.x -= (p.x - last.x) / cam.zoom; cam.y -= (p.y - last.y) / cam.zoom; });
|
|
1139
|
+
last = p;
|
|
1140
|
+
lastMove = now;
|
|
1141
|
+
host.gesture("pan", true);
|
|
1142
|
+
host.gesture("wheel", false);
|
|
1143
|
+
invalidate();
|
|
1144
|
+
return;
|
|
1145
|
+
}
|
|
1146
|
+
if (!readOnly)
|
|
1147
|
+
tools.pointerMove(info(e));
|
|
1148
|
+
if (mode === "tool") {
|
|
1149
|
+
host.gesture("tool", true);
|
|
1150
|
+
invalidate();
|
|
1151
|
+
}
|
|
1152
|
+
cursor();
|
|
1153
|
+
});
|
|
1154
|
+
listen(canvas, "pointerup", (e) => {
|
|
1155
|
+
if (contextPress.up(e.pointerId)) {
|
|
1156
|
+
if (canvas.hasPointerCapture(e.pointerId))
|
|
1157
|
+
canvas.releasePointerCapture(e.pointerId);
|
|
1158
|
+
if (touchEvent(e))
|
|
1159
|
+
touch.pointerUp(e);
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
if (touchEvent(e)) {
|
|
1163
|
+
touch.pointerUp(e);
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
if (pointer !== e.pointerId)
|
|
1167
|
+
return;
|
|
1168
|
+
if (mode === "pan" && e.button === 1)
|
|
1169
|
+
e.preventDefault();
|
|
1170
|
+
const ended = mode;
|
|
1171
|
+
release();
|
|
1172
|
+
if (ended === "text")
|
|
1173
|
+
session?.pointer(world(e), "up");
|
|
1174
|
+
else if (ended === "gradient")
|
|
1175
|
+
tools.select.pointerUp(info(e));
|
|
1176
|
+
else if (ended === "tool" && !readOnly)
|
|
1177
|
+
tools.pointerUp(info(e));
|
|
1178
|
+
else if (ended === "pan" && win.performance.now() - lastMove < 50 && Math.hypot(velocity.x, velocity.y) > 0.2)
|
|
1179
|
+
fling();
|
|
1180
|
+
invalidate();
|
|
1181
|
+
});
|
|
1182
|
+
listen(canvas, "pointercancel", (e) => {
|
|
1183
|
+
if (touchEvent(e)) {
|
|
1184
|
+
if (contextPress.pointer === e.pointerId)
|
|
1185
|
+
contextPress.cancel();
|
|
1186
|
+
touch.pointerCancel(e);
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
if (pointer === e.pointerId)
|
|
1190
|
+
cancel();
|
|
1191
|
+
else if (contextPress.held)
|
|
1192
|
+
contextPress.cancel();
|
|
1193
|
+
});
|
|
1194
|
+
listen(canvas, "lostpointercapture", (e) => {
|
|
1195
|
+
if (touchEvent(e)) {
|
|
1196
|
+
if (contextPress.pointer === e.pointerId)
|
|
1197
|
+
contextPress.cancel();
|
|
1198
|
+
touch.lostPointerCapture(e);
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
if (pointer !== null)
|
|
1202
|
+
cancel();
|
|
1203
|
+
else if (contextPress.held)
|
|
1204
|
+
contextPress.cancel();
|
|
1205
|
+
});
|
|
1206
|
+
listen(canvas, "blur", cancel);
|
|
1207
|
+
listen(canvas, "click", (e) => { if (builtins.enabled(`tool:${tools.active}`))
|
|
1208
|
+
e.preventDefault(); });
|
|
1209
|
+
listen(canvas, "auxclick", (e) => { if (e.button === 1 && builtins.enabled("pan"))
|
|
1210
|
+
e.preventDefault(); });
|
|
1211
|
+
listen(canvas, "dblclick", (e) => {
|
|
1212
|
+
if (!builtins.enabled("textEditing") || !builtins.enabled(`tool:${tools.active}`))
|
|
1213
|
+
return;
|
|
1214
|
+
e.preventDefault();
|
|
1215
|
+
if (lastPress !== "mouse")
|
|
1216
|
+
return;
|
|
1217
|
+
if (readOnly || e.button !== 0 || space || sessionPress || insideSession(e))
|
|
1218
|
+
return;
|
|
1219
|
+
tools.doubleClick(info(e));
|
|
1220
|
+
click = { at: e.timeStamp, x: e.clientX, y: e.clientY, count: 2 };
|
|
1221
|
+
});
|
|
1222
|
+
listen(viewport, "contextmenu", (e) => {
|
|
1223
|
+
if ((e.target !== canvas && e.target !== sink?.element) || !builtins.enabled("contextMenu"))
|
|
1224
|
+
return;
|
|
1225
|
+
e.preventDefault();
|
|
1226
|
+
const type = e.pointerType;
|
|
1227
|
+
if (type === "touch" || (!type && touch.touching()))
|
|
1228
|
+
return;
|
|
1229
|
+
if (!menuOn())
|
|
1230
|
+
contextPress.cancel();
|
|
1231
|
+
else if (contextPress.event(local(e), e.button === 2))
|
|
1232
|
+
e.stopPropagation();
|
|
1233
|
+
});
|
|
1234
|
+
listen(canvas, "wheel", (e) => {
|
|
1235
|
+
if (!builtins.enabled(e.ctrlKey || e.metaKey ? "zoom" : "pan")) {
|
|
1236
|
+
cameraInput.stop();
|
|
1237
|
+
touch.stop();
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
e.preventDefault();
|
|
1241
|
+
stopFling();
|
|
1242
|
+
touch.stop();
|
|
1243
|
+
host.wheel(e.ctrlKey || e.metaKey ? "zoom" : "pan");
|
|
1244
|
+
if (e.ctrlKey || e.metaKey)
|
|
1245
|
+
cameraInput.wheel(e);
|
|
1246
|
+
else
|
|
1247
|
+
translateCamera(() => { cameraInput.wheel(e); });
|
|
1248
|
+
}, { passive: false });
|
|
1249
|
+
if (builtins.enabled("zoom"))
|
|
1250
|
+
cleanups.push(listenTrackpadGestures(canvas, cameraInput, win.navigator, () => touch.touching()));
|
|
1251
|
+
listen(canvas, "keydown", (e) => {
|
|
1252
|
+
if (e.isComposing || e.keyCode === 229)
|
|
1253
|
+
return;
|
|
1254
|
+
cameraInput.stop();
|
|
1255
|
+
if (!builtins.allows(e))
|
|
1256
|
+
return;
|
|
1257
|
+
if (win.performance.now() < keyGraceUntil) {
|
|
1258
|
+
e.preventDefault();
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
if (mode === "gradient") {
|
|
1262
|
+
if (e.key === "Escape" && tools.select.state().mode === "gradient")
|
|
1263
|
+
tools.select.key(e.key, { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey });
|
|
1264
|
+
e.preventDefault();
|
|
1265
|
+
invalidate();
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
1268
|
+
if (ui?.handleKey(e)) {
|
|
1269
|
+
invalidate();
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
if (e.code === "Space") {
|
|
1273
|
+
space = true;
|
|
1274
|
+
cursor();
|
|
1275
|
+
e.preventDefault();
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
1278
|
+
if (e.key === "Escape" && tools.active === "hand") {
|
|
1279
|
+
host.tools.setTool("select");
|
|
1280
|
+
e.preventDefault();
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
if (touch.key(e.key)) {
|
|
1284
|
+
e.preventDefault();
|
|
1285
|
+
invalidate();
|
|
1286
|
+
return;
|
|
1287
|
+
}
|
|
1288
|
+
if (readOnly) {
|
|
1289
|
+
if ((e.ctrlKey || e.metaKey) && !e.altKey && e.key.toLowerCase() === "a") {
|
|
1290
|
+
host.controller.commands.selectAll?.run();
|
|
1291
|
+
e.preventDefault();
|
|
1292
|
+
}
|
|
1293
|
+
return;
|
|
1294
|
+
}
|
|
1295
|
+
if (e.key === "Escape" && !session && mode === null && !ctrl.hasPreview()
|
|
1296
|
+
&& selection.size === 0 && tools.active === "select" && tools.select.state().mode === "idle")
|
|
1297
|
+
cancelImageInserts();
|
|
1298
|
+
if (tools.key(e.key, { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey })) {
|
|
1299
|
+
e.preventDefault();
|
|
1300
|
+
invalidate();
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1303
|
+
});
|
|
1304
|
+
listen(canvas, "keyup", (e) => { if (builtins.allows(e) && e.code === "Space") {
|
|
1305
|
+
space = false;
|
|
1306
|
+
cursor();
|
|
1307
|
+
} });
|
|
1308
|
+
recovery.visibilityChanged = () => {
|
|
1309
|
+
images.setSuspended(dom.hidden || loop?.tier === "deep");
|
|
1310
|
+
if (dom.hidden) {
|
|
1311
|
+
hides++;
|
|
1312
|
+
cancelImageInserts();
|
|
1313
|
+
cancel();
|
|
1314
|
+
}
|
|
1315
|
+
else if (watchedDpr !== (win.devicePixelRatio || 1))
|
|
1316
|
+
onResolution();
|
|
1317
|
+
};
|
|
1318
|
+
loop.setHidden(dom.hidden || renderer.contextLost);
|
|
1319
|
+
loop.start();
|
|
1320
|
+
if (mountAbort.signal.aborted)
|
|
1321
|
+
throw mountAbort.signal.reason;
|
|
1322
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1323
|
+
return Object.freeze({ controller: host.controller, tools: host.tools, camera: host.camera, clipboard, ui: wiring?.ui ?? null, images: Object.freeze({ flush: () => imageOps.flush(), register: (hashes, options) => imageOps.register(hashes, options), pick: pickImages, insert: insertImages, cancel: cancelImageInserts }), dispose, focus: () => { if (!disposed)
|
|
1324
|
+
host.returnFocus(); } });
|
|
1325
|
+
}
|
|
1326
|
+
catch (error) {
|
|
1327
|
+
try {
|
|
1328
|
+
dispose();
|
|
1329
|
+
}
|
|
1330
|
+
catch { }
|
|
1331
|
+
throw error;
|
|
1332
|
+
}
|
|
1333
|
+
}
|