canvasengine 2.0.0-beta.2 → 2.0.0-beta.20

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.
Files changed (40) hide show
  1. package/dist/index.d.ts +1285 -0
  2. package/dist/index.js +4150 -0
  3. package/dist/index.js.map +1 -0
  4. package/index.d.ts +4 -0
  5. package/package.json +5 -12
  6. package/src/components/Canvas.ts +53 -45
  7. package/src/components/Container.ts +2 -2
  8. package/src/components/DOMContainer.ts +229 -0
  9. package/src/components/DisplayObject.ts +263 -189
  10. package/src/components/Graphic.ts +213 -36
  11. package/src/components/Mesh.ts +222 -0
  12. package/src/components/NineSliceSprite.ts +4 -1
  13. package/src/components/ParticleEmitter.ts +12 -8
  14. package/src/components/Sprite.ts +77 -14
  15. package/src/components/Text.ts +34 -14
  16. package/src/components/Video.ts +110 -0
  17. package/src/components/Viewport.ts +59 -43
  18. package/src/components/index.ts +5 -4
  19. package/src/components/types/DisplayObject.ts +30 -0
  20. package/src/directives/Drag.ts +357 -52
  21. package/src/directives/KeyboardControls.ts +3 -1
  22. package/src/directives/Sound.ts +94 -31
  23. package/src/directives/ViewportFollow.ts +35 -7
  24. package/src/engine/animation.ts +41 -5
  25. package/src/engine/bootstrap.ts +13 -2
  26. package/src/engine/directive.ts +2 -2
  27. package/src/engine/reactive.ts +336 -168
  28. package/src/engine/trigger.ts +65 -9
  29. package/src/engine/utils.ts +92 -9
  30. package/src/hooks/useProps.ts +1 -1
  31. package/src/index.ts +5 -1
  32. package/src/utils/RadialGradient.ts +29 -0
  33. package/src/utils/functions.ts +7 -0
  34. package/testing/index.ts +12 -0
  35. package/src/components/DrawMap/index.ts +0 -65
  36. package/src/components/Tilemap/Tile.ts +0 -79
  37. package/src/components/Tilemap/TileGroup.ts +0 -207
  38. package/src/components/Tilemap/TileLayer.ts +0 -163
  39. package/src/components/Tilemap/TileSet.ts +0 -41
  40. package/src/components/Tilemap/index.ts +0 -80
