canvasengine 2.0.0-beta.2 → 2.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2951 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ 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);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+
10
+ // src/engine/directive.ts
11
+ var directives = {};
12
+ var Directive = class {
13
+ };
14
+ function registerDirective(name, directive) {
15
+ directives[name] = directive;
16
+ }
17
+ function applyDirective(element, directiveName) {
18
+ if (!directives[directiveName]) {
19
+ return null;
20
+ }
21
+ const directive = new directives[directiveName]();
22
+ directive.onInit?.(element);
23
+ return directive;
24
+ }
25
+
26
+ // src/engine/utils.ts
27
+ function isBrowser() {
28
+ return typeof window !== "undefined";
29
+ }
30
+ function preciseNow() {
31
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
32
+ }
33
+ function fps2ms(fps) {
34
+ return 1e3 / fps;
35
+ }
36
+ function isPromise(value) {
37
+ return value && value instanceof Promise;
38
+ }
39
+ function arrayEquals(a, b) {
40
+ if (a.length !== b.length) return false;
41
+ for (let i = 0; i < a.length; i++) {
42
+ const v = a[i];
43
+ const bv = b[i];
44
+ if (typeof v === "object" && v !== null) {
45
+ if (typeof bv !== "object" || bv === null) return false;
46
+ if (Array.isArray(v)) {
47
+ if (!Array.isArray(bv) || !arrayEquals(v, bv)) return false;
48
+ } else if (!objectEquals(v, bv)) {
49
+ return false;
50
+ }
51
+ } else if (v !== bv) {
52
+ return false;
53
+ }
54
+ }
55
+ return true;
56
+ }
57
+ function objectEquals(a, b) {
58
+ const keysA = Object.keys(a);
59
+ const keysB = Object.keys(b);
60
+ if (keysA.length !== keysB.length) return false;
61
+ for (let key of keysA) {
62
+ if (!b.hasOwnProperty(key)) return false;
63
+ if (!deepEquals(a[key], b[key])) return false;
64
+ }
65
+ return true;
66
+ }
67
+ function deepEquals(a, b) {
68
+ if (a === b) return true;
69
+ if (typeof a !== typeof b) return false;
70
+ if (typeof a === "object" && a !== null) {
71
+ if (Array.isArray(a)) {
72
+ return Array.isArray(b) && arrayEquals(a, b);
73
+ }
74
+ return objectEquals(a, b);
75
+ }
76
+ return false;
77
+ }
78
+ function isFunction(val) {
79
+ return {}.toString.call(val) === "[object Function]";
80
+ }
81
+ function isObject(val) {
82
+ return typeof val == "object" && val != null && !Array.isArray(val);
83
+ }
84
+ function set(obj, path, value, onlyPlainObject = false) {
85
+ if (Object(obj) !== obj) return obj;
86
+ if (typeof path === "string") {
87
+ path = path.split(".");
88
+ }
89
+ let len = path.length;
90
+ if (!len) return obj;
91
+ let current = obj;
92
+ for (let i = 0; i < len - 1; i++) {
93
+ let segment = path[i];
94
+ let nextSegment = path[i + 1];
95
+ let isNextNumeric = !isNaN(nextSegment) && isFinite(nextSegment);
96
+ if (!current[segment] || typeof current[segment] !== "object") {
97
+ current[segment] = isNextNumeric && !onlyPlainObject ? [] : {};
98
+ }
99
+ current = current[segment];
100
+ }
101
+ current[path[len - 1]] = value;
102
+ return obj;
103
+ }
104
+ function error(text) {
105
+ console.error(text);
106
+ }
107
+ function setObservablePoint(observablePoint, point) {
108
+ if (typeof point === "number") {
109
+ observablePoint.set(point);
110
+ } else if (Array.isArray(point)) {
111
+ observablePoint.set(point[0], point[1]);
112
+ } else {
113
+ observablePoint.set(point.x, point.y);
114
+ }
115
+ }
116
+ function calculateDistance(x1, y1, x2, y2) {
117
+ const dx = x1 - x2;
118
+ const dy = y1 - y2;
119
+ return Math.sqrt(dx * dx + dy * dy);
120
+ }
121
+
122
+ // src/directives/KeyboardControls.ts
123
+ var keyCodeTable = {
124
+ 3: "break",
125
+ 8: "backspace",
126
+ // backspace / delete
127
+ 9: "tab",
128
+ 12: "clear",
129
+ 13: "enter",
130
+ 16: "shift",
131
+ 17: "ctrl",
132
+ 18: "alt",
133
+ 19: "pause/break",
134
+ 20: "caps lock",
135
+ 27: "escape",
136
+ 28: "conversion",
137
+ 29: "non-conversion",
138
+ 32: "space",
139
+ 33: "page up",
140
+ 34: "page down",
141
+ 35: "end",
142
+ 36: "home",
143
+ 37: "left",
144
+ 38: "up",
145
+ 39: "right",
146
+ 40: "down",
147
+ 41: "select",
148
+ 42: "print",
149
+ 43: "execute",
150
+ 44: "Print Screen",
151
+ 45: "insert",
152
+ 46: "delete",
153
+ 48: "n0",
154
+ 49: "n1",
155
+ 50: "n2",
156
+ 51: "n3",
157
+ 52: "n4",
158
+ 53: "n5",
159
+ 54: "n6",
160
+ 55: "n7",
161
+ 56: "n8",
162
+ 57: "n9",
163
+ 58: ":",
164
+ 59: "semicolon (firefox), equals",
165
+ 60: "<",
166
+ 61: "equals (firefox)",
167
+ 63: "\xDF",
168
+ 64: "@",
169
+ 65: "a",
170
+ 66: "b",
171
+ 67: "c",
172
+ 68: "d",
173
+ 69: "e",
174
+ 70: "f",
175
+ 71: "g",
176
+ 72: "h",
177
+ 73: "i",
178
+ 74: "j",
179
+ 75: "k",
180
+ 76: "l",
181
+ 77: "m",
182
+ 78: "n",
183
+ 79: "o",
184
+ 80: "p",
185
+ 81: "q",
186
+ 82: "r",
187
+ 83: "s",
188
+ 84: "t",
189
+ 85: "u",
190
+ 86: "v",
191
+ 87: "w",
192
+ 88: "x",
193
+ 89: "y",
194
+ 90: "z",
195
+ 91: "Windows Key / Left \u2318 / Chromebook Search key",
196
+ 92: "right window key",
197
+ 93: "Windows Menu / Right \u2318",
198
+ 96: "numpad 0",
199
+ 97: "numpad 1",
200
+ 98: "numpad 2",
201
+ 99: "numpad 3",
202
+ 100: "numpad 4",
203
+ 101: "numpad 5",
204
+ 102: "numpad 6",
205
+ 103: "numpad 7",
206
+ 104: "numpad 8",
207
+ 105: "numpad 9",
208
+ 106: "multiply",
209
+ 107: "add",
210
+ 108: "numpad period (firefox)",
211
+ 109: "subtract",
212
+ 110: "decimal point",
213
+ 111: "divide",
214
+ 112: "f1",
215
+ 113: "f2",
216
+ 114: "f3",
217
+ 115: "f4",
218
+ 116: "f5",
219
+ 117: "f6",
220
+ 118: "f7",
221
+ 119: "f8",
222
+ 120: "f9",
223
+ 121: "f10",
224
+ 122: "f11",
225
+ 123: "f12",
226
+ 124: "f13",
227
+ 125: "f14",
228
+ 126: "f15",
229
+ 127: "f16",
230
+ 128: "f17",
231
+ 129: "f18",
232
+ 130: "f19",
233
+ 131: "f20",
234
+ 132: "f21",
235
+ 133: "f22",
236
+ 134: "f23",
237
+ 135: "f24",
238
+ 144: "num lock",
239
+ 145: "scroll lock",
240
+ 160: "^",
241
+ 161: "!",
242
+ 163: "#",
243
+ 164: "$",
244
+ 165: "\xF9",
245
+ 166: "page backward",
246
+ 167: "page forward",
247
+ 169: "closing paren (AZERTY)",
248
+ 170: "*",
249
+ 171: "~ + * key",
250
+ 173: "minus (firefox), mute/unmute",
251
+ 174: "decrease volume level",
252
+ 175: "increase volume level",
253
+ 176: "next",
254
+ 177: "previous",
255
+ 178: "stop",
256
+ 179: "play/pause",
257
+ 180: "e-mail",
258
+ 181: "mute/unmute (firefox)",
259
+ 182: "decrease volume level (firefox)",
260
+ 183: "increase volume level (firefox)",
261
+ 186: "semi-colon / \xF1",
262
+ 187: "equal sign",
263
+ 188: "comma",
264
+ 189: "dash",
265
+ 190: "period",
266
+ 191: "forward slash / \xE7",
267
+ 192: "grave accent / \xF1 / \xE6",
268
+ 193: "?, / or \xB0",
269
+ 194: "numpad period (chrome)",
270
+ 219: "open bracket",
271
+ 220: "back slash",
272
+ 221: "close bracket / \xE5",
273
+ 222: "single quote / \xF8",
274
+ 223: "`",
275
+ 224: "left or right \u2318 key (firefox)",
276
+ 225: "altgr",
277
+ 226: "< /git >",
278
+ 230: "GNOME Compose Key",
279
+ 231: "\xE7",
280
+ 233: "XF86Forward",
281
+ 234: "XF86Back",
282
+ 240: "alphanumeric",
283
+ 242: "hiragana/katakana",
284
+ 243: "half-width/full-width",
285
+ 244: "kanji",
286
+ 255: "toggle touchpad"
287
+ };
288
+ var inverse = (obj) => {
289
+ const newObj = {};
290
+ for (let key in obj) {
291
+ const val = obj[key];
292
+ newObj[val] = key;
293
+ }
294
+ return newObj;
295
+ };
296
+ var inverseKeyCodeTable = inverse(keyCodeTable);
297
+ var KeyboardControls = class extends Directive {
298
+ constructor() {
299
+ super(...arguments);
300
+ this.keyState = {};
301
+ this.boundKeys = {};
302
+ this.stop = false;
303
+ this.lastKeyPressed = null;
304
+ this._controlsOptions = {};
305
+ // TODO: This should be dynamic
306
+ this.serverFps = 60;
307
+ this.directionState = {
308
+ up: false,
309
+ down: false,
310
+ left: false,
311
+ right: false
312
+ };
313
+ }
314
+ onInit(element) {
315
+ this.setupListeners();
316
+ this.setInputs(element.props.controls.value);
317
+ this.interval = setInterval(() => {
318
+ this.preStep();
319
+ }, fps2ms(this.serverFps ?? 60));
320
+ }
321
+ onMount(element) {
322
+ }
323
+ onUpdate(props) {
324
+ this.setInputs(props);
325
+ }
326
+ onDestroy() {
327
+ clearInterval(this.interval);
328
+ document.removeEventListener("keydown", (e) => {
329
+ this.onKeyChange(e, true);
330
+ });
331
+ document.removeEventListener("keyup", (e) => {
332
+ this.onKeyChange(e, false);
333
+ });
334
+ }
335
+ /** @internal */
336
+ preStep() {
337
+ if (this.stop) return;
338
+ const direction = this.getDirection();
339
+ if (direction !== "none") {
340
+ const directionControl = this.boundKeys[direction];
341
+ if (directionControl) {
342
+ const { keyDown } = directionControl.options;
343
+ if (keyDown) {
344
+ this.applyInput(direction);
345
+ }
346
+ }
347
+ } else {
348
+ const boundKeys = Object.keys(this.boundKeys);
349
+ for (let keyName of boundKeys) {
350
+ this.applyInput(keyName);
351
+ }
352
+ }
353
+ }
354
+ applyInput(keyName) {
355
+ const keyState = this.keyState[keyName];
356
+ if (!keyState) return;
357
+ const { isDown, count } = keyState;
358
+ if (isDown) {
359
+ const { repeat, keyDown } = this.boundKeys[keyName].options;
360
+ if (repeat || count == 0) {
361
+ let parameters = this.boundKeys[keyName].parameters;
362
+ if (typeof parameters === "function") {
363
+ parameters = parameters();
364
+ }
365
+ if (keyDown) {
366
+ keyDown(this.boundKeys[keyName]);
367
+ }
368
+ this.keyState[keyName].count++;
369
+ }
370
+ }
371
+ }
372
+ setupListeners() {
373
+ document.addEventListener("keydown", (e) => {
374
+ this.onKeyChange(e, true);
375
+ });
376
+ document.addEventListener("keyup", (e) => {
377
+ this.onKeyChange(e, false);
378
+ });
379
+ }
380
+ bindKey(keys, actionName, options, parameters) {
381
+ if (!Array.isArray(keys)) keys = [keys];
382
+ const keyOptions = Object.assign({
383
+ repeat: false
384
+ }, options);
385
+ keys.forEach((keyName) => {
386
+ this.boundKeys[keyName] = { actionName, options: keyOptions, parameters };
387
+ });
388
+ }
389
+ applyKeyDown(name) {
390
+ const code = inverseKeyCodeTable[name];
391
+ const e = new Event("keydown");
392
+ e.keyCode = code;
393
+ this.onKeyChange(e, true);
394
+ }
395
+ applyKeyUp(name) {
396
+ const code = inverseKeyCodeTable[name];
397
+ const e = new Event("keyup");
398
+ e.keyCode = code;
399
+ this.onKeyChange(e, false);
400
+ }
401
+ applyKeyPress(name) {
402
+ return new Promise((resolve) => {
403
+ this.applyKeyDown(name);
404
+ setTimeout(() => {
405
+ this.applyKeyUp(name);
406
+ resolve();
407
+ }, 200);
408
+ });
409
+ }
410
+ onKeyChange(e, isDown) {
411
+ e = e || window.event;
412
+ const keyName = keyCodeTable[e.keyCode];
413
+ if (keyName && this.boundKeys[keyName]) {
414
+ if (this.keyState[keyName] == null) {
415
+ this.keyState[keyName] = {
416
+ count: 0,
417
+ isDown: true
418
+ };
419
+ }
420
+ this.keyState[keyName].isDown = isDown;
421
+ if (!isDown) {
422
+ this.keyState[keyName].count = 0;
423
+ const { keyUp } = this.boundKeys[keyName].options;
424
+ if (keyUp) {
425
+ keyUp(this.boundKeys[keyName]);
426
+ }
427
+ }
428
+ this.lastKeyPressed = isDown ? e.keyCode : null;
429
+ }
430
+ if (keyName) {
431
+ this.updateDirectionState(keyName, isDown);
432
+ }
433
+ }
434
+ updateDirectionState(keyName, isDown) {
435
+ switch (keyName) {
436
+ case "up":
437
+ this.directionState.up = isDown;
438
+ break;
439
+ case "down":
440
+ this.directionState.down = isDown;
441
+ break;
442
+ case "left":
443
+ this.directionState.left = isDown;
444
+ break;
445
+ case "right":
446
+ this.directionState.right = isDown;
447
+ break;
448
+ }
449
+ }
450
+ getDirection() {
451
+ const { up, down, left, right } = this.directionState;
452
+ if (up && left) return "up_left";
453
+ if (up && right) return "up_right";
454
+ if (down && left) return "down_left";
455
+ if (down && right) return "down_right";
456
+ if (up) return "up";
457
+ if (down) return "down";
458
+ if (left) return "left";
459
+ if (right) return "right";
460
+ return "none";
461
+ }
462
+ /**
463
+ * From the name of the entry, we retrieve the control information
464
+ *
465
+ * ```ts
466
+ * import { Input, inject, KeyboardControls } from '@rpgjs/client'
467
+ *
468
+ * const controls = inject(KeyboardControls)
469
+ * controls.getControl(Input.Enter)
470
+
471
+ * if (control) {
472
+ * console.log(control.actionName) // action
473
+ * }
474
+ * ```
475
+ * @title Get Control
476
+ * @method getControl(inputName)
477
+ * @param {string} inputName
478
+ * @returns { { actionName: string, options: any } | undefined }
479
+ * @memberof KeyboardControls
480
+ */
481
+ getControl(inputName) {
482
+ return this.boundKeys[inputName];
483
+ }
484
+ /**
485
+ * Returns all controls
486
+ *
487
+ * @method getControls()
488
+ * @since 4.2.0
489
+ * @returns { { [key: string]: BoundKey } }
490
+ * @memberof KeyboardControls
491
+ */
492
+ getControls() {
493
+ return this.boundKeys;
494
+ }
495
+ /**
496
+ * Triggers an input according to the name of the control
497
+ *
498
+ * ```ts
499
+ * import { Control, inject, KeyboardControls } from '@rpgjs/client'
500
+ *
501
+ * const controls = inject(KeyboardControls)
502
+ * controls.applyControl(Control.Action)
503
+ * ```
504
+ *
505
+ * You can put a second parameter or indicate on whether the key is pressed or released
506
+ *
507
+ * ```ts
508
+ * import { Control, inject, KeyboardControls } from '@rpgjs/client'
509
+ *
510
+ * const controls = inject(KeyboardControls)
511
+ * controls.applyControl(Control.Up, true) // keydown
512
+ * controls.applyControl(Control.Up, false) // keyup
513
+ * ```
514
+ * @title Apply Control
515
+ * @method applyControl(controlName,isDown)
516
+ * @param {string} controlName
517
+ * @param {boolean} [isDown]
518
+ * @returns {Promise<void>}
519
+ * @memberof KeyboardControls
520
+ */
521
+ async applyControl(controlName, isDown) {
522
+ const control = this._controlsOptions[controlName];
523
+ if (control) {
524
+ const input = Array.isArray(control.bind) ? control.bind[0] : control.bind;
525
+ if (isDown === void 0) {
526
+ await this.applyKeyPress(input);
527
+ } else if (isDown) {
528
+ this.applyKeyDown(input);
529
+ } else {
530
+ this.applyKeyUp(input);
531
+ }
532
+ }
533
+ }
534
+ /**
535
+ * Stop listening to the inputs. Pressing a key won't do anything
536
+ *
537
+ * @title Stop Inputs
538
+ * @method stopInputs()
539
+ * @returns {void}
540
+ * @memberof KeyboardControls
541
+ */
542
+ stopInputs() {
543
+ this.stop = true;
544
+ }
545
+ /**
546
+ * Listen to the inputs again
547
+ *
548
+ * @title Listen Inputs
549
+ * @method listenInputs()
550
+ * @returns {void}
551
+ * @memberof KeyboardControls
552
+ */
553
+ listenInputs() {
554
+ this.stop = false;
555
+ this.keyState = {};
556
+ }
557
+ /**
558
+ * Assign custom inputs to the scene
559
+ *
560
+ * The object is the following:
561
+ *
562
+ * * 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
563
+ * * The value is an object representing control information:
564
+ * * repeat {boolean} The key can be held down to repeat the action. (false by default)
565
+ * * bind {string | string[]} To which key is linked the control
566
+ * * method {Function} Function to be triggered. If you do not set this property, the name of the control is sent directly to the server.
567
+ * * delay {object|number} (since v3.2.0) Indicates how long (in milliseconds) the player can press the key again to perform the action
568
+ * * delay.duration
569
+ * * delay.otherControls {string | string[]} Indicates the other controls that will also have the delay at the same time
570
+ *
571
+ * ```ts
572
+ * import { Control, Input, inject, KeyboardControls } from '@rpgjs/client'
573
+ *
574
+ * const controls = inject(KeyboardControls)
575
+ * controls.setInputs({
576
+ [Control.Up]: {
577
+ repeat: true,
578
+ bind: Input.Up
579
+ },
580
+ [Control.Down]: {
581
+ repeat: true,
582
+ bind: Input.Down
583
+ },
584
+ [Control.Right]: {
585
+ repeat: true,
586
+ bind: Input.Right
587
+ },
588
+ [Control.Left]: {
589
+ repeat: true,
590
+ bind: Input.Left
591
+ },
592
+ [Control.Action]: {
593
+ bind: [Input.Space, Input.Enter]
594
+ },
595
+ [Control.Back]: {
596
+ bind: Input.Escape
597
+ },
598
+
599
+ // The myscustom1 control is sent to the server when the A key is pressed.
600
+ mycustom1: {
601
+ bind: Input.A
602
+ },
603
+
604
+ // the myAction method is executed when the B key is pressed
605
+ mycustom2: {
606
+ bind: Input.B,
607
+ method({ actionName }) {
608
+ console.log('cool', actionName)
609
+ }
610
+ },
611
+
612
+ // The player can redo the action after 400ms
613
+ mycustom3: {
614
+ bind: Input.C,
615
+ delay: 400 // ms
616
+ },
617
+
618
+ // The player can redo the action (mycustom4) and the directions after 400ms
619
+ mycustom4: {
620
+ bind: Input.C,
621
+ delay: {
622
+ duration: 400,
623
+ otherControls: [Control.Up, Control.Down, Control.Left, Control.Right]
624
+ }
625
+ }
626
+ })
627
+ *
628
+ * ```
629
+ * @enum {string} Control
630
+ *
631
+ * Control.Up | up
632
+ * Control.Down | down
633
+ * Control.Left | left
634
+ * Control.Right | right
635
+ * Control.Action | action
636
+ * Control.Back | back
637
+ *
638
+ * @enum {string} Mouse Event
639
+ *
640
+ * click | Click
641
+ * dblclick | Double Click
642
+ * mousedown | Mouse Down
643
+ * mouseup | Mouse Up
644
+ * mouseover | Mouse Over
645
+ * mousemove | Mouse Move
646
+ * mouseout | Mouse Out
647
+ * contextmenu | Context Menu
648
+ *
649
+ *
650
+ * @enum {string} Input
651
+ *
652
+ * break | Pause
653
+ * backspace | Backspace / Delete
654
+ * tab | Tab
655
+ * clear | Clear
656
+ * enter | Enter
657
+ * shift | Shift
658
+ * ctrl | Control
659
+ * alt | Alt
660
+ * pause/break | Pause / Break
661
+ * caps lock | Caps Lock
662
+ * escape | Escape
663
+ * conversion | Conversion
664
+ * non-conversion | Non-conversion
665
+ * space | Space
666
+ * page up | Page Up
667
+ * page down | Page Down
668
+ * end | End
669
+ * home | Home
670
+ * left | Left Arrow
671
+ * up | Up Arrow
672
+ * right | Right Arrow
673
+ * down | Down Arrow
674
+ * select | Select
675
+ * print | Print
676
+ * execute | Execute
677
+ * Print Screen | Print Screen
678
+ * insert | Insert
679
+ * delete | Delete
680
+ * n0 | 0
681
+ * n1 | 1
682
+ * n2 | 2
683
+ * n3 | 3
684
+ * n4 | 4
685
+ * n5 | 5
686
+ * n6 | 6
687
+ * n7 | 7
688
+ * n8 | 8
689
+ * n9 | 9
690
+ * : | Colon
691
+ * semicolon (firefox), equals | Semicolon (Firefox), Equals
692
+ * < | Less Than
693
+ * equals (firefox) | Equals (Firefox)
694
+ * ß | Eszett
695
+ * @ | At
696
+ * a | A
697
+ * b | B
698
+ * c | C
699
+ * d | D
700
+ * e | E
701
+ * f | F
702
+ * g | G
703
+ * h | H
704
+ * i | I
705
+ * j | J
706
+ * k | K
707
+ * l | L
708
+ * m | M
709
+ * n | N
710
+ * o | O
711
+ * p | P
712
+ * q | Q
713
+ * r | R
714
+ * s | S
715
+ * t | T
716
+ * u | U
717
+ * v | V
718
+ * w | W
719
+ * x | X
720
+ * y | Y
721
+ * z | Z
722
+ * Windows Key / Left ⌘ / Chromebook Search key | Windows Key / Left Command ⌘ / Chromebook Search Key
723
+ * right window key | Right Windows Key
724
+ * Windows Menu / Right ⌘ | Windows Menu / Right Command ⌘
725
+ * numpad 0 | Numpad 0
726
+ * numpad 1 | Numpad 1
727
+ * numpad 2 | Numpad 2
728
+ * numpad 3 | Numpad 3
729
+ * numpad 4 | Numpad 4
730
+ * numpad 5 | Numpad 5
731
+ * numpad 6 | Numpad 6
732
+ * numpad 7 | Numpad 7
733
+ * numpad 8 | Numpad 8
734
+ * numpad 9 | Numpad 9
735
+ * multiply | Multiply
736
+ * add | Add
737
+ * numpad period (firefox) | Numpad Period (Firefox)
738
+ * subtract | Subtract
739
+ * decimal point | Decimal Point
740
+ * divide | Divide
741
+ * f1 | F1
742
+ * f2 | F2
743
+ * f3 | F3
744
+ * f4 | F4
745
+ * f5 | F5
746
+ * f6 | F6
747
+ * f7 | F7
748
+ * f8 | F8
749
+ * f9 | F9
750
+ * f10 | F10
751
+ * f11 | F11
752
+ * f12 | F12
753
+ * f13 | F13
754
+ * f14 | F14
755
+ * f15 | F15
756
+ * f16 | F16
757
+ * f17 | F17
758
+ * f18 | F18
759
+ * f19 | F19
760
+ * f20 | F20
761
+ * f21 | F21
762
+ * f22 | F22
763
+ * f23 | F23
764
+ * f24 | F24
765
+ * num lock | Num Lock
766
+ * scroll lock | Scroll Lock
767
+ * ^ | Caret
768
+ * ! | Exclamation Point
769
+ * # | Hash
770
+ * $ | Dollar Sign
771
+ * ù | Grave Accent U
772
+ * page backward | Page Backward
773
+ * page forward | Page Forward
774
+ * closing paren (AZERTY) | Closing Parenthesis (AZERTY)
775
+ * * | Asterisk
776
+ * ~ + * key | Tilde + Asterisk Key
777
+ * minus (firefox), mute/unmute | Minus (Firefox), Mute/Unmute
778
+ * decrease volume level | Decrease Volume Level
779
+ * increase volume level | Increase Volume Level
780
+ * next | Next
781
+ * previous | Previous
782
+ * stop | Stop
783
+ * play/pause | Play/Pause
784
+ * e-mail | Email
785
+ * mute/unmute (firefox) | Mute/Unmute (Firefox)
786
+ * decrease volume level (firefox) | Decrease Volume Level (Firefox)
787
+ * increase volume level (firefox) | Increase Volume Level (Firefox)
788
+ * semi-colon / ñ | Semicolon / ñ
789
+ * equal sign | Equal Sign
790
+ * comma | Comma
791
+ * dash | Dash
792
+ * period | Period
793
+ * forward slash / ç | Forward Slash / ç
794
+ * grave accent / ñ / æ | Grave Accent / ñ / æ
795
+ * ?, / or ° | ?, / or °
796
+ * numpad period (chrome) | Numpad Period (Chrome)
797
+ * open bracket | Open Bracket
798
+ * back slash | Backslash
799
+ * close bracket / å | Close Bracket / å
800
+ * single quote / ø | Single Quote / ø
801
+ * \` | Backtick
802
+ * left or right ⌘ key (firefox) | Left or Right Command Key (Firefox)
803
+ * altgr | AltGr
804
+ * < /git > | < /git >
805
+ * GNOME Compose Key | GNOME Compose Key
806
+ * ç | ç
807
+ * XF86Forward | XF86Forward
808
+ * XF86Back | XF86Back
809
+ * alphanumeric | Alphanumeric
810
+ * hiragana/katakana | Hiragana/Katakana
811
+ * half-width/full-width | Half-Width/Full-Width
812
+ * kanji | Kanji
813
+ * toggle touchpad | Toggle Touchpad
814
+ *
815
+ * @title Set Inputs
816
+ * @method setInputs(inputs)
817
+ * @param {object} inputs
818
+ * @memberof KeyboardControls
819
+ */
820
+ setInputs(inputs) {
821
+ if (!inputs) return;
822
+ this.boundKeys = {};
823
+ let inputsTransformed = {};
824
+ for (let control in inputs) {
825
+ const option = inputs[control];
826
+ const { bind } = option;
827
+ let inputsKey = bind;
828
+ if (!Array.isArray(inputsKey)) {
829
+ inputsKey = [bind];
830
+ }
831
+ for (let input of inputsKey) {
832
+ this.bindKey(input, control, option);
833
+ }
834
+ }
835
+ this._controlsOptions = inputs;
836
+ }
837
+ get options() {
838
+ return this._controlsOptions;
839
+ }
840
+ };
841
+ registerDirective("controls", KeyboardControls);
842
+
843
+ // src/directives/Scheduler.ts
844
+ var Scheduler = class extends Directive {
845
+ constructor() {
846
+ super(...arguments);
847
+ this.fps = 60;
848
+ this.deltaTime = 0;
849
+ this.frame = 0;
850
+ this.timestamp = 0;
851
+ this.requestedDelay = 0;
852
+ this.lastTimestamp = 0;
853
+ this._stop = false;
854
+ }
855
+ onInit(element) {
856
+ this.tick = element.propObservables?.tick;
857
+ }
858
+ onDestroy() {
859
+ }
860
+ onMount(element) {
861
+ }
862
+ onUpdate(props) {
863
+ }
864
+ nextTick(timestamp) {
865
+ this.lastTimestamp = this.lastTimestamp || this.timestamp;
866
+ this.deltaTime = preciseNow() - this.timestamp;
867
+ this.timestamp = timestamp;
868
+ this.tick.set({
869
+ timestamp: this.timestamp,
870
+ deltaTime: this.deltaTime,
871
+ frame: this.frame,
872
+ deltaRatio: ~~this.deltaTime / ~~fps2ms(this.fps)
873
+ });
874
+ this.lastTimestamp = this.timestamp;
875
+ this.frame++;
876
+ }
877
+ /**
878
+ * start the schedule
879
+ * @return {Scheduler} returns this scheduler instance
880
+ */
881
+ start(options = {}) {
882
+ if (options.maxFps) this.maxFps = options.maxFps;
883
+ if (options.fps) this.fps = options.fps;
884
+ if (options.delay) this.requestedDelay = options.delay;
885
+ const requestAnimationFrame = (fn) => {
886
+ if (isBrowser()) {
887
+ window.requestAnimationFrame(fn.bind(this));
888
+ } else {
889
+ setTimeout(() => {
890
+ this.requestedDelay = 0;
891
+ fn(preciseNow());
892
+ }, fps2ms(this.fps) + this.requestedDelay);
893
+ }
894
+ };
895
+ if (!this.maxFps) {
896
+ const loop2 = (timestamp) => {
897
+ requestAnimationFrame(loop2);
898
+ this.nextTick(timestamp);
899
+ };
900
+ requestAnimationFrame(loop2);
901
+ } else {
902
+ const msInterval = fps2ms(this.maxFps);
903
+ let now = preciseNow();
904
+ let then = preciseNow();
905
+ const loop2 = (timestamp) => {
906
+ if (this._stop) return;
907
+ requestAnimationFrame(loop2);
908
+ now = preciseNow();
909
+ const elapsed = now - then;
910
+ if (elapsed > msInterval) {
911
+ then = now - elapsed % msInterval;
912
+ this.nextTick(timestamp);
913
+ }
914
+ };
915
+ requestAnimationFrame(loop2);
916
+ }
917
+ return this;
918
+ }
919
+ stop() {
920
+ this._stop = true;
921
+ }
922
+ };
923
+ registerDirective("tick", Scheduler);
924
+
925
+ // src/directives/ViewportFollow.ts
926
+ var ViewportFollow = class extends Directive {
927
+ onInit(element) {
928
+ }
929
+ onMount(element) {
930
+ const { viewportFollow } = element.props;
931
+ const { viewport } = element.props.context;
932
+ if (!viewport) {
933
+ throw error("ViewportFollow directive requires a Viewport component to be mounted in the same context");
934
+ }
935
+ viewport.follow(element.componentInstance);
936
+ }
937
+ onUpdate(props) {
938
+ }
939
+ onDestroy() {
940
+ }
941
+ };
942
+ registerDirective("viewportFollow", ViewportFollow);
943
+
944
+ // src/directives/Sound.ts
945
+ import { effect } from "@signe/reactive";
946
+ import { Howl } from "howler";
947
+ var EVENTS = ["load", "loaderror", "playerror", "play", "end", "pause", "stop", "mute", "volume", "rate", "seek", "fade", "unlock"];
948
+ var Sound = class extends Directive {
949
+ constructor() {
950
+ super(...arguments);
951
+ this.eventsFn = [];
952
+ this.maxVolume = 1;
953
+ this.maxDistance = 100;
954
+ }
955
+ onInit(element) {
956
+ }
957
+ onMount(element) {
958
+ const { props } = element;
959
+ const tick2 = props.context.tick;
960
+ const { src, autoplay, loop: loop2, volume, spatial } = props.sound;
961
+ this.sound = new Howl({
962
+ src,
963
+ autoplay,
964
+ loop: loop2,
965
+ volume
966
+ });
967
+ for (let event of EVENTS) {
968
+ if (!props.sound[event]) continue;
969
+ const fn = props.sound[event];
970
+ this.eventsFn.push(fn);
971
+ this.sound.on(event, fn);
972
+ }
973
+ if (spatial) {
974
+ const { soundListenerPosition } = props.context;
975
+ if (!soundListenerPosition) {
976
+ throw new error("SoundListenerPosition directive is required for spatial sound in component parent");
977
+ }
978
+ const { x: listenerX, y: listenerY } = soundListenerPosition;
979
+ this.tickSubscription = effect(() => {
980
+ tick2();
981
+ const { x, y } = element.componentInstance;
982
+ const distance = calculateDistance(x, y, listenerX(), listenerY());
983
+ const volume2 = Math.max(this.maxVolume - distance / this.maxDistance, 0);
984
+ this.sound.volume(volume2);
985
+ }).subscription;
986
+ }
987
+ }
988
+ onUpdate(props) {
989
+ const { volume, loop: loop2, mute, seek, playing, rate, spatial } = props;
990
+ if (volume != void 0) this.sound.volume(volume);
991
+ if (loop2 != void 0) this.sound.loop(loop2);
992
+ if (mute != void 0) this.sound.mute(mute);
993
+ if (seek != void 0) this.sound.seek(seek);
994
+ if (playing != void 0) {
995
+ if (playing) this.sound.play();
996
+ else this.sound.pause();
997
+ }
998
+ if (spatial) {
999
+ this.maxVolume = spatial.maxVolume ?? this.maxVolume;
1000
+ this.maxDistance = spatial.maxDistance ?? this.maxDistance;
1001
+ }
1002
+ if (rate != void 0) this.sound.rate(rate);
1003
+ }
1004
+ onDestroy() {
1005
+ this.sound.stop();
1006
+ this.tickSubscription?.unsubscribe();
1007
+ for (let event of EVENTS) {
1008
+ if (this.eventsFn[event]) {
1009
+ this.sound.off(event, this.eventsFn[event]);
1010
+ }
1011
+ }
1012
+ }
1013
+ };
1014
+ var SoundListenerPosition = class extends Directive {
1015
+ onMount(element) {
1016
+ element.props.context.soundListenerPosition = element.propObservables?.soundListenerPosition;
1017
+ }
1018
+ onInit(element) {
1019
+ }
1020
+ onUpdate(props) {
1021
+ }
1022
+ onDestroy() {
1023
+ }
1024
+ };
1025
+ registerDirective("sound", Sound);
1026
+ registerDirective("soundListenerPosition", SoundListenerPosition);
1027
+
1028
+ // src/directives/Drag.ts
1029
+ import { effect as effect2, isSignal } from "@signe/reactive";
1030
+ import { Rectangle } from "pixi.js";
1031
+ import { snap } from "popmotion";
1032
+
1033
+ // src/directives/Transition.ts
1034
+ import { DisplacementFilter, Sprite, Texture, WRAP_MODES } from "pixi.js";
1035
+ import { animate } from "popmotion";
1036
+ var Transition = class extends Directive {
1037
+ onInit(element) {
1038
+ }
1039
+ onMount(element) {
1040
+ const { image } = element.props.transition;
1041
+ const displacementSprite = new Sprite(Texture.from(image));
1042
+ displacementSprite.texture.baseTexture.wrapMode = WRAP_MODES.REPEAT;
1043
+ const displacementFilter = new DisplacementFilter(displacementSprite);
1044
+ const instance = element.componentInstance;
1045
+ instance.filters = [displacementFilter];
1046
+ instance.addChild(displacementSprite);
1047
+ setTimeout(() => {
1048
+ animate({
1049
+ from: 0,
1050
+ to: 1,
1051
+ duration: 500,
1052
+ onUpdate: (progress) => {
1053
+ displacementFilter.scale.x = progress;
1054
+ displacementFilter.scale.y = progress;
1055
+ }
1056
+ });
1057
+ }, 5e3);
1058
+ }
1059
+ onUpdate(props) {
1060
+ }
1061
+ onDestroy() {
1062
+ }
1063
+ };
1064
+ registerDirective("transition", Transition);
1065
+
1066
+ // src/index.ts
1067
+ export * from "@signe/reactive";
1068
+ import { Howler } from "howler";
1069
+
1070
+ // src/components/Canvas.ts
1071
+ import { effect as effect4, signal as signal3 } from "@signe/reactive";
1072
+ import { Container as Container3, autoDetectRenderer } from "pixi.js";
1073
+ import { loadYoga } from "yoga-layout";
1074
+
1075
+ // src/engine/reactive.ts
1076
+ import { isSignal as isSignal2 } from "@signe/reactive";
1077
+ import {
1078
+ Observable,
1079
+ Subject,
1080
+ defer,
1081
+ from,
1082
+ map,
1083
+ of,
1084
+ switchMap
1085
+ } from "rxjs";
1086
+ var components = {};
1087
+ var isElement = (value) => {
1088
+ return value && typeof value === "object" && "tag" in value && "props" in value && "componentInstance" in value;
1089
+ };
1090
+ var isPrimitive = (value) => {
1091
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || value === void 0;
1092
+ };
1093
+ function registerComponent(name, component) {
1094
+ components[name] = component;
1095
+ }
1096
+ function destroyElement(element) {
1097
+ if (Array.isArray(element)) {
1098
+ element.forEach((e) => destroyElement(e));
1099
+ return;
1100
+ }
1101
+ if (!element) {
1102
+ return;
1103
+ }
1104
+ element.propSubscriptions.forEach((sub) => sub.unsubscribe());
1105
+ element.effectSubscriptions.forEach((sub) => sub.unsubscribe());
1106
+ for (let name in element.directives) {
1107
+ element.directives[name].onDestroy?.();
1108
+ }
1109
+ element.componentInstance.onDestroy?.(element.parent);
1110
+ element.effectUnmounts.forEach((fn) => fn?.());
1111
+ }
1112
+ function createComponent(tag, props) {
1113
+ if (!components[tag]) {
1114
+ throw new Error(`Component ${tag} is not registered`);
1115
+ }
1116
+ const instance = new components[tag]();
1117
+ const element = {
1118
+ tag,
1119
+ props: {},
1120
+ componentInstance: instance,
1121
+ propSubscriptions: [],
1122
+ propObservables: props,
1123
+ parent: null,
1124
+ directives: {},
1125
+ effectUnmounts: [],
1126
+ effectSubscriptions: [],
1127
+ effectMounts: [],
1128
+ destroy() {
1129
+ destroyElement(this);
1130
+ },
1131
+ allElements: new Subject()
1132
+ };
1133
+ if (props) {
1134
+ const recursiveProps = (props2, path = "") => {
1135
+ const _set = (path2, key, value) => {
1136
+ if (path2 == "") {
1137
+ element.props[key] = value;
1138
+ return;
1139
+ }
1140
+ set(element.props, path2 + "." + key, value);
1141
+ };
1142
+ Object.entries(props2).forEach(([key, value]) => {
1143
+ if (isSignal2(value)) {
1144
+ const _value = value;
1145
+ if ("dependencies" in _value && _value.dependencies.size == 0) {
1146
+ _set(path, key, _value());
1147
+ return;
1148
+ }
1149
+ element.propSubscriptions.push(
1150
+ _value.observable.subscribe((value2) => {
1151
+ _set(path, key, value2);
1152
+ if (element.directives[key]) {
1153
+ element.directives[key].onUpdate?.(value2);
1154
+ }
1155
+ if (key == "tick") {
1156
+ return;
1157
+ }
1158
+ instance.onUpdate?.(
1159
+ path == "" ? {
1160
+ [key]: value2
1161
+ } : set({}, path + "." + key, value2)
1162
+ );
1163
+ })
1164
+ );
1165
+ } else {
1166
+ if (isObject(value) && key != "context" && !isElement(value)) {
1167
+ recursiveProps(value, (path ? path + "." : "") + key);
1168
+ } else {
1169
+ _set(path, key, value);
1170
+ }
1171
+ }
1172
+ });
1173
+ };
1174
+ recursiveProps(props);
1175
+ }
1176
+ instance.onInit?.(element.props);
1177
+ instance.onUpdate?.(element.props);
1178
+ const onMount = (parent, element2, index) => {
1179
+ element2.props.context = parent.props.context;
1180
+ element2.parent = parent;
1181
+ element2.componentInstance.onMount?.(element2, index);
1182
+ for (let name in element2.directives) {
1183
+ element2.directives[name].onMount?.(element2);
1184
+ }
1185
+ element2.effectMounts.forEach((fn) => {
1186
+ element2.effectUnmounts.push(fn(element2));
1187
+ });
1188
+ };
1189
+ const elementsListen = new Subject();
1190
+ if (props?.isRoot) {
1191
+ const propagateContext = async (element2) => {
1192
+ if (!element2.props.children) {
1193
+ return;
1194
+ }
1195
+ for (let child of element2.props.children) {
1196
+ if (!child) continue;
1197
+ if (isPromise(child)) {
1198
+ child = await child;
1199
+ }
1200
+ if (child instanceof Observable) {
1201
+ child.subscribe(
1202
+ ({
1203
+ elements: comp,
1204
+ prev
1205
+ }) => {
1206
+ const components2 = comp.filter((c) => c !== null);
1207
+ if (prev) {
1208
+ components2.forEach((c) => {
1209
+ const index = element2.props.children.indexOf(prev.props.key);
1210
+ onMount(element2, c, index + 1);
1211
+ propagateContext(c);
1212
+ });
1213
+ return;
1214
+ }
1215
+ components2.forEach((component) => {
1216
+ if (!Array.isArray(component)) {
1217
+ onMount(element2, component);
1218
+ propagateContext(component);
1219
+ } else {
1220
+ component.forEach((comp2) => {
1221
+ onMount(element2, comp2);
1222
+ propagateContext(comp2);
1223
+ });
1224
+ }
1225
+ });
1226
+ elementsListen.next(void 0);
1227
+ }
1228
+ );
1229
+ } else {
1230
+ onMount(element2, child);
1231
+ await propagateContext(child);
1232
+ }
1233
+ }
1234
+ };
1235
+ element.allElements = elementsListen;
1236
+ element.props.context.rootElement = element;
1237
+ element.componentInstance.onMount?.(element);
1238
+ propagateContext(element);
1239
+ }
1240
+ if (props) {
1241
+ for (let key in props) {
1242
+ const directive = applyDirective(element, key);
1243
+ if (directive) element.directives[key] = directive;
1244
+ }
1245
+ }
1246
+ return element;
1247
+ }
1248
+ function loop(itemsSubject, createElementFn) {
1249
+ let elements = [];
1250
+ const addAt = (items, insertIndex) => {
1251
+ return items.map((item, index) => {
1252
+ const element = createElementFn(item, insertIndex + index);
1253
+ elements.splice(insertIndex + index, 0, element);
1254
+ return element;
1255
+ });
1256
+ };
1257
+ return defer(() => {
1258
+ let initialItems = [...itemsSubject._subject.items];
1259
+ let init = true;
1260
+ return itemsSubject.observable.pipe(
1261
+ map((event) => {
1262
+ const { type, items, index } = event;
1263
+ if (init) {
1264
+ if (elements.length > 0) {
1265
+ return {
1266
+ elements,
1267
+ fullElements: elements
1268
+ };
1269
+ }
1270
+ const newElements = addAt(initialItems, 0);
1271
+ initialItems = [];
1272
+ init = false;
1273
+ return {
1274
+ elements: newElements,
1275
+ fullElements: elements
1276
+ };
1277
+ } else if (type == "reset") {
1278
+ if (elements.length != 0) {
1279
+ elements.forEach((element) => {
1280
+ destroyElement(element);
1281
+ });
1282
+ elements = [];
1283
+ }
1284
+ const newElements = addAt(items, 0);
1285
+ return {
1286
+ elements: newElements,
1287
+ fullElements: elements
1288
+ };
1289
+ } else if (type == "add" && index != void 0) {
1290
+ const lastElement = elements[index - 1];
1291
+ const newElements = addAt(items, index);
1292
+ return {
1293
+ prev: lastElement,
1294
+ elements: newElements,
1295
+ fullElements: elements
1296
+ };
1297
+ } else if (index != void 0 && type == "remove") {
1298
+ const currentElement = elements[index];
1299
+ destroyElement(currentElement);
1300
+ elements.splice(index, 1);
1301
+ return {
1302
+ elements: []
1303
+ };
1304
+ }
1305
+ return {
1306
+ elements: [],
1307
+ fullElements: elements
1308
+ };
1309
+ })
1310
+ );
1311
+ });
1312
+ }
1313
+ function cond(condition, createElementFn) {
1314
+ let element = null;
1315
+ return condition.observable.pipe(
1316
+ switchMap((bool) => {
1317
+ if (bool) {
1318
+ let _el = createElementFn();
1319
+ if (isPromise(_el)) {
1320
+ return from(_el).pipe(
1321
+ map((el) => {
1322
+ element = _el;
1323
+ return {
1324
+ type: "init",
1325
+ elements: [el]
1326
+ };
1327
+ })
1328
+ );
1329
+ }
1330
+ element = _el;
1331
+ return of({
1332
+ type: "init",
1333
+ elements: [element]
1334
+ });
1335
+ } else if (element) {
1336
+ destroyElement(element);
1337
+ }
1338
+ return of({
1339
+ elements: []
1340
+ });
1341
+ })
1342
+ );
1343
+ }
1344
+
1345
+ // src/hooks/useProps.ts
1346
+ import { isSignal as isSignal3, signal } from "@signe/reactive";
1347
+ var useProps = (props, defaults = {}) => {
1348
+ if (isSignal3(props)) {
1349
+ return props();
1350
+ }
1351
+ const obj = {};
1352
+ for (let key in props) {
1353
+ const value = props[key];
1354
+ obj[key] = isPrimitive(value) ? signal(value) : value;
1355
+ }
1356
+ for (let key in defaults) {
1357
+ if (!(key in obj)) {
1358
+ obj[key] = signal(defaults[key]);
1359
+ }
1360
+ }
1361
+ return obj;
1362
+ };
1363
+ var useDefineProps = (props) => {
1364
+ return (schema) => {
1365
+ const rawProps = isSignal3(props) ? props() : props;
1366
+ const validatedProps = {};
1367
+ for (const key in schema) {
1368
+ const propConfig = schema[key];
1369
+ const value = rawProps[key];
1370
+ let validatedValue;
1371
+ if (typeof propConfig === "function") {
1372
+ validateType(key, value, [propConfig]);
1373
+ validatedValue = value;
1374
+ } else if (Array.isArray(propConfig)) {
1375
+ validateType(key, value, propConfig);
1376
+ validatedValue = value;
1377
+ } else if (propConfig && typeof propConfig === "object") {
1378
+ if (propConfig.required && value === void 0) {
1379
+ throw new Error(`Missing required prop: ${key}`);
1380
+ }
1381
+ if (propConfig.type) {
1382
+ const types = Array.isArray(propConfig.type) ? propConfig.type : [propConfig.type];
1383
+ validateType(key, value, types);
1384
+ }
1385
+ if (propConfig.validator && !propConfig.validator(value, rawProps)) {
1386
+ throw new Error(`Invalid prop: custom validation failed for prop "${key}"`);
1387
+ }
1388
+ if (value === void 0 && "default" in propConfig) {
1389
+ validatedValue = typeof propConfig.default === "function" ? propConfig.default(rawProps) : propConfig.default;
1390
+ } else {
1391
+ validatedValue = value;
1392
+ }
1393
+ }
1394
+ validatedProps[key] = isSignal3(validatedValue) ? validatedValue : signal(validatedValue);
1395
+ }
1396
+ return {
1397
+ ...useProps(rawProps),
1398
+ ...validatedProps
1399
+ };
1400
+ };
1401
+ };
1402
+ function validateType(key, value, types) {
1403
+ if (value === void 0 || value === null) return;
1404
+ const valueToCheck = isSignal3(value) ? value() : value;
1405
+ const valid = types.some((type) => {
1406
+ if (type === Number) return typeof valueToCheck === "number";
1407
+ if (type === String) return typeof valueToCheck === "string";
1408
+ if (type === Boolean) return typeof valueToCheck === "boolean";
1409
+ if (type === Function) return typeof valueToCheck === "function";
1410
+ if (type === Object) return typeof valueToCheck === "object";
1411
+ if (type === Array) return Array.isArray(valueToCheck);
1412
+ if (type === null) return valueToCheck === null;
1413
+ return valueToCheck instanceof type;
1414
+ });
1415
+ if (!valid) {
1416
+ throw new Error(
1417
+ `Invalid prop: type check failed for prop "${key}". Expected ${types.map((t) => t.name).join(" or ")}`
1418
+ );
1419
+ }
1420
+ }
1421
+
1422
+ // src/components/DisplayObject.ts
1423
+ import { effect as effect3, signal as signal2 } from "@signe/reactive";
1424
+ import { DropShadowFilter } from "pixi-filters";
1425
+ import { BlurFilter, ObservablePoint } from "pixi.js";
1426
+ var EVENTS2 = [
1427
+ "added",
1428
+ "childAdded",
1429
+ "childRemoved",
1430
+ "click",
1431
+ "clickcapture",
1432
+ "destroyed",
1433
+ "globalmousemove",
1434
+ "globalpointermove",
1435
+ "globaltouchmove",
1436
+ "mousedown",
1437
+ "mousedowncapture",
1438
+ "mouseenter",
1439
+ "mouseentercapture",
1440
+ "mouseleave",
1441
+ "mouseleavecapture",
1442
+ "mousemove",
1443
+ "mousemovecapture",
1444
+ "mouseout",
1445
+ "mouseoutcapture",
1446
+ "mouseover",
1447
+ "mouseovercapture",
1448
+ "mouseup",
1449
+ "mouseupcapture",
1450
+ "mouseupoutside",
1451
+ "mouseupoutsidecapture",
1452
+ "pointercancel",
1453
+ "pointercancelcapture",
1454
+ "pointerdown",
1455
+ "pointerdowncapture",
1456
+ "pointerenter",
1457
+ "pointerentercapture",
1458
+ "pointerleave",
1459
+ "pointerleavecapture",
1460
+ "pointermove",
1461
+ "pointermovecapture",
1462
+ "pointerout",
1463
+ "pointeroutcapture",
1464
+ "pointerover",
1465
+ "pointerovercapture",
1466
+ "pointertap",
1467
+ "pointertapcapture",
1468
+ "pointerup",
1469
+ "pointerupcapture",
1470
+ "pointerupoutside",
1471
+ "pointerupoutsidecapture",
1472
+ "removed",
1473
+ "rightclick",
1474
+ "rightclickcapture",
1475
+ "rightdown",
1476
+ "rightdowncapture",
1477
+ "rightup",
1478
+ "rightupcapture",
1479
+ "rightupoutside",
1480
+ "rightupoutsidecapture",
1481
+ "tap",
1482
+ "tapcapture",
1483
+ "touchcancel",
1484
+ "touchcancelcapture",
1485
+ "touchend",
1486
+ "touchendcapture",
1487
+ "touchendoutside",
1488
+ "touchendoutsidecapture",
1489
+ "touchmove",
1490
+ "touchmovecapture",
1491
+ "touchstart",
1492
+ "touchstartcapture",
1493
+ "wheel",
1494
+ "wheelcapture"
1495
+ ];
1496
+ function DisplayObject(extendClass) {
1497
+ var _canvasContext, _DisplayObject_instances, applyFlexLayout_fn, flexRender_fn, setAlign_fn, setEdgeSize_fn, _a;
1498
+ return _a = class extends extendClass {
1499
+ constructor() {
1500
+ super(...arguments);
1501
+ __privateAdd(this, _DisplayObject_instances);
1502
+ __privateAdd(this, _canvasContext, null);
1503
+ this.isFlex = false;
1504
+ this.fullProps = {};
1505
+ this.isMounted = false;
1506
+ this._anchorPoints = new ObservablePoint(
1507
+ { _onUpdate: () => {
1508
+ } },
1509
+ 0,
1510
+ 0
1511
+ );
1512
+ this.isCustomAnchor = false;
1513
+ this.displayWidth = signal2(0);
1514
+ this.displayHeight = signal2(0);
1515
+ this.overrideProps = [];
1516
+ }
1517
+ get yoga() {
1518
+ return __privateGet(this, _canvasContext)?.Yoga;
1519
+ }
1520
+ get deltaRatio() {
1521
+ return __privateGet(this, _canvasContext)?.scheduler?.tick.value.deltaRatio;
1522
+ }
1523
+ onInit(props) {
1524
+ this._id = props.id;
1525
+ for (let event of EVENTS2) {
1526
+ if (props[event] && !this.overrideProps.includes(event)) {
1527
+ this.eventMode = "static";
1528
+ this.on(event, props[event]);
1529
+ }
1530
+ }
1531
+ }
1532
+ onMount({ parent, props }, index) {
1533
+ __privateSet(this, _canvasContext, props.context);
1534
+ this.node = this.yoga.Node.create();
1535
+ if (parent) {
1536
+ const instance = parent.componentInstance;
1537
+ if (index === void 0) {
1538
+ instance.addChild(this);
1539
+ } else {
1540
+ instance.addChildAt(this, index);
1541
+ }
1542
+ if (instance.layer) this.parentLayer = instance.layer;
1543
+ this.isMounted = true;
1544
+ this.effectSize(props.width, props.height);
1545
+ this.onUpdate(props);
1546
+ this.parent.node.insertChild(
1547
+ this.node,
1548
+ this.parent.node.getChildCount()
1549
+ );
1550
+ if (parent.props.flexDirection) {
1551
+ this.parent.node.calculateLayout();
1552
+ for (let child of this.parent.children) {
1553
+ const { left, top } = child.getComputedLayout();
1554
+ child.x = left;
1555
+ child.y = top;
1556
+ }
1557
+ }
1558
+ }
1559
+ }
1560
+ effectSize(width, height) {
1561
+ const handleSize = (size, setter, parentSize) => {
1562
+ if (typeof size === "string" && size.endsWith("%")) {
1563
+ effect3(() => {
1564
+ setter(parentSize() * (parseInt(size) / 100));
1565
+ if (this.isFlex) {
1566
+ __privateMethod(this, _DisplayObject_instances, applyFlexLayout_fn).call(this);
1567
+ }
1568
+ });
1569
+ } else {
1570
+ setter(+size);
1571
+ }
1572
+ };
1573
+ if (width != void 0)
1574
+ handleSize(width, this.setWidth.bind(this), this.parent.displayWidth);
1575
+ if (height != void 0)
1576
+ handleSize(
1577
+ height,
1578
+ this.setHeight.bind(this),
1579
+ this.parent.displayHeight
1580
+ );
1581
+ }
1582
+ onUpdate(props) {
1583
+ this.fullProps = {
1584
+ ...this.fullProps,
1585
+ ...props
1586
+ };
1587
+ if (!__privateGet(this, _canvasContext) || !this.parent) return;
1588
+ if (props.x !== void 0) this.setX(props.x);
1589
+ if (props.y !== void 0) this.setY(props.y);
1590
+ if (props.scale !== void 0)
1591
+ setObservablePoint(this.scale, props.scale);
1592
+ if (props.anchor !== void 0 && !this.isCustomAnchor) {
1593
+ setObservablePoint(this.anchor, props.anchor);
1594
+ }
1595
+ if (props.skew !== void 0) setObservablePoint(this.skew, props.skew);
1596
+ if (props.tint) this.tint = props.tint;
1597
+ if (props.rotation !== void 0) this.rotation = props.rotation;
1598
+ if (props.angle !== void 0) this.angle = props.angle;
1599
+ if (props.zIndex !== void 0) this.zIndex = props.zIndex;
1600
+ if (props.roundPixels !== void 0) this.roundPixels = props.roundPixels;
1601
+ if (props.cursor) this.cursor = props.cursor;
1602
+ if (props.visible !== void 0) this.visible = props.visible;
1603
+ if (props.alpha !== void 0) this.alpha = props.alpha;
1604
+ if (props.pivot) setObservablePoint(this.pivot, props.pivot);
1605
+ if (props.flexDirection) this.setFlexDirection(props.flexDirection);
1606
+ if (props.flexWrap) this.setFlexWrap(props.flexWrap);
1607
+ if (props.justifyContent) this.setJustifyContent(props.justifyContent);
1608
+ if (props.alignItems) this.setAlignItems(props.alignItems);
1609
+ if (props.alignContent) this.setAlignContent(props.alignContent);
1610
+ if (props.alignSelf) this.setAlignSelf(props.alignSelf);
1611
+ if (props.margin) this.setMargin(props.margin);
1612
+ if (props.padding) this.setPadding(props.padding);
1613
+ if (props.gap) this.setGap(props.gap);
1614
+ if (props.border) this.setBorder(props.border);
1615
+ if (props.positionType) this.setPositionType(props.positionType);
1616
+ if (props.filters) this.filters = props.filters;
1617
+ if (props.maskOf) {
1618
+ if (isElement(props.maskOf)) {
1619
+ props.maskOf.componentInstance.mask = this;
1620
+ }
1621
+ }
1622
+ if (props.blendMode) this.blendMode = props.blendMode;
1623
+ if (props.filterArea) this.filterArea = props.filterArea;
1624
+ const currentFilters = this.filters || [];
1625
+ if (props.shadow) {
1626
+ let dropShadowFilter = currentFilters.find(
1627
+ (filter) => filter instanceof DropShadowFilter
1628
+ );
1629
+ if (!dropShadowFilter) {
1630
+ dropShadowFilter = new DropShadowFilter();
1631
+ currentFilters.push(dropShadowFilter);
1632
+ }
1633
+ Object.assign(dropShadowFilter, props.shadow);
1634
+ }
1635
+ if (props.blur) {
1636
+ let blurFilter = currentFilters.find(
1637
+ (filter) => filter instanceof BlurFilter
1638
+ );
1639
+ if (!blurFilter) {
1640
+ const options = typeof props.blur === "number" ? {
1641
+ strength: props.blur
1642
+ } : props.blur;
1643
+ blurFilter = new BlurFilter(options);
1644
+ currentFilters.push(blurFilter);
1645
+ }
1646
+ Object.assign(blurFilter, props.blur);
1647
+ }
1648
+ this.filters = currentFilters;
1649
+ __privateMethod(this, _DisplayObject_instances, flexRender_fn).call(this, props);
1650
+ }
1651
+ onDestroy() {
1652
+ super.destroy();
1653
+ this.node?.freeRecursive();
1654
+ }
1655
+ getComputedLayout() {
1656
+ return this.node.getComputedLayout();
1657
+ }
1658
+ applyComputedLayout() {
1659
+ const layout = this.getComputedLayout();
1660
+ this.x = layout.left;
1661
+ this.y = layout.top;
1662
+ }
1663
+ calculateLayout() {
1664
+ this.node.calculateLayout();
1665
+ }
1666
+ setFlexDirection(direction) {
1667
+ const mapping = {
1668
+ row: this.yoga.FLEX_DIRECTION_ROW,
1669
+ column: this.yoga.FLEX_DIRECTION_COLUMN,
1670
+ "row-reverse": this.yoga.FLEX_DIRECTION_ROW_REVERSE,
1671
+ "column-reverse": this.yoga.FLEX_DIRECTION_COLUMN_REVERSE
1672
+ };
1673
+ this.node.setFlexDirection(mapping[direction]);
1674
+ }
1675
+ setFlexWrap(wrap) {
1676
+ const mapping = {
1677
+ wrap: this.yoga.WRAP_WRAP,
1678
+ nowrap: this.yoga.WRAP_NO_WRAP,
1679
+ "wrap-reverse": this.yoga.WRAP_WRAP_REVERSE
1680
+ };
1681
+ this.node.setFlexWrap(mapping[wrap]);
1682
+ }
1683
+ setAlignContent(align) {
1684
+ __privateMethod(this, _DisplayObject_instances, setAlign_fn).call(this, "setAlignContent", align);
1685
+ }
1686
+ setAlignSelf(align) {
1687
+ __privateMethod(this, _DisplayObject_instances, setAlign_fn).call(this, "setAlignSelf", align);
1688
+ }
1689
+ setAlignItems(align) {
1690
+ __privateMethod(this, _DisplayObject_instances, setAlign_fn).call(this, "setAlignItems", align);
1691
+ }
1692
+ setJustifyContent(justifyContent) {
1693
+ const mapping = {
1694
+ "flex-start": this.yoga.JUSTIFY_FLEX_START,
1695
+ "flex-end": this.yoga.JUSTIFY_FLEX_END,
1696
+ center: this.yoga.JUSTIFY_CENTER,
1697
+ "space-between": this.yoga.JUSTIFY_SPACE_BETWEEN,
1698
+ "space-around": this.yoga.JUSTIFY_SPACE_AROUND
1699
+ };
1700
+ this.node.setJustifyContent(mapping[justifyContent]);
1701
+ }
1702
+ setPosition(position) {
1703
+ __privateMethod(this, _DisplayObject_instances, setEdgeSize_fn).call(this, "setPosition", position);
1704
+ }
1705
+ setX(x) {
1706
+ x = x + this.getWidth() * this._anchorPoints.x;
1707
+ if (!this.parent.isFlex) {
1708
+ this.x = x;
1709
+ }
1710
+ this.node.setPosition(this.yoga.EDGE_LEFT, x);
1711
+ }
1712
+ setY(y) {
1713
+ y = y + this.getHeight() * this._anchorPoints.y;
1714
+ if (!this.parent.isFlex) {
1715
+ this.y = y;
1716
+ }
1717
+ this.node.setPosition(this.yoga.EDGE_TOP, y);
1718
+ }
1719
+ setPadding(padding) {
1720
+ __privateMethod(this, _DisplayObject_instances, setEdgeSize_fn).call(this, "setPadding", padding);
1721
+ }
1722
+ setMargin(margin) {
1723
+ __privateMethod(this, _DisplayObject_instances, setEdgeSize_fn).call(this, "setMargin", margin);
1724
+ }
1725
+ setGap(gap) {
1726
+ this.node.setGap(this.yoga.GAP_ALL, +gap);
1727
+ }
1728
+ setBorder(border) {
1729
+ __privateMethod(this, _DisplayObject_instances, setEdgeSize_fn).call(this, "setBorder", border);
1730
+ }
1731
+ setPositionType(positionType) {
1732
+ const mapping = {
1733
+ relative: this.yoga.POSITION_TYPE_RELATIVE,
1734
+ absolute: this.yoga.POSITION_TYPE_ABSOLUTE
1735
+ };
1736
+ this.node.setPositionType(mapping[positionType]);
1737
+ }
1738
+ calculateBounds() {
1739
+ super.calculateBounds();
1740
+ if (!this._geometry) return;
1741
+ const bounds = this._geometry.bounds;
1742
+ const width = Math.abs(bounds.minX - bounds.maxX);
1743
+ const height = Math.abs(bounds.minY - bounds.maxY);
1744
+ }
1745
+ setWidth(width) {
1746
+ this.displayWidth.set(width);
1747
+ this.node?.setWidth(width);
1748
+ }
1749
+ setHeight(height) {
1750
+ this.displayHeight.set(height);
1751
+ this.node?.setHeight(height);
1752
+ }
1753
+ getWidth() {
1754
+ return this.displayWidth();
1755
+ }
1756
+ getHeight() {
1757
+ return this.displayHeight();
1758
+ }
1759
+ }, _canvasContext = new WeakMap(), _DisplayObject_instances = new WeakSet(), applyFlexLayout_fn = function() {
1760
+ this.calculateLayout();
1761
+ for (let child of this.children) {
1762
+ const { left, top } = child.node.getComputedLayout();
1763
+ child.x = left;
1764
+ child.y = top;
1765
+ }
1766
+ }, flexRender_fn = function(props) {
1767
+ if (!this.parent) return;
1768
+ if (props.flexDirection || props.justifyContent) {
1769
+ this.isFlex = true;
1770
+ __privateMethod(this, _DisplayObject_instances, applyFlexLayout_fn).call(this);
1771
+ }
1772
+ }, setAlign_fn = function(methodName, align) {
1773
+ const mapping = {
1774
+ auto: this.yoga.ALIGN_AUTO,
1775
+ "flex-start": this.yoga.ALIGN_FLEX_START,
1776
+ "flex-end": this.yoga.ALIGN_FLEX_END,
1777
+ center: this.yoga.ALIGN_CENTER,
1778
+ stretch: this.yoga.ALIGN_STRETCH,
1779
+ baseline: this.yoga.ALIGN_BASELINE,
1780
+ "space-between": this.yoga.ALIGN_SPACE_BETWEEN,
1781
+ "space-around": this.yoga.ALIGN_SPACE_AROUND
1782
+ };
1783
+ const method = this.node[methodName].bind(this.node);
1784
+ method(mapping[align]);
1785
+ }, setEdgeSize_fn = function(methodName, size) {
1786
+ const method = this.node[methodName].bind(this.node);
1787
+ if (size instanceof Array) {
1788
+ if (size.length === 2) {
1789
+ method(this.yoga.EDGE_VERTICAL, size[0]);
1790
+ method(this.yoga.EDGE_HORIZONTAL, size[1]);
1791
+ } else if (size.length === 4) {
1792
+ method(this.yoga.EDGE_TOP, size[0]);
1793
+ method(this.yoga.EDGE_RIGHT, size[1]);
1794
+ method(this.yoga.EDGE_BOTTOM, size[2]);
1795
+ method(this.yoga.EDGE_LEFT, size[3]);
1796
+ }
1797
+ } else {
1798
+ method(this.yoga.EDGE_ALL, size);
1799
+ }
1800
+ }, _a;
1801
+ }
1802
+
1803
+ // src/components/Canvas.ts
1804
+ registerComponent("Canvas", class Canvas extends DisplayObject(Container3) {
1805
+ });
1806
+ var Canvas2 = async (props = {}) => {
1807
+ let { cursorStyles, width, height, class: className } = useProps(props);
1808
+ const Yoga = await loadYoga();
1809
+ if (!props.width) width = signal3(800);
1810
+ if (!props.height) height = signal3(600);
1811
+ const renderer = await autoDetectRenderer({
1812
+ ...props,
1813
+ width: width?.(),
1814
+ height: height?.()
1815
+ });
1816
+ const canvasSize = signal3({
1817
+ width: renderer.width,
1818
+ height: renderer.height
1819
+ });
1820
+ props.isRoot = true;
1821
+ const options = {
1822
+ ...props,
1823
+ context: {
1824
+ Yoga,
1825
+ renderer,
1826
+ canvasSize
1827
+ },
1828
+ width: width?.(),
1829
+ height: height?.()
1830
+ };
1831
+ if (!props.tick) {
1832
+ options.context.tick = options.tick = signal3({
1833
+ timestamp: 0,
1834
+ deltaTime: 0,
1835
+ frame: 0,
1836
+ deltaRatio: 1
1837
+ });
1838
+ }
1839
+ const canvasElement = createComponent("Canvas", options);
1840
+ canvasElement.render = (rootElement) => {
1841
+ const canvasEl = renderer.view.canvas;
1842
+ globalThis.__PIXI_STAGE__ = canvasElement.componentInstance;
1843
+ globalThis.__PIXI_RENDERER__ = renderer;
1844
+ if (props.tickStart !== false) canvasElement.directives.tick.start();
1845
+ effect4(() => {
1846
+ canvasElement.propObservables.tick();
1847
+ renderer.render(canvasElement.componentInstance);
1848
+ });
1849
+ if (cursorStyles) {
1850
+ effect4(() => {
1851
+ renderer.events.cursorStyles = cursorStyles();
1852
+ });
1853
+ }
1854
+ if (className) {
1855
+ effect4(() => {
1856
+ canvasEl.classList.add(className());
1857
+ });
1858
+ }
1859
+ const resizeCanvas = async () => {
1860
+ let w, h2;
1861
+ if (width?.() === "100%" && height?.() === "100%") {
1862
+ const parent = canvasEl.parentElement;
1863
+ w = parent ? parent.clientWidth : window.innerWidth;
1864
+ h2 = parent ? parent.clientHeight : window.innerHeight;
1865
+ } else {
1866
+ w = width?.() ?? canvasEl.offsetWidth;
1867
+ h2 = height?.() ?? canvasEl.offsetHeight;
1868
+ }
1869
+ renderer.resize(w, h2);
1870
+ canvasSize.set({ width: w, height: h2 });
1871
+ canvasElement.componentInstance.setWidth(w);
1872
+ canvasElement.componentInstance.setHeight(h2);
1873
+ };
1874
+ window.addEventListener("resize", resizeCanvas);
1875
+ const existingCanvas = rootElement.querySelector("canvas");
1876
+ if (existingCanvas) {
1877
+ rootElement.replaceChild(canvasEl, existingCanvas);
1878
+ } else {
1879
+ rootElement.appendChild(canvasEl);
1880
+ }
1881
+ resizeCanvas();
1882
+ };
1883
+ return canvasElement;
1884
+ };
1885
+
1886
+ // src/components/Container.ts
1887
+ import { Container as PixiContainer } from "pixi.js";
1888
+ var CanvasContainer = class extends DisplayObject(PixiContainer) {
1889
+ constructor() {
1890
+ super(...arguments);
1891
+ this.isCustomAnchor = true;
1892
+ }
1893
+ onUpdate(props) {
1894
+ if (props.anchor) {
1895
+ setObservablePoint(this._anchorPoints, props.anchor);
1896
+ props.pivot = [
1897
+ this.getWidth() * this._anchorPoints.x,
1898
+ this.getHeight() * this._anchorPoints.y
1899
+ ];
1900
+ }
1901
+ super.onUpdate(props);
1902
+ if (props.sortableChildren != void 0) {
1903
+ this.sortableChildren = props.sortableChildren;
1904
+ }
1905
+ }
1906
+ onMount(args) {
1907
+ super.onMount(args);
1908
+ const { componentInstance, props } = args;
1909
+ const { pixiChildren } = props;
1910
+ if (pixiChildren) {
1911
+ pixiChildren.forEach((child) => {
1912
+ componentInstance.addChild(child);
1913
+ });
1914
+ }
1915
+ }
1916
+ };
1917
+ registerComponent("Container", CanvasContainer);
1918
+ var Container4 = (props) => {
1919
+ return createComponent("Container", props);
1920
+ };
1921
+
1922
+ // src/components/Graphic.ts
1923
+ import { effect as effect5 } from "@signe/reactive";
1924
+ import { Graphics as PixiGraphics } from "pixi.js";
1925
+ var CanvasGraphics = class extends DisplayObject(PixiGraphics) {
1926
+ onInit(props) {
1927
+ super.onInit(props);
1928
+ if (props.draw) {
1929
+ effect5(() => {
1930
+ this.clear();
1931
+ props.draw?.(this);
1932
+ });
1933
+ }
1934
+ }
1935
+ };
1936
+ registerComponent("Graphics", CanvasGraphics);
1937
+ function Graphics(props) {
1938
+ return createComponent("Graphics", props);
1939
+ }
1940
+ function Rect(props) {
1941
+ const { width, height, color, borderRadius, border } = useProps(props, {
1942
+ borderRadius: null,
1943
+ border: null
1944
+ });
1945
+ return Graphics({
1946
+ draw: (g) => {
1947
+ if (borderRadius()) {
1948
+ g.roundRect(0, 0, width(), height(), borderRadius());
1949
+ } else {
1950
+ g.rect(0, 0, width(), height());
1951
+ }
1952
+ if (border) {
1953
+ g.stroke(border);
1954
+ }
1955
+ g.fill(color());
1956
+ },
1957
+ ...props
1958
+ });
1959
+ }
1960
+ function drawShape(g, shape, props) {
1961
+ const { color, border } = props;
1962
+ if ("radius" in props) {
1963
+ g.circle(0, 0, props.radius());
1964
+ } else {
1965
+ g.ellipse(0, 0, props.width() / 2, props.height() / 2);
1966
+ }
1967
+ if (border()) {
1968
+ g.stroke(border());
1969
+ }
1970
+ g.fill(color());
1971
+ }
1972
+ function Circle(props) {
1973
+ const { radius, color, border } = useProps(props, {
1974
+ border: null
1975
+ });
1976
+ return Graphics({
1977
+ draw: (g) => drawShape(g, "circle", { radius, color, border }),
1978
+ ...props
1979
+ });
1980
+ }
1981
+ function Ellipse(props) {
1982
+ const { width, height, color, border } = useProps(props, {
1983
+ border: null
1984
+ });
1985
+ return Graphics({
1986
+ draw: (g) => drawShape(g, "ellipse", { width, height, color, border }),
1987
+ ...props
1988
+ });
1989
+ }
1990
+ function Triangle(props) {
1991
+ const { width, height, color, border } = useProps(props, {
1992
+ border: null,
1993
+ color: "#000"
1994
+ });
1995
+ return Graphics({
1996
+ draw: (g) => {
1997
+ g.moveTo(0, height());
1998
+ g.lineTo(width() / 2, 0);
1999
+ g.lineTo(width(), height());
2000
+ g.lineTo(0, height());
2001
+ g.fill(color());
2002
+ if (border) {
2003
+ g.stroke(border);
2004
+ }
2005
+ },
2006
+ ...props
2007
+ });
2008
+ }
2009
+ function Svg(props) {
2010
+ return Graphics({
2011
+ draw: (g) => g.svg(props.svg),
2012
+ ...props
2013
+ });
2014
+ }
2015
+
2016
+ // src/engine/signal.ts
2017
+ var currentSubscriptionsTracker = null;
2018
+ var mountTracker = null;
2019
+ function mount(fn) {
2020
+ mountTracker?.(fn);
2021
+ }
2022
+ function tick(fn) {
2023
+ mount((el) => {
2024
+ const { context } = el.props;
2025
+ let subscription;
2026
+ if (context.tick) {
2027
+ subscription = context.tick.observable.subscribe(({ value }) => {
2028
+ fn(value, el);
2029
+ });
2030
+ }
2031
+ return () => {
2032
+ subscription?.unsubscribe();
2033
+ };
2034
+ });
2035
+ }
2036
+ function h(componentFunction, props = {}, ...children) {
2037
+ const allSubscriptions = /* @__PURE__ */ new Set();
2038
+ const allMounts = /* @__PURE__ */ new Set();
2039
+ currentSubscriptionsTracker = (subscription) => {
2040
+ allSubscriptions.add(subscription);
2041
+ };
2042
+ mountTracker = (fn) => {
2043
+ allMounts.add(fn);
2044
+ };
2045
+ if (children[0] instanceof Array) {
2046
+ children = children[0];
2047
+ }
2048
+ let component = componentFunction({ ...props, children });
2049
+ if (!component) {
2050
+ component = {};
2051
+ }
2052
+ component.effectSubscriptions = Array.from(allSubscriptions);
2053
+ component.effectMounts = [
2054
+ ...Array.from(allMounts),
2055
+ ...component.effectMounts ?? []
2056
+ ];
2057
+ if (component instanceof Promise) {
2058
+ component.then((component2) => {
2059
+ if (component2.props.isRoot) {
2060
+ allMounts.forEach((fn) => fn(component2));
2061
+ }
2062
+ });
2063
+ }
2064
+ currentSubscriptionsTracker = null;
2065
+ mountTracker = null;
2066
+ return component;
2067
+ }
2068
+
2069
+ // src/components/Scene.ts
2070
+ function Scene(props) {
2071
+ return h(Container4);
2072
+ }
2073
+
2074
+ // src/components/ParticleEmitter.ts
2075
+ import * as particles from "@barvynkoa/particle-emitter";
2076
+ var CanvasParticlesEmitter = class extends CanvasContainer {
2077
+ constructor() {
2078
+ super(...arguments);
2079
+ this.elapsed = Date.now();
2080
+ }
2081
+ onMount(params) {
2082
+ super.onMount(params);
2083
+ const { props } = params;
2084
+ const tick2 = props.context.tick;
2085
+ this.emitter = new particles.Emitter(this, props.config);
2086
+ this.subscriptionTick = tick2.observable.subscribe((value) => {
2087
+ if (!this.emitter) return;
2088
+ const now = Date.now();
2089
+ this.emitter.update((now - this.elapsed) * 1e-3);
2090
+ this.elapsed = now;
2091
+ });
2092
+ }
2093
+ onUpdate(props) {
2094
+ }
2095
+ onDestroy() {
2096
+ super.onDestroy();
2097
+ this.emitter?.destroy();
2098
+ this.emitter = null;
2099
+ this.subscriptionTick.unsubscribe();
2100
+ }
2101
+ };
2102
+ registerComponent("ParticlesEmitter", CanvasParticlesEmitter);
2103
+ function ParticlesEmitter(props) {
2104
+ return createComponent("ParticlesEmitter", props);
2105
+ }
2106
+
2107
+ // src/components/Sprite.ts
2108
+ import { computed, effect as effect7, isSignal as isSignal4 } from "@signe/reactive";
2109
+ import {
2110
+ Assets,
2111
+ Container as Container5,
2112
+ Sprite as PixiSprite,
2113
+ Rectangle as Rectangle2,
2114
+ Texture as Texture2
2115
+ } from "pixi.js";
2116
+
2117
+ // src/engine/animation.ts
2118
+ import { effect as effect6, signal as signal4 } from "@signe/reactive";
2119
+ import { animate as animatePopmotion } from "popmotion";
2120
+ function isAnimatedSignal(signal6) {
2121
+ return signal6.animatedState !== void 0;
2122
+ }
2123
+ function animatedSignal(initialValue, options = {}) {
2124
+ const state = {
2125
+ current: initialValue,
2126
+ start: initialValue,
2127
+ end: initialValue
2128
+ };
2129
+ let animation;
2130
+ const publicSignal = signal4(initialValue);
2131
+ const privateSignal = signal4(state);
2132
+ effect6(() => {
2133
+ const currentState = privateSignal();
2134
+ publicSignal.set(currentState.current);
2135
+ });
2136
+ function animatedSignal2(newValue) {
2137
+ if (newValue === void 0) {
2138
+ return privateSignal();
2139
+ }
2140
+ const prevState = privateSignal();
2141
+ const newState = {
2142
+ current: prevState.current,
2143
+ start: prevState.current,
2144
+ end: newValue
2145
+ };
2146
+ privateSignal.set(newState);
2147
+ if (animation) {
2148
+ animation.stop();
2149
+ }
2150
+ animation = animatePopmotion({
2151
+ // TODO
2152
+ duration: 20,
2153
+ ...options,
2154
+ from: prevState.current,
2155
+ to: newValue,
2156
+ onUpdate: (value) => {
2157
+ privateSignal.update((s) => ({ ...s, current: value }));
2158
+ if (options.onUpdate) {
2159
+ options.onUpdate(value);
2160
+ }
2161
+ }
2162
+ });
2163
+ }
2164
+ const fn = function() {
2165
+ return privateSignal().current;
2166
+ };
2167
+ for (const key in publicSignal) {
2168
+ fn[key] = publicSignal[key];
2169
+ }
2170
+ fn.animatedState = privateSignal;
2171
+ fn.update = (updater) => {
2172
+ animatedSignal2(updater(privateSignal().current));
2173
+ };
2174
+ fn.set = (newValue) => {
2175
+ animatedSignal2(newValue);
2176
+ };
2177
+ return fn;
2178
+ }
2179
+
2180
+ // src/components/Sprite.ts
2181
+ var log = console.log;
2182
+ var CanvasSprite = class extends DisplayObject(PixiSprite) {
2183
+ constructor() {
2184
+ super(...arguments);
2185
+ this.currentAnimation = null;
2186
+ this.time = 0;
2187
+ this.frameIndex = 0;
2188
+ this.animations = /* @__PURE__ */ new Map();
2189
+ this.subscriptionSheet = [];
2190
+ this.sheetParams = {};
2191
+ this.sheetCurrentAnimation = "stand" /* Stand */;
2192
+ this.currentAnimationContainer = null;
2193
+ }
2194
+ async createTextures(options) {
2195
+ const { width, height, framesHeight, framesWidth, image, offset } = options;
2196
+ const texture = await Assets.load(image);
2197
+ const spriteWidth = options.spriteWidth;
2198
+ const spriteHeight = options.spriteHeight;
2199
+ const frames = [];
2200
+ const offsetX = offset && offset.x || 0;
2201
+ const offsetY = offset && offset.y || 0;
2202
+ for (let i = 0; i < framesHeight; i++) {
2203
+ frames[i] = [];
2204
+ for (let j = 0; j < framesWidth; j++) {
2205
+ const rectX = j * spriteWidth + offsetX;
2206
+ const rectY = i * spriteHeight + offsetY;
2207
+ if (rectY > height) {
2208
+ throw log(
2209
+ `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.`
2210
+ );
2211
+ }
2212
+ if (rectX > width) {
2213
+ throw log(
2214
+ `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.`
2215
+ );
2216
+ }
2217
+ frames[i].push(
2218
+ new Texture2({
2219
+ source: texture.source,
2220
+ frame: new Rectangle2(rectX, rectY, spriteWidth, spriteHeight)
2221
+ })
2222
+ );
2223
+ }
2224
+ }
2225
+ return frames;
2226
+ }
2227
+ async createAnimations() {
2228
+ const { textures } = this.spritesheet;
2229
+ if (!textures) {
2230
+ return;
2231
+ }
2232
+ for (let animationName in textures) {
2233
+ const props = [
2234
+ "width",
2235
+ "height",
2236
+ "framesHeight",
2237
+ "framesWidth",
2238
+ "rectWidth",
2239
+ "rectHeight",
2240
+ "offset",
2241
+ "image",
2242
+ "sound"
2243
+ ];
2244
+ const parentObj = props.reduce(
2245
+ (prev, val) => ({ ...prev, [val]: this.spritesheet[val] }),
2246
+ {}
2247
+ );
2248
+ const optionsTextures = {
2249
+ ...parentObj,
2250
+ ...textures[animationName]
2251
+ };
2252
+ const {
2253
+ rectWidth,
2254
+ width = 0,
2255
+ framesWidth = 1,
2256
+ rectHeight,
2257
+ height = 0,
2258
+ framesHeight = 1
2259
+ } = optionsTextures;
2260
+ optionsTextures.spriteWidth = rectWidth ? rectWidth : width / framesWidth;
2261
+ optionsTextures.spriteHeight = rectHeight ? rectHeight : height / framesHeight;
2262
+ this.animations.set(animationName, {
2263
+ frames: await this.createTextures(
2264
+ optionsTextures
2265
+ ),
2266
+ name: animationName,
2267
+ animations: textures[animationName].animations,
2268
+ params: [],
2269
+ data: optionsTextures,
2270
+ sprites: []
2271
+ });
2272
+ }
2273
+ }
2274
+ async onMount(params) {
2275
+ const { props, propObservables } = params;
2276
+ const tick2 = props.context.tick;
2277
+ const sheet = props.sheet ?? {};
2278
+ if (sheet?.onFinish) {
2279
+ this.onFinish = sheet.onFinish;
2280
+ }
2281
+ this.subscriptionTick = tick2.observable.subscribe((value) => {
2282
+ this.update(value);
2283
+ });
2284
+ if (props.sheet?.definition) {
2285
+ this.spritesheet = props.sheet.definition;
2286
+ await this.createAnimations();
2287
+ }
2288
+ if (sheet.params) {
2289
+ for (let key in propObservables?.sheet["params"]) {
2290
+ const value = propObservables?.sheet["params"][key];
2291
+ if (isSignal4(value)) {
2292
+ this.subscriptionSheet.push(
2293
+ value.observable.subscribe((value2) => {
2294
+ if (this.animations.size == 0) return;
2295
+ this.play(this.sheetCurrentAnimation, [{ [key]: value2 }]);
2296
+ })
2297
+ );
2298
+ } else {
2299
+ this.play(this.sheetCurrentAnimation, [{ [key]: value }]);
2300
+ }
2301
+ }
2302
+ }
2303
+ const isMoving = computed(() => {
2304
+ const { x, y } = propObservables ?? {};
2305
+ if (!x || !y) return false;
2306
+ const xSignal = x;
2307
+ const ySignal = y;
2308
+ const isMovingX = isAnimatedSignal(xSignal) && xSignal.animatedState().current !== xSignal.animatedState().end;
2309
+ const isMovingY = isAnimatedSignal(ySignal) && ySignal.animatedState().current !== ySignal.animatedState().end;
2310
+ return isMovingX || isMovingY;
2311
+ });
2312
+ effect7(() => {
2313
+ const _isMoving = isMoving();
2314
+ if (!this.isMounted) return;
2315
+ if (_isMoving) {
2316
+ this.sheetCurrentAnimation = "walk" /* Walk */;
2317
+ } else {
2318
+ this.sheetCurrentAnimation = "stand" /* Stand */;
2319
+ }
2320
+ this.play(this.sheetCurrentAnimation, [this.sheetParams]);
2321
+ });
2322
+ super.onMount(params);
2323
+ }
2324
+ async onUpdate(props) {
2325
+ super.onUpdate(props);
2326
+ const sheet = props.sheet;
2327
+ if (sheet?.params) this.sheetParams = sheet?.params;
2328
+ if (sheet?.playing && this.isMounted) {
2329
+ this.sheetCurrentAnimation = sheet?.playing;
2330
+ this.play(this.sheetCurrentAnimation, [this.sheetParams]);
2331
+ }
2332
+ if (props.hitbox) this.hitbox = props.hitbox;
2333
+ if (props.scaleMode) this.baseTexture.scaleMode = props.scaleMode;
2334
+ else if (props.image && this.fullProps.rectangle === void 0) {
2335
+ this.texture = await Assets.load(this.fullProps.image);
2336
+ } else if (props.texture) {
2337
+ this.texture = props.texture;
2338
+ }
2339
+ if (props.rectangle !== void 0) {
2340
+ const { x, y, width, height } = props.rectangle?.value ?? props.rectangle;
2341
+ const texture = await Assets.load(this.fullProps.image);
2342
+ this.texture = new Texture2({
2343
+ source: texture.source,
2344
+ frame: new Rectangle2(x, y, width, height)
2345
+ });
2346
+ }
2347
+ }
2348
+ onDestroy() {
2349
+ super.onDestroy();
2350
+ this.subscriptionSheet.forEach((sub) => sub.unsubscribe());
2351
+ this.subscriptionTick.unsubscribe();
2352
+ if (this.currentAnimationContainer && this.parent instanceof Container5) {
2353
+ this.parent.removeChild(this.currentAnimationContainer);
2354
+ }
2355
+ }
2356
+ has(name) {
2357
+ return this.animations.has(name);
2358
+ }
2359
+ get(name) {
2360
+ return this.animations.get(name);
2361
+ }
2362
+ isPlaying(name) {
2363
+ if (!name) return !!this.currentAnimation;
2364
+ if (this.currentAnimation == null) return false;
2365
+ return this.currentAnimation.name == name;
2366
+ }
2367
+ stop() {
2368
+ this.currentAnimation = null;
2369
+ this.destroy();
2370
+ }
2371
+ play(name, params = []) {
2372
+ const animParams = this.currentAnimation?.params;
2373
+ if (this.isPlaying(name) && arrayEquals(params, animParams || [])) return;
2374
+ const animation = this.get(name);
2375
+ if (!animation) {
2376
+ throw new Error(
2377
+ `Impossible to play the ${name} animation because it doesn't exist on the "${this.id}" spritesheet`
2378
+ );
2379
+ }
2380
+ const cloneParams = structuredClone(params);
2381
+ this.removeChildren();
2382
+ animation.sprites = [];
2383
+ this.currentAnimation = animation;
2384
+ this.currentAnimation.params = cloneParams;
2385
+ this.time = 0;
2386
+ this.frameIndex = 0;
2387
+ let animations = animation.animations;
2388
+ animations = isFunction(animations) ? animations(...cloneParams) : animations;
2389
+ this.currentAnimationContainer = new Container5();
2390
+ for (let container of animations) {
2391
+ const sprite = new PixiSprite();
2392
+ for (let frame of container) {
2393
+ this.currentAnimation.sprites.push(frame);
2394
+ }
2395
+ this.currentAnimationContainer.addChild(sprite);
2396
+ }
2397
+ const sound = this.currentAnimation.data.sound;
2398
+ if (sound) {
2399
+ }
2400
+ this.update({
2401
+ deltaRatio: 1
2402
+ });
2403
+ }
2404
+ update({ deltaRatio }) {
2405
+ if (!this.isPlaying() || !this.currentAnimation || !this.currentAnimationContainer)
2406
+ return;
2407
+ const self = this;
2408
+ const { frames, sprites, data } = this.currentAnimation;
2409
+ let frame = sprites[this.frameIndex];
2410
+ const nextFrame = sprites[this.frameIndex + 1];
2411
+ for (let _sprite of this.currentAnimationContainer.children) {
2412
+ let applyTransformValue = function(prop, alias) {
2413
+ const optionProp = alias || prop;
2414
+ const val = getVal(optionProp);
2415
+ if (val !== void 0) {
2416
+ self[prop] = val;
2417
+ }
2418
+ };
2419
+ const sprite = _sprite;
2420
+ if (!frame || frame.frameY == void 0 || frame.frameX == void 0) {
2421
+ continue;
2422
+ }
2423
+ this.texture = frames[frame.frameY][frame.frameX];
2424
+ const getVal = (prop) => {
2425
+ return frame[prop] ?? data[prop] ?? this.spritesheet[prop];
2426
+ };
2427
+ const applyTransform = (prop) => {
2428
+ const val = getVal(prop);
2429
+ if (val) {
2430
+ this[prop].set(...val);
2431
+ }
2432
+ };
2433
+ if (this.applyTransform) {
2434
+ frame = {
2435
+ ...frame,
2436
+ ...this.applyTransform(frame, data, this.spritesheet)
2437
+ };
2438
+ }
2439
+ const realSize = getVal("spriteRealSize");
2440
+ const heightOfSprite = typeof realSize == "number" ? realSize : realSize?.height;
2441
+ const widthOfSprite = typeof realSize == "number" ? realSize : realSize?.width;
2442
+ const applyAnchorBySize = () => {
2443
+ if (heightOfSprite && this.hitbox) {
2444
+ const { spriteWidth, spriteHeight } = data;
2445
+ const w = (spriteWidth - this.hitbox.w) / 2 / spriteWidth;
2446
+ const gap = (spriteHeight - heightOfSprite) / 2;
2447
+ const h2 = (spriteHeight - this.hitbox.h - gap) / spriteHeight;
2448
+ this.anchor.set(w, h2);
2449
+ }
2450
+ };
2451
+ if (frame.sound) {
2452
+ }
2453
+ applyAnchorBySize();
2454
+ applyTransform("anchor");
2455
+ applyTransform("scale");
2456
+ applyTransform("skew");
2457
+ applyTransform("pivot");
2458
+ applyTransformValue("alpha", "opacity");
2459
+ applyTransformValue("x");
2460
+ applyTransformValue("y");
2461
+ applyTransformValue("angle");
2462
+ applyTransformValue("rotation");
2463
+ applyTransformValue("visible");
2464
+ }
2465
+ if (!nextFrame) {
2466
+ this.time = 0;
2467
+ this.frameIndex = 0;
2468
+ if (this.onFinish && sprites.length > 1) this.onFinish();
2469
+ return;
2470
+ }
2471
+ this.time += deltaRatio ?? 1;
2472
+ if (this.time >= nextFrame.time) {
2473
+ this.frameIndex++;
2474
+ }
2475
+ }
2476
+ };
2477
+ registerComponent("Sprite", CanvasSprite);
2478
+ var Sprite2 = (props) => {
2479
+ return createComponent("Sprite", props);
2480
+ };
2481
+
2482
+ // src/components/Text.ts
2483
+ import { Text as PixiText } from "pixi.js";
2484
+
2485
+ // src/engine/trigger.ts
2486
+ import { effect as effect8, signal as signal5 } from "@signe/reactive";
2487
+ function isTrigger(arg) {
2488
+ return arg?.start && arg?.listen;
2489
+ }
2490
+ function trigger(config) {
2491
+ const _signal = signal5(0);
2492
+ return {
2493
+ start: () => {
2494
+ _signal.set(Math.random());
2495
+ },
2496
+ listen: () => {
2497
+ return {
2498
+ config,
2499
+ seed: _signal()
2500
+ };
2501
+ }
2502
+ };
2503
+ }
2504
+ function on(triggerSignal, callback) {
2505
+ if (!isTrigger(triggerSignal)) {
2506
+ throw new Error("In 'on(arg)' must have a trigger signal type");
2507
+ }
2508
+ effect8(() => {
2509
+ const result = triggerSignal.listen();
2510
+ if (result?.seed) callback(result.config);
2511
+ });
2512
+ }
2513
+
2514
+ // src/components/Text.ts
2515
+ var CanvasText = class extends DisplayObject(PixiText) {
2516
+ constructor() {
2517
+ super(...arguments);
2518
+ this.fullText = "";
2519
+ this.currentIndex = 0;
2520
+ this.typewriterSpeed = 1;
2521
+ // Default speed
2522
+ this._wordWrapWidth = 0;
2523
+ this.typewriterOptions = {};
2524
+ }
2525
+ onMount(args) {
2526
+ super.onMount(args);
2527
+ const { props } = args;
2528
+ const tick2 = props.context.tick;
2529
+ if (props.text && props.typewriter) {
2530
+ this.fullText = props.text;
2531
+ this.text = "";
2532
+ this.currentIndex = 0;
2533
+ if (props.typewriter) {
2534
+ this.typewriterOptions = props.typewriter;
2535
+ if (this.typewriterOptions.skip) {
2536
+ on(this.typewriterOptions.skip, () => {
2537
+ this.skipTypewriter();
2538
+ });
2539
+ }
2540
+ }
2541
+ }
2542
+ this.subscriptionTick = tick2.observable.subscribe(() => {
2543
+ if (props.typewriter) {
2544
+ this.typewriterEffect();
2545
+ }
2546
+ });
2547
+ }
2548
+ onUpdate(props) {
2549
+ super.onUpdate(props);
2550
+ if (props.typewriter) {
2551
+ if (props.typewriter) {
2552
+ this.typewriterOptions = props.typewriter;
2553
+ }
2554
+ }
2555
+ if (props.text) {
2556
+ this.text = props.text;
2557
+ }
2558
+ if (props.text !== void 0 && props.text !== this.fullText && this.fullProps.typewriter) {
2559
+ this.text = "";
2560
+ this.currentIndex = 0;
2561
+ this.fullText = props.text;
2562
+ }
2563
+ if (props.style) {
2564
+ for (const key in props.style) {
2565
+ this.style[key] = props.style[key];
2566
+ }
2567
+ if (props.style.wordWrapWidth) {
2568
+ this._wordWrapWidth = props.style.wordWrapWidth;
2569
+ }
2570
+ }
2571
+ if (props.color) {
2572
+ this.style.fill = props.color;
2573
+ }
2574
+ if (props.size) {
2575
+ this.style.fontSize = props.size;
2576
+ }
2577
+ if (props.fontFamily) {
2578
+ this.style.fontFamily = props.fontFamily;
2579
+ }
2580
+ if (this._wordWrapWidth) {
2581
+ this.setWidth(this._wordWrapWidth);
2582
+ } else {
2583
+ this.setWidth(this.width);
2584
+ }
2585
+ this.setHeight(this.height);
2586
+ }
2587
+ get onCompleteCallback() {
2588
+ return this.typewriterOptions.onComplete;
2589
+ }
2590
+ typewriterEffect() {
2591
+ if (this.currentIndex < this.fullText.length) {
2592
+ const nextIndex = Math.min(
2593
+ this.currentIndex + (this.typewriterOptions.speed ?? 1),
2594
+ this.fullText.length
2595
+ );
2596
+ this.text = this.fullText.slice(0, nextIndex);
2597
+ this.currentIndex = nextIndex;
2598
+ if (this.currentIndex === this.fullText.length && this.onCompleteCallback) {
2599
+ this.onCompleteCallback();
2600
+ }
2601
+ }
2602
+ }
2603
+ // Add a method to skip the typewriter effect
2604
+ skipTypewriter() {
2605
+ if (this.skipSignal) {
2606
+ this.skipSignal();
2607
+ }
2608
+ this.text = this.fullText;
2609
+ this.currentIndex = this.fullText.length;
2610
+ }
2611
+ onDestroy() {
2612
+ super.onDestroy();
2613
+ this.subscriptionTick.unsubscribe();
2614
+ }
2615
+ };
2616
+ registerComponent("Text", CanvasText);
2617
+ function Text(props) {
2618
+ return createComponent("Text", props);
2619
+ }
2620
+
2621
+ // src/components/TilingSprite.ts
2622
+ import { TilingSprite as PixiTilingSprite, Texture as Texture3 } from "pixi.js";
2623
+ var CanvasTilingSprite = class extends DisplayObject(PixiTilingSprite) {
2624
+ onUpdate(props) {
2625
+ super.onUpdate(props);
2626
+ if (props.image) {
2627
+ this.texture = Texture3.from(props.image);
2628
+ }
2629
+ if (props.tileScale) {
2630
+ this.tileScale.set(props.tileScale.x, props.tileScale.y);
2631
+ }
2632
+ if (props.tilePosition) {
2633
+ this.tilePosition.set(props.tilePosition.x, props.tilePosition.y);
2634
+ }
2635
+ if (props.width !== void 0) {
2636
+ this.width = props.width;
2637
+ }
2638
+ if (props.height !== void 0) {
2639
+ this.height = props.height;
2640
+ }
2641
+ }
2642
+ };
2643
+ registerComponent("TilingSprite", CanvasTilingSprite);
2644
+ function TilingSprite(props) {
2645
+ return createComponent("TilingSprite", props);
2646
+ }
2647
+
2648
+ // src/components/Viewport.ts
2649
+ import { Viewport as PixiViewport } from "pixi-viewport";
2650
+ import { effect as effect9 } from "@signe/reactive";
2651
+ var EVENTS3 = [
2652
+ "bounce-x-end",
2653
+ "bounce-x-start",
2654
+ "bounce-y-end",
2655
+ "bounce-y-start",
2656
+ "clicked",
2657
+ "drag-end",
2658
+ "drag-start",
2659
+ "frame-end",
2660
+ "mouse-edge-end",
2661
+ "mouse-edge-start",
2662
+ "moved",
2663
+ "moved-end",
2664
+ "pinch-end",
2665
+ "pinch-start",
2666
+ "snap-end",
2667
+ "snap-start",
2668
+ "snap-zoom-end",
2669
+ "snap-zoom-start",
2670
+ "wheel-scroll",
2671
+ "zoomed",
2672
+ "zoomed-end"
2673
+ ];
2674
+ var CanvasViewport = class extends DisplayObject(PixiViewport) {
2675
+ constructor() {
2676
+ const defaultOptions = {
2677
+ noTicker: true,
2678
+ events: {
2679
+ domElement: {
2680
+ addEventListener: () => {
2681
+ }
2682
+ }
2683
+ }
2684
+ };
2685
+ super(defaultOptions);
2686
+ this.overrideProps = ["wheel"];
2687
+ }
2688
+ onInit(props) {
2689
+ super.onInit(props);
2690
+ for (let event of EVENTS3) {
2691
+ const camelCaseEvent = event.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
2692
+ if (props[camelCaseEvent]) {
2693
+ this.on(event, props[camelCaseEvent]);
2694
+ }
2695
+ }
2696
+ }
2697
+ onMount(element) {
2698
+ super.onMount(element);
2699
+ const { tick: tick2, renderer, canvasSize } = element.props.context;
2700
+ let isDragging = false;
2701
+ effect9(() => {
2702
+ this.screenWidth = canvasSize().width;
2703
+ this.screenHeight = canvasSize().height;
2704
+ });
2705
+ renderer.events.domElement.addEventListener(
2706
+ "wheel",
2707
+ this.input.wheelFunction
2708
+ );
2709
+ this.options.events = renderer.events;
2710
+ this.tickSubscription = tick2.observable.subscribe(({ value }) => {
2711
+ this.update(value.timestamp);
2712
+ });
2713
+ element.props.context.viewport = this;
2714
+ this.updateViewportSettings(element.props);
2715
+ }
2716
+ onUpdate(props) {
2717
+ super.onUpdate(props);
2718
+ this.updateViewportSettings(props);
2719
+ }
2720
+ updateViewportSettings(props) {
2721
+ if (props.screenWidth !== void 0) {
2722
+ this.screenWidth = props.screenWidth;
2723
+ }
2724
+ if (props.screenHeight !== void 0) {
2725
+ this.screenHeight = props.screenHeight;
2726
+ }
2727
+ if (props.worldWidth !== void 0) {
2728
+ this.worldWidth = props.worldWidth;
2729
+ }
2730
+ if (props.worldHeight !== void 0) {
2731
+ this.worldHeight = props.worldHeight;
2732
+ }
2733
+ if (props.clamp) {
2734
+ this.clamp(props.clamp);
2735
+ }
2736
+ if (props.wheel) {
2737
+ if (props.wheel === true) {
2738
+ this.wheel();
2739
+ } else {
2740
+ this.wheel(props.wheel);
2741
+ }
2742
+ }
2743
+ if (props.decelerate) {
2744
+ if (props.decelerate === true) {
2745
+ this.decelerate();
2746
+ } else {
2747
+ this.decelerate(props.decelerate);
2748
+ }
2749
+ }
2750
+ if (props.pinch) {
2751
+ if (props.pinch === true) {
2752
+ this.pinch();
2753
+ } else {
2754
+ this.pinch(props.pinch);
2755
+ }
2756
+ }
2757
+ }
2758
+ onDestroy() {
2759
+ super.onDestroy();
2760
+ this.tickSubscription.unsubscribe();
2761
+ }
2762
+ };
2763
+ registerComponent("Viewport", CanvasViewport);
2764
+ function Viewport(props) {
2765
+ return createComponent("Viewport", props);
2766
+ }
2767
+
2768
+ // src/components/NineSliceSprite.ts
2769
+ import { Assets as Assets2, NineSliceSprite as PixiNineSliceSprite } from "pixi.js";
2770
+ var CanvasNineSliceSprite = class extends DisplayObject(PixiNineSliceSprite) {
2771
+ constructor() {
2772
+ super({
2773
+ width: 0,
2774
+ height: 0
2775
+ });
2776
+ }
2777
+ async onUpdate(props) {
2778
+ for (const [key, value] of Object.entries(props)) {
2779
+ if (value !== void 0) {
2780
+ if (key === "image") {
2781
+ this.texture = await Assets2.load(value);
2782
+ } else if (key in this) {
2783
+ this[key] = value;
2784
+ }
2785
+ }
2786
+ }
2787
+ }
2788
+ };
2789
+ registerComponent("NineSliceSprite", CanvasNineSliceSprite);
2790
+ function NineSliceSprite(props) {
2791
+ return createComponent("NineSliceSprite", props);
2792
+ }
2793
+
2794
+ // src/engine/bootstrap.ts
2795
+ var bootstrapCanvas = async (rootElement, canvas) => {
2796
+ const canvasElement = await h(canvas);
2797
+ if (canvasElement.tag != "Canvas") {
2798
+ throw new Error("Canvas is required");
2799
+ }
2800
+ canvasElement.render(rootElement);
2801
+ return canvasElement;
2802
+ };
2803
+
2804
+ // src/utils/Ease.ts
2805
+ import {
2806
+ linear,
2807
+ easeIn,
2808
+ easeInOut,
2809
+ easeOut,
2810
+ circIn,
2811
+ circInOut,
2812
+ circOut,
2813
+ backIn,
2814
+ backInOut,
2815
+ backOut,
2816
+ anticipate,
2817
+ bounceIn,
2818
+ bounceInOut,
2819
+ bounceOut
2820
+ } from "popmotion";
2821
+ var Easing = {
2822
+ linear,
2823
+ easeIn,
2824
+ easeInOut,
2825
+ easeOut,
2826
+ circIn,
2827
+ circInOut,
2828
+ circOut,
2829
+ backIn,
2830
+ backInOut,
2831
+ backOut,
2832
+ anticipate,
2833
+ bounceIn,
2834
+ bounceInOut,
2835
+ bounceOut
2836
+ };
2837
+
2838
+ // src/utils/RadialGradient.ts
2839
+ import { Texture as Texture5, ImageSource, DOMAdapter, Matrix } from "pixi.js";
2840
+ var RadialGradient = class {
2841
+ constructor(x0, y0, x1, y1, x2, y2, focalPoint = 0) {
2842
+ this.x0 = x0;
2843
+ this.y0 = y0;
2844
+ this.x1 = x1;
2845
+ this.y1 = y1;
2846
+ this.x2 = x2;
2847
+ this.y2 = y2;
2848
+ this.focalPoint = focalPoint;
2849
+ this.gradient = null;
2850
+ this.texture = null;
2851
+ this.size = 600;
2852
+ this.size = x0;
2853
+ const halfSize = this.size * 0.5;
2854
+ this.canvas = DOMAdapter.get().createCanvas();
2855
+ this.canvas.width = this.size;
2856
+ this.canvas.height = this.size;
2857
+ this.ctx = this.canvas.getContext("2d");
2858
+ if (this.ctx) {
2859
+ this.gradient = this.ctx.createRadialGradient(
2860
+ halfSize * (1 - focalPoint),
2861
+ halfSize,
2862
+ 0,
2863
+ halfSize,
2864
+ halfSize,
2865
+ halfSize - 0.5
2866
+ );
2867
+ }
2868
+ }
2869
+ addColorStop(offset, color) {
2870
+ if (this.gradient) {
2871
+ this.gradient.addColorStop(offset, color);
2872
+ }
2873
+ }
2874
+ render({ translate } = {}) {
2875
+ const { x0, y0, x1, y1, x2, y2, focalPoint } = this;
2876
+ const defaultSize = this.size;
2877
+ if (this.ctx && this.gradient) {
2878
+ this.ctx.fillStyle = this.gradient;
2879
+ this.ctx.fillRect(0, 0, defaultSize, defaultSize);
2880
+ this.texture = new Texture5({
2881
+ source: new ImageSource({
2882
+ resource: this.canvas,
2883
+ addressModeU: "clamp-to-edge",
2884
+ addressModeV: "clamp-to-edge"
2885
+ })
2886
+ });
2887
+ const m = new Matrix();
2888
+ const dx = Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
2889
+ const dy = Math.sqrt((x2 - x0) * (x2 - x0) + (y2 - y0) * (y2 - y0));
2890
+ const angle = Math.atan2(y1 - y0, x1 - x0);
2891
+ const scaleX = dx / defaultSize;
2892
+ const scaleY = dy / defaultSize;
2893
+ m.rotate(-angle);
2894
+ m.scale(scaleX, scaleY);
2895
+ if (translate) {
2896
+ m.translate(translate.x, translate.y);
2897
+ }
2898
+ this.transform = m;
2899
+ }
2900
+ return {
2901
+ texture: this.texture,
2902
+ matrix: this.transform
2903
+ };
2904
+ }
2905
+ };
2906
+
2907
+ // src/index.ts
2908
+ import { isObservable } from "rxjs";
2909
+ export {
2910
+ Canvas2 as Canvas,
2911
+ Circle,
2912
+ Container4 as Container,
2913
+ DisplayObject,
2914
+ EVENTS2 as EVENTS,
2915
+ Easing,
2916
+ Ellipse,
2917
+ Graphics,
2918
+ Howler,
2919
+ NineSliceSprite,
2920
+ ParticlesEmitter,
2921
+ RadialGradient,
2922
+ Rect,
2923
+ Scene,
2924
+ Sprite2 as Sprite,
2925
+ Text,
2926
+ TilingSprite,
2927
+ Triangle,
2928
+ Viewport,
2929
+ animatedSignal,
2930
+ bootstrapCanvas,
2931
+ cond,
2932
+ createComponent,
2933
+ currentSubscriptionsTracker,
2934
+ h,
2935
+ isAnimatedSignal,
2936
+ isElement,
2937
+ isObservable,
2938
+ isPrimitive,
2939
+ isTrigger,
2940
+ loop,
2941
+ mount,
2942
+ mountTracker,
2943
+ on,
2944
+ registerComponent,
2945
+ Svg as svg,
2946
+ tick,
2947
+ trigger,
2948
+ useDefineProps,
2949
+ useProps
2950
+ };
2951
+ //# sourceMappingURL=index.js.map