@open-artifact/canvas-engine 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/src/engine.js ADDED
@@ -0,0 +1,738 @@
1
+ /**
2
+ * `CanvasEngine`: the TypeScript face of the wasm canvas core.
3
+ *
4
+ * TypeScript owns the document. The engine keeps a mirror of what to draw, updated
5
+ * with id-keyed patches (`applyPatch`), renders every frame in wasm, and handles
6
+ * pointer, wheel, touch and keyboard input itself. It reports low-frequency events
7
+ * (selection, camera, commits, texture requests, holes…) and never edits the
8
+ * document: a finished drag is a `commit` the owner applies (or not; see `commit`).
9
+ */
10
+ import { loadCanvasWasm } from '@open-artifact/wasm-canvas';
11
+ import { screenToWorld, visibleRect, worldToScreen } from "./camera.js";
12
+ import { CURSORS, FRAME_HOLES, FRAME_MORE, FRAME_RENDER, KEY_ESCAPE, KEY_MODIFIER, KEY_SPACE, MOD_ALT, MOD_CTRL, MOD_META, MOD_SHIFT, OPTION, PatchEncoder, POINTER_TYPES, THEME_OPTION, TOOLS, parseColor, } from "./protocol.js";
13
+ /** Handle edge bits from the core (left, right, top, bottom) to compass names. */
14
+ const HANDLES = { 5: 'nw', 4: 'n', 6: 'ne', 2: 'e', 10: 'se', 8: 's', 9: 'sw', 1: 'w' };
15
+ const TOOL_NAMES = ['select', 'pan', 'none'];
16
+ function modifiers(m) {
17
+ return { shift: !!(m & MOD_SHIFT), alt: !!(m & MOD_ALT), ctrl: !!(m & MOD_CTRL), meta: !!(m & MOD_META) };
18
+ }
19
+ function rectOf(r) {
20
+ return { x: r[0], y: r[1], w: r[2], h: r[3] };
21
+ }
22
+ const CONTEXT_ATTRIBUTES = {
23
+ alpha: true,
24
+ antialias: true,
25
+ depth: true,
26
+ stencil: false,
27
+ premultipliedAlpha: true,
28
+ preserveDrawingBuffer: false,
29
+ powerPreference: 'high-performance',
30
+ };
31
+ function modsOf(e) {
32
+ return (e.shiftKey ? MOD_SHIFT : 0) | (e.altKey ? MOD_ALT : 0) | (e.ctrlKey ? MOD_CTRL : 0) | (e.metaKey ? MOD_META : 0);
33
+ }
34
+ function isEditable(target) {
35
+ const el = target;
36
+ if (!el || typeof el.closest !== 'function')
37
+ return false;
38
+ return !!el.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]');
39
+ }
40
+ function sourceSize(s) {
41
+ if (typeof HTMLImageElement !== 'undefined' && s instanceof HTMLImageElement)
42
+ return [s.naturalWidth, s.naturalHeight];
43
+ return [s.width, s.height];
44
+ }
45
+ const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
46
+ export class CanvasEngine {
47
+ canvas;
48
+ #core;
49
+ #memory;
50
+ #enc = new PatchEncoder();
51
+ #listeners = new Map();
52
+ #raf = 0;
53
+ #destroyed = false;
54
+ #cleanup = [];
55
+ #dpr;
56
+ #size;
57
+ #maxZoom = 64;
58
+ #rect = null;
59
+ #cursor = -1;
60
+ #lost = false;
61
+ /** The DOM event being handled, handed to `dblclick`/`contextmenu` listeners. */
62
+ #domEvent;
63
+ constructor(core, memory, canvas, size, dpr) {
64
+ this.#core = core;
65
+ this.#memory = memory;
66
+ this.canvas = canvas;
67
+ this.#size = size;
68
+ this.#dpr = dpr;
69
+ }
70
+ /**
71
+ * Creates an engine drawing into `canvas` (WebGL2). The canvas is sized to its CSS
72
+ * box times the device pixel ratio, and follows it.
73
+ */
74
+ static async create(canvas, options = {}) {
75
+ const wasm = await loadCanvasWasm();
76
+ const gl = canvas.getContext('webgl2', CONTEXT_ATTRIBUTES);
77
+ if (!gl)
78
+ throw new Error('canvas-engine: WebGL2 is not available');
79
+ const dpr = options.dpr ?? (typeof devicePixelRatio === 'number' ? devicePixelRatio : 1);
80
+ const box = canvas.getBoundingClientRect();
81
+ const w = box.width || canvas.width / dpr;
82
+ const h = box.height || canvas.height / dpr;
83
+ canvas.width = Math.max(1, Math.round(w * dpr));
84
+ canvas.height = Math.max(1, Math.round(h * dpr));
85
+ const core = new wasm.CanvasCore(gl, w, h, dpr);
86
+ const engine = new CanvasEngine(core, wasm.memory, canvas, [w, h], dpr);
87
+ engine.setOptions(options);
88
+ if (options.tool)
89
+ engine.setTool(options.tool);
90
+ if (options.listen !== false)
91
+ engine.#listen(canvas);
92
+ engine.requestFrame();
93
+ return engine;
94
+ }
95
+ /**
96
+ * An engine without a canvas or GPU: same scene, camera, gestures and events,
97
+ * nothing drawn. Frames advance only through `tick(now)`. For tests and tools.
98
+ */
99
+ static async createHeadless(options) {
100
+ const wasm = await loadCanvasWasm();
101
+ const dpr = options.dpr ?? 1;
102
+ const core = new wasm.CanvasCore(undefined, options.width, options.height, dpr);
103
+ const engine = new CanvasEngine(core, wasm.memory, null, [options.width, options.height], dpr);
104
+ engine.setOptions(options);
105
+ if (options.tool)
106
+ engine.setTool(options.tool);
107
+ return engine;
108
+ }
109
+ // ---------------------------------------------------------------- events
110
+ /** Subscribes to an event; returns the unsubscribe function. */
111
+ on(event, cb) {
112
+ let set = this.#listeners.get(event);
113
+ if (!set)
114
+ this.#listeners.set(event, (set = new Set()));
115
+ set.add(cb);
116
+ return () => set.delete(cb);
117
+ }
118
+ #emit(event, payload) {
119
+ const set = this.#listeners.get(event);
120
+ if (!set)
121
+ return;
122
+ for (const cb of set)
123
+ cb(payload);
124
+ }
125
+ #drain() {
126
+ if (!this.#core.has_events())
127
+ return;
128
+ const events = JSON.parse(this.#core.take_events());
129
+ const items = this.#enc.items;
130
+ for (const e of events) {
131
+ switch (e.type) {
132
+ case 'selection':
133
+ this.#emit('selection', { ids: items.ids(e.ids), modifiers: modifiers(e.mods) });
134
+ break;
135
+ case 'camera':
136
+ this.#emit('camera', { x: e.x, y: e.y, zoom: e.zoom, settled: e.settled });
137
+ break;
138
+ case 'moving':
139
+ this.#emit('moving', { moving: e.moving });
140
+ break;
141
+ case 'commit': {
142
+ const m = modifiers(e.mods);
143
+ if (e.op === 'move')
144
+ this.#emit('commit', { op: 'move', ids: items.ids(e.ids), dx: e.dx, dy: e.dy, modifiers: m });
145
+ else if (e.op === 'resize') {
146
+ const id = items.id(e.id);
147
+ if (id !== undefined)
148
+ this.#emit('commit', { op: 'resize', id, rect: rectOf(e.rect), modifiers: m });
149
+ }
150
+ else
151
+ this.#emit('commit', { op: 'select', ids: items.ids(e.ids), modifiers: m });
152
+ break;
153
+ }
154
+ case 'textureNeeded':
155
+ this.#emit('textureNeeded', { keys: this.#enc.textures.ids(e.keys) });
156
+ break;
157
+ case 'hover':
158
+ this.#emit('hover', { id: e.id === null ? null : (items.id(e.id) ?? null) });
159
+ break;
160
+ case 'gesture':
161
+ this.#emit('gesture', { kind: e.kind, phase: e.phase, modifiers: modifiers(e.mods) });
162
+ break;
163
+ case 'dragging':
164
+ this.#emit('dragging', { ids: items.ids(e.ids), dx: e.dx, dy: e.dy, modifiers: modifiers(e.mods) });
165
+ break;
166
+ case 'resizing': {
167
+ const id = items.id(e.id);
168
+ if (id !== undefined)
169
+ this.#emit('resizing', { id, rect: rectOf(e.rect), modifiers: modifiers(e.mods) });
170
+ break;
171
+ }
172
+ case 'pointer':
173
+ this.#emit(e.kind, {
174
+ id: e.id === null ? null : (items.id(e.id) ?? null),
175
+ world: { x: e.world[0], y: e.world[1] },
176
+ screen: { x: e.screen[0], y: e.screen[1] },
177
+ modifiers: modifiers(e.mods),
178
+ event: this.#domEvent,
179
+ });
180
+ break;
181
+ case 'contextrestored':
182
+ this.#emit('contextrestored', {});
183
+ break;
184
+ }
185
+ }
186
+ }
187
+ // ---------------------------------------------------------------- frames
188
+ /** Schedules a frame (no-op if one is scheduled, or headless). */
189
+ requestFrame() {
190
+ if (this.#raf || this.#destroyed || !this.canvas || typeof requestAnimationFrame === 'undefined')
191
+ return;
192
+ this.#raf = requestAnimationFrame(t => {
193
+ this.#raf = 0;
194
+ this.tick(t);
195
+ });
196
+ }
197
+ /** Advances one frame at time `t` (ms): animations, events, drawing. Called by the frame loop. */
198
+ tick(t = now()) {
199
+ if (this.#destroyed)
200
+ return;
201
+ const t0 = now();
202
+ const bits = this.#lost ? 0 : this.#core.frame(t);
203
+ const engineMs = now() - t0;
204
+ this.#drain();
205
+ if (bits & FRAME_HOLES)
206
+ this.#emit('holes', { holes: this.holes() });
207
+ if (bits & FRAME_RENDER)
208
+ this.#emit('frame', { engineMs });
209
+ if (bits & FRAME_MORE)
210
+ this.requestFrame();
211
+ }
212
+ /** Visible holes in screen space. */
213
+ holes() {
214
+ const raw = this.#core.holes();
215
+ const out = [];
216
+ for (let i = 0; i + 6 < raw.length; i += 7) {
217
+ const id = this.#enc.items.id(raw[i]);
218
+ if (id === undefined)
219
+ continue;
220
+ const [x, y, w, h, rotation, zoom] = [raw[i + 1], raw[i + 2], raw[i + 3], raw[i + 4], raw[i + 5], raw[i + 6]];
221
+ // The element is world-sized at the canvas origin: scale, rotate about its centre, then place.
222
+ const c = Math.cos(rotation) * zoom;
223
+ const s = Math.sin(rotation) * zoom;
224
+ const cx = x + w / 2;
225
+ const cy = y + h / 2;
226
+ const ww = w / zoom / 2;
227
+ const hh = h / zoom / 2;
228
+ const e = cx - (c * ww - s * hh);
229
+ const f = cy - (s * ww + c * hh);
230
+ out.push({ id, x, y, w, h, rotation, zoom, transform: `matrix(${c}, ${s}, ${-s}, ${c}, ${e}, ${f})` });
231
+ }
232
+ return out;
233
+ }
234
+ #touch() {
235
+ this.#drain();
236
+ this.#syncCursor();
237
+ this.requestFrame();
238
+ }
239
+ #syncCursor() {
240
+ if (!this.canvas)
241
+ return;
242
+ const c = this.#core.cursor();
243
+ if (c !== this.#cursor) {
244
+ this.#cursor = c;
245
+ this.canvas.style.cursor = CURSORS[c] ?? 'default';
246
+ }
247
+ }
248
+ // ---------------------------------------------------------------- scene
249
+ /** Applies a patch (or a list of items to upsert) to the mirror. */
250
+ applyPatch(patch) {
251
+ const p = Array.isArray(patch) ? { upsert: patch } : patch;
252
+ const enc = this.#enc.encode(p);
253
+ if (enc.records)
254
+ this.#core.apply(enc.ops, enc.paths);
255
+ this.#touch();
256
+ }
257
+ /**
258
+ * Stores a texture under `key`: one source, or several resolutions of the same
259
+ * image (the engine draws the smallest one at least as wide as the item on screen).
260
+ * Sources larger than `maxTextureSide` are scaled down. Returns false when nothing fit.
261
+ */
262
+ setTexture(key, source) {
263
+ const list = Array.isArray(source) ? source : [source];
264
+ const max = this.#core.max_texture_side();
265
+ const sources = [];
266
+ const sizes = [];
267
+ for (const s of list) {
268
+ let [w, h] = sourceSize(s);
269
+ if (!w || !h)
270
+ continue;
271
+ let src = s;
272
+ if (w > max || h > max) {
273
+ const k = max / Math.max(w, h);
274
+ [src, w, h] = [scaleDown(s, Math.max(1, Math.floor(w * k)), Math.max(1, Math.floor(h * k))), Math.max(1, Math.floor(w * k)), Math.max(1, Math.floor(h * k))];
275
+ }
276
+ sources.push(src);
277
+ sizes.push(w, h);
278
+ }
279
+ if (!sizes.length)
280
+ return false;
281
+ const bits = this.#core.set_texture(this.#enc.textures.ensure(key), sources, new Uint32Array(sizes));
282
+ this.#touch();
283
+ return bits !== 0;
284
+ }
285
+ removeTexture(key) {
286
+ const h = this.#enc.textures.get(key);
287
+ if (h !== undefined)
288
+ this.#core.remove_texture(h);
289
+ this.#touch();
290
+ }
291
+ /** Largest texture side accepted without scaling. */
292
+ get maxTextureSide() {
293
+ return this.#core.max_texture_side();
294
+ }
295
+ // ---------------------------------------------------------------- state
296
+ setTool(tool) {
297
+ this.#core.set_tool(TOOLS[tool]);
298
+ this.#touch();
299
+ }
300
+ get tool() {
301
+ return TOOL_NAMES[this.#core.tool()] ?? 'select';
302
+ }
303
+ setOptions(o) {
304
+ const set = (k, v) => this.#core.set_option(k, v);
305
+ const b = (v) => (v ? 1 : 0);
306
+ if (o.minZoom !== undefined)
307
+ set(OPTION.minZoom, o.minZoom);
308
+ if (o.maxZoom !== undefined) {
309
+ set(OPTION.maxZoom, o.maxZoom);
310
+ this.#maxZoom = o.maxZoom;
311
+ }
312
+ if (o.snap !== undefined)
313
+ set(OPTION.snap, b(o.snap));
314
+ if (o.snapDistance !== undefined)
315
+ set(OPTION.snapDistance, o.snapDistance);
316
+ if (o.dragThreshold !== undefined)
317
+ set(OPTION.dragThreshold, o.dragThreshold);
318
+ if (o.hitTolerance !== undefined)
319
+ set(OPTION.hitTolerance, o.hitTolerance);
320
+ if (o.handleSize !== undefined)
321
+ set(OPTION.handleSize, o.handleSize);
322
+ if (o.settleMs !== undefined)
323
+ set(OPTION.settleMs, o.settleMs);
324
+ if (o.cameraEventMs !== undefined)
325
+ set(OPTION.cameraEventMs, o.cameraEventMs);
326
+ if (o.wheelZoom !== undefined)
327
+ set(OPTION.wheelZoom, b(o.wheelZoom));
328
+ if (o.zoomSpeed !== undefined)
329
+ set(OPTION.zoomSpeed, o.zoomSpeed);
330
+ if (o.wheelZoomMax !== undefined)
331
+ set(OPTION.wheelZoomMax, o.wheelZoomMax);
332
+ if (o.selection !== undefined)
333
+ set(OPTION.selection, b(o.selection === 'controlled'));
334
+ if (o.marquee !== undefined)
335
+ set(OPTION.marquee, b(o.marquee === 'contain'));
336
+ if (o.fadeMs !== undefined)
337
+ set(OPTION.fadeMs, o.fadeMs);
338
+ if (o.dragEvents !== undefined)
339
+ set(OPTION.dragEvents, b(o.dragEvents));
340
+ if (o.grid !== undefined)
341
+ set(OPTION.grid, { none: 0, dots: 1, lines: 2 }[o.grid]);
342
+ if (o.gridSpacing !== undefined)
343
+ set(OPTION.gridSpacing, o.gridSpacing);
344
+ if (o.gridMajor !== undefined)
345
+ set(OPTION.gridMajor, o.gridMajor);
346
+ if (o.gridFade !== undefined) {
347
+ set(OPTION.gridFadeStart, o.gridFade[0]);
348
+ set(OPTION.gridFadeEnd, o.gridFade[1]);
349
+ }
350
+ if (o.textureBudget !== undefined)
351
+ set(OPTION.textureBudget, o.textureBudget);
352
+ for (const [k, v] of Object.entries(o.theme ?? {})) {
353
+ const key = THEME_OPTION[k];
354
+ if (key !== undefined && v !== undefined)
355
+ set(key, parseColor(v));
356
+ }
357
+ this.#touch();
358
+ }
359
+ /** Replaces the selection (the way to apply a `select` commit in 'controlled' mode). No event. */
360
+ setSelection(ids) {
361
+ const hs = [];
362
+ for (const id of ids) {
363
+ const h = this.#enc.items.get(id);
364
+ if (h !== undefined)
365
+ hs.push(h);
366
+ }
367
+ this.#core.set_selection(new Uint32Array(hs));
368
+ this.#touch();
369
+ }
370
+ get selection() {
371
+ return this.#enc.items.ids(this.#core.selection());
372
+ }
373
+ /** Other users' cursors and selections, drawn in the overlay. */
374
+ setPeers(peers) {
375
+ const data = [];
376
+ for (const p of peers) {
377
+ const sel = [];
378
+ for (const id of p.selection ?? []) {
379
+ const h = this.#enc.items.get(id);
380
+ if (h !== undefined)
381
+ sel.push(h);
382
+ }
383
+ data.push(parseColor(p.color), p.cursor ? 1 : 0, p.cursor?.x ?? 0, p.cursor?.y ?? 0, sel.length, ...sel);
384
+ }
385
+ this.#core.set_peers(new Float64Array(data));
386
+ this.#touch();
387
+ }
388
+ /** Topmost hittable item at a screen point. */
389
+ hitTest(screen) {
390
+ const h = this.#core.hit_test(screen.x, screen.y);
391
+ return h < 0 ? null : (this.#enc.items.id(h) ?? null);
392
+ }
393
+ /** The resize handle of the selected item at a screen point (only handles the engine draws). */
394
+ hitHandle(screen) {
395
+ const r = this.#core.hit_handle(screen.x, screen.y);
396
+ if (r.length < 2)
397
+ return null;
398
+ const id = this.#enc.items.id(r[0]);
399
+ const handle = HANDLES[r[1]];
400
+ return id !== undefined && handle ? { id, handle } : null;
401
+ }
402
+ /** An item's rect as the engine has it now (mid-gesture included), or null if unknown. */
403
+ itemRect(id) {
404
+ const h = this.#enc.items.get(id);
405
+ if (h === undefined)
406
+ return null;
407
+ const r = this.#core.item_rect(h);
408
+ return r.length < 5 ? null : { x: r[0], y: r[1], w: r[2], h: r[3], rotation: r[4] };
409
+ }
410
+ /**
411
+ * Starts moving an item (and the selection, if it is in it) from a press the host
412
+ * received, e.g. on a DOM title above the canvas. The pointer's later moves and
413
+ * release must reach the engine: with the DOM listeners the canvas captures the
414
+ * pointer. It becomes a drag past the drag threshold, like a press on the item.
415
+ * Returns false when a gesture is running, the tool is not 'select' or nothing is movable.
416
+ */
417
+ startMove(id, p) {
418
+ const h = this.#enc.items.get(id);
419
+ if (h === undefined)
420
+ return false;
421
+ const ok = this.#core.start_move(p.id ?? 1, p.x, p.y, h, modsOf(flags(p)));
422
+ if (ok && this.canvas && p.id !== undefined) {
423
+ try {
424
+ this.canvas.setPointerCapture(p.id);
425
+ }
426
+ catch {
427
+ // Not an active pointer (synthetic input): moves must then be fed through `input`.
428
+ }
429
+ }
430
+ this.#touch();
431
+ return ok;
432
+ }
433
+ /** Items whose bounds meet a world rect. */
434
+ queryRect(r) {
435
+ return this.#enc.items.ids(this.#core.query_rect(r.x, r.y, r.w, r.h));
436
+ }
437
+ /** Abandons the gesture in progress (restoring what it moved). */
438
+ cancelGesture() {
439
+ this.#core.cancel_gesture();
440
+ this.#touch();
441
+ }
442
+ // ---------------------------------------------------------------- camera
443
+ get camera() {
444
+ const c = this.#core.camera();
445
+ return { x: c[0], y: c[1], zoom: c[2] };
446
+ }
447
+ /** Whether the camera is moving (not yet settled). */
448
+ get moving() {
449
+ return this.#core.camera()[8] === 1;
450
+ }
451
+ setCamera(c) {
452
+ this.#core.set_camera(c.x, c.y, c.zoom);
453
+ this.#touch();
454
+ }
455
+ panBy(dx, dy) {
456
+ this.#core.pan_by(dx, dy);
457
+ this.#touch();
458
+ }
459
+ /** Zooms by `factor` keeping the screen point fixed (default the centre). */
460
+ zoomAt(factor, screen) {
461
+ const [w, h] = this.#size;
462
+ this.#core.zoom_at(factor, screen?.x ?? w / 2, screen?.y ?? h / 2);
463
+ this.#touch();
464
+ }
465
+ /** Animates the camera to frame a world rect. */
466
+ glideTo(r, o = {}) {
467
+ this.#core.glide_to(r.x, r.y, r.w, r.h, o.duration ?? 300, o.padding ?? 40, o.maxZoom ?? this.#maxZoom);
468
+ this.#touch();
469
+ }
470
+ /** Jumps to frame a world rect. */
471
+ fit(r, o = {}) {
472
+ this.glideTo(r, { ...o, duration: 0 });
473
+ }
474
+ screenToWorld(p) {
475
+ return screenToWorld(this.camera, p);
476
+ }
477
+ worldToScreen(p) {
478
+ return worldToScreen(this.camera, p);
479
+ }
480
+ /** The world rect the canvas shows. */
481
+ viewport() {
482
+ const [w, h] = this.#size;
483
+ return visibleRect(this.camera, w, h);
484
+ }
485
+ /** Resizes the drawing surface (CSS pixels). Called automatically when listening. */
486
+ resize(width, height, dpr = this.#dpr) {
487
+ this.#size = [width, height];
488
+ this.#dpr = dpr;
489
+ if (this.canvas) {
490
+ this.canvas.width = Math.max(1, Math.round(width * dpr));
491
+ this.canvas.height = Math.max(1, Math.round(height * dpr));
492
+ }
493
+ this.#core.resize(width, height, dpr);
494
+ this.#touch();
495
+ }
496
+ stats() {
497
+ const s = this.#core.stats();
498
+ return {
499
+ items: s[0],
500
+ visible: s[1],
501
+ drawCalls: s[2],
502
+ textures: s[3],
503
+ textureBytes: s[4],
504
+ atlasLayers: s[5],
505
+ quads: s[6],
506
+ pathVertices: s[7],
507
+ pathIndices: s[8],
508
+ batches: s[9],
509
+ holes: s[10],
510
+ maxAtlasLayers: s[11],
511
+ wasmMemory: this.#memory.buffer.byteLength,
512
+ };
513
+ }
514
+ // ---------------------------------------------------------------- input
515
+ /**
516
+ * Feeds input directly (what the DOM listeners do). For tests, headless use and
517
+ * hosts that route events themselves (with `listen: false`). Returns whether the
518
+ * engine handled it.
519
+ */
520
+ input = {
521
+ pointerDown: (p) => {
522
+ const r = this.#core.pointer_down(p.id ?? 1, p.x, p.y, p.button ?? 0, modsOf(flags(p)), POINTER_TYPES[p.type ?? 'mouse']);
523
+ this.#touch();
524
+ return r;
525
+ },
526
+ pointerMove: (p) => {
527
+ const r = this.#core.pointer_move(p.id ?? 1, p.x, p.y, p.buttons ?? 0, modsOf(flags(p)));
528
+ this.#touch();
529
+ return r;
530
+ },
531
+ pointerUp: (p) => {
532
+ const r = this.#core.pointer_up(p.id ?? 1, p.x, p.y, p.button ?? 0, modsOf(flags(p)));
533
+ this.#touch();
534
+ return r;
535
+ },
536
+ pointerCancel: (id = 1) => {
537
+ this.#core.pointer_cancel(id);
538
+ this.#touch();
539
+ },
540
+ pointerLeave: () => {
541
+ this.#core.pointer_leave();
542
+ this.#touch();
543
+ },
544
+ /** Wheel deltas in pixels. */
545
+ wheel: (p) => {
546
+ const r = this.#core.wheel(p.x, p.y, p.dx, p.dy, modsOf(flags(p)));
547
+ this.#touch();
548
+ return r;
549
+ },
550
+ /** A double click at a screen point: emits `dblclick` with the item under it. */
551
+ dblclick: (p) => {
552
+ this.#core.pointer_event(0, p.x, p.y, modsOf(flags(p)));
553
+ this.#touch();
554
+ },
555
+ /** A context menu request at a screen point: emits `contextmenu` with the item under it. */
556
+ contextmenu: (p) => {
557
+ this.#core.pointer_event(1, p.x, p.y, modsOf(flags(p)));
558
+ this.#touch();
559
+ },
560
+ /** 'space' | 'escape' | 'modifier'. */
561
+ key: (key, down, mods = {}) => {
562
+ const code = key === 'space' ? KEY_SPACE : key === 'escape' ? KEY_ESCAPE : KEY_MODIFIER;
563
+ const r = this.#core.key(code, down, modsOf(flags(mods)));
564
+ this.#touch();
565
+ return r;
566
+ },
567
+ };
568
+ #canvasPoint(e, refresh = false) {
569
+ if (refresh || !this.#rect)
570
+ this.#rect = this.canvas.getBoundingClientRect();
571
+ return { x: e.clientX - this.#rect.left, y: e.clientY - this.#rect.top };
572
+ }
573
+ #listen(canvas) {
574
+ const add = (target, type, fn, opts) => {
575
+ target.addEventListener(type, fn, opts);
576
+ this.#cleanup.push(() => target.removeEventListener(type, fn, opts));
577
+ };
578
+ canvas.style.touchAction = 'none';
579
+ add(canvas, 'pointerdown', (e) => {
580
+ const p = this.#canvasPoint(e, true);
581
+ const handled = this.#core.pointer_down(e.pointerId, p.x, p.y, e.button, modsOf(e), POINTER_TYPES[e.pointerType] ?? 0);
582
+ if (handled) {
583
+ canvas.setPointerCapture?.(e.pointerId);
584
+ if (e.button === 1)
585
+ e.preventDefault();
586
+ }
587
+ this.#touch();
588
+ });
589
+ add(canvas, 'pointermove', (e) => {
590
+ const p = this.#canvasPoint(e);
591
+ this.#core.pointer_move(e.pointerId, p.x, p.y, e.buttons, modsOf(e));
592
+ this.#touch();
593
+ });
594
+ const up = (e) => {
595
+ const p = this.#canvasPoint(e);
596
+ this.#core.pointer_up(e.pointerId, p.x, p.y, e.button, modsOf(e));
597
+ this.#touch();
598
+ };
599
+ add(canvas, 'pointerup', up);
600
+ add(canvas, 'pointercancel', (e) => {
601
+ this.#core.pointer_cancel(e.pointerId);
602
+ this.#touch();
603
+ });
604
+ add(canvas, 'pointerleave', () => {
605
+ this.#core.pointer_leave();
606
+ this.#touch();
607
+ });
608
+ add(canvas, 'wheel', (e) => {
609
+ e.preventDefault();
610
+ const p = this.#canvasPoint(e, true);
611
+ const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? this.#size[1] : 1;
612
+ this.#core.wheel(p.x, p.y, e.deltaX * unit, e.deltaY * unit, modsOf(e));
613
+ this.#touch();
614
+ }, { passive: false });
615
+ // Safari trackpad pinch.
616
+ let gestureScale = 1;
617
+ add(canvas, 'gesturestart', (e) => {
618
+ e.preventDefault();
619
+ gestureScale = 1;
620
+ });
621
+ add(canvas, 'gesturechange', (e) => {
622
+ e.preventDefault();
623
+ const scale = e.scale ?? 1;
624
+ const p = this.#canvasPoint({ clientX: e.clientX ?? 0, clientY: e.clientY ?? 0 });
625
+ this.#core.zoom_at(scale / gestureScale, p.x, p.y);
626
+ gestureScale = scale;
627
+ this.#touch();
628
+ });
629
+ const pointerEvent = (kind) => (e) => {
630
+ const p = this.#canvasPoint(e, true);
631
+ this.#domEvent = e;
632
+ this.#core.pointer_event(kind, p.x, p.y, modsOf(e));
633
+ try {
634
+ this.#touch();
635
+ }
636
+ finally {
637
+ this.#domEvent = undefined;
638
+ }
639
+ };
640
+ add(canvas, 'dblclick', pointerEvent(0));
641
+ add(canvas, 'contextmenu', (e) => {
642
+ if (e.button === 1)
643
+ e.preventDefault();
644
+ else
645
+ pointerEvent(1)(e);
646
+ });
647
+ const key = (down) => (e) => {
648
+ if (isEditable(e.target))
649
+ return;
650
+ let handled = false;
651
+ if (e.code === 'Space') {
652
+ if (e.repeat) {
653
+ e.preventDefault();
654
+ return;
655
+ }
656
+ handled = this.#core.key(KEY_SPACE, down, modsOf(e));
657
+ }
658
+ else if (e.key === 'Escape' && down)
659
+ handled = this.#core.key(KEY_ESCAPE, true, modsOf(e));
660
+ else if (['Shift', 'Control', 'Meta', 'Alt'].includes(e.key))
661
+ this.#core.key(KEY_MODIFIER, down, modsOf(e));
662
+ if (handled)
663
+ e.preventDefault();
664
+ this.#touch();
665
+ };
666
+ add(window, 'keydown', key(true));
667
+ add(window, 'keyup', key(false));
668
+ add(window, 'blur', () => {
669
+ this.#core.key(KEY_SPACE, false, 0);
670
+ this.#touch();
671
+ });
672
+ add(window, 'scroll', () => (this.#rect = null), { capture: true, passive: true });
673
+ if (typeof ResizeObserver !== 'undefined') {
674
+ const ro = new ResizeObserver(entries => {
675
+ const box = entries[0].contentRect;
676
+ this.#rect = null;
677
+ if (box.width !== this.#size[0] || box.height !== this.#size[1])
678
+ this.resize(box.width, box.height, devicePixelRatio || 1);
679
+ });
680
+ ro.observe(canvas);
681
+ this.#cleanup.push(() => ro.disconnect());
682
+ }
683
+ const watchDpr = () => {
684
+ const mq = matchMedia(`(resolution: ${devicePixelRatio}dppx)`);
685
+ const onChange = () => {
686
+ this.resize(this.#size[0], this.#size[1], devicePixelRatio || 1);
687
+ watchDpr();
688
+ };
689
+ mq.addEventListener('change', onChange, { once: true });
690
+ this.#cleanup.push(() => mq.removeEventListener('change', onChange));
691
+ };
692
+ if (typeof matchMedia === 'function')
693
+ watchDpr();
694
+ add(canvas, 'webglcontextlost', (e) => {
695
+ e.preventDefault();
696
+ this.#lost = true;
697
+ this.#core.context_lost();
698
+ this.#emit('contextlost', {});
699
+ });
700
+ add(canvas, 'webglcontextrestored', () => {
701
+ const gl = canvas.getContext('webgl2', CONTEXT_ATTRIBUTES);
702
+ if (!gl)
703
+ return;
704
+ this.#core.context_restored(gl);
705
+ this.#lost = false;
706
+ this.#touch();
707
+ });
708
+ }
709
+ /** Stops listening and frees the engine. The canvas keeps its last frame. */
710
+ destroy() {
711
+ if (this.#destroyed)
712
+ return;
713
+ this.#destroyed = true;
714
+ if (this.#raf)
715
+ cancelAnimationFrame(this.#raf);
716
+ for (const fn of this.#cleanup)
717
+ fn();
718
+ this.#cleanup.length = 0;
719
+ this.#listeners.clear();
720
+ this.#core.free();
721
+ }
722
+ }
723
+ function flags(p) {
724
+ return { shiftKey: !!p.shift, altKey: !!p.alt, ctrlKey: !!p.ctrl, metaKey: !!p.meta };
725
+ }
726
+ /** Draws a source into a smaller canvas. */
727
+ function scaleDown(s, w, h) {
728
+ const c = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(w, h) : Object.assign(document.createElement('canvas'), { width: w, height: h });
729
+ const ctx = c.getContext('2d');
730
+ if (typeof ImageData !== 'undefined' && s instanceof ImageData) {
731
+ const tmp = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(s.width, s.height) : Object.assign(document.createElement('canvas'), { width: s.width, height: s.height });
732
+ tmp.getContext('2d').putImageData(s, 0, 0);
733
+ ctx.drawImage(tmp, 0, 0, w, h);
734
+ }
735
+ else
736
+ ctx.drawImage(s, 0, 0, w, h);
737
+ return c;
738
+ }