package/dist/index.js ADDED
@@ -0,0 +1,4150 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __typeError = (msg) => {
3
+ throw TypeError(msg);
4
+ };
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
10
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
11
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
12
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
13
+
14
+ // src/engine/directive.ts
15
+ var directives = {};
16
+ var Directive = class {
17
+ };
18
+ function registerDirective(name, directive) {
19
+ directives[name] = directive;
20
+ }
21
+ function applyDirective(element, directiveName) {
22
+ if (!directives[directiveName]) {
23
+ return null;
24
+ }
25
+ const directive = new directives[directiveName]();
26
+ directive.onInit?.(element);
27
+ return directive;
28
+ }
29
+
30
+ // src/engine/utils.ts
31
+ var utils_exports = {};
32
+ __export(utils_exports, {
33
+ arrayEquals: () => arrayEquals,
34
+ calculateDistance: () => calculateDistance,
35
+ error: () => error,
36
+ fps2ms: () => fps2ms,
37
+ get: () => get,
38
+ isBrowser: () => isBrowser,
39
+ isFunction: () => isFunction,
40
+ isObject: () => isObject,
41
+ isPromise: () => isPromise,
42
+ log: () => log,
43
+ preciseNow: () => preciseNow,
44
+ set: () => set,
45
+ setObservablePoint: () => setObservablePoint
46
+ });
47
+ function isBrowser() {
48
+ return typeof window !== "undefined";
49
+ }
50
+ function preciseNow() {
51
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
52
+ }
53
+ function fps2ms(fps) {
54
+ return 1e3 / fps;
55
+ }
56
+ function isPromise(value) {
57
+ return value && value instanceof Promise;
58
+ }
59
+ function arrayEquals(a, b) {
60
+ if (a.length !== b.length) return false;
61
+ for (let i = 0; i < a.length; i++) {
62
+ const v = a[i];
63
+ const bv = b[i];
64
+ if (typeof v === "object" && v !== null) {
65
+ if (typeof bv !== "object" || bv === null) return false;
66
+ if (Array.isArray(v)) {
67
+ if (!Array.isArray(bv) || !arrayEquals(v, bv)) return false;
68
+ } else if (!objectEquals(v, bv)) {
69
+ return false;
70
+ }
71
+ } else if (v !== bv) {
72
+ return false;
73
+ }
74
+ }
75
+ return true;
76
+ }
77
+ function objectEquals(a, b) {
78
+ const keysA = Object.keys(a);
79
+ const keysB = Object.keys(b);
80
+ if (keysA.length !== keysB.length) return false;
81
+ for (let key of keysA) {
82
+ if (!b.hasOwnProperty(key)) return false;
83
+ if (!deepEquals(a[key], b[key])) return false;
84
+ }
85
+ return true;
86
+ }
87
+ function deepEquals(a, b) {
88
+ if (a === b) return true;
89
+ if (typeof a !== typeof b) return false;
90
+ if (typeof a === "object" && a !== null) {
91
+ if (Array.isArray(a)) {
92
+ return Array.isArray(b) && arrayEquals(a, b);
93
+ }
94
+ return objectEquals(a, b);
95
+ }
96
+ return false;
97
+ }
98
+ function isFunction(val) {
99
+ return {}.toString.call(val) === "[object Function]";
100
+ }
101
+ function isObject(val) {
102
+ return typeof val == "object" && val != null && !Array.isArray(val) && val.constructor === Object;
103
+ }
104
+ function set(obj, path, value, onlyPlainObject = false) {
105
+ if (Object(obj) !== obj) return obj;
106
+ if (typeof path === "string") {
107
+ path = path.split(".");
108
+ }
109
+ let len = path.length;
110
+ if (!len) return obj;
111
+ let current = obj;
112
+ for (let i = 0; i < len - 1; i++) {
113
+ let segment = path[i];
114
+ let nextSegment = path[i + 1];
115
+ let isNextNumeric = !isNaN(Number(nextSegment)) && isFinite(Number(nextSegment));
116
+ if (!current[segment] || typeof current[segment] !== "object") {
117
+ current[segment] = isNextNumeric && !onlyPlainObject ? [] : {};
118
+ }
119
+ current = current[segment];
120
+ }
121
+ current[path[len - 1]] = value;
122
+ return obj;
123
+ }
124
+ function get(obj, path) {
125
+ const keys = path.split(".");
126
+ let current = obj;
127
+ for (let key of keys) {
128
+ if (current[key] === void 0) {
129
+ return void 0;
130
+ }
131
+ current = current[key];
132
+ }
133
+ return current;
134
+ }
135
+ function log(text) {
136
+ console.log(text);
137
+ }
138
+ function error(text) {
139
+ console.error(text);
140
+ }
141
+ function setObservablePoint(observablePoint, point) {
142
+ if (typeof point === "number") {
143
+ observablePoint.set(point);
144
+ } else if (Array.isArray(point)) {
145
+ observablePoint.set(point[0], point[1]);
146
+ } else {
147
+ observablePoint.set(point.x, point.y);
148
+ }
149
+ }
150
+ function calculateDistance(x1, y1, x2, y2) {
151
+ const dx = x1 - x2;
152
+ const dy = y1 - y2;
153
+ return Math.sqrt(dx * dx + dy * dy);
154
+ }
155
+
156
+ // src/directives/KeyboardControls.ts
157
+ var keyCodeTable = {
158
+ 3: "break",
159
+ 8: "backspace",
160
+ // backspace / delete
161
+ 9: "tab",
162
+ 12: "clear",
163
+ 13: "enter",
164
+ 16: "shift",
165
+ 17: "ctrl",
166
+ 18: "alt",
167
+ 19: "pause/break",
168
+ 20: "caps lock",
169
+ 27: "escape",
170
+ 28: "conversion",
171
+ 29: "non-conversion",
172
+ 32: "space",
173
+ 33: "page up",
174
+ 34: "page down",
175
+ 35: "end",
176
+ 36: "home",
177
+ 37: "left",
178
+ 38: "up",
179
+ 39: "right",
180
+ 40: "down",
181
+ 41: "select",
182
+ 42: "print",
183
+ 43: "execute",
184
+ 44: "Print Screen",
185
+ 45: "insert",
186
+ 46: "delete",
187
+ 48: "n0",
188
+ 49: "n1",
189
+ 50: "n2",
190
+ 51: "n3",
191
+ 52: "n4",
192
+ 53: "n5",
193
+ 54: "n6",
194
+ 55: "n7",
195
+ 56: "n8",
196
+ 57: "n9",
197
+ 58: ":",
198
+ 59: "semicolon (firefox), equals",
199
+ 60: "<",
200
+ 61: "equals (firefox)",
201
+ 63: "\xDF",
202
+ 64: "@",
203
+ 65: "a",
204
+ 66: "b",
205
+ 67: "c",
206
+ 68: "d",
207
+ 69: "e",
208
+ 70: "f",
209
+ 71: "g",
210
+ 72: "h",
211
+ 73: "i",
212
+ 74: "j",
213
+ 75: "k",
214
+ 76: "l",
215
+ 77: "m",
216
+ 78: "n",
217
+ 79: "o",
218
+ 80: "p",
219
+ 81: "q",
220
+ 82: "r",
221
+ 83: "s",
222
+ 84: "t",
223
+ 85: "u",
224
+ 86: "v",
225
+ 87: "w",
226
+ 88: "x",
227
+ 89: "y",
228
+ 90: "z",
229
+ 91: "Windows Key / Left \u2318 / Chromebook Search key",
230
+ 92: "right window key",
231
+ 93: "Windows Menu / Right \u2318",
232
+ 96: "numpad 0",
233
+ 97: "numpad 1",
234
+ 98: "numpad 2",
235
+ 99: "numpad 3",
236
+ 100: "numpad 4",
237
+ 101: "numpad 5",
238
+ 102: "numpad 6",
239
+ 103: "numpad 7",
240
+ 104: "numpad 8",
241
+ 105: "numpad 9",
242
+ 106: "multiply",
243
+ 107: "add",
244
+ 108: "numpad period (firefox)",
245
+ 109: "subtract",
246
+ 110: "decimal point",
247
+ 111: "divide",
248
+ 112: "f1",
249
+ 113: "f2",
250
+ 114: "f3",
251
+ 115: "f4",
252
+ 116: "f5",
253
+ 117: "f6",
254
+ 118: "f7",
255
+ 119: "f8",
256
+ 120: "f9",
257
+ 121: "f10",
258
+ 122: "f11",
259
+ 123: "f12",
260
+ 124: "f13",
261
+ 125: "f14",
262
+ 126: "f15",
263
+ 127: "f16",
264
+ 128: "f17",
265
+ 129: "f18",
266
+ 130: "f19",
267
+ 131: "f20",
268
+ 132: "f21",
269
+ 133: "f22",
270
+ 134: "f23",
271
+ 135: "f24",
272
+ 144: "num lock",
273
+ 145: "scroll lock",
274
+ 160: "^",
275
+ 161: "!",
276
+ 163: "#",
277
+ 164: "$",
278
+ 165: "\xF9",
279
+ 166: "page backward",
280
+ 167: "page forward",
281
+ 169: "closing paren (AZERTY)",
282
+ 170: "*",
283
+ 171: "~ + * key",
284
+ 173: "minus (firefox), mute/unmute",
285
+ 174: "decrease volume level",
286
+ 175: "increase volume level",
287
+ 176: "next",
288
+ 177: "previous",
289
+ 178: "stop",
290
+ 179: "play/pause",
291
+ 180: "e-mail",
292
+ 181: "mute/unmute (firefox)",
293
+ 182: "decrease volume level (firefox)",
294
+ 183: "increase volume level (firefox)",
295
+ 186: "semi-colon / \xF1",
296
+ 187: "equal sign",
297
+ 188: "comma",
298
+ 189: "dash",
299
+ 190: "period",
300
+ 191: "forward slash / \xE7",
301
+ 192: "grave accent / \xF1 / \xE6",
302
+ 193: "?, / or \xB0",
303
+ 194: "numpad period (chrome)",
304
+ 219: "open bracket",
305
+ 220: "back slash",
306
+ 221: "close bracket / \xE5",
307
+ 222: "single quote / \xF8",
308
+ 223: "`",
309
+ 224: "left or right \u2318 key (firefox)",
310
+ 225: "altgr",
311
+ 226: "< /git >",
312
+ 230: "GNOME Compose Key",
313
+ 231: "\xE7",
314
+ 233: "XF86Forward",
315
+ 234: "XF86Back",
316
+ 240: "alphanumeric",
317
+ 242: "hiragana/katakana",
318
+ 243: "half-width/full-width",
319
+ 244: "kanji",
320
+ 255: "toggle touchpad"
321
+ };
322
+ var inverse = (obj) => {
323
+ const newObj = {};
324
+ for (let key in obj) {
325
+ const val = obj[key];
326
+ newObj[val] = key;
327
+ }
328
+ return newObj;
329
+ };
330
+ var inverseKeyCodeTable = inverse(keyCodeTable);
331
+ var KeyboardControls = class extends Directive {
332
+ constructor() {
333
+ super(...arguments);
334
+ this.keyState = {};
335
+ this.boundKeys = {};
336
+ this.stop = false;
337
+ this.lastKeyPressed = null;
338
+ this._controlsOptions = {};
339
+ // TODO: This should be dynamic
340
+ this.serverFps = 60;
341
+ this.directionState = {
342
+ up: false,
343
+ down: false,
344
+ left: false,
345
+ right: false
346
+ };
347
+ }
348
+ onInit(element) {
349
+ const value = element.props.controls.value ?? element.props.controls;
350
+ if (!value) return;
351
+ this.setupListeners();
352
+ this.setInputs(value);
353
+ this.interval = setInterval(() => {
354
+ this.preStep();
355
+ }, fps2ms(this.serverFps ?? 60));
356
+ }
357
+ onMount(element) {
358
+ }
359
+ onUpdate(props) {
360
+ this.setInputs(props);
361
+ }
362
+ onDestroy() {
363
+ clearInterval(this.interval);
364
+ document.removeEventListener("keydown", (e) => {
365
+ this.onKeyChange(e, true);
366
+ });
367
+ document.removeEventListener("keyup", (e) => {
368
+ this.onKeyChange(e, false);
369
+ });
370
+ }
371
+ /** @internal */
372
+ preStep() {
373
+ if (this.stop) return;
374
+ const direction = this.getDirection();
375
+ if (direction !== "none") {
376
+ const directionControl = this.boundKeys[direction];
377
+ if (directionControl) {
378
+ const { keyDown } = directionControl.options;
379
+ if (keyDown) {
380
+ this.applyInput(direction);
381
+ }
382
+ }
383
+ } else {
384
+ const boundKeys = Object.keys(this.boundKeys);
385
+ for (let keyName of boundKeys) {
386
+ this.applyInput(keyName);
387
+ }
388
+ }
389
+ }
390
+ applyInput(keyName) {
391
+ const keyState = this.keyState[keyName];
392
+ if (!keyState) return;
393
+ const { isDown, count } = keyState;
394
+ if (isDown) {
395
+ const { repeat, keyDown } = this.boundKeys[keyName].options;
396
+ if (repeat || count == 0) {
397
+ let parameters = this.boundKeys[keyName].parameters;
398
+ if (typeof parameters === "function") {
399
+ parameters = parameters();
400
+ }
401
+ if (keyDown) {
402
+ keyDown(this.boundKeys[keyName]);
403
+ }
404
+ this.keyState[keyName].count++;
405
+ }
406
+ }
407
+ }
408
+ setupListeners() {
409
+ document.addEventListener("keydown", (e) => {
410
+ this.onKeyChange(e, true);
411
+ });
412
+ document.addEventListener("keyup", (e) => {
413
+ this.onKeyChange(e, false);
414
+ });
415
+ }
416
+ bindKey(keys, actionName, options, parameters) {
417
+ if (!Array.isArray(keys)) keys = [keys];
418
+ const keyOptions = Object.assign({
419
+ repeat: false
420
+ }, options);
421
+ keys.forEach((keyName) => {
422
+ this.boundKeys[keyName] = { actionName, options: keyOptions, parameters };
423
+ });
424
+ }
425
+ applyKeyDown(name) {
426
+ const code = inverseKeyCodeTable[name];
427
+ const e = new Event("keydown");
428
+ e.keyCode = code;
429
+ this.onKeyChange(e, true);
430
+ }
431
+ applyKeyUp(name) {
432
+ const code = inverseKeyCodeTable[name];
433
+ const e = new Event("keyup");
434
+ e.keyCode = code;
435
+ this.onKeyChange(e, false);
436
+ }
437
+ applyKeyPress(name) {
438
+ return new Promise((resolve) => {
439
+ this.applyKeyDown(name);
440
+ setTimeout(() => {
441
+ this.applyKeyUp(name);
442
+ resolve();
443
+ }, 200);
444
+ });
445
+ }
446
+ onKeyChange(e, isDown) {
447
+ e = e || window.event;
448
+ const keyName = keyCodeTable[e.keyCode];
449
+ if (keyName && this.boundKeys[keyName]) {
450
+ if (this.keyState[keyName] == null) {
451
+ this.keyState[keyName] = {
452
+ count: 0,
453
+ isDown: true
454
+ };
455
+ }
456
+ this.keyState[keyName].isDown = isDown;
457
+ if (!isDown) {
458
+ this.keyState[keyName].count = 0;
459
+ const { keyUp } = this.boundKeys[keyName].options;
460
+ if (keyUp) {
461
+ keyUp(this.boundKeys[keyName]);
462
+ }
463
+ }
464
+ this.lastKeyPressed = isDown ? e.keyCode : null;
465
+ }
466
+ if (keyName) {
467
+ this.updateDirectionState(keyName, isDown);
468
+ }
469
+ }
470
+ updateDirectionState(keyName, isDown) {
471
+ switch (keyName) {
472
+ case "up":
473
+ this.directionState.up = isDown;
474
+ break;
475
+ case "down":
476
+ this.directionState.down = isDown;
477
+ break;
478
+ case "left":
479
+ this.directionState.left = isDown;
480
+ break;
481
+ case "right":
482
+ this.directionState.right = isDown;
483
+ break;
484
+ }
485
+ }
486
+ getDirection() {
487
+ const { up, down, left, right } = this.directionState;
488
+ if (up && left) return "up_left";
489
+ if (up && right) return "up_right";
490
+ if (down && left) return "down_left";
491
+ if (down && right) return "down_right";
492
+ if (up) return "up";
493
+ if (down) return "down";
494
+ if (left) return "left";
495
+ if (right) return "right";
496
+ return "none";
497
+ }
498
+ /**
499
+ * From the name of the entry, we retrieve the control information
500
+ *
501
+ * ```ts
502
+ * import { Input, inject, KeyboardControls } from '@rpgjs/client'
503
+ *
504
+ * const controls = inject(KeyboardControls)
505
+ * controls.getControl(Input.Enter)
506
+
507
+ * if (control) {
508
+ * console.log(control.actionName) // action
509
+ * }
510
+ * ```
511
+ * @title Get Control
512
+ * @method getControl(inputName)
513
+ * @param {string} inputName
514
+ * @returns { { actionName: string, options: any } | undefined }
515
+ * @memberof KeyboardControls
516
+ */
517
+ getControl(inputName) {
518
+ return this.boundKeys[inputName];
519
+ }
520
+ /**
521
+ * Returns all controls
522
+ *
523
+ * @method getControls()
524
+ * @since 4.2.0
525
+ * @returns { { [key: string]: BoundKey } }
526
+ * @memberof KeyboardControls
527
+ */
528
+ getControls() {
529
+ return this.boundKeys;
530
+ }
531
+ /**
532
+ * Triggers an input according to the name of the control
533
+ *
534
+ * ```ts
535
+ * import { Control, inject, KeyboardControls } from '@rpgjs/client'
536
+ *
537
+ * const controls = inject(KeyboardControls)
538
+ * controls.applyControl(Control.Action)
539
+ * ```
540
+ *
541
+ * You can put a second parameter or indicate on whether the key is pressed or released
542
+ *
543
+ * ```ts
544
+ * import { Control, inject, KeyboardControls } from '@rpgjs/client'
545
+ *
546
+ * const controls = inject(KeyboardControls)
547
+ * controls.applyControl(Control.Up, true) // keydown
548
+ * controls.applyControl(Control.Up, false) // keyup
549
+ * ```
550
+ * @title Apply Control
551
+ * @method applyControl(controlName,isDown)
552
+ * @param {string} controlName
553
+ * @param {boolean} [isDown]
554
+ * @returns {Promise<void>}
555
+ * @memberof KeyboardControls
556
+ */
557
+ async applyControl(controlName, isDown) {
558
+ const control = this._controlsOptions[controlName];
559
+ if (control) {
560
+ const input = Array.isArray(control.bind) ? control.bind[0] : control.bind;
561
+ if (isDown === void 0) {
562
+ await this.applyKeyPress(input);
563
+ } else if (isDown) {
564
+ this.applyKeyDown(input);
565
+ } else {
566
+ this.applyKeyUp(input);
567
+ }
568
+ }
569
+ }
570
+ /**
571
+ * Stop listening to the inputs. Pressing a key won't do anything
572
+ *
573
+ * @title Stop Inputs
574
+ * @method stopInputs()
575
+ * @returns {void}
576
+ * @memberof KeyboardControls
577
+ */
578
+ stopInputs() {
579
+ this.stop = true;
580
+ }
581
+ /**
582
+ * Listen to the inputs again
583
+ *
584
+ * @title Listen Inputs
585
+ * @method listenInputs()
586
+ * @returns {void}
587
+ * @memberof KeyboardControls
588
+ */
589
+ listenInputs() {
590
+ this.stop = false;
591
+ this.keyState = {};
592
+ }
593
+ /**
594
+ * Assign custom inputs to the scene
595
+ *
596
+ * The object is the following:
597
+ *
598
+ * * the key of the object is the name of the control. Either it is existing controls (Up, Dow, Left, Right, Action, Back) or customized controls
599
+ * * The value is an object representing control information:
600
+ * * repeat {boolean} The key can be held down to repeat the action. (false by default)
601
+ * * bind {string | string[]} To which key is linked the control
602
+ * * method {Function} Function to be triggered. If you do not set this property, the name of the control is sent directly to the server.
603
+ * * delay {object|number} (since v3.2.0) Indicates how long (in milliseconds) the player can press the key again to perform the action
604
+ * * delay.duration
605
+ * * delay.otherControls {string | string[]} Indicates the other controls that will also have the delay at the same time
606
+ *
607
+ * ```ts
608
+ * import { Control, Input, inject, KeyboardControls } from '@rpgjs/client'
609
+ *
610
+ * const controls = inject(KeyboardControls)
611
+ * controls.setInputs({
612
+ [Control.Up]: {
613
+ repeat: true,
614
+ bind: Input.Up
615
+ },
616
+ [Control.Down]: {
617
+ repeat: true,
618
+ bind: Input.Down
619
+ },
620
+ [Control.Right]: {
621
+ repeat: true,
622
+ bind: Input.Right
623
+ },
624
+ [Control.Left]: {
625
+ repeat: true,
626
+ bind: Input.Left
627
+ },
628
+ [Control.Action]: {
629
+ bind: [Input.Space, Input.Enter]
630
+ },
631
+ [Control.Back]: {
632
+ bind: Input.Escape
633
+ },
634
+
635
+ // The myscustom1 control is sent to the server when the A key is pressed.
636
+ mycustom1: {
637
+ bind: Input.A
638
+ },
639
+
640
+ // the myAction method is executed when the B key is pressed
641
+ mycustom2: {
642
+ bind: Input.B,
643
+ method({ actionName }) {
644
+ console.log('cool', actionName)
645
+ }
646
+ },
647
+
648
+ // The player can redo the action after 400ms
649
+ mycustom3: {
650
+ bind: Input.C,
651
+ delay: 400 // ms
652
+ },
653
+
654
+ // The player can redo the action (mycustom4) and the directions after 400ms
655
+ mycustom4: {
656
+ bind: Input.C,
657
+ delay: {
658
+ duration: 400,
659
+ otherControls: [Control.Up, Control.Down, Control.Left, Control.Right]
660
+ }
661
+ }
662
+ })
663
+ *
664
+ * ```
665
+ * @enum {string} Control
666
+ *
667
+ * Control.Up | up
668
+ * Control.Down | down
669
+ * Control.Left | left
670
+ * Control.Right | right
671
+ * Control.Action | action
672
+ * Control.Back | back
673
+ *
674
+ * @enum {string} Mouse Event
675
+ *
676
+ * click | Click
677
+ * dblclick | Double Click
678
+ * mousedown | Mouse Down
679
+ * mouseup | Mouse Up
680
+ * mouseover | Mouse Over
681
+ * mousemove | Mouse Move
682
+ * mouseout | Mouse Out
683
+ * contextmenu | Context Menu
684
+ *
685
+ *
686
+ * @enum {string} Input
687
+ *
688
+ * break | Pause
689
+ * backspace | Backspace / Delete
690
+ * tab | Tab
691
+ * clear | Clear
692
+ * enter | Enter
693
+ * shift | Shift
694
+ * ctrl | Control
695
+ * alt | Alt
696
+ * pause/break | Pause / Break
697
+ * caps lock | Caps Lock
698
+ * escape | Escape
699
+ * conversion | Conversion
700
+ * non-conversion | Non-conversion
701
+ * space | Space
702
+ * page up | Page Up
703
+ * page down | Page Down
704
+ * end | End
705
+ * home | Home
706
+ * left | Left Arrow
707
+ * up | Up Arrow
708
+ * right | Right Arrow
709
+ * down | Down Arrow
710
+ * select | Select
711
+ * print | Print
712
+ * execute | Execute
713
+ * Print Screen | Print Screen
714
+ * insert | Insert
715
+ * delete | Delete
716
+ * n0 | 0
717
+ * n1 | 1
718
+ * n2 | 2
719
+ * n3 | 3
720
+ * n4 | 4
721
+ * n5 | 5
722
+ * n6 | 6
723
+ * n7 | 7
724
+ * n8 | 8
725
+ * n9 | 9
726
+ * : | Colon
727
+ * semicolon (firefox), equals | Semicolon (Firefox), Equals
728
+ * < | Less Than
729
+ * equals (firefox) | Equals (Firefox)
730
+ * ß | Eszett
731
+ * @ | At
732
+ * a | A
733
+ * b | B
734
+ * c | C
735
+ * d | D
736
+ * e | E
737
+ * f | F
738
+ * g | G
739
+ * h | H
740
+ * i | I
741
+ * j | J
742
+ * k | K
743
+ * l | L
744
+ * m | M
745
+ * n | N
746
+ * o | O
747
+ * p | P
748
+ * q | Q
749
+ * r | R
750
+ * s | S
751
+ * t | T
752
+ * u | U
753
+ * v | V
754
+ * w | W
755
+ * x | X
756
+ * y | Y
757
+ * z | Z
758
+ * Windows Key / Left ⌘ / Chromebook Search key | Windows Key / Left Command ⌘ / Chromebook Search Key
759
+ * right window key | Right Windows Key
760
+ * Windows Menu / Right ⌘ | Windows Menu / Right Command ⌘
761
+ * numpad 0 | Numpad 0
762
+ * numpad 1 | Numpad 1
763
+ * numpad 2 | Numpad 2
764
+ * numpad 3 | Numpad 3
765
+ * numpad 4 | Numpad 4
766
+ * numpad 5 | Numpad 5
767
+ * numpad 6 | Numpad 6
768
+ * numpad 7 | Numpad 7
769
+ * numpad 8 | Numpad 8
770
+ * numpad 9 | Numpad 9
771
+ * multiply | Multiply
772
+ * add | Add
773
+ * numpad period (firefox) | Numpad Period (Firefox)
774
+ * subtract | Subtract
775
+ * decimal point | Decimal Point
776
+ * divide | Divide
777
+ * f1 | F1
778
+ * f2 | F2
779
+ * f3 | F3
780
+ * f4 | F4
781
+ * f5 | F5
782
+ * f6 | F6
783
+ * f7 | F7
784
+ * f8 | F8
785
+ * f9 | F9
786
+ * f10 | F10
787
+ * f11 | F11
788
+ * f12 | F12
789
+ * f13 | F13
790
+ * f14 | F14
791
+ * f15 | F15
792
+ * f16 | F16
793
+ * f17 | F17
794
+ * f18 | F18
795
+ * f19 | F19
796
+ * f20 | F20
797
+ * f21 | F21
798
+ * f22 | F22
799
+ * f23 | F23
800
+ * f24 | F24
801
+ * num lock | Num Lock
802
+ * scroll lock | Scroll Lock
803
+ * ^ | Caret
804
+ * ! | Exclamation Point
805
+ * # | Hash
806
+ * $ | Dollar Sign
807
+ * ù | Grave Accent U
808
+ * page backward | Page Backward
809
+ * page forward | Page Forward
810
+ * closing paren (AZERTY) | Closing Parenthesis (AZERTY)
811
+ * * | Asterisk
812
+ * ~ + * key | Tilde + Asterisk Key
813
+ * minus (firefox), mute/unmute | Minus (Firefox), Mute/Unmute
814
+ * decrease volume level | Decrease Volume Level
815
+ * increase volume level | Increase Volume Level
816
+ * next | Next
817
+ * previous | Previous
818
+ * stop | Stop
819
+ * play/pause | Play/Pause
820
+ * e-mail | Email
821
+ * mute/unmute (firefox) | Mute/Unmute (Firefox)
822
+ * decrease volume level (firefox) | Decrease Volume Level (Firefox)
823
+ * increase volume level (firefox) | Increase Volume Level (Firefox)
824
+ * semi-colon / ñ | Semicolon / ñ
825
+ * equal sign | Equal Sign
826
+ * comma | Comma
827
+ * dash | Dash
828
+ * period | Period
829
+ * forward slash / ç | Forward Slash / ç
830
+ * grave accent / ñ / æ | Grave Accent / ñ / æ
831
+ * ?, / or ° | ?, / or °
832
+ * numpad period (chrome) | Numpad Period (Chrome)
833
+ * open bracket | Open Bracket
834
+ * back slash | Backslash
835
+ * close bracket / å | Close Bracket / å
836
+ * single quote / ø | Single Quote / ø
837
+ * \` | Backtick
838
+ * left or right ⌘ key (firefox) | Left or Right Command Key (Firefox)
839
+ * altgr | AltGr
840
+ * < /git > | < /git >
841
+ * GNOME Compose Key | GNOME Compose Key
842
+ * ç | ç
843
+ * XF86Forward | XF86Forward
844
+ * XF86Back | XF86Back
845
+ * alphanumeric | Alphanumeric
846
+ * hiragana/katakana | Hiragana/Katakana
847
+ * half-width/full-width | Half-Width/Full-Width
848
+ * kanji | Kanji
849
+ * toggle touchpad | Toggle Touchpad
850
+ *
851
+ * @title Set Inputs
852
+ * @method setInputs(inputs)
853
+ * @param {object} inputs
854
+ * @memberof KeyboardControls
855
+ */
856
+ setInputs(inputs) {
857
+ if (!inputs) return;
858
+ this.boundKeys = {};
859
+ let inputsTransformed = {};
860
+ for (let control in inputs) {
861
+ const option = inputs[control];
862
+ const { bind } = option;
863
+ let inputsKey = bind;
864
+ if (!Array.isArray(inputsKey)) {
865
+ inputsKey = [bind];
866
+ }
867
+ for (let input of inputsKey) {
868
+ this.bindKey(input, control, option);
869
+ }
870
+ }
871
+ this._controlsOptions = inputs;
872
+ }
873
+ get options() {
874
+ return this._controlsOptions;
875
+ }
876
+ };
877
+ registerDirective("controls", KeyboardControls);
878
+
879
+ // src/directives/Scheduler.ts
880
+ var Scheduler = class extends Directive {
881
+ constructor() {
882
+ super(...arguments);
883
+ this.fps = 60;
884
+ this.deltaTime = 0;
885
+ this.frame = 0;
886
+ this.timestamp = 0;
887
+ this.requestedDelay = 0;
888
+ this.lastTimestamp = 0;
889
+ this._stop = false;
890
+ }
891
+ onInit(element) {
892
+ this.tick = element.propObservables?.tick;
893
+ }
894
+ onDestroy() {
895
+ }
896
+ onMount(element) {
897
+ }
898
+ onUpdate(props) {
899
+ }
900
+ nextTick(timestamp) {
901
+ this.lastTimestamp = this.lastTimestamp || this.timestamp;
902
+ this.deltaTime = preciseNow() - this.timestamp;
903
+ this.timestamp = timestamp;
904
+ this.tick.set({
905
+ timestamp: this.timestamp,
906
+ deltaTime: this.deltaTime,
907
+ frame: this.frame,
908
+ deltaRatio: ~~this.deltaTime / ~~fps2ms(this.fps)
909
+ });
910
+ this.lastTimestamp = this.timestamp;
911
+ this.frame++;
912
+ }
913
+ /**
914
+ * start the schedule
915
+ * @return {Scheduler} returns this scheduler instance
916
+ */
917
+ start(options = {}) {
918
+ if (options.maxFps) this.maxFps = options.maxFps;
919
+ if (options.fps) this.fps = options.fps;
920
+ if (options.delay) this.requestedDelay = options.delay;
921
+ const requestAnimationFrame = (fn) => {
922
+ if (isBrowser()) {
923
+ window.requestAnimationFrame(fn.bind(this));
924
+ } else {
925
+ setTimeout(() => {
926
+ this.requestedDelay = 0;
927
+ fn(preciseNow());
928
+ }, fps2ms(this.fps) + this.requestedDelay);
929
+ }
930
+ };
931
+ if (!this.maxFps) {
932
+ const loop2 = (timestamp) => {
933
+ requestAnimationFrame(loop2);
934
+ this.nextTick(timestamp);
935
+ };
936
+ requestAnimationFrame(loop2);
937
+ } else {
938
+ const msInterval = fps2ms(this.maxFps);
939
+ let now = preciseNow();
940
+ let then = preciseNow();
941
+ const loop2 = (timestamp) => {
942
+ if (this._stop) return;
943
+ requestAnimationFrame(loop2);
944
+ now = preciseNow();
945
+ const elapsed = now - then;
946
+ if (elapsed > msInterval) {
947
+ then = now - elapsed % msInterval;
948
+ this.nextTick(timestamp);
949
+ }
950
+ };
951
+ requestAnimationFrame(loop2);
952
+ }
953
+ return this;
954
+ }
955
+ stop() {
956
+ this._stop = true;
957
+ }
958
+ };
959
+ registerDirective("tick", Scheduler);
960
+
961
+ // src/hooks/useProps.ts
962
+ import { isSignal as isSignal2, signal as signal2 } from "@signe/reactive";
963
+
964
+ // src/engine/reactive.ts
965
+ import { isComputed, isSignal, signal } from "@signe/reactive";
966
+ import {
967
+ Observable,
968
+ Subject,
969
+ defer,
970
+ from,
971
+ map,
972
+ of
973
+ } from "rxjs";
974
+ var components = {};
975
+ var isElement = (value) => {
976
+ return value && typeof value === "object" && "tag" in value && "props" in value && "componentInstance" in value;
977
+ };
978
+ var isPrimitive = (value) => {
979
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || value === void 0;
980
+ };
981
+ function registerComponent(name, component) {
982
+ components[name] = component;
983
+ }
984
+ function destroyElement(element) {
985
+ if (Array.isArray(element)) {
986
+ element.forEach((e) => destroyElement(e));
987
+ return;
988
+ }
989
+ if (!element) {
990
+ return;
991
+ }
992
+ for (let name in element.directives) {
993
+ element.directives[name].onDestroy?.(element);
994
+ }
995
+ element.componentInstance.onDestroy(element.parent, () => {
996
+ element.propSubscriptions.forEach((sub) => sub.unsubscribe());
997
+ element.effectSubscriptions.forEach((sub) => sub.unsubscribe());
998
+ element.effectUnmounts.forEach((fn) => fn?.());
999
+ });
1000
+ }
1001
+ function createComponent(tag, props) {
1002
+ if (!components[tag]) {
1003
+ throw new Error(`Component ${tag} is not registered`);
1004
+ }
1005
+ const instance = new components[tag]();
1006
+ const element = {
1007
+ tag,
1008
+ props: {},
1009
+ componentInstance: instance,
1010
+ propSubscriptions: [],
1011
+ propObservables: props,
1012
+ parent: null,
1013
+ directives: {},
1014
+ effectUnmounts: [],
1015
+ effectSubscriptions: [],
1016
+ effectMounts: [],
1017
+ destroy() {
1018
+ destroyElement(this);
1019
+ },
1020
+ allElements: new Subject()
1021
+ };
1022
+ if (props) {
1023
+ const recursiveProps = (props2, path = "") => {
1024
+ const _set = (path2, key, value) => {
1025
+ if (path2 == "") {
1026
+ element.props[key] = value;
1027
+ return;
1028
+ }
1029
+ set(element.props, path2 + "." + key, value);
1030
+ };
1031
+ Object.entries(props2).forEach(([key, value]) => {
1032
+ if (isSignal(value)) {
1033
+ const _value = value;
1034
+ if ("dependencies" in _value && _value.dependencies.size == 0) {
1035
+ _set(path, key, _value());
1036
+ return;
1037
+ }
1038
+ element.propSubscriptions.push(
1039
+ _value.observable.subscribe((value2) => {
1040
+ _set(path, key, value2);
1041
+ if (element.directives[key]) {
1042
+ element.directives[key].onUpdate?.(value2, element);
1043
+ }
1044
+ if (key == "tick") {
1045
+ return;
1046
+ }
1047
+ instance.onUpdate?.(
1048
+ path == "" ? {
1049
+ [key]: value2
1050
+ } : set({}, path + "." + key, value2)
1051
+ );
1052
+ })
1053
+ );
1054
+ } else {
1055
+ if (isObject(value) && key != "context" && !isElement(value)) {
1056
+ recursiveProps(value, (path ? path + "." : "") + key);
1057
+ } else {
1058
+ _set(path, key, value);
1059
+ }
1060
+ }
1061
+ });
1062
+ };
1063
+ recursiveProps(props);
1064
+ }
1065
+ instance.onInit?.(element.props);
1066
+ const elementsListen = new Subject();
1067
+ if (props?.isRoot) {
1068
+ element.allElements = elementsListen;
1069
+ element.props.context.rootElement = element;
1070
+ element.componentInstance.onMount?.(element);
1071
+ propagateContext(element);
1072
+ }
1073
+ if (props) {
1074
+ for (let key in props) {
1075
+ const directive = applyDirective(element, key);
1076
+ if (directive) element.directives[key] = directive;
1077
+ }
1078
+ }
1079
+ function onMount(parent, element2, index) {
1080
+ element2.props.context = parent.props.context;
1081
+ element2.parent = parent;
1082
+ element2.componentInstance.onMount?.(element2, index);
1083
+ for (let name in element2.directives) {
1084
+ element2.directives[name].onMount?.(element2);
1085
+ }
1086
+ element2.effectMounts.forEach((fn) => {
1087
+ element2.effectUnmounts.push(fn(element2));
1088
+ });
1089
+ }
1090
+ ;
1091
+ async function propagateContext(element2) {
1092
+ if (element2.props.attach) {
1093
+ const isReactiveAttach = isSignal(element2.propObservables?.attach);
1094
+ if (!isReactiveAttach) {
1095
+ element2.props.children.push(element2.props.attach);
1096
+ } else {
1097
+ await new Promise((resolve) => {
1098
+ let lastElement = null;
1099
+ element2.propSubscriptions.push(element2.propObservables.attach.observable.subscribe(async (args) => {
1100
+ const value = args?.value ?? args;
1101
+ if (!value) {
1102
+ throw new Error(`attach in ${element2.tag} is undefined or null, add a component`);
1103
+ }
1104
+ if (lastElement) {
1105
+ destroyElement(lastElement);
1106
+ }
1107
+ lastElement = value;
1108
+ await createElement(element2, value);
1109
+ resolve(void 0);
1110
+ }));
1111
+ });
1112
+ }
1113
+ }
1114
+ if (!element2.props.children) {
1115
+ return;
1116
+ }
1117
+ for (let child of element2.props.children) {
1118
+ if (!child) continue;
1119
+ await createElement(element2, child);
1120
+ }
1121
+ }
1122
+ ;
1123
+ async function createElement(parent, child) {
1124
+ if (isPromise(child)) {
1125
+ child = await child;
1126
+ }
1127
+ if (child instanceof Observable) {
1128
+ child.subscribe(
1129
+ ({
1130
+ elements: comp,
1131
+ prev
1132
+ }) => {
1133
+ const components2 = comp.filter((c) => c !== null);
1134
+ if (prev) {
1135
+ components2.forEach((c) => {
1136
+ const index = parent.props.children.indexOf(prev.props.key);
1137
+ onMount(parent, c, index + 1);
1138
+ propagateContext(c);
1139
+ });
1140
+ return;
1141
+ }
1142
+ components2.forEach((component) => {
1143
+ if (!Array.isArray(component)) {
1144
+ onMount(parent, component);
1145
+ propagateContext(component);
1146
+ } else {
1147
+ component.forEach((comp2) => {
1148
+ onMount(parent, comp2);
1149
+ propagateContext(comp2);
1150
+ });
1151
+ }
1152
+ });
1153
+ elementsListen.next(void 0);
1154
+ }
1155
+ );
1156
+ } else {
1157
+ onMount(parent, child);
1158
+ await propagateContext(child);
1159
+ }
1160
+ }
1161
+ return element;
1162
+ }
1163
+ function loop(itemsSubject, createElementFn) {
1164
+ if (isComputed(itemsSubject) && itemsSubject.dependencies.size == 0) {
1165
+ itemsSubject = signal(itemsSubject());
1166
+ } else if (!isSignal(itemsSubject)) {
1167
+ itemsSubject = signal(itemsSubject);
1168
+ }
1169
+ return defer(() => {
1170
+ let elements = [];
1171
+ let elementMap = /* @__PURE__ */ new Map();
1172
+ let isFirstSubscription = true;
1173
+ const isArraySignal = (signal10) => Array.isArray(signal10());
1174
+ return new Observable((subscriber) => {
1175
+ const subscription = isArraySignal(itemsSubject) ? itemsSubject.observable.subscribe((change) => {
1176
+ if (isFirstSubscription) {
1177
+ isFirstSubscription = false;
1178
+ elements.forEach((el) => el.destroy());
1179
+ elements = [];
1180
+ elementMap.clear();
1181
+ const items = itemsSubject();
1182
+ if (items) {
1183
+ items.forEach((item, index) => {
1184
+ const element = createElementFn(item, index);
1185
+ if (element) {
1186
+ elements.push(element);
1187
+ elementMap.set(index, element);
1188
+ }
1189
+ });
1190
+ }
1191
+ subscriber.next({
1192
+ elements: [...elements]
1193
+ });
1194
+ return;
1195
+ }
1196
+ if (change.type === "init" || change.type === "reset") {
1197
+ elements.forEach((el) => el.destroy());
1198
+ elements = [];
1199
+ elementMap.clear();
1200
+ const items = itemsSubject();
1201
+ if (items) {
1202
+ items.forEach((item, index) => {
1203
+ const element = createElementFn(item, index);
1204
+ if (element) {
1205
+ elements.push(element);
1206
+ elementMap.set(index, element);
1207
+ }
1208
+ });
1209
+ }
1210
+ } else if (change.type === "add" && change.index !== void 0) {
1211
+ const newElements = change.items.map((item, i) => {
1212
+ const element = createElementFn(item, change.index + i);
1213
+ if (element) {
1214
+ elementMap.set(change.index + i, element);
1215
+ }
1216
+ return element;
1217
+ }).filter((el) => el !== null);
1218
+ elements.splice(change.index, 0, ...newElements);
1219
+ } else if (change.type === "remove" && change.index !== void 0) {
1220
+ const removed = elements.splice(change.index, 1);
1221
+ removed.forEach((el) => {
1222
+ el.destroy();
1223
+ elementMap.delete(change.index);
1224
+ });
1225
+ } else if (change.type === "update" && change.index !== void 0 && change.items.length === 1) {
1226
+ const index = change.index;
1227
+ const newItem = change.items[0];
1228
+ if (index >= elements.length || elements[index] === void 0 || !elementMap.has(index)) {
1229
+ const newElement = createElementFn(newItem, index);
1230
+ if (newElement) {
1231
+ elements.splice(index, 0, newElement);
1232
+ elementMap.set(index, newElement);
1233
+ } else {
1234
+ console.warn(`Element creation returned null for index ${index} during add-like update.`);
1235
+ }
1236
+ } else {
1237
+ const oldElement = elements[index];
1238
+ oldElement.destroy();
1239
+ const newElement = createElementFn(newItem, index);
1240
+ if (newElement) {
1241
+ elements[index] = newElement;
1242
+ elementMap.set(index, newElement);
1243
+ } else {
1244
+ elements.splice(index, 1);
1245
+ elementMap.delete(index);
1246
+ }
1247
+ }
1248
+ }
1249
+ subscriber.next({
1250
+ elements: [...elements]
1251
+ // Create a new array to ensure change detection
1252
+ });
1253
+ }) : itemsSubject.observable.subscribe((change) => {
1254
+ const key = change.key;
1255
+ if (isFirstSubscription) {
1256
+ isFirstSubscription = false;
1257
+ elements.forEach((el) => el.destroy());
1258
+ elements = [];
1259
+ elementMap.clear();
1260
+ const items = itemsSubject();
1261
+ if (items) {
1262
+ Object.entries(items).forEach(([key2, value]) => {
1263
+ const element = createElementFn(value, key2);
1264
+ if (element) {
1265
+ elements.push(element);
1266
+ elementMap.set(key2, element);
1267
+ }
1268
+ });
1269
+ }
1270
+ subscriber.next({
1271
+ elements: [...elements]
1272
+ });
1273
+ return;
1274
+ }
1275
+ if (change.type === "init" || change.type === "reset") {
1276
+ elements.forEach((el) => el.destroy());
1277
+ elements = [];
1278
+ elementMap.clear();
1279
+ const items = itemsSubject();
1280
+ if (items) {
1281
+ Object.entries(items).forEach(([key2, value]) => {
1282
+ const element = createElementFn(value, key2);
1283
+ if (element) {
1284
+ elements.push(element);
1285
+ elementMap.set(key2, element);
1286
+ }
1287
+ });
1288
+ }
1289
+ } else if (change.type === "add" && change.key && change.value !== void 0) {
1290
+ const element = createElementFn(change.value, key);
1291
+ if (element) {
1292
+ elements.push(element);
1293
+ elementMap.set(key, element);
1294
+ }
1295
+ } else if (change.type === "remove" && change.key) {
1296
+ const index = elements.findIndex((el) => elementMap.get(key) === el);
1297
+ if (index !== -1) {
1298
+ const [removed] = elements.splice(index, 1);
1299
+ removed.destroy();
1300
+ elementMap.delete(key);
1301
+ }
1302
+ } else if (change.type === "update" && change.key && change.value !== void 0) {
1303
+ const index = elements.findIndex((el) => elementMap.get(key) === el);
1304
+ if (index !== -1) {
1305
+ const oldElement = elements[index];
1306
+ oldElement.destroy();
1307
+ const newElement = createElementFn(change.value, key);
1308
+ if (newElement) {
1309
+ elements[index] = newElement;
1310
+ elementMap.set(key, newElement);
1311
+ }
1312
+ }
1313
+ }
1314
+ subscriber.next({
1315
+ elements: [...elements]
1316
+ // Create a new array to ensure change detection
1317
+ });
1318
+ });
1319
+ return subscription;
1320
+ });
1321
+ });
1322
+ }
1323
+ function cond(condition, createElementFn) {
1324
+ let element = null;
1325
+ if (isSignal(condition)) {
1326
+ const signalCondition = condition;
1327
+ return new Observable((subscriber) => {
1328
+ return signalCondition.observable.subscribe((bool) => {
1329
+ if (bool) {
1330
+ let _el = createElementFn();
1331
+ if (isPromise(_el)) {
1332
+ from(_el).subscribe((el) => {
1333
+ element = el;
1334
+ subscriber.next({
1335
+ type: "init",
1336
+ elements: [el]
1337
+ });
1338
+ });
1339
+ } else {
1340
+ element = _el;
1341
+ subscriber.next({
1342
+ type: "init",
1343
+ elements: [element]
1344
+ });
1345
+ }
1346
+ } else if (element) {
1347
+ destroyElement(element);
1348
+ subscriber.next({
1349
+ elements: []
1350
+ });
1351
+ } else {
1352
+ subscriber.next({
1353
+ elements: []
1354
+ });
1355
+ }
1356
+ });
1357
+ });
1358
+ } else {
1359
+ if (condition) {
1360
+ let _el = createElementFn();
1361
+ if (isPromise(_el)) {
1362
+ return from(_el).pipe(
1363
+ map((el) => ({
1364
+ type: "init",
1365
+ elements: [el]
1366
+ }))
1367
+ );
1368
+ }
1369
+ return of({
1370
+ type: "init",
1371
+ elements: [_el]
1372
+ });
1373
+ }
1374
+ return of({
1375
+ elements: []
1376
+ });
1377
+ }
1378
+ }
1379
+
1380
+ // src/hooks/useProps.ts
1381
+ var useProps = (props, defaults = {}) => {
1382
+ if (isSignal2(props)) {
1383
+ return props();
1384
+ }
1385
+ const obj = {};
1386
+ for (let key in props) {
1387
+ const value = props[key];
1388
+ obj[key] = isPrimitive(value) ? signal2(value) : value;
1389
+ }
1390
+ for (let key in defaults) {
1391
+ if (!(key in obj)) {
1392
+ obj[key] = isPrimitive(defaults[key]) ? signal2(defaults[key]) : defaults[key];
1393
+ }
1394
+ }
1395
+ return obj;
1396
+ };
1397
+ var useDefineProps = (props) => {
1398
+ return (schema) => {
1399
+ const rawProps = isSignal2(props) ? props() : props;
1400
+ const validatedProps = {};
1401
+ for (const key in schema) {
1402
+ const propConfig = schema[key];
1403
+ const value = rawProps[key];
1404
+ let validatedValue;
1405
+ if (typeof propConfig === "function") {
1406
+ validateType(key, value, [propConfig]);
1407
+ validatedValue = value;
1408
+ } else if (Array.isArray(propConfig)) {
1409
+ validateType(key, value, propConfig);
1410
+ validatedValue = value;
1411
+ } else if (propConfig && typeof propConfig === "object") {
1412
+ if (propConfig.required && value === void 0) {
1413
+ throw new Error(`Missing required prop: ${key}`);
1414
+ }
1415
+ if (propConfig.type) {
1416
+ const types = Array.isArray(propConfig.type) ? propConfig.type : [propConfig.type];
1417
+ validateType(key, value, types);
1418
+ }
1419
+ if (propConfig.validator && !propConfig.validator(value, rawProps)) {
1420
+ throw new Error(`Invalid prop: custom validation failed for prop "${key}"`);
1421
+ }
1422
+ if (value === void 0 && "default" in propConfig) {
1423
+ validatedValue = typeof propConfig.default === "function" ? propConfig.default(rawProps) : propConfig.default;
1424
+ } else {
1425
+ validatedValue = value;
1426
+ }
1427
+ }
1428
+ validatedProps[key] = isSignal2(validatedValue) ? validatedValue : signal2(validatedValue);
1429
+ }
1430
+ return {
1431
+ ...useProps(rawProps),
1432
+ ...validatedProps
1433
+ };
1434
+ };
1435
+ };
1436
+ function validateType(key, value, types) {
1437
+ if (value === void 0 || value === null) return;
1438
+ const valueToCheck = isSignal2(value) ? value() : value;
1439
+ const valid = types.some((type) => {
1440
+ if (type === Number) return typeof valueToCheck === "number";
1441
+ if (type === String) return typeof valueToCheck === "string";
1442
+ if (type === Boolean) return typeof valueToCheck === "boolean";
1443
+ if (type === Function) return typeof valueToCheck === "function";
1444
+ if (type === Object) return typeof valueToCheck === "object";
1445
+ if (type === Array) return Array.isArray(valueToCheck);
1446
+ if (type === null) return valueToCheck === null;
1447
+ return valueToCheck instanceof type;
1448
+ });
1449
+ if (!valid) {
1450
+ throw new Error(
1451
+ `Invalid prop: type check failed for prop "${key}". Expected ${types.map((t) => t.name).join(" or ")}`
1452
+ );
1453
+ }
1454
+ }
1455
+
1456
+ // src/directives/ViewportFollow.ts
1457
+ var ViewportFollow = class extends Directive {
1458
+ onInit(element) {
1459
+ }
1460
+ onMount(element) {
1461
+ this.onUpdate(element.props.viewportFollow, element);
1462
+ }
1463
+ onUpdate(viewportFollow, element) {
1464
+ const { viewport } = element.props.context;
1465
+ if (!viewport) {
1466
+ throw error("ViewportFollow directive requires a Viewport component to be mounted in the same context");
1467
+ }
1468
+ if (viewportFollow) {
1469
+ if (viewportFollow === true) {
1470
+ viewport.follow(element.componentInstance);
1471
+ } else {
1472
+ const options = useProps(viewportFollow, {
1473
+ speed: void 0,
1474
+ acceleration: void 0,
1475
+ radius: void 0
1476
+ });
1477
+ viewport.follow(element.componentInstance, {
1478
+ speed: options.speed(),
1479
+ acceleration: options.acceleration(),
1480
+ radius: options.radius()
1481
+ });
1482
+ }
1483
+ } else if (viewportFollow === null) {
1484
+ viewport.plugins.remove("follow");
1485
+ }
1486
+ }
1487
+ onDestroy(element) {
1488
+ const { viewportFollow } = element.props;
1489
+ const { viewport } = element.props.context;
1490
+ if (viewportFollow) viewport.plugins.remove("follow");
1491
+ }
1492
+ };
1493
+ registerDirective("viewportFollow", ViewportFollow);
1494
+
1495
+ // src/directives/Sound.ts
1496
+ import { effect } from "@signe/reactive";
1497
+ import { Howl } from "howler";
1498
+ var EVENTS = ["load", "loaderror", "playerror", "play", "end", "pause", "stop", "mute", "volume", "rate", "seek", "fade", "unlock"];
1499
+ var Sound = class extends Directive {
1500
+ constructor() {
1501
+ super(...arguments);
1502
+ this.sounds = [];
1503
+ this.eventsFn = [];
1504
+ this.maxVolume = 1;
1505
+ this.maxDistance = 100;
1506
+ }
1507
+ onInit(element) {
1508
+ }
1509
+ onMount(element) {
1510
+ const { props } = element;
1511
+ const tick2 = props.context.tick;
1512
+ const propsSound = props.sound.value ?? props.sound;
1513
+ if (!propsSound.src) {
1514
+ return;
1515
+ }
1516
+ const { src, autoplay, loop: loop2, volume, spatial } = propsSound;
1517
+ const sources = Array.isArray(src) ? src : [src];
1518
+ for (const source of sources) {
1519
+ if (!source) continue;
1520
+ const sound = new Howl({
1521
+ src: source,
1522
+ autoplay,
1523
+ loop: loop2,
1524
+ volume
1525
+ });
1526
+ for (let event of EVENTS) {
1527
+ if (!propsSound[event]) continue;
1528
+ const fn = propsSound[event];
1529
+ this.eventsFn.push(fn);
1530
+ sound.on(event, fn);
1531
+ }
1532
+ this.sounds.push(sound);
1533
+ }
1534
+ if (spatial && this.sounds.length > 0) {
1535
+ const { soundListenerPosition } = props.context;
1536
+ if (!soundListenerPosition) {
1537
+ throw new error("SoundListenerPosition directive is required for spatial sound in component parent");
1538
+ }
1539
+ const { x: listenerX, y: listenerY } = soundListenerPosition;
1540
+ this.tickSubscription = effect(() => {
1541
+ tick2();
1542
+ const { x, y } = element.componentInstance;
1543
+ const distance = calculateDistance(x, y, listenerX(), listenerY());
1544
+ const volume2 = Math.max(this.maxVolume - distance / this.maxDistance, 0);
1545
+ this.sounds.forEach((sound) => sound.volume(volume2));
1546
+ }).subscription;
1547
+ }
1548
+ this.onUpdate(propsSound);
1549
+ }
1550
+ onUpdate(props) {
1551
+ const soundProps = props.value ?? props;
1552
+ const { volume, loop: loop2, mute, seek, playing, rate, spatial } = soundProps;
1553
+ this.sounds.forEach((sound) => {
1554
+ if (volume !== void 0) sound.volume(volume);
1555
+ if (loop2 !== void 0) sound.loop(loop2);
1556
+ if (mute !== void 0) sound.mute(mute);
1557
+ if (seek !== void 0) sound.seek(seek);
1558
+ if (playing !== void 0) {
1559
+ if (playing) sound.play();
1560
+ else sound.pause();
1561
+ }
1562
+ if (rate !== void 0) sound.rate(rate);
1563
+ });
1564
+ if (spatial) {
1565
+ this.maxVolume = spatial.maxVolume ?? this.maxVolume;
1566
+ this.maxDistance = spatial.maxDistance ?? this.maxDistance;
1567
+ }
1568
+ }
1569
+ onDestroy() {
1570
+ this.sounds.forEach((sound) => {
1571
+ sound.stop();
1572
+ for (let event of EVENTS) {
1573
+ const eventFn = this.eventsFn.find((fn) => fn === this.eventsFn[event]);
1574
+ if (eventFn) {
1575
+ sound.off(event, eventFn);
1576
+ }
1577
+ }
1578
+ });
1579
+ this.sounds = [];
1580
+ this.eventsFn = [];
1581
+ this.tickSubscription?.unsubscribe();
1582
+ }
1583
+ };
1584
+ var SoundListenerPosition = class extends Directive {
1585
+ onMount(element) {
1586
+ element.props.context.soundListenerPosition = element.propObservables?.soundListenerPosition;
1587
+ }
1588
+ onInit(element) {
1589
+ }
1590
+ onUpdate(props) {
1591
+ }
1592
+ onDestroy() {
1593
+ }
1594
+ };
1595
+ registerDirective("sound", Sound);
1596
+ registerDirective("soundListenerPosition", SoundListenerPosition);
1597
+
1598
+ // src/directives/Drag.ts
1599
+ import { effect as effect2, isComputed as isComputed2, isSignal as isSignal3 } from "@signe/reactive";
1600
+ import { Rectangle, Point } from "pixi.js";
1601
+ import { snap } from "popmotion";
1602
+
1603
+ // src/hooks/addContext.ts
1604
+ var addContext = (element, key, value) => {
1605
+ element.props.context = {
1606
+ ...element.props.context ?? {},
1607
+ [key]: value
1608
+ };
1609
+ };
1610
+
1611
+ // src/directives/Drag.ts
1612
+ var Drop = class extends Directive {
1613
+ constructor() {
1614
+ super(...arguments);
1615
+ this.elementRef = null;
1616
+ }
1617
+ onInit(element) {
1618
+ this.elementRef = element;
1619
+ }
1620
+ onMount(element) {
1621
+ addContext(element, "drop", element);
1622
+ }
1623
+ onUpdate() {
1624
+ }
1625
+ onDestroy() {
1626
+ this.elementRef = null;
1627
+ }
1628
+ };
1629
+ var Drag = class extends Directive {
1630
+ constructor() {
1631
+ super(...arguments);
1632
+ this.elementRef = null;
1633
+ this.stageRef = null;
1634
+ this.offsetInParent = new Point();
1635
+ this.isDragging = false;
1636
+ this.viewport = null;
1637
+ this.animationFrameId = null;
1638
+ this.lastPointerPosition = new Point();
1639
+ this.pressedKeys = /* @__PURE__ */ new Set();
1640
+ this.pointerIsDown = false;
1641
+ this.onDragMoveHandler = () => {
1642
+ };
1643
+ this.onDragEndHandler = () => {
1644
+ };
1645
+ this.onDragStartHandler = () => {
1646
+ };
1647
+ this.onKeyDownHandler = () => {
1648
+ };
1649
+ this.onKeyUpHandler = () => {
1650
+ };
1651
+ this.subscriptions = [];
1652
+ }
1653
+ onInit(element) {
1654
+ this.elementRef = element;
1655
+ this.onDragMoveHandler = this.onDragMove.bind(this);
1656
+ this.onDragEndHandler = this.onDragEnd.bind(this);
1657
+ this.onDragStartHandler = this.onPointerDown.bind(this);
1658
+ this.onKeyDownHandler = this.onKeyDown.bind(this);
1659
+ this.onKeyUpHandler = this.onKeyUp.bind(this);
1660
+ }
1661
+ onMount(element) {
1662
+ const { rootElement, canvasSize, viewport, tick: tick2 } = element.props.context;
1663
+ const instance = element.componentInstance;
1664
+ const dragProps = this.dragProps;
1665
+ const haveNotProps = Object.keys(dragProps).length === 0;
1666
+ if (haveNotProps) {
1667
+ this.onDestroy();
1668
+ return;
1669
+ }
1670
+ if (!instance) return;
1671
+ this.stageRef = rootElement.componentInstance;
1672
+ if (!this.stageRef) return;
1673
+ this.viewport = viewport;
1674
+ instance.eventMode = "static";
1675
+ this.stageRef.eventMode = "static";
1676
+ const _effect = effect2(() => {
1677
+ if (this.stageRef) {
1678
+ this.stageRef.hitArea = new Rectangle(0, 0, canvasSize().width, canvasSize().height);
1679
+ }
1680
+ });
1681
+ instance.on("pointerdown", this.onDragStartHandler);
1682
+ this.stageRef.on("pointerup", this.onDragEndHandler);
1683
+ this.stageRef.on("pointerupoutside", this.onDragEndHandler);
1684
+ const keysToPress = dragProps.keyToPress ? dragProps.keyToPress : [];
1685
+ window.addEventListener("keydown", this.onKeyDownHandler);
1686
+ window.addEventListener("keyup", this.onKeyUpHandler);
1687
+ this.subscriptions = [
1688
+ tick2.observable.subscribe(() => {
1689
+ if (this.isDragging && this.viewport) {
1690
+ this.updateViewportPosition(this.lastPointerPosition);
1691
+ }
1692
+ }),
1693
+ _effect.subscription
1694
+ ];
1695
+ }
1696
+ get dragProps() {
1697
+ const drag = this.elementRef?.props.drag;
1698
+ const options = useProps(drag?.value ?? drag, {
1699
+ snap: 0,
1700
+ viewport: {},
1701
+ direction: "all",
1702
+ keyToPress: []
1703
+ });
1704
+ options.viewport = useProps(options.viewport, {
1705
+ edgeThreshold: 300,
1706
+ maxSpeed: 40
1707
+ });
1708
+ return options;
1709
+ }
1710
+ get axis() {
1711
+ const direction = this.dragProps.direction();
1712
+ const axis = {
1713
+ x: true,
1714
+ y: true
1715
+ };
1716
+ if (direction === "x") {
1717
+ axis.y = false;
1718
+ }
1719
+ if (direction === "y") {
1720
+ axis.x = false;
1721
+ }
1722
+ return axis;
1723
+ }
1724
+ /**
1725
+ * Updates element position when dragging and starts continuous viewport movement
1726
+ * @param event The pointer event that triggered the drag move
1727
+ */
1728
+ onDragMove(event) {
1729
+ if (!this.isDragging || !this.elementRef?.componentInstance || !this.elementRef.componentInstance.parent) return;
1730
+ const instance = this.elementRef.componentInstance;
1731
+ const parent = instance.parent;
1732
+ const dragProps = this.dragProps;
1733
+ const propObservables = this.elementRef.propObservables;
1734
+ const snapTo = snap(dragProps?.snap() ?? 0);
1735
+ dragProps?.move?.(event);
1736
+ const currentParentLocalPointer = parent.toLocal(event.global);
1737
+ const newX = currentParentLocalPointer.x - this.offsetInParent.x;
1738
+ const newY = currentParentLocalPointer.y - this.offsetInParent.y;
1739
+ if (dragProps?.snap()) {
1740
+ instance.position.x = snapTo(newX);
1741
+ instance.position.y = snapTo(newY);
1742
+ } else {
1743
+ if (this.axis.x) instance.position.x = newX;
1744
+ if (this.axis.y) instance.position.y = newY;
1745
+ }
1746
+ this.lastPointerPosition.copyFrom(event.global);
1747
+ const { x: xProp, y: yProp } = propObservables;
1748
+ const updatePosition = (prop, value) => {
1749
+ if (isComputed2(prop)) {
1750
+ prop.dependencies.forEach((dependency) => {
1751
+ dependency.set(value);
1752
+ });
1753
+ } else if (isSignal3(prop)) {
1754
+ prop.set(value);
1755
+ }
1756
+ };
1757
+ if (xProp !== void 0) updatePosition(xProp, instance.position.x);
1758
+ if (yProp !== void 0) updatePosition(yProp, instance.position.y);
1759
+ }
1760
+ /**
1761
+ * Moves the viewport if the dragged element is near screen edges
1762
+ * @param globalPosition The global pointer position
1763
+ */
1764
+ updateViewportPosition(globalPosition) {
1765
+ if (!this.viewport || !this.elementRef) return;
1766
+ const dragProps = this.dragProps;
1767
+ const edgeThreshold = dragProps?.viewport?.edgeThreshold();
1768
+ const maxSpeed = dragProps?.viewport?.maxSpeed();
1769
+ const screenLeft = 0;
1770
+ const screenRight = this.viewport.screenWidth;
1771
+ const screenTop = 0;
1772
+ const screenBottom = this.viewport.screenHeight;
1773
+ const instance = this.elementRef.componentInstance;
1774
+ const distanceFromLeft = globalPosition.x - screenLeft;
1775
+ const distanceFromRight = screenRight - globalPosition.x;
1776
+ const distanceFromTop = globalPosition.y - screenTop;
1777
+ const distanceFromBottom = screenBottom - globalPosition.y;
1778
+ let moveX = 0;
1779
+ let moveY = 0;
1780
+ if (distanceFromLeft < edgeThreshold) {
1781
+ const velocity = maxSpeed * (1 - distanceFromLeft / edgeThreshold);
1782
+ moveX = -velocity;
1783
+ } else if (distanceFromRight < edgeThreshold) {
1784
+ const velocity = maxSpeed * (1 - distanceFromRight / edgeThreshold);
1785
+ moveX = velocity;
1786
+ }
1787
+ if (distanceFromTop < edgeThreshold) {
1788
+ const velocity = maxSpeed * (1 - distanceFromTop / edgeThreshold);
1789
+ moveY = -velocity;
1790
+ } else if (distanceFromBottom < edgeThreshold) {
1791
+ const velocity = maxSpeed * (1 - distanceFromBottom / edgeThreshold);
1792
+ moveY = velocity;
1793
+ }
1794
+ if (moveX !== 0 || moveY !== 0) {
1795
+ const lastViewValue = this.viewport.center;
1796
+ this.viewport.moveCenter(
1797
+ this.viewport.center.x + moveX,
1798
+ this.viewport.center.y + moveY
1799
+ );
1800
+ if (this.axis.x && lastViewValue.x !== this.viewport.center.x) {
1801
+ instance.position.x += moveX;
1802
+ }
1803
+ if (this.axis.y && lastViewValue.y !== this.viewport.center.y) {
1804
+ instance.position.y += moveY;
1805
+ }
1806
+ }
1807
+ }
1808
+ /**
1809
+ * Handles drag end event and stops viewport movement
1810
+ */
1811
+ onDragEnd() {
1812
+ this.pointerIsDown = false;
1813
+ if (!this.isDragging) return;
1814
+ const dragProps = this.dragProps;
1815
+ this.isDragging = false;
1816
+ dragProps?.end?.();
1817
+ if (this.stageRef) {
1818
+ this.stageRef.off("pointermove", this.onDragMoveHandler);
1819
+ }
1820
+ }
1821
+ onKeyDown(event) {
1822
+ this.pressedKeys.add(event.code);
1823
+ this.pressedKeys.add(event.key.toLowerCase());
1824
+ if (this.pointerIsDown && !this.isDragging && this.areRequiredKeysPressed()) {
1825
+ this.startDrag();
1826
+ }
1827
+ }
1828
+ onKeyUp(event) {
1829
+ this.pressedKeys.delete(event.code);
1830
+ this.pressedKeys.delete(event.key.toLowerCase());
1831
+ if (this.isDragging && !this.areRequiredKeysPressed()) {
1832
+ this.onDragEnd();
1833
+ }
1834
+ }
1835
+ areRequiredKeysPressed() {
1836
+ const keyToPress = this.dragProps.keyToPress ? this.dragProps.keyToPress : [];
1837
+ if (!keyToPress || keyToPress.length === 0) {
1838
+ return true;
1839
+ }
1840
+ return keyToPress.some((key) => {
1841
+ if (this.pressedKeys.has(key)) {
1842
+ return true;
1843
+ }
1844
+ if (key.toLowerCase() === "space") {
1845
+ return this.pressedKeys.has("Space") || this.pressedKeys.has(" ");
1846
+ }
1847
+ if (key.toLowerCase() === "shift") {
1848
+ return this.pressedKeys.has("ShiftLeft") || this.pressedKeys.has("ShiftRight");
1849
+ }
1850
+ if (key.toLowerCase() === "control" || key.toLowerCase() === "ctrl") {
1851
+ return this.pressedKeys.has("ControlLeft") || this.pressedKeys.has("ControlRight");
1852
+ }
1853
+ if (key.toLowerCase() === "alt") {
1854
+ return this.pressedKeys.has("AltLeft") || this.pressedKeys.has("AltRight");
1855
+ }
1856
+ return false;
1857
+ });
1858
+ }
1859
+ onPointerDown(event) {
1860
+ if (!this.elementRef?.componentInstance || !this.stageRef || !this.elementRef.componentInstance.parent) return;
1861
+ this.pointerIsDown = true;
1862
+ const instance = this.elementRef.componentInstance;
1863
+ const parent = instance.parent;
1864
+ const parentLocalPointer = parent.toLocal(event.global);
1865
+ this.offsetInParent.x = parentLocalPointer.x - instance.position.x;
1866
+ this.offsetInParent.y = parentLocalPointer.y - instance.position.y;
1867
+ this.lastPointerPosition.copyFrom(event.global);
1868
+ if (this.areRequiredKeysPressed()) {
1869
+ this.startDrag();
1870
+ }
1871
+ }
1872
+ startDrag() {
1873
+ if (this.isDragging || !this.stageRef) return;
1874
+ this.isDragging = true;
1875
+ const dragProps = this.dragProps;
1876
+ dragProps?.start?.();
1877
+ this.stageRef.on("pointermove", this.onDragMoveHandler);
1878
+ }
1879
+ onUpdate(props) {
1880
+ if (props.type && props.type === "reset") {
1881
+ this.onDestroy();
1882
+ this.onMount(this.elementRef);
1883
+ }
1884
+ }
1885
+ onDestroy() {
1886
+ this.subscriptions.forEach((subscription) => subscription.unsubscribe());
1887
+ const instance = this.elementRef?.componentInstance;
1888
+ if (instance) {
1889
+ instance.off("pointerdown", this.onDragStartHandler);
1890
+ }
1891
+ if (this.stageRef) {
1892
+ this.stageRef.off("pointermove", this.onDragMoveHandler);
1893
+ this.stageRef.off("pointerup", this.onDragEndHandler);
1894
+ this.stageRef.off("pointerupoutside", this.onDragEndHandler);
1895
+ }
1896
+ window.removeEventListener("keydown", this.onKeyDownHandler);
1897
+ window.removeEventListener("keyup", this.onKeyUpHandler);
1898
+ this.stageRef = null;
1899
+ this.viewport = null;
1900
+ this.pressedKeys.clear();
1901
+ this.pointerIsDown = false;
1902
+ }
1903
+ };
1904
+ registerDirective("drag", Drag);
1905
+ registerDirective("drop", Drop);
1906
+
1907
+ // src/directives/Transition.ts
1908
+ import { DisplacementFilter, Sprite, Texture, WRAP_MODES } from "pixi.js";
1909
+ import { animate } from "popmotion";
1910
+ var Transition = class extends Directive {
1911
+ onInit(element) {
1912
+ }
1913
+ onMount(element) {
1914
+ const { image } = element.props.transition;
1915
+ const displacementSprite = new Sprite(Texture.from(image));
1916
+ displacementSprite.texture.baseTexture.wrapMode = WRAP_MODES.REPEAT;
1917
+ const displacementFilter = new DisplacementFilter(displacementSprite);
1918
+ const instance = element.componentInstance;
1919
+ instance.filters = [displacementFilter];
1920
+ instance.addChild(displacementSprite);
1921
+ setTimeout(() => {
1922
+ animate({
1923
+ from: 0,
1924
+ to: 1,
1925
+ duration: 500,
1926
+ onUpdate: (progress) => {
1927
+ displacementFilter.scale.x = progress;
1928
+ displacementFilter.scale.y = progress;
1929
+ }
1930
+ });
1931
+ }, 5e3);
1932
+ }
1933
+ onUpdate(props) {
1934
+ }
1935
+ onDestroy() {
1936
+ }
1937
+ };
1938
+ registerDirective("transition", Transition);
1939
+
1940
+ // src/index.ts
1941
+ export * from "@signe/reactive";
1942
+ import { Howler } from "howler";
1943
+
1944
+ // src/components/Canvas.ts
1945
+ import { effect as effect3, signal as signal5 } from "@signe/reactive";
1946
+ import { Container as Container3 } from "pixi.js";
1947
+
1948
+ // src/components/DisplayObject.ts
1949
+ import { signal as signal4 } from "@signe/reactive";
1950
+ import { BlurFilter, ObservablePoint } from "pixi.js";
1951
+
1952
+ // src/utils/functions.ts
1953
+ function isPercent(value) {
1954
+ if (!value) return false;
1955
+ if (typeof value === "string") {
1956
+ return value.endsWith("%");
1957
+ }
1958
+ return false;
1959
+ }
1960
+
1961
+ // src/components/DisplayObject.ts
1962
+ import { BehaviorSubject } from "rxjs";
1963
+ var EVENTS2 = [
1964
+ "added",
1965
+ "childAdded",
1966
+ "childRemoved",
1967
+ "click",
1968
+ "clickcapture",
1969
+ "destroyed",
1970
+ "globalmousemove",
1971
+ "globalpointermove",
1972
+ "globaltouchmove",
1973
+ "mousedown",
1974
+ "mousedowncapture",
1975
+ "mouseenter",
1976
+ "mouseentercapture",
1977
+ "mouseleave",
1978
+ "mouseleavecapture",
1979
+ "mousemove",
1980
+ "mousemovecapture",
1981
+ "mouseout",
1982
+ "mouseoutcapture",
1983
+ "mouseover",
1984
+ "mouseovercapture",
1985
+ "mouseup",
1986
+ "mouseupcapture",
1987
+ "mouseupoutside",
1988
+ "mouseupoutsidecapture",
1989
+ "pointercancel",
1990
+ "pointercancelcapture",
1991
+ "pointerdown",
1992
+ "pointerdowncapture",
1993
+ "pointerenter",
1994
+ "pointerentercapture",
1995
+ "pointerleave",
1996
+ "pointerleavecapture",
1997
+ "pointermove",
1998
+ "pointermovecapture",
1999
+ "pointerout",
2000
+ "pointeroutcapture",
2001
+ "pointerover",
2002
+ "pointerovercapture",
2003
+ "pointertap",
2004
+ "pointertapcapture",
2005
+ "pointerup",
2006
+ "pointerupcapture",
2007
+ "pointerupoutside",
2008
+ "pointerupoutsidecapture",
2009
+ "removed",
2010
+ "rightclick",
2011
+ "rightclickcapture",
2012
+ "rightdown",
2013
+ "rightdowncapture",
2014
+ "rightup",
2015
+ "rightupcapture",
2016
+ "rightupoutside",
2017
+ "rightupoutsidecapture",
2018
+ "tap",
2019
+ "tapcapture",
2020
+ "touchcancel",
2021
+ "touchcancelcapture",
2022
+ "touchend",
2023
+ "touchendcapture",
2024
+ "touchendoutside",
2025
+ "touchendoutsidecapture",
2026
+ "touchmove",
2027
+ "touchmovecapture",
2028
+ "touchstart",
2029
+ "touchstartcapture",
2030
+ "wheel",
2031
+ "wheelcapture"
2032
+ ];
2033
+ function DisplayObject(extendClass) {
2034
+ var _canvasContext, _a;
2035
+ return _a = class extends extendClass {
2036
+ constructor() {
2037
+ super(...arguments);
2038
+ __privateAdd(this, _canvasContext, null);
2039
+ this.isFlex = false;
2040
+ this.fullProps = {};
2041
+ this.isMounted = false;
2042
+ this._anchorPoints = new ObservablePoint({ _onUpdate: () => {
2043
+ } }, 0, 0);
2044
+ this.isCustomAnchor = false;
2045
+ this.displayWidth = signal4(0);
2046
+ this.displayHeight = signal4(0);
2047
+ this.overrideProps = [];
2048
+ this.layout = null;
2049
+ this.onBeforeDestroy = null;
2050
+ this.onAfterMount = null;
2051
+ this.subjectInit = new BehaviorSubject(null);
2052
+ this.disableLayout = false;
2053
+ }
2054
+ get deltaRatio() {
2055
+ return __privateGet(this, _canvasContext)?.scheduler?.tick.value.deltaRatio;
2056
+ }
2057
+ get parentIsFlex() {
2058
+ if (this.disableLayout) return false;
2059
+ return this.parent?.isFlex;
2060
+ }
2061
+ onInit(props) {
2062
+ this._id = props.id;
2063
+ for (let event of EVENTS2) {
2064
+ if (props[event] && !this.overrideProps.includes(event)) {
2065
+ this.eventMode = "static";
2066
+ this.on(event, props[event]);
2067
+ }
2068
+ }
2069
+ if (props.onBeforeDestroy || props["on-before-destroy"]) {
2070
+ this.onBeforeDestroy = props.onBeforeDestroy || props["on-before-destroy"];
2071
+ }
2072
+ if (props.onAfterMount || props["on-after-mount"]) {
2073
+ this.onAfterMount = props.onAfterMount || props["on-after-mount"];
2074
+ }
2075
+ if (props.justifyContent || props.alignItems || props.flexDirection || props.flexWrap || props.alignContent || props.display == "flex" || isPercent(props.width) || isPercent(props.height) || props.isRoot) {
2076
+ this.layout = {};
2077
+ this.isFlex = true;
2078
+ }
2079
+ this.subjectInit.next(this);
2080
+ }
2081
+ async onMount({ parent, props }, index) {
2082
+ __privateSet(this, _canvasContext, props.context);
2083
+ if (parent) {
2084
+ const instance = parent.componentInstance;
2085
+ if (instance.isFlex && !this.layout && !this.disableLayout) {
2086
+ try {
2087
+ this.layout = {};
2088
+ } catch (error2) {
2089
+ console.warn("Failed to set layout:", error2);
2090
+ }
2091
+ }
2092
+ if (index === void 0) {
2093
+ instance.addChild(this);
2094
+ } else {
2095
+ instance.addChildAt(this, index);
2096
+ }
2097
+ this.isMounted = true;
2098
+ this.onUpdate(props);
2099
+ if (this.onAfterMount) {
2100
+ await this.onAfterMount();
2101
+ }
2102
+ }
2103
+ }
2104
+ onUpdate(props) {
2105
+ this.fullProps = {
2106
+ ...this.fullProps,
2107
+ ...props
2108
+ };
2109
+ if (!__privateGet(this, _canvasContext) || !this.parent) return;
2110
+ if (props.x !== void 0) this.setX(props.x);
2111
+ if (props.y !== void 0) this.setY(props.y);
2112
+ if (props.scale !== void 0)
2113
+ setObservablePoint(this.scale, props.scale);
2114
+ if (props.anchor !== void 0 && !this.isCustomAnchor) {
2115
+ setObservablePoint(this.anchor, props.anchor);
2116
+ }
2117
+ if (props.width !== void 0) this.setWidth(props.width);
2118
+ if (props.height !== void 0) this.setHeight(props.height);
2119
+ if (props.minWidth !== void 0) this.setMinWidth(props.minWidth);
2120
+ if (props.minHeight !== void 0) this.setMinHeight(props.minHeight);
2121
+ if (props.maxWidth !== void 0) this.setMaxWidth(props.maxWidth);
2122
+ if (props.maxHeight !== void 0) this.setMaxHeight(props.maxHeight);
2123
+ if (props.aspectRatio !== void 0)
2124
+ this.setAspectRatio(props.aspectRatio);
2125
+ if (props.flexGrow !== void 0) this.setFlexGrow(props.flexGrow);
2126
+ if (props.flexShrink !== void 0) this.setFlexShrink(props.flexShrink);
2127
+ if (props.flexBasis !== void 0) this.setFlexBasis(props.flexBasis);
2128
+ if (props.rowGap !== void 0) this.setRowGap(props.rowGap);
2129
+ if (props.columnGap !== void 0) this.setColumnGap(props.columnGap);
2130
+ if (props.top !== void 0) this.setTop(props.top);
2131
+ if (props.left !== void 0) this.setLeft(props.left);
2132
+ if (props.right !== void 0) this.setRight(props.right);
2133
+ if (props.bottom !== void 0) this.setBottom(props.bottom);
2134
+ if (props.objectFit !== void 0) this.setObjectFit(props.objectFit);
2135
+ if (props.objectPosition !== void 0)
2136
+ this.setObjectPosition(props.objectPosition);
2137
+ if (props.transformOrigin !== void 0)
2138
+ this.setTransformOrigin(props.transformOrigin);
2139
+ if (props.skew !== void 0) setObservablePoint(this.skew, props.skew);
2140
+ if (props.tint) this.tint = props.tint;
2141
+ if (props.rotation !== void 0) this.rotation = props.rotation;
2142
+ if (props.angle !== void 0) this.angle = props.angle;
2143
+ if (props.zIndex !== void 0) this.zIndex = props.zIndex;
2144
+ if (props.roundPixels !== void 0) this.roundPixels = props.roundPixels;
2145
+ if (props.cursor) this.cursor = props.cursor;
2146
+ if (props.visible !== void 0) this.visible = props.visible;
2147
+ if (props.alpha !== void 0) this.alpha = props.alpha;
2148
+ if (props.pivot) setObservablePoint(this.pivot, props.pivot);
2149
+ if (props.flexDirection) this.setFlexDirection(props.flexDirection);
2150
+ if (props.flexWrap) this.setFlexWrap(props.flexWrap);
2151
+ if (props.justifyContent) this.setJustifyContent(props.justifyContent);
2152
+ if (props.alignItems) this.setAlignItems(props.alignItems);
2153
+ if (props.alignContent) this.setAlignContent(props.alignContent);
2154
+ if (props.alignSelf) this.setAlignSelf(props.alignSelf);
2155
+ if (props.margin) this.setMargin(props.margin);
2156
+ if (props.padding) this.setPadding(props.padding);
2157
+ if (props.gap) this.setGap(props.gap);
2158
+ if (props.border) this.setBorder(props.border);
2159
+ if (props.positionType) this.setPositionType(props.positionType);
2160
+ if (props.filters) this.filters = props.filters;
2161
+ if (props.maskOf) {
2162
+ if (isElement(props.maskOf)) {
2163
+ props.maskOf.componentInstance.mask = this;
2164
+ }
2165
+ }
2166
+ if (props.blendMode) this.blendMode = props.blendMode;
2167
+ if (props.filterArea) this.filterArea = props.filterArea;
2168
+ const currentFilters = this.filters || [];
2169
+ if (props.blur) {
2170
+ let blurFilter = currentFilters.find(
2171
+ (filter2) => filter2 instanceof BlurFilter
2172
+ );
2173
+ if (!blurFilter) {
2174
+ const options = typeof props.blur === "number" ? {
2175
+ strength: props.blur
2176
+ } : props.blur;
2177
+ blurFilter = new BlurFilter(options);
2178
+ currentFilters.push(blurFilter);
2179
+ }
2180
+ Object.assign(blurFilter, props.blur);
2181
+ }
2182
+ this.filters = currentFilters;
2183
+ }
2184
+ async onDestroy(parent, afterDestroy) {
2185
+ if (this.onBeforeDestroy) {
2186
+ await this.onBeforeDestroy();
2187
+ }
2188
+ super.destroy();
2189
+ if (afterDestroy) afterDestroy();
2190
+ }
2191
+ setFlexDirection(direction) {
2192
+ this.layout = { flexDirection: direction };
2193
+ }
2194
+ setFlexWrap(wrap) {
2195
+ this.layout = { flexWrap: wrap };
2196
+ }
2197
+ setAlignContent(align) {
2198
+ this.layout = { alignContent: align };
2199
+ }
2200
+ setAlignSelf(align) {
2201
+ this.layout = { alignSelf: align };
2202
+ }
2203
+ setAlignItems(align) {
2204
+ this.layout = { alignItems: align };
2205
+ }
2206
+ setJustifyContent(justifyContent) {
2207
+ this.layout = { justifyContent };
2208
+ }
2209
+ setPosition(position) {
2210
+ if (position instanceof Array) {
2211
+ if (position.length === 2) {
2212
+ this.layout = {
2213
+ positionY: position[0],
2214
+ positionX: position[1]
2215
+ };
2216
+ } else if (position.length === 4) {
2217
+ this.layout = {
2218
+ positionTop: position[0],
2219
+ positionRight: position[1],
2220
+ positionBottom: position[2],
2221
+ positionLeft: position[3]
2222
+ };
2223
+ }
2224
+ } else {
2225
+ this.layout = { position };
2226
+ }
2227
+ }
2228
+ setX(x) {
2229
+ x = x + this.getWidth() * this._anchorPoints.x;
2230
+ if (!this.parentIsFlex) {
2231
+ this.x = x;
2232
+ } else {
2233
+ this.x = x;
2234
+ this.layout = { x };
2235
+ }
2236
+ }
2237
+ setY(y) {
2238
+ y = y + this.getHeight() * this._anchorPoints.y;
2239
+ if (!this.parentIsFlex) {
2240
+ this.y = y;
2241
+ } else {
2242
+ this.y = y;
2243
+ this.layout = { y };
2244
+ }
2245
+ }
2246
+ setPadding(padding) {
2247
+ if (padding instanceof Array) {
2248
+ if (padding.length === 2) {
2249
+ this.layout = {
2250
+ paddingVertical: padding[0],
2251
+ paddingHorizontal: padding[1]
2252
+ };
2253
+ } else if (padding.length === 4) {
2254
+ this.layout = {
2255
+ paddingTop: padding[0],
2256
+ paddingRight: padding[1],
2257
+ paddingBottom: padding[2],
2258
+ paddingLeft: padding[3]
2259
+ };
2260
+ }
2261
+ } else {
2262
+ this.layout = { padding };
2263
+ }
2264
+ }
2265
+ setMargin(margin) {
2266
+ if (margin instanceof Array) {
2267
+ if (margin.length === 2) {
2268
+ this.layout = {
2269
+ marginVertical: margin[0],
2270
+ marginHorizontal: margin[1]
2271
+ };
2272
+ } else if (margin.length === 4) {
2273
+ this.layout = {
2274
+ marginTop: margin[0],
2275
+ marginRight: margin[1],
2276
+ marginBottom: margin[2],
2277
+ marginLeft: margin[3]
2278
+ };
2279
+ }
2280
+ } else {
2281
+ this.layout = { margin };
2282
+ }
2283
+ }
2284
+ setGap(gap) {
2285
+ this.layout = { gap };
2286
+ }
2287
+ setBorder(border) {
2288
+ if (border instanceof Array) {
2289
+ if (border.length === 2) {
2290
+ this.layout = {
2291
+ borderVertical: border[0],
2292
+ borderHorizontal: border[1]
2293
+ };
2294
+ } else if (border.length === 4) {
2295
+ this.layout = {
2296
+ borderTop: border[0],
2297
+ borderRight: border[1],
2298
+ borderBottom: border[2],
2299
+ borderLeft: border[3]
2300
+ };
2301
+ }
2302
+ } else {
2303
+ this.layout = { border };
2304
+ }
2305
+ }
2306
+ setPositionType(positionType) {
2307
+ this.layout = { position: positionType };
2308
+ }
2309
+ setWidth(width) {
2310
+ this.displayWidth.set(width);
2311
+ if (!this.parentIsFlex) {
2312
+ this.width = width;
2313
+ } else {
2314
+ this.layout = { width };
2315
+ }
2316
+ }
2317
+ setHeight(height) {
2318
+ this.displayHeight.set(height);
2319
+ if (!this.parentIsFlex) {
2320
+ this.height = height;
2321
+ } else {
2322
+ this.layout = { height };
2323
+ }
2324
+ }
2325
+ getWidth() {
2326
+ return this.displayWidth();
2327
+ }
2328
+ getHeight() {
2329
+ return this.displayHeight();
2330
+ }
2331
+ // Min/Max constraints
2332
+ setMinWidth(minWidth) {
2333
+ this.layout = { minWidth };
2334
+ }
2335
+ setMinHeight(minHeight) {
2336
+ this.layout = { minHeight };
2337
+ }
2338
+ setMaxWidth(maxWidth) {
2339
+ this.layout = { maxWidth };
2340
+ }
2341
+ setMaxHeight(maxHeight) {
2342
+ this.layout = { maxHeight };
2343
+ }
2344
+ // Aspect ratio
2345
+ setAspectRatio(aspectRatio) {
2346
+ this.layout = { aspectRatio };
2347
+ }
2348
+ // Flex properties
2349
+ setFlexGrow(flexGrow) {
2350
+ this.layout = { flexGrow };
2351
+ }
2352
+ setFlexShrink(flexShrink) {
2353
+ this.layout = { flexShrink };
2354
+ }
2355
+ setFlexBasis(flexBasis) {
2356
+ this.layout = { flexBasis };
2357
+ }
2358
+ // Gap properties
2359
+ setRowGap(rowGap) {
2360
+ this.layout = { rowGap };
2361
+ }
2362
+ setColumnGap(columnGap) {
2363
+ this.layout = { columnGap };
2364
+ }
2365
+ // Position insets
2366
+ setTop(top) {
2367
+ this.layout = { top };
2368
+ }
2369
+ setLeft(left) {
2370
+ this.layout = { left };
2371
+ }
2372
+ setRight(right) {
2373
+ this.layout = { right };
2374
+ }
2375
+ setBottom(bottom) {
2376
+ this.layout = { bottom };
2377
+ }
2378
+ // Object properties
2379
+ setObjectFit(objectFit) {
2380
+ this.layout = { objectFit };
2381
+ }
2382
+ setObjectPosition(objectPosition) {
2383
+ this.layout = { objectPosition };
2384
+ }
2385
+ setTransformOrigin(transformOrigin) {
2386
+ this.layout = { transformOrigin };
2387
+ }
2388
+ }, _canvasContext = new WeakMap(), _a;
2389
+ }
2390
+
2391
+ // src/components/Canvas.ts
2392
+ registerComponent("Canvas", class Canvas extends DisplayObject(Container3) {
2393
+ });
2394
+ var Canvas2 = async (props = {}) => {
2395
+ let { cursorStyles, width, height, class: className } = useProps(props);
2396
+ if (!props.width) width = signal5(800);
2397
+ if (!props.height) height = signal5(600);
2398
+ const canvasSize = signal5({
2399
+ width: 0,
2400
+ height: 0
2401
+ });
2402
+ props.isRoot = true;
2403
+ const options = {
2404
+ ...props,
2405
+ context: {
2406
+ canvasSize,
2407
+ app: signal5(null)
2408
+ },
2409
+ width: width?.(),
2410
+ height: height?.()
2411
+ };
2412
+ if (!props.tick) {
2413
+ options.context.tick = options.tick = signal5({
2414
+ timestamp: 0,
2415
+ deltaTime: 0,
2416
+ frame: 0,
2417
+ deltaRatio: 1
2418
+ });
2419
+ }
2420
+ const canvasElement = createComponent("Canvas", options);
2421
+ canvasElement.render = (rootElement, app) => {
2422
+ if (!app) {
2423
+ return;
2424
+ }
2425
+ const renderer = app.renderer;
2426
+ const canvasEl = renderer.view.canvas;
2427
+ globalThis.__PIXI_STAGE__ = canvasElement.componentInstance;
2428
+ globalThis.__PIXI_RENDERER__ = renderer;
2429
+ if (props.tickStart !== false) canvasElement.directives.tick.start();
2430
+ effect3(() => {
2431
+ canvasElement.propObservables.tick();
2432
+ renderer.render(canvasElement.componentInstance);
2433
+ });
2434
+ app.stage = canvasElement.componentInstance;
2435
+ app.stage.layout = {
2436
+ width: app.screen.width,
2437
+ height: app.screen.height,
2438
+ justifyContent: props.justifyContent,
2439
+ alignItems: props.alignItems
2440
+ };
2441
+ canvasSize.set({ width: app.screen.width, height: app.screen.height });
2442
+ app.renderer.on("resize", (width2, height2) => {
2443
+ canvasSize.set({ width: width2, height: height2 });
2444
+ if (app.stage.layout) {
2445
+ app.stage.layout = {
2446
+ width: width2,
2447
+ height: height2
2448
+ };
2449
+ }
2450
+ });
2451
+ if (props.tickStart !== false) canvasElement.directives.tick.start();
2452
+ app.ticker.add(() => {
2453
+ canvasElement.propObservables.tick();
2454
+ });
2455
+ if (cursorStyles) {
2456
+ effect3(() => {
2457
+ renderer.events.cursorStyles = cursorStyles();
2458
+ });
2459
+ }
2460
+ if (className) {
2461
+ effect3(() => {
2462
+ canvasEl.classList.add(className());
2463
+ });
2464
+ }
2465
+ const existingCanvas = rootElement.querySelector("canvas");
2466
+ if (existingCanvas) {
2467
+ rootElement.replaceChild(canvasEl, existingCanvas);
2468
+ } else {
2469
+ rootElement.appendChild(canvasEl);
2470
+ }
2471
+ options.context.app.set(app);
2472
+ };
2473
+ return canvasElement;
2474
+ };
2475
+
2476
+ // src/components/Container.ts
2477
+ import { Container as PixiContainer } from "pixi.js";
2478
+ var CanvasContainer = class extends DisplayObject(PixiContainer) {
2479
+ constructor() {
2480
+ super(...arguments);
2481
+ this.isCustomAnchor = true;
2482
+ }
2483
+ onUpdate(props) {
2484
+ if (props.anchor) {
2485
+ setObservablePoint(this._anchorPoints, props.anchor);
2486
+ props.pivot = [
2487
+ this.getWidth() * this._anchorPoints.x,
2488
+ this.getHeight() * this._anchorPoints.y
2489
+ ];
2490
+ }
2491
+ super.onUpdate(props);
2492
+ if (props.sortableChildren != void 0) {
2493
+ this.sortableChildren = props.sortableChildren;
2494
+ }
2495
+ }
2496
+ async onMount(args) {
2497
+ await super.onMount(args);
2498
+ const { componentInstance, props } = args;
2499
+ const { pixiChildren } = props;
2500
+ if (pixiChildren) {
2501
+ pixiChildren.forEach((child) => {
2502
+ componentInstance.addChild(child);
2503
+ });
2504
+ }
2505
+ }
2506
+ };
2507
+ registerComponent("Container", CanvasContainer);
2508
+ var Container4 = (props) => {
2509
+ return createComponent("Container", props);
2510
+ };
2511
+
2512
+ // src/components/Graphic.ts
2513
+ import { effect as effect4, isSignal as isSignal4, signal as signal6 } from "@signe/reactive";
2514
+ import { Assets, Graphics as PixiGraphics } from "pixi.js";
2515
+ var CanvasGraphics = class extends DisplayObject(PixiGraphics) {
2516
+ /**
2517
+ * Initializes the graphics component with reactive width and height handling.
2518
+ *
2519
+ * This method handles different types of width and height props:
2520
+ * - **Numbers**: Direct pixel values
2521
+ * - **Strings with %**: Percentage values that trigger flex layout and use layout box dimensions
2522
+ * - **Signals**: Reactive values that update automatically
2523
+ *
2524
+ * When percentage values are detected, the component:
2525
+ * 1. Sets `display: 'flex'` to enable layout calculations
2526
+ * 2. Listens to layout events to get computed dimensions
2527
+ * 3. Updates internal width/height signals with layout box values
2528
+ *
2529
+ * The draw function receives the reactive width and height signals as parameters.
2530
+ *
2531
+ * @param props - Component properties including width, height, and draw function
2532
+ * @example
2533
+ * ```typescript
2534
+ * // With pixel values
2535
+ * Graphics({ width: 100, height: 50, draw: (g, w, h) => g.rect(0, 0, w(), h()) });
2536
+ *
2537
+ * // With percentage values (uses layout box)
2538
+ * Graphics({ width: "50%", height: "100%", draw: (g, w, h) => g.rect(0, 0, w(), h()) });
2539
+ *
2540
+ * // With signals
2541
+ * const width = signal(100);
2542
+ * Graphics({ width, height: 50, draw: (g, w, h) => g.rect(0, 0, w(), h()) });
2543
+ * ```
2544
+ */
2545
+ async onInit(props) {
2546
+ await super.onInit(props);
2547
+ }
2548
+ /**
2549
+ * Called when the component is mounted to the scene graph.
2550
+ * Creates the reactive effect for drawing using the original signals from propObservables.
2551
+ * @param {Element<DisplayObject>} element - The element being mounted with props and propObservables.
2552
+ * @param {number} [index] - The index of the component among its siblings.
2553
+ */
2554
+ async onMount(element, index) {
2555
+ await super.onMount(element, index);
2556
+ const { props, propObservables } = element;
2557
+ const width = isSignal4(propObservables?.width) ? propObservables.width : signal6(props.width || 0);
2558
+ const height = isSignal4(propObservables?.height) ? propObservables.height : signal6(props.height || 0);
2559
+ this.width = width;
2560
+ this.height = height;
2561
+ const isWidthPercentage = isPercent(width());
2562
+ const isHeightPercentage = isPercent(height());
2563
+ if (props.draw) {
2564
+ this.clearEffect = effect4(() => {
2565
+ const w = width();
2566
+ const h2 = height();
2567
+ if (typeof w == "string" || typeof h2 == "string") {
2568
+ return;
2569
+ }
2570
+ if (w == 0 || h2 == 0) {
2571
+ return;
2572
+ }
2573
+ this.clear();
2574
+ props.draw?.(this, w, h2);
2575
+ this.subjectInit.next(this);
2576
+ });
2577
+ }
2578
+ this.on("layout", (event) => {
2579
+ const layoutBox = event.computedLayout;
2580
+ if (isWidthPercentage && isSignal4(width)) {
2581
+ width.set(layoutBox.width);
2582
+ }
2583
+ if (isHeightPercentage && isSignal4(height)) {
2584
+ height.set(layoutBox.height);
2585
+ }
2586
+ });
2587
+ }
2588
+ /**
2589
+ * Called when component props are updated.
2590
+ * Updates the internal width and height signals when props change.
2591
+ * @param props - Updated properties
2592
+ */
2593
+ onUpdate(props) {
2594
+ super.onUpdate(props);
2595
+ if (props.width !== void 0 && this.width) {
2596
+ if (isSignal4(props.width)) {
2597
+ this.width = props.width;
2598
+ } else {
2599
+ this.width.set(props.width);
2600
+ }
2601
+ }
2602
+ if (props.height !== void 0 && this.height) {
2603
+ if (isSignal4(props.height)) {
2604
+ this.height = props.height;
2605
+ } else {
2606
+ this.height.set(props.height);
2607
+ }
2608
+ }
2609
+ }
2610
+ /**
2611
+ * Called when the component is about to be destroyed.
2612
+ * This method should be overridden by subclasses to perform any cleanup.
2613
+ * It ensures that the clearEffect subscription is unsubscribed before calling the original afterDestroy callback.
2614
+ * @param parent The parent element.
2615
+ * @param afterDestroy A callback function to be executed after the component's own destruction logic.
2616
+ * @example
2617
+ * // This method is typically called by the engine internally.
2618
+ * // await component.onDestroy(parentElement, () => console.log('Component destroyed'));
2619
+ */
2620
+ async onDestroy(parent, afterDestroy) {
2621
+ const _afterDestroyCallback = async () => {
2622
+ this.clearEffect.subscription.unsubscribe();
2623
+ afterDestroy();
2624
+ };
2625
+ await super.onDestroy(parent, _afterDestroyCallback);
2626
+ }
2627
+ };
2628
+ registerComponent("Graphics", CanvasGraphics);
2629
+ function Graphics(props) {
2630
+ return createComponent("Graphics", props);
2631
+ }
2632
+ function Rect(props) {
2633
+ const { color, borderRadius, border } = useProps(props, {
2634
+ borderRadius: null,
2635
+ border: null
2636
+ });
2637
+ return Graphics({
2638
+ draw: (g, width, height) => {
2639
+ if (borderRadius()) {
2640
+ g.roundRect(0, 0, width, height, borderRadius());
2641
+ } else {
2642
+ g.rect(0, 0, width, height);
2643
+ }
2644
+ if (border) {
2645
+ g.stroke(border);
2646
+ }
2647
+ g.fill(color());
2648
+ },
2649
+ ...props
2650
+ });
2651
+ }
2652
+ function drawShape(g, shape, props) {
2653
+ const { color, border } = props;
2654
+ if ("radius" in props) {
2655
+ g.circle(0, 0, props.radius());
2656
+ } else {
2657
+ g.ellipse(0, 0, props.width() / 2, props.height() / 2);
2658
+ }
2659
+ if (border()) {
2660
+ g.stroke(border());
2661
+ }
2662
+ g.fill(color());
2663
+ }
2664
+ function Circle(props) {
2665
+ const { radius, color, border } = useProps(props, {
2666
+ border: null
2667
+ });
2668
+ return Graphics({
2669
+ draw: (g) => drawShape(g, "circle", { radius, color, border }),
2670
+ ...props
2671
+ });
2672
+ }
2673
+ function Ellipse(props) {
2674
+ const { width, height, color, border } = useProps(props, {
2675
+ border: null
2676
+ });
2677
+ return Graphics({
2678
+ draw: (g, gWidth, gHeight) => drawShape(g, "ellipse", { width: signal6(gWidth), height: signal6(gHeight), color, border }),
2679
+ ...props
2680
+ });
2681
+ }
2682
+ function Triangle(props) {
2683
+ const { width, height, color, border } = useProps(props, {
2684
+ border: null,
2685
+ color: "#000"
2686
+ });
2687
+ return Graphics({
2688
+ draw: (g, gWidth, gHeight) => {
2689
+ g.moveTo(0, gHeight);
2690
+ g.lineTo(gWidth / 2, 0);
2691
+ g.lineTo(gWidth, gHeight);
2692
+ g.lineTo(0, gHeight);
2693
+ g.fill(color());
2694
+ if (border) {
2695
+ g.stroke(border);
2696
+ }
2697
+ },
2698
+ ...props
2699
+ });
2700
+ }
2701
+ function Svg(props) {
2702
+ return Graphics({
2703
+ draw: async (g) => {
2704
+ if (props.src) {
2705
+ const svgData = await Assets.load({
2706
+ src: props.src,
2707
+ data: {
2708
+ parseAsGraphicsContext: true
2709
+ }
2710
+ });
2711
+ const graphics = new PixiGraphics(svgData);
2712
+ g.context = graphics.context;
2713
+ } else if (props.content) {
2714
+ g.svg(props.content);
2715
+ } else if (props.svg) {
2716
+ g.svg(props.svg);
2717
+ }
2718
+ },
2719
+ ...props
2720
+ });
2721
+ }
2722
+
2723
+ // src/components/Mesh.ts
2724
+ import { Mesh as PixiMesh, Geometry, Assets as Assets2 } from "pixi.js";
2725
+ var CanvasMesh = class extends DisplayObject(PixiMesh) {
2726
+ /**
2727
+ * Constructor for the CanvasMesh component.
2728
+ * Initializes the PixiMesh with default geometry and shader to prevent errors.
2729
+ *
2730
+ * @example
2731
+ * ```typescript
2732
+ * // This constructor is called internally by the engine
2733
+ * const mesh = new CanvasMesh();
2734
+ * ```
2735
+ */
2736
+ constructor() {
2737
+ super({
2738
+ geometry: new Geometry()
2739
+ });
2740
+ }
2741
+ /**
2742
+ * Initializes the mesh component with the provided properties.
2743
+ * This method is called before onUpdate to set up initial state.
2744
+ *
2745
+ * @param props - The initial properties
2746
+ * @example
2747
+ * ```typescript
2748
+ * // This method is called internally when the component is created
2749
+ * mesh.onInit({
2750
+ * geometry: myGeometry,
2751
+ * texture: "texture.png"
2752
+ * });
2753
+ * ```
2754
+ */
2755
+ onInit(props) {
2756
+ super.onInit(props);
2757
+ if (props.geometry) {
2758
+ try {
2759
+ this.geometry = props.geometry;
2760
+ } catch (error2) {
2761
+ console.warn("Failed to set geometry:", error2);
2762
+ }
2763
+ }
2764
+ if (props.shader) {
2765
+ this.shader = props.shader;
2766
+ }
2767
+ }
2768
+ /**
2769
+ * Updates the mesh component when properties change.
2770
+ * Handles texture loading, shader updates, and other property changes.
2771
+ *
2772
+ * @param props - The updated properties
2773
+ * @example
2774
+ * ```typescript
2775
+ * // This method is called internally when props change
2776
+ * mesh.onUpdate({
2777
+ * tint: 0x00ff00,
2778
+ * texture: "new-texture.png"
2779
+ * });
2780
+ * ```
2781
+ */
2782
+ async onUpdate(props) {
2783
+ super.onUpdate(props);
2784
+ if (props.geometry) {
2785
+ try {
2786
+ this.geometry = props.geometry;
2787
+ } catch (error2) {
2788
+ console.warn("Failed to update geometry:", error2);
2789
+ }
2790
+ }
2791
+ if (props.shader) {
2792
+ this.shader = props.shader;
2793
+ }
2794
+ if (props.texture) {
2795
+ if (typeof props.texture === "string") {
2796
+ this.texture = await Assets2.load(props.texture);
2797
+ } else {
2798
+ this.texture = props.texture;
2799
+ }
2800
+ } else if (props.image) {
2801
+ this.texture = await Assets2.load(props.image);
2802
+ }
2803
+ if (props.tint !== void 0) {
2804
+ this.tint = props.tint;
2805
+ }
2806
+ if (props.blendMode !== void 0) {
2807
+ this.blendMode = props.blendMode;
2808
+ }
2809
+ if (props.roundPixels !== void 0) {
2810
+ this.roundPixels = props.roundPixels;
2811
+ }
2812
+ }
2813
+ /**
2814
+ * Called when the component is about to be destroyed.
2815
+ * Cleans up the draw effect subscription and calls the parent destroy method.
2816
+ *
2817
+ * @param parent - The parent element
2818
+ * @param afterDestroy - Callback function to execute after destruction
2819
+ * @example
2820
+ * ```typescript
2821
+ * // This method is typically called by the engine internally
2822
+ * await mesh.onDestroy(parentElement, () => console.log('Mesh destroyed'));
2823
+ * ```
2824
+ */
2825
+ async onDestroy(parent, afterDestroy) {
2826
+ const _afterDestroyCallback = async () => {
2827
+ afterDestroy();
2828
+ };
2829
+ await super.onDestroy(parent, _afterDestroyCallback);
2830
+ }
2831
+ };
2832
+ registerComponent("Mesh", CanvasMesh);
2833
+ var Mesh = (props) => {
2834
+ return createComponent("Mesh", props);
2835
+ };
2836
+
2837
+ // src/engine/signal.ts
2838
+ var currentSubscriptionsTracker = null;
2839
+ var mountTracker = null;
2840
+ function mount(fn) {
2841
+ mountTracker?.(fn);
2842
+ }
2843
+ function tick(fn) {
2844
+ mount((el) => {
2845
+ const { context } = el.props;
2846
+ let subscription;
2847
+ if (context.tick) {
2848
+ subscription = context.tick.observable.subscribe(({ value }) => {
2849
+ fn(value, el);
2850
+ });
2851
+ }
2852
+ return () => {
2853
+ subscription?.unsubscribe();
2854
+ };
2855
+ });
2856
+ }
2857
+ function h(componentFunction, props = {}, ...children) {
2858
+ const allSubscriptions = /* @__PURE__ */ new Set();
2859
+ const allMounts = /* @__PURE__ */ new Set();
2860
+ currentSubscriptionsTracker = (subscription) => {
2861
+ allSubscriptions.add(subscription);
2862
+ };
2863
+ mountTracker = (fn) => {
2864
+ allMounts.add(fn);
2865
+ };
2866
+ if (children[0] instanceof Array) {
2867
+ children = children[0];
2868
+ }
2869
+ let component = componentFunction({ ...props, children });
2870
+ if (!component) {
2871
+ component = {};
2872
+ }
2873
+ component.effectSubscriptions = Array.from(allSubscriptions);
2874
+ component.effectMounts = [
2875
+ ...Array.from(allMounts),
2876
+ ...component.effectMounts ?? []
2877
+ ];
2878
+ if (component instanceof Promise) {
2879
+ component.then((component2) => {
2880
+ if (component2.props.isRoot) {
2881
+ allMounts.forEach((fn) => fn(component2));
2882
+ }
2883
+ });
2884
+ }
2885
+ currentSubscriptionsTracker = null;
2886
+ mountTracker = null;
2887
+ return component;
2888
+ }
2889
+
2890
+ // src/components/Scene.ts
2891
+ function Scene(props) {
2892
+ return h(Container4);
2893
+ }
2894
+
2895
+ // src/components/ParticleEmitter.ts
2896
+ import * as particles from "@barvynkoa/particle-emitter";
2897
+ var CanvasParticlesEmitter = class extends CanvasContainer {
2898
+ constructor() {
2899
+ super(...arguments);
2900
+ this.elapsed = Date.now();
2901
+ }
2902
+ async onMount(params) {
2903
+ await super.onMount(params);
2904
+ const { props } = params;
2905
+ const tick2 = props.context.tick;
2906
+ this.emitter = new particles.Emitter(this, props.config);
2907
+ this.subscriptionTick = tick2.observable.subscribe((value) => {
2908
+ if (!this.emitter) return;
2909
+ const now = Date.now();
2910
+ this.emitter.update((now - this.elapsed) * 1e-3);
2911
+ this.elapsed = now;
2912
+ });
2913
+ }
2914
+ onUpdate(props) {
2915
+ }
2916
+ async onDestroy(parent, afterDestroy) {
2917
+ const _afterDestroy = async () => {
2918
+ this.emitter?.destroy();
2919
+ this.emitter = null;
2920
+ this.subscriptionTick.unsubscribe();
2921
+ afterDestroy();
2922
+ };
2923
+ await super.onDestroy(parent, _afterDestroy);
2924
+ }
2925
+ };
2926
+ registerComponent("ParticlesEmitter", CanvasParticlesEmitter);
2927
+ function ParticlesEmitter(props) {
2928
+ return createComponent("ParticlesEmitter", props);
2929
+ }
2930
+
2931
+ // src/components/Sprite.ts
2932
+ import { Howl as Howl2 } from "howler";
2933
+ import { computed, effect as effect6, isSignal as isSignal5 } from "@signe/reactive";
2934
+ import {
2935
+ Assets as Assets3,
2936
+ Container as Container5,
2937
+ Sprite as PixiSprite,
2938
+ Rectangle as Rectangle2,
2939
+ Texture as Texture3
2940
+ } from "pixi.js";
2941
+
2942
+ // src/engine/animation.ts
2943
+ import { effect as effect5, signal as signal7 } from "@signe/reactive";
2944
+ import { animate as animatePopmotion } from "popmotion";
2945
+ function isAnimatedSignal(signal10) {
2946
+ return signal10.animatedState !== void 0;
2947
+ }
2948
+ function animatedSignal(initialValue, options = {}) {
2949
+ const state = {
2950
+ current: initialValue,
2951
+ start: initialValue,
2952
+ end: initialValue
2953
+ };
2954
+ let animation;
2955
+ const publicSignal = signal7(initialValue);
2956
+ const privateSignal = signal7(state);
2957
+ effect5(() => {
2958
+ const currentState = privateSignal();
2959
+ publicSignal.set(currentState.current);
2960
+ });
2961
+ function animatedSignal2(newValue, animationConfig = {}) {
2962
+ if (newValue === void 0) {
2963
+ return privateSignal();
2964
+ }
2965
+ const prevState = privateSignal();
2966
+ const newState = {
2967
+ current: prevState.current,
2968
+ start: prevState.current,
2969
+ end: newValue
2970
+ };
2971
+ privateSignal.set(newState);
2972
+ if (animation) {
2973
+ animation.stop();
2974
+ }
2975
+ animation = animatePopmotion({
2976
+ // TODO
2977
+ duration: 20,
2978
+ ...options,
2979
+ ...animationConfig,
2980
+ from: prevState.current,
2981
+ to: newValue,
2982
+ onUpdate: (value) => {
2983
+ privateSignal.update((s) => ({ ...s, current: value }));
2984
+ if (options.onUpdate) {
2985
+ options.onUpdate(value);
2986
+ }
2987
+ }
2988
+ });
2989
+ }
2990
+ const fn = function() {
2991
+ return privateSignal().current;
2992
+ };
2993
+ for (const key in publicSignal) {
2994
+ fn[key] = publicSignal[key];
2995
+ }
2996
+ fn.animatedState = privateSignal;
2997
+ fn.update = (updater) => {
2998
+ animatedSignal2(updater(privateSignal().current));
2999
+ };
3000
+ fn.set = async (newValue, animationConfig = {}) => {
3001
+ return new Promise((resolve) => {
3002
+ animatedSignal2(newValue, {
3003
+ ...animationConfig,
3004
+ onComplete: resolve
3005
+ });
3006
+ });
3007
+ };
3008
+ return fn;
3009
+ }
3010
+ async function animatedSequence(sequence) {
3011
+ for (const item of sequence) {
3012
+ if (Array.isArray(item)) {
3013
+ await Promise.all(item.map((fn) => fn()));
3014
+ } else {
3015
+ await item();
3016
+ }
3017
+ }
3018
+ }
3019
+
3020
+ // src/components/Sprite.ts
3021
+ var log2 = console.log;
3022
+ var CanvasSprite = class extends DisplayObject(PixiSprite) {
3023
+ constructor() {
3024
+ super(...arguments);
3025
+ this.currentAnimation = null;
3026
+ this.time = 0;
3027
+ this.frameIndex = 0;
3028
+ this.animations = /* @__PURE__ */ new Map();
3029
+ this.subscriptionSheet = [];
3030
+ this.sheetParams = {};
3031
+ this.sheetCurrentAnimation = "stand" /* Stand */;
3032
+ this.app = null;
3033
+ this.currentAnimationContainer = null;
3034
+ }
3035
+ get renderer() {
3036
+ return this.app?.renderer;
3037
+ }
3038
+ async createTextures(options) {
3039
+ const { width, height, framesHeight, framesWidth, image, offset } = options;
3040
+ if (!image || typeof image !== "string" || image.trim() === "") {
3041
+ console.warn("Invalid image path provided to createTextures:", image);
3042
+ return [];
3043
+ }
3044
+ const texture = await Assets3.load(image);
3045
+ const spriteWidth = options.spriteWidth;
3046
+ const spriteHeight = options.spriteHeight;
3047
+ const frames = [];
3048
+ const offsetX = offset && offset.x || 0;
3049
+ const offsetY = offset && offset.y || 0;
3050
+ for (let i = 0; i < framesHeight; i++) {
3051
+ frames[i] = [];
3052
+ for (let j = 0; j < framesWidth; j++) {
3053
+ const rectX = j * spriteWidth + offsetX;
3054
+ const rectY = i * spriteHeight + offsetY;
3055
+ if (rectY > height) {
3056
+ throw log2(
3057
+ `Warning, there is a problem with the height of the "${this.id}" spritesheet. When cutting into frames, the frame exceeds the height of the image.`
3058
+ );
3059
+ }
3060
+ if (rectX > width) {
3061
+ throw log2(
3062
+ `Warning, there is a problem with the width of the "${this.id}" spritesheet. When cutting into frames, the frame exceeds the width of the image.`
3063
+ );
3064
+ }
3065
+ frames[i].push(
3066
+ new Texture3({
3067
+ source: texture.source,
3068
+ frame: new Rectangle2(rectX, rectY, spriteWidth, spriteHeight)
3069
+ })
3070
+ );
3071
+ }
3072
+ }
3073
+ return frames;
3074
+ }
3075
+ async createAnimations() {
3076
+ const { textures } = this.spritesheet;
3077
+ if (!textures) {
3078
+ return;
3079
+ }
3080
+ for (let animationName in textures) {
3081
+ const props = [
3082
+ "width",
3083
+ "height",
3084
+ "framesHeight",
3085
+ "framesWidth",
3086
+ "rectWidth",
3087
+ "rectHeight",
3088
+ "offset",
3089
+ "image",
3090
+ "sound"
3091
+ ];
3092
+ const parentObj = props.reduce(
3093
+ (prev, val) => ({ ...prev, [val]: this.spritesheet[val] }),
3094
+ {}
3095
+ );
3096
+ const optionsTextures = {
3097
+ ...parentObj,
3098
+ ...textures[animationName]
3099
+ };
3100
+ const {
3101
+ rectWidth,
3102
+ width = 0,
3103
+ framesWidth = 1,
3104
+ rectHeight,
3105
+ height = 0,
3106
+ framesHeight = 1
3107
+ } = optionsTextures;
3108
+ optionsTextures.spriteWidth = rectWidth ? rectWidth : width / framesWidth;
3109
+ optionsTextures.spriteHeight = rectHeight ? rectHeight : height / framesHeight;
3110
+ this.animations.set(animationName, {
3111
+ frames: await this.createTextures(
3112
+ optionsTextures
3113
+ ),
3114
+ name: animationName,
3115
+ animations: textures[animationName].animations,
3116
+ params: [],
3117
+ data: optionsTextures,
3118
+ sprites: []
3119
+ });
3120
+ }
3121
+ }
3122
+ async onMount(params) {
3123
+ const { props, propObservables } = params;
3124
+ const tick2 = props.context.tick;
3125
+ const sheet = props.sheet ?? {};
3126
+ this.app = props.context.app();
3127
+ if (sheet?.onFinish) {
3128
+ this.onFinish = sheet.onFinish;
3129
+ }
3130
+ this.subscriptionTick = tick2.observable.subscribe((value) => {
3131
+ this.update(value);
3132
+ });
3133
+ if (props.sheet?.definition) {
3134
+ this.spritesheet = props.sheet.definition;
3135
+ await this.createAnimations();
3136
+ }
3137
+ if (sheet.params) {
3138
+ for (let key in propObservables?.sheet["params"]) {
3139
+ const value = propObservables?.sheet["params"][key];
3140
+ if (isSignal5(value)) {
3141
+ this.subscriptionSheet.push(
3142
+ value.observable.subscribe((value2) => {
3143
+ if (this.animations.size == 0) return;
3144
+ this.play(this.sheetCurrentAnimation, [{ [key]: value2 }]);
3145
+ })
3146
+ );
3147
+ } else {
3148
+ this.play(this.sheetCurrentAnimation, [{ [key]: value }]);
3149
+ }
3150
+ }
3151
+ }
3152
+ const isMoving = computed(() => {
3153
+ const { x, y } = propObservables ?? {};
3154
+ if (!x || !y) return false;
3155
+ const xSignal = x;
3156
+ const ySignal = y;
3157
+ const isMovingX = isAnimatedSignal(xSignal) && xSignal.animatedState().current !== xSignal.animatedState().end;
3158
+ const isMovingY = isAnimatedSignal(ySignal) && ySignal.animatedState().current !== ySignal.animatedState().end;
3159
+ return isMovingX || isMovingY;
3160
+ });
3161
+ effect6(() => {
3162
+ const _isMoving = isMoving();
3163
+ if (!this.isMounted) return;
3164
+ if (_isMoving) {
3165
+ this.sheetCurrentAnimation = "walk" /* Walk */;
3166
+ } else {
3167
+ this.sheetCurrentAnimation = "stand" /* Stand */;
3168
+ }
3169
+ if (this.spritesheet) this.play(this.sheetCurrentAnimation, [this.sheetParams]);
3170
+ });
3171
+ super.onMount(params);
3172
+ }
3173
+ async onUpdate(props) {
3174
+ super.onUpdate(props);
3175
+ const setTexture = async (image) => {
3176
+ if (!image || typeof image !== "string" || image.trim() === "") {
3177
+ console.warn("Invalid image path provided to setTexture:", image);
3178
+ return null;
3179
+ }
3180
+ const onProgress = this.fullProps.loader?.onProgress;
3181
+ const texture = await Assets3.load(image, (progress) => {
3182
+ if (onProgress) onProgress(progress);
3183
+ if (progress == 1) {
3184
+ const onComplete = this.fullProps.loader?.onComplete;
3185
+ if (onComplete) {
3186
+ setTimeout(() => {
3187
+ onComplete(texture);
3188
+ });
3189
+ }
3190
+ }
3191
+ });
3192
+ return texture;
3193
+ };
3194
+ const sheet = props.sheet;
3195
+ if (sheet?.params) this.sheetParams = sheet?.params;
3196
+ if (sheet?.playing && this.isMounted) {
3197
+ this.sheetCurrentAnimation = sheet?.playing;
3198
+ this.play(this.sheetCurrentAnimation, [this.sheetParams]);
3199
+ }
3200
+ if (props.hitbox) this.hitbox = props.hitbox;
3201
+ if (props.scaleMode) this.baseTexture.scaleMode = props.scaleMode;
3202
+ else if (props.image && this.fullProps.rectangle === void 0) {
3203
+ const texture = await setTexture(this.fullProps.image);
3204
+ if (texture) {
3205
+ this.texture = texture;
3206
+ }
3207
+ } else if (props.texture) {
3208
+ if (isElement(props.texture)) {
3209
+ const textureInstance = props.texture.componentInstance;
3210
+ textureInstance.subjectInit.subscribe((value) => {
3211
+ console.log("a", value?.width);
3212
+ });
3213
+ this.texture = this.renderer?.generateTexture(props.texture.componentInstance);
3214
+ } else {
3215
+ this.texture = props.texture;
3216
+ }
3217
+ }
3218
+ if (props.rectangle !== void 0) {
3219
+ const { x, y, width, height } = props.rectangle?.value ?? props.rectangle;
3220
+ const texture = await setTexture(this.fullProps.image);
3221
+ if (texture) {
3222
+ this.texture = new Texture3({
3223
+ source: texture.source,
3224
+ frame: new Rectangle2(x, y, width, height)
3225
+ });
3226
+ }
3227
+ }
3228
+ }
3229
+ async onDestroy(parent, afterDestroy) {
3230
+ await super.onDestroy(parent);
3231
+ this.subscriptionSheet.forEach((sub) => sub.unsubscribe());
3232
+ this.subscriptionTick.unsubscribe();
3233
+ if (this.currentAnimationContainer && this.parent instanceof Container5) {
3234
+ this.parent.removeChild(this.currentAnimationContainer);
3235
+ }
3236
+ }
3237
+ has(name) {
3238
+ return this.animations.has(name);
3239
+ }
3240
+ get(name) {
3241
+ return this.animations.get(name);
3242
+ }
3243
+ isPlaying(name) {
3244
+ if (!name) return !!this.currentAnimation;
3245
+ if (this.currentAnimation == null) return false;
3246
+ return this.currentAnimation.name == name;
3247
+ }
3248
+ stop() {
3249
+ this.currentAnimation = null;
3250
+ this.destroy();
3251
+ }
3252
+ play(name, params = []) {
3253
+ const animParams = this.currentAnimation?.params;
3254
+ if (this.isPlaying(name) && arrayEquals(params, animParams || [])) return;
3255
+ const animation = this.get(name);
3256
+ if (!animation) {
3257
+ throw new Error(
3258
+ `Impossible to play the ${name} animation because it doesn't exist on the "${this.id}" spritesheet`
3259
+ );
3260
+ }
3261
+ const cloneParams = structuredClone(params);
3262
+ this.removeChildren();
3263
+ animation.sprites = [];
3264
+ this.currentAnimation = animation;
3265
+ this.currentAnimation.params = cloneParams;
3266
+ this.time = 0;
3267
+ this.frameIndex = 0;
3268
+ let animations = animation.animations;
3269
+ animations = isFunction(animations) ? animations(...cloneParams) : animations;
3270
+ this.currentAnimationContainer = new Container5();
3271
+ for (let container of animations) {
3272
+ const sprite = new PixiSprite();
3273
+ for (let frame of container) {
3274
+ this.currentAnimation.sprites.push(frame);
3275
+ }
3276
+ this.currentAnimationContainer.addChild(sprite);
3277
+ }
3278
+ const sound = this.currentAnimation.data.sound;
3279
+ if (sound) {
3280
+ new Howl2({
3281
+ src: sound,
3282
+ autoplay: true,
3283
+ loop: false,
3284
+ volume: 1
3285
+ });
3286
+ }
3287
+ this.update({
3288
+ deltaRatio: 1
3289
+ });
3290
+ }
3291
+ update({ deltaRatio }) {
3292
+ if (!this.isPlaying() || !this.currentAnimation || !this.currentAnimationContainer)
3293
+ return;
3294
+ const self = this;
3295
+ const { frames, sprites, data } = this.currentAnimation;
3296
+ let frame = sprites[this.frameIndex];
3297
+ const nextFrame = sprites[this.frameIndex + 1];
3298
+ for (let _sprite of this.currentAnimationContainer.children) {
3299
+ let applyTransformValue = function(prop, alias) {
3300
+ const optionProp = alias || prop;
3301
+ const val = getVal(optionProp);
3302
+ if (val !== void 0) {
3303
+ self[prop] = val;
3304
+ }
3305
+ };
3306
+ const sprite = _sprite;
3307
+ if (!frame || frame.frameY == void 0 || frame.frameX == void 0) {
3308
+ continue;
3309
+ }
3310
+ this.texture = frames[frame.frameY][frame.frameX];
3311
+ const getVal = (prop) => {
3312
+ return frame[prop] ?? data[prop] ?? this.spritesheet[prop];
3313
+ };
3314
+ const applyTransform = (prop) => {
3315
+ const val = getVal(prop);
3316
+ if (val) {
3317
+ this[prop].set(...val);
3318
+ }
3319
+ };
3320
+ if (this.applyTransform) {
3321
+ frame = {
3322
+ ...frame,
3323
+ ...this.applyTransform(frame, data, this.spritesheet)
3324
+ };
3325
+ }
3326
+ const realSize = getVal("spriteRealSize");
3327
+ const heightOfSprite = typeof realSize == "number" ? realSize : realSize?.height;
3328
+ const widthOfSprite = typeof realSize == "number" ? realSize : realSize?.width;
3329
+ const applyAnchorBySize = () => {
3330
+ if (heightOfSprite && this.hitbox) {
3331
+ const { spriteWidth, spriteHeight } = data;
3332
+ const w = (spriteWidth - this.hitbox.w) / 2 / spriteWidth;
3333
+ const gap = (spriteHeight - heightOfSprite) / 2;
3334
+ const h2 = (spriteHeight - this.hitbox.h - gap) / spriteHeight;
3335
+ this.anchor.set(w, h2);
3336
+ }
3337
+ };
3338
+ if (frame.sound) {
3339
+ }
3340
+ applyAnchorBySize();
3341
+ applyTransform("anchor");
3342
+ applyTransform("scale");
3343
+ applyTransform("skew");
3344
+ applyTransform("pivot");
3345
+ applyTransformValue("alpha", "opacity");
3346
+ applyTransformValue("x");
3347
+ applyTransformValue("y");
3348
+ applyTransformValue("angle");
3349
+ applyTransformValue("rotation");
3350
+ applyTransformValue("visible");
3351
+ }
3352
+ if (!nextFrame) {
3353
+ this.time = 0;
3354
+ this.frameIndex = 0;
3355
+ if (this.onFinish && sprites.length > 1) this.onFinish();
3356
+ return;
3357
+ }
3358
+ this.time += deltaRatio ?? 1;
3359
+ if (this.time >= nextFrame.time) {
3360
+ this.frameIndex++;
3361
+ }
3362
+ }
3363
+ };
3364
+ registerComponent("Sprite", CanvasSprite);
3365
+ var Sprite2 = (props) => {
3366
+ return createComponent("Sprite", props);
3367
+ };
3368
+
3369
+ // src/components/Video.ts
3370
+ import { effect as effect7, signal as signal8 } from "@signe/reactive";
3371
+ function Video(props) {
3372
+ const eventsMap = {
3373
+ audioprocess: null,
3374
+ canplay: null,
3375
+ canplaythrough: null,
3376
+ complete: null,
3377
+ durationchange: null,
3378
+ emptied: null,
3379
+ ended: null,
3380
+ loadeddata: null,
3381
+ loadedmetadata: null,
3382
+ pause: null,
3383
+ play: null,
3384
+ playing: null,
3385
+ progress: null,
3386
+ ratechange: null,
3387
+ seeked: null,
3388
+ seeking: null,
3389
+ stalled: null,
3390
+ suspend: null,
3391
+ timeupdate: null,
3392
+ volumechange: null,
3393
+ waiting: null
3394
+ };
3395
+ const video = signal8(null);
3396
+ const defineProps = useDefineProps(props);
3397
+ const { play, loop: loop2, muted } = defineProps({
3398
+ play: {
3399
+ type: Boolean,
3400
+ default: true
3401
+ },
3402
+ loop: {
3403
+ type: Boolean,
3404
+ default: false
3405
+ },
3406
+ muted: {
3407
+ type: Boolean,
3408
+ default: false
3409
+ }
3410
+ });
3411
+ effect7(() => {
3412
+ const _video = video();
3413
+ const state = play();
3414
+ if (_video && state !== void 0) {
3415
+ if (state) {
3416
+ _video.play();
3417
+ } else {
3418
+ _video.pause();
3419
+ }
3420
+ }
3421
+ if (_video && loop2()) {
3422
+ _video.loop = loop2();
3423
+ }
3424
+ if (_video && muted()) {
3425
+ _video.muted = muted();
3426
+ }
3427
+ });
3428
+ mount(() => {
3429
+ return () => {
3430
+ for (let event in eventsMap) {
3431
+ if (eventsMap[event]) {
3432
+ video().removeEventListener(event, eventsMap[event]);
3433
+ }
3434
+ }
3435
+ };
3436
+ });
3437
+ return h(Sprite2, {
3438
+ ...props,
3439
+ image: props.src,
3440
+ loader: {
3441
+ onComplete: (texture) => {
3442
+ const source = texture.source.resource;
3443
+ video.set(source);
3444
+ if (props?.loader?.onComplete) {
3445
+ props.loader.onComplete(texture);
3446
+ }
3447
+ for (let event in eventsMap) {
3448
+ if (props[event]) {
3449
+ const cb = (ev) => {
3450
+ props[event](ev);
3451
+ };
3452
+ eventsMap[event] = cb;
3453
+ source.addEventListener(event, cb);
3454
+ }
3455
+ }
3456
+ }
3457
+ }
3458
+ });
3459
+ }
3460
+
3461
+ // src/components/Text.ts
3462
+ import { Text as PixiText } from "pixi.js";
3463
+
3464
+ // src/engine/trigger.ts
3465
+ import { effect as effect8, signal as signal9 } from "@signe/reactive";
3466
+ function isTrigger(arg) {
3467
+ return arg?.start && arg?.listen;
3468
+ }
3469
+ function trigger(globalConfig) {
3470
+ const _signal = signal9({
3471
+ config: globalConfig,
3472
+ value: 0,
3473
+ resolve: (value) => void 0
3474
+ });
3475
+ return {
3476
+ start: (config) => {
3477
+ return new Promise((resolve) => {
3478
+ _signal.set({
3479
+ config: {
3480
+ ...globalConfig,
3481
+ ...config
3482
+ },
3483
+ resolve,
3484
+ value: Math.random()
3485
+ });
3486
+ });
3487
+ },
3488
+ listen: () => {
3489
+ return {
3490
+ config: globalConfig,
3491
+ seed: _signal()
3492
+ };
3493
+ }
3494
+ };
3495
+ }
3496
+ function on(triggerSignal, callback) {
3497
+ if (!isTrigger(triggerSignal)) {
3498
+ throw new Error("In 'on(arg)' must have a trigger signal type");
3499
+ }
3500
+ effect8(() => {
3501
+ const result = triggerSignal.listen();
3502
+ if (result?.seed.value) {
3503
+ const ret = callback(result?.seed.config);
3504
+ if (ret && typeof ret.then === "function") {
3505
+ ret.then(result?.seed.resolve);
3506
+ }
3507
+ }
3508
+ });
3509
+ }
3510
+
3511
+ // src/components/Text.ts
3512
+ var CanvasText = class extends DisplayObject(PixiText) {
3513
+ constructor() {
3514
+ super(...arguments);
3515
+ this.fullText = "";
3516
+ this.currentIndex = 0;
3517
+ this.typewriterSpeed = 1;
3518
+ // Default speed
3519
+ this._wordWrapWidth = 0;
3520
+ this.typewriterOptions = {};
3521
+ }
3522
+ /**
3523
+ * Called when the component is mounted to the scene graph.
3524
+ * Initializes the typewriter effect if configured.
3525
+ * @param {Element<CanvasText>} element - The element being mounted with parent and props.
3526
+ * @param {number} [index] - The index of the component among its siblings.
3527
+ */
3528
+ async onMount(element, index) {
3529
+ const { props } = element;
3530
+ await super.onMount(element, index);
3531
+ const tick2 = props.context.tick;
3532
+ if (props.text && props.typewriter) {
3533
+ this.fullText = props.text;
3534
+ this.text = "";
3535
+ this.currentIndex = 0;
3536
+ if (props.typewriter) {
3537
+ this.typewriterOptions = props.typewriter;
3538
+ if (this.typewriterOptions.skip && isTrigger(this.typewriterOptions.skip)) {
3539
+ on(this.typewriterOptions.skip, () => {
3540
+ this.skipTypewriter();
3541
+ });
3542
+ }
3543
+ }
3544
+ }
3545
+ this.subscriptionTick = tick2.observable.subscribe(() => {
3546
+ if (props.typewriter) {
3547
+ this.typewriterEffect();
3548
+ }
3549
+ });
3550
+ }
3551
+ onUpdate(props) {
3552
+ super.onUpdate(props);
3553
+ if (props.typewriter) {
3554
+ if (props.typewriter) {
3555
+ this.typewriterOptions = props.typewriter;
3556
+ }
3557
+ }
3558
+ if (props.text !== void 0) {
3559
+ this.text = "" + props.text;
3560
+ }
3561
+ if (props.text !== void 0 && props.text !== this.fullText && this.fullProps.typewriter) {
3562
+ this.text = "";
3563
+ this.currentIndex = 0;
3564
+ this.fullText = props.text;
3565
+ }
3566
+ if (props.style) {
3567
+ for (const key in props.style) {
3568
+ this.style[key] = props.style[key];
3569
+ }
3570
+ if (props.style.wordWrapWidth) {
3571
+ this._wordWrapWidth = props.style.wordWrapWidth;
3572
+ }
3573
+ }
3574
+ if (props.color) {
3575
+ this.style.fill = props.color;
3576
+ }
3577
+ if (props.size) {
3578
+ this.style.fontSize = props.size;
3579
+ }
3580
+ if (props.fontFamily) {
3581
+ this.style.fontFamily = props.fontFamily;
3582
+ }
3583
+ if (this._wordWrapWidth) {
3584
+ this.setWidth(this._wordWrapWidth);
3585
+ } else {
3586
+ this.setWidth(this.width);
3587
+ }
3588
+ this.setHeight(this.height);
3589
+ }
3590
+ get onCompleteCallback() {
3591
+ return this.typewriterOptions.onComplete;
3592
+ }
3593
+ typewriterEffect() {
3594
+ if (this.currentIndex < this.fullText.length) {
3595
+ const nextIndex = Math.min(
3596
+ this.currentIndex + (this.typewriterOptions.speed ?? 1),
3597
+ this.fullText.length
3598
+ );
3599
+ this.text = this.fullText.slice(0, nextIndex);
3600
+ this.currentIndex = nextIndex;
3601
+ if (this.currentIndex === this.fullText.length && this.onCompleteCallback) {
3602
+ this.onCompleteCallback();
3603
+ }
3604
+ }
3605
+ }
3606
+ // Add a method to skip the typewriter effect
3607
+ skipTypewriter() {
3608
+ if (this.skipSignal) {
3609
+ this.skipSignal();
3610
+ }
3611
+ this.text = this.fullText;
3612
+ this.currentIndex = this.fullText.length;
3613
+ }
3614
+ /**
3615
+ * Called when the component is about to be destroyed.
3616
+ * Unsubscribes from the tick observable.
3617
+ * @param {Element<any>} parent - The parent element.
3618
+ * @param {() => void} [afterDestroy] - An optional callback function to be executed after the component's own destruction logic.
3619
+ */
3620
+ async onDestroy(parent, afterDestroy) {
3621
+ const _afterDestroy = async () => {
3622
+ if (this.subscriptionTick) {
3623
+ this.subscriptionTick.unsubscribe();
3624
+ }
3625
+ if (afterDestroy) {
3626
+ afterDestroy();
3627
+ }
3628
+ };
3629
+ await super.onDestroy(parent, _afterDestroy);
3630
+ }
3631
+ };
3632
+ registerComponent("Text", CanvasText);
3633
+ function Text(props) {
3634
+ return createComponent("Text", props);
3635
+ }
3636
+
3637
+ // src/components/TilingSprite.ts
3638
+ import { TilingSprite as PixiTilingSprite, Texture as Texture4 } from "pixi.js";
3639
+ var CanvasTilingSprite = class extends DisplayObject(PixiTilingSprite) {
3640
+ onUpdate(props) {
3641
+ super.onUpdate(props);
3642
+ if (props.image) {
3643
+ this.texture = Texture4.from(props.image);
3644
+ }
3645
+ if (props.tileScale) {
3646
+ this.tileScale.set(props.tileScale.x, props.tileScale.y);
3647
+ }
3648
+ if (props.tilePosition) {
3649
+ this.tilePosition.set(props.tilePosition.x, props.tilePosition.y);
3650
+ }
3651
+ if (props.width !== void 0) {
3652
+ this.width = props.width;
3653
+ }
3654
+ if (props.height !== void 0) {
3655
+ this.height = props.height;
3656
+ }
3657
+ }
3658
+ };
3659
+ registerComponent("TilingSprite", CanvasTilingSprite);
3660
+ function TilingSprite(props) {
3661
+ return createComponent("TilingSprite", props);
3662
+ }
3663
+
3664
+ // src/components/Viewport.ts
3665
+ import { Viewport as PixiViewport } from "pixi-viewport";
3666
+ import { effect as effect9 } from "@signe/reactive";
3667
+ var EVENTS3 = [
3668
+ "bounce-x-end",
3669
+ "bounce-x-start",
3670
+ "bounce-y-end",
3671
+ "bounce-y-start",
3672
+ "clicked",
3673
+ "drag-end",
3674
+ "drag-start",
3675
+ "frame-end",
3676
+ "mouse-edge-end",
3677
+ "mouse-edge-start",
3678
+ "moved",
3679
+ "moved-end",
3680
+ "pinch-end",
3681
+ "pinch-start",
3682
+ "snap-end",
3683
+ "snap-start",
3684
+ "snap-zoom-end",
3685
+ "snap-zoom-start",
3686
+ "wheel-scroll",
3687
+ "zoomed",
3688
+ "zoomed-end"
3689
+ ];
3690
+ var CanvasViewport = class extends DisplayObject(PixiViewport) {
3691
+ constructor() {
3692
+ const defaultOptions = {
3693
+ noTicker: true,
3694
+ events: {
3695
+ domElement: {
3696
+ addEventListener: () => {
3697
+ }
3698
+ }
3699
+ }
3700
+ };
3701
+ super(defaultOptions);
3702
+ this.overrideProps = ["wheel"];
3703
+ }
3704
+ onInit(props) {
3705
+ super.onInit(props);
3706
+ for (let event of EVENTS3) {
3707
+ if (props[event]) this.on(event, props[event]);
3708
+ }
3709
+ }
3710
+ /**
3711
+ * Called when the component is mounted to the scene graph.
3712
+ * Initializes viewport settings and subscriptions.
3713
+ * @param {Element<CanvasViewport>} element - The element being mounted. Its `props` property (of type ViewportProps) contains component properties and context.
3714
+ * @param {number} [index] - The index of the component among its siblings.
3715
+ */
3716
+ async onMount(element, index) {
3717
+ await super.onMount(element, index);
3718
+ const { props } = element;
3719
+ const { tick: tick2, app, canvasSize } = props.context;
3720
+ let isDragging = false;
3721
+ effect9(() => {
3722
+ this.screenWidth = canvasSize().width;
3723
+ this.screenHeight = canvasSize().height;
3724
+ });
3725
+ effect9(() => {
3726
+ const _app = app();
3727
+ if (!_app) return;
3728
+ const renderer = _app.renderer;
3729
+ renderer.events.domElement.addEventListener(
3730
+ "wheel",
3731
+ this.input.wheelFunction
3732
+ );
3733
+ this.options.events = renderer.events;
3734
+ });
3735
+ this.tickSubscription = tick2.observable.subscribe(({ value }) => {
3736
+ this.update(value.timestamp);
3737
+ });
3738
+ element.props.context.viewport = this;
3739
+ this.updateViewportSettings(props);
3740
+ }
3741
+ onUpdate(props) {
3742
+ super.onUpdate(props);
3743
+ this.updateViewportSettings(props);
3744
+ }
3745
+ updateViewportSettings(props) {
3746
+ if (props.screenWidth !== void 0) {
3747
+ this.screenWidth = props.screenWidth;
3748
+ }
3749
+ if (props.screenHeight !== void 0) {
3750
+ this.screenHeight = props.screenHeight;
3751
+ }
3752
+ if (props.worldWidth !== void 0) {
3753
+ this.worldWidth = props.worldWidth;
3754
+ }
3755
+ if (props.worldHeight !== void 0) {
3756
+ this.worldHeight = props.worldHeight;
3757
+ }
3758
+ if (props.drag) {
3759
+ this.drag(props.drag);
3760
+ }
3761
+ if (props.clamp) {
3762
+ this.clamp(props.clamp.value ?? props.clamp);
3763
+ }
3764
+ if (props.wheel) {
3765
+ if (props.wheel === true) {
3766
+ this.wheel();
3767
+ } else {
3768
+ this.wheel(props.wheel);
3769
+ }
3770
+ }
3771
+ if (props.decelerate) {
3772
+ if (props.decelerate === true) {
3773
+ this.decelerate();
3774
+ } else {
3775
+ this.decelerate(props.decelerate);
3776
+ }
3777
+ }
3778
+ if (props.pinch) {
3779
+ if (props.pinch === true) {
3780
+ this.pinch();
3781
+ } else {
3782
+ this.pinch(props.pinch);
3783
+ }
3784
+ }
3785
+ }
3786
+ /**
3787
+ * Called when the component is about to be destroyed.
3788
+ * Unsubscribes from the tick observable.
3789
+ * @param {Element<any>} parent - The parent element.
3790
+ * @param {() => void} [afterDestroy] - An optional callback function to be executed after the component's own destruction logic.
3791
+ */
3792
+ async onDestroy(parent, afterDestroy) {
3793
+ const _afterDestroy = async () => {
3794
+ this.tickSubscription.unsubscribe();
3795
+ afterDestroy();
3796
+ };
3797
+ await super.onDestroy(parent, _afterDestroy);
3798
+ }
3799
+ };
3800
+ registerComponent("Viewport", CanvasViewport);
3801
+ function Viewport(props) {
3802
+ return createComponent("Viewport", props);
3803
+ }
3804
+
3805
+ // src/components/NineSliceSprite.ts
3806
+ import { Assets as Assets4, NineSliceSprite as PixiNineSliceSprite } from "pixi.js";
3807
+ var CanvasNineSliceSprite = class extends DisplayObject(PixiNineSliceSprite) {
3808
+ constructor() {
3809
+ super({
3810
+ width: 0,
3811
+ height: 0
3812
+ });
3813
+ }
3814
+ async onUpdate(props) {
3815
+ for (const [key, value] of Object.entries(props)) {
3816
+ if (value !== void 0) {
3817
+ if (key === "image") {
3818
+ this.texture = await Assets4.load(value);
3819
+ } else if (key in this) {
3820
+ this[key] = value;
3821
+ }
3822
+ }
3823
+ }
3824
+ }
3825
+ };
3826
+ registerComponent("NineSliceSprite", CanvasNineSliceSprite);
3827
+ function NineSliceSprite(props) {
3828
+ return createComponent("NineSliceSprite", props);
3829
+ }
3830
+
3831
+ // src/components/DOMContainer.ts
3832
+ import { DOMContainer as PixiDOMContainer } from "pixi.js";
3833
+ var EVENTS4 = [
3834
+ "click",
3835
+ "mouseover",
3836
+ "mouseout",
3837
+ "mouseenter",
3838
+ "mouseleave",
3839
+ "mousemove",
3840
+ "mouseup",
3841
+ "mousedown",
3842
+ "touchstart",
3843
+ "touchend",
3844
+ "touchmove",
3845
+ "touchcancel",
3846
+ "wheel",
3847
+ "scroll",
3848
+ "resize",
3849
+ "focus",
3850
+ "blur",
3851
+ "change",
3852
+ "input",
3853
+ "submit",
3854
+ "reset",
3855
+ "keydown",
3856
+ "keyup",
3857
+ "keypress",
3858
+ "contextmenu",
3859
+ "drag",
3860
+ "dragend",
3861
+ "dragenter",
3862
+ "dragleave",
3863
+ "dragover",
3864
+ "drop",
3865
+ "dragstart",
3866
+ "select",
3867
+ "selectstart",
3868
+ "selectend",
3869
+ "selectall",
3870
+ "selectnone"
3871
+ ];
3872
+ var CanvasDOMContainer = class extends DisplayObject(PixiDOMContainer) {
3873
+ constructor() {
3874
+ super(...arguments);
3875
+ this.disableLayout = true;
3876
+ this.eventListeners = /* @__PURE__ */ new Map();
3877
+ }
3878
+ onInit(props) {
3879
+ super.onInit(props);
3880
+ if (props.element === void 0) {
3881
+ throw new Error("DOMContainer: element is required");
3882
+ }
3883
+ if (typeof props.element === "string") {
3884
+ this.element = document.createElement(props.element);
3885
+ } else {
3886
+ this.element = props.element.value;
3887
+ }
3888
+ for (const event of EVENTS4) {
3889
+ if (props.attrs?.[event]) {
3890
+ const eventHandler = (e) => {
3891
+ props.attrs[event]?.(e);
3892
+ };
3893
+ this.eventListeners.set(event, eventHandler);
3894
+ this.element.addEventListener(event, eventHandler, false);
3895
+ }
3896
+ }
3897
+ }
3898
+ onUpdate(props) {
3899
+ super.onUpdate(props);
3900
+ for (const [key, value] of Object.entries(props.attrs || {})) {
3901
+ if (key === "class") {
3902
+ const classList = value.items || value.value || value;
3903
+ this.element.className = "";
3904
+ if (typeof classList === "string") {
3905
+ this.element.className = classList;
3906
+ } else if (Array.isArray(classList)) {
3907
+ this.element.classList.add(...classList);
3908
+ } else if (typeof classList === "object" && classList !== null) {
3909
+ for (const [className, shouldAdd] of Object.entries(classList)) {
3910
+ if (shouldAdd) {
3911
+ this.element.classList.add(className);
3912
+ }
3913
+ }
3914
+ }
3915
+ } else if (key === "style") {
3916
+ const styleValue = value.items || value.value || value;
3917
+ if (typeof styleValue === "string") {
3918
+ this.element.setAttribute("style", styleValue);
3919
+ } else if (typeof styleValue === "object" && styleValue !== null) {
3920
+ for (const [styleProp, styleVal] of Object.entries(styleValue)) {
3921
+ if (styleVal !== null && styleVal !== void 0) {
3922
+ this.element.style[styleProp] = styleVal;
3923
+ }
3924
+ }
3925
+ }
3926
+ } else if (!EVENTS4.includes(key)) {
3927
+ this.element.setAttribute(key, value);
3928
+ }
3929
+ }
3930
+ if (props.textContent) {
3931
+ this.element.textContent = props.textContent;
3932
+ }
3933
+ if (props.sortableChildren !== void 0) {
3934
+ this.sortableChildren = props.sortableChildren;
3935
+ }
3936
+ }
3937
+ async onDestroy(parent, afterDestroy) {
3938
+ if (this.element) {
3939
+ for (const [event, handler] of this.eventListeners) {
3940
+ this.element.removeEventListener(event, handler, false);
3941
+ }
3942
+ this.eventListeners.clear();
3943
+ }
3944
+ const _afterDestroyCallback = async () => {
3945
+ afterDestroy();
3946
+ };
3947
+ await super.onDestroy(parent, _afterDestroyCallback);
3948
+ }
3949
+ };
3950
+ registerComponent("DOMContainer", CanvasDOMContainer);
3951
+ var DOMContainer = (props) => {
3952
+ return createComponent("DOMContainer", props);
3953
+ };
3954
+
3955
+ // src/engine/bootstrap.ts
3956
+ import "@pixi/layout";
3957
+ import { Application as Application3 } from "pixi.js";
3958
+ var bootstrapCanvas = async (rootElement, canvas) => {
3959
+ const app = new Application3();
3960
+ await app.init({
3961
+ resizeTo: rootElement,
3962
+ autoStart: false
3963
+ });
3964
+ const canvasElement = await h(canvas);
3965
+ if (canvasElement.tag != "Canvas") {
3966
+ throw new Error("Canvas is required");
3967
+ }
3968
+ canvasElement.render(rootElement, app);
3969
+ return {
3970
+ canvasElement,
3971
+ app
3972
+ };
3973
+ };
3974
+
3975
+ // src/utils/Ease.ts
3976
+ import {
3977
+ linear,
3978
+ easeIn,
3979
+ easeInOut,
3980
+ easeOut,
3981
+ circIn,
3982
+ circInOut,
3983
+ circOut,
3984
+ backIn,
3985
+ backInOut,
3986
+ backOut,
3987
+ anticipate,
3988
+ bounceIn,
3989
+ bounceInOut,
3990
+ bounceOut
3991
+ } from "popmotion";
3992
+ var Easing = {
3993
+ linear,
3994
+ easeIn,
3995
+ easeInOut,
3996
+ easeOut,
3997
+ circIn,
3998
+ circInOut,
3999
+ circOut,
4000
+ backIn,
4001
+ backInOut,
4002
+ backOut,
4003
+ anticipate,
4004
+ bounceIn,
4005
+ bounceInOut,
4006
+ bounceOut
4007
+ };
4008
+
4009
+ // src/utils/RadialGradient.ts
4010
+ import { Texture as Texture6, ImageSource, DOMAdapter, Matrix } from "pixi.js";
4011
+ var RadialGradient = class {
4012
+ /**
4013
+ * Creates a new RadialGradient instance
4014
+ * @param x0 - The x-coordinate of the starting circle
4015
+ * @param y0 - The y-coordinate of the starting circle
4016
+ * @param x1 - The x-coordinate of the ending circle
4017
+ * @param y1 - The y-coordinate of the ending circle
4018
+ * @param x2 - The x-coordinate for gradient transformation
4019
+ * @param y2 - The y-coordinate for gradient transformation
4020
+ * @param focalPoint - The focal point of the gradient (0-1), defaults to 0
4021
+ */
4022
+ constructor(x0, y0, x1, y1, x2, y2, focalPoint = 0) {
4023
+ this.x0 = x0;
4024
+ this.y0 = y0;
4025
+ this.x1 = x1;
4026
+ this.y1 = y1;
4027
+ this.x2 = x2;
4028
+ this.y2 = y2;
4029
+ this.focalPoint = focalPoint;
4030
+ this.gradient = null;
4031
+ this.texture = null;
4032
+ this.size = 600;
4033
+ this.size = x0;
4034
+ const halfSize = this.size * 0.5;
4035
+ this.canvas = DOMAdapter.get().createCanvas();
4036
+ this.canvas.width = this.size;
4037
+ this.canvas.height = this.size;
4038
+ this.ctx = this.canvas.getContext("2d");
4039
+ if (this.ctx) {
4040
+ this.gradient = this.ctx.createRadialGradient(
4041
+ halfSize * (1 - focalPoint),
4042
+ halfSize,
4043
+ 0,
4044
+ halfSize,
4045
+ halfSize,
4046
+ halfSize - 0.5
4047
+ );
4048
+ }
4049
+ }
4050
+ /**
4051
+ * Adds a color stop to the gradient
4052
+ * @param offset - The position of the color stop (0-1)
4053
+ * @param color - The color value (any valid CSS color string)
4054
+ */
4055
+ addColorStop(offset, color) {
4056
+ if (this.gradient) {
4057
+ this.gradient.addColorStop(offset, color);
4058
+ }
4059
+ }
4060
+ /**
4061
+ * Renders the gradient and returns the texture with its transformation matrix
4062
+ * @param options - Render options
4063
+ * @param options.translate - Optional translation coordinates
4064
+ * @returns Object containing the texture and transformation matrix
4065
+ */
4066
+ render({ translate } = {}) {
4067
+ const { x0, y0, x1, y1, x2, y2, focalPoint } = this;
4068
+ const defaultSize = this.size;
4069
+ if (this.ctx && this.gradient) {
4070
+ this.ctx.fillStyle = this.gradient;
4071
+ this.ctx.fillRect(0, 0, defaultSize, defaultSize);
4072
+ this.texture = new Texture6({
4073
+ source: new ImageSource({
4074
+ resource: this.canvas,
4075
+ addressModeU: "clamp-to-edge",
4076
+ addressModeV: "clamp-to-edge"
4077
+ })
4078
+ });
4079
+ const m = new Matrix();
4080
+ const dx = Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
4081
+ const dy = Math.sqrt((x2 - x0) * (x2 - x0) + (y2 - y0) * (y2 - y0));
4082
+ const angle = Math.atan2(y1 - y0, x1 - x0);
4083
+ const scaleX = dx / defaultSize;
4084
+ const scaleY = dy / defaultSize;
4085
+ m.rotate(-angle);
4086
+ m.scale(scaleX, scaleY);
4087
+ if (translate) {
4088
+ m.translate(translate.x, translate.y);
4089
+ }
4090
+ this.transform = m;
4091
+ }
4092
+ return {
4093
+ texture: this.texture,
4094
+ matrix: this.transform
4095
+ };
4096
+ }
4097
+ };
4098
+
4099
+ // src/index.ts
4100
+ import { isObservable } from "rxjs";
4101
+ import * as Howl3 from "howler";
4102
+ export {
4103
+ Canvas2 as Canvas,
4104
+ Circle,
4105
+ Container4 as Container,
4106
+ DOMContainer,
4107
+ DisplayObject,
4108
+ EVENTS2 as EVENTS,
4109
+ Easing,
4110
+ Ellipse,
4111
+ Graphics,
4112
+ Howl3 as Howl,
4113
+ Howler,
4114
+ Mesh,
4115
+ NineSliceSprite,
4116
+ ParticlesEmitter,
4117
+ RadialGradient,
4118
+ Rect,
4119
+ Scene,
4120
+ Sprite2 as Sprite,
4121
+ Svg,
4122
+ Text,
4123
+ TilingSprite,
4124
+ Triangle,
4125
+ utils_exports as Utils,
4126
+ Video,
4127
+ Viewport,
4128
+ animatedSequence,
4129
+ animatedSignal,
4130
+ bootstrapCanvas,
4131
+ cond,
4132
+ createComponent,
4133
+ currentSubscriptionsTracker,
4134
+ h,
4135
+ isAnimatedSignal,
4136
+ isElement,
4137
+ isObservable,
4138
+ isPrimitive,
4139
+ isTrigger,
4140
+ loop,
4141
+ mount,
4142
+ mountTracker,
4143
+ on,
4144
+ registerComponent,
4145
+ tick,
4146
+ trigger,
4147
+ useDefineProps,
4148
+ useProps
4149
+ };
4150
+ //# sourceMappingURL=index.js.map