@tioniq/sceniq 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.
@@ -0,0 +1,2470 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9;
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+ var _chunkOCHCBJJEcjs = require('./chunk-OCHCBJJE.cjs');
11
+
12
+ // src/input/keyboard-observer.ts
13
+ var _disposiq = require('@tioniq/disposiq');
14
+ var _eventiq = require('@tioniq/eventiq');
15
+ var KeyboardObserver = (_class = class {
16
+ __init() {this._listeners = new (0, _disposiq.DisposableStore)()}
17
+
18
+
19
+ constructor(element) {;_class.prototype.__init.call(this);
20
+ this.onKeyDown = createKeyEventObserver(element, "keydown", this._listeners);
21
+ this.onKeyUp = createKeyEventObserver(element, "keyup", this._listeners);
22
+ }
23
+ /** Removes every key listener, whoever still subscribes; nothing is raised afterwards. The scene calls it. */
24
+ dispose() {
25
+ this._listeners.dispose();
26
+ }
27
+ }, _class);
28
+ function createKeyEventObserver(element, eventName, listeners) {
29
+ return new (0, _eventiq.LazyEventDispatcher)((dispatcher) => {
30
+ if (listeners.disposed) {
31
+ return _disposiq.emptyDisposable;
32
+ }
33
+ const listener = _disposiq.addEventListener.call(void 0, element, eventName, (e) => {
34
+ dispatcher.dispatch(convertKeyboardEvent(e));
35
+ });
36
+ listeners.add(listener);
37
+ return new (0, _disposiq.DisposableAction)(() => {
38
+ listeners.remove(listener);
39
+ listener.dispose();
40
+ });
41
+ });
42
+ }
43
+ function convertKeyboardEvent(event) {
44
+ return {
45
+ altKey: event.altKey,
46
+ ctrlKey: event.ctrlKey,
47
+ shiftKey: event.shiftKey,
48
+ metaKey: event.metaKey,
49
+ key: event.key,
50
+ code: event.code,
51
+ repeat: event.repeat,
52
+ preventDefault: () => event.preventDefault(),
53
+ get defaultPrevented() {
54
+ return event.defaultPrevented;
55
+ }
56
+ };
57
+ }
58
+
59
+ // src/input/pointer-action-event.ts
60
+ function createPointerActionEvent(params) {
61
+ const { context, type, observeEvent: e, viewportPosition, parent } = params;
62
+ const clickSlop = parent ? parent.clickSlop : _nullishCoalesce(params.clickSlop, () => ( 5));
63
+ const deliverClick = parent ? (dispatch) => parent.deliverClick(dispatch) : _nullishCoalesce(params.deliverClick, () => ( callNow));
64
+ let position = params.position;
65
+ if (!position) {
66
+ const point = context.getTransform().inverse().transformPoint(new DOMPoint(viewportPosition.x, viewportPosition.y));
67
+ position = new (0, _chunkOCHCBJJEcjs.Point)(point.x, point.y);
68
+ }
69
+ return {
70
+ type,
71
+ context,
72
+ altKey: e.altKey,
73
+ ctrlKey: e.ctrlKey,
74
+ shiftKey: e.shiftKey,
75
+ metaKey: e.metaKey,
76
+ button: e.button,
77
+ viewportPosition,
78
+ movement: e.movement,
79
+ pointerId: _nullishCoalesce(e.pointerId, () => ( 1)),
80
+ pointerType: _nullishCoalesce(e.pointerType, () => ( "mouse")),
81
+ get cursor() {
82
+ return parent != null ? parent.cursor : this._cursor;
83
+ },
84
+ set cursor(value) {
85
+ if (parent != null) {
86
+ parent.cursor = value;
87
+ } else {
88
+ this._cursor = value;
89
+ }
90
+ },
91
+ get target() {
92
+ return parent != null ? parent.target : this._target;
93
+ },
94
+ set target(value) {
95
+ if (parent != null) {
96
+ parent.target = value;
97
+ } else {
98
+ this._target = value;
99
+ }
100
+ },
101
+ position,
102
+ clickSlop,
103
+ deliverClick,
104
+ with(overrides) {
105
+ const newContext = _nullishCoalesce(overrides.context, () => ( context));
106
+ const newViewport = _nullishCoalesce(overrides.viewportPosition, () => ( viewportPosition));
107
+ return createPointerActionEvent({
108
+ context: newContext,
109
+ type: _nullishCoalesce(overrides.type, () => ( type)),
110
+ observeEvent: e,
111
+ viewportPosition: newViewport,
112
+ // The position follows the context unless given, or unless nothing it depends on changed.
113
+ position: _nullishCoalesce(overrides.position, () => ( (overrides.context == null && overrides.viewportPosition == null ? this.position : void 0))),
114
+ parent: this
115
+ });
116
+ }
117
+ };
118
+ }
119
+ function callNow(dispatch) {
120
+ dispatch();
121
+ }
122
+
123
+ // src/input/pointer-observer.ts
124
+
125
+
126
+ var PointerObserver = (_class2 = class {
127
+
128
+ /** Every DOM listener attached, so {@link dispose} can remove them whoever still subscribes. */
129
+ __init2() {this._listeners = new (0, _disposiq.DisposableStore)()}
130
+
131
+ __init3() {this._activePointers = /* @__PURE__ */ new Map()}
132
+ __init4() {this._lastPositions = /* @__PURE__ */ new Map()}
133
+ __init5() {this._coreUsers = 0}
134
+ __init6() {this._coreSubscription = null}
135
+
136
+
137
+
138
+ /** The browser took the pointer away (a scroll gesture, a lost capture, the window losing focus). */
139
+
140
+
141
+
142
+
143
+ /** Subscribing prevents the browser's context menu on the element. */
144
+
145
+ constructor(element, options) {;_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);_class2.prototype.__init6.call(this);
146
+ this._element = element;
147
+ this._capture = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _ => _.capture]), () => ( true));
148
+ this.onPointerDown = this._createCoreDispatcher();
149
+ this.onPointerMove = this._createCoreDispatcher();
150
+ this.onPointerUp = this._createCoreDispatcher();
151
+ this.onPointerCancel = this._createCoreDispatcher();
152
+ this.onPointerEnter = this._createCoreDispatcher();
153
+ this.onPointerLeave = this._createCoreDispatcher();
154
+ this.onWheel = new (0, _eventiq.LazyEventDispatcher)(
155
+ (dispatcher) => this._listen(
156
+ this._element,
157
+ "wheel",
158
+ (e) => {
159
+ dispatcher.dispatch(this._convertWheelEvent(e, this._viewportPosition(e)));
160
+ },
161
+ { passive: false }
162
+ )
163
+ );
164
+ this.onContextMenu = new (0, _eventiq.LazyEventDispatcher)(
165
+ (dispatcher) => this._listen(this._element, "contextmenu", (e) => {
166
+ e.preventDefault();
167
+ dispatcher.dispatch(this._convertMouseEvent(e, this._viewportPosition(e), _chunkOCHCBJJEcjs.Point.zero));
168
+ })
169
+ );
170
+ }
171
+ /** Whether {@link dispose} was called. */
172
+ get disposed() {
173
+ return this._listeners.disposed;
174
+ }
175
+ /**
176
+ * Removes every DOM listener, including those kept by subscribers that never unsubscribed (a
177
+ * controller whose disposable was dropped); nothing is raised afterwards. The scene calls it.
178
+ */
179
+ dispose() {
180
+ if (this._listeners.disposed) {
181
+ return;
182
+ }
183
+ this._listeners.dispose();
184
+ this._coreSubscription = null;
185
+ this._activePointers.clear();
186
+ this._lastPositions.clear();
187
+ }
188
+ /** Adds a DOM listener that {@link dispose} removes; none once disposed. */
189
+ _listen(target, name, handler, options) {
190
+ if (this._listeners.disposed) {
191
+ return _disposiq.emptyDisposable;
192
+ }
193
+ const listener = _disposiq.addEventListener.call(void 0, target, name, handler, options);
194
+ this._listeners.add(listener);
195
+ return new (0, _disposiq.DisposableAction)(() => {
196
+ this._listeners.remove(listener);
197
+ listener.dispose();
198
+ });
199
+ }
200
+ get element() {
201
+ return this._element;
202
+ }
203
+ /** The pointers currently down (or touching), by id, at their last position. */
204
+ get activePointers() {
205
+ return this._activePointers;
206
+ }
207
+ /**
208
+ * Forwards pointer and wheel events of an element laid over this one (a toolbar, a label) as if
209
+ * they happened on this element. Events outside this element's box are dropped.
210
+ */
211
+ addExternalElement(element, options) {
212
+ const store = new (0, _disposiq.DisposableStore)();
213
+ if (_nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.mouseEvents]), () => ( true))) {
214
+ const forward = (name, target) => {
215
+ store.add(
216
+ this._listen(element, name, (e) => {
217
+ const position = this._viewportPosition(e);
218
+ if (!this._isInside(position)) {
219
+ return;
220
+ }
221
+ target.dispatch(this._convertMouseEvent(e, position, this._movement(e, position)));
222
+ })
223
+ );
224
+ };
225
+ forward("pointerdown", this.onPointerDown);
226
+ forward("pointermove", this.onPointerMove);
227
+ forward("pointerup", this.onPointerUp);
228
+ forward("pointerleave", this.onPointerLeave);
229
+ forward("pointerenter", this.onPointerEnter);
230
+ }
231
+ if (_nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.wheelEvents]), () => ( true))) {
232
+ store.add(
233
+ this._listen(
234
+ element,
235
+ "wheel",
236
+ (e) => {
237
+ const position = this._viewportPosition(e);
238
+ if (!this._isInside(position)) {
239
+ return;
240
+ }
241
+ this.onWheel.dispatch(this._convertWheelEvent(e, position));
242
+ },
243
+ { passive: false }
244
+ )
245
+ );
246
+ }
247
+ return store;
248
+ }
249
+ /** Raises a leave as if the pointer left the element, for example when an overlay covers it. */
250
+ simulateMouseLeave() {
251
+ this._activePointers.clear();
252
+ this._lastPositions.clear();
253
+ this.onPointerLeave.dispatch({
254
+ altKey: false,
255
+ ctrlKey: false,
256
+ shiftKey: false,
257
+ metaKey: false,
258
+ button: -1,
259
+ buttons: 0,
260
+ viewportPosition: new (0, _chunkOCHCBJJEcjs.Point)(-1, -1),
261
+ movement: _chunkOCHCBJJEcjs.Point.zero,
262
+ pointerId: -1,
263
+ pointerType: "mouse",
264
+ isPrimary: true,
265
+ pressure: 0,
266
+ preventDefault: noop
267
+ });
268
+ }
269
+ /** A dispatcher whose subscription keeps the shared pointer listeners attached. */
270
+ _createCoreDispatcher() {
271
+ return new (0, _eventiq.LazyEventDispatcher)(() => {
272
+ this._acquireCore();
273
+ return new (0, _disposiq.DisposableAction)(() => this._releaseCore());
274
+ });
275
+ }
276
+ _acquireCore() {
277
+ if (this._coreUsers++ > 0 || this._listeners.disposed) {
278
+ return;
279
+ }
280
+ const element = this._element;
281
+ const store = new (0, _disposiq.DisposableStore)();
282
+ const on = (name, handler) => {
283
+ store.add(this._listen(element, name, handler));
284
+ };
285
+ on("pointerdown", (e) => {
286
+ e.preventDefault();
287
+ const position = this._viewportPosition(e);
288
+ this._activePointers.set(e.pointerId, position);
289
+ if (this._capture && typeof element.setPointerCapture === "function") {
290
+ try {
291
+ element.setPointerCapture(e.pointerId);
292
+ } catch (e2) {
293
+ }
294
+ }
295
+ const movement = this._movement(e, position);
296
+ this.onPointerDown.dispatch(this._convertMouseEvent(e, position, movement));
297
+ });
298
+ on("pointermove", (e) => {
299
+ const position = this._viewportPosition(e);
300
+ if (this._activePointers.has(e.pointerId)) {
301
+ this._activePointers.set(e.pointerId, position);
302
+ }
303
+ const movement = this._movement(e, position);
304
+ this.onPointerMove.dispatch(this._convertMouseEvent(e, position, movement));
305
+ });
306
+ const end = (e, target) => {
307
+ const position = this._viewportPosition(e);
308
+ const movement = this._movement(e, position);
309
+ const wasActive = this._activePointers.delete(e.pointerId);
310
+ if (e.pointerType !== "mouse") {
311
+ this._lastPositions.delete(e.pointerId);
312
+ }
313
+ if (wasActive || target === this.onPointerUp) {
314
+ target.dispatch(this._convertMouseEvent(e, position, movement));
315
+ }
316
+ };
317
+ on("pointerup", (e) => end(e, this.onPointerUp));
318
+ on("pointercancel", (e) => end(e, this.onPointerCancel));
319
+ on("lostpointercapture", (e) => {
320
+ if (this._activePointers.has(e.pointerId)) {
321
+ end(e, this.onPointerCancel);
322
+ }
323
+ });
324
+ on("pointerenter", (e) => {
325
+ const position = this._viewportPosition(e);
326
+ this._lastPositions.set(e.pointerId, position);
327
+ this.onPointerEnter.dispatch(this._convertMouseEvent(e, position, _chunkOCHCBJJEcjs.Point.zero));
328
+ });
329
+ on("pointerleave", (e) => {
330
+ const position = this._viewportPosition(e);
331
+ if (!this._activePointers.has(e.pointerId)) {
332
+ this._lastPositions.delete(e.pointerId);
333
+ }
334
+ this.onPointerLeave.dispatch(this._convertMouseEvent(e, position, _chunkOCHCBJJEcjs.Point.zero));
335
+ });
336
+ this._coreSubscription = store;
337
+ }
338
+ _releaseCore() {
339
+ if (--this._coreUsers > 0) {
340
+ return;
341
+ }
342
+ _optionalChain([this, 'access', _4 => _4._coreSubscription, 'optionalAccess', _5 => _5.dispose, 'call', _6 => _6()]);
343
+ this._coreSubscription = null;
344
+ this._activePointers.clear();
345
+ this._lastPositions.clear();
346
+ }
347
+ _movement(e, position) {
348
+ const last = this._lastPositions.get(e.pointerId);
349
+ this._lastPositions.set(e.pointerId, position);
350
+ return last ? position.subtract(last) : _chunkOCHCBJJEcjs.Point.zero;
351
+ }
352
+ /** The event's position from the element's content box, where a canvas shows its bitmap. */
353
+ _viewportPosition(event) {
354
+ const element = this._element;
355
+ const rect = element.getBoundingClientRect();
356
+ let x = event.clientX - rect.left - (element.clientLeft || 0);
357
+ let y = event.clientY - rect.top - (element.clientTop || 0);
358
+ const style = typeof globalThis.getComputedStyle === "function" ? globalThis.getComputedStyle(element) : null;
359
+ if (style) {
360
+ const left = Number.parseFloat(style.paddingLeft);
361
+ const top = Number.parseFloat(style.paddingTop);
362
+ if (left > 0) x -= left;
363
+ if (top > 0) y -= top;
364
+ }
365
+ return new (0, _chunkOCHCBJJEcjs.Point)(x, y);
366
+ }
367
+ _isInside(position) {
368
+ const element = this._element;
369
+ return position.x >= 0 && position.y >= 0 && position.x <= element.clientWidth && position.y <= element.clientHeight;
370
+ }
371
+ _convertMouseEvent(event, viewportPosition, movement) {
372
+ const pointer = event;
373
+ return {
374
+ altKey: event.altKey,
375
+ ctrlKey: event.ctrlKey,
376
+ shiftKey: event.shiftKey,
377
+ metaKey: event.metaKey,
378
+ button: event.button,
379
+ buttons: event.buttons,
380
+ viewportPosition,
381
+ movement,
382
+ pointerId: _nullishCoalesce(pointer.pointerId, () => ( 1)),
383
+ pointerType: pointer.pointerType || "mouse",
384
+ isPrimary: _nullishCoalesce(pointer.isPrimary, () => ( true)),
385
+ pressure: _nullishCoalesce(pointer.pressure, () => ( 0)),
386
+ preventDefault: () => event.preventDefault()
387
+ };
388
+ }
389
+ _convertWheelEvent(event, viewportPosition) {
390
+ return {
391
+ altKey: event.altKey,
392
+ ctrlKey: event.ctrlKey,
393
+ shiftKey: event.shiftKey,
394
+ metaKey: event.metaKey,
395
+ viewportPosition,
396
+ delta: new (0, _chunkOCHCBJJEcjs.Point)(event.deltaX, event.deltaY),
397
+ deltaMode: event.deltaMode,
398
+ preventDefault: () => event.preventDefault()
399
+ };
400
+ }
401
+ }, _class2);
402
+ function noop() {
403
+ }
404
+
405
+ // src/layout-epoch.ts
406
+
407
+
408
+ var epoch = 0;
409
+ var relayout = /* @__PURE__ */ new (0, _eventiq.EventDispatcher)();
410
+ function layoutEpoch() {
411
+ return epoch;
412
+ }
413
+ var onRelayout = relayout;
414
+ function relayoutAllViews() {
415
+ epoch++;
416
+ relayout.dispatch(epoch);
417
+ }
418
+ var fontWatchers = 0;
419
+ var fontSubscription = null;
420
+ function watchFontLoading() {
421
+ const fonts = _optionalChain([globalThis, 'access', _7 => _7.document, 'optionalAccess', _8 => _8.fonts]);
422
+ if (!fonts || typeof fonts.addEventListener !== "function") {
423
+ return new (0, _disposiq.DisposableAction)(() => {
424
+ });
425
+ }
426
+ if (fontWatchers++ === 0) {
427
+ fontSubscription = _disposiq.addEventListener.call(void 0, fonts, "loadingdone", relayoutAllViews);
428
+ }
429
+ return new (0, _disposiq.DisposableAction)(() => {
430
+ if (--fontWatchers === 0) {
431
+ _optionalChain([fontSubscription, 'optionalAccess', _9 => _9.dispose, 'call', _10 => _10()]);
432
+ fontSubscription = null;
433
+ }
434
+ });
435
+ }
436
+
437
+ // src/animation/interpolator.ts
438
+ var AnimationInterpolator = class {
439
+ };
440
+ var LinearInterpolator = class extends AnimationInterpolator {
441
+ interpolate(progress) {
442
+ return progress;
443
+ }
444
+ };
445
+ var EaseInInterpolator = class extends AnimationInterpolator {
446
+ interpolate(progress) {
447
+ return progress * progress;
448
+ }
449
+ };
450
+ var EaseOutInterpolator = class extends AnimationInterpolator {
451
+ interpolate(progress) {
452
+ return Math.sqrt(progress);
453
+ }
454
+ };
455
+ var EaseInOutInterpolator = class extends AnimationInterpolator {
456
+ interpolate(progress) {
457
+ return 0.5 - Math.cos(progress * Math.PI) / 2;
458
+ }
459
+ };
460
+ var BounceInterpolator = class extends AnimationInterpolator {
461
+ interpolate(t) {
462
+ if (t < 1 / 2.75) {
463
+ return 7.5625 * t * t;
464
+ }
465
+ if (t < 2 / 2.75) {
466
+ t -= 1.5 / 2.75;
467
+ return 7.5625 * t * t + 0.75;
468
+ }
469
+ if (t < 2.5 / 2.75) {
470
+ t -= 2.25 / 2.75;
471
+ return 7.5625 * t * t + 0.9375;
472
+ }
473
+ t -= 2.625 / 2.75;
474
+ return 7.5625 * t * t + 0.984375;
475
+ }
476
+ };
477
+ var OvershootInterpolator = class extends AnimationInterpolator {
478
+
479
+ constructor(tension) {
480
+ super();
481
+ this._tension = tension;
482
+ }
483
+ interpolate(progress) {
484
+ progress -= 1;
485
+ return progress * progress * ((this._tension + 1) * progress + this._tension) + 1;
486
+ }
487
+ };
488
+ var animationInterpolators = {
489
+ linear: new LinearInterpolator(),
490
+ easeIn: new EaseInInterpolator(),
491
+ easeOut: new EaseOutInterpolator(),
492
+ easeInOut: new EaseInOutInterpolator(),
493
+ bounce: new BounceInterpolator(),
494
+ overshoot: new OvershootInterpolator(1.70158)
495
+ };
496
+
497
+ // src/update/scheduler.ts
498
+
499
+ var FrameScheduler = (_class3 = class {
500
+ __init7() {this._onUpdate = new (0, _eventiq.EventSafeDispatcher)()}
501
+ __init8() {this._reportError = (error) => this.reportError(error)}
502
+ __init9() {this._actions = []}
503
+
504
+ __init10() {this._autoUpdate = false}
505
+ /** Holders of the frame loop (see acquireAutoUpdate); the loop runs while any holds it. */
506
+ __init11() {this._holders = 0}
507
+ __init12() {this._scheduled = false}
508
+ __init13() {this._updating = false}
509
+ /**
510
+ * Receives errors thrown while a frame runs (see {@link FrameSchedulerOptions.onError}). Default
511
+ * `console.error`.
512
+ */
513
+
514
+ constructor(options) {;_class3.prototype.__init7.call(this);_class3.prototype.__init8.call(this);_class3.prototype.__init9.call(this);_class3.prototype.__init10.call(this);_class3.prototype.__init11.call(this);_class3.prototype.__init12.call(this);_class3.prototype.__init13.call(this);
515
+ this._requestFrame = _optionalChain([options, 'optionalAccess', _11 => _11.requestFrame]);
516
+ this.onError = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _12 => _12.onError]), () => ( defaultOnError));
517
+ }
518
+ /** Hands an error to {@link onError}; an error thrown by the handler itself goes to the console. */
519
+ reportError(error) {
520
+ try {
521
+ this.onError(error);
522
+ } catch (handlerError) {
523
+ console.error(error, handlerError);
524
+ }
525
+ }
526
+ get updating() {
527
+ return this._updating;
528
+ }
529
+ /**
530
+ * Raised once per frame, after the actions passed to {@link scheduleUpdate}. Scenes draw here. A
531
+ * listener that throws is reported to {@link onError} and does not stop the others.
532
+ */
533
+ get onUpdate() {
534
+ return this._onUpdate;
535
+ }
536
+ /** Whether a frame is requested after every frame: the flag is set, or someone holds the loop. */
537
+ get autoUpdate() {
538
+ return this._autoUpdate || this._holders > 0;
539
+ }
540
+ set autoUpdate(value) {
541
+ this._autoUpdate = value;
542
+ if (value && !this._scheduled) {
543
+ this.scheduleUpdate();
544
+ }
545
+ }
546
+ /** How many hold the frame loop now. */
547
+ get holders() {
548
+ return this._holders;
549
+ }
550
+ /**
551
+ * Keeps the frame loop running until the returned release is called. Every animation holds it for
552
+ * its own life, so the first of two overlapping animations to finish does not stop the frames the
553
+ * other still needs. Releasing twice does nothing.
554
+ */
555
+ acquireAutoUpdate() {
556
+ this._holders++;
557
+ if (!this._scheduled) {
558
+ this.scheduleUpdate();
559
+ }
560
+ let released = false;
561
+ return () => {
562
+ if (released) {
563
+ return;
564
+ }
565
+ released = true;
566
+ this._holders--;
567
+ };
568
+ }
569
+ /** Requests a frame, running `action` at its start. Requests made before the frame share it. */
570
+ scheduleUpdate(action) {
571
+ if (action != void 0) {
572
+ this._actions.push(action);
573
+ }
574
+ if (this._scheduled) {
575
+ return;
576
+ }
577
+ this._scheduled = true;
578
+ const requestFrame = _nullishCoalesce(this._requestFrame, () => ( globalThis.requestAnimationFrame));
579
+ requestFrame(() => this._update());
580
+ }
581
+ /**
582
+ * Runs `callback` once per frame with the eased progress from 0 to 1 over `duration` milliseconds,
583
+ * holding the frame loop meanwhile. Disposing the result stops it early. A callback that throws
584
+ * stops the animation (without `onFinished`) and is reported to {@link onError}.
585
+ */
586
+ animate(callback, options) {
587
+ const duration = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _13 => _13.duration]), () => ( 1e3));
588
+ const interpolate = _optionalChain([options, 'optionalAccess', _14 => _14.interpolate]);
589
+ const now = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _15 => _15.now]), () => ( (() => performance.now())));
590
+ const startTime = now();
591
+ let release = null;
592
+ let subscription = null;
593
+ let finished = false;
594
+ const stop = () => {
595
+ if (finished) {
596
+ return;
597
+ }
598
+ finished = true;
599
+ _optionalChain([subscription, 'optionalAccess', _16 => _16.dispose, 'call', _17 => _17()]);
600
+ _optionalChain([release, 'optionalCall', _18 => _18()]);
601
+ };
602
+ const step = () => {
603
+ if (finished) {
604
+ return;
605
+ }
606
+ const progress = duration > 0 ? Math.min(1, (now() - startTime) / duration) : 1;
607
+ try {
608
+ callback(interpolate ? interpolate(progress) : progress);
609
+ } catch (error) {
610
+ stop();
611
+ this.reportError(error);
612
+ return;
613
+ }
614
+ if (progress >= 1) {
615
+ stop();
616
+ _optionalChain([options, 'optionalAccess', _19 => _19.onFinished, 'optionalCall', _20 => _20()]);
617
+ }
618
+ };
619
+ subscription = this._onUpdate.subscribe(step);
620
+ release = this.acquireAutoUpdate();
621
+ step();
622
+ return { dispose: stop };
623
+ }
624
+ _update() {
625
+ this._scheduled = false;
626
+ this._updating = true;
627
+ const actions = this._actions.splice(0);
628
+ for (const action of actions) {
629
+ try {
630
+ action();
631
+ } catch (error) {
632
+ this.reportError(error);
633
+ }
634
+ }
635
+ this._onUpdate.dispatch(void 0, this._reportError);
636
+ this._updating = false;
637
+ if (this.autoUpdate && !this._scheduled) {
638
+ this.scheduleUpdate();
639
+ }
640
+ }
641
+ }, _class3);
642
+ function defaultOnError(error) {
643
+ console.error("sceniq: error during a frame", error);
644
+ }
645
+ var defaultScheduler = /* @__PURE__ */ new FrameScheduler();
646
+
647
+ // src/animation/reduced-motion.ts
648
+ function prefersReducedMotion() {
649
+ const matchMedia = globalThis.matchMedia;
650
+ if (typeof matchMedia !== "function") {
651
+ return false;
652
+ }
653
+ try {
654
+ return matchMedia("(prefers-reduced-motion: reduce)").matches;
655
+ } catch (e3) {
656
+ return false;
657
+ }
658
+ }
659
+ function motionDuration(duration, ignoreReducedMotion) {
660
+ return !ignoreReducedMotion && duration > 0 && prefersReducedMotion() ? 0 : duration;
661
+ }
662
+
663
+ // src/camera.ts
664
+
665
+
666
+ var Camera = (_class4 = class {
667
+ __init14() {this._onMatrixChanged = new (0, _eventiq.EventDispatcher)()}
668
+ __init15() {this._zoom = new (0, _eventiq.Vary)(1)}
669
+
670
+ __init16() {this._zoomInterceptors = []}
671
+
672
+
673
+
674
+ __init17() {this._disposables = new (0, _disposiq.DisposableStore)()}
675
+ __init18() {this._animation = null}
676
+ /** The inverse of the matrix, computed when first needed after a change. */
677
+ __init19() {this._inverse = null}
678
+ /** @param context The context whose canvas the camera shows; its size is the screen. */
679
+ constructor(context, options) {;_class4.prototype.__init14.call(this);_class4.prototype.__init15.call(this);_class4.prototype.__init16.call(this);_class4.prototype.__init17.call(this);_class4.prototype.__init18.call(this);_class4.prototype.__init19.call(this);
680
+ this._context = context;
681
+ this._scheduler = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _21 => _21.scheduler]), () => ( defaultScheduler));
682
+ this._matrix = context.getTransform().translate();
683
+ this._onMatrixChanged.subscribe(() => {
684
+ this._inverse = null;
685
+ });
686
+ if (_optionalChain([options, 'optionalAccess', _22 => _22.dpr])) {
687
+ let previousDpr = 1;
688
+ this._disposables.add(
689
+ options.dpr.subscribe((dpr) => {
690
+ const scale = dpr / previousDpr;
691
+ previousDpr = dpr;
692
+ if (scale === 1) {
693
+ return;
694
+ }
695
+ this._matrix.scaleSelf(scale, scale);
696
+ this._onMatrixChanged.dispatch(this._matrix);
697
+ })
698
+ );
699
+ this._dpr = options.dpr;
700
+ } else {
701
+ this._dpr = _eventiq.createConstVar.call(void 0, 1);
702
+ }
703
+ }
704
+ dispose() {
705
+ this._disposables.dispose();
706
+ }
707
+ get onMatrixChanged() {
708
+ return this._onMatrixChanged;
709
+ }
710
+ /**
711
+ * How many CSS pixels one world unit takes on screen: 1 at the start. The device pixel ratio is
712
+ * never part of it (the matrix has it on top). Derived from the matrix after every change, however
713
+ * the camera was moved.
714
+ */
715
+ get currentZoom() {
716
+ return this._zoom;
717
+ }
718
+ /**
719
+ * World to the surface's device pixels, the device pixel ratio included. Read-only: change it with
720
+ * {@link setMatrix}, {@link zoom} or {@link pan}, so listeners hear of it.
721
+ */
722
+ get matrix() {
723
+ return this._matrix;
724
+ }
725
+ get dpr() {
726
+ return this._dpr;
727
+ }
728
+ /** Device pixels to world: the inverse of {@link Camera.matrix}, kept until the matrix changes. */
729
+ get inverseMatrix() {
730
+ this._inverse ??= this._matrix.inverse();
731
+ return this._inverse;
732
+ }
733
+ /** The frame loop the camera's animations run on. */
734
+ get scheduler() {
735
+ return this._scheduler;
736
+ }
737
+ /** Whether an animation of this camera is running. */
738
+ get animating() {
739
+ return this._animation !== null;
740
+ }
741
+ /** Stops the running animation, if any, where it is. Pan and zoom controls call it when touched. */
742
+ stopAnimation() {
743
+ const animation = this._animation;
744
+ this._animation = null;
745
+ _optionalChain([animation, 'optionalAccess', _23 => _23.dispose, 'call', _24 => _24()]);
746
+ }
747
+ addZoomInterceptor(interceptor) {
748
+ this._zoomInterceptors.push(interceptor);
749
+ return new (0, _disposiq.DisposableAction)(() => {
750
+ const index = this._zoomInterceptors.indexOf(interceptor);
751
+ if (index >= 0) {
752
+ this._zoomInterceptors.splice(index, 1);
753
+ }
754
+ });
755
+ }
756
+ /**
757
+ * Multiplies the zoom by `zoom` about `anchor` (world coordinates; the world origin by default),
758
+ * after the zoom interceptors (`minZoom`/`maxZoom` among them) had their say. False when nothing
759
+ * changed.
760
+ */
761
+ zoom(zoom, anchor) {
762
+ const matrix = this._matrix;
763
+ const interceptors = this._zoomInterceptors;
764
+ let data = { zoom, anchor };
765
+ const currentZoomValue = this._zoom.value;
766
+ for (const interceptor of interceptors) {
767
+ const result = interceptor(data, currentZoomValue);
768
+ if (!result) {
769
+ continue;
770
+ }
771
+ if (result === "ignore") {
772
+ return false;
773
+ }
774
+ data = result;
775
+ }
776
+ const scale = data.zoom;
777
+ if (scale === 1 || !(scale > 0) || !Number.isFinite(scale)) {
778
+ return false;
779
+ }
780
+ anchor = data.anchor;
781
+ if (anchor) {
782
+ matrix.translateSelf(anchor.x, anchor.y);
783
+ matrix.scaleSelf(scale, scale);
784
+ matrix.translateSelf(-anchor.x, -anchor.y);
785
+ } else {
786
+ matrix.scaleSelf(scale, scale);
787
+ }
788
+ this._changed();
789
+ return true;
790
+ }
791
+ /**
792
+ * Replaces the matrix (device pixels, the device pixel ratio included, like {@link Camera.matrix}). A zoom
793
+ * outside the interceptors' limits is brought within them about the middle of the screen.
794
+ */
795
+ setMatrix(matrix) {
796
+ let next = DOMMatrix.fromMatrix(matrix);
797
+ const wanted = Math.hypot(next.a, next.b) / this._dpr.value;
798
+ const allowed = this.limitZoom(wanted);
799
+ if (allowed !== wanted && wanted > 0) {
800
+ const scale = allowed / wanted;
801
+ const canvas = this._context.canvas;
802
+ const cx = canvas.width / 2;
803
+ const cy = canvas.height / 2;
804
+ next = new DOMMatrix().translateSelf(cx, cy).scaleSelf(scale, scale).translateSelf(-cx, -cy).multiplySelf(next);
805
+ }
806
+ const current = this._matrix;
807
+ if (current.a === next.a && current.b === next.b && current.c === next.c && current.d === next.d && current.e === next.e && current.f === next.f) {
808
+ return;
809
+ }
810
+ current.setMatrixValue(next.toString());
811
+ this._changed();
812
+ }
813
+ /** Sets the zoom to `zoom` about `anchor` (world coordinates), within the interceptors' limits. */
814
+ zoomTo(zoom, anchor) {
815
+ return this.zoom(zoom / this._zoom.value, anchor);
816
+ }
817
+ pan(delta) {
818
+ this._matrix.translateSelf(delta.x, delta.y);
819
+ this._onMatrixChanged.dispatch(this._matrix);
820
+ }
821
+ /** After the matrix's scale changed: the zoom follows from it, then listeners hear of it. */
822
+ _changed() {
823
+ const m = this._matrix;
824
+ this._zoom.value = Math.hypot(m.a, m.b) / this._dpr.value;
825
+ this._onMatrixChanged.dispatch(m);
826
+ }
827
+ panTo(point) {
828
+ const currentPan = this.getCurrentPan();
829
+ this.pan(point.subtract(currentPan).negate());
830
+ }
831
+ panCenterTo(point) {
832
+ const canvas = this._context.canvas;
833
+ const screenCenter = this.deviceToWorld(new (0, _chunkOCHCBJJEcjs.Point)(canvas.width / 2, canvas.height / 2));
834
+ this.pan(point.subtract(screenCenter).negate());
835
+ }
836
+ panCenterToAnimated(point, animationOptions) {
837
+ const canvas = this._context.canvas;
838
+ const startScreenCenter = this.deviceToWorld(new (0, _chunkOCHCBJJEcjs.Point)(canvas.width / 2, canvas.height / 2));
839
+ return this._animate((progress) => {
840
+ this.panCenterTo(startScreenCenter.add(point.subtract(startScreenCenter).multiply(progress)));
841
+ }, animationOptions);
842
+ }
843
+ zoomToAnimated(zoom, options) {
844
+ zoom = this.limitZoom(zoom);
845
+ const startZoom = this._zoom.value;
846
+ const diff = zoom - startZoom;
847
+ const anchor = _optionalChain([options, 'optionalAccess', _25 => _25.anchor]);
848
+ return this._animate((progress) => {
849
+ const startAnchor = _nullishCoalesce(anchor, () => ( this.getScreenCenterWorld()));
850
+ const currentMustBe = startZoom + diff * progress;
851
+ const currentIs = this._zoom.value;
852
+ const updated = this.zoom(currentMustBe / currentIs, startAnchor);
853
+ if (!updated) {
854
+ this._onMatrixChanged.dispatch(this._matrix);
855
+ }
856
+ }, options);
857
+ }
858
+ /** Shows world point `center` in the middle of the screen at `zoom`, in one step. */
859
+ setView(center, zoom) {
860
+ this.zoomTo(zoom);
861
+ this.panCenterTo(center);
862
+ }
863
+ /**
864
+ * Moves to `center` and `zoom` over time: the centre moves in a straight line and the zoom changes
865
+ * by the same factor every frame, so zooming far in or out looks even. Starting another animation, or
866
+ * {@link stopAnimation}, stops it.
867
+ */
868
+ flyTo(center, zoom, options) {
869
+ const startCenter = this.getScreenCenterWorld();
870
+ const startZoom = this._zoom.value;
871
+ const ratio = this.limitZoom(zoom) / startZoom;
872
+ return this._animate((progress) => {
873
+ this.setView(startCenter.add(center.subtract(startCenter).multiply(progress)), startZoom * ratio ** progress);
874
+ }, options);
875
+ }
876
+ /**
877
+ * The centre and zoom that fit `rect` (world units) on screen, inside `padding` CSS pixels, within
878
+ * the zoom interceptors' limits (those of `attachZoomPan`'s `minZoom` and `maxZoom` among them).
879
+ */
880
+ viewForBounds(rect, padding) {
881
+ const dpr = this._dpr.value;
882
+ const canvas = this._context.canvas;
883
+ const { top, right, bottom, left } = toPadding(padding);
884
+ const width = Math.max(1, canvas.width / dpr - left - right);
885
+ const height = Math.max(1, canvas.height / dpr - top - bottom);
886
+ const zoomX = rect.width > 0 ? width / rect.width : Infinity;
887
+ const zoomY = rect.height > 0 ? height / rect.height : Infinity;
888
+ let zoom = Math.min(zoomX, zoomY);
889
+ if (!Number.isFinite(zoom)) {
890
+ zoom = this._zoom.value;
891
+ }
892
+ zoom = this.limitZoom(zoom);
893
+ const center = new (0, _chunkOCHCBJJEcjs.Point)(rect.x + rect.width / 2 + (right - left) / 2 / zoom, rect.y + rect.height / 2 + (bottom - top) / 2 / zoom);
894
+ return { center, zoom };
895
+ }
896
+ /**
897
+ * Zooms and pans so `rect` (world units) fills the screen inside `padding`. With `animate` it flies
898
+ * there (see {@link flyTo}); the result stops the animation. The zoom stays within the interceptors'
899
+ * limits and `maxZoom`, so fitting a single point does not zoom in forever.
900
+ */
901
+ fitBounds(rect, options) {
902
+ const view = this.viewForBounds(rect, _optionalChain([options, 'optionalAccess', _26 => _26.padding]));
903
+ const zoom = _optionalChain([options, 'optionalAccess', _27 => _27.maxZoom]) !== void 0 ? Math.min(view.zoom, options.maxZoom) : view.zoom;
904
+ const animate = _optionalChain([options, 'optionalAccess', _28 => _28.animate]);
905
+ if (animate) {
906
+ return this.flyTo(view.center, zoom, typeof animate === "object" ? animate : { duration: 500, interpolator: animationInterpolators.easeInOut });
907
+ }
908
+ this.stopAnimation();
909
+ this.setView(view.center, zoom);
910
+ return noopDisposable;
911
+ }
912
+ /** `zoom` brought within the zoom interceptors' limits, as `zoom()` would bring it. */
913
+ limitZoom(zoom) {
914
+ const current = this._zoom.value;
915
+ let data = { zoom: zoom / current };
916
+ for (const interceptor of this._zoomInterceptors) {
917
+ const result = interceptor(data, current);
918
+ if (!result) {
919
+ continue;
920
+ }
921
+ if (result === "ignore") {
922
+ return current;
923
+ }
924
+ data = result;
925
+ }
926
+ return current * data.zoom;
927
+ }
928
+ getCurrentPan() {
929
+ const originalPoint = new DOMPoint(0, 0);
930
+ const point = this.inverseMatrix.transformPoint(originalPoint);
931
+ return new (0, _chunkOCHCBJJEcjs.Point)(point.x, point.y);
932
+ }
933
+ getScreenCenter() {
934
+ const canvas = this._context.canvas;
935
+ return new (0, _chunkOCHCBJJEcjs.Point)(canvas.width / 2, canvas.height / 2);
936
+ }
937
+ getScreenCenterWorld() {
938
+ const canvas = this._context.canvas;
939
+ return this.deviceToWorld(new (0, _chunkOCHCBJJEcjs.Point)(canvas.width / 2, canvas.height / 2));
940
+ }
941
+ getCurrentEnd() {
942
+ const originalPoint = new DOMPoint(this._context.canvas.width, this._context.canvas.height);
943
+ const point = this.inverseMatrix.transformPoint(originalPoint);
944
+ return new (0, _chunkOCHCBJJEcjs.Point)(point.x, point.y);
945
+ }
946
+ /** A point in CSS pixels from the surface's top-left (a pointer event's position) in world coordinates. */
947
+ cssToWorld(point) {
948
+ const dpr = this._dpr.value;
949
+ return this.deviceToWorld(new (0, _chunkOCHCBJJEcjs.Point)(point.x * dpr, point.y * dpr));
950
+ }
951
+ /** A point in the surface's device pixels in world coordinates. */
952
+ deviceToWorld(point) {
953
+ const result = this.inverseMatrix.transformPoint(new DOMPoint(point.x, point.y));
954
+ return new (0, _chunkOCHCBJJEcjs.Point)(result.x, result.y);
955
+ }
956
+ /** A world point in CSS pixels from the surface's top-left. */
957
+ worldToCss(point) {
958
+ const device = this.worldToDevice(point);
959
+ const dpr = this._dpr.value;
960
+ return new (0, _chunkOCHCBJJEcjs.Point)(device.x / dpr, device.y / dpr);
961
+ }
962
+ /** A world point in the surface's device pixels. */
963
+ worldToDevice(point) {
964
+ const result = this._matrix.transformPoint(new DOMPoint(point.x, point.y));
965
+ return new (0, _chunkOCHCBJJEcjs.Point)(result.x, result.y);
966
+ }
967
+ _animate(update, options) {
968
+ this.stopAnimation();
969
+ const duration = motionDuration(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _29 => _29.duration]), () => ( 1e3)), _optionalChain([options, 'optionalAccess', _30 => _30.ignoreReducedMotion]));
970
+ const onFinished = _optionalChain([options, 'optionalAccess', _31 => _31.onFinished]);
971
+ const interpolator = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _32 => _32.interpolator]), () => ( animationInterpolators.linear));
972
+ let animation = null;
973
+ animation = this._scheduler.animate(update, {
974
+ duration,
975
+ interpolate: (progress) => interpolator.interpolate(progress),
976
+ onFinished: () => {
977
+ if (this._animation === animation) {
978
+ this._animation = null;
979
+ }
980
+ _optionalChain([onFinished, 'optionalCall', _33 => _33()]);
981
+ }
982
+ });
983
+ if (duration > 0) {
984
+ this._animation = animation;
985
+ }
986
+ return {
987
+ dispose: () => {
988
+ if (this._animation === animation) {
989
+ this._animation = null;
990
+ }
991
+ _optionalChain([animation, 'optionalAccess', _34 => _34.dispose, 'call', _35 => _35()]);
992
+ }
993
+ };
994
+ }
995
+ }, _class4);
996
+ var noopDisposable = { dispose() {
997
+ } };
998
+ function toPadding(padding) {
999
+ if (padding === void 0) return { top: 0, right: 0, bottom: 0, left: 0 };
1000
+ if (typeof padding === "number") return { top: padding, right: padding, bottom: padding, left: padding };
1001
+ return { top: _nullishCoalesce(padding.top, () => ( 0)), right: _nullishCoalesce(padding.right, () => ( 0)), bottom: _nullishCoalesce(padding.bottom, () => ( 0)), left: _nullishCoalesce(padding.left, () => ( 0)) };
1002
+ }
1003
+ function createMinMaxZoomInterceptor(minZoom, maxZoom) {
1004
+ return (data, currentZoom) => {
1005
+ let zoom = data.zoom * currentZoom;
1006
+ if (minZoom != void 0 && zoom < minZoom) {
1007
+ zoom = minZoom;
1008
+ }
1009
+ if (maxZoom != void 0 && zoom > maxZoom) {
1010
+ zoom = maxZoom;
1011
+ }
1012
+ if (zoom === currentZoom) {
1013
+ return "ignore";
1014
+ }
1015
+ return {
1016
+ zoom: zoom / currentZoom,
1017
+ anchor: data.anchor
1018
+ };
1019
+ };
1020
+ }
1021
+
1022
+ // src/layouts/layout-context.ts
1023
+ var LayoutContext = class _LayoutContext {
1024
+
1025
+
1026
+
1027
+
1028
+ constructor(context, viewBox, offset, screenBounds) {
1029
+ this._context = context;
1030
+ this._viewBox = viewBox;
1031
+ this._offset = offset;
1032
+ this._screenBounds = screenBounds;
1033
+ }
1034
+ get context() {
1035
+ return this._context;
1036
+ }
1037
+ get viewBox() {
1038
+ return this._viewBox;
1039
+ }
1040
+ get offset() {
1041
+ return this._offset;
1042
+ }
1043
+ get screenBounds() {
1044
+ return this._screenBounds;
1045
+ }
1046
+ isVisible(bounds) {
1047
+ return this._screenBounds.intersects(bounds.shift(this._offset));
1048
+ }
1049
+ static create(context) {
1050
+ const topLeft = getTransformedPoint(context, 0, 0);
1051
+ const bottomRight = getTransformedPoint(context, context.canvas.width, context.canvas.height);
1052
+ const screenBounds = _chunkOCHCBJJEcjs.RectBounds.fromTwoPoints(_chunkOCHCBJJEcjs.Point.fromDomPoint(topLeft), _chunkOCHCBJJEcjs.Point.fromDomPoint(bottomRight));
1053
+ return new _LayoutContext(context, _chunkOCHCBJJEcjs.ViewBox.max, _chunkOCHCBJJEcjs.Point.zero, screenBounds);
1054
+ }
1055
+ };
1056
+ function getTransformedPoint(context, x, y) {
1057
+ const originalPoint = new DOMPoint(x, y);
1058
+ return context.getTransform().invertSelf().transformPoint(originalPoint);
1059
+ }
1060
+
1061
+ // src/layer.ts
1062
+
1063
+
1064
+ // src/render-utils.ts
1065
+ function clearCanvas(context) {
1066
+ context.save();
1067
+ context.setTransform(1, 0, 0, 1, 0, 0);
1068
+ context.clearRect(0, 0, context.canvas.width, context.canvas.height);
1069
+ context.restore();
1070
+ }
1071
+
1072
+ // src/layer.ts
1073
+
1074
+ var OFFSCREEN_MARGIN = 0.25;
1075
+ var LAYOUT_SCALE_TOLERANCE = 1.5;
1076
+ var Layer = (_class5 = class {
1077
+ constructor(canvas, context, _name, options) {;_class5.prototype.__init20.call(this);_class5.prototype.__init21.call(this);_class5.prototype.__init22.call(this);_class5.prototype.__init23.call(this);_class5.prototype.__init24.call(this);_class5.prototype.__init25.call(this);_class5.prototype.__init26.call(this);
1078
+ this.context = context;
1079
+ this._name = _name;
1080
+ this._canvas = canvas;
1081
+ this._skipOffscreenLayout = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _36 => _36.skipOffscreenLayout]), () => ( false));
1082
+ }
1083
+
1084
+
1085
+
1086
+ __init20() {this._components = []}
1087
+ /** The components by what they paint, so removing one does not search the list. */
1088
+ __init21() {this._byItem = /* @__PURE__ */ new Map()}
1089
+ __init22() {this._onInvalidate = new (0, _eventiq.EventDispatcher)()}
1090
+ __init23() {this._previousTransform = null}
1091
+
1092
+ __init24() {this._disposed = false}
1093
+ /** `layoutEpoch()` when the layer last painted: a newer epoch means its layouts may be stale. */
1094
+ __init25() {this._paintedEpoch = -1}
1095
+ /** Something changed since the last frame: the layer must lay out and check its components. */
1096
+ __init26() {this._changed = true}
1097
+ get name() {
1098
+ return this._name;
1099
+ }
1100
+ get onInvalidate() {
1101
+ return this._onInvalidate;
1102
+ }
1103
+ /** The surface this layer belongs to. */
1104
+ get surface() {
1105
+ return this._canvas;
1106
+ }
1107
+ /** Adds a component; the same as {@link addComponent}. */
1108
+ add(item, order) {
1109
+ return this.addComponent(item, order);
1110
+ }
1111
+ addComponent(item, order) {
1112
+ this._throwIfDisposed();
1113
+ this._addComponent(item, order);
1114
+ this._invalidate();
1115
+ return new (0, _disposiq.DisposableAction)(() => {
1116
+ this.removeComponent(item);
1117
+ });
1118
+ }
1119
+ /** Adds many components; disposing the result removes them all in one pass. */
1120
+ addComponents(items, order) {
1121
+ this._throwIfDisposed();
1122
+ for (const component of items) {
1123
+ this._addComponent(component, order);
1124
+ }
1125
+ this._invalidate();
1126
+ return new (0, _disposiq.DisposableAction)(() => this.removeComponents(items));
1127
+ }
1128
+ removeComponent(item) {
1129
+ const component = this._byItem.get(item);
1130
+ if (component === void 0) {
1131
+ return;
1132
+ }
1133
+ this._byItem.delete(item);
1134
+ const index = this._components.indexOf(component);
1135
+ if (index >= 0) {
1136
+ this._components.splice(index, 1);
1137
+ }
1138
+ component.subscriptions.dispose();
1139
+ this.invalidateForce();
1140
+ }
1141
+ /** Removes many components in one pass over the list, with one invalidation. */
1142
+ removeComponents(items) {
1143
+ const removed = /* @__PURE__ */ new Set();
1144
+ for (const item of items) {
1145
+ const component = this._byItem.get(item);
1146
+ if (component !== void 0) {
1147
+ this._byItem.delete(item);
1148
+ removed.add(component);
1149
+ }
1150
+ }
1151
+ if (removed.size === 0) {
1152
+ return;
1153
+ }
1154
+ let kept = 0;
1155
+ const components = this._components;
1156
+ for (let i = 0; i < components.length; i++) {
1157
+ const component = components[i];
1158
+ if (!removed.has(component)) {
1159
+ components[kept++] = component;
1160
+ }
1161
+ }
1162
+ components.length = kept;
1163
+ for (const component of removed) {
1164
+ component.subscriptions.dispose();
1165
+ }
1166
+ this.invalidateForce();
1167
+ }
1168
+ /** Whether {@link dispose} was called. */
1169
+ get disposed() {
1170
+ return this._disposed;
1171
+ }
1172
+ /**
1173
+ * Removes the layer from its surface, detaches every component (views stop following their
1174
+ * variables and their `onMounted` cleanups run) and releases the layer's bitmap. A surface disposes
1175
+ * its layers when it is disposed or when {@link Surface.removeLayer} removes one.
1176
+ */
1177
+ dispose() {
1178
+ if (this._disposed) {
1179
+ return;
1180
+ }
1181
+ this._disposed = true;
1182
+ this._canvas.removeLayer(this);
1183
+ const components = this._components.splice(0);
1184
+ this._byItem.clear();
1185
+ for (const component of components) {
1186
+ component.subscriptions.dispose();
1187
+ }
1188
+ this._previousTransform = null;
1189
+ const canvas = this.context.canvas;
1190
+ canvas.width = 0;
1191
+ canvas.height = 0;
1192
+ }
1193
+ _throwIfDisposed() {
1194
+ if (this._disposed) {
1195
+ throw new Error(`Layer ${this._name} is disposed`);
1196
+ }
1197
+ }
1198
+ invalidateForce() {
1199
+ this._previousTransform = null;
1200
+ this._invalidate();
1201
+ }
1202
+ _invalidate() {
1203
+ this._changed = true;
1204
+ this._onInvalidate.dispatch();
1205
+ }
1206
+ /** @internal Called by the surface each frame. */
1207
+ draw(canvasDrawState) {
1208
+ const startTime = performance.now();
1209
+ const drawables = this._components;
1210
+ const layerDrawState = {
1211
+ layer: this,
1212
+ time: 0,
1213
+ checkTime: 0,
1214
+ type: "draw",
1215
+ totalComponents: drawables.length,
1216
+ drewComponents: 0
1217
+ };
1218
+ canvasDrawState.layerDrawStates.push(layerDrawState);
1219
+ const context = this.context;
1220
+ const currentTransform = context.getTransform().translate();
1221
+ if (!this._changed && this._previousTransform != null && isTransformsEqual(this._previousTransform, currentTransform) && this._paintedEpoch === layoutEpoch()) {
1222
+ layerDrawState.type = "skip";
1223
+ layerDrawState.time = layerDrawState.checkTime = performance.now() - startTime;
1224
+ return context.canvas;
1225
+ }
1226
+ this._changed = false;
1227
+ _chunkOCHCBJJEcjs.beginPaint.call(void 0, );
1228
+ try {
1229
+ return this._layoutAndPaint(layerDrawState, currentTransform, startTime);
1230
+ } finally {
1231
+ _chunkOCHCBJJEcjs.endPaint.call(void 0, );
1232
+ }
1233
+ }
1234
+ _layoutAndPaint(layerDrawState, currentTransform, startTime) {
1235
+ const context = this.context;
1236
+ const drawables = this._components;
1237
+ const layoutContext = LayoutContext.create(context);
1238
+ const shouldDrawContext = {
1239
+ context,
1240
+ visibleBounds: layoutContext.screenBounds
1241
+ };
1242
+ let layoutArea = null;
1243
+ let scale = 0;
1244
+ if (this._skipOffscreenLayout) {
1245
+ const screen = layoutContext.screenBounds;
1246
+ const margin = Math.max(screen.width, screen.height) * OFFSCREEN_MARGIN;
1247
+ layoutArea = screen.withPadding(margin);
1248
+ scale = screen.width > 0 ? context.canvas.width / screen.width : 0;
1249
+ }
1250
+ let shouldDraw = false;
1251
+ for (let i = 0; i < drawables.length; i++) {
1252
+ const component = drawables[i];
1253
+ if (component.isView) {
1254
+ if (layoutArea && canSkipLayout(component, layoutArea, scale)) {
1255
+ component.skipped = true;
1256
+ if (component.drewLastFrame) {
1257
+ shouldDraw = true;
1258
+ }
1259
+ continue;
1260
+ }
1261
+ const changesBeforeLayout = component.changes;
1262
+ let componentState;
1263
+ try {
1264
+ componentState = component.drawable.getDrawState(layoutContext);
1265
+ } catch (error) {
1266
+ componentState = null;
1267
+ this._reportError(error);
1268
+ }
1269
+ const shouldDrawComponent = _optionalChain([componentState, 'optionalAccess', _37 => _37.visibleInScreen]) === true;
1270
+ component.state = componentState;
1271
+ component.skipped = false;
1272
+ if (layoutArea) {
1273
+ const sameLayout = component.extent !== void 0 && changesBeforeLayout === component.laidOutChanges && scale === component.layoutScale && component.laidOutEpoch === layoutEpoch();
1274
+ if (!sameLayout) {
1275
+ component.extent = componentState ? stateExtent(componentState) : null;
1276
+ }
1277
+ component.layoutScale = scale;
1278
+ component.laidOutChanges = changesBeforeLayout;
1279
+ component.laidOutEpoch = layoutEpoch();
1280
+ }
1281
+ if (component.dirty || component.drewLastFrame !== shouldDrawComponent) {
1282
+ shouldDraw = true;
1283
+ }
1284
+ continue;
1285
+ }
1286
+ if (shouldDraw) {
1287
+ continue;
1288
+ }
1289
+ if (component.dirty) {
1290
+ shouldDraw = true;
1291
+ continue;
1292
+ }
1293
+ if (component.drewLastFrame !== this._canDraw(component.drawable, shouldDrawContext)) {
1294
+ shouldDraw = true;
1295
+ }
1296
+ }
1297
+ if (!shouldDraw) {
1298
+ shouldDraw = this._previousTransform == void 0 || !isTransformsEqual(this._previousTransform, currentTransform) || this._paintedEpoch !== layoutEpoch();
1299
+ }
1300
+ this._previousTransform = currentTransform;
1301
+ if (!shouldDraw) {
1302
+ layerDrawState.type = "skip";
1303
+ layerDrawState.time = layerDrawState.checkTime = performance.now() - startTime;
1304
+ return context.canvas;
1305
+ }
1306
+ this._paintedEpoch = layoutEpoch();
1307
+ let drewCount = 0;
1308
+ const frameTransform = context.getTransform();
1309
+ clearCanvas(context);
1310
+ for (let i = 0; i < drawables.length; i++) {
1311
+ const component = drawables[i];
1312
+ component.dirty = false;
1313
+ try {
1314
+ if (component.isView) {
1315
+ const state = component.state;
1316
+ if (component.skipped || state == null || !state.visibleInScreen) {
1317
+ component.drewLastFrame = false;
1318
+ continue;
1319
+ }
1320
+ component.drewLastFrame = true;
1321
+ component.drawable.draw(context, state);
1322
+ continue;
1323
+ }
1324
+ if (!this._canDraw(component.drawable, shouldDrawContext)) {
1325
+ component.drewLastFrame = false;
1326
+ continue;
1327
+ }
1328
+ component.drewLastFrame = true;
1329
+ component.drawable.draw(context);
1330
+ drewCount++;
1331
+ } catch (error) {
1332
+ context.setTransform(frameTransform);
1333
+ context.globalAlpha = 1;
1334
+ this._reportError(error);
1335
+ }
1336
+ }
1337
+ context.setTransform(frameTransform);
1338
+ layerDrawState.time = performance.now() - startTime;
1339
+ layerDrawState.drewComponents = drewCount;
1340
+ return context.canvas;
1341
+ }
1342
+ _canDraw(drawable, context) {
1343
+ try {
1344
+ return drawable.canDraw(context);
1345
+ } catch (error) {
1346
+ this._reportError(error);
1347
+ return false;
1348
+ }
1349
+ }
1350
+ _reportError(error) {
1351
+ this._canvas.scheduler.reportError(error);
1352
+ }
1353
+ /** @internal Called by the surface with pointer input. */
1354
+ handleMouseAction(action) {
1355
+ const components = this._components.slice();
1356
+ for (let i = components.length - 1; i >= 0; i--) {
1357
+ const component = components[i];
1358
+ if (component.subscriptions.disposed) {
1359
+ continue;
1360
+ }
1361
+ if (component.isView) {
1362
+ if (component.state) {
1363
+ if (component.drawable.handleMouseAction(action, component.state)) {
1364
+ return true;
1365
+ }
1366
+ }
1367
+ continue;
1368
+ }
1369
+ if (component.drawable.handleMouseAction(action)) {
1370
+ return true;
1371
+ }
1372
+ }
1373
+ return false;
1374
+ }
1375
+ _addComponent(component, order) {
1376
+ let paintComponent;
1377
+ if (component instanceof _chunkOCHCBJJEcjs.View) {
1378
+ paintComponent = {
1379
+ drawable: component,
1380
+ order: 0,
1381
+ dirty: true,
1382
+ drewLastFrame: false,
1383
+ changes: 0,
1384
+ subscriptions: new (0, _disposiq.DisposableStore)(),
1385
+ isView: true
1386
+ };
1387
+ } else {
1388
+ paintComponent = {
1389
+ drawable: component,
1390
+ order: 0,
1391
+ dirty: true,
1392
+ drewLastFrame: false,
1393
+ changes: 0,
1394
+ subscriptions: new (0, _disposiq.DisposableStore)(),
1395
+ isView: false
1396
+ };
1397
+ }
1398
+ if (_eventiq.isVariableOf.call(void 0, order)) {
1399
+ paintComponent.subscriptions.addOne(
1400
+ order.subscribeSilent((order2) => {
1401
+ paintComponent.order = order2;
1402
+ paintComponent.dirty = true;
1403
+ this._components.sort((a, b) => a.order - b.order);
1404
+ this._invalidate();
1405
+ })
1406
+ );
1407
+ paintComponent.order = order.value;
1408
+ } else if (typeof order === "number") {
1409
+ paintComponent.order = order;
1410
+ }
1411
+ const previous = this._byItem.get(component);
1412
+ if (previous !== void 0) {
1413
+ this.removeComponent(component);
1414
+ }
1415
+ this._byItem.set(component, paintComponent);
1416
+ insertByOrder(this._components, paintComponent);
1417
+ component.onChanged.subscribe(() => {
1418
+ paintComponent.changes++;
1419
+ this._changed = true;
1420
+ if (paintComponent.dirty) {
1421
+ return;
1422
+ }
1423
+ paintComponent.dirty = true;
1424
+ this._invalidate();
1425
+ }).disposeWith(paintComponent.subscriptions);
1426
+ return paintComponent;
1427
+ }
1428
+ }, _class5);
1429
+ function insertByOrder(components, component) {
1430
+ let low = 0;
1431
+ let high = components.length;
1432
+ while (low < high) {
1433
+ const mid = low + high >>> 1;
1434
+ if (components[mid].order <= component.order) {
1435
+ low = mid + 1;
1436
+ } else {
1437
+ high = mid;
1438
+ }
1439
+ }
1440
+ components.splice(low, 0, component);
1441
+ }
1442
+ function isTransformsEqual(a, b) {
1443
+ return a.a === b.a && a.b === b.b && a.c === b.c && a.d === b.d && a.e === b.e && a.f === b.f;
1444
+ }
1445
+ function canSkipLayout(component, layoutArea, scale) {
1446
+ const extent = component.extent;
1447
+ if (component.dirty || component.state == null || extent == null) {
1448
+ return false;
1449
+ }
1450
+ if (component.changes !== component.laidOutChanges || component.laidOutEpoch !== layoutEpoch()) {
1451
+ return false;
1452
+ }
1453
+ const lastScale = _nullishCoalesce(component.layoutScale, () => ( 0));
1454
+ if (!(lastScale > 0 && scale > 0)) {
1455
+ return false;
1456
+ }
1457
+ const ratio = lastScale > scale ? lastScale / scale : scale / lastScale;
1458
+ if (ratio >= LAYOUT_SCALE_TOLERANCE) {
1459
+ return false;
1460
+ }
1461
+ return !layoutArea.intersects(extent);
1462
+ }
1463
+ function stateExtent(state) {
1464
+ const children = state.children;
1465
+ let extent;
1466
+ if (!children || children.length === 0) {
1467
+ extent = state.localBounds.shift(state.globalOffset);
1468
+ } else {
1469
+ let union = stateExtent(children[0]);
1470
+ if (union == null) {
1471
+ return null;
1472
+ }
1473
+ for (let i = 1; i < children.length; i++) {
1474
+ const child = stateExtent(children[i]);
1475
+ if (child == null) {
1476
+ return null;
1477
+ }
1478
+ union = union.union(child);
1479
+ }
1480
+ extent = union;
1481
+ }
1482
+ return Number.isFinite(extent.x) && Number.isFinite(extent.y) && Number.isFinite(extent.width) && Number.isFinite(extent.height) ? extent : null;
1483
+ }
1484
+
1485
+ // src/zoom-level-view.ts
1486
+ var DETAILED_ABOVE_FACTOR = 1.25;
1487
+ var sharedLevels = /* @__PURE__ */ new WeakMap();
1488
+ function shareZoomLevels(target, levels) {
1489
+ sharedLevels.set(target, levels);
1490
+ }
1491
+ function levelsOf(target) {
1492
+ let levels = sharedLevels.get(target);
1493
+ if (!levels) {
1494
+ levels = /* @__PURE__ */ new Map();
1495
+ sharedLevels.set(target, levels);
1496
+ }
1497
+ return levels;
1498
+ }
1499
+ var ZoomLevelView = (_class6 = class extends _chunkOCHCBJJEcjs.View {
1500
+
1501
+
1502
+
1503
+
1504
+
1505
+ __init27() {this._isSimplified = false}
1506
+ constructor(options) {
1507
+ super(options);_class6.prototype.__init27.call(this);;
1508
+ this._detailed = options.detailed;
1509
+ this._simplified = options.simplified;
1510
+ this._referenceWidth = options.referenceWidth;
1511
+ this._simplifiedBelow = options.simplifiedBelow;
1512
+ this._levelKey = `${options.referenceWidth}|${options.simplifiedBelow}`;
1513
+ this.registerEvent(this._detailed.onChanged);
1514
+ this.registerEvent(this._simplified.onChanged);
1515
+ }
1516
+ get isSimplified() {
1517
+ return this._isSimplified;
1518
+ }
1519
+ getDrawState(context) {
1520
+ if (!this.visible.value) {
1521
+ return null;
1522
+ }
1523
+ const scale = context.context.canvas.width / context.screenBounds.width;
1524
+ const pixelWidth = this._referenceWidth * scale;
1525
+ const levels = levelsOf(context.context.canvas);
1526
+ let simplified = _nullishCoalesce(levels.get(this._levelKey), () => ( false));
1527
+ if (simplified) {
1528
+ if (pixelWidth > this._simplifiedBelow * DETAILED_ABOVE_FACTOR) {
1529
+ simplified = false;
1530
+ }
1531
+ } else if (pixelWidth < this._simplifiedBelow) {
1532
+ simplified = true;
1533
+ }
1534
+ levels.set(this._levelKey, simplified);
1535
+ this._isSimplified = simplified;
1536
+ return (simplified ? this._simplified : this._detailed).getDrawState(context);
1537
+ }
1538
+ // A Layer draws and hit-tests the component it holds rather than `state.view`, so both are forwarded.
1539
+ draw(context, state) {
1540
+ state.view.draw(context, state);
1541
+ }
1542
+ handleMouseAction(action, state) {
1543
+ return state.view.handleMouseAction(action, state);
1544
+ }
1545
+ }, _class6);
1546
+
1547
+ // src/surface.ts
1548
+
1549
+
1550
+
1551
+
1552
+
1553
+
1554
+
1555
+ var surfaceCounter = 0;
1556
+ var Surface = (_class7 = class {
1557
+ __init28() {this._disposables = new (0, _disposiq.DisposableStore)()}
1558
+ __init29() {this._layers = []}
1559
+ __init30() {this._parentScenes = []}
1560
+ __init31() {this._onInvalidate = new (0, _eventiq.EventDispatcher)()}
1561
+ __init32() {this._onDispose = new (0, _eventiq.EventDispatcher)()}
1562
+ __init33() {this._onDraw = new (0, _eventiq.EventDispatcher)()}
1563
+ __init34() {this._cursorPosition = new (0, _eventiq.Vary)(_chunkOCHCBJJEcjs.Point.zero, (p1, p2) => p1.equals(p2))}
1564
+
1565
+
1566
+
1567
+
1568
+
1569
+
1570
+ /** Zoom-level picks shared by all of this surface's layers. */
1571
+ __init35() {this._zoomLevels = /* @__PURE__ */ new Map()}
1572
+ __init36() {this._previousPointerTarget = null}
1573
+ __init37() {this._dirty = true}
1574
+ constructor(options) {;_class7.prototype.__init28.call(this);_class7.prototype.__init29.call(this);_class7.prototype.__init30.call(this);_class7.prototype.__init31.call(this);_class7.prototype.__init32.call(this);_class7.prototype.__init33.call(this);_class7.prototype.__init34.call(this);_class7.prototype.__init35.call(this);_class7.prototype.__init36.call(this);_class7.prototype.__init37.call(this);
1575
+ this._name = _optionalChain([options, 'optionalAccess', _38 => _38.name]) || `Surface${++surfaceCounter}`;
1576
+ this._scheduler = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _39 => _39.scheduler]), () => ( defaultScheduler));
1577
+ const canvas = _chunkOCHCBJJEcjs.createCanvasElement.call(void 0, );
1578
+ const context = canvas.getContext("2d");
1579
+ if (!context) {
1580
+ throw new Error("Canvas 2D context is not available");
1581
+ }
1582
+ this._context = context;
1583
+ const dpr = _optionalChain([options, 'optionalAccess', _40 => _40.dpr]);
1584
+ this._dpr = _eventiq.isVariableOf.call(void 0, dpr) ? dpr : _eventiq.createConstVar.call(void 0, dpr || 1);
1585
+ this._camera = new Camera(context, {
1586
+ dpr: this._dpr,
1587
+ scheduler: this._scheduler
1588
+ });
1589
+ this._disposables.add(this._camera);
1590
+ this._camera.onMatrixChanged.subscribe(() => this._redraw()).disposeWith(this._disposables);
1591
+ this._size = new (0, _eventiq.Vary)(new (0, _chunkOCHCBJJEcjs.Size)(canvas.width, canvas.height), (s1, s2) => s1.equals(s2));
1592
+ }
1593
+ get name() {
1594
+ return this._name;
1595
+ }
1596
+ get context() {
1597
+ return this._context;
1598
+ }
1599
+ get camera() {
1600
+ return this._camera;
1601
+ }
1602
+ get scheduler() {
1603
+ return this._scheduler;
1604
+ }
1605
+ get dpr() {
1606
+ return this._dpr;
1607
+ }
1608
+ get size() {
1609
+ return this._size;
1610
+ }
1611
+ /** Sets the size in device pixels, rounded down to whole pixels as a canvas is. */
1612
+ set size(value) {
1613
+ const width = Math.max(0, Math.floor(value.width));
1614
+ const height = Math.max(0, Math.floor(value.height));
1615
+ const size = new (0, _chunkOCHCBJJEcjs.Size)(width, height);
1616
+ if (this._size.value.equals(size)) {
1617
+ return;
1618
+ }
1619
+ const canvas = this._context.canvas;
1620
+ canvas.width = width;
1621
+ canvas.height = height;
1622
+ this._size.value = size;
1623
+ this._redraw();
1624
+ }
1625
+ get layers() {
1626
+ return this._layers.map((data) => data.layer);
1627
+ }
1628
+ /**
1629
+ * How far a point of the scene is from the middle of what this surface shows, in half-diagonals of
1630
+ * the surface: 0 at the middle, 1 at a corner, more off screen.
1631
+ */
1632
+ viewDistance(x, y) {
1633
+ const canvas = this._context.canvas;
1634
+ const halfWidth = canvas.width / 2;
1635
+ const halfHeight = canvas.height / 2;
1636
+ const halfDiagonal = Math.hypot(halfWidth, halfHeight);
1637
+ if (halfDiagonal === 0) {
1638
+ return Infinity;
1639
+ }
1640
+ const m = this._camera.matrix;
1641
+ const px = m.a * x + m.c * y + m.e;
1642
+ const py = m.b * x + m.d * y + m.f;
1643
+ return Math.hypot(px - halfWidth, py - halfHeight) / halfDiagonal;
1644
+ }
1645
+ get disposed() {
1646
+ return this._disposables.disposed;
1647
+ }
1648
+ get onInvalidate() {
1649
+ return this._onInvalidate;
1650
+ }
1651
+ /** Raised after every redraw of this surface. */
1652
+ get onDraw() {
1653
+ return this._onDraw;
1654
+ }
1655
+ get onDispose() {
1656
+ return this._onDispose;
1657
+ }
1658
+ /** The last pointer position over this surface, in world coordinates. */
1659
+ get cursorPosition() {
1660
+ return this._cursorPosition;
1661
+ }
1662
+ get keyboardObserver() {
1663
+ if (this._parentScenes.length === 0) {
1664
+ throw new Error("Surface has no parent scene");
1665
+ }
1666
+ return this._parentScenes[0].keyboardObserver;
1667
+ }
1668
+ createLayer(order, options) {
1669
+ this._disposables.throwIfDisposed();
1670
+ const canvas = _chunkOCHCBJJEcjs.createCanvasElement.call(void 0, );
1671
+ const context = canvas.getContext("2d");
1672
+ if (!context) {
1673
+ throw new Error("Canvas 2D context is not available");
1674
+ }
1675
+ const layerName = _optionalChain([options, 'optionalAccess', _41 => _41.name]) || `Layer${this._layers.length}`;
1676
+ const layer = new Layer(this, context, layerName, { skipOffscreenLayout: _optionalChain([options, 'optionalAccess', _42 => _42.skipOffscreenLayout]) });
1677
+ shareZoomLevels(canvas, this._zoomLevels);
1678
+ const layerData = {
1679
+ layer,
1680
+ canvas,
1681
+ context,
1682
+ order: order || 0,
1683
+ subscriptions: new (0, _disposiq.DisposableStore)()
1684
+ };
1685
+ layer.onInvalidate.subscribe(() => this._redraw()).disposeWith(layerData.subscriptions);
1686
+ this._size.subscribe((size) => {
1687
+ canvas.width = size.width;
1688
+ canvas.height = size.height;
1689
+ layer.invalidateForce();
1690
+ }).disposeWith(layerData.subscriptions);
1691
+ if (_nullishCoalesce(_optionalChain([options, 'optionalAccess', _43 => _43.attachCamera]), () => ( true))) {
1692
+ this._camera.onMatrixChanged.subscribe((matrix) => {
1693
+ context.setTransform(matrix);
1694
+ }).disposeWith(layerData.subscriptions);
1695
+ context.setTransform(this._camera.matrix);
1696
+ this._size.subscribeSilent(() => {
1697
+ context.setTransform(this._camera.matrix);
1698
+ }).disposeWith(layerData.subscriptions);
1699
+ } else {
1700
+ const applyDpr = () => {
1701
+ const dpr = this._dpr.value;
1702
+ context.setTransform(dpr, 0, 0, dpr, 0, 0);
1703
+ };
1704
+ this._dpr.subscribe(applyDpr).disposeWith(layerData.subscriptions);
1705
+ this._size.subscribeSilent(applyDpr).disposeWith(layerData.subscriptions);
1706
+ }
1707
+ this._layers.push(layerData);
1708
+ this._layers.sort((a, b) => a.order - b.order);
1709
+ this._redraw();
1710
+ return layer;
1711
+ }
1712
+ /** Removes a layer created by {@link createLayer} and disposes it (see {@link Layer.dispose}). */
1713
+ removeLayer(layer) {
1714
+ const index = this._layers.findIndex((data2) => data2.layer === layer);
1715
+ if (index < 0) {
1716
+ return;
1717
+ }
1718
+ const [data] = this._layers.splice(index, 1);
1719
+ data.subscriptions.dispose();
1720
+ layer.dispose();
1721
+ this._redraw();
1722
+ }
1723
+ /** Makes every layer lay out and paint again on the next frame, as after a font finished loading. */
1724
+ invalidateLayers() {
1725
+ for (const data of this._layers) {
1726
+ data.layer.invalidateForce();
1727
+ }
1728
+ }
1729
+ /** @internal Called by the scene each frame. */
1730
+ draw(sceneDrawContext) {
1731
+ const context = this._context;
1732
+ const canvas = context.canvas;
1733
+ if (canvas.width === 0 || canvas.height === 0) {
1734
+ return canvas;
1735
+ }
1736
+ const drawState = {
1737
+ surface: this,
1738
+ scene: sceneDrawContext.scene,
1739
+ time: 0,
1740
+ type: "draw",
1741
+ layerDrawStates: []
1742
+ };
1743
+ sceneDrawContext.surfaceDrawStates.push(drawState);
1744
+ if (!this._dirty) {
1745
+ drawState.type = "skip";
1746
+ return canvas;
1747
+ }
1748
+ const startTime = performance.now();
1749
+ this._dirty = false;
1750
+ clearCanvas(context);
1751
+ const layers = this._layers;
1752
+ for (let i = 0; i < layers.length; i++) {
1753
+ const layer = layers[i];
1754
+ context.drawImage(layer.layer.draw(drawState), 0, 0);
1755
+ }
1756
+ this._onDraw.dispatch();
1757
+ drawState.time = performance.now() - startTime;
1758
+ return canvas;
1759
+ }
1760
+ /** @internal Called by the scene with pointer input over this surface. */
1761
+ handlePointerAction(action) {
1762
+ if (action.type === "leave") {
1763
+ if (this._previousPointerTarget !== null) {
1764
+ this._previousPointerTarget.handleMouseLeave();
1765
+ this._previousPointerTarget = null;
1766
+ }
1767
+ return false;
1768
+ }
1769
+ const originalPoint = new DOMPoint(action.viewportPosition.x, action.viewportPosition.y);
1770
+ const point = this._camera.inverseMatrix.transformPoint(originalPoint);
1771
+ this._cursorPosition.value = new (0, _chunkOCHCBJJEcjs.Point)(point.x, point.y);
1772
+ const layers = this._layers;
1773
+ let handled = false;
1774
+ for (let i = layers.length - 1; i >= 0; i--) {
1775
+ const layer = layers[i];
1776
+ const transformedAction = action.with({
1777
+ context: layer.context
1778
+ });
1779
+ if (layer.layer.handleMouseAction(transformedAction)) {
1780
+ handled = true;
1781
+ break;
1782
+ }
1783
+ }
1784
+ const newTarget = action.target;
1785
+ if (this._previousPointerTarget !== null && newTarget !== this._previousPointerTarget) {
1786
+ this._previousPointerTarget.handleMouseLeave();
1787
+ }
1788
+ if (newTarget instanceof _chunkOCHCBJJEcjs.View) {
1789
+ this._previousPointerTarget = newTarget;
1790
+ } else {
1791
+ this._previousPointerTarget = null;
1792
+ }
1793
+ return handled;
1794
+ }
1795
+ /**
1796
+ * Calls `callback` every frame with the eased progress from 0 to 1, for `time` milliseconds
1797
+ * (default 1000). Disposing the result stops it early.
1798
+ */
1799
+ animate(callback, optionsOrTime) {
1800
+ const options = typeof optionsOrTime === "number" ? { time: optionsOrTime } : optionsOrTime || {};
1801
+ const interpolator = _nullishCoalesce(options.interpolator, () => ( animationInterpolators.linear));
1802
+ const animation = this._scheduler.animate(callback, {
1803
+ duration: options.time || 1e3,
1804
+ interpolate: (progress) => interpolator.interpolate(progress),
1805
+ onFinished: options.onFinished
1806
+ });
1807
+ const disposables = new (0, _disposiq.DisposableStore)();
1808
+ disposables.add(animation);
1809
+ return disposables;
1810
+ }
1811
+ dispose() {
1812
+ if (this._disposables.disposed) {
1813
+ return;
1814
+ }
1815
+ const layers = this._layers.splice(0);
1816
+ for (const data of layers) {
1817
+ data.subscriptions.dispose();
1818
+ data.layer.dispose();
1819
+ }
1820
+ this._previousPointerTarget = null;
1821
+ this._disposables.dispose();
1822
+ const canvas = this._context.canvas;
1823
+ canvas.width = 0;
1824
+ canvas.height = 0;
1825
+ this._onDispose.dispatch();
1826
+ }
1827
+ /** @internal */
1828
+ attachToScene(scene) {
1829
+ this._parentScenes.push(scene);
1830
+ }
1831
+ /** @internal */
1832
+ detachFromScene(scene) {
1833
+ const index = this._parentScenes.indexOf(scene);
1834
+ if (index >= 0) {
1835
+ this._parentScenes.splice(index, 1);
1836
+ }
1837
+ }
1838
+ _redraw() {
1839
+ if (this._disposables.disposed) {
1840
+ return;
1841
+ }
1842
+ if (this._dirty) {
1843
+ return;
1844
+ }
1845
+ this._dirty = true;
1846
+ this._onInvalidate.dispatch();
1847
+ }
1848
+ }, _class7);
1849
+
1850
+ // src/scene.ts
1851
+
1852
+
1853
+
1854
+ // src/device/dpr.ts
1855
+
1856
+
1857
+ function createDprVar() {
1858
+ const subscription = new (0, _disposiq.DisposableContainer)();
1859
+ const variable = _eventiq.createVar.call(void 0, globalThis.devicePixelRatio || 1);
1860
+ const updatePixelRatio = () => {
1861
+ const ratio = globalThis.devicePixelRatio || 1;
1862
+ if (typeof globalThis.matchMedia === "function") {
1863
+ const media = globalThis.matchMedia(`(resolution: ${ratio}dppx)`);
1864
+ subscription.set(_disposiq.addEventListener.call(void 0, media, "change", updatePixelRatio));
1865
+ }
1866
+ variable.value = ratio;
1867
+ };
1868
+ updatePixelRatio();
1869
+ return {
1870
+ variable,
1871
+ changeSubscription: subscription
1872
+ };
1873
+ }
1874
+
1875
+ // src/measurer.ts
1876
+
1877
+
1878
+ var Measurer = (_class8 = class extends _disposiq.Disposable {
1879
+ constructor(_canvas, options) {
1880
+ super();_class8.prototype.__init38.call(this);;
1881
+ this._canvas = _canvas;
1882
+ this._size = new (0, _eventiq.Vary)(contentBoxSize(_canvas), (s1, s2) => s1.equals(s2));
1883
+ if (_optionalChain([options, 'optionalAccess', _44 => _44.enableResizeObserver]) && typeof globalThis.ResizeObserver === "function") {
1884
+ const resizeObserver = new ResizeObserver((entries) => {
1885
+ const entry = entries[entries.length - 1];
1886
+ const box = _optionalChain([entry, 'optionalAccess', _45 => _45.contentBoxSize, 'optionalAccess', _46 => _46[0]]);
1887
+ this._size.value = box ? new (0, _chunkOCHCBJJEcjs.Size)(box.inlineSize, box.blockSize) : contentBoxSize(this._canvas);
1888
+ const device = _optionalChain([entry, 'optionalAccess', _47 => _47.devicePixelContentBoxSize, 'optionalAccess', _48 => _48[0]]);
1889
+ this._deviceSize.value = device ? new (0, _chunkOCHCBJJEcjs.Size)(device.inlineSize, device.blockSize) : null;
1890
+ });
1891
+ try {
1892
+ resizeObserver.observe(_canvas, { box: "device-pixel-content-box" });
1893
+ } catch (e4) {
1894
+ resizeObserver.observe(_canvas);
1895
+ }
1896
+ this.addDisposable(() => resizeObserver.disconnect());
1897
+ } else {
1898
+ const resizeCanvas = () => {
1899
+ this._size.value = contentBoxSize(this._canvas);
1900
+ };
1901
+ this.addDisposable(_disposiq.addEventListener.call(void 0, globalThis, "resize", resizeCanvas));
1902
+ }
1903
+ }
1904
+
1905
+
1906
+ __init38() {this._deviceSize = new (0, _eventiq.Vary)(null, (a, b) => a && b ? a.equals(b) : a === b)}
1907
+ /** The content box in CSS pixels, possibly fractional. */
1908
+ get size() {
1909
+ return this._size;
1910
+ }
1911
+ /** The content box in device pixels as the browser lays it out; null where it does not say. */
1912
+ get deviceSize() {
1913
+ return this._deviceSize;
1914
+ }
1915
+ }, _class8);
1916
+ function contentBoxSize(element) {
1917
+ const style = typeof globalThis.getComputedStyle === "function" ? globalThis.getComputedStyle(element) : null;
1918
+ const px = (value) => {
1919
+ const number = value ? Number.parseFloat(value) : 0;
1920
+ return Number.isFinite(number) ? number : 0;
1921
+ };
1922
+ const horizontal = style ? px(style.borderLeftWidth) + px(style.borderRightWidth) + px(style.paddingLeft) + px(style.paddingRight) : 0;
1923
+ const vertical = style ? px(style.borderTopWidth) + px(style.borderBottomWidth) + px(style.paddingTop) + px(style.paddingBottom) : 0;
1924
+ return new (0, _chunkOCHCBJJEcjs.Size)(Math.max(0, element.offsetWidth - horizontal), Math.max(0, element.offsetHeight - vertical));
1925
+ }
1926
+
1927
+ // src/scene.ts
1928
+ var DOUBLE_CLICK_DISTANCE = 24;
1929
+ var Scene = (_class9 = class {
1930
+ constructor(_context, options) {;_class9.prototype.__init39.call(this);_class9.prototype.__init40.call(this);_class9.prototype.__init41.call(this);_class9.prototype.__init42.call(this);_class9.prototype.__init43.call(this);_class9.prototype.__init44.call(this);_class9.prototype.__init45.call(this);_class9.prototype.__init46.call(this);_class9.prototype.__init47.call(this);_class9.prototype.__init48.call(this);_class9.prototype.__init49.call(this);_class9.prototype.__init50.call(this);
1931
+ this._context = _context;
1932
+ const canvas = _context.canvas;
1933
+ this._scheduler = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _49 => _49.scheduler]), () => ( defaultScheduler));
1934
+ this._focusOnPointerDown = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _50 => _50.focusOnPointerDown]), () => ( true));
1935
+ this._clickSlop = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _51 => _51.clickSlop]), () => ( 5));
1936
+ this._clickDelay = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _52 => _52.clickDelay]), () => ( 0));
1937
+ this._defaultCursor = canvas.style.cursor;
1938
+ const touchAction = _optionalChain([options, 'optionalAccess', _53 => _53.touchAction]) === void 0 ? "none" : options.touchAction;
1939
+ if (touchAction !== null) {
1940
+ canvas.style.touchAction = touchAction;
1941
+ }
1942
+ this._keyboardObserver = new KeyboardObserver(canvas);
1943
+ this._disposables.add(this._keyboardObserver);
1944
+ this._measurer = new Measurer(canvas, {
1945
+ enableResizeObserver: true
1946
+ });
1947
+ this._disposables.add(this._measurer);
1948
+ const dprVar = createDprVar();
1949
+ this._disposables.add(dprVar.changeSubscription);
1950
+ this._dpr = dprVar.variable.with(this._exportScale).map(([dpr, scale]) => dpr * scale);
1951
+ this._size = this._measurer.size.with(this._measurer.deviceSize, dprVar.variable, this._exportScale).map(([css, device, dpr, exportScale]) => bitmapSize(css, device, dpr, exportScale));
1952
+ this._size.subscribe((size) => {
1953
+ canvas.width = size.width;
1954
+ canvas.height = size.height;
1955
+ const bounds = new (0, _chunkOCHCBJJEcjs.RectBounds)(0, 0, size.width, size.height);
1956
+ this._dirty = true;
1957
+ for (const data of this._surfaces) {
1958
+ if (data.fillsScene) {
1959
+ data.bounds = bounds;
1960
+ data.surface.size = size;
1961
+ }
1962
+ }
1963
+ this._draw();
1964
+ }).disposeWith(this._disposables);
1965
+ this._measurer.size.subscribeSilent(() => this.redraw()).disposeWith(this._disposables);
1966
+ this._pointerObserver = new PointerObserver(canvas, { capture: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _54 => _54.pointerCapture]), () => ( true)) });
1967
+ this._disposables.add(this._pointerObserver);
1968
+ this._initPointerEvents();
1969
+ this._disposables.add(watchFontLoading());
1970
+ onRelayout.subscribe(() => {
1971
+ for (const data of this._surfaces) {
1972
+ data.surface.invalidateLayers();
1973
+ }
1974
+ this.redraw();
1975
+ }).disposeWith(this._disposables);
1976
+ this._scheduler.onUpdate.subscribe(() => this._draw()).disposeWith(this._disposables);
1977
+ }
1978
+
1979
+ __init39() {this._disposables = new (0, _disposiq.DisposableStore)()}
1980
+ __init40() {this._surfaces = []}
1981
+
1982
+
1983
+
1984
+
1985
+
1986
+ /** Multiplies the device pixel ratio while an export draws the scene larger. */
1987
+ __init41() {this._exportScale = _eventiq.createVar.call(void 0, 1)}
1988
+ __init42() {this._onFrame = new (0, _eventiq.EventDispatcher)()}
1989
+ __init43() {this._frame = 0}
1990
+ /** Something changed since the last composite; a clean scene draws nothing in a frame. */
1991
+ __init44() {this._dirty = true}
1992
+
1993
+
1994
+ __init45() {this._activeEventCursor = null}
1995
+
1996
+ /** Set while more than one pointer is down: a gesture, not a press, so views get no input. */
1997
+ __init46() {this._gesture = false}
1998
+
1999
+
2000
+ /** A click held back by clickDelay, waiting to see whether a second press makes a double-click. */
2001
+ __init47() {this._pendingClick = null}
2002
+ /** Where the current press went down (CSS pixels), for the click it may make. */
2003
+ __init48() {this._pressPosition = _chunkOCHCBJJEcjs.Point.zero}
2004
+ /** The current press is the second of a double-click: its click is dropped. */
2005
+ __init49() {this._swallowClick = false}
2006
+ /** Logs what every frame drew to the console. */
2007
+ __init50() {this.debug = false}
2008
+ /** The canvas's size in device pixels. */
2009
+ get size() {
2010
+ return this._size;
2011
+ }
2012
+ get dpr() {
2013
+ return this._dpr;
2014
+ }
2015
+ get scheduler() {
2016
+ return this._scheduler;
2017
+ }
2018
+ /**
2019
+ * Raised after every frame the scene draws, with what it drew and how long it took: for a frame
2020
+ * counter, a stats overlay (see {@link FrameStatsMonitor}) or a performance test. Not raised for frames
2021
+ * in which nothing changed, because none are drawn.
2022
+ */
2023
+ get onFrame() {
2024
+ return this._onFrame;
2025
+ }
2026
+ /**
2027
+ * The scene as a picture: drawn again at `scale` times its pixels (default 1: as on screen, device
2028
+ * pixel ratio included), then encoded. Views see a larger device pixel ratio while it draws, so text,
2029
+ * strokes and cached bitmaps are sharp at the larger size. The canvas on the page is put back before
2030
+ * this returns, so nothing flickers. Images still loading are drawn as they are at that moment.
2031
+ */
2032
+ toBlob(options) {
2033
+ const copy = this._renderCopy(options);
2034
+ return new Promise((resolve, reject) => {
2035
+ copy.toBlob(
2036
+ (blob) => blob ? resolve(blob) : reject(new Error("The canvas could not be encoded")),
2037
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _55 => _55.type]), () => ( "image/png")),
2038
+ _optionalChain([options, 'optionalAccess', _56 => _56.quality])
2039
+ );
2040
+ });
2041
+ }
2042
+ /** The scene as a data URL; see {@link toBlob}. */
2043
+ toDataURL(options) {
2044
+ return this._renderCopy(options).toDataURL(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _57 => _57.type]), () => ( "image/png")), _optionalChain([options, 'optionalAccess', _58 => _58.quality]));
2045
+ }
2046
+ /** Draws the scene at an export scale into a new canvas and puts the page's canvas back. */
2047
+ _renderCopy(options) {
2048
+ this._disposables.throwIfDisposed();
2049
+ const canvas = this._context.canvas;
2050
+ const requested = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _59 => _59.scale]), () => ( 1));
2051
+ if (!(requested > 0) || !Number.isFinite(requested)) {
2052
+ throw new RangeError(`Export scale must be a positive number, not ${requested}`);
2053
+ }
2054
+ const width = Math.max(1, canvas.width);
2055
+ const height = Math.max(1, canvas.height);
2056
+ const scale = Math.min(requested, MAX_EXPORT_SIDE / width, MAX_EXPORT_SIDE / height, Math.sqrt(MAX_EXPORT_PIXELS / (width * height)));
2057
+ const copy = _chunkOCHCBJJEcjs.createCanvasElement.call(void 0, );
2058
+ try {
2059
+ this._exportScale.value = scale;
2060
+ this._dirty = true;
2061
+ this._draw();
2062
+ copy.width = canvas.width;
2063
+ copy.height = canvas.height;
2064
+ const context = copy.getContext("2d");
2065
+ if (!context) {
2066
+ throw new Error("No 2D context for the export canvas");
2067
+ }
2068
+ if (_optionalChain([options, 'optionalAccess', _60 => _60.background])) {
2069
+ context.fillStyle = options.background;
2070
+ context.fillRect(0, 0, copy.width, copy.height);
2071
+ }
2072
+ context.drawImage(canvas, 0, 0);
2073
+ } finally {
2074
+ this._exportScale.value = 1;
2075
+ }
2076
+ return copy;
2077
+ }
2078
+ get container() {
2079
+ return this._context.canvas;
2080
+ }
2081
+ get surfaces() {
2082
+ return this._surfaces.map((data) => data.surface);
2083
+ }
2084
+ get keyboardObserver() {
2085
+ return this._keyboardObserver;
2086
+ }
2087
+ get pointerObserver() {
2088
+ return this._pointerObserver;
2089
+ }
2090
+ /** The cursor shown when no view under the pointer asks for one. */
2091
+ get cursor() {
2092
+ return this._defaultCursor;
2093
+ }
2094
+ set cursor(value) {
2095
+ if (this._defaultCursor === value) {
2096
+ return;
2097
+ }
2098
+ this._defaultCursor = value;
2099
+ if (this._activeEventCursor !== null) {
2100
+ return;
2101
+ }
2102
+ this._context.canvas.style.cursor = value;
2103
+ }
2104
+ /** Creates a surface that follows this scene's DPR and scheduler, and adds it. */
2105
+ createSurface(options) {
2106
+ this._disposables.throwIfDisposed();
2107
+ const surface = new Surface({
2108
+ name: _optionalChain([options, 'optionalAccess', _61 => _61.name]),
2109
+ dpr: this._dpr,
2110
+ scheduler: this._scheduler
2111
+ });
2112
+ this._disposables.add(surface);
2113
+ this.addSurface(surface, _optionalChain([options, 'optionalAccess', _62 => _62.order]), _optionalChain([options, 'optionalAccess', _63 => _63.rect]));
2114
+ return surface;
2115
+ }
2116
+ removeSurface(surface) {
2117
+ if (this._disposables.disposed) {
2118
+ return;
2119
+ }
2120
+ const index = this._surfaces.findIndex((data) => data.surface === surface);
2121
+ if (index >= 0) {
2122
+ const data = this._surfaces[index];
2123
+ data.subscriptions.dispose();
2124
+ this._surfaces.splice(index, 1);
2125
+ }
2126
+ this._disposables.remove(surface);
2127
+ surface.detachFromScene(this);
2128
+ this.redraw();
2129
+ }
2130
+ /**
2131
+ * Where a surface lies in the scene, in device pixels; null when it is not in this scene. Input
2132
+ * controllers use it to map pointer positions into the surface.
2133
+ */
2134
+ surfaceBounds(surface) {
2135
+ const data = this._surfaces.find((data2) => data2.surface === surface);
2136
+ return data ? data.bounds : null;
2137
+ }
2138
+ /**
2139
+ * Adds a surface, placed at `rect` in device pixels (following it when it is a variable), or over
2140
+ * the whole scene when `rect` is not given.
2141
+ */
2142
+ addSurface(surface, order, rect) {
2143
+ if (surface.disposed) {
2144
+ throw new Error("Surface is disposed");
2145
+ }
2146
+ const data = {
2147
+ surface,
2148
+ order: order || 0,
2149
+ subscriptions: new (0, _disposiq.DisposableStore)(),
2150
+ bounds: _chunkOCHCBJJEcjs.RectBounds.zero,
2151
+ fillsScene: !rect
2152
+ };
2153
+ this._surfaces.push(data);
2154
+ if (rect) {
2155
+ if (_eventiq.isVariableOf.call(void 0, rect)) {
2156
+ rect.subscribe((bounds) => {
2157
+ data.bounds = bounds;
2158
+ surface.size = bounds.size;
2159
+ this.redraw();
2160
+ }).disposeWith(data.subscriptions);
2161
+ } else {
2162
+ data.bounds = rect;
2163
+ surface.size = rect.size;
2164
+ }
2165
+ } else {
2166
+ const size = this._size.value;
2167
+ data.bounds = new (0, _chunkOCHCBJJEcjs.RectBounds)(0, 0, size.width, size.height);
2168
+ surface.size = size;
2169
+ }
2170
+ surface.onInvalidate.subscribe(() => this.redraw()).disposeWith(data.subscriptions);
2171
+ surface.onDispose.subscribe(() => {
2172
+ const index = this._surfaces.indexOf(data);
2173
+ if (index >= 0) {
2174
+ this._surfaces.splice(index, 1);
2175
+ data.subscriptions.dispose();
2176
+ }
2177
+ }).disposeWith(data.subscriptions);
2178
+ this._surfaces.sort((a, b) => a.order - b.order);
2179
+ this.redraw();
2180
+ surface.attachToScene(this);
2181
+ }
2182
+ /**
2183
+ * Milliseconds a view's click is held back to tell it from a double-click: a second press near it
2184
+ * within that time makes a double-click, and neither click reaches the views. 0 (the default)
2185
+ * delivers clicks at once. `attachZoomPan` with `doubleClickZoom` sets it, so a double-click zooms
2186
+ * without also clicking what is under the pointer twice.
2187
+ */
2188
+ get clickDelay() {
2189
+ return this._clickDelay;
2190
+ }
2191
+ set clickDelay(value) {
2192
+ this._clickDelay = Math.max(0, value);
2193
+ if (this._clickDelay === 0) {
2194
+ this._flushPendingClick();
2195
+ }
2196
+ }
2197
+ /** Delivers a click at once, or holds it back for clickDelay. */
2198
+ _deliverClick(dispatch) {
2199
+ if (this._swallowClick) {
2200
+ this._swallowClick = false;
2201
+ return;
2202
+ }
2203
+ if (this._clickDelay <= 0) {
2204
+ dispatch();
2205
+ return;
2206
+ }
2207
+ this._flushPendingClick();
2208
+ const timer = setTimeout(() => {
2209
+ if (_optionalChain([this, 'access', _64 => _64._pendingClick, 'optionalAccess', _65 => _65.timer]) === timer) {
2210
+ this._pendingClick = null;
2211
+ dispatch();
2212
+ }
2213
+ }, this._clickDelay);
2214
+ this._pendingClick = { dispatch, position: this._pressPosition, timer };
2215
+ }
2216
+ /** Delivers a held click now (a press elsewhere means it was a single click). */
2217
+ _flushPendingClick() {
2218
+ const pending = this._pendingClick;
2219
+ if (!pending) {
2220
+ return;
2221
+ }
2222
+ this._pendingClick = null;
2223
+ clearTimeout(pending.timer);
2224
+ pending.dispatch();
2225
+ }
2226
+ /** A press begins: if it is the second of a double-click, the held click and its own are dropped. */
2227
+ _onPress(position) {
2228
+ this._pressPosition = position;
2229
+ this._swallowClick = false;
2230
+ const pending = this._pendingClick;
2231
+ if (!pending) {
2232
+ return;
2233
+ }
2234
+ if (pending.position.distance(position) <= DOUBLE_CLICK_DISTANCE) {
2235
+ this._pendingClick = null;
2236
+ clearTimeout(pending.timer);
2237
+ this._swallowClick = true;
2238
+ return;
2239
+ }
2240
+ this._flushPendingClick();
2241
+ }
2242
+ /**
2243
+ * Requests a frame in which the scene composites its surfaces again; surfaces that did not change
2244
+ * are composited from their last bitmap. A scene nothing changed in draws nothing in a frame, even
2245
+ * when other scenes on the same scheduler do.
2246
+ */
2247
+ redraw() {
2248
+ this._dirty = true;
2249
+ this._scheduler.scheduleUpdate();
2250
+ }
2251
+ addExternalPointerElement(element, options) {
2252
+ return this._pointerObserver.addExternalElement(element, options);
2253
+ }
2254
+ simulateMouseLeave() {
2255
+ this._pointerObserver.simulateMouseLeave();
2256
+ }
2257
+ dispose() {
2258
+ if (this._disposables.disposed) {
2259
+ return;
2260
+ }
2261
+ for (const data of this._surfaces) {
2262
+ data.subscriptions.dispose();
2263
+ }
2264
+ this._surfaces.length = 0;
2265
+ if (this._pendingClick) {
2266
+ clearTimeout(this._pendingClick.timer);
2267
+ this._pendingClick = null;
2268
+ }
2269
+ this._disposables.dispose();
2270
+ }
2271
+ _draw() {
2272
+ if (this._disposables.disposed) {
2273
+ return;
2274
+ }
2275
+ if (!this._dirty) {
2276
+ return;
2277
+ }
2278
+ const context = this._context;
2279
+ const canvas = context.canvas;
2280
+ if (canvas.width === 0 || canvas.height === 0) {
2281
+ return;
2282
+ }
2283
+ this._dirty = false;
2284
+ const drawContext = {
2285
+ scene: this,
2286
+ debug: this.debug,
2287
+ startTime: performance.now(),
2288
+ endTime: 0,
2289
+ surfaceDrawStates: []
2290
+ };
2291
+ clearCanvas(context);
2292
+ for (const data of this._surfaces) {
2293
+ const image = data.surface.draw(drawContext);
2294
+ const bounds = data.bounds;
2295
+ if (bounds.size.isZero) {
2296
+ continue;
2297
+ }
2298
+ context.drawImage(image, bounds.x, bounds.y, bounds.width, bounds.height);
2299
+ }
2300
+ drawContext.endTime = performance.now();
2301
+ this._frame++;
2302
+ if (drawContext.debug) {
2303
+ console.debug(describeDrawState(drawContext));
2304
+ }
2305
+ if (this._onFrame.hasSubscriptions) {
2306
+ this._onFrame.dispatch(toFrameInfo(drawContext, this._frame));
2307
+ }
2308
+ }
2309
+ _initPointerEvents() {
2310
+ const deliverClick = (dispatch) => this._deliverClick(dispatch);
2311
+ const emit = (type, e) => {
2312
+ const dpr = this._dpr.value;
2313
+ const viewportPosition = e.viewportPosition.multiply(dpr);
2314
+ const event = createPointerActionEvent({
2315
+ context: this._context,
2316
+ type,
2317
+ observeEvent: e,
2318
+ viewportPosition,
2319
+ clickSlop: this._clickSlop * dpr,
2320
+ deliverClick
2321
+ });
2322
+ let handled = false;
2323
+ for (let i = this._surfaces.length - 1; i >= 0; i--) {
2324
+ const data = this._surfaces[i];
2325
+ if (handled || event.type !== "leave" && !data.bounds.contains(viewportPosition)) {
2326
+ data.surface.handlePointerAction(event.with({ type: "leave" }));
2327
+ continue;
2328
+ }
2329
+ const surfaceEvent = event.with({
2330
+ viewportPosition: viewportPosition.subtract(data.bounds.topLeft)
2331
+ });
2332
+ if (data.surface.handlePointerAction(surfaceEvent)) {
2333
+ handled = true;
2334
+ }
2335
+ }
2336
+ if (event.cursor != null) {
2337
+ if (this._activeEventCursor === event.cursor) {
2338
+ return;
2339
+ }
2340
+ this._activeEventCursor = event.cursor;
2341
+ this._context.canvas.style.cursor = event.cursor;
2342
+ return;
2343
+ }
2344
+ if (this._activeEventCursor === null) {
2345
+ return;
2346
+ }
2347
+ this._activeEventCursor = null;
2348
+ this._context.canvas.style.cursor = this._defaultCursor;
2349
+ };
2350
+ const observer = this._pointerObserver;
2351
+ const forViews = (e) => e.isPrimary && !this._gesture;
2352
+ const endGesture = () => {
2353
+ if (observer.activePointers.size === 0) {
2354
+ this._gesture = false;
2355
+ }
2356
+ };
2357
+ this._disposables.add(
2358
+ observer.onPointerEnter.subscribe((e) => {
2359
+ if (forViews(e)) {
2360
+ emit("enter", e);
2361
+ }
2362
+ }),
2363
+ observer.onPointerMove.subscribe((e) => {
2364
+ if (forViews(e)) {
2365
+ emit("move", e);
2366
+ }
2367
+ }),
2368
+ observer.onPointerDown.subscribe((e) => {
2369
+ if (this._focusOnPointerDown) {
2370
+ this.container.focus({ preventScroll: true });
2371
+ }
2372
+ if (observer.activePointers.size > 1) {
2373
+ if (!this._gesture) {
2374
+ this._gesture = true;
2375
+ emit("leave", e);
2376
+ }
2377
+ return;
2378
+ }
2379
+ if (forViews(e)) {
2380
+ this._onPress(e.viewportPosition);
2381
+ emit("down", e);
2382
+ }
2383
+ }),
2384
+ observer.onPointerUp.subscribe((e) => {
2385
+ if (forViews(e)) {
2386
+ emit("up", e);
2387
+ }
2388
+ endGesture();
2389
+ }),
2390
+ observer.onPointerCancel.subscribe((e) => {
2391
+ if (!this._gesture) {
2392
+ emit("leave", e);
2393
+ }
2394
+ endGesture();
2395
+ }),
2396
+ observer.onPointerLeave.subscribe((e) => {
2397
+ if (e.isPrimary) {
2398
+ emit("leave", e);
2399
+ }
2400
+ })
2401
+ );
2402
+ }
2403
+ }, _class9);
2404
+ function bitmapSize(css, device, dpr, exportScale) {
2405
+ if (device && Math.abs(device.width - css.width * dpr) < 2 && Math.abs(device.height - css.height * dpr) < 2) {
2406
+ return new (0, _chunkOCHCBJJEcjs.Size)(Math.floor(device.width * exportScale), Math.floor(device.height * exportScale));
2407
+ }
2408
+ const scale = dpr * exportScale;
2409
+ return new (0, _chunkOCHCBJJEcjs.Size)(Math.floor(css.width * scale), Math.floor(css.height * scale));
2410
+ }
2411
+ var MAX_EXPORT_SIDE = 16384;
2412
+ var MAX_EXPORT_PIXELS = 268e6;
2413
+ function toFrameInfo(drawContext, frame) {
2414
+ const redrawnLayers = [];
2415
+ const surfaces = drawContext.surfaceDrawStates.map((surface) => ({
2416
+ name: surface.surface.name,
2417
+ drawn: surface.type === "draw",
2418
+ time: surface.time,
2419
+ layers: surface.layerDrawStates.map((layer) => {
2420
+ const drawn = layer.type === "draw";
2421
+ if (drawn) redrawnLayers.push(layer.layer.name);
2422
+ return { name: layer.layer.name, drawn, time: layer.time, components: layer.totalComponents };
2423
+ })
2424
+ }));
2425
+ return { frame, startTime: drawContext.startTime, time: drawContext.endTime - drawContext.startTime, surfaces, redrawnLayers };
2426
+ }
2427
+ function describeDrawState(drawContext) {
2428
+ const time = drawContext.endTime - drawContext.startTime;
2429
+ const states = drawContext.surfaceDrawStates;
2430
+ const drawn = states.filter((state) => state.type !== "skip");
2431
+ let str = `Scene ${time.toFixed(3)}ms, ${drawn.length}/${states.length} surfaces drawn`;
2432
+ for (const state of drawn) {
2433
+ const layersDrawn = state.layerDrawStates.filter((layer) => layer.type !== "skip");
2434
+ str += `
2435
+ Surface ${state.surface.name} ${state.time.toFixed(3)}ms, ${layersDrawn.length}/${state.layerDrawStates.length} layers drawn`;
2436
+ for (const layer of layersDrawn) {
2437
+ str += `
2438
+ Layer ${layer.layer.name} ${layer.time.toFixed(3)}ms, ${layer.drewComponents}/${layer.totalComponents} components drawn`;
2439
+ }
2440
+ }
2441
+ return str;
2442
+ }
2443
+
2444
+
2445
+
2446
+
2447
+
2448
+
2449
+
2450
+
2451
+
2452
+
2453
+
2454
+
2455
+
2456
+
2457
+
2458
+
2459
+
2460
+
2461
+
2462
+
2463
+
2464
+
2465
+
2466
+
2467
+
2468
+
2469
+
2470
+ exports.KeyboardObserver = KeyboardObserver; exports.createPointerActionEvent = createPointerActionEvent; exports.PointerObserver = PointerObserver; exports.layoutEpoch = layoutEpoch; exports.relayoutAllViews = relayoutAllViews; exports.AnimationInterpolator = AnimationInterpolator; exports.LinearInterpolator = LinearInterpolator; exports.EaseInInterpolator = EaseInInterpolator; exports.EaseOutInterpolator = EaseOutInterpolator; exports.EaseInOutInterpolator = EaseInOutInterpolator; exports.BounceInterpolator = BounceInterpolator; exports.OvershootInterpolator = OvershootInterpolator; exports.animationInterpolators = animationInterpolators; exports.FrameScheduler = FrameScheduler; exports.defaultScheduler = defaultScheduler; exports.prefersReducedMotion = prefersReducedMotion; exports.motionDuration = motionDuration; exports.Camera = Camera; exports.createMinMaxZoomInterceptor = createMinMaxZoomInterceptor; exports.LayoutContext = LayoutContext; exports.Layer = Layer; exports.shareZoomLevels = shareZoomLevels; exports.ZoomLevelView = ZoomLevelView; exports.Surface = Surface; exports.Scene = Scene;