canvasengine 2.0.0-beta.2 → 2.0.0-beta.21

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