@vunk/plus 1.11.0 → 1.11.2

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.
@@ -1,2960 +0,0 @@
1
- import { P as Point, E as ExtensionType, r as removeItems, T as Ticker, U as UPDATE_PRIORITY, a as EventEmitter, w as warn, e as extensions, C as Container } from './index2.mjs';
2
- import './init.mjs';
3
- import 'vue';
4
- import '@vunk/shared/enum';
5
- import '@vunk/shared/promise';
6
- import './_commonjsHelpers.mjs';
7
- import './_plugin-vue_export-helper.mjs';
8
- import '@vunk/shared/object';
9
- import '@vunk/core/composables';
10
- import './colorToUniform.mjs';
11
-
12
- class FederatedEvent {
13
- /**
14
- * @param manager - The event boundary which manages this event. Propagation can only occur
15
- * within the boundary's jurisdiction.
16
- */
17
- constructor(manager) {
18
- /** Flags whether this event bubbles. This will take effect only if it is set before propagation. */
19
- this.bubbles = true;
20
- /** @deprecated since 7.0.0 */
21
- this.cancelBubble = true;
22
- /**
23
- * Flags whether this event can be canceled using {@link FederatedEvent.preventDefault}. This is always
24
- * false (for now).
25
- */
26
- this.cancelable = false;
27
- /**
28
- * Flag added for compatibility with DOM `Event`. It is not used in the Federated Events
29
- * API.
30
- * @see https://dom.spec.whatwg.org/#dom-event-composed
31
- * @ignore
32
- */
33
- this.composed = false;
34
- /** Flags whether the default response of the user agent was prevent through this event. */
35
- this.defaultPrevented = false;
36
- /**
37
- * The propagation phase.
38
- * @default {@link FederatedEvent.NONE}
39
- */
40
- this.eventPhase = FederatedEvent.prototype.NONE;
41
- /** Flags whether propagation was stopped. */
42
- this.propagationStopped = false;
43
- /** Flags whether propagation was immediately stopped. */
44
- this.propagationImmediatelyStopped = false;
45
- /** The coordinates of the event relative to the nearest DOM layer. This is a non-standard property. */
46
- this.layer = new Point();
47
- /** The coordinates of the event relative to the DOM document. This is a non-standard property. */
48
- this.page = new Point();
49
- /**
50
- * The event propagation phase NONE that indicates that the event is not in any phase.
51
- * @default 0
52
- * @advanced
53
- */
54
- this.NONE = 0;
55
- /**
56
- * The event propagation phase CAPTURING_PHASE that indicates that the event is in the capturing phase.
57
- * @default 1
58
- * @advanced
59
- */
60
- this.CAPTURING_PHASE = 1;
61
- /**
62
- * The event propagation phase AT_TARGET that indicates that the event is at the target.
63
- * @default 2
64
- * @advanced
65
- */
66
- this.AT_TARGET = 2;
67
- /**
68
- * The event propagation phase BUBBLING_PHASE that indicates that the event is in the bubbling phase.
69
- * @default 3
70
- * @advanced
71
- */
72
- this.BUBBLING_PHASE = 3;
73
- this.manager = manager;
74
- }
75
- /** @readonly */
76
- get layerX() {
77
- return this.layer.x;
78
- }
79
- /** @readonly */
80
- get layerY() {
81
- return this.layer.y;
82
- }
83
- /** @readonly */
84
- get pageX() {
85
- return this.page.x;
86
- }
87
- /** @readonly */
88
- get pageY() {
89
- return this.page.y;
90
- }
91
- /**
92
- * Fallback for the deprecated `InteractionEvent.data`.
93
- * @deprecated since 7.0.0
94
- */
95
- get data() {
96
- return this;
97
- }
98
- /**
99
- * The propagation path for this event. Alias for {@link EventBoundary.propagationPath}.
100
- * @advanced
101
- */
102
- composedPath() {
103
- if (this.manager && (!this.path || this.path[this.path.length - 1] !== this.target)) {
104
- this.path = this.target ? this.manager.propagationPath(this.target) : [];
105
- }
106
- return this.path;
107
- }
108
- /**
109
- * Unimplemented method included for implementing the DOM interface `Event`. It will throw an `Error`.
110
- * @deprecated
111
- * @ignore
112
- * @param _type
113
- * @param _bubbles
114
- * @param _cancelable
115
- */
116
- initEvent(_type, _bubbles, _cancelable) {
117
- throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.");
118
- }
119
- /**
120
- * Unimplemented method included for implementing the DOM interface `UIEvent`. It will throw an `Error`.
121
- * @ignore
122
- * @deprecated
123
- * @param _typeArg
124
- * @param _bubblesArg
125
- * @param _cancelableArg
126
- * @param _viewArg
127
- * @param _detailArg
128
- */
129
- initUIEvent(_typeArg, _bubblesArg, _cancelableArg, _viewArg, _detailArg) {
130
- throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.");
131
- }
132
- /**
133
- * Prevent default behavior of both PixiJS and the user agent.
134
- * @example
135
- * ```ts
136
- * sprite.on('click', (event) => {
137
- * // Prevent both browser's default click behavior
138
- * // and PixiJS's default handling
139
- * event.preventDefault();
140
- *
141
- * // Custom handling
142
- * customClickHandler();
143
- * });
144
- * ```
145
- * @remarks
146
- * - Only works if the native event is cancelable
147
- * - Does not stop event propagation
148
- */
149
- preventDefault() {
150
- if (this.nativeEvent instanceof Event && this.nativeEvent.cancelable) {
151
- this.nativeEvent.preventDefault();
152
- }
153
- this.defaultPrevented = true;
154
- }
155
- /**
156
- * Stop this event from propagating to any additional listeners, including those
157
- * on the current target and any following targets in the propagation path.
158
- * @example
159
- * ```ts
160
- * container.on('pointerdown', (event) => {
161
- * // Stop all further event handling
162
- * event.stopImmediatePropagation();
163
- *
164
- * // These handlers won't be called:
165
- * // - Other pointerdown listeners on this container
166
- * // - Any pointerdown listeners on parent containers
167
- * });
168
- * ```
169
- * @remarks
170
- * - Immediately stops all event propagation
171
- * - Prevents other listeners on same target from being called
172
- * - More aggressive than stopPropagation()
173
- */
174
- stopImmediatePropagation() {
175
- this.propagationImmediatelyStopped = true;
176
- }
177
- /**
178
- * Stop this event from propagating to the next target in the propagation path.
179
- * The rest of the listeners on the current target will still be notified.
180
- * @example
181
- * ```ts
182
- * child.on('pointermove', (event) => {
183
- * // Handle event on child
184
- * updateChild();
185
- *
186
- * // Prevent parent handlers from being called
187
- * event.stopPropagation();
188
- * });
189
- *
190
- * // This won't be called if child handles the event
191
- * parent.on('pointermove', (event) => {
192
- * updateParent();
193
- * });
194
- * ```
195
- * @remarks
196
- * - Stops event bubbling to parent containers
197
- * - Does not prevent other listeners on same target
198
- * - Less aggressive than stopImmediatePropagation()
199
- */
200
- stopPropagation() {
201
- this.propagationStopped = true;
202
- }
203
- }
204
-
205
- var appleIphone = /iPhone/i;
206
- var appleIpod = /iPod/i;
207
- var appleTablet = /iPad/i;
208
- var appleUniversal = /\biOS-universal(?:.+)Mac\b/i;
209
- var androidPhone = /\bAndroid(?:.+)Mobile\b/i;
210
- var androidTablet = /Android/i;
211
- var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i;
212
- var amazonTablet = /Silk/i;
213
- var windowsPhone = /Windows Phone/i;
214
- var windowsTablet = /\bWindows(?:.+)ARM\b/i;
215
- var otherBlackBerry = /BlackBerry/i;
216
- var otherBlackBerry10 = /BB10/i;
217
- var otherOpera = /Opera Mini/i;
218
- var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i;
219
- var otherFirefox = /Mobile(?:.+)Firefox\b/i;
220
- var isAppleTabletOnIos13 = function (navigator) {
221
- return (typeof navigator !== 'undefined' &&
222
- navigator.platform === 'MacIntel' &&
223
- typeof navigator.maxTouchPoints === 'number' &&
224
- navigator.maxTouchPoints > 1 &&
225
- typeof MSStream === 'undefined');
226
- };
227
- function createMatch(userAgent) {
228
- return function (regex) { return regex.test(userAgent); };
229
- }
230
- function isMobile$1(param) {
231
- var nav = {
232
- userAgent: '',
233
- platform: '',
234
- maxTouchPoints: 0
235
- };
236
- if (!param && typeof navigator !== 'undefined') {
237
- nav = {
238
- userAgent: navigator.userAgent,
239
- platform: navigator.platform,
240
- maxTouchPoints: navigator.maxTouchPoints || 0
241
- };
242
- }
243
- else if (typeof param === 'string') {
244
- nav.userAgent = param;
245
- }
246
- else if (param && param.userAgent) {
247
- nav = {
248
- userAgent: param.userAgent,
249
- platform: param.platform,
250
- maxTouchPoints: param.maxTouchPoints || 0
251
- };
252
- }
253
- var userAgent = nav.userAgent;
254
- var tmp = userAgent.split('[FBAN');
255
- if (typeof tmp[1] !== 'undefined') {
256
- userAgent = tmp[0];
257
- }
258
- tmp = userAgent.split('Twitter');
259
- if (typeof tmp[1] !== 'undefined') {
260
- userAgent = tmp[0];
261
- }
262
- var match = createMatch(userAgent);
263
- var result = {
264
- apple: {
265
- phone: match(appleIphone) && !match(windowsPhone),
266
- ipod: match(appleIpod),
267
- tablet: !match(appleIphone) &&
268
- (match(appleTablet) || isAppleTabletOnIos13(nav)) &&
269
- !match(windowsPhone),
270
- universal: match(appleUniversal),
271
- device: (match(appleIphone) ||
272
- match(appleIpod) ||
273
- match(appleTablet) ||
274
- match(appleUniversal) ||
275
- isAppleTabletOnIos13(nav)) &&
276
- !match(windowsPhone)
277
- },
278
- amazon: {
279
- phone: match(amazonPhone),
280
- tablet: !match(amazonPhone) && match(amazonTablet),
281
- device: match(amazonPhone) || match(amazonTablet)
282
- },
283
- android: {
284
- phone: (!match(windowsPhone) && match(amazonPhone)) ||
285
- (!match(windowsPhone) && match(androidPhone)),
286
- tablet: !match(windowsPhone) &&
287
- !match(amazonPhone) &&
288
- !match(androidPhone) &&
289
- (match(amazonTablet) || match(androidTablet)),
290
- device: (!match(windowsPhone) &&
291
- (match(amazonPhone) ||
292
- match(amazonTablet) ||
293
- match(androidPhone) ||
294
- match(androidTablet))) ||
295
- match(/\bokhttp\b/i)
296
- },
297
- windows: {
298
- phone: match(windowsPhone),
299
- tablet: match(windowsTablet),
300
- device: match(windowsPhone) || match(windowsTablet)
301
- },
302
- other: {
303
- blackberry: match(otherBlackBerry),
304
- blackberry10: match(otherBlackBerry10),
305
- opera: match(otherOpera),
306
- firefox: match(otherFirefox),
307
- chrome: match(otherChrome),
308
- device: match(otherBlackBerry) ||
309
- match(otherBlackBerry10) ||
310
- match(otherOpera) ||
311
- match(otherFirefox) ||
312
- match(otherChrome)
313
- },
314
- any: false,
315
- phone: false,
316
- tablet: false
317
- };
318
- result.any =
319
- result.apple.device ||
320
- result.android.device ||
321
- result.windows.device ||
322
- result.other.device;
323
- result.phone =
324
- result.apple.phone || result.android.phone || result.windows.phone;
325
- result.tablet =
326
- result.apple.tablet || result.android.tablet || result.windows.tablet;
327
- return result;
328
- }
329
-
330
- const isMobileCall = isMobile$1.default ?? isMobile$1;
331
- const isMobile = isMobileCall(globalThis.navigator);
332
-
333
- const KEY_CODE_TAB = 9;
334
- const DIV_TOUCH_SIZE = 100;
335
- const DIV_TOUCH_POS_X = 0;
336
- const DIV_TOUCH_POS_Y = 0;
337
- const DIV_TOUCH_ZINDEX = 2;
338
- const DIV_HOOK_SIZE = 1;
339
- const DIV_HOOK_POS_X = -1e3;
340
- const DIV_HOOK_POS_Y = -1e3;
341
- const DIV_HOOK_ZINDEX = 2;
342
- const _AccessibilitySystem = class _AccessibilitySystem {
343
- // 2fps
344
- // eslint-disable-next-line jsdoc/require-param
345
- /**
346
- * @param {WebGLRenderer|WebGPURenderer} renderer - A reference to the current renderer
347
- */
348
- constructor(renderer, _mobileInfo = isMobile) {
349
- this._mobileInfo = _mobileInfo;
350
- /** Whether accessibility divs are visible for debugging */
351
- this.debug = false;
352
- /** Whether to activate on tab key press */
353
- this._activateOnTab = true;
354
- /** Whether to deactivate accessibility when mouse moves */
355
- this._deactivateOnMouseMove = true;
356
- /** Internal variable, see isActive getter. */
357
- this._isActive = false;
358
- /** Internal variable, see isMobileAccessibility getter. */
359
- this._isMobileAccessibility = false;
360
- /** This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. */
361
- this._div = null;
362
- /** A simple pool for storing divs. */
363
- this._pool = [];
364
- /** This is a tick used to check if an object is no longer being rendered. */
365
- this._renderId = 0;
366
- /** The array of currently active accessible items. */
367
- this._children = [];
368
- /** Count to throttle div updates on android devices. */
369
- this._androidUpdateCount = 0;
370
- /** The frequency to update the div elements. */
371
- this._androidUpdateFrequency = 500;
372
- this._hookDiv = null;
373
- if (_mobileInfo.tablet || _mobileInfo.phone) {
374
- this._createTouchHook();
375
- }
376
- this._renderer = renderer;
377
- }
378
- /**
379
- * Value of `true` if accessibility is currently active and accessibility layers are showing.
380
- * @type {boolean}
381
- * @readonly
382
- */
383
- get isActive() {
384
- return this._isActive;
385
- }
386
- /**
387
- * Value of `true` if accessibility is enabled for touch devices.
388
- * @type {boolean}
389
- * @readonly
390
- */
391
- get isMobileAccessibility() {
392
- return this._isMobileAccessibility;
393
- }
394
- /**
395
- * The DOM element that will sit over the PixiJS element. This is where the div overlays will go.
396
- * @readonly
397
- */
398
- get hookDiv() {
399
- return this._hookDiv;
400
- }
401
- /**
402
- * Creates the touch hooks.
403
- * @private
404
- */
405
- _createTouchHook() {
406
- const hookDiv = document.createElement("button");
407
- hookDiv.style.width = `${DIV_HOOK_SIZE}px`;
408
- hookDiv.style.height = `${DIV_HOOK_SIZE}px`;
409
- hookDiv.style.position = "absolute";
410
- hookDiv.style.top = `${DIV_HOOK_POS_X}px`;
411
- hookDiv.style.left = `${DIV_HOOK_POS_Y}px`;
412
- hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString();
413
- hookDiv.style.backgroundColor = "#FF0000";
414
- hookDiv.title = "select to enable accessibility for this content";
415
- hookDiv.addEventListener("focus", () => {
416
- this._isMobileAccessibility = true;
417
- this._activate();
418
- this._destroyTouchHook();
419
- });
420
- document.body.appendChild(hookDiv);
421
- this._hookDiv = hookDiv;
422
- }
423
- /**
424
- * Destroys the touch hooks.
425
- * @private
426
- */
427
- _destroyTouchHook() {
428
- if (!this._hookDiv) {
429
- return;
430
- }
431
- document.body.removeChild(this._hookDiv);
432
- this._hookDiv = null;
433
- }
434
- /**
435
- * Activating will cause the Accessibility layer to be shown.
436
- * This is called when a user presses the tab key.
437
- * @private
438
- */
439
- _activate() {
440
- if (this._isActive) {
441
- return;
442
- }
443
- this._isActive = true;
444
- if (!this._div) {
445
- this._div = document.createElement("div");
446
- this._div.style.width = `${DIV_TOUCH_SIZE}px`;
447
- this._div.style.height = `${DIV_TOUCH_SIZE}px`;
448
- this._div.style.position = "absolute";
449
- this._div.style.top = `${DIV_TOUCH_POS_X}px`;
450
- this._div.style.left = `${DIV_TOUCH_POS_Y}px`;
451
- this._div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
452
- this._div.style.pointerEvents = "none";
453
- }
454
- if (this._activateOnTab) {
455
- this._onKeyDown = this._onKeyDown.bind(this);
456
- globalThis.addEventListener("keydown", this._onKeyDown, false);
457
- }
458
- if (this._deactivateOnMouseMove) {
459
- this._onMouseMove = this._onMouseMove.bind(this);
460
- globalThis.document.addEventListener("mousemove", this._onMouseMove, true);
461
- }
462
- const canvas = this._renderer.view.canvas;
463
- if (!canvas.parentNode) {
464
- const observer = new MutationObserver(() => {
465
- if (canvas.parentNode) {
466
- canvas.parentNode.appendChild(this._div);
467
- observer.disconnect();
468
- this._initAccessibilitySetup();
469
- }
470
- });
471
- observer.observe(document.body, { childList: true, subtree: true });
472
- } else {
473
- canvas.parentNode.appendChild(this._div);
474
- this._initAccessibilitySetup();
475
- }
476
- }
477
- // New method to handle initialization after div is ready
478
- _initAccessibilitySetup() {
479
- this._renderer.runners.postrender.add(this);
480
- if (this._renderer.lastObjectRendered) {
481
- this._updateAccessibleObjects(this._renderer.lastObjectRendered);
482
- }
483
- }
484
- /**
485
- * Deactivates the accessibility system. Removes listeners and accessibility elements.
486
- * @private
487
- */
488
- _deactivate() {
489
- if (!this._isActive || this._isMobileAccessibility) {
490
- return;
491
- }
492
- this._isActive = false;
493
- globalThis.document.removeEventListener("mousemove", this._onMouseMove, true);
494
- if (this._activateOnTab) {
495
- globalThis.addEventListener("keydown", this._onKeyDown, false);
496
- }
497
- this._renderer.runners.postrender.remove(this);
498
- for (const child of this._children) {
499
- if (child._accessibleDiv && child._accessibleDiv.parentNode) {
500
- child._accessibleDiv.parentNode.removeChild(child._accessibleDiv);
501
- child._accessibleDiv = null;
502
- }
503
- child._accessibleActive = false;
504
- }
505
- this._pool.forEach((div) => {
506
- if (div.parentNode) {
507
- div.parentNode.removeChild(div);
508
- }
509
- });
510
- if (this._div && this._div.parentNode) {
511
- this._div.parentNode.removeChild(this._div);
512
- }
513
- this._pool = [];
514
- this._children = [];
515
- }
516
- /**
517
- * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
518
- * @private
519
- * @param {Container} container - The Container to check.
520
- */
521
- _updateAccessibleObjects(container) {
522
- if (!container.visible || !container.accessibleChildren) {
523
- return;
524
- }
525
- if (container.accessible) {
526
- if (!container._accessibleActive) {
527
- this._addChild(container);
528
- }
529
- container._renderId = this._renderId;
530
- }
531
- const children = container.children;
532
- if (children) {
533
- for (let i = 0; i < children.length; i++) {
534
- this._updateAccessibleObjects(children[i]);
535
- }
536
- }
537
- }
538
- /**
539
- * Runner init called, view is available at this point.
540
- * @ignore
541
- */
542
- init(options) {
543
- const defaultOpts = _AccessibilitySystem.defaultOptions;
544
- const mergedOptions = {
545
- accessibilityOptions: {
546
- ...defaultOpts,
547
- ...options?.accessibilityOptions || {}
548
- }
549
- };
550
- this.debug = mergedOptions.accessibilityOptions.debug;
551
- this._activateOnTab = mergedOptions.accessibilityOptions.activateOnTab;
552
- this._deactivateOnMouseMove = mergedOptions.accessibilityOptions.deactivateOnMouseMove;
553
- if (mergedOptions.accessibilityOptions.enabledByDefault) {
554
- this._activate();
555
- } else if (this._activateOnTab) {
556
- this._onKeyDown = this._onKeyDown.bind(this);
557
- globalThis.addEventListener("keydown", this._onKeyDown, false);
558
- }
559
- this._renderer.runners.postrender.remove(this);
560
- }
561
- /**
562
- * Updates the accessibility layer during rendering.
563
- * - Removes divs for containers no longer in the scene
564
- * - Updates the position and dimensions of the root div
565
- * - Updates positions of active accessibility divs
566
- * Only fires while the accessibility system is active.
567
- * @ignore
568
- */
569
- postrender() {
570
- const now = performance.now();
571
- if (this._mobileInfo.android.device && now < this._androidUpdateCount) {
572
- return;
573
- }
574
- this._androidUpdateCount = now + this._androidUpdateFrequency;
575
- if (!this._renderer.renderingToScreen || !this._renderer.view.canvas) {
576
- return;
577
- }
578
- const activeIds = /* @__PURE__ */ new Set();
579
- if (this._renderer.lastObjectRendered) {
580
- this._updateAccessibleObjects(this._renderer.lastObjectRendered);
581
- for (const child of this._children) {
582
- if (child._renderId === this._renderId) {
583
- activeIds.add(this._children.indexOf(child));
584
- }
585
- }
586
- }
587
- for (let i = this._children.length - 1; i >= 0; i--) {
588
- const child = this._children[i];
589
- if (!activeIds.has(i)) {
590
- if (child._accessibleDiv && child._accessibleDiv.parentNode) {
591
- child._accessibleDiv.parentNode.removeChild(child._accessibleDiv);
592
- this._pool.push(child._accessibleDiv);
593
- child._accessibleDiv = null;
594
- }
595
- child._accessibleActive = false;
596
- removeItems(this._children, i, 1);
597
- }
598
- }
599
- if (this._renderer.renderingToScreen) {
600
- const { x, y, width: viewWidth, height: viewHeight } = this._renderer.screen;
601
- const div = this._div;
602
- div.style.left = `${x}px`;
603
- div.style.top = `${y}px`;
604
- div.style.width = `${viewWidth}px`;
605
- div.style.height = `${viewHeight}px`;
606
- }
607
- for (let i = 0; i < this._children.length; i++) {
608
- const child = this._children[i];
609
- if (!child._accessibleActive || !child._accessibleDiv) {
610
- continue;
611
- }
612
- const div = child._accessibleDiv;
613
- const hitArea = child.hitArea || child.getBounds().rectangle;
614
- if (child.hitArea) {
615
- const wt = child.worldTransform;
616
- const sx = this._renderer.resolution;
617
- const sy = this._renderer.resolution;
618
- div.style.left = `${(wt.tx + hitArea.x * wt.a) * sx}px`;
619
- div.style.top = `${(wt.ty + hitArea.y * wt.d) * sy}px`;
620
- div.style.width = `${hitArea.width * wt.a * sx}px`;
621
- div.style.height = `${hitArea.height * wt.d * sy}px`;
622
- } else {
623
- this._capHitArea(hitArea);
624
- const sx = this._renderer.resolution;
625
- const sy = this._renderer.resolution;
626
- div.style.left = `${hitArea.x * sx}px`;
627
- div.style.top = `${hitArea.y * sy}px`;
628
- div.style.width = `${hitArea.width * sx}px`;
629
- div.style.height = `${hitArea.height * sy}px`;
630
- }
631
- }
632
- this._renderId++;
633
- }
634
- /**
635
- * private function that will visually add the information to the
636
- * accessibility div
637
- * @param {HTMLElement} div -
638
- */
639
- _updateDebugHTML(div) {
640
- div.innerHTML = `type: ${div.type}</br> title : ${div.title}</br> tabIndex: ${div.tabIndex}`;
641
- }
642
- /**
643
- * Adjust the hit area based on the bounds of a display object
644
- * @param {Rectangle} hitArea - Bounds of the child
645
- */
646
- _capHitArea(hitArea) {
647
- if (hitArea.x < 0) {
648
- hitArea.width += hitArea.x;
649
- hitArea.x = 0;
650
- }
651
- if (hitArea.y < 0) {
652
- hitArea.height += hitArea.y;
653
- hitArea.y = 0;
654
- }
655
- const { width: viewWidth, height: viewHeight } = this._renderer;
656
- if (hitArea.x + hitArea.width > viewWidth) {
657
- hitArea.width = viewWidth - hitArea.x;
658
- }
659
- if (hitArea.y + hitArea.height > viewHeight) {
660
- hitArea.height = viewHeight - hitArea.y;
661
- }
662
- }
663
- /**
664
- * Creates or reuses a div element for a Container and adds it to the accessibility layer.
665
- * Sets up ARIA attributes, event listeners, and positioning based on the container's properties.
666
- * @private
667
- * @param {Container} container - The child to make accessible.
668
- */
669
- _addChild(container) {
670
- let div = this._pool.pop();
671
- if (!div) {
672
- if (container.accessibleType === "button") {
673
- div = document.createElement("button");
674
- } else {
675
- div = document.createElement(container.accessibleType);
676
- div.style.cssText = `
677
- color: transparent;
678
- pointer-events: none;
679
- padding: 0;
680
- margin: 0;
681
- border: 0;
682
- outline: 0;
683
- background: transparent;
684
- box-sizing: border-box;
685
- user-select: none;
686
- -webkit-user-select: none;
687
- -moz-user-select: none;
688
- -ms-user-select: none;
689
- `;
690
- if (container.accessibleText) {
691
- div.innerText = container.accessibleText;
692
- }
693
- }
694
- div.style.width = `${DIV_TOUCH_SIZE}px`;
695
- div.style.height = `${DIV_TOUCH_SIZE}px`;
696
- div.style.backgroundColor = this.debug ? "rgba(255,255,255,0.5)" : "transparent";
697
- div.style.position = "absolute";
698
- div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
699
- div.style.borderStyle = "none";
700
- if (navigator.userAgent.toLowerCase().includes("chrome")) {
701
- div.setAttribute("aria-live", "off");
702
- } else {
703
- div.setAttribute("aria-live", "polite");
704
- }
705
- if (navigator.userAgent.match(/rv:.*Gecko\//)) {
706
- div.setAttribute("aria-relevant", "additions");
707
- } else {
708
- div.setAttribute("aria-relevant", "text");
709
- }
710
- div.addEventListener("click", this._onClick.bind(this));
711
- div.addEventListener("focus", this._onFocus.bind(this));
712
- div.addEventListener("focusout", this._onFocusOut.bind(this));
713
- }
714
- div.style.pointerEvents = container.accessiblePointerEvents;
715
- div.type = container.accessibleType;
716
- if (container.accessibleTitle && container.accessibleTitle !== null) {
717
- div.title = container.accessibleTitle;
718
- } else if (!container.accessibleHint || container.accessibleHint === null) {
719
- div.title = `container ${container.tabIndex}`;
720
- }
721
- if (container.accessibleHint && container.accessibleHint !== null) {
722
- div.setAttribute("aria-label", container.accessibleHint);
723
- }
724
- if (this.debug) {
725
- this._updateDebugHTML(div);
726
- }
727
- container._accessibleActive = true;
728
- container._accessibleDiv = div;
729
- div.container = container;
730
- this._children.push(container);
731
- this._div.appendChild(container._accessibleDiv);
732
- if (container.interactive) {
733
- container._accessibleDiv.tabIndex = container.tabIndex;
734
- }
735
- }
736
- /**
737
- * Dispatch events with the EventSystem.
738
- * @param e
739
- * @param type
740
- * @private
741
- */
742
- _dispatchEvent(e, type) {
743
- const { container: target } = e.target;
744
- const boundary = this._renderer.events.rootBoundary;
745
- const event = Object.assign(new FederatedEvent(boundary), { target });
746
- boundary.rootTarget = this._renderer.lastObjectRendered;
747
- type.forEach((type2) => boundary.dispatchEvent(event, type2));
748
- }
749
- /**
750
- * Maps the div button press to pixi's EventSystem (click)
751
- * @private
752
- * @param {MouseEvent} e - The click event.
753
- */
754
- _onClick(e) {
755
- this._dispatchEvent(e, ["click", "pointertap", "tap"]);
756
- }
757
- /**
758
- * Maps the div focus events to pixi's EventSystem (mouseover)
759
- * @private
760
- * @param {FocusEvent} e - The focus event.
761
- */
762
- _onFocus(e) {
763
- if (!e.target.getAttribute("aria-live")) {
764
- e.target.setAttribute("aria-live", "assertive");
765
- }
766
- this._dispatchEvent(e, ["mouseover"]);
767
- }
768
- /**
769
- * Maps the div focus events to pixi's EventSystem (mouseout)
770
- * @private
771
- * @param {FocusEvent} e - The focusout event.
772
- */
773
- _onFocusOut(e) {
774
- if (!e.target.getAttribute("aria-live")) {
775
- e.target.setAttribute("aria-live", "polite");
776
- }
777
- this._dispatchEvent(e, ["mouseout"]);
778
- }
779
- /**
780
- * Is called when a key is pressed
781
- * @private
782
- * @param {KeyboardEvent} e - The keydown event.
783
- */
784
- _onKeyDown(e) {
785
- if (e.keyCode !== KEY_CODE_TAB || !this._activateOnTab) {
786
- return;
787
- }
788
- this._activate();
789
- }
790
- /**
791
- * Is called when the mouse moves across the renderer element
792
- * @private
793
- * @param {MouseEvent} e - The mouse event.
794
- */
795
- _onMouseMove(e) {
796
- if (e.movementX === 0 && e.movementY === 0) {
797
- return;
798
- }
799
- this._deactivate();
800
- }
801
- /**
802
- * Destroys the accessibility system. Removes all elements and listeners.
803
- * > [!IMPORTANT] This is typically called automatically when the {@link Application} is destroyed.
804
- * > A typically user should not need to call this method directly.
805
- */
806
- destroy() {
807
- this._deactivate();
808
- this._destroyTouchHook();
809
- this._div = null;
810
- this._pool = null;
811
- this._children = null;
812
- this._renderer = null;
813
- if (this._activateOnTab) {
814
- globalThis.removeEventListener("keydown", this._onKeyDown);
815
- }
816
- }
817
- /**
818
- * Enables or disables the accessibility system.
819
- * @param enabled - Whether to enable or disable accessibility.
820
- * @example
821
- * ```js
822
- * app.renderer.accessibility.setAccessibilityEnabled(true); // Enable accessibility
823
- * app.renderer.accessibility.setAccessibilityEnabled(false); // Disable accessibility
824
- * ```
825
- */
826
- setAccessibilityEnabled(enabled) {
827
- if (enabled) {
828
- this._activate();
829
- } else {
830
- this._deactivate();
831
- }
832
- }
833
- };
834
- /** @ignore */
835
- _AccessibilitySystem.extension = {
836
- type: [
837
- ExtensionType.WebGLSystem,
838
- ExtensionType.WebGPUSystem
839
- ],
840
- name: "accessibility"
841
- };
842
- /**
843
- * The default options used by the system.
844
- * You can set these before initializing the {@link Application} to change the default behavior.
845
- * @example
846
- * ```js
847
- * import { AccessibilitySystem } from 'pixi.js';
848
- *
849
- * AccessibilitySystem.defaultOptions.enabledByDefault = true;
850
- *
851
- * const app = new Application()
852
- * app.init()
853
- * ```
854
- */
855
- _AccessibilitySystem.defaultOptions = {
856
- /**
857
- * Whether to enable accessibility features on initialization
858
- * @default false
859
- */
860
- enabledByDefault: false,
861
- /**
862
- * Whether to visually show the accessibility divs for debugging
863
- * @default false
864
- */
865
- debug: false,
866
- /**
867
- * Whether to activate accessibility when tab key is pressed
868
- * @default true
869
- */
870
- activateOnTab: true,
871
- /**
872
- * Whether to deactivate accessibility when mouse moves
873
- * @default true
874
- */
875
- deactivateOnMouseMove: true
876
- };
877
- let AccessibilitySystem = _AccessibilitySystem;
878
-
879
- const accessibilityTarget = {
880
- accessible: false,
881
- accessibleTitle: null,
882
- accessibleHint: null,
883
- tabIndex: 0,
884
- accessibleType: "button",
885
- accessibleText: null,
886
- accessiblePointerEvents: "auto",
887
- accessibleChildren: true,
888
- _accessibleActive: false,
889
- _accessibleDiv: null,
890
- _renderId: -1
891
- };
892
-
893
- class DOMPipe {
894
- /**
895
- * Constructor for the DOMPipe class.
896
- * @param renderer - The renderer instance that this DOMPipe will be associated with.
897
- */
898
- constructor(renderer) {
899
- /** Array to keep track of attached DOM elements */
900
- this._attachedDomElements = [];
901
- this._renderer = renderer;
902
- this._renderer.runners.postrender.add(this);
903
- this._domElement = document.createElement("div");
904
- this._domElement.style.position = "absolute";
905
- this._domElement.style.top = "0";
906
- this._domElement.style.left = "0";
907
- this._domElement.style.pointerEvents = "none";
908
- this._domElement.style.zIndex = "1000";
909
- }
910
- /**
911
- * Adds a renderable DOM container to the list of attached elements.
912
- * @param domContainer - The DOM container to be added.
913
- * @param _instructionSet - The instruction set (unused).
914
- */
915
- addRenderable(domContainer, _instructionSet) {
916
- if (!this._attachedDomElements.includes(domContainer)) {
917
- this._attachedDomElements.push(domContainer);
918
- }
919
- }
920
- /**
921
- * Updates a renderable DOM container.
922
- * @param _domContainer - The DOM container to be updated (unused).
923
- */
924
- updateRenderable(_domContainer) {
925
- }
926
- /**
927
- * Validates a renderable DOM container.
928
- * @param _domContainer - The DOM container to be validated (unused).
929
- * @returns Always returns true as validation is not required.
930
- */
931
- validateRenderable(_domContainer) {
932
- return true;
933
- }
934
- /** Handles the post-rendering process, ensuring DOM elements are correctly positioned and visible. */
935
- postrender() {
936
- const attachedDomElements = this._attachedDomElements;
937
- if (attachedDomElements.length === 0) {
938
- this._domElement.remove();
939
- return;
940
- }
941
- const canvas = this._renderer.view.canvas;
942
- if (this._domElement.parentNode !== canvas.parentNode) {
943
- canvas.parentNode?.appendChild(this._domElement);
944
- }
945
- const sx = parseFloat(canvas.style.width) / canvas.width * this._renderer.resolution;
946
- const sy = parseFloat(canvas.style.height) / canvas.height * this._renderer.resolution;
947
- this._domElement.style.transform = `translate(${canvas.offsetLeft}px, ${canvas.offsetTop}px) scale(${sx}, ${sy})`;
948
- for (let i = 0; i < attachedDomElements.length; i++) {
949
- const domContainer = attachedDomElements[i];
950
- const element = domContainer.element;
951
- if (!domContainer.parent || domContainer.globalDisplayStatus < 7) {
952
- element?.remove();
953
- attachedDomElements.splice(i, 1);
954
- i--;
955
- } else {
956
- if (!this._domElement.contains(element)) {
957
- element.style.position = "absolute";
958
- element.style.pointerEvents = "auto";
959
- this._domElement.appendChild(element);
960
- }
961
- const wt = domContainer.worldTransform;
962
- const anchor = domContainer._anchor;
963
- const ax = domContainer.width * anchor.x;
964
- const ay = domContainer.height * anchor.y;
965
- element.style.transformOrigin = `${ax}px ${ay}px`;
966
- element.style.transform = `matrix(${wt.a}, ${wt.b}, ${wt.c}, ${wt.d}, ${wt.tx - ax}, ${wt.ty - ay})`;
967
- element.style.opacity = domContainer.groupAlpha.toString();
968
- }
969
- }
970
- }
971
- /** Destroys the DOMPipe, removing all attached DOM elements and cleaning up resources. */
972
- destroy() {
973
- this._renderer.runners.postrender.remove(this);
974
- for (let i = 0; i < this._attachedDomElements.length; i++) {
975
- const domContainer = this._attachedDomElements[i];
976
- domContainer.element?.remove();
977
- }
978
- this._attachedDomElements.length = 0;
979
- this._domElement.remove();
980
- this._renderer = null;
981
- }
982
- }
983
- /**
984
- * Static property defining the extension type and name for the DOMPipe.
985
- * This is used to register the DOMPipe with different rendering pipelines.
986
- */
987
- DOMPipe.extension = {
988
- type: [
989
- ExtensionType.WebGLPipes,
990
- ExtensionType.WebGPUPipes,
991
- ExtensionType.CanvasPipes
992
- ],
993
- name: "dom"
994
- };
995
-
996
- class EventsTickerClass {
997
- constructor() {
998
- /** The frequency that fake events will be fired. */
999
- this.interactionFrequency = 10;
1000
- this._deltaTime = 0;
1001
- this._didMove = false;
1002
- this._tickerAdded = false;
1003
- this._pauseUpdate = true;
1004
- }
1005
- /**
1006
- * Initializes the event ticker.
1007
- * @param events - The event system.
1008
- */
1009
- init(events) {
1010
- this.removeTickerListener();
1011
- this.events = events;
1012
- this.interactionFrequency = 10;
1013
- this._deltaTime = 0;
1014
- this._didMove = false;
1015
- this._tickerAdded = false;
1016
- this._pauseUpdate = true;
1017
- }
1018
- /** Whether to pause the update checks or not. */
1019
- get pauseUpdate() {
1020
- return this._pauseUpdate;
1021
- }
1022
- set pauseUpdate(paused) {
1023
- this._pauseUpdate = paused;
1024
- }
1025
- /** Adds the ticker listener. */
1026
- addTickerListener() {
1027
- if (this._tickerAdded || !this.domElement) {
1028
- return;
1029
- }
1030
- Ticker.system.add(this._tickerUpdate, this, UPDATE_PRIORITY.INTERACTION);
1031
- this._tickerAdded = true;
1032
- }
1033
- /** Removes the ticker listener. */
1034
- removeTickerListener() {
1035
- if (!this._tickerAdded) {
1036
- return;
1037
- }
1038
- Ticker.system.remove(this._tickerUpdate, this);
1039
- this._tickerAdded = false;
1040
- }
1041
- /** Sets flag to not fire extra events when the user has already moved there mouse */
1042
- pointerMoved() {
1043
- this._didMove = true;
1044
- }
1045
- /** Updates the state of interactive objects. */
1046
- _update() {
1047
- if (!this.domElement || this._pauseUpdate) {
1048
- return;
1049
- }
1050
- if (this._didMove) {
1051
- this._didMove = false;
1052
- return;
1053
- }
1054
- const rootPointerEvent = this.events["_rootPointerEvent"];
1055
- if (this.events.supportsTouchEvents && rootPointerEvent.pointerType === "touch") {
1056
- return;
1057
- }
1058
- globalThis.document.dispatchEvent(this.events.supportsPointerEvents ? new PointerEvent("pointermove", {
1059
- clientX: rootPointerEvent.clientX,
1060
- clientY: rootPointerEvent.clientY,
1061
- pointerType: rootPointerEvent.pointerType,
1062
- pointerId: rootPointerEvent.pointerId
1063
- }) : new MouseEvent("mousemove", {
1064
- clientX: rootPointerEvent.clientX,
1065
- clientY: rootPointerEvent.clientY
1066
- }));
1067
- }
1068
- /**
1069
- * Updates the state of interactive objects if at least {@link interactionFrequency}
1070
- * milliseconds have passed since the last invocation.
1071
- *
1072
- * Invoked by a throttled ticker update from {@link Ticker.system}.
1073
- * @param ticker - The throttled ticker.
1074
- */
1075
- _tickerUpdate(ticker) {
1076
- this._deltaTime += ticker.deltaTime;
1077
- if (this._deltaTime < this.interactionFrequency) {
1078
- return;
1079
- }
1080
- this._deltaTime = 0;
1081
- this._update();
1082
- }
1083
- }
1084
- const EventsTicker = new EventsTickerClass();
1085
-
1086
- class FederatedMouseEvent extends FederatedEvent {
1087
- constructor() {
1088
- super(...arguments);
1089
- /** The coordinates of the mouse event relative to the canvas. */
1090
- this.client = new Point();
1091
- /** The movement in this pointer relative to the last `mousemove` event. */
1092
- this.movement = new Point();
1093
- /** The offset of the pointer coordinates w.r.t. target Container in world space. This is not supported at the moment. */
1094
- this.offset = new Point();
1095
- /** The pointer coordinates in world space. */
1096
- this.global = new Point();
1097
- /**
1098
- * The pointer coordinates in the renderer's {@link AbstractRenderer.screen screen}. This has slightly
1099
- * different semantics than native PointerEvent screenX/screenY.
1100
- */
1101
- this.screen = new Point();
1102
- }
1103
- /** @readonly */
1104
- get clientX() {
1105
- return this.client.x;
1106
- }
1107
- /** @readonly */
1108
- get clientY() {
1109
- return this.client.y;
1110
- }
1111
- /**
1112
- * Alias for {@link FederatedMouseEvent.clientX this.clientX}.
1113
- * @readonly
1114
- */
1115
- get x() {
1116
- return this.clientX;
1117
- }
1118
- /**
1119
- * Alias for {@link FederatedMouseEvent.clientY this.clientY}.
1120
- * @readonly
1121
- */
1122
- get y() {
1123
- return this.clientY;
1124
- }
1125
- /** @readonly */
1126
- get movementX() {
1127
- return this.movement.x;
1128
- }
1129
- /** @readonly */
1130
- get movementY() {
1131
- return this.movement.y;
1132
- }
1133
- /** @readonly */
1134
- get offsetX() {
1135
- return this.offset.x;
1136
- }
1137
- /** @readonly */
1138
- get offsetY() {
1139
- return this.offset.y;
1140
- }
1141
- /** @readonly */
1142
- get globalX() {
1143
- return this.global.x;
1144
- }
1145
- /** @readonly */
1146
- get globalY() {
1147
- return this.global.y;
1148
- }
1149
- /**
1150
- * The pointer coordinates in the renderer's screen. Alias for `screen.x`.
1151
- * @readonly
1152
- */
1153
- get screenX() {
1154
- return this.screen.x;
1155
- }
1156
- /**
1157
- * The pointer coordinates in the renderer's screen. Alias for `screen.y`.
1158
- * @readonly
1159
- */
1160
- get screenY() {
1161
- return this.screen.y;
1162
- }
1163
- /**
1164
- * Converts global coordinates into container-local coordinates.
1165
- *
1166
- * This method transforms coordinates from world space to a container's local space,
1167
- * useful for precise positioning and hit testing.
1168
- * @param container - The Container to get local coordinates for
1169
- * @param point - Optional Point object to store the result. If not provided, a new Point will be created
1170
- * @param globalPos - Optional custom global coordinates. If not provided, the event's global position is used
1171
- * @returns The local coordinates as a Point object
1172
- * @example
1173
- * ```ts
1174
- * // Basic usage - get local coordinates relative to a container
1175
- * sprite.on('pointermove', (event: FederatedMouseEvent) => {
1176
- * // Get position relative to the sprite
1177
- * const localPos = event.getLocalPosition(sprite);
1178
- * console.log('Local position:', localPos.x, localPos.y);
1179
- * });
1180
- * // Using custom global coordinates
1181
- * const customGlobal = new Point(100, 100);
1182
- * sprite.on('pointermove', (event: FederatedMouseEvent) => {
1183
- * // Transform custom coordinates
1184
- * const localPos = event.getLocalPosition(sprite, undefined, customGlobal);
1185
- * console.log('Custom local position:', localPos.x, localPos.y);
1186
- * });
1187
- * ```
1188
- * @see {@link Container.worldTransform} For the transformation matrix
1189
- * @see {@link Point} For the point class used to store coordinates
1190
- */
1191
- getLocalPosition(container, point, globalPos) {
1192
- return container.worldTransform.applyInverse(globalPos || this.global, point);
1193
- }
1194
- /**
1195
- * Whether the modifier key was pressed when this event natively occurred.
1196
- * @param key - The modifier key.
1197
- */
1198
- getModifierState(key) {
1199
- return "getModifierState" in this.nativeEvent && this.nativeEvent.getModifierState(key);
1200
- }
1201
- /**
1202
- * Not supported.
1203
- * @param _typeArg
1204
- * @param _canBubbleArg
1205
- * @param _cancelableArg
1206
- * @param _viewArg
1207
- * @param _detailArg
1208
- * @param _screenXArg
1209
- * @param _screenYArg
1210
- * @param _clientXArg
1211
- * @param _clientYArg
1212
- * @param _ctrlKeyArg
1213
- * @param _altKeyArg
1214
- * @param _shiftKeyArg
1215
- * @param _metaKeyArg
1216
- * @param _buttonArg
1217
- * @param _relatedTargetArg
1218
- * @deprecated since 7.0.0
1219
- * @ignore
1220
- */
1221
- // eslint-disable-next-line max-params
1222
- initMouseEvent(_typeArg, _canBubbleArg, _cancelableArg, _viewArg, _detailArg, _screenXArg, _screenYArg, _clientXArg, _clientYArg, _ctrlKeyArg, _altKeyArg, _shiftKeyArg, _metaKeyArg, _buttonArg, _relatedTargetArg) {
1223
- throw new Error("Method not implemented.");
1224
- }
1225
- }
1226
-
1227
- class FederatedPointerEvent extends FederatedMouseEvent {
1228
- constructor() {
1229
- super(...arguments);
1230
- /**
1231
- * The width of the pointer's contact along the x-axis, measured in CSS pixels.
1232
- * radiusX of TouchEvents will be represented by this value.
1233
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width
1234
- */
1235
- this.width = 0;
1236
- /**
1237
- * The height of the pointer's contact along the y-axis, measured in CSS pixels.
1238
- * radiusY of TouchEvents will be represented by this value.
1239
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height
1240
- */
1241
- this.height = 0;
1242
- /**
1243
- * Indicates whether or not the pointer device that created the event is the primary pointer.
1244
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary
1245
- */
1246
- this.isPrimary = false;
1247
- }
1248
- /**
1249
- * Only included for completeness for now
1250
- * @ignore
1251
- */
1252
- getCoalescedEvents() {
1253
- if (this.type === "pointermove" || this.type === "mousemove" || this.type === "touchmove") {
1254
- return [this];
1255
- }
1256
- return [];
1257
- }
1258
- /**
1259
- * Only included for completeness for now
1260
- * @ignore
1261
- */
1262
- getPredictedEvents() {
1263
- throw new Error("getPredictedEvents is not supported!");
1264
- }
1265
- }
1266
-
1267
- class FederatedWheelEvent extends FederatedMouseEvent {
1268
- constructor() {
1269
- super(...arguments);
1270
- /**
1271
- * Units specified in pixels.
1272
- * @ignore
1273
- */
1274
- this.DOM_DELTA_PIXEL = 0;
1275
- /**
1276
- * Units specified in lines.
1277
- * @ignore
1278
- */
1279
- this.DOM_DELTA_LINE = 1;
1280
- /**
1281
- * Units specified in pages.
1282
- * @ignore
1283
- */
1284
- this.DOM_DELTA_PAGE = 2;
1285
- }
1286
- }
1287
- /**
1288
- * Units specified in pixels.
1289
- * @ignore
1290
- */
1291
- FederatedWheelEvent.DOM_DELTA_PIXEL = 0;
1292
- /**
1293
- * Units specified in lines.
1294
- * @ignore
1295
- */
1296
- FederatedWheelEvent.DOM_DELTA_LINE = 1;
1297
- /**
1298
- * Units specified in pages.
1299
- * @ignore
1300
- */
1301
- FederatedWheelEvent.DOM_DELTA_PAGE = 2;
1302
-
1303
- const PROPAGATION_LIMIT = 2048;
1304
- const tempHitLocation = new Point();
1305
- const tempLocalMapping = new Point();
1306
- class EventBoundary {
1307
- /**
1308
- * @param rootTarget - The holder of the event boundary.
1309
- */
1310
- constructor(rootTarget) {
1311
- /**
1312
- * Emits events after they were dispatched into the scene graph.
1313
- *
1314
- * This can be used for global events listening, regardless of the scene graph being used. It should
1315
- * not be used by interactive libraries for normal use.
1316
- *
1317
- * Special events that do not bubble all the way to the root target are not emitted from here,
1318
- * e.g. pointerenter, pointerleave, click.
1319
- */
1320
- this.dispatch = new EventEmitter();
1321
- /**
1322
- * This flag would emit `pointermove`, `touchmove`, and `mousemove` events on all Containers.
1323
- *
1324
- * The `moveOnAll` semantics mirror those of earlier versions of PixiJS. This was disabled in favor of
1325
- * the Pointer Event API's approach.
1326
- */
1327
- this.moveOnAll = false;
1328
- /** Enables the global move events. `globalpointermove`, `globaltouchmove`, and `globalmousemove` */
1329
- this.enableGlobalMoveEvents = true;
1330
- /**
1331
- * State object for mapping methods.
1332
- * @see EventBoundary#trackingData
1333
- */
1334
- this.mappingState = {
1335
- trackingData: {}
1336
- };
1337
- /**
1338
- * The event pool maps event constructors to an free pool of instances of those specific events.
1339
- * @see EventBoundary#allocateEvent
1340
- * @see EventBoundary#freeEvent
1341
- */
1342
- this.eventPool = /* @__PURE__ */ new Map();
1343
- /** Every interactive element gathered from the scene. Only used in `pointermove` */
1344
- this._allInteractiveElements = [];
1345
- /** Every element that passed the hit test. Only used in `pointermove` */
1346
- this._hitElements = [];
1347
- /** Whether or not to collect all the interactive elements from the scene. Enabled in `pointermove` */
1348
- this._isPointerMoveEvent = false;
1349
- this.rootTarget = rootTarget;
1350
- this.hitPruneFn = this.hitPruneFn.bind(this);
1351
- this.hitTestFn = this.hitTestFn.bind(this);
1352
- this.mapPointerDown = this.mapPointerDown.bind(this);
1353
- this.mapPointerMove = this.mapPointerMove.bind(this);
1354
- this.mapPointerOut = this.mapPointerOut.bind(this);
1355
- this.mapPointerOver = this.mapPointerOver.bind(this);
1356
- this.mapPointerUp = this.mapPointerUp.bind(this);
1357
- this.mapPointerUpOutside = this.mapPointerUpOutside.bind(this);
1358
- this.mapWheel = this.mapWheel.bind(this);
1359
- this.mappingTable = {};
1360
- this.addEventMapping("pointerdown", this.mapPointerDown);
1361
- this.addEventMapping("pointermove", this.mapPointerMove);
1362
- this.addEventMapping("pointerout", this.mapPointerOut);
1363
- this.addEventMapping("pointerleave", this.mapPointerOut);
1364
- this.addEventMapping("pointerover", this.mapPointerOver);
1365
- this.addEventMapping("pointerup", this.mapPointerUp);
1366
- this.addEventMapping("pointerupoutside", this.mapPointerUpOutside);
1367
- this.addEventMapping("wheel", this.mapWheel);
1368
- }
1369
- /**
1370
- * Adds an event mapping for the event `type` handled by `fn`.
1371
- *
1372
- * Event mappings can be used to implement additional or custom events. They take an event
1373
- * coming from the upstream scene (or directly from the {@link EventSystem}) and dispatch new downstream events
1374
- * generally trickling down and bubbling up to {@link EventBoundary.rootTarget this.rootTarget}.
1375
- *
1376
- * To modify the semantics of existing events, the built-in mapping methods of EventBoundary should be overridden
1377
- * instead.
1378
- * @param type - The type of upstream event to map.
1379
- * @param fn - The mapping method. The context of this function must be bound manually, if desired.
1380
- */
1381
- addEventMapping(type, fn) {
1382
- if (!this.mappingTable[type]) {
1383
- this.mappingTable[type] = [];
1384
- }
1385
- this.mappingTable[type].push({
1386
- fn,
1387
- priority: 0
1388
- });
1389
- this.mappingTable[type].sort((a, b) => a.priority - b.priority);
1390
- }
1391
- /**
1392
- * Dispatches the given event
1393
- * @param e - The event to dispatch.
1394
- * @param type - The type of event to dispatch. Defaults to `e.type`.
1395
- */
1396
- dispatchEvent(e, type) {
1397
- e.propagationStopped = false;
1398
- e.propagationImmediatelyStopped = false;
1399
- this.propagate(e, type);
1400
- this.dispatch.emit(type || e.type, e);
1401
- }
1402
- /**
1403
- * Maps the given upstream event through the event boundary and propagates it downstream.
1404
- * @param e - The event to map.
1405
- */
1406
- mapEvent(e) {
1407
- if (!this.rootTarget) {
1408
- return;
1409
- }
1410
- const mappers = this.mappingTable[e.type];
1411
- if (mappers) {
1412
- for (let i = 0, j = mappers.length; i < j; i++) {
1413
- mappers[i].fn(e);
1414
- }
1415
- } else {
1416
- warn(`[EventBoundary]: Event mapping not defined for ${e.type}`);
1417
- }
1418
- }
1419
- /**
1420
- * Finds the Container that is the target of a event at the given coordinates.
1421
- *
1422
- * The passed (x,y) coordinates are in the world space above this event boundary.
1423
- * @param x - The x coordinate of the event.
1424
- * @param y - The y coordinate of the event.
1425
- */
1426
- hitTest(x, y) {
1427
- EventsTicker.pauseUpdate = true;
1428
- const useMove = this._isPointerMoveEvent && this.enableGlobalMoveEvents;
1429
- const fn = useMove ? "hitTestMoveRecursive" : "hitTestRecursive";
1430
- const invertedPath = this[fn](
1431
- this.rootTarget,
1432
- this.rootTarget.eventMode,
1433
- tempHitLocation.set(x, y),
1434
- this.hitTestFn,
1435
- this.hitPruneFn
1436
- );
1437
- return invertedPath && invertedPath[0];
1438
- }
1439
- /**
1440
- * Propagate the passed event from from {@link EventBoundary.rootTarget this.rootTarget} to its
1441
- * target `e.target`.
1442
- * @param e - The event to propagate.
1443
- * @param type - The type of event to propagate. Defaults to `e.type`.
1444
- */
1445
- propagate(e, type) {
1446
- if (!e.target) {
1447
- return;
1448
- }
1449
- const composedPath = e.composedPath();
1450
- e.eventPhase = e.CAPTURING_PHASE;
1451
- for (let i = 0, j = composedPath.length - 1; i < j; i++) {
1452
- e.currentTarget = composedPath[i];
1453
- this.notifyTarget(e, type);
1454
- if (e.propagationStopped || e.propagationImmediatelyStopped)
1455
- return;
1456
- }
1457
- e.eventPhase = e.AT_TARGET;
1458
- e.currentTarget = e.target;
1459
- this.notifyTarget(e, type);
1460
- if (e.propagationStopped || e.propagationImmediatelyStopped)
1461
- return;
1462
- e.eventPhase = e.BUBBLING_PHASE;
1463
- for (let i = composedPath.length - 2; i >= 0; i--) {
1464
- e.currentTarget = composedPath[i];
1465
- this.notifyTarget(e, type);
1466
- if (e.propagationStopped || e.propagationImmediatelyStopped)
1467
- return;
1468
- }
1469
- }
1470
- /**
1471
- * Emits the event `e` to all interactive containers. The event is propagated in the bubbling phase always.
1472
- *
1473
- * This is used in the `globalpointermove` event.
1474
- * @param e - The emitted event.
1475
- * @param type - The listeners to notify.
1476
- * @param targets - The targets to notify.
1477
- */
1478
- all(e, type, targets = this._allInteractiveElements) {
1479
- if (targets.length === 0)
1480
- return;
1481
- e.eventPhase = e.BUBBLING_PHASE;
1482
- const events = Array.isArray(type) ? type : [type];
1483
- for (let i = targets.length - 1; i >= 0; i--) {
1484
- events.forEach((event) => {
1485
- e.currentTarget = targets[i];
1486
- this.notifyTarget(e, event);
1487
- });
1488
- }
1489
- }
1490
- /**
1491
- * Finds the propagation path from {@link EventBoundary.rootTarget rootTarget} to the passed
1492
- * `target`. The last element in the path is `target`.
1493
- * @param target - The target to find the propagation path to.
1494
- */
1495
- propagationPath(target) {
1496
- const propagationPath = [target];
1497
- for (let i = 0; i < PROPAGATION_LIMIT && (target !== this.rootTarget && target.parent); i++) {
1498
- if (!target.parent) {
1499
- throw new Error("Cannot find propagation path to disconnected target");
1500
- }
1501
- propagationPath.push(target.parent);
1502
- target = target.parent;
1503
- }
1504
- propagationPath.reverse();
1505
- return propagationPath;
1506
- }
1507
- hitTestMoveRecursive(currentTarget, eventMode, location, testFn, pruneFn, ignore = false) {
1508
- let shouldReturn = false;
1509
- if (this._interactivePrune(currentTarget))
1510
- return null;
1511
- if (currentTarget.eventMode === "dynamic" || eventMode === "dynamic") {
1512
- EventsTicker.pauseUpdate = false;
1513
- }
1514
- if (currentTarget.interactiveChildren && currentTarget.children) {
1515
- const children = currentTarget.children;
1516
- for (let i = children.length - 1; i >= 0; i--) {
1517
- const child = children[i];
1518
- const nestedHit = this.hitTestMoveRecursive(
1519
- child,
1520
- this._isInteractive(eventMode) ? eventMode : child.eventMode,
1521
- location,
1522
- testFn,
1523
- pruneFn,
1524
- ignore || pruneFn(currentTarget, location)
1525
- );
1526
- if (nestedHit) {
1527
- if (nestedHit.length > 0 && !nestedHit[nestedHit.length - 1].parent) {
1528
- continue;
1529
- }
1530
- const isInteractive = currentTarget.isInteractive();
1531
- if (nestedHit.length > 0 || isInteractive) {
1532
- if (isInteractive)
1533
- this._allInteractiveElements.push(currentTarget);
1534
- nestedHit.push(currentTarget);
1535
- }
1536
- if (this._hitElements.length === 0)
1537
- this._hitElements = nestedHit;
1538
- shouldReturn = true;
1539
- }
1540
- }
1541
- }
1542
- const isInteractiveMode = this._isInteractive(eventMode);
1543
- const isInteractiveTarget = currentTarget.isInteractive();
1544
- if (isInteractiveTarget && isInteractiveTarget)
1545
- this._allInteractiveElements.push(currentTarget);
1546
- if (ignore || this._hitElements.length > 0)
1547
- return null;
1548
- if (shouldReturn)
1549
- return this._hitElements;
1550
- if (isInteractiveMode && (!pruneFn(currentTarget, location) && testFn(currentTarget, location))) {
1551
- return isInteractiveTarget ? [currentTarget] : [];
1552
- }
1553
- return null;
1554
- }
1555
- /**
1556
- * Recursive implementation for {@link EventBoundary.hitTest hitTest}.
1557
- * @param currentTarget - The Container that is to be hit tested.
1558
- * @param eventMode - The event mode for the `currentTarget` or one of its parents.
1559
- * @param location - The location that is being tested for overlap.
1560
- * @param testFn - Callback that determines whether the target passes hit testing. This callback
1561
- * can assume that `pruneFn` failed to prune the container.
1562
- * @param pruneFn - Callback that determiness whether the target and all of its children
1563
- * cannot pass the hit test. It is used as a preliminary optimization to prune entire subtrees
1564
- * of the scene graph.
1565
- * @returns An array holding the hit testing target and all its ancestors in order. The first element
1566
- * is the target itself and the last is {@link EventBoundary.rootTarget rootTarget}. This is the opposite
1567
- * order w.r.t. the propagation path. If no hit testing target is found, null is returned.
1568
- */
1569
- hitTestRecursive(currentTarget, eventMode, location, testFn, pruneFn) {
1570
- if (this._interactivePrune(currentTarget) || pruneFn(currentTarget, location)) {
1571
- return null;
1572
- }
1573
- if (currentTarget.eventMode === "dynamic" || eventMode === "dynamic") {
1574
- EventsTicker.pauseUpdate = false;
1575
- }
1576
- if (currentTarget.interactiveChildren && currentTarget.children) {
1577
- const children = currentTarget.children;
1578
- const relativeLocation = location;
1579
- for (let i = children.length - 1; i >= 0; i--) {
1580
- const child = children[i];
1581
- const nestedHit = this.hitTestRecursive(
1582
- child,
1583
- this._isInteractive(eventMode) ? eventMode : child.eventMode,
1584
- relativeLocation,
1585
- testFn,
1586
- pruneFn
1587
- );
1588
- if (nestedHit) {
1589
- if (nestedHit.length > 0 && !nestedHit[nestedHit.length - 1].parent) {
1590
- continue;
1591
- }
1592
- const isInteractive = currentTarget.isInteractive();
1593
- if (nestedHit.length > 0 || isInteractive)
1594
- nestedHit.push(currentTarget);
1595
- return nestedHit;
1596
- }
1597
- }
1598
- }
1599
- const isInteractiveMode = this._isInteractive(eventMode);
1600
- const isInteractiveTarget = currentTarget.isInteractive();
1601
- if (isInteractiveMode && testFn(currentTarget, location)) {
1602
- return isInteractiveTarget ? [currentTarget] : [];
1603
- }
1604
- return null;
1605
- }
1606
- _isInteractive(int) {
1607
- return int === "static" || int === "dynamic";
1608
- }
1609
- _interactivePrune(container) {
1610
- if (!container || !container.visible || !container.renderable || !container.measurable) {
1611
- return true;
1612
- }
1613
- if (container.eventMode === "none") {
1614
- return true;
1615
- }
1616
- if (container.eventMode === "passive" && !container.interactiveChildren) {
1617
- return true;
1618
- }
1619
- return false;
1620
- }
1621
- /**
1622
- * Checks whether the container or any of its children cannot pass the hit test at all.
1623
- *
1624
- * {@link EventBoundary}'s implementation uses the {@link Container.hitArea hitArea}
1625
- * and {@link Container._maskEffect} for pruning.
1626
- * @param container - The container to prune.
1627
- * @param location - The location to test for overlap.
1628
- */
1629
- hitPruneFn(container, location) {
1630
- if (container.hitArea) {
1631
- container.worldTransform.applyInverse(location, tempLocalMapping);
1632
- if (!container.hitArea.contains(tempLocalMapping.x, tempLocalMapping.y)) {
1633
- return true;
1634
- }
1635
- }
1636
- if (container.effects && container.effects.length) {
1637
- for (let i = 0; i < container.effects.length; i++) {
1638
- const effect = container.effects[i];
1639
- if (effect.containsPoint) {
1640
- const effectContainsPoint = effect.containsPoint(location, this.hitTestFn);
1641
- if (!effectContainsPoint) {
1642
- return true;
1643
- }
1644
- }
1645
- }
1646
- }
1647
- return false;
1648
- }
1649
- /**
1650
- * Checks whether the container passes hit testing for the given location.
1651
- * @param container - The container to test.
1652
- * @param location - The location to test for overlap.
1653
- * @returns - Whether `container` passes hit testing for `location`.
1654
- */
1655
- hitTestFn(container, location) {
1656
- if (container.hitArea) {
1657
- return true;
1658
- }
1659
- if (container?.containsPoint) {
1660
- container.worldTransform.applyInverse(location, tempLocalMapping);
1661
- return container.containsPoint(tempLocalMapping);
1662
- }
1663
- return false;
1664
- }
1665
- /**
1666
- * Notify all the listeners to the event's `currentTarget`.
1667
- *
1668
- * If the `currentTarget` contains the property `on<type>`, then it is called here,
1669
- * simulating the behavior from version 6.x and prior.
1670
- * @param e - The event passed to the target.
1671
- * @param type - The type of event to notify. Defaults to `e.type`.
1672
- */
1673
- notifyTarget(e, type) {
1674
- if (!e.currentTarget.isInteractive()) {
1675
- return;
1676
- }
1677
- type ?? (type = e.type);
1678
- const handlerKey = `on${type}`;
1679
- e.currentTarget[handlerKey]?.(e);
1680
- const key = e.eventPhase === e.CAPTURING_PHASE || e.eventPhase === e.AT_TARGET ? `${type}capture` : type;
1681
- this._notifyListeners(e, key);
1682
- if (e.eventPhase === e.AT_TARGET) {
1683
- this._notifyListeners(e, type);
1684
- }
1685
- }
1686
- /**
1687
- * Maps the upstream `pointerdown` events to a downstream `pointerdown` event.
1688
- *
1689
- * `touchstart`, `rightdown`, `mousedown` events are also dispatched for specific pointer types.
1690
- * @param from - The upstream `pointerdown` event.
1691
- */
1692
- mapPointerDown(from) {
1693
- if (!(from instanceof FederatedPointerEvent)) {
1694
- warn("EventBoundary cannot map a non-pointer event as a pointer event");
1695
- return;
1696
- }
1697
- const e = this.createPointerEvent(from);
1698
- this.dispatchEvent(e, "pointerdown");
1699
- if (e.pointerType === "touch") {
1700
- this.dispatchEvent(e, "touchstart");
1701
- } else if (e.pointerType === "mouse" || e.pointerType === "pen") {
1702
- const isRightButton = e.button === 2;
1703
- this.dispatchEvent(e, isRightButton ? "rightdown" : "mousedown");
1704
- }
1705
- const trackingData = this.trackingData(from.pointerId);
1706
- trackingData.pressTargetsByButton[from.button] = e.composedPath();
1707
- this.freeEvent(e);
1708
- }
1709
- /**
1710
- * Maps the upstream `pointermove` to downstream `pointerout`, `pointerover`, and `pointermove` events, in that order.
1711
- *
1712
- * The tracking data for the specific pointer has an updated `overTarget`. `mouseout`, `mouseover`,
1713
- * `mousemove`, and `touchmove` events are fired as well for specific pointer types.
1714
- * @param from - The upstream `pointermove` event.
1715
- */
1716
- mapPointerMove(from) {
1717
- if (!(from instanceof FederatedPointerEvent)) {
1718
- warn("EventBoundary cannot map a non-pointer event as a pointer event");
1719
- return;
1720
- }
1721
- this._allInteractiveElements.length = 0;
1722
- this._hitElements.length = 0;
1723
- this._isPointerMoveEvent = true;
1724
- const e = this.createPointerEvent(from);
1725
- this._isPointerMoveEvent = false;
1726
- const isMouse = e.pointerType === "mouse" || e.pointerType === "pen";
1727
- const trackingData = this.trackingData(from.pointerId);
1728
- const outTarget = this.findMountedTarget(trackingData.overTargets);
1729
- if (trackingData.overTargets?.length > 0 && outTarget !== e.target) {
1730
- const outType = from.type === "mousemove" ? "mouseout" : "pointerout";
1731
- const outEvent = this.createPointerEvent(from, outType, outTarget);
1732
- this.dispatchEvent(outEvent, "pointerout");
1733
- if (isMouse)
1734
- this.dispatchEvent(outEvent, "mouseout");
1735
- if (!e.composedPath().includes(outTarget)) {
1736
- const leaveEvent = this.createPointerEvent(from, "pointerleave", outTarget);
1737
- leaveEvent.eventPhase = leaveEvent.AT_TARGET;
1738
- while (leaveEvent.target && !e.composedPath().includes(leaveEvent.target)) {
1739
- leaveEvent.currentTarget = leaveEvent.target;
1740
- this.notifyTarget(leaveEvent);
1741
- if (isMouse)
1742
- this.notifyTarget(leaveEvent, "mouseleave");
1743
- leaveEvent.target = leaveEvent.target.parent;
1744
- }
1745
- this.freeEvent(leaveEvent);
1746
- }
1747
- this.freeEvent(outEvent);
1748
- }
1749
- if (outTarget !== e.target) {
1750
- const overType = from.type === "mousemove" ? "mouseover" : "pointerover";
1751
- const overEvent = this.clonePointerEvent(e, overType);
1752
- this.dispatchEvent(overEvent, "pointerover");
1753
- if (isMouse)
1754
- this.dispatchEvent(overEvent, "mouseover");
1755
- let overTargetAncestor = outTarget?.parent;
1756
- while (overTargetAncestor && overTargetAncestor !== this.rootTarget.parent) {
1757
- if (overTargetAncestor === e.target)
1758
- break;
1759
- overTargetAncestor = overTargetAncestor.parent;
1760
- }
1761
- const didPointerEnter = !overTargetAncestor || overTargetAncestor === this.rootTarget.parent;
1762
- if (didPointerEnter) {
1763
- const enterEvent = this.clonePointerEvent(e, "pointerenter");
1764
- enterEvent.eventPhase = enterEvent.AT_TARGET;
1765
- while (enterEvent.target && enterEvent.target !== outTarget && enterEvent.target !== this.rootTarget.parent) {
1766
- enterEvent.currentTarget = enterEvent.target;
1767
- this.notifyTarget(enterEvent);
1768
- if (isMouse)
1769
- this.notifyTarget(enterEvent, "mouseenter");
1770
- enterEvent.target = enterEvent.target.parent;
1771
- }
1772
- this.freeEvent(enterEvent);
1773
- }
1774
- this.freeEvent(overEvent);
1775
- }
1776
- const allMethods = [];
1777
- const allowGlobalPointerEvents = this.enableGlobalMoveEvents ?? true;
1778
- this.moveOnAll ? allMethods.push("pointermove") : this.dispatchEvent(e, "pointermove");
1779
- allowGlobalPointerEvents && allMethods.push("globalpointermove");
1780
- if (e.pointerType === "touch") {
1781
- this.moveOnAll ? allMethods.splice(1, 0, "touchmove") : this.dispatchEvent(e, "touchmove");
1782
- allowGlobalPointerEvents && allMethods.push("globaltouchmove");
1783
- }
1784
- if (isMouse) {
1785
- this.moveOnAll ? allMethods.splice(1, 0, "mousemove") : this.dispatchEvent(e, "mousemove");
1786
- allowGlobalPointerEvents && allMethods.push("globalmousemove");
1787
- this.cursor = e.target?.cursor;
1788
- }
1789
- if (allMethods.length > 0) {
1790
- this.all(e, allMethods);
1791
- }
1792
- this._allInteractiveElements.length = 0;
1793
- this._hitElements.length = 0;
1794
- trackingData.overTargets = e.composedPath();
1795
- this.freeEvent(e);
1796
- }
1797
- /**
1798
- * Maps the upstream `pointerover` to downstream `pointerover` and `pointerenter` events, in that order.
1799
- *
1800
- * The tracking data for the specific pointer gets a new `overTarget`.
1801
- * @param from - The upstream `pointerover` event.
1802
- */
1803
- mapPointerOver(from) {
1804
- if (!(from instanceof FederatedPointerEvent)) {
1805
- warn("EventBoundary cannot map a non-pointer event as a pointer event");
1806
- return;
1807
- }
1808
- const trackingData = this.trackingData(from.pointerId);
1809
- const e = this.createPointerEvent(from);
1810
- const isMouse = e.pointerType === "mouse" || e.pointerType === "pen";
1811
- this.dispatchEvent(e, "pointerover");
1812
- if (isMouse)
1813
- this.dispatchEvent(e, "mouseover");
1814
- if (e.pointerType === "mouse")
1815
- this.cursor = e.target?.cursor;
1816
- const enterEvent = this.clonePointerEvent(e, "pointerenter");
1817
- enterEvent.eventPhase = enterEvent.AT_TARGET;
1818
- while (enterEvent.target && enterEvent.target !== this.rootTarget.parent) {
1819
- enterEvent.currentTarget = enterEvent.target;
1820
- this.notifyTarget(enterEvent);
1821
- if (isMouse)
1822
- this.notifyTarget(enterEvent, "mouseenter");
1823
- enterEvent.target = enterEvent.target.parent;
1824
- }
1825
- trackingData.overTargets = e.composedPath();
1826
- this.freeEvent(e);
1827
- this.freeEvent(enterEvent);
1828
- }
1829
- /**
1830
- * Maps the upstream `pointerout` to downstream `pointerout`, `pointerleave` events, in that order.
1831
- *
1832
- * The tracking data for the specific pointer is cleared of a `overTarget`.
1833
- * @param from - The upstream `pointerout` event.
1834
- */
1835
- mapPointerOut(from) {
1836
- if (!(from instanceof FederatedPointerEvent)) {
1837
- warn("EventBoundary cannot map a non-pointer event as a pointer event");
1838
- return;
1839
- }
1840
- const trackingData = this.trackingData(from.pointerId);
1841
- if (trackingData.overTargets) {
1842
- const isMouse = from.pointerType === "mouse" || from.pointerType === "pen";
1843
- const outTarget = this.findMountedTarget(trackingData.overTargets);
1844
- const outEvent = this.createPointerEvent(from, "pointerout", outTarget);
1845
- this.dispatchEvent(outEvent);
1846
- if (isMouse)
1847
- this.dispatchEvent(outEvent, "mouseout");
1848
- const leaveEvent = this.createPointerEvent(from, "pointerleave", outTarget);
1849
- leaveEvent.eventPhase = leaveEvent.AT_TARGET;
1850
- while (leaveEvent.target && leaveEvent.target !== this.rootTarget.parent) {
1851
- leaveEvent.currentTarget = leaveEvent.target;
1852
- this.notifyTarget(leaveEvent);
1853
- if (isMouse)
1854
- this.notifyTarget(leaveEvent, "mouseleave");
1855
- leaveEvent.target = leaveEvent.target.parent;
1856
- }
1857
- trackingData.overTargets = null;
1858
- this.freeEvent(outEvent);
1859
- this.freeEvent(leaveEvent);
1860
- }
1861
- this.cursor = null;
1862
- }
1863
- /**
1864
- * Maps the upstream `pointerup` event to downstream `pointerup`, `pointerupoutside`,
1865
- * and `click`/`rightclick`/`pointertap` events, in that order.
1866
- *
1867
- * The `pointerupoutside` event bubbles from the original `pointerdown` target to the most specific
1868
- * ancestor of the `pointerdown` and `pointerup` targets, which is also the `click` event's target. `touchend`,
1869
- * `rightup`, `mouseup`, `touchendoutside`, `rightupoutside`, `mouseupoutside`, and `tap` are fired as well for
1870
- * specific pointer types.
1871
- * @param from - The upstream `pointerup` event.
1872
- */
1873
- mapPointerUp(from) {
1874
- if (!(from instanceof FederatedPointerEvent)) {
1875
- warn("EventBoundary cannot map a non-pointer event as a pointer event");
1876
- return;
1877
- }
1878
- const now = performance.now();
1879
- const e = this.createPointerEvent(from);
1880
- this.dispatchEvent(e, "pointerup");
1881
- if (e.pointerType === "touch") {
1882
- this.dispatchEvent(e, "touchend");
1883
- } else if (e.pointerType === "mouse" || e.pointerType === "pen") {
1884
- const isRightButton = e.button === 2;
1885
- this.dispatchEvent(e, isRightButton ? "rightup" : "mouseup");
1886
- }
1887
- const trackingData = this.trackingData(from.pointerId);
1888
- const pressTarget = this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
1889
- let clickTarget = pressTarget;
1890
- if (pressTarget && !e.composedPath().includes(pressTarget)) {
1891
- let currentTarget = pressTarget;
1892
- while (currentTarget && !e.composedPath().includes(currentTarget)) {
1893
- e.currentTarget = currentTarget;
1894
- this.notifyTarget(e, "pointerupoutside");
1895
- if (e.pointerType === "touch") {
1896
- this.notifyTarget(e, "touchendoutside");
1897
- } else if (e.pointerType === "mouse" || e.pointerType === "pen") {
1898
- const isRightButton = e.button === 2;
1899
- this.notifyTarget(e, isRightButton ? "rightupoutside" : "mouseupoutside");
1900
- }
1901
- currentTarget = currentTarget.parent;
1902
- }
1903
- delete trackingData.pressTargetsByButton[from.button];
1904
- clickTarget = currentTarget;
1905
- }
1906
- if (clickTarget) {
1907
- const clickEvent = this.clonePointerEvent(e, "click");
1908
- clickEvent.target = clickTarget;
1909
- clickEvent.path = null;
1910
- if (!trackingData.clicksByButton[from.button]) {
1911
- trackingData.clicksByButton[from.button] = {
1912
- clickCount: 0,
1913
- target: clickEvent.target,
1914
- timeStamp: now
1915
- };
1916
- }
1917
- const clickHistory = trackingData.clicksByButton[from.button];
1918
- if (clickHistory.target === clickEvent.target && now - clickHistory.timeStamp < 200) {
1919
- ++clickHistory.clickCount;
1920
- } else {
1921
- clickHistory.clickCount = 1;
1922
- }
1923
- clickHistory.target = clickEvent.target;
1924
- clickHistory.timeStamp = now;
1925
- clickEvent.detail = clickHistory.clickCount;
1926
- if (clickEvent.pointerType === "mouse") {
1927
- const isRightButton = clickEvent.button === 2;
1928
- this.dispatchEvent(clickEvent, isRightButton ? "rightclick" : "click");
1929
- } else if (clickEvent.pointerType === "touch") {
1930
- this.dispatchEvent(clickEvent, "tap");
1931
- }
1932
- this.dispatchEvent(clickEvent, "pointertap");
1933
- this.freeEvent(clickEvent);
1934
- }
1935
- this.freeEvent(e);
1936
- }
1937
- /**
1938
- * Maps the upstream `pointerupoutside` event to a downstream `pointerupoutside` event, bubbling from the original
1939
- * `pointerdown` target to `rootTarget`.
1940
- *
1941
- * (The most specific ancestor of the `pointerdown` event and the `pointerup` event must the
1942
- * `{@link EventBoundary}'s root because the `pointerup` event occurred outside of the boundary.)
1943
- *
1944
- * `touchendoutside`, `mouseupoutside`, and `rightupoutside` events are fired as well for specific pointer
1945
- * types. The tracking data for the specific pointer is cleared of a `pressTarget`.
1946
- * @param from - The upstream `pointerupoutside` event.
1947
- */
1948
- mapPointerUpOutside(from) {
1949
- if (!(from instanceof FederatedPointerEvent)) {
1950
- warn("EventBoundary cannot map a non-pointer event as a pointer event");
1951
- return;
1952
- }
1953
- const trackingData = this.trackingData(from.pointerId);
1954
- const pressTarget = this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
1955
- const e = this.createPointerEvent(from);
1956
- if (pressTarget) {
1957
- let currentTarget = pressTarget;
1958
- while (currentTarget) {
1959
- e.currentTarget = currentTarget;
1960
- this.notifyTarget(e, "pointerupoutside");
1961
- if (e.pointerType === "touch") {
1962
- this.notifyTarget(e, "touchendoutside");
1963
- } else if (e.pointerType === "mouse" || e.pointerType === "pen") {
1964
- this.notifyTarget(e, e.button === 2 ? "rightupoutside" : "mouseupoutside");
1965
- }
1966
- currentTarget = currentTarget.parent;
1967
- }
1968
- delete trackingData.pressTargetsByButton[from.button];
1969
- }
1970
- this.freeEvent(e);
1971
- }
1972
- /**
1973
- * Maps the upstream `wheel` event to a downstream `wheel` event.
1974
- * @param from - The upstream `wheel` event.
1975
- */
1976
- mapWheel(from) {
1977
- if (!(from instanceof FederatedWheelEvent)) {
1978
- warn("EventBoundary cannot map a non-wheel event as a wheel event");
1979
- return;
1980
- }
1981
- const wheelEvent = this.createWheelEvent(from);
1982
- this.dispatchEvent(wheelEvent);
1983
- this.freeEvent(wheelEvent);
1984
- }
1985
- /**
1986
- * Finds the most specific event-target in the given propagation path that is still mounted in the scene graph.
1987
- *
1988
- * This is used to find the correct `pointerup` and `pointerout` target in the case that the original `pointerdown`
1989
- * or `pointerover` target was unmounted from the scene graph.
1990
- * @param propagationPath - The propagation path was valid in the past.
1991
- * @returns - The most specific event-target still mounted at the same location in the scene graph.
1992
- */
1993
- findMountedTarget(propagationPath) {
1994
- if (!propagationPath) {
1995
- return null;
1996
- }
1997
- let currentTarget = propagationPath[0];
1998
- for (let i = 1; i < propagationPath.length; i++) {
1999
- if (propagationPath[i].parent === currentTarget) {
2000
- currentTarget = propagationPath[i];
2001
- } else {
2002
- break;
2003
- }
2004
- }
2005
- return currentTarget;
2006
- }
2007
- /**
2008
- * Creates an event whose `originalEvent` is `from`, with an optional `type` and `target` override.
2009
- *
2010
- * The event is allocated using {@link EventBoundary#allocateEvent this.allocateEvent}.
2011
- * @param from - The `originalEvent` for the returned event.
2012
- * @param [type=from.type] - The type of the returned event.
2013
- * @param target - The target of the returned event.
2014
- */
2015
- createPointerEvent(from, type, target) {
2016
- const event = this.allocateEvent(FederatedPointerEvent);
2017
- this.copyPointerData(from, event);
2018
- this.copyMouseData(from, event);
2019
- this.copyData(from, event);
2020
- event.nativeEvent = from.nativeEvent;
2021
- event.originalEvent = from;
2022
- event.target = target ?? this.hitTest(event.global.x, event.global.y) ?? this._hitElements[0];
2023
- if (typeof type === "string") {
2024
- event.type = type;
2025
- }
2026
- return event;
2027
- }
2028
- /**
2029
- * Creates a wheel event whose `originalEvent` is `from`.
2030
- *
2031
- * The event is allocated using {@link EventBoundary#allocateEvent this.allocateEvent}.
2032
- * @param from - The upstream wheel event.
2033
- */
2034
- createWheelEvent(from) {
2035
- const event = this.allocateEvent(FederatedWheelEvent);
2036
- this.copyWheelData(from, event);
2037
- this.copyMouseData(from, event);
2038
- this.copyData(from, event);
2039
- event.nativeEvent = from.nativeEvent;
2040
- event.originalEvent = from;
2041
- event.target = this.hitTest(event.global.x, event.global.y);
2042
- return event;
2043
- }
2044
- /**
2045
- * Clones the event `from`, with an optional `type` override.
2046
- *
2047
- * The event is allocated using {@link EventBoundary#allocateEvent this.allocateEvent}.
2048
- * @param from - The event to clone.
2049
- * @param [type=from.type] - The type of the returned event.
2050
- */
2051
- clonePointerEvent(from, type) {
2052
- const event = this.allocateEvent(FederatedPointerEvent);
2053
- event.nativeEvent = from.nativeEvent;
2054
- event.originalEvent = from.originalEvent;
2055
- this.copyPointerData(from, event);
2056
- this.copyMouseData(from, event);
2057
- this.copyData(from, event);
2058
- event.target = from.target;
2059
- event.path = from.composedPath().slice();
2060
- event.type = type ?? event.type;
2061
- return event;
2062
- }
2063
- /**
2064
- * Copies wheel {@link FederatedWheelEvent} data from `from` into `to`.
2065
- *
2066
- * The following properties are copied:
2067
- * + deltaMode
2068
- * + deltaX
2069
- * + deltaY
2070
- * + deltaZ
2071
- * @param from - The event to copy data from.
2072
- * @param to - The event to copy data into.
2073
- */
2074
- copyWheelData(from, to) {
2075
- to.deltaMode = from.deltaMode;
2076
- to.deltaX = from.deltaX;
2077
- to.deltaY = from.deltaY;
2078
- to.deltaZ = from.deltaZ;
2079
- }
2080
- /**
2081
- * Copies pointer {@link FederatedPointerEvent} data from `from` into `to`.
2082
- *
2083
- * The following properties are copied:
2084
- * + pointerId
2085
- * + width
2086
- * + height
2087
- * + isPrimary
2088
- * + pointerType
2089
- * + pressure
2090
- * + tangentialPressure
2091
- * + tiltX
2092
- * + tiltY
2093
- * @param from - The event to copy data from.
2094
- * @param to - The event to copy data into.
2095
- */
2096
- copyPointerData(from, to) {
2097
- if (!(from instanceof FederatedPointerEvent && to instanceof FederatedPointerEvent))
2098
- return;
2099
- to.pointerId = from.pointerId;
2100
- to.width = from.width;
2101
- to.height = from.height;
2102
- to.isPrimary = from.isPrimary;
2103
- to.pointerType = from.pointerType;
2104
- to.pressure = from.pressure;
2105
- to.tangentialPressure = from.tangentialPressure;
2106
- to.tiltX = from.tiltX;
2107
- to.tiltY = from.tiltY;
2108
- to.twist = from.twist;
2109
- }
2110
- /**
2111
- * Copies mouse {@link FederatedMouseEvent} data from `from` to `to`.
2112
- *
2113
- * The following properties are copied:
2114
- * + altKey
2115
- * + button
2116
- * + buttons
2117
- * + clientX
2118
- * + clientY
2119
- * + metaKey
2120
- * + movementX
2121
- * + movementY
2122
- * + pageX
2123
- * + pageY
2124
- * + x
2125
- * + y
2126
- * + screen
2127
- * + shiftKey
2128
- * + global
2129
- * @param from - The event to copy data from.
2130
- * @param to - The event to copy data into.
2131
- */
2132
- copyMouseData(from, to) {
2133
- if (!(from instanceof FederatedMouseEvent && to instanceof FederatedMouseEvent))
2134
- return;
2135
- to.altKey = from.altKey;
2136
- to.button = from.button;
2137
- to.buttons = from.buttons;
2138
- to.client.copyFrom(from.client);
2139
- to.ctrlKey = from.ctrlKey;
2140
- to.metaKey = from.metaKey;
2141
- to.movement.copyFrom(from.movement);
2142
- to.screen.copyFrom(from.screen);
2143
- to.shiftKey = from.shiftKey;
2144
- to.global.copyFrom(from.global);
2145
- }
2146
- /**
2147
- * Copies base {@link FederatedEvent} data from `from` into `to`.
2148
- *
2149
- * The following properties are copied:
2150
- * + isTrusted
2151
- * + srcElement
2152
- * + timeStamp
2153
- * + type
2154
- * @param from - The event to copy data from.
2155
- * @param to - The event to copy data into.
2156
- */
2157
- copyData(from, to) {
2158
- to.isTrusted = from.isTrusted;
2159
- to.srcElement = from.srcElement;
2160
- to.timeStamp = performance.now();
2161
- to.type = from.type;
2162
- to.detail = from.detail;
2163
- to.view = from.view;
2164
- to.which = from.which;
2165
- to.layer.copyFrom(from.layer);
2166
- to.page.copyFrom(from.page);
2167
- }
2168
- /**
2169
- * @param id - The pointer ID.
2170
- * @returns The tracking data stored for the given pointer. If no data exists, a blank
2171
- * state will be created.
2172
- */
2173
- trackingData(id) {
2174
- if (!this.mappingState.trackingData[id]) {
2175
- this.mappingState.trackingData[id] = {
2176
- pressTargetsByButton: {},
2177
- clicksByButton: {},
2178
- overTarget: null
2179
- };
2180
- }
2181
- return this.mappingState.trackingData[id];
2182
- }
2183
- /**
2184
- * Allocate a specific type of event from {@link EventBoundary#eventPool this.eventPool}.
2185
- *
2186
- * This allocation is constructor-agnostic, as long as it only takes one argument - this event
2187
- * boundary.
2188
- * @param constructor - The event's constructor.
2189
- */
2190
- allocateEvent(constructor) {
2191
- if (!this.eventPool.has(constructor)) {
2192
- this.eventPool.set(constructor, []);
2193
- }
2194
- const event = this.eventPool.get(constructor).pop() || new constructor(this);
2195
- event.eventPhase = event.NONE;
2196
- event.currentTarget = null;
2197
- event.defaultPrevented = false;
2198
- event.path = null;
2199
- event.target = null;
2200
- return event;
2201
- }
2202
- /**
2203
- * Frees the event and puts it back into the event pool.
2204
- *
2205
- * It is illegal to reuse the event until it is allocated again, using `this.allocateEvent`.
2206
- *
2207
- * It is also advised that events not allocated from {@link EventBoundary#allocateEvent this.allocateEvent}
2208
- * not be freed. This is because of the possibility that the same event is freed twice, which can cause
2209
- * it to be allocated twice & result in overwriting.
2210
- * @param event - The event to be freed.
2211
- * @throws Error if the event is managed by another event boundary.
2212
- */
2213
- freeEvent(event) {
2214
- if (event.manager !== this)
2215
- throw new Error("It is illegal to free an event not managed by this EventBoundary!");
2216
- const constructor = event.constructor;
2217
- if (!this.eventPool.has(constructor)) {
2218
- this.eventPool.set(constructor, []);
2219
- }
2220
- this.eventPool.get(constructor).push(event);
2221
- }
2222
- /**
2223
- * Similar to {@link EventEmitter.emit}, except it stops if the `propagationImmediatelyStopped` flag
2224
- * is set on the event.
2225
- * @param e - The event to call each listener with.
2226
- * @param type - The event key.
2227
- */
2228
- _notifyListeners(e, type) {
2229
- const listeners = e.currentTarget._events[type];
2230
- if (!listeners)
2231
- return;
2232
- if ("fn" in listeners) {
2233
- if (listeners.once)
2234
- e.currentTarget.removeListener(type, listeners.fn, void 0, true);
2235
- listeners.fn.call(listeners.context, e);
2236
- } else {
2237
- for (let i = 0, j = listeners.length; i < j && !e.propagationImmediatelyStopped; i++) {
2238
- if (listeners[i].once)
2239
- e.currentTarget.removeListener(type, listeners[i].fn, void 0, true);
2240
- listeners[i].fn.call(listeners[i].context, e);
2241
- }
2242
- }
2243
- }
2244
- }
2245
-
2246
- const MOUSE_POINTER_ID = 1;
2247
- const TOUCH_TO_POINTER = {
2248
- touchstart: "pointerdown",
2249
- touchend: "pointerup",
2250
- touchendoutside: "pointerupoutside",
2251
- touchmove: "pointermove",
2252
- touchcancel: "pointercancel"
2253
- };
2254
- const _EventSystem = class _EventSystem {
2255
- /**
2256
- * @param {Renderer} renderer
2257
- */
2258
- constructor(renderer) {
2259
- /**
2260
- * Indicates whether the current device supports touch events according to the W3C Touch Events spec.
2261
- * This is used to determine the appropriate event handling strategy.
2262
- * @see {@link https://www.w3.org/TR/touch-events/} W3C Touch Events Specification
2263
- * @readonly
2264
- * @default 'ontouchstart' in globalThis
2265
- */
2266
- this.supportsTouchEvents = "ontouchstart" in globalThis;
2267
- /**
2268
- * Indicates whether the current device supports pointer events according to the W3C Pointer Events spec.
2269
- * Used to optimize event handling and provide more consistent cross-device interaction.
2270
- * @see {@link https://www.w3.org/TR/pointerevents/} W3C Pointer Events Specification
2271
- * @readonly
2272
- * @default !!globalThis.PointerEvent
2273
- */
2274
- this.supportsPointerEvents = !!globalThis.PointerEvent;
2275
- /**
2276
- * The DOM element to which the root event listeners are bound. This is automatically set to
2277
- * the renderer's {@link Renderer#view view}.
2278
- */
2279
- this.domElement = null;
2280
- /** The resolution used to convert between the DOM client space into world space. */
2281
- this.resolution = 1;
2282
- this.renderer = renderer;
2283
- this.rootBoundary = new EventBoundary(null);
2284
- EventsTicker.init(this);
2285
- this.autoPreventDefault = true;
2286
- this._eventsAdded = false;
2287
- this._rootPointerEvent = new FederatedPointerEvent(null);
2288
- this._rootWheelEvent = new FederatedWheelEvent(null);
2289
- this.cursorStyles = {
2290
- default: "inherit",
2291
- pointer: "pointer"
2292
- };
2293
- this.features = new Proxy({ ..._EventSystem.defaultEventFeatures }, {
2294
- set: (target, key, value) => {
2295
- if (key === "globalMove") {
2296
- this.rootBoundary.enableGlobalMoveEvents = value;
2297
- }
2298
- target[key] = value;
2299
- return true;
2300
- }
2301
- });
2302
- this._onPointerDown = this._onPointerDown.bind(this);
2303
- this._onPointerMove = this._onPointerMove.bind(this);
2304
- this._onPointerUp = this._onPointerUp.bind(this);
2305
- this._onPointerOverOut = this._onPointerOverOut.bind(this);
2306
- this.onWheel = this.onWheel.bind(this);
2307
- }
2308
- /**
2309
- * The default interaction mode for all display objects.
2310
- * @see Container.eventMode
2311
- * @type {EventMode}
2312
- * @readonly
2313
- * @since 7.2.0
2314
- */
2315
- static get defaultEventMode() {
2316
- return this._defaultEventMode;
2317
- }
2318
- /**
2319
- * Runner init called, view is available at this point.
2320
- * @ignore
2321
- */
2322
- init(options) {
2323
- const { canvas, resolution } = this.renderer;
2324
- this.setTargetElement(canvas);
2325
- this.resolution = resolution;
2326
- _EventSystem._defaultEventMode = options.eventMode ?? "passive";
2327
- Object.assign(this.features, options.eventFeatures ?? {});
2328
- this.rootBoundary.enableGlobalMoveEvents = this.features.globalMove;
2329
- }
2330
- /**
2331
- * Handle changing resolution.
2332
- * @ignore
2333
- */
2334
- resolutionChange(resolution) {
2335
- this.resolution = resolution;
2336
- }
2337
- /** Destroys all event listeners and detaches the renderer. */
2338
- destroy() {
2339
- this.setTargetElement(null);
2340
- this.renderer = null;
2341
- this._currentCursor = null;
2342
- }
2343
- /**
2344
- * Sets the current cursor mode, handling any callbacks or CSS style changes.
2345
- * The cursor can be a CSS cursor string, a custom callback function, or a key from the cursorStyles dictionary.
2346
- * @param mode - Cursor mode to set. Can be:
2347
- * - A CSS cursor string (e.g., 'pointer', 'grab')
2348
- * - A key from the cursorStyles dictionary
2349
- * - null/undefined to reset to default
2350
- * @example
2351
- * ```ts
2352
- * // Using predefined cursor styles
2353
- * app.renderer.events.setCursor('pointer'); // Set standard pointer cursor
2354
- * app.renderer.events.setCursor('grab'); // Set grab cursor
2355
- * app.renderer.events.setCursor(null); // Reset to default
2356
- *
2357
- * // Using custom cursor styles
2358
- * app.renderer.events.cursorStyles.custom = 'url("cursor.png"), auto';
2359
- * app.renderer.events.setCursor('custom'); // Apply custom cursor
2360
- *
2361
- * // Using callback-based cursor
2362
- * app.renderer.events.cursorStyles.dynamic = (mode) => {
2363
- * document.body.style.cursor = mode === 'hover' ? 'pointer' : 'default';
2364
- * };
2365
- * app.renderer.events.setCursor('dynamic'); // Trigger cursor callback
2366
- * ```
2367
- * @remarks
2368
- * - Has no effect on OffscreenCanvas except for callback-based cursors
2369
- * - Caches current cursor to avoid unnecessary DOM updates
2370
- * - Supports CSS cursor values, style objects, and callback functions
2371
- * @see {@link EventSystem.cursorStyles} For defining custom cursor styles
2372
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/cursor} MDN Cursor Reference
2373
- */
2374
- setCursor(mode) {
2375
- mode || (mode = "default");
2376
- let applyStyles = true;
2377
- if (globalThis.OffscreenCanvas && this.domElement instanceof OffscreenCanvas) {
2378
- applyStyles = false;
2379
- }
2380
- if (this._currentCursor === mode) {
2381
- return;
2382
- }
2383
- this._currentCursor = mode;
2384
- const style = this.cursorStyles[mode];
2385
- if (style) {
2386
- switch (typeof style) {
2387
- case "string":
2388
- if (applyStyles) {
2389
- this.domElement.style.cursor = style;
2390
- }
2391
- break;
2392
- case "function":
2393
- style(mode);
2394
- break;
2395
- case "object":
2396
- if (applyStyles) {
2397
- Object.assign(this.domElement.style, style);
2398
- }
2399
- break;
2400
- }
2401
- } else if (applyStyles && typeof mode === "string" && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) {
2402
- this.domElement.style.cursor = mode;
2403
- }
2404
- }
2405
- /**
2406
- * The global pointer event instance containing the most recent pointer state.
2407
- * This is useful for accessing pointer information without listening to events.
2408
- * @example
2409
- * ```ts
2410
- * // Access current pointer position at any time
2411
- * const eventSystem = app.renderer.events;
2412
- * const pointer = eventSystem.pointer;
2413
- *
2414
- * // Get global coordinates
2415
- * console.log('Position:', pointer.global.x, pointer.global.y);
2416
- *
2417
- * // Check button state
2418
- * console.log('Buttons pressed:', pointer.buttons);
2419
- *
2420
- * // Get pointer type and pressure
2421
- * console.log('Type:', pointer.pointerType);
2422
- * console.log('Pressure:', pointer.pressure);
2423
- * ```
2424
- * @readonly
2425
- * @since 7.2.0
2426
- * @see {@link FederatedPointerEvent} For all available pointer properties
2427
- */
2428
- get pointer() {
2429
- return this._rootPointerEvent;
2430
- }
2431
- /**
2432
- * Event handler for pointer down events on {@link EventSystem#domElement this.domElement}.
2433
- * @param nativeEvent - The native mouse/pointer/touch event.
2434
- */
2435
- _onPointerDown(nativeEvent) {
2436
- if (!this.features.click)
2437
- return;
2438
- this.rootBoundary.rootTarget = this.renderer.lastObjectRendered;
2439
- const events = this._normalizeToPointerData(nativeEvent);
2440
- if (this.autoPreventDefault && events[0].isNormalized) {
2441
- const cancelable = nativeEvent.cancelable || !("cancelable" in nativeEvent);
2442
- if (cancelable) {
2443
- nativeEvent.preventDefault();
2444
- }
2445
- }
2446
- for (let i = 0, j = events.length; i < j; i++) {
2447
- const nativeEvent2 = events[i];
2448
- const federatedEvent = this._bootstrapEvent(this._rootPointerEvent, nativeEvent2);
2449
- this.rootBoundary.mapEvent(federatedEvent);
2450
- }
2451
- this.setCursor(this.rootBoundary.cursor);
2452
- }
2453
- /**
2454
- * Event handler for pointer move events on on {@link EventSystem#domElement this.domElement}.
2455
- * @param nativeEvent - The native mouse/pointer/touch events.
2456
- */
2457
- _onPointerMove(nativeEvent) {
2458
- if (!this.features.move)
2459
- return;
2460
- this.rootBoundary.rootTarget = this.renderer.lastObjectRendered;
2461
- EventsTicker.pointerMoved();
2462
- const normalizedEvents = this._normalizeToPointerData(nativeEvent);
2463
- for (let i = 0, j = normalizedEvents.length; i < j; i++) {
2464
- const event = this._bootstrapEvent(this._rootPointerEvent, normalizedEvents[i]);
2465
- this.rootBoundary.mapEvent(event);
2466
- }
2467
- this.setCursor(this.rootBoundary.cursor);
2468
- }
2469
- /**
2470
- * Event handler for pointer up events on {@link EventSystem#domElement this.domElement}.
2471
- * @param nativeEvent - The native mouse/pointer/touch event.
2472
- */
2473
- _onPointerUp(nativeEvent) {
2474
- if (!this.features.click)
2475
- return;
2476
- this.rootBoundary.rootTarget = this.renderer.lastObjectRendered;
2477
- let target = nativeEvent.target;
2478
- if (nativeEvent.composedPath && nativeEvent.composedPath().length > 0) {
2479
- target = nativeEvent.composedPath()[0];
2480
- }
2481
- const outside = target !== this.domElement ? "outside" : "";
2482
- const normalizedEvents = this._normalizeToPointerData(nativeEvent);
2483
- for (let i = 0, j = normalizedEvents.length; i < j; i++) {
2484
- const event = this._bootstrapEvent(this._rootPointerEvent, normalizedEvents[i]);
2485
- event.type += outside;
2486
- this.rootBoundary.mapEvent(event);
2487
- }
2488
- this.setCursor(this.rootBoundary.cursor);
2489
- }
2490
- /**
2491
- * Event handler for pointer over & out events on {@link EventSystem#domElement this.domElement}.
2492
- * @param nativeEvent - The native mouse/pointer/touch event.
2493
- */
2494
- _onPointerOverOut(nativeEvent) {
2495
- if (!this.features.click)
2496
- return;
2497
- this.rootBoundary.rootTarget = this.renderer.lastObjectRendered;
2498
- const normalizedEvents = this._normalizeToPointerData(nativeEvent);
2499
- for (let i = 0, j = normalizedEvents.length; i < j; i++) {
2500
- const event = this._bootstrapEvent(this._rootPointerEvent, normalizedEvents[i]);
2501
- this.rootBoundary.mapEvent(event);
2502
- }
2503
- this.setCursor(this.rootBoundary.cursor);
2504
- }
2505
- /**
2506
- * Passive handler for `wheel` events on {@link EventSystem.domElement this.domElement}.
2507
- * @param nativeEvent - The native wheel event.
2508
- */
2509
- onWheel(nativeEvent) {
2510
- if (!this.features.wheel)
2511
- return;
2512
- const wheelEvent = this.normalizeWheelEvent(nativeEvent);
2513
- this.rootBoundary.rootTarget = this.renderer.lastObjectRendered;
2514
- this.rootBoundary.mapEvent(wheelEvent);
2515
- }
2516
- /**
2517
- * Sets the {@link EventSystem#domElement domElement} and binds event listeners.
2518
- * This method manages the DOM event bindings for the event system, allowing you to
2519
- * change or remove the target element that receives input events.
2520
- * > [!IMPORTANT] This will default to the canvas element of the renderer, so you
2521
- * > should not need to call this unless you are using a custom element.
2522
- * @param element - The new DOM element to bind events to, or null to remove all event bindings
2523
- * @example
2524
- * ```ts
2525
- * // Set a new canvas element as the target
2526
- * const canvas = document.createElement('canvas');
2527
- * app.renderer.events.setTargetElement(canvas);
2528
- *
2529
- * // Remove all event bindings
2530
- * app.renderer.events.setTargetElement(null);
2531
- *
2532
- * // Switch to a different canvas
2533
- * const newCanvas = document.querySelector('#game-canvas');
2534
- * app.renderer.events.setTargetElement(newCanvas);
2535
- * ```
2536
- * @remarks
2537
- * - Automatically removes event listeners from previous element
2538
- * - Required for the event system to function
2539
- * - Safe to call multiple times
2540
- * @see {@link EventSystem#domElement} The current DOM element
2541
- * @see {@link EventsTicker} For the ticker system that tracks pointer movement
2542
- */
2543
- setTargetElement(element) {
2544
- this._removeEvents();
2545
- this.domElement = element;
2546
- EventsTicker.domElement = element;
2547
- this._addEvents();
2548
- }
2549
- /** Register event listeners on {@link Renderer#domElement this.domElement}. */
2550
- _addEvents() {
2551
- if (this._eventsAdded || !this.domElement) {
2552
- return;
2553
- }
2554
- EventsTicker.addTickerListener();
2555
- const style = this.domElement.style;
2556
- if (style) {
2557
- if (globalThis.navigator.msPointerEnabled) {
2558
- style.msContentZooming = "none";
2559
- style.msTouchAction = "none";
2560
- } else if (this.supportsPointerEvents) {
2561
- style.touchAction = "none";
2562
- }
2563
- }
2564
- if (this.supportsPointerEvents) {
2565
- globalThis.document.addEventListener("pointermove", this._onPointerMove, true);
2566
- this.domElement.addEventListener("pointerdown", this._onPointerDown, true);
2567
- this.domElement.addEventListener("pointerleave", this._onPointerOverOut, true);
2568
- this.domElement.addEventListener("pointerover", this._onPointerOverOut, true);
2569
- globalThis.addEventListener("pointerup", this._onPointerUp, true);
2570
- } else {
2571
- globalThis.document.addEventListener("mousemove", this._onPointerMove, true);
2572
- this.domElement.addEventListener("mousedown", this._onPointerDown, true);
2573
- this.domElement.addEventListener("mouseout", this._onPointerOverOut, true);
2574
- this.domElement.addEventListener("mouseover", this._onPointerOverOut, true);
2575
- globalThis.addEventListener("mouseup", this._onPointerUp, true);
2576
- if (this.supportsTouchEvents) {
2577
- this.domElement.addEventListener("touchstart", this._onPointerDown, true);
2578
- this.domElement.addEventListener("touchend", this._onPointerUp, true);
2579
- this.domElement.addEventListener("touchmove", this._onPointerMove, true);
2580
- }
2581
- }
2582
- this.domElement.addEventListener("wheel", this.onWheel, {
2583
- passive: true,
2584
- capture: true
2585
- });
2586
- this._eventsAdded = true;
2587
- }
2588
- /** Unregister event listeners on {@link EventSystem#domElement this.domElement}. */
2589
- _removeEvents() {
2590
- if (!this._eventsAdded || !this.domElement) {
2591
- return;
2592
- }
2593
- EventsTicker.removeTickerListener();
2594
- const style = this.domElement.style;
2595
- if (style) {
2596
- if (globalThis.navigator.msPointerEnabled) {
2597
- style.msContentZooming = "";
2598
- style.msTouchAction = "";
2599
- } else if (this.supportsPointerEvents) {
2600
- style.touchAction = "";
2601
- }
2602
- }
2603
- if (this.supportsPointerEvents) {
2604
- globalThis.document.removeEventListener("pointermove", this._onPointerMove, true);
2605
- this.domElement.removeEventListener("pointerdown", this._onPointerDown, true);
2606
- this.domElement.removeEventListener("pointerleave", this._onPointerOverOut, true);
2607
- this.domElement.removeEventListener("pointerover", this._onPointerOverOut, true);
2608
- globalThis.removeEventListener("pointerup", this._onPointerUp, true);
2609
- } else {
2610
- globalThis.document.removeEventListener("mousemove", this._onPointerMove, true);
2611
- this.domElement.removeEventListener("mousedown", this._onPointerDown, true);
2612
- this.domElement.removeEventListener("mouseout", this._onPointerOverOut, true);
2613
- this.domElement.removeEventListener("mouseover", this._onPointerOverOut, true);
2614
- globalThis.removeEventListener("mouseup", this._onPointerUp, true);
2615
- if (this.supportsTouchEvents) {
2616
- this.domElement.removeEventListener("touchstart", this._onPointerDown, true);
2617
- this.domElement.removeEventListener("touchend", this._onPointerUp, true);
2618
- this.domElement.removeEventListener("touchmove", this._onPointerMove, true);
2619
- }
2620
- }
2621
- this.domElement.removeEventListener("wheel", this.onWheel, true);
2622
- this.domElement = null;
2623
- this._eventsAdded = false;
2624
- }
2625
- /**
2626
- * Maps coordinates from DOM/screen space into PixiJS normalized coordinates.
2627
- * This takes into account the current scale, position, and resolution of the DOM element.
2628
- * @param point - The point to store the mapped coordinates in
2629
- * @param x - The x coordinate in DOM/client space
2630
- * @param y - The y coordinate in DOM/client space
2631
- * @example
2632
- * ```ts
2633
- * // Map mouse coordinates to PixiJS space
2634
- * const point = new Point();
2635
- * app.renderer.events.mapPositionToPoint(
2636
- * point,
2637
- * event.clientX,
2638
- * event.clientY
2639
- * );
2640
- * console.log('Mapped position:', point.x, point.y);
2641
- *
2642
- * // Using with pointer events
2643
- * sprite.on('pointermove', (event) => {
2644
- * // event.global already contains mapped coordinates
2645
- * console.log('Global:', event.global.x, event.global.y);
2646
- *
2647
- * // Map to local coordinates
2648
- * const local = event.getLocalPosition(sprite);
2649
- * console.log('Local:', local.x, local.y);
2650
- * });
2651
- * ```
2652
- * @remarks
2653
- * - Accounts for element scaling and positioning
2654
- * - Adjusts for device pixel ratio/resolution
2655
- */
2656
- mapPositionToPoint(point, x, y) {
2657
- const rect = this.domElement.isConnected ? this.domElement.getBoundingClientRect() : {
2658
- x: 0,
2659
- y: 0,
2660
- width: this.domElement.width,
2661
- height: this.domElement.height,
2662
- left: 0,
2663
- top: 0
2664
- };
2665
- const resolutionMultiplier = 1 / this.resolution;
2666
- point.x = (x - rect.left) * (this.domElement.width / rect.width) * resolutionMultiplier;
2667
- point.y = (y - rect.top) * (this.domElement.height / rect.height) * resolutionMultiplier;
2668
- }
2669
- /**
2670
- * Ensures that the original event object contains all data that a regular pointer event would have
2671
- * @param event - The original event data from a touch or mouse event
2672
- * @returns An array containing a single normalized pointer event, in the case of a pointer
2673
- * or mouse event, or a multiple normalized pointer events if there are multiple changed touches
2674
- */
2675
- _normalizeToPointerData(event) {
2676
- const normalizedEvents = [];
2677
- if (this.supportsTouchEvents && event instanceof TouchEvent) {
2678
- for (let i = 0, li = event.changedTouches.length; i < li; i++) {
2679
- const touch = event.changedTouches[i];
2680
- if (typeof touch.button === "undefined")
2681
- touch.button = 0;
2682
- if (typeof touch.buttons === "undefined")
2683
- touch.buttons = 1;
2684
- if (typeof touch.isPrimary === "undefined") {
2685
- touch.isPrimary = event.touches.length === 1 && event.type === "touchstart";
2686
- }
2687
- if (typeof touch.width === "undefined")
2688
- touch.width = touch.radiusX || 1;
2689
- if (typeof touch.height === "undefined")
2690
- touch.height = touch.radiusY || 1;
2691
- if (typeof touch.tiltX === "undefined")
2692
- touch.tiltX = 0;
2693
- if (typeof touch.tiltY === "undefined")
2694
- touch.tiltY = 0;
2695
- if (typeof touch.pointerType === "undefined")
2696
- touch.pointerType = "touch";
2697
- if (typeof touch.pointerId === "undefined")
2698
- touch.pointerId = touch.identifier || 0;
2699
- if (typeof touch.pressure === "undefined")
2700
- touch.pressure = touch.force || 0.5;
2701
- if (typeof touch.twist === "undefined")
2702
- touch.twist = 0;
2703
- if (typeof touch.tangentialPressure === "undefined")
2704
- touch.tangentialPressure = 0;
2705
- if (typeof touch.layerX === "undefined")
2706
- touch.layerX = touch.offsetX = touch.clientX;
2707
- if (typeof touch.layerY === "undefined")
2708
- touch.layerY = touch.offsetY = touch.clientY;
2709
- touch.isNormalized = true;
2710
- touch.type = event.type;
2711
- normalizedEvents.push(touch);
2712
- }
2713
- } else if (!globalThis.MouseEvent || event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof globalThis.PointerEvent))) {
2714
- const tempEvent = event;
2715
- if (typeof tempEvent.isPrimary === "undefined")
2716
- tempEvent.isPrimary = true;
2717
- if (typeof tempEvent.width === "undefined")
2718
- tempEvent.width = 1;
2719
- if (typeof tempEvent.height === "undefined")
2720
- tempEvent.height = 1;
2721
- if (typeof tempEvent.tiltX === "undefined")
2722
- tempEvent.tiltX = 0;
2723
- if (typeof tempEvent.tiltY === "undefined")
2724
- tempEvent.tiltY = 0;
2725
- if (typeof tempEvent.pointerType === "undefined")
2726
- tempEvent.pointerType = "mouse";
2727
- if (typeof tempEvent.pointerId === "undefined")
2728
- tempEvent.pointerId = MOUSE_POINTER_ID;
2729
- if (typeof tempEvent.pressure === "undefined")
2730
- tempEvent.pressure = 0.5;
2731
- if (typeof tempEvent.twist === "undefined")
2732
- tempEvent.twist = 0;
2733
- if (typeof tempEvent.tangentialPressure === "undefined")
2734
- tempEvent.tangentialPressure = 0;
2735
- tempEvent.isNormalized = true;
2736
- normalizedEvents.push(tempEvent);
2737
- } else {
2738
- normalizedEvents.push(event);
2739
- }
2740
- return normalizedEvents;
2741
- }
2742
- /**
2743
- * Normalizes the native {@link https://w3c.github.io/uievents/#interface-wheelevent WheelEvent}.
2744
- *
2745
- * The returned {@link FederatedWheelEvent} is a shared instance. It will not persist across
2746
- * multiple native wheel events.
2747
- * @param nativeEvent - The native wheel event that occurred on the canvas.
2748
- * @returns A federated wheel event.
2749
- */
2750
- normalizeWheelEvent(nativeEvent) {
2751
- const event = this._rootWheelEvent;
2752
- this._transferMouseData(event, nativeEvent);
2753
- event.deltaX = nativeEvent.deltaX;
2754
- event.deltaY = nativeEvent.deltaY;
2755
- event.deltaZ = nativeEvent.deltaZ;
2756
- event.deltaMode = nativeEvent.deltaMode;
2757
- this.mapPositionToPoint(event.screen, nativeEvent.clientX, nativeEvent.clientY);
2758
- event.global.copyFrom(event.screen);
2759
- event.offset.copyFrom(event.screen);
2760
- event.nativeEvent = nativeEvent;
2761
- event.type = nativeEvent.type;
2762
- return event;
2763
- }
2764
- /**
2765
- * Normalizes the `nativeEvent` into a federateed {@link FederatedPointerEvent}.
2766
- * @param event
2767
- * @param nativeEvent
2768
- */
2769
- _bootstrapEvent(event, nativeEvent) {
2770
- event.originalEvent = null;
2771
- event.nativeEvent = nativeEvent;
2772
- event.pointerId = nativeEvent.pointerId;
2773
- event.width = nativeEvent.width;
2774
- event.height = nativeEvent.height;
2775
- event.isPrimary = nativeEvent.isPrimary;
2776
- event.pointerType = nativeEvent.pointerType;
2777
- event.pressure = nativeEvent.pressure;
2778
- event.tangentialPressure = nativeEvent.tangentialPressure;
2779
- event.tiltX = nativeEvent.tiltX;
2780
- event.tiltY = nativeEvent.tiltY;
2781
- event.twist = nativeEvent.twist;
2782
- this._transferMouseData(event, nativeEvent);
2783
- this.mapPositionToPoint(event.screen, nativeEvent.clientX, nativeEvent.clientY);
2784
- event.global.copyFrom(event.screen);
2785
- event.offset.copyFrom(event.screen);
2786
- event.isTrusted = nativeEvent.isTrusted;
2787
- if (event.type === "pointerleave") {
2788
- event.type = "pointerout";
2789
- }
2790
- if (event.type.startsWith("mouse")) {
2791
- event.type = event.type.replace("mouse", "pointer");
2792
- }
2793
- if (event.type.startsWith("touch")) {
2794
- event.type = TOUCH_TO_POINTER[event.type] || event.type;
2795
- }
2796
- return event;
2797
- }
2798
- /**
2799
- * Transfers base & mouse event data from the `nativeEvent` to the federated event.
2800
- * @param event
2801
- * @param nativeEvent
2802
- */
2803
- _transferMouseData(event, nativeEvent) {
2804
- event.isTrusted = nativeEvent.isTrusted;
2805
- event.srcElement = nativeEvent.srcElement;
2806
- event.timeStamp = performance.now();
2807
- event.type = nativeEvent.type;
2808
- event.altKey = nativeEvent.altKey;
2809
- event.button = nativeEvent.button;
2810
- event.buttons = nativeEvent.buttons;
2811
- event.client.x = nativeEvent.clientX;
2812
- event.client.y = nativeEvent.clientY;
2813
- event.ctrlKey = nativeEvent.ctrlKey;
2814
- event.metaKey = nativeEvent.metaKey;
2815
- event.movement.x = nativeEvent.movementX;
2816
- event.movement.y = nativeEvent.movementY;
2817
- event.page.x = nativeEvent.pageX;
2818
- event.page.y = nativeEvent.pageY;
2819
- event.relatedTarget = null;
2820
- event.shiftKey = nativeEvent.shiftKey;
2821
- }
2822
- };
2823
- /** @ignore */
2824
- _EventSystem.extension = {
2825
- name: "events",
2826
- type: [
2827
- ExtensionType.WebGLSystem,
2828
- ExtensionType.CanvasSystem,
2829
- ExtensionType.WebGPUSystem
2830
- ],
2831
- priority: -1
2832
- };
2833
- /**
2834
- * The event features that are enabled by the EventSystem
2835
- * @since 7.2.0
2836
- * @example
2837
- * ```ts
2838
- * import { EventSystem, EventSystemFeatures } from 'pixi.js';
2839
- * // Access the default event features
2840
- * EventSystem.defaultEventFeatures = {
2841
- * // Enable pointer movement events
2842
- * move: true,
2843
- * // Enable global pointer move events
2844
- * globalMove: true,
2845
- * // Enable click events
2846
- * click: true,
2847
- * // Enable wheel events
2848
- * wheel: true,
2849
- * };
2850
- * ```
2851
- */
2852
- _EventSystem.defaultEventFeatures = {
2853
- /** Enables pointer events associated with pointer movement. */
2854
- move: true,
2855
- /** Enables global pointer move events. */
2856
- globalMove: true,
2857
- /** Enables pointer events associated with clicking. */
2858
- click: true,
2859
- /** Enables wheel events. */
2860
- wheel: true
2861
- };
2862
- let EventSystem = _EventSystem;
2863
-
2864
- const FederatedContainer = {
2865
- onclick: null,
2866
- onmousedown: null,
2867
- onmouseenter: null,
2868
- onmouseleave: null,
2869
- onmousemove: null,
2870
- onglobalmousemove: null,
2871
- onmouseout: null,
2872
- onmouseover: null,
2873
- onmouseup: null,
2874
- onmouseupoutside: null,
2875
- onpointercancel: null,
2876
- onpointerdown: null,
2877
- onpointerenter: null,
2878
- onpointerleave: null,
2879
- onpointermove: null,
2880
- onglobalpointermove: null,
2881
- onpointerout: null,
2882
- onpointerover: null,
2883
- onpointertap: null,
2884
- onpointerup: null,
2885
- onpointerupoutside: null,
2886
- onrightclick: null,
2887
- onrightdown: null,
2888
- onrightup: null,
2889
- onrightupoutside: null,
2890
- ontap: null,
2891
- ontouchcancel: null,
2892
- ontouchend: null,
2893
- ontouchendoutside: null,
2894
- ontouchmove: null,
2895
- onglobaltouchmove: null,
2896
- ontouchstart: null,
2897
- onwheel: null,
2898
- get interactive() {
2899
- return this.eventMode === "dynamic" || this.eventMode === "static";
2900
- },
2901
- set interactive(value) {
2902
- this.eventMode = value ? "static" : "passive";
2903
- },
2904
- _internalEventMode: void 0,
2905
- get eventMode() {
2906
- return this._internalEventMode ?? EventSystem.defaultEventMode;
2907
- },
2908
- set eventMode(value) {
2909
- this._internalEventMode = value;
2910
- },
2911
- isInteractive() {
2912
- return this.eventMode === "static" || this.eventMode === "dynamic";
2913
- },
2914
- interactiveChildren: true,
2915
- hitArea: null,
2916
- addEventListener(type, listener, options) {
2917
- const capture = typeof options === "boolean" && options || typeof options === "object" && options.capture;
2918
- const signal = typeof options === "object" ? options.signal : void 0;
2919
- const once = typeof options === "object" ? options.once === true : false;
2920
- const context = typeof listener === "function" ? void 0 : listener;
2921
- type = capture ? `${type}capture` : type;
2922
- const listenerFn = typeof listener === "function" ? listener : listener.handleEvent;
2923
- const emitter = this;
2924
- if (signal) {
2925
- signal.addEventListener("abort", () => {
2926
- emitter.off(type, listenerFn, context);
2927
- });
2928
- }
2929
- if (once) {
2930
- emitter.once(type, listenerFn, context);
2931
- } else {
2932
- emitter.on(type, listenerFn, context);
2933
- }
2934
- },
2935
- removeEventListener(type, listener, options) {
2936
- const capture = typeof options === "boolean" && options || typeof options === "object" && options.capture;
2937
- const context = typeof listener === "function" ? void 0 : listener;
2938
- type = capture ? `${type}capture` : type;
2939
- listener = typeof listener === "function" ? listener : listener.handleEvent;
2940
- this.off(type, listener, context);
2941
- },
2942
- dispatchEvent(e) {
2943
- if (!(e instanceof FederatedEvent)) {
2944
- throw new Error("Container cannot propagate events outside of the Federated Events API");
2945
- }
2946
- e.defaultPrevented = false;
2947
- e.path = null;
2948
- e.target = this;
2949
- e.manager.dispatchEvent(e);
2950
- return !e.defaultPrevented;
2951
- }
2952
- };
2953
-
2954
- extensions.add(AccessibilitySystem);
2955
- extensions.mixin(Container, accessibilityTarget);
2956
-
2957
- extensions.add(EventSystem);
2958
- extensions.mixin(Container, FederatedContainer);
2959
-
2960
- extensions.add(DOMPipe);