@rpgjs/client 5.0.0-beta.7 → 5.0.0-beta.8

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 (73) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/Game/Map.js +2 -1
  3. package/dist/Game/Map.js.map +1 -1
  4. package/dist/Game/Object.d.ts +17 -9
  5. package/dist/Game/Object.js +1 -12
  6. package/dist/Game/Object.js.map +1 -1
  7. package/dist/Gui/Gui.d.ts +17 -4
  8. package/dist/Gui/Gui.js +63 -33
  9. package/dist/Gui/Gui.js.map +1 -1
  10. package/dist/Gui/Gui.spec.d.ts +1 -0
  11. package/dist/Resource.js +1 -1
  12. package/dist/Resource.js.map +1 -1
  13. package/dist/RpgClient.d.ts +35 -2
  14. package/dist/RpgClientEngine.d.ts +41 -5
  15. package/dist/RpgClientEngine.js +43 -3
  16. package/dist/RpgClientEngine.js.map +1 -1
  17. package/dist/components/character.ce.js +225 -2
  18. package/dist/components/character.ce.js.map +1 -1
  19. package/dist/components/dynamics/bar.ce.js +96 -0
  20. package/dist/components/dynamics/bar.ce.js.map +1 -0
  21. package/dist/components/dynamics/image.ce.js +23 -0
  22. package/dist/components/dynamics/image.ce.js.map +1 -0
  23. package/dist/components/dynamics/parse-value.d.ts +3 -0
  24. package/dist/components/dynamics/parse-value.js +51 -35
  25. package/dist/components/dynamics/parse-value.js.map +1 -1
  26. package/dist/components/dynamics/parse-value.spec.d.ts +1 -0
  27. package/dist/components/dynamics/shape-utils.d.ts +16 -0
  28. package/dist/components/dynamics/shape-utils.js +73 -0
  29. package/dist/components/dynamics/shape-utils.js.map +1 -0
  30. package/dist/components/dynamics/shape-utils.spec.d.ts +1 -0
  31. package/dist/components/dynamics/shape.ce.js +83 -0
  32. package/dist/components/dynamics/shape.ce.js.map +1 -0
  33. package/dist/components/dynamics/text.ce.js +28 -41
  34. package/dist/components/dynamics/text.ce.js.map +1 -1
  35. package/dist/components/player-components-utils.d.ts +67 -0
  36. package/dist/components/player-components-utils.js +162 -0
  37. package/dist/components/player-components-utils.js.map +1 -0
  38. package/dist/components/player-components-utils.spec.d.ts +1 -0
  39. package/dist/components/player-components.ce.js +188 -0
  40. package/dist/components/player-components.ce.js.map +1 -0
  41. package/dist/core/setup.js.map +1 -1
  42. package/dist/module.js +3 -0
  43. package/dist/module.js.map +1 -1
  44. package/dist/node_modules/.pnpm/@signe_reactive@2.10.0/node_modules/@signe/reactive/dist/index.js +197 -3
  45. package/dist/node_modules/.pnpm/@signe_reactive@2.10.0/node_modules/@signe/reactive/dist/index.js.map +1 -1
  46. package/dist/node_modules/.pnpm/@signe_room@2.10.0/node_modules/@signe/room/dist/index.js +1 -1
  47. package/dist/services/loadMap.d.ts +6 -0
  48. package/dist/services/loadMap.js.map +1 -1
  49. package/package.json +4 -4
  50. package/src/Game/Map.ts +12 -2
  51. package/src/Game/Object.ts +22 -35
  52. package/src/Gui/Gui.spec.ts +273 -0
  53. package/src/Gui/Gui.ts +105 -50
  54. package/src/Resource.ts +1 -2
  55. package/src/RpgClient.ts +36 -2
  56. package/src/RpgClientEngine.ts +64 -10
  57. package/src/components/character.ce +281 -1
  58. package/src/components/dynamics/bar.ce +87 -0
  59. package/src/components/dynamics/image.ce +20 -0
  60. package/src/components/dynamics/parse-value.spec.ts +41 -0
  61. package/src/components/dynamics/parse-value.ts +102 -37
  62. package/src/components/dynamics/shape-utils.spec.ts +46 -0
  63. package/src/components/dynamics/shape-utils.ts +61 -0
  64. package/src/components/dynamics/shape.ce +89 -0
  65. package/src/components/dynamics/text.ce +34 -149
  66. package/src/components/player-components-utils.spec.ts +109 -0
  67. package/src/components/player-components-utils.ts +205 -0
  68. package/src/components/player-components.ce +221 -0
  69. package/src/core/setup.ts +2 -2
  70. package/src/module.ts +5 -1
  71. package/src/services/loadMap.ts +2 -0
  72. package/dist/node_modules/.pnpm/@signe_reactive@2.9.2/node_modules/@signe/reactive/dist/index.js +0 -227
  73. package/dist/node_modules/.pnpm/@signe_reactive@2.9.2/node_modules/@signe/reactive/dist/index.js.map +0 -1
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # @rpgjs/client
2
+
3
+ ## 5.0.0-beta.8
4
+
5
+ ### Major Changes
6
+
7
+ - 35e7fa4: beta.8
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [35e7fa4]
12
+ - @rpgjs/common@5.0.0-beta.8
13
+ - @rpgjs/server@5.0.0-beta.8
14
+ - @rpgjs/ui-css@5.0.0-beta.8
package/dist/Game/Map.js CHANGED
@@ -23,7 +23,8 @@ var RpgClientMap = class extends RpgCommonMap {
23
23
  return local ?? state;
24
24
  });
25
25
  this.manualClientPhysicsTick = false;
26
- const isTest = typeof process !== "undefined" && process.env?.TEST === "true" || typeof window !== "undefined" && window.__RPGJS_TEST__ === true;
26
+ const testGlobal = globalThis;
27
+ const isTest = testGlobal.process?.env?.TEST === "true" || testGlobal.__RPGJS_TEST__ === true;
27
28
  this.isTestEnvironment = isTest;
28
29
  if (isTest) this.autoTickEnabled = false;
29
30
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Map.js","names":[],"sources":["../../src/Game/Map.ts"],"sourcesContent":["import {\n RpgCommonMap,\n type WeatherState,\n type MapPhysicsInitContext,\n type MapPhysicsEntityContext,\n} from \"@rpgjs/common\";\nimport { sync, users } from \"@signe/sync\";\nimport { RpgClientPlayer } from \"./Player\";\nimport { Signal, signal, computed, effect } from \"canvasengine\";\nimport { RpgClientEvent } from \"./Event\";\nimport { RpgClientEngine } from \"../RpgClientEngine\";\nimport { inject } from \"../core/inject\";\n\nexport class RpgClientMap extends RpgCommonMap<any> {\n engine: RpgClientEngine = inject(RpgClientEngine)\n @users(RpgClientPlayer) players = signal<Record<string, RpgClientPlayer>>({});\n @sync(RpgClientEvent) events = signal<Record<string, RpgClientEvent>>({});\n currentPlayer = computed(() => this.players()[this.engine.playerIdSignal()!])\n weatherState = signal<WeatherState | null>(null);\n localWeatherOverride = signal<WeatherState | null>(null);\n weather = computed<WeatherState | null>(() => {\n const local = this.localWeatherOverride() \n const state = this.weatherState()\n return local ?? state\n });\n private manualClientPhysicsTick = false;\n private readonly isTestEnvironment: boolean;\n\n constructor() {\n super();\n // Détecter l'environnement de test\n const isTest = (typeof process !== 'undefined' && process.env?.TEST === 'true')\n || (typeof window !== 'undefined' && (window as any).__RPGJS_TEST__ === true);\n this.isTestEnvironment = isTest;\n if (isTest) {\n this.autoTickEnabled = false;\n }\n }\n\n configureClientPrediction(enabled: boolean): void {\n this.manualClientPhysicsTick = enabled;\n this.autoTickEnabled = enabled ? false : !this.isTestEnvironment;\n }\n\n getCurrentPlayer() {\n return this.currentPlayer()\n }\n\n reset(force = false) {\n const currentPlayerId = this.engine.playerIdSignal();\n const currentPlayer = !force && currentPlayerId\n ? this.players()[currentPlayerId]\n : undefined;\n\n this.players.set(\n currentPlayerId && currentPlayer ? { [currentPlayerId]: currentPlayer } : {}\n );\n this.events.set({})\n this.weatherState.set(null);\n this.localWeatherOverride.set(null);\n this.clearPhysic()\n }\n\n getWeather(): WeatherState | null {\n return this.weather();\n }\n\n setLocalWeather(next: WeatherState | null): void {\n this.localWeatherOverride.set(next);\n }\n\n clearLocalWeather(): void {\n this.localWeatherOverride.set(null);\n }\n\n stepClientPhysics(deltaMs: number): number {\n if (!this.manualClientPhysicsTick) {\n return 0;\n }\n return this.nextTick(deltaMs);\n }\n\n stepPredictionTick(): void {\n this.forceSingleTick();\n }\n\n protected emitPhysicsInit(context: MapPhysicsInitContext): void {\n this.engine?.emitSceneMapHook?.(\"onPhysicsInit\", this, context);\n }\n\n protected emitPhysicsEntityAdd(context: MapPhysicsEntityContext): void {\n this.engine?.emitSceneMapHook?.(\"onPhysicsEntityAdd\", this, context);\n }\n\n protected emitPhysicsEntityRemove(context: MapPhysicsEntityContext): void {\n this.engine?.emitSceneMapHook?.(\"onPhysicsEntityRemove\", this, context);\n }\n\n protected emitPhysicsReset(): void {\n this.engine?.emitSceneMapHook?.(\"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,SAAS,QAAQ;;CAG/B,qBAA2B;EACzB,KAAK,iBAAiB;;CAGxB,gBAA0B,SAAsC;EAC9D,KAAK,QAAQ,mBAAmB,iBAAiB,MAAM,QAAQ;;CAGjE,qBAA+B,SAAwC;EACrE,KAAK,QAAQ,mBAAmB,sBAAsB,MAAM,QAAQ;;CAGtE,wBAAkC,SAAwC;EACxE,KAAK,QAAQ,mBAAmB,yBAAyB,MAAM,QAAQ;;CAGzE,mBAAmC;EACjC,KAAK,QAAQ,mBAAmB,kBAAkB,KAAK;;;YApFxD,MAAM,gBAAgB,EAAA,mBAAA,eAAA,OAAA,CAAA,EAAA,aAAA,WAAA,WAAA,KAAA,EAAA;YACtB,KAAK,eAAe,EAAA,mBAAA,eAAA,OAAA,CAAA,EAAA,aAAA,WAAA,UAAA,KAAA,EAAA"}
1
+ {"version":3,"file":"Map.js","names":[],"sources":["../../src/Game/Map.ts"],"sourcesContent":["import {\n RpgCommonMap,\n type WeatherState,\n type MapPhysicsInitContext,\n type MapPhysicsEntityContext,\n} from \"@rpgjs/common\";\nimport { sync, users } from \"@signe/sync\";\nimport { RpgClientPlayer } from \"./Player\";\nimport { Signal, signal, computed, effect } from \"canvasengine\";\nimport { RpgClientEvent } from \"./Event\";\nimport { RpgClientEngine } from \"../RpgClientEngine\";\nimport { inject } from \"../core/inject\";\n\ntype TestGlobalScope = typeof globalThis & {\n process?: {\n env?: {\n TEST?: string;\n };\n };\n __RPGJS_TEST__?: boolean;\n};\n\nexport class RpgClientMap extends RpgCommonMap<any> {\n engine: RpgClientEngine = inject(RpgClientEngine)\n @users(RpgClientPlayer) players = signal<Record<string, RpgClientPlayer>>({});\n @sync(RpgClientEvent) events = signal<Record<string, RpgClientEvent>>({});\n currentPlayer = computed(() => this.players()[this.engine.playerIdSignal()!])\n weatherState = signal<WeatherState | null>(null);\n localWeatherOverride = signal<WeatherState | null>(null);\n weather = computed<WeatherState | null>(() => {\n const local = this.localWeatherOverride() \n const state = this.weatherState()\n return local ?? state\n });\n private manualClientPhysicsTick = false;\n private readonly isTestEnvironment: boolean;\n\n constructor() {\n super();\n // Détecter l'environnement de test\n const testGlobal = globalThis as TestGlobalScope;\n const isTest = testGlobal.process?.env?.TEST === 'true'\n || testGlobal.__RPGJS_TEST__ === true;\n this.isTestEnvironment = isTest;\n if (isTest) {\n this.autoTickEnabled = false;\n }\n }\n\n configureClientPrediction(enabled: boolean): void {\n this.manualClientPhysicsTick = enabled;\n this.autoTickEnabled = enabled ? false : !this.isTestEnvironment;\n }\n\n getCurrentPlayer() {\n return this.currentPlayer()\n }\n\n reset(force = false) {\n const currentPlayerId = this.engine.playerIdSignal();\n const currentPlayer = !force && currentPlayerId\n ? this.players()[currentPlayerId]\n : undefined;\n\n this.players.set(\n currentPlayerId && currentPlayer ? { [currentPlayerId]: currentPlayer } : {}\n );\n this.events.set({})\n this.weatherState.set(null);\n this.localWeatherOverride.set(null);\n this.clearPhysic()\n }\n\n getWeather(): WeatherState | null {\n return this.weather();\n }\n\n setLocalWeather(next: WeatherState | null): void {\n this.localWeatherOverride.set(next);\n }\n\n clearLocalWeather(): void {\n this.localWeatherOverride.set(null);\n }\n\n stepClientPhysics(deltaMs: number): number {\n if (!this.manualClientPhysicsTick) {\n return 0;\n }\n return this.nextTick(deltaMs);\n }\n\n stepPredictionTick(): void {\n this.forceSingleTick();\n }\n\n protected emitPhysicsInit(context: MapPhysicsInitContext): void {\n this.engine?.emitSceneMapHook?.(\"onPhysicsInit\", this, context);\n }\n\n protected emitPhysicsEntityAdd(context: MapPhysicsEntityContext): void {\n this.engine?.emitSceneMapHook?.(\"onPhysicsEntityAdd\", this, context);\n }\n\n protected emitPhysicsEntityRemove(context: MapPhysicsEntityContext): void {\n this.engine?.emitSceneMapHook?.(\"onPhysicsEntityRemove\", this, context);\n }\n\n protected emitPhysicsReset(): void {\n this.engine?.emitSceneMapHook?.(\"onPhysicsReset\", this);\n }\n}\n"],"mappings":";;;;;;;;;;AAsBA,IAAa,eAAb,cAAkC,aAA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,QAAQ,mBAAmB,iBAAiB,MAAM,QAAQ;;CAGjE,qBAA+B,SAAwC;EACrE,KAAK,QAAQ,mBAAmB,sBAAsB,MAAM,QAAQ;;CAGtE,wBAAkC,SAAwC;EACxE,KAAK,QAAQ,mBAAmB,yBAAyB,MAAM,QAAQ;;CAGzE,mBAAmC;EACjC,KAAK,QAAQ,mBAAmB,kBAAkB,KAAK;;;YArFxD,MAAM,gBAAgB,EAAA,mBAAA,eAAA,OAAA,CAAA,EAAA,aAAA,WAAA,WAAA,KAAA,EAAA;YACtB,KAAK,eAAe,EAAA,mBAAA,eAAA,OAAA,CAAA,EAAA,aAAA,WAAA,UAAA,KAAA,EAAA"}
@@ -1,4 +1,5 @@
1
1
  import { Hooks, RpgCommonPlayer } from '@rpgjs/common';
2
+ import { Trigger } from 'canvasengine';
2
3
  import { RpgClientEngine } from '../RpgClientEngine';
3
4
  type Frame = {
4
5
  x: number;
@@ -10,6 +11,20 @@ type AnimationRestoreOptions = {
10
11
  restoreGraphics?: any[];
11
12
  timeoutMs?: number;
12
13
  };
14
+ type FlashType = 'alpha' | 'tint' | 'both';
15
+ type FlashOptions = {
16
+ type?: FlashType;
17
+ duration?: number;
18
+ cycles?: number;
19
+ alpha?: number;
20
+ tint?: number | string;
21
+ };
22
+ type FlashTriggerOptions = Omit<FlashOptions, "tint"> & {
23
+ tint: number;
24
+ };
25
+ type ConfigurableTrigger<T> = Omit<Trigger<T>, "start"> & {
26
+ start(config?: T): Promise<void>;
27
+ };
13
28
  export declare abstract class RpgClientObject extends RpgCommonPlayer {
14
29
  abstract _type: string;
15
30
  emitParticleTrigger: any;
@@ -19,8 +34,7 @@ export declare abstract class RpgClientObject extends RpgCommonPlayer {
19
34
  _param: any;
20
35
  frames: Frame[];
21
36
  graphicsSignals: any;
22
- _component: {};
23
- flashTrigger: any;
37
+ flashTrigger: ConfigurableTrigger<FlashTriggerOptions>;
24
38
  private animationRestoreState?;
25
39
  constructor();
26
40
  /**
@@ -87,13 +101,7 @@ export declare abstract class RpgClientObject extends RpgCommonPlayer {
87
101
  * });
88
102
  * ```
89
103
  */
90
- flash(options?: {
91
- type?: 'alpha' | 'tint' | 'both';
92
- duration?: number;
93
- cycles?: number;
94
- alpha?: number;
95
- tint?: number | string;
96
- }): void;
104
+ flash(options?: FlashOptions): void;
97
105
  /**
98
106
  * Reset animation state when animation changes externally
99
107
  *
@@ -1,11 +1,9 @@
1
1
  import { inject } from "../core/inject.js";
2
- import __ce_component from "../components/dynamics/text.ce.js";
3
2
  import { RpgClientEngine } from "../RpgClientEngine.js";
4
3
  import { signal, trigger } from "canvasengine";
5
4
  import { ModulesToken, RpgCommonPlayer } from "@rpgjs/common";
6
- import { filter, from, map, of, switchMap } from "rxjs";
5
+ import { from, map, of, switchMap } from "rxjs";
7
6
  //#region src/Game/Object.ts
8
- var DYNAMIC_COMPONENTS = { text: __ce_component };
9
7
  var RpgClientObject = class extends RpgCommonPlayer {
10
8
  constructor() {
11
9
  super();
@@ -16,7 +14,6 @@ var RpgClientObject = class extends RpgCommonPlayer {
16
14
  this._param = signal({});
17
15
  this.frames = [];
18
16
  this.graphicsSignals = signal([]);
19
- this._component = {};
20
17
  this.flashTrigger = trigger();
21
18
  this.hooks.callHooks("client-sprite-onInit", this).subscribe();
22
19
  this._frames.observable.subscribe(({ items }) => {
@@ -30,14 +27,6 @@ var RpgClientObject = class extends RpgCommonPlayer {
30
27
  })).subscribe((sheets) => {
31
28
  this.graphicsSignals.set(sheets);
32
29
  });
33
- this.componentsTop.observable.pipe(filter((value) => value !== null && value !== void 0), map((value) => typeof value === "string" ? JSON.parse(value) : value)).subscribe(({ components }) => {
34
- for (const component of components) for (const [key, value] of Object.entries(component)) {
35
- this._component = value;
36
- console.log(value);
37
- const type = value.type;
38
- if (DYNAMIC_COMPONENTS[type]) this.engine.addSpriteComponentInFront(DYNAMIC_COMPONENTS[type]);
39
- }
40
- });
41
30
  this.engine.tick.pipe().subscribe(() => {
42
31
  const frame = this.frames.shift();
43
32
  if (frame) {
@@ -1 +1 @@
1
- {"version":3,"file":"Object.js","names":[],"sources":["../../src/Game/Object.ts"],"sourcesContent":["import { Hooks, ModulesToken, RpgCommonPlayer } from \"@rpgjs/common\";\nimport { trigger, signal, effect } from \"canvasengine\";\nimport { filter, from, map, of, Subscription, switchMap } from \"rxjs\";\nimport { inject } from \"../core/inject\";\nimport { RpgClientEngine } from \"../RpgClientEngine\";\nimport TextComponent from \"../components/dynamics/text.ce\";\n\nconst DYNAMIC_COMPONENTS = {\n text: TextComponent,\n}\n\ntype Frame = { x: number; y: number; ts: number };\n\ntype AnimationRestoreOptions = {\n restoreAnimationName?: string;\n restoreGraphics?: any[];\n timeoutMs?: number;\n};\n\nexport abstract class RpgClientObject extends RpgCommonPlayer {\n abstract _type: string;\n emitParticleTrigger = trigger();\n particleName = signal(\"\");\n animationCurrentIndex = signal(0);\n animationIsPlaying = signal(false);\n _param = signal({});\n frames: Frame[] = [];\n graphicsSignals = signal<any[]>([]);\n _component = {} // temporary component memory\n flashTrigger = trigger();\n private animationRestoreState?: {\n animationName: string;\n graphics: any[];\n };\n\n constructor() {\n super();\n this.hooks.callHooks(\"client-sprite-onInit\", this).subscribe();\n\n this._frames.observable.subscribe(({ items }) => {\n if (!this.id) return;\n //if (this.id == this.engine.playerIdSignal()!) return;\n const nextFrames = items.flatMap((item): Frame[] =>\n Array.isArray(item) ? item : [item]\n );\n this.frames = [...this.frames, ...nextFrames];\n });\n\n this.graphics.observable\n .pipe(\n map(({ items }) => items),\n switchMap(graphics => {\n if (graphics.length === 0) return of([]);\n return from(Promise.all(graphics.map(graphic => this.engine.getSpriteSheet(graphic))));\n })\n )\n .subscribe((sheets) => { \n this.graphicsSignals.set(sheets);\n });\n\n this.componentsTop.observable\n .pipe(\n filter(value => value !== null && value !== undefined),\n map((value) => typeof value === 'string' ? JSON.parse(value) : value),\n )\n .subscribe(({components}) => {\n for (const component of components) {\n for (const [key, value] of Object.entries(component)) {\n this._component = value as any; // temporary component memory\n console.log(value)\n const type = (value as any).type as keyof typeof DYNAMIC_COMPONENTS;\n if (DYNAMIC_COMPONENTS[type]) {\n this.engine.addSpriteComponentInFront(DYNAMIC_COMPONENTS[type]);\n }\n }\n }\n });\n\n this.engine.tick\n .pipe\n //throttleTime(10)\n ()\n .subscribe(() => {\n const frame = this.frames.shift();\n if (frame) {\n if (typeof frame.x !== \"number\" || typeof frame.y !== \"number\") return;\n this.engine.scene.setBodyPosition(\n this.id,\n frame.x,\n frame.y,\n \"top-left\"\n );\n }\n });\n }\n\n /**\n * Access the shared client hook registry.\n *\n * @returns The hook service used to register and trigger client-side hooks.\n */\n get hooks() {\n return inject<Hooks>(ModulesToken);\n }\n\n /**\n * Access the current client engine instance.\n *\n * @returns The active {@link RpgClientEngine} instance.\n */\n get engine() {\n return inject(RpgClientEngine);\n }\n\n private animationSubscription?: Subscription;\n private animationResetTimeout?: ReturnType<typeof setTimeout>;\n private animationWaitResolve?: () => void;\n\n private clearAnimationControls() {\n if (this.animationSubscription) {\n this.animationSubscription.unsubscribe();\n this.animationSubscription = undefined;\n }\n if (this.animationResetTimeout) {\n clearTimeout(this.animationResetTimeout);\n this.animationResetTimeout = undefined;\n }\n }\n\n private resolveAnimationWait() {\n const resolve = this.animationWaitResolve;\n this.animationWaitResolve = undefined;\n resolve?.();\n }\n\n private finishTemporaryAnimation() {\n const restoreState = this.animationRestoreState;\n this.clearAnimationControls();\n this.animationCurrentIndex.set(0);\n if (restoreState) {\n this.animationName.set(restoreState.animationName);\n this.graphics.set([...restoreState.graphics]);\n }\n this.animationRestoreState = undefined;\n this.animationIsPlaying.set(false);\n this.resolveAnimationWait();\n }\n\n /**\n * Trigger a flash animation on this sprite\n * \n * This method triggers a flash effect using CanvasEngine's flash directive.\n * The flash can be configured with various options including type (alpha, tint, or both),\n * duration, cycles, and color.\n * \n * ## Design\n * \n * The flash uses a trigger system that is connected to the flash directive in the\n * character component. This allows for flexible configuration and can be triggered\n * from both server events and client-side code.\n * \n * @param options - Flash configuration options\n * @param options.type - Type of flash effect: 'alpha' (opacity), 'tint' (color), or 'both' (default: 'alpha')\n * @param options.duration - Duration of the flash animation in milliseconds (default: 300)\n * @param options.cycles - Number of flash cycles (flash on/off) (default: 1)\n * @param options.alpha - Alpha value when flashing, from 0 to 1 (default: 0.3)\n * @param options.tint - Tint color when flashing as hex value or color name (default: 0xffffff - white)\n * \n * @example\n * ```ts\n * // Simple flash with default settings (alpha flash)\n * player.flash();\n * \n * // Flash with red tint\n * player.flash({ type: 'tint', tint: 0xff0000 });\n * \n * // Flash with both alpha and tint\n * player.flash({ \n * type: 'both', \n * alpha: 0.5, \n * tint: 0xff0000,\n * duration: 200,\n * cycles: 2\n * });\n * \n * // Quick damage flash\n * player.flash({ \n * type: 'tint', \n * tint: 0xff0000, \n * duration: 150,\n * cycles: 1\n * });\n * ```\n */\n flash(options?: {\n type?: 'alpha' | 'tint' | 'both';\n duration?: number;\n cycles?: number;\n alpha?: number;\n tint?: number | string;\n }): void {\n const flashOptions = {\n type: options?.type || 'alpha',\n duration: options?.duration ?? 300,\n cycles: options?.cycles ?? 1,\n alpha: options?.alpha ?? 0.3,\n tint: options?.tint ?? 0xffffff,\n };\n \n // Convert color name to hex if needed\n let tintValue = flashOptions.tint;\n if (typeof tintValue === 'string') {\n // Common color name to hex mapping\n const colorMap: Record<string, number> = {\n 'white': 0xffffff,\n 'red': 0xff0000,\n 'green': 0x00ff00,\n 'blue': 0x0000ff,\n 'yellow': 0xffff00,\n 'cyan': 0x00ffff,\n 'magenta': 0xff00ff,\n 'black': 0x000000,\n };\n tintValue = colorMap[tintValue.toLowerCase()] ?? 0xffffff;\n }\n \n this.flashTrigger.start({\n ...flashOptions,\n tint: tintValue,\n });\n }\n\n /**\n * Reset animation state when animation changes externally\n *\n * This method should be called when the animation changes due to movement\n * or other external factors to ensure the animation system doesn't get stuck\n *\n * @example\n * ```ts\n * // Reset when player starts moving\n * player.resetAnimationState();\n * ```\n */\n resetAnimationState() {\n if (this.animationRestoreState) {\n this.finishTemporaryAnimation();\n return;\n }\n this.animationIsPlaying.set(false);\n this.animationCurrentIndex.set(0);\n this.clearAnimationControls();\n this.resolveAnimationWait();\n }\n\n /**\n * Set a custom animation for a specific number of times\n *\n * Plays a custom animation for the specified number of repetitions.\n * The animation system prevents overlapping animations and automatically\n * returns to the previous animation when complete.\n *\n * @param animationName - Name of the animation to play\n * @param nbTimes - Number of times to repeat the animation (default: Infinity for continuous)\n * @param options - Restore and timeout options\n * @returns A promise resolved when a finite animation finishes, is interrupted, or times out\n *\n * @example\n * ```ts\n * // Play attack animation 3 times\n * await player.setAnimation('attack', 3);\n *\n * // Play continuous spell animation\n * player.setAnimation('spell');\n * ```\n */\n setAnimation(animationName: string, nbTimes?: number, options?: AnimationRestoreOptions): Promise<void>;\n /**\n * Set a custom animation with temporary graphic change\n *\n * Plays a custom animation for the specified number of repetitions and temporarily\n * changes the player's graphic (sprite sheet) during the animation. The graphic\n * is automatically reset when the animation finishes.\n *\n * @param animationName - Name of the animation to play\n * @param graphic - The graphic(s) to temporarily use during the animation\n * @param nbTimes - Number of times to repeat the animation (default: Infinity for continuous)\n * @param options - Restore and timeout options\n * @returns A promise resolved when a finite animation finishes, is interrupted, or times out\n *\n * @example\n * ```ts\n * // Play attack animation with temporary graphic change\n * await player.setAnimation('attack', 'hero_attack', 3);\n * ```\n */\n setAnimation(animationName: string, graphic?: string | string[], nbTimes?: number, options?: AnimationRestoreOptions): Promise<void>;\n setAnimation(\n animationName: string,\n graphicOrNbTimes?: string | string[] | number,\n nbTimesOrOptions?: number | AnimationRestoreOptions,\n options?: AnimationRestoreOptions\n ): Promise<void> {\n let graphic: string | string[] | undefined;\n let finalNbTimes: number = Infinity;\n let restoreOptions: AnimationRestoreOptions | undefined = options;\n\n // Handle overloads\n if (typeof graphicOrNbTimes === 'number') {\n // setAnimation(animationName, nbTimes)\n finalNbTimes = graphicOrNbTimes;\n restoreOptions = typeof nbTimesOrOptions === 'object' ? nbTimesOrOptions : options;\n } else if (graphicOrNbTimes !== undefined) {\n // setAnimation(animationName, graphic, nbTimes)\n graphic = graphicOrNbTimes;\n if (typeof nbTimesOrOptions === 'number') {\n finalNbTimes = nbTimesOrOptions;\n } else {\n finalNbTimes = Infinity;\n restoreOptions = nbTimesOrOptions ?? options;\n }\n } else {\n // setAnimation(animationName) - nbTimes remains Infinity\n finalNbTimes = Infinity;\n }\n\n if (this.animationIsPlaying()) {\n this.finishTemporaryAnimation();\n }\n\n const waitPromise =\n finalNbTimes === Infinity\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n this.animationWaitResolve = resolve;\n });\n\n this.animationIsPlaying.set(true);\n const previousAnimationName =\n restoreOptions?.restoreAnimationName ?? this.animationName();\n const previousGraphics = restoreOptions?.restoreGraphics\n ? [...restoreOptions.restoreGraphics]\n : [...this.graphics()];\n this.animationRestoreState = {\n animationName: previousAnimationName,\n graphics: previousGraphics,\n };\n this.animationCurrentIndex.set(0);\n\n // Temporarily change graphic if provided\n if (graphic !== undefined) {\n if (Array.isArray(graphic)) {\n this.graphics.set(graphic);\n } else {\n this.graphics.set([graphic]);\n }\n }\n\n this.clearAnimationControls();\n\n this.animationSubscription =\n this.animationCurrentIndex.observable.subscribe((index) => {\n if (index >= finalNbTimes) {\n this.finishTemporaryAnimation();\n }\n });\n\n if (finalNbTimes !== Infinity) {\n this.animationResetTimeout = setTimeout(() => {\n if (this.animationIsPlaying()) {\n this.finishTemporaryAnimation();\n }\n }, restoreOptions?.timeoutMs ?? Math.max(1000, finalNbTimes * 1000));\n }\n\n this.animationName.set(animationName);\n\n return waitPromise;\n }\n\n /**\n * Display a registered component animation effect on this object.\n *\n * @param id - Identifier of the component animation to play.\n * @param params - Parameters forwarded to the animation effect.\n * @returns A promise resolved when the animation component calls `onFinish`.\n */\n showComponentAnimation(id: string, params: any): Promise<void> {\n const engine = inject(RpgClientEngine);\n return engine.getComponentAnimation(id).displayEffect(params, this);\n }\n\n /**\n * Display a registered spritesheet animation effect on this object.\n *\n * @param graphic - Identifier of the spritesheet to use.\n * @param animationName - Name of the animation inside the spritesheet.\n * @returns A promise resolved when the animation component calls `onFinish`.\n */\n showAnimation(graphic: string, animationName: string = 'default'): Promise<void> {\n return this.showComponentAnimation('animation', {\n graphic,\n animationName,\n });\n }\n \n /**\n * Check whether this client object represents an event.\n *\n * @returns `true` if the object type is `event`, otherwise `false`.\n */\n isEvent(): boolean {\n return this._type === 'event';\n }\n\n /**\n * Check whether this client object represents a player.\n *\n * @returns `true` if the object type is `player`, otherwise `false`.\n */\n isPlayer(): boolean {\n return this._type === 'player';\n }\n}\n"],"mappings":";;;;;;;AAOA,IAAM,qBAAqB,EACzB,MAAM,gBACP;AAUD,IAAsB,kBAAtB,cAA8C,gBAAgB;CAgB5D,cAAc;EACZ,OAAO;6BAfa,SAAS;sBAChB,OAAO,GAAG;+BACD,OAAO,EAAE;4BACZ,OAAO,MAAM;gBACzB,OAAO,EAAE,CAAC;gBACD,EAAE;yBACF,OAAc,EAAE,CAAC;oBACtB,EAAE;sBACA,SAAS;EAQtB,KAAK,MAAM,UAAU,wBAAwB,KAAK,CAAC,WAAW;EAE9D,KAAK,QAAQ,WAAW,WAAW,EAAE,YAAY;GAC/C,IAAI,CAAC,KAAK,IAAI;GAEd,MAAM,aAAa,MAAM,SAAS,SAChC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC,KAAK,CACpC;GACD,KAAK,SAAS,CAAC,GAAG,KAAK,QAAQ,GAAG,WAAW;IAC7C;EAEF,KAAK,SAAS,WACb,KACC,KAAK,EAAE,YAAY,MAAM,EACzB,WAAU,aAAY;GACpB,IAAI,SAAS,WAAW,GAAG,OAAO,GAAG,EAAE,CAAC;GACxC,OAAO,KAAK,QAAQ,IAAI,SAAS,KAAI,YAAW,KAAK,OAAO,eAAe,QAAQ,CAAC,CAAC,CAAC;IACtF,CACH,CACA,WAAW,WAAW;GACrB,KAAK,gBAAgB,IAAI,OAAO;IAChC;EAEF,KAAK,cAAc,WAClB,KACC,QAAO,UAAS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AAgB,kBACrC,CAAC,GAAG,eAAe,gBAAgB,GACnC,CAAC,GAAG,KAAK,UAAU,CAAC;EACxB,KAAK,wBAAwB;GAC3B,eAAe;GACf,UAAU;GACX;EACD,KAAK,sBAAsB,IAAI,EAAE;EAGjC,IAAI,YAAY,KAAA,GACd,IAAI,MAAM,QAAQ,QAAQ,EACxB,KAAK,SAAS,IAAI,QAAQ;OAE1B,KAAK,SAAS,IAAI,CAAC,QAAQ,CAAC;EAIhC,KAAK,wBAAwB;EAE7B,KAAK,wBACH,KAAK,sBAAsB,WAAW,WAAW,UAAU;GACzD,IAAI,SAAS,cACX,KAAK,0BAA0B;IAEjC;EAEJ,IAAI,iBAAiB,UACnB,KAAK,wBAAwB,iBAAiB;GAC5C,IAAI,KAAK,oBAAoB,EAC3B,KAAK,0BAA0B;KAEhC,gBAAgB,aAAa,KAAK,IAAI,KAAM,eAAe,IAAK,CAAC;EAGtE,KAAK,cAAc,IAAI,cAAc;EAErC,OAAO;;;;;;;;;CAUT,uBAAuB,IAAY,QAA4B;EAE7D,OADe,OAAO,gBACf,CAAO,sBAAsB,GAAG,CAAC,cAAc,QAAQ,KAAK;;;;;;;;;CAUrE,cAAc,SAAiB,gBAAwB,WAA0B;EAC/E,OAAO,KAAK,uBAAuB,aAAa;GAC9C;GACA;GACD,CAAC;;;;;;;CAQJ,UAAmB;EACjB,OAAO,KAAK,UAAU;;;;;;;CAQxB,WAAoB;EAClB,OAAO,KAAK,UAAU"}
1
+ {"version":3,"file":"Object.js","names":[],"sources":["../../src/Game/Object.ts"],"sourcesContent":["import { Hooks, ModulesToken, RpgCommonPlayer } from \"@rpgjs/common\";\nimport { trigger, signal, type Trigger } from \"canvasengine\";\nimport { from, map, of, Subscription, switchMap } from \"rxjs\";\nimport { inject } from \"../core/inject\";\nimport { RpgClientEngine } from \"../RpgClientEngine\";\ntype Frame = { x: number; y: number; ts: number };\n\ntype AnimationRestoreOptions = {\n restoreAnimationName?: string;\n restoreGraphics?: any[];\n timeoutMs?: number;\n};\n\ntype FlashType = 'alpha' | 'tint' | 'both';\n\ntype FlashOptions = {\n type?: FlashType;\n duration?: number;\n cycles?: number;\n alpha?: number;\n tint?: number | string;\n};\n\ntype FlashTriggerOptions = Omit<FlashOptions, \"tint\"> & {\n tint: number;\n};\n\ntype ConfigurableTrigger<T> = Omit<Trigger<T>, \"start\"> & {\n start(config?: T): Promise<void>;\n};\n\nexport abstract class RpgClientObject extends RpgCommonPlayer {\n abstract _type: string;\n emitParticleTrigger = trigger();\n particleName = signal(\"\");\n animationCurrentIndex = signal(0);\n animationIsPlaying = signal(false);\n _param = signal({});\n frames: Frame[] = [];\n graphicsSignals = signal<any[]>([]);\n flashTrigger: ConfigurableTrigger<FlashTriggerOptions> = trigger<FlashTriggerOptions>();\n private animationRestoreState?: {\n animationName: string;\n graphics: any[];\n };\n\n constructor() {\n super();\n this.hooks.callHooks(\"client-sprite-onInit\", this).subscribe();\n\n this._frames.observable.subscribe(({ items }) => {\n if (!this.id) return;\n //if (this.id == this.engine.playerIdSignal()!) return;\n const nextFrames = items.flatMap((item): Frame[] =>\n Array.isArray(item) ? item : [item]\n );\n this.frames = [...this.frames, ...nextFrames];\n });\n\n this.graphics.observable\n .pipe(\n map(({ items }) => items),\n switchMap(graphics => {\n if (graphics.length === 0) return of([]);\n return from(Promise.all(graphics.map(graphic => this.engine.getSpriteSheet(graphic))));\n })\n )\n .subscribe((sheets) => { \n this.graphicsSignals.set(sheets);\n });\n\n this.engine.tick\n .pipe\n //throttleTime(10)\n ()\n .subscribe(() => {\n const frame = this.frames.shift();\n if (frame) {\n if (typeof frame.x !== \"number\" || typeof frame.y !== \"number\") return;\n this.engine.scene.setBodyPosition(\n this.id,\n frame.x,\n frame.y,\n \"top-left\"\n );\n }\n });\n }\n\n /**\n * Access the shared client hook registry.\n *\n * @returns The hook service used to register and trigger client-side hooks.\n */\n get hooks() {\n return inject<Hooks>(ModulesToken);\n }\n\n /**\n * Access the current client engine instance.\n *\n * @returns The active {@link RpgClientEngine} instance.\n */\n get engine() {\n return inject(RpgClientEngine);\n }\n\n private animationSubscription?: Subscription;\n private animationResetTimeout?: ReturnType<typeof setTimeout>;\n private animationWaitResolve?: () => void;\n\n private clearAnimationControls() {\n if (this.animationSubscription) {\n this.animationSubscription.unsubscribe();\n this.animationSubscription = undefined;\n }\n if (this.animationResetTimeout) {\n clearTimeout(this.animationResetTimeout);\n this.animationResetTimeout = undefined;\n }\n }\n\n private resolveAnimationWait() {\n const resolve = this.animationWaitResolve;\n this.animationWaitResolve = undefined;\n resolve?.();\n }\n\n private finishTemporaryAnimation() {\n const restoreState = this.animationRestoreState;\n this.clearAnimationControls();\n this.animationCurrentIndex.set(0);\n if (restoreState) {\n this.animationName.set(restoreState.animationName);\n this.graphics.set([...restoreState.graphics]);\n }\n this.animationRestoreState = undefined;\n this.animationIsPlaying.set(false);\n this.resolveAnimationWait();\n }\n\n /**\n * Trigger a flash animation on this sprite\n * \n * This method triggers a flash effect using CanvasEngine's flash directive.\n * The flash can be configured with various options including type (alpha, tint, or both),\n * duration, cycles, and color.\n * \n * ## Design\n * \n * The flash uses a trigger system that is connected to the flash directive in the\n * character component. This allows for flexible configuration and can be triggered\n * from both server events and client-side code.\n * \n * @param options - Flash configuration options\n * @param options.type - Type of flash effect: 'alpha' (opacity), 'tint' (color), or 'both' (default: 'alpha')\n * @param options.duration - Duration of the flash animation in milliseconds (default: 300)\n * @param options.cycles - Number of flash cycles (flash on/off) (default: 1)\n * @param options.alpha - Alpha value when flashing, from 0 to 1 (default: 0.3)\n * @param options.tint - Tint color when flashing as hex value or color name (default: 0xffffff - white)\n * \n * @example\n * ```ts\n * // Simple flash with default settings (alpha flash)\n * player.flash();\n * \n * // Flash with red tint\n * player.flash({ type: 'tint', tint: 0xff0000 });\n * \n * // Flash with both alpha and tint\n * player.flash({ \n * type: 'both', \n * alpha: 0.5, \n * tint: 0xff0000,\n * duration: 200,\n * cycles: 2\n * });\n * \n * // Quick damage flash\n * player.flash({ \n * type: 'tint', \n * tint: 0xff0000, \n * duration: 150,\n * cycles: 1\n * });\n * ```\n */\n flash(options?: FlashOptions): void {\n const flashOptions = {\n type: options?.type || 'alpha',\n duration: options?.duration ?? 300,\n cycles: options?.cycles ?? 1,\n alpha: options?.alpha ?? 0.3,\n tint: options?.tint ?? 0xffffff,\n };\n \n // Convert color name to hex if needed\n let tintValue = flashOptions.tint;\n if (typeof tintValue === 'string') {\n // Common color name to hex mapping\n const colorMap: Record<string, number> = {\n 'white': 0xffffff,\n 'red': 0xff0000,\n 'green': 0x00ff00,\n 'blue': 0x0000ff,\n 'yellow': 0xffff00,\n 'cyan': 0x00ffff,\n 'magenta': 0xff00ff,\n 'black': 0x000000,\n };\n tintValue = colorMap[tintValue.toLowerCase()] ?? 0xffffff;\n }\n \n this.flashTrigger.start({\n ...flashOptions,\n tint: tintValue,\n });\n }\n\n /**\n * Reset animation state when animation changes externally\n *\n * This method should be called when the animation changes due to movement\n * or other external factors to ensure the animation system doesn't get stuck\n *\n * @example\n * ```ts\n * // Reset when player starts moving\n * player.resetAnimationState();\n * ```\n */\n resetAnimationState() {\n if (this.animationRestoreState) {\n this.finishTemporaryAnimation();\n return;\n }\n this.animationIsPlaying.set(false);\n this.animationCurrentIndex.set(0);\n this.clearAnimationControls();\n this.resolveAnimationWait();\n }\n\n /**\n * Set a custom animation for a specific number of times\n *\n * Plays a custom animation for the specified number of repetitions.\n * The animation system prevents overlapping animations and automatically\n * returns to the previous animation when complete.\n *\n * @param animationName - Name of the animation to play\n * @param nbTimes - Number of times to repeat the animation (default: Infinity for continuous)\n * @param options - Restore and timeout options\n * @returns A promise resolved when a finite animation finishes, is interrupted, or times out\n *\n * @example\n * ```ts\n * // Play attack animation 3 times\n * await player.setAnimation('attack', 3);\n *\n * // Play continuous spell animation\n * player.setAnimation('spell');\n * ```\n */\n setAnimation(animationName: string, nbTimes?: number, options?: AnimationRestoreOptions): Promise<void>;\n /**\n * Set a custom animation with temporary graphic change\n *\n * Plays a custom animation for the specified number of repetitions and temporarily\n * changes the player's graphic (sprite sheet) during the animation. The graphic\n * is automatically reset when the animation finishes.\n *\n * @param animationName - Name of the animation to play\n * @param graphic - The graphic(s) to temporarily use during the animation\n * @param nbTimes - Number of times to repeat the animation (default: Infinity for continuous)\n * @param options - Restore and timeout options\n * @returns A promise resolved when a finite animation finishes, is interrupted, or times out\n *\n * @example\n * ```ts\n * // Play attack animation with temporary graphic change\n * await player.setAnimation('attack', 'hero_attack', 3);\n * ```\n */\n setAnimation(animationName: string, graphic?: string | string[], nbTimes?: number, options?: AnimationRestoreOptions): Promise<void>;\n setAnimation(\n animationName: string,\n graphicOrNbTimes?: string | string[] | number,\n nbTimesOrOptions?: number | AnimationRestoreOptions,\n options?: AnimationRestoreOptions\n ): Promise<void> {\n let graphic: string | string[] | undefined;\n let finalNbTimes: number = Infinity;\n let restoreOptions: AnimationRestoreOptions | undefined = options;\n\n // Handle overloads\n if (typeof graphicOrNbTimes === 'number') {\n // setAnimation(animationName, nbTimes)\n finalNbTimes = graphicOrNbTimes;\n restoreOptions = typeof nbTimesOrOptions === 'object' ? nbTimesOrOptions : options;\n } else if (graphicOrNbTimes !== undefined) {\n // setAnimation(animationName, graphic, nbTimes)\n graphic = graphicOrNbTimes;\n if (typeof nbTimesOrOptions === 'number') {\n finalNbTimes = nbTimesOrOptions;\n } else {\n finalNbTimes = Infinity;\n restoreOptions = nbTimesOrOptions ?? options;\n }\n } else {\n // setAnimation(animationName) - nbTimes remains Infinity\n finalNbTimes = Infinity;\n }\n\n if (this.animationIsPlaying()) {\n this.finishTemporaryAnimation();\n }\n\n const waitPromise =\n finalNbTimes === Infinity\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n this.animationWaitResolve = resolve;\n });\n\n this.animationIsPlaying.set(true);\n const previousAnimationName =\n restoreOptions?.restoreAnimationName ?? this.animationName();\n const previousGraphics = restoreOptions?.restoreGraphics\n ? [...restoreOptions.restoreGraphics]\n : [...this.graphics()];\n this.animationRestoreState = {\n animationName: previousAnimationName,\n graphics: previousGraphics,\n };\n this.animationCurrentIndex.set(0);\n\n // Temporarily change graphic if provided\n if (graphic !== undefined) {\n if (Array.isArray(graphic)) {\n this.graphics.set(graphic);\n } else {\n this.graphics.set([graphic]);\n }\n }\n\n this.clearAnimationControls();\n\n this.animationSubscription =\n this.animationCurrentIndex.observable.subscribe((index) => {\n if (index >= finalNbTimes) {\n this.finishTemporaryAnimation();\n }\n });\n\n if (finalNbTimes !== Infinity) {\n this.animationResetTimeout = setTimeout(() => {\n if (this.animationIsPlaying()) {\n this.finishTemporaryAnimation();\n }\n }, restoreOptions?.timeoutMs ?? Math.max(1000, finalNbTimes * 1000));\n }\n\n this.animationName.set(animationName);\n\n return waitPromise;\n }\n\n /**\n * Display a registered component animation effect on this object.\n *\n * @param id - Identifier of the component animation to play.\n * @param params - Parameters forwarded to the animation effect.\n * @returns A promise resolved when the animation component calls `onFinish`.\n */\n showComponentAnimation(id: string, params: any): Promise<void> {\n const engine = inject(RpgClientEngine);\n return engine.getComponentAnimation(id).displayEffect(params, this);\n }\n\n /**\n * Display a registered spritesheet animation effect on this object.\n *\n * @param graphic - Identifier of the spritesheet to use.\n * @param animationName - Name of the animation inside the spritesheet.\n * @returns A promise resolved when the animation component calls `onFinish`.\n */\n showAnimation(graphic: string, animationName: string = 'default'): Promise<void> {\n return this.showComponentAnimation('animation', {\n graphic,\n animationName,\n });\n }\n \n /**\n * Check whether this client object represents an event.\n *\n * @returns `true` if the object type is `event`, otherwise `false`.\n */\n isEvent(): boolean {\n return this._type === 'event';\n }\n\n /**\n * Check whether this client object represents a player.\n *\n * @returns `true` if the object type is `player`, otherwise `false`.\n */\n isPlayer(): boolean {\n return this._type === 'player';\n }\n}\n"],"mappings":";;;;;;AA+BA,IAAsB,kBAAtB,cAA8C,gBAAgB;CAe5D,cAAc;EACZ,OAAO;6BAda,SAAS;sBAChB,OAAO,GAAG;+BACD,OAAO,EAAE;4BACZ,OAAO,MAAM;gBACzB,OAAO,EAAE,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js';
4
4
  interface GuiOptions {
5
5
  name?: string;
6
6
  id?: string;
7
- component: any;
7
+ component?: any;
8
8
  display?: boolean;
9
9
  data?: any;
10
10
  /**
@@ -24,14 +24,18 @@ interface GuiOptions {
24
24
  * @default false
25
25
  */
26
26
  attachToSprite?: boolean;
27
+ /**
28
+ * Vue v4 compatibility flag. Prefer attachToSprite in v5 projects.
29
+ */
30
+ rpgAttachToSprite?: boolean;
27
31
  }
28
- interface GuiInstance {
32
+ export interface GuiInstance {
29
33
  name: string;
30
34
  component: any;
31
35
  display: WritableSignal<boolean>;
32
36
  data: WritableSignal<any>;
33
37
  autoDisplay: boolean;
34
- dependencies?: () => Signal[];
38
+ dependencies?: Signal[];
35
39
  subscription?: Subscription;
36
40
  attachToSprite?: boolean;
37
41
  }
@@ -113,7 +117,7 @@ export declare class RpgGui {
113
117
  * });
114
118
  * ```
115
119
  */
116
- add(gui: GuiOptions): void;
120
+ add(gui: GuiOptions | any): void;
117
121
  registerOptimisticReducer(guiId: string, reducer: OptimisticReducer): void;
118
122
  /**
119
123
  * Get all attached GUI components (attachToSprite: true)
@@ -130,6 +134,8 @@ export declare class RpgGui {
130
134
  * ```
131
135
  */
132
136
  getAttachedGuis(): GuiInstance[];
137
+ getVueGuis(): GuiInstance[];
138
+ getAttachedVueGuis(): GuiInstance[];
133
139
  /**
134
140
  * Check if a player should display attached GUIs
135
141
  *
@@ -187,6 +193,13 @@ export declare class RpgGui {
187
193
  */
188
194
  hide(id: string): void;
189
195
  private isVueComponent;
196
+ private isVueComponentInstance;
197
+ private removeCanvasGui;
198
+ private removeVueGui;
199
+ private resolveComponent;
200
+ private resolveGuiId;
201
+ private resolveAttachToSprite;
202
+ private toGuiState;
190
203
  private clearPendingActions;
191
204
  private applyReducers;
192
205
  private applyOptimisticAction;
package/dist/Gui/Gui.js CHANGED
@@ -146,6 +146,7 @@ var RpgGui = class {
146
146
  */
147
147
  _setVueGuiInstance(vueGuiInstance) {
148
148
  this.vueGuiInstance = vueGuiInstance;
149
+ this._initializeVueComponents();
149
150
  }
150
151
  /**
151
152
  * Notify VueGui about GUI state changes
@@ -156,35 +157,16 @@ var RpgGui = class {
156
157
  * @param data - Component data
157
158
  */
158
159
  _notifyVueGui(guiId, display, data = {}) {
159
- if (this.vueGuiInstance && this.vueGuiInstance.vm) {
160
- const extraGui = this.extraGuis.find((gui) => gui.name === guiId);
161
- if (extraGui) {
162
- this.vueGuiInstance.vm.gui[guiId] = {
163
- name: guiId,
164
- display,
165
- data,
166
- attachToSprite: extraGui.attachToSprite || false
167
- };
168
- this.vueGuiInstance.vm.gui = Object.assign({}, this.vueGuiInstance.vm.gui);
169
- }
170
- }
160
+ const extraGui = this.extraGuis.find((gui) => gui.name === guiId);
161
+ if (!extraGui) return;
162
+ this.vueGuiInstance?.updateGuiState?.(this.toGuiState(extraGui, display, data));
171
163
  }
172
164
  /**
173
165
  * Initialize Vue components in the VueGui instance
174
166
  * This should be called after VueGui is mounted
175
167
  */
176
168
  _initializeVueComponents() {
177
- if (this.vueGuiInstance && this.vueGuiInstance.vm) {
178
- this.extraGuis.forEach((gui) => {
179
- this.vueGuiInstance.vm.gui[gui.name] = {
180
- name: gui.name,
181
- display: gui.display(),
182
- data: gui.data(),
183
- attachToSprite: gui.attachToSprite || false
184
- };
185
- });
186
- this.vueGuiInstance.vm.gui = Object.assign({}, this.vueGuiInstance.vm.gui);
187
- }
169
+ this.vueGuiInstance?.initializeGuiStates?.(this.extraGuis.map((gui) => this.toGuiState(gui)));
188
170
  }
189
171
  guiInteraction(guiId, name, data) {
190
172
  const clientActionId = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`;
@@ -244,24 +226,34 @@ var RpgGui = class {
244
226
  * ```
245
227
  */
246
228
  add(gui) {
247
- const guiId = gui.name || gui.id;
229
+ const component = this.resolveComponent(gui);
230
+ const guiId = this.resolveGuiId(gui, component);
248
231
  if (!guiId) throw new Error("GUI must have a name or id");
232
+ const attachToSprite = this.resolveAttachToSprite(gui, component);
249
233
  const guiInstance = {
250
234
  name: guiId,
251
- component: gui.component,
235
+ component,
252
236
  display: signal(gui.display || false),
253
237
  data: signal(gui.data || {}),
254
238
  autoDisplay: gui.autoDisplay || false,
255
239
  dependencies: gui.dependencies ? gui.dependencies() : [],
256
- attachToSprite: gui.attachToSprite || false
240
+ attachToSprite
257
241
  };
258
- if (typeof gui.component !== "function") {
259
- guiInstance.component = gui;
260
- this.extraGuis.push(guiInstance);
261
- if (guiInstance.autoDisplay) this._notifyVueGui(guiId, true, gui.data || {});
242
+ if (this.isVueComponentInstance(guiInstance)) {
243
+ this.removeCanvasGui(guiId);
244
+ const existingIndex = this.extraGuis.findIndex((existing) => existing.name === guiId);
245
+ if (existingIndex >= 0) {
246
+ this.extraGuis[existingIndex].subscription?.unsubscribe();
247
+ this.extraGuis[existingIndex] = guiInstance;
248
+ } else this.extraGuis.push(guiInstance);
249
+ this._initializeVueComponents();
250
+ if (guiInstance.autoDisplay) this.display(guiId, gui.data);
251
+ else this._notifyVueGui(guiId, guiInstance.display(), guiInstance.data());
262
252
  return;
263
253
  }
254
+ this.removeVueGui(guiId);
264
255
  this.gui()[guiId] = guiInstance;
256
+ this._initializeVueComponents();
265
257
  if (guiInstance.autoDisplay && typeof gui.component === "function") this.display(guiId, gui.data);
266
258
  }
267
259
  registerOptimisticReducer(guiId, reducer) {
@@ -283,8 +275,13 @@ var RpgGui = class {
283
275
  * ```
284
276
  */
285
277
  getAttachedGuis() {
286
- const allGuis = this.getAll();
287
- return Object.values(allGuis).filter((gui) => gui.attachToSprite === true);
278
+ return Object.values(this.gui()).filter((gui) => gui.attachToSprite === true);
279
+ }
280
+ getVueGuis() {
281
+ return [...this.extraGuis];
282
+ }
283
+ getAttachedVueGuis() {
284
+ return this.extraGuis.filter((gui) => gui.attachToSprite === true);
288
285
  }
289
286
  /**
290
287
  * Check if a player should display attached GUIs
@@ -358,7 +355,7 @@ var RpgGui = class {
358
355
  guiInstance.subscription.unsubscribe();
359
356
  guiInstance.subscription = void 0;
360
357
  }
361
- const deps = dependencies.length > 0 ? dependencies : guiInstance.dependencies ? guiInstance.dependencies() : [];
358
+ const deps = dependencies.length > 0 ? dependencies : guiInstance.dependencies ?? [];
362
359
  if (deps.length > 0) {
363
360
  guiInstance.subscription = combineLatest(deps.map((dependency) => dependency.observable)).subscribe((values) => {
364
361
  if (values.every((value) => value !== void 0)) {
@@ -399,6 +396,39 @@ var RpgGui = class {
399
396
  isVueComponent(id) {
400
397
  return this.extraGuis.some((gui) => gui.name === id);
401
398
  }
399
+ isVueComponentInstance(gui) {
400
+ return typeof gui.component !== "function";
401
+ }
402
+ removeCanvasGui(guiId) {
403
+ const current = this.gui();
404
+ if (!(guiId in current)) return;
405
+ const next = { ...current };
406
+ delete next[guiId];
407
+ this.gui.set(next);
408
+ }
409
+ removeVueGui(guiId) {
410
+ const removed = this.extraGuis.filter((existing) => existing.name === guiId);
411
+ removed.forEach((gui) => gui.subscription?.unsubscribe());
412
+ if (removed.length > 0) this.extraGuis = this.extraGuis.filter((existing) => existing.name !== guiId);
413
+ }
414
+ resolveComponent(gui) {
415
+ return gui?.component ?? gui;
416
+ }
417
+ resolveGuiId(gui, component) {
418
+ return gui?.name || gui?.id || component?.name || component?.__name;
419
+ }
420
+ resolveAttachToSprite(gui, component) {
421
+ return !!(gui?.attachToSprite || gui?.rpgAttachToSprite || component?.attachToSprite || component?.rpgAttachToSprite);
422
+ }
423
+ toGuiState(gui, display = gui.display(), data = gui.data()) {
424
+ return {
425
+ name: gui.name,
426
+ component: gui.component,
427
+ display,
428
+ data,
429
+ attachToSprite: gui.attachToSprite || false
430
+ };
431
+ }
402
432
  clearPendingActions(guiId) {
403
433
  this.pendingActions.delete(guiId);
404
434
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Gui.js","names":[],"sources":["../../src/Gui/Gui.ts"],"sourcesContent":["import { Context, inject } from \"@signe/di\";\nimport { signal, Signal, WritableSignal } from \"canvasengine\";\nimport { AbstractWebsocket, WebSocketToken } from \"../services/AbstractSocket\";\nimport { DialogboxComponent, ShopComponent, SaveLoadComponent, MainMenuComponent, NotificationComponent, TitleScreenComponent, GameoverComponent } from \"../components/gui\";\nimport { combineLatest, Subscription } from \"rxjs\";\nimport { delay, PrebuiltGui } from \"@rpgjs/common\";\n\ninterface GuiOptions {\n name?: string;\n id?: string;\n component: any;\n display?: boolean;\n data?: any;\n /**\n * Auto display the GUI when added to the system\n * @default false\n */\n autoDisplay?: boolean;\n /**\n * Function that returns an array of Signal dependencies\n * The GUI will only display when all dependencies are resolved (!= undefined)\n * @returns Array of Signal dependencies\n */\n dependencies?: () => Signal[];\n /**\n * Attach the GUI to sprites instead of displaying globally\n * When true, the GUI will be rendered in character.ce for each sprite\n * @default false\n */\n attachToSprite?: boolean;\n}\n\ninterface GuiInstance {\n name: string;\n component: any;\n display: WritableSignal<boolean>;\n data: WritableSignal<any>;\n autoDisplay: boolean;\n dependencies?: () => Signal[];\n subscription?: Subscription;\n attachToSprite?: boolean;\n}\n\ninterface GuiAction {\n guiId: string;\n name: string;\n data: any;\n clientActionId: string;\n}\n\ntype OptimisticReducer = (data: any, action: GuiAction) => any;\n\nconst throwError = (id: string) => {\n throw `The GUI named ${id} is non-existent. Please add the component in the gui property of the decorator @RpgClient`;\n};\n\nconst updateItemQuantity = (items: any[], id: string) => {\n const index = items.findIndex((item) => item?.id === id);\n if (index === -1) return items;\n const item = items[index];\n if (item?.usable === false) return items;\n if (item?.consumable === false) return items;\n const quantity = typeof item?.quantity === \"number\" ? item.quantity : 1;\n const nextQuantity = Math.max(0, quantity - 1);\n if (nextQuantity === quantity) return items;\n if (nextQuantity <= 0) {\n return items.filter((_, idx) => idx !== index);\n }\n const nextItems = items.slice();\n nextItems[index] = { ...item, quantity: nextQuantity };\n return nextItems;\n};\n\nconst updateEquippedFlag = (items: any[], id: string, equip: boolean) => {\n const index = items.findIndex((item) => item?.id === id);\n if (index === -1) return items;\n const item = items[index];\n if (item?.equipped === equip) return items;\n const nextItems = items.slice();\n nextItems[index] = { ...item, equipped: equip };\n return nextItems;\n};\n\nconst mainMenuOptimisticReducer: OptimisticReducer = (data, action) => {\n if (!data || typeof data !== \"object\") return data;\n if (action.name === \"useItem\") {\n if (!Array.isArray(data.items)) return data;\n const id = action.data?.id;\n if (!id) return data;\n const nextItems = updateItemQuantity(data.items, id);\n if (nextItems === data.items) return data;\n return { ...data, items: nextItems };\n }\n if (action.name === \"equipItem\") {\n const id = action.data?.id;\n if (!id || typeof action.data?.equip !== \"boolean\") return data;\n const equip = action.data.equip;\n let nextItems = data.items;\n let nextEquips = data.equips;\n if (Array.isArray(data.items)) {\n nextItems = updateEquippedFlag(data.items, id, equip);\n }\n if (Array.isArray(data.equips)) {\n nextEquips = updateEquippedFlag(data.equips, id, equip);\n }\n if (nextItems === data.items && nextEquips === data.equips) return data;\n return {\n ...data,\n ...(nextItems !== data.items ? { items: nextItems } : {}),\n ...(nextEquips !== data.equips ? { equips: nextEquips } : {})\n };\n }\n return data;\n};\n\nexport class RpgGui {\n private webSocket: AbstractWebsocket;\n gui = signal<Record<string, GuiInstance>>({});\n extraGuis: GuiInstance[] = [];\n private vueGuiInstance: any = null; // Reference to VueGui instance\n private optimisticReducers = new Map<string, OptimisticReducer[]>();\n private pendingActions = new Map<string, GuiAction[]>();\n /**\n * Signal tracking which player IDs should display attached GUIs\n * Key: player ID, Value: boolean (true = show, false = hide)\n */\n attachedGuiDisplayState = signal<Record<string, boolean>>({});\n\n constructor(private context: Context) {\n this.webSocket = inject(context, WebSocketToken);\n this.add({\n name: \"rpg-dialog\",\n component: DialogboxComponent,\n });\n this.add({\n name: PrebuiltGui.MainMenu,\n component: MainMenuComponent,\n });\n this.add({\n name: PrebuiltGui.Shop,\n component: ShopComponent,\n });\n this.add({\n name: PrebuiltGui.Notification,\n component: NotificationComponent,\n autoDisplay: true,\n });\n this.add({\n name: PrebuiltGui.Save,\n component: SaveLoadComponent,\n });\n this.add({\n name: PrebuiltGui.TitleScreen,\n component: TitleScreenComponent,\n });\n this.add({\n name: PrebuiltGui.Gameover,\n component: GameoverComponent,\n });\n\n this.registerOptimisticReducer(PrebuiltGui.MainMenu, mainMenuOptimisticReducer);\n }\n\n async _initialize() {\n this.webSocket.on(\"gui.open\", (data: { guiId: string; data: any }) => {\n this.clearPendingActions(data.guiId);\n this.display(data.guiId, data.data);\n });\n\n this.webSocket.on(\"gui.exit\", (guiId: string) => {\n this.hide(guiId);\n });\n\n this.webSocket.on(\"gui.update\", (payload: { guiId: string; data: any; clientActionId?: string }) => {\n this.applyServerUpdate(payload.guiId, payload.data, payload.clientActionId);\n });\n\n /**\n * Listen for tooltip display state changes from server\n * This is triggered by showAttachedGui/hideAttachedGui on the server\n */\n this.webSocket.on(\"gui.tooltip\", (data: { players: string[]; display: boolean }) => {\n const currentState = { ...this.attachedGuiDisplayState() };\n data.players.forEach((playerId) => {\n currentState[playerId] = data.display;\n });\n this.attachedGuiDisplayState.set(currentState);\n });\n }\n\n /**\n * Set the VueGui instance reference for Vue component management\n * This is called by VueGui when it's initialized\n * \n * @param vueGuiInstance - The VueGui instance\n */\n _setVueGuiInstance(vueGuiInstance: any) {\n this.vueGuiInstance = vueGuiInstance;\n }\n\n /**\n * Notify VueGui about GUI state changes\n * This synchronizes the Vue component display state\n * \n * @param guiId - The GUI component ID\n * @param display - Display state\n * @param data - Component data\n */\n private _notifyVueGui(guiId: string, display: boolean, data: any = {}) {\n if (this.vueGuiInstance && this.vueGuiInstance.vm) {\n // Find the GUI in extraGuis\n const extraGui = this.extraGuis.find(gui => gui.name === guiId);\n if (extraGui) {\n // Update the Vue component's display state and data\n this.vueGuiInstance.vm.gui[guiId] = {\n name: guiId,\n display,\n data,\n attachToSprite: extraGui.attachToSprite || false\n };\n // Trigger Vue reactivity\n this.vueGuiInstance.vm.gui = Object.assign({}, this.vueGuiInstance.vm.gui);\n }\n }\n }\n\n /**\n * Initialize Vue components in the VueGui instance\n * This should be called after VueGui is mounted\n */\n _initializeVueComponents() {\n if (this.vueGuiInstance && this.vueGuiInstance.vm) {\n // Initialize all extraGuis in the Vue instance\n this.extraGuis.forEach(gui => {\n this.vueGuiInstance.vm.gui[gui.name] = {\n name: gui.name,\n display: gui.display(),\n data: gui.data(),\n attachToSprite: gui.attachToSprite || false\n };\n });\n \n // Trigger Vue reactivity\n this.vueGuiInstance.vm.gui = Object.assign({}, this.vueGuiInstance.vm.gui);\n }\n }\n\n guiInteraction(guiId: string, name: string, data: any) {\n const clientActionId = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`;\n const actionData = { ...(data || {}), clientActionId };\n this.applyOptimisticAction({\n guiId,\n name,\n data: actionData,\n clientActionId\n });\n this.webSocket.emit(\"gui.interaction\", {\n guiId,\n name,\n data: actionData,\n });\n }\n\n guiClose(guiId: string, data?: any) {\n this.webSocket.emit(\"gui.exit\", {\n guiId,\n data,\n });\n }\n\n /**\n * Add a GUI component to the system\n * \n * By default, only CanvasEngine components (.ce files) are accepted.\n * Vue components should be handled by the @rpgjs/vue package.\n * \n * @param gui - GUI configuration options\n * @param gui.name - Name or ID of the GUI component\n * @param gui.id - Alternative ID if name is not provided\n * @param gui.component - The component to render (must be a CanvasEngine component)\n * @param gui.display - Initial display state (default: false)\n * @param gui.data - Initial data for the component\n * @param gui.autoDisplay - Auto display when added (default: false)\n * @param gui.dependencies - Function returning Signal dependencies\n * @param gui.attachToSprite - Attach GUI to sprites instead of global display (default: false)\n * \n * @example\n * ```ts\n * gui.add({\n * name: 'inventory',\n * component: InventoryComponent, // Must be a .ce component\n * autoDisplay: true,\n * dependencies: () => [playerSignal, inventorySignal]\n * });\n * \n * // Attach to sprites\n * gui.add({\n * name: 'tooltip',\n * component: TooltipComponent,\n * attachToSprite: true\n * });\n * ```\n */\n add(gui: GuiOptions) {\n const guiId = gui.name || gui.id;\n if (!guiId) {\n throw new Error(\"GUI must have a name or id\");\n }\n const guiInstance: GuiInstance = {\n name: guiId,\n component: gui.component,\n display: signal(gui.display || false),\n data: signal(gui.data || {}),\n autoDisplay: gui.autoDisplay || false,\n dependencies: gui.dependencies ? gui.dependencies() : [],\n attachToSprite: gui.attachToSprite || false,\n };\n\n // Accept both CanvasEngine components (.ce) and Vue components\n // Vue components will be handled by VueGui if available\n if (typeof gui.component !== 'function') {\n guiInstance.component = gui;\n this.extraGuis.push(guiInstance);\n \n // Auto display Vue components if enabled\n if (guiInstance.autoDisplay) {\n this._notifyVueGui(guiId, true, gui.data || {});\n }\n return;\n }\n\n this.gui()[guiId] = guiInstance;\n\n // Auto display if enabled and it's a CanvasEngine component\n if (guiInstance.autoDisplay && typeof gui.component === 'function') {\n this.display(guiId, gui.data);\n }\n }\n\n registerOptimisticReducer(guiId: string, reducer: OptimisticReducer) {\n const existing = this.optimisticReducers.get(guiId) || [];\n this.optimisticReducers.set(guiId, existing.concat(reducer));\n }\n\n /**\n * Get all attached GUI components (attachToSprite: true)\n * \n * Returns all GUI instances that are configured to be attached to sprites.\n * These GUIs should be rendered in character.ce instead of canvas.ce.\n * \n * @returns Array of GUI instances with attachToSprite: true\n * \n * @example\n * ```ts\n * const attachedGuis = gui.getAttachedGuis();\n * // Use in character.ce to render tooltips\n * ```\n */\n getAttachedGuis(): GuiInstance[] {\n const allGuis = this.getAll();\n return Object.values(allGuis).filter(gui => gui.attachToSprite === true);\n }\n\n /**\n * Check if a player should display attached GUIs\n * \n * @param playerId - The player ID to check\n * @returns true if attached GUIs should be displayed for this player\n */\n shouldDisplayAttachedGui(playerId: string): boolean {\n return this.attachedGuiDisplayState()[playerId] === true;\n }\n\n get(id: string): GuiInstance | undefined {\n // Check CanvasEngine GUIs first\n const canvasGui = this.gui()[id];\n if (canvasGui) {\n return canvasGui;\n }\n \n // Check Vue GUIs in extraGuis\n return this.extraGuis.find(gui => gui.name === id);\n }\n\n exists(id: string): boolean {\n return !!this.get(id);\n }\n\n getAll(): Record<string, GuiInstance> {\n const allGuis = { ...this.gui() };\n \n // Add extraGuis to the result\n this.extraGuis.forEach(gui => {\n allGuis[gui.name] = gui;\n });\n \n return allGuis;\n }\n\n /**\n * Display a GUI component\n * \n * Displays the GUI immediately if no dependencies are configured,\n * or waits for all dependencies to be resolved if dependencies are present.\n * Automatically manages subscriptions to prevent memory leaks.\n * Works with both CanvasEngine components and Vue components.\n * \n * @param id - The GUI component ID\n * @param data - Data to pass to the component\n * @param dependencies - Optional runtime dependencies (overrides config dependencies)\n * \n * @example\n * ```ts\n * // Display immediately\n * gui.display('inventory', { items: [] });\n * \n * // Display with runtime dependencies\n * gui.display('shop', { shopId: 1 }, [playerSignal, shopSignal]);\n * ```\n */\n display(id: string, data = {}, dependencies: Signal[] = []) {\n if (!this.exists(id)) {\n throw throwError(id);\n }\n\n const guiInstance = this.get(id)!;\n \n // Check if it's a Vue component (in extraGuis)\n const isVueComponent = this.extraGuis.some(gui => gui.name === id);\n \n if (isVueComponent) {\n // Handle Vue component display\n this._handleVueComponentDisplay(id, data, dependencies, guiInstance);\n } else {\n guiInstance.data.set(data);\n guiInstance.display.set(true);\n }\n }\n\n isDisplaying(id: string): boolean {\n const guiInstance = this.get(id);\n if (!guiInstance) return false;\n return guiInstance.display();\n }\n\n /**\n * Handle Vue component display logic\n * \n * @param id - GUI component ID\n * @param data - Component data\n * @param dependencies - Runtime dependencies\n * @param guiInstance - GUI instance\n */\n private _handleVueComponentDisplay(id: string, data: any, dependencies: Signal[], guiInstance: GuiInstance) {\n // Unsubscribe from previous subscription if exists\n if (guiInstance.subscription) {\n guiInstance.subscription.unsubscribe();\n guiInstance.subscription = undefined;\n }\n\n // Use runtime dependencies or config dependencies\n const deps = dependencies.length > 0 \n ? dependencies \n : (guiInstance.dependencies ? guiInstance.dependencies() : []);\n\n if (deps.length > 0) {\n // Subscribe to dependencies\n guiInstance.subscription = combineLatest(\n deps.map(dependency => dependency.observable)\n ).subscribe((values) => {\n if (values.every(value => value !== undefined)) {\n guiInstance.data.set(data);\n guiInstance.display.set(true);\n this._notifyVueGui(id, true, data);\n }\n });\n return;\n }\n\n // No dependencies, display immediately\n guiInstance.data.set(data);\n guiInstance.display.set(true);\n this._notifyVueGui(id, true, data);\n }\n\n /**\n * Hide a GUI component\n * \n * Hides the GUI and cleans up any active subscriptions.\n * Works with both CanvasEngine components and Vue components.\n * \n * @param id - The GUI component ID\n * \n * @example\n * ```ts\n * gui.hide('inventory');\n * ```\n */\n hide(id: string) {\n if (!this.exists(id)) {\n throw throwError(id);\n }\n\n const guiInstance = this.get(id)!;\n \n // Unsubscribe if there's an active subscription\n if (guiInstance.subscription) {\n guiInstance.subscription.unsubscribe();\n guiInstance.subscription = undefined;\n }\n\n guiInstance.display.set(false)\n \n // Check if it's a Vue component and notify VueGui\n const isVueComponent = this.extraGuis.some(gui => gui.name === id);\n if (isVueComponent) {\n this._notifyVueGui(id, false);\n }\n }\n\n private isVueComponent(id: string) {\n return this.extraGuis.some(gui => gui.name === id);\n }\n\n private clearPendingActions(guiId: string) {\n this.pendingActions.delete(guiId);\n }\n\n private applyReducers(guiId: string, data: any, actions: GuiAction[]) {\n const reducers = this.optimisticReducers.get(guiId);\n if (!reducers || reducers.length === 0) return data;\n let next = data;\n for (const action of actions) {\n for (const reducer of reducers) {\n const updated = reducer(next, action);\n if (updated !== undefined && updated !== null && updated !== next) {\n next = updated;\n }\n }\n }\n return next;\n }\n\n private applyOptimisticAction(action: GuiAction) {\n const guiInstance = this.get(action.guiId);\n if (!guiInstance) return;\n const reducers = this.optimisticReducers.get(action.guiId);\n if (!reducers || reducers.length === 0) return;\n const currentData = guiInstance.data();\n const nextData = this.applyReducers(action.guiId, currentData, [action]);\n if (nextData === currentData) return;\n guiInstance.data.set(nextData);\n const pending = this.pendingActions.get(action.guiId) || [];\n pending.push(action);\n this.pendingActions.set(action.guiId, pending);\n if (this.isVueComponent(action.guiId)) {\n this._notifyVueGui(action.guiId, guiInstance.display(), nextData);\n }\n }\n\n private applyServerUpdate(guiId: string, data: any, clientActionId?: string) {\n const guiInstance = this.get(guiId);\n if (!guiInstance) return;\n let pending = this.pendingActions.get(guiId) || [];\n if (clientActionId) {\n pending = pending.filter(action => action.clientActionId !== clientActionId);\n } else {\n pending = [];\n }\n let nextData = data;\n if (pending.length) {\n nextData = this.applyReducers(guiId, nextData, pending);\n }\n guiInstance.data.set(nextData);\n this.pendingActions.set(guiId, pending);\n if (this.isVueComponent(guiId)) {\n this._notifyVueGui(guiId, guiInstance.display(), nextData);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAoDA,IAAM,cAAc,OAAe;CACjC,MAAM,iBAAiB,GAAG;;AAG5B,IAAM,sBAAsB,OAAc,OAAe;CACvD,MAAM,QAAQ,MAAM,WAAW,SAAS,MAAM,OAAO,GAAG;CACxD,IAAI,UAAU,IAAI,OAAO;CACzB,MAAM,OAAO,MAAM;CACnB,IAAI,MAAM,WAAW,OAAO,OAAO;CACnC,IAAI,MAAM,eAAe,OAAO,OAAO;CACvC,MAAM,WAAW,OAAO,MAAM,aAAa,WAAW,KAAK,WAAW;CACtE,MAAM,eAAe,KAAK,IAAI,GAAG,WAAW,EAAE;CAC9C,IAAI,iBAAiB,UAAU,OAAO;CACtC,IAAI,gBAAgB,GAClB,OAAO,MAAM,QAAQ,GAAG,QAAQ,QAAQ,MAAM;CAEhD,MAAM,YAAY,MAAM,OAAO;CAC/B,UAAU,SAAS;EAAE,GAAG;EAAM,UAAU;EAAc;CACtD,OAAO;;AAGT,IAAM,sBAAsB,OAAc,IAAY,UAAmB;CACvE,MAAM,QAAQ,MAAM,WAAW,SAAS,MAAM,OAAO,GAAG;CACxD,IAAI,UAAU,IAAI,OAAO;CACzB,MAAM,OAAO,MAAM;CACnB,IAAI,MAAM,aAAa,OAAO,OAAO;CACrC,MAAM,YAAY,MAAM,OAAO;CAC/B,UAAU,SAAS;EAAE,GAAG;EAAM,UAAU;EAAO;CAC/C,OAAO;;AAGT,IAAM,6BAAgD,MAAM,WAAW;CACrE,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO;CAC9C,IAAI,OAAO,SAAS,WAAW;EAC7B,IAAI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, inject } from \"@signe/di\";\nimport { signal, Signal, WritableSignal } from \"canvasengine\";\nimport { AbstractWebsocket, WebSocketToken } from \"../services/AbstractSocket\";\nimport { DialogboxComponent, ShopComponent, SaveLoadComponent, MainMenuComponent, NotificationComponent, TitleScreenComponent, GameoverComponent } from \"../components/gui\";\nimport { combineLatest, Subscription } from \"rxjs\";\nimport { PrebuiltGui } from \"@rpgjs/common\";\n\ninterface GuiOptions {\n name?: string;\n id?: string;\n component?: any;\n display?: boolean;\n data?: any;\n /**\n * Auto display the GUI when added to the system\n * @default false\n */\n autoDisplay?: boolean;\n /**\n * Function that returns an array of Signal dependencies\n * The GUI will only display when all dependencies are resolved (!= undefined)\n * @returns Array of Signal dependencies\n */\n dependencies?: () => Signal[];\n /**\n * Attach the GUI to sprites instead of displaying globally\n * When true, the GUI will be rendered in character.ce for each sprite\n * @default false\n */\n attachToSprite?: boolean;\n /**\n * Vue v4 compatibility flag. Prefer attachToSprite in v5 projects.\n */\n rpgAttachToSprite?: boolean;\n}\n\nexport interface GuiInstance {\n name: string;\n component: any;\n display: WritableSignal<boolean>;\n data: WritableSignal<any>;\n autoDisplay: boolean;\n dependencies?: Signal[];\n subscription?: Subscription;\n attachToSprite?: boolean;\n}\n\ntype GuiState = {\n name: string;\n component: any;\n display: boolean;\n data: any;\n attachToSprite: boolean;\n};\n\ntype VueGuiBridge = {\n updateGuiState?: (state: GuiState) => void;\n initializeGuiStates?: (states: GuiState[]) => void;\n};\n\ninterface GuiAction {\n guiId: string;\n name: string;\n data: any;\n clientActionId: string;\n}\n\ntype OptimisticReducer = (data: any, action: GuiAction) => any;\n\nconst throwError = (id: string) => {\n throw `The GUI named ${id} is non-existent. Please add the component in the gui property of the decorator @RpgClient`;\n};\n\nconst updateItemQuantity = (items: any[], id: string) => {\n const index = items.findIndex((item) => item?.id === id);\n if (index === -1) return items;\n const item = items[index];\n if (item?.usable === false) return items;\n if (item?.consumable === false) return items;\n const quantity = typeof item?.quantity === \"number\" ? item.quantity : 1;\n const nextQuantity = Math.max(0, quantity - 1);\n if (nextQuantity === quantity) return items;\n if (nextQuantity <= 0) {\n return items.filter((_, idx) => idx !== index);\n }\n const nextItems = items.slice();\n nextItems[index] = { ...item, quantity: nextQuantity };\n return nextItems;\n};\n\nconst updateEquippedFlag = (items: any[], id: string, equip: boolean) => {\n const index = items.findIndex((item) => item?.id === id);\n if (index === -1) return items;\n const item = items[index];\n if (item?.equipped === equip) return items;\n const nextItems = items.slice();\n nextItems[index] = { ...item, equipped: equip };\n return nextItems;\n};\n\nconst mainMenuOptimisticReducer: OptimisticReducer = (data, action) => {\n if (!data || typeof data !== \"object\") return data;\n if (action.name === \"useItem\") {\n if (!Array.isArray(data.items)) return data;\n const id = action.data?.id;\n if (!id) return data;\n const nextItems = updateItemQuantity(data.items, id);\n if (nextItems === data.items) return data;\n return { ...data, items: nextItems };\n }\n if (action.name === \"equipItem\") {\n const id = action.data?.id;\n if (!id || typeof action.data?.equip !== \"boolean\") return data;\n const equip = action.data.equip;\n let nextItems = data.items;\n let nextEquips = data.equips;\n if (Array.isArray(data.items)) {\n nextItems = updateEquippedFlag(data.items, id, equip);\n }\n if (Array.isArray(data.equips)) {\n nextEquips = updateEquippedFlag(data.equips, id, equip);\n }\n if (nextItems === data.items && nextEquips === data.equips) return data;\n return {\n ...data,\n ...(nextItems !== data.items ? { items: nextItems } : {}),\n ...(nextEquips !== data.equips ? { equips: nextEquips } : {})\n };\n }\n return data;\n};\n\nexport class RpgGui {\n private webSocket: AbstractWebsocket;\n gui = signal<Record<string, GuiInstance>>({});\n extraGuis: GuiInstance[] = [];\n private vueGuiInstance: VueGuiBridge | null = null;\n private optimisticReducers = new Map<string, OptimisticReducer[]>();\n private pendingActions = new Map<string, GuiAction[]>();\n /**\n * Signal tracking which player IDs should display attached GUIs\n * Key: player ID, Value: boolean (true = show, false = hide)\n */\n attachedGuiDisplayState = signal<Record<string, boolean>>({});\n\n constructor(private context: Context) {\n this.webSocket = inject(context, WebSocketToken);\n this.add({\n name: \"rpg-dialog\",\n component: DialogboxComponent,\n });\n this.add({\n name: PrebuiltGui.MainMenu,\n component: MainMenuComponent,\n });\n this.add({\n name: PrebuiltGui.Shop,\n component: ShopComponent,\n });\n this.add({\n name: PrebuiltGui.Notification,\n component: NotificationComponent,\n autoDisplay: true,\n });\n this.add({\n name: PrebuiltGui.Save,\n component: SaveLoadComponent,\n });\n this.add({\n name: PrebuiltGui.TitleScreen,\n component: TitleScreenComponent,\n });\n this.add({\n name: PrebuiltGui.Gameover,\n component: GameoverComponent,\n });\n\n this.registerOptimisticReducer(PrebuiltGui.MainMenu, mainMenuOptimisticReducer);\n }\n\n async _initialize() {\n this.webSocket.on(\"gui.open\", (data: { guiId: string; data: any }) => {\n this.clearPendingActions(data.guiId);\n this.display(data.guiId, data.data);\n });\n\n this.webSocket.on(\"gui.exit\", (guiId: string) => {\n this.hide(guiId);\n });\n\n this.webSocket.on(\"gui.update\", (payload: { guiId: string; data: any; clientActionId?: string }) => {\n this.applyServerUpdate(payload.guiId, payload.data, payload.clientActionId);\n });\n\n /**\n * Listen for tooltip display state changes from server\n * This is triggered by showAttachedGui/hideAttachedGui on the server\n */\n this.webSocket.on(\"gui.tooltip\", (data: { players: string[]; display: boolean }) => {\n const currentState = { ...this.attachedGuiDisplayState() };\n data.players.forEach((playerId) => {\n currentState[playerId] = data.display;\n });\n this.attachedGuiDisplayState.set(currentState);\n });\n }\n\n /**\n * Set the VueGui instance reference for Vue component management\n * This is called by VueGui when it's initialized\n * \n * @param vueGuiInstance - The VueGui instance\n */\n _setVueGuiInstance(vueGuiInstance: any) {\n this.vueGuiInstance = vueGuiInstance;\n this._initializeVueComponents();\n }\n\n /**\n * Notify VueGui about GUI state changes\n * This synchronizes the Vue component display state\n * \n * @param guiId - The GUI component ID\n * @param display - Display state\n * @param data - Component data\n */\n private _notifyVueGui(guiId: string, display: boolean, data: any = {}) {\n const extraGui = this.extraGuis.find(gui => gui.name === guiId);\n if (!extraGui) return;\n this.vueGuiInstance?.updateGuiState?.(this.toGuiState(extraGui, display, data));\n }\n\n /**\n * Initialize Vue components in the VueGui instance\n * This should be called after VueGui is mounted\n */\n _initializeVueComponents() {\n this.vueGuiInstance?.initializeGuiStates?.(\n this.extraGuis.map(gui => this.toGuiState(gui))\n );\n }\n\n guiInteraction(guiId: string, name: string, data: any) {\n const clientActionId = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`;\n const actionData = { ...(data || {}), clientActionId };\n this.applyOptimisticAction({\n guiId,\n name,\n data: actionData,\n clientActionId\n });\n this.webSocket.emit(\"gui.interaction\", {\n guiId,\n name,\n data: actionData,\n });\n }\n\n guiClose(guiId: string, data?: any) {\n this.webSocket.emit(\"gui.exit\", {\n guiId,\n data,\n });\n }\n\n /**\n * Add a GUI component to the system\n * \n * By default, only CanvasEngine components (.ce files) are accepted.\n * Vue components should be handled by the @rpgjs/vue package.\n * \n * @param gui - GUI configuration options\n * @param gui.name - Name or ID of the GUI component\n * @param gui.id - Alternative ID if name is not provided\n * @param gui.component - The component to render (must be a CanvasEngine component)\n * @param gui.display - Initial display state (default: false)\n * @param gui.data - Initial data for the component\n * @param gui.autoDisplay - Auto display when added (default: false)\n * @param gui.dependencies - Function returning Signal dependencies\n * @param gui.attachToSprite - Attach GUI to sprites instead of global display (default: false)\n * \n * @example\n * ```ts\n * gui.add({\n * name: 'inventory',\n * component: InventoryComponent, // Must be a .ce component\n * autoDisplay: true,\n * dependencies: () => [playerSignal, inventorySignal]\n * });\n * \n * // Attach to sprites\n * gui.add({\n * name: 'tooltip',\n * component: TooltipComponent,\n * attachToSprite: true\n * });\n * ```\n */\n add(gui: GuiOptions | any) {\n const component = this.resolveComponent(gui);\n const guiId = this.resolveGuiId(gui, component);\n if (!guiId) {\n throw new Error(\"GUI must have a name or id\");\n }\n const attachToSprite = this.resolveAttachToSprite(gui, component);\n const guiInstance: GuiInstance = {\n name: guiId,\n component,\n display: signal<boolean>(gui.display || false),\n data: signal<any>(gui.data || {}),\n autoDisplay: gui.autoDisplay || false,\n dependencies: gui.dependencies ? gui.dependencies() : [],\n attachToSprite,\n };\n\n if (this.isVueComponentInstance(guiInstance)) {\n this.removeCanvasGui(guiId);\n const existingIndex = this.extraGuis.findIndex(existing => existing.name === guiId);\n if (existingIndex >= 0) {\n this.extraGuis[existingIndex].subscription?.unsubscribe();\n this.extraGuis[existingIndex] = guiInstance;\n } else {\n this.extraGuis.push(guiInstance);\n }\n\n this._initializeVueComponents();\n \n if (guiInstance.autoDisplay) {\n this.display(guiId, gui.data);\n } else {\n this._notifyVueGui(guiId, guiInstance.display(), guiInstance.data());\n }\n return;\n }\n\n this.removeVueGui(guiId);\n this.gui()[guiId] = guiInstance;\n this._initializeVueComponents();\n\n // Auto display if enabled and it's a CanvasEngine component\n if (guiInstance.autoDisplay && typeof gui.component === 'function') {\n this.display(guiId, gui.data);\n }\n }\n\n registerOptimisticReducer(guiId: string, reducer: OptimisticReducer) {\n const existing = this.optimisticReducers.get(guiId) || [];\n this.optimisticReducers.set(guiId, existing.concat(reducer));\n }\n\n /**\n * Get all attached GUI components (attachToSprite: true)\n * \n * Returns all GUI instances that are configured to be attached to sprites.\n * These GUIs should be rendered in character.ce instead of canvas.ce.\n * \n * @returns Array of GUI instances with attachToSprite: true\n * \n * @example\n * ```ts\n * const attachedGuis = gui.getAttachedGuis();\n * // Use in character.ce to render tooltips\n * ```\n */\n getAttachedGuis(): GuiInstance[] {\n return Object.values(this.gui()).filter(gui => gui.attachToSprite === true);\n }\n\n getVueGuis(): GuiInstance[] {\n return [...this.extraGuis];\n }\n\n getAttachedVueGuis(): GuiInstance[] {\n return this.extraGuis.filter(gui => gui.attachToSprite === true);\n }\n\n /**\n * Check if a player should display attached GUIs\n * \n * @param playerId - The player ID to check\n * @returns true if attached GUIs should be displayed for this player\n */\n shouldDisplayAttachedGui(playerId: string): boolean {\n return this.attachedGuiDisplayState()[playerId] === true;\n }\n\n get(id: string): GuiInstance | undefined {\n // Check CanvasEngine GUIs first\n const canvasGui = this.gui()[id];\n if (canvasGui) {\n return canvasGui;\n }\n \n // Check Vue GUIs in extraGuis\n return this.extraGuis.find(gui => gui.name === id);\n }\n\n exists(id: string): boolean {\n return !!this.get(id);\n }\n\n getAll(): Record<string, GuiInstance> {\n const allGuis = { ...this.gui() };\n \n // Add extraGuis to the result\n this.extraGuis.forEach(gui => {\n allGuis[gui.name] = gui;\n });\n \n return allGuis;\n }\n\n /**\n * Display a GUI component\n * \n * Displays the GUI immediately if no dependencies are configured,\n * or waits for all dependencies to be resolved if dependencies are present.\n * Automatically manages subscriptions to prevent memory leaks.\n * Works with both CanvasEngine components and Vue components.\n * \n * @param id - The GUI component ID\n * @param data - Data to pass to the component\n * @param dependencies - Optional runtime dependencies (overrides config dependencies)\n * \n * @example\n * ```ts\n * // Display immediately\n * gui.display('inventory', { items: [] });\n * \n * // Display with runtime dependencies\n * gui.display('shop', { shopId: 1 }, [playerSignal, shopSignal]);\n * ```\n */\n display(id: string, data = {}, dependencies: Signal[] = []) {\n if (!this.exists(id)) {\n throw throwError(id);\n }\n\n const guiInstance = this.get(id)!;\n \n // Check if it's a Vue component (in extraGuis)\n const isVueComponent = this.extraGuis.some(gui => gui.name === id);\n \n if (isVueComponent) {\n // Handle Vue component display\n this._handleVueComponentDisplay(id, data, dependencies, guiInstance);\n } else {\n guiInstance.data.set(data);\n guiInstance.display.set(true);\n }\n }\n\n isDisplaying(id: string): boolean {\n const guiInstance = this.get(id);\n if (!guiInstance) return false;\n return guiInstance.display();\n }\n\n /**\n * Handle Vue component display logic\n * \n * @param id - GUI component ID\n * @param data - Component data\n * @param dependencies - Runtime dependencies\n * @param guiInstance - GUI instance\n */\n private _handleVueComponentDisplay(id: string, data: any, dependencies: Signal[], guiInstance: GuiInstance) {\n // Unsubscribe from previous subscription if exists\n if (guiInstance.subscription) {\n guiInstance.subscription.unsubscribe();\n guiInstance.subscription = undefined;\n }\n\n // Use runtime dependencies or config dependencies\n const deps = dependencies.length > 0 \n ? dependencies \n : (guiInstance.dependencies ?? []);\n\n if (deps.length > 0) {\n // Subscribe to dependencies\n guiInstance.subscription = combineLatest(\n deps.map(dependency => dependency.observable)\n ).subscribe((values) => {\n if (values.every(value => value !== undefined)) {\n guiInstance.data.set(data);\n guiInstance.display.set(true);\n this._notifyVueGui(id, true, data);\n }\n });\n return;\n }\n\n // No dependencies, display immediately\n guiInstance.data.set(data);\n guiInstance.display.set(true);\n this._notifyVueGui(id, true, data);\n }\n\n /**\n * Hide a GUI component\n * \n * Hides the GUI and cleans up any active subscriptions.\n * Works with both CanvasEngine components and Vue components.\n * \n * @param id - The GUI component ID\n * \n * @example\n * ```ts\n * gui.hide('inventory');\n * ```\n */\n hide(id: string) {\n if (!this.exists(id)) {\n throw throwError(id);\n }\n\n const guiInstance = this.get(id)!;\n \n // Unsubscribe if there's an active subscription\n if (guiInstance.subscription) {\n guiInstance.subscription.unsubscribe();\n guiInstance.subscription = undefined;\n }\n\n guiInstance.display.set(false)\n \n // Check if it's a Vue component and notify VueGui\n const isVueComponent = this.extraGuis.some(gui => gui.name === id);\n if (isVueComponent) {\n this._notifyVueGui(id, false);\n }\n }\n\n private isVueComponent(id: string) {\n return this.extraGuis.some(gui => gui.name === id);\n }\n\n private isVueComponentInstance(gui: GuiInstance) {\n return typeof gui.component !== \"function\";\n }\n\n private removeCanvasGui(guiId: string) {\n const current = this.gui();\n if (!(guiId in current)) return;\n const next = { ...current };\n delete next[guiId];\n this.gui.set(next);\n }\n\n private removeVueGui(guiId: string) {\n const removed = this.extraGuis.filter(existing => existing.name === guiId);\n removed.forEach(gui => gui.subscription?.unsubscribe());\n if (removed.length > 0) {\n this.extraGuis = this.extraGuis.filter(existing => existing.name !== guiId);\n }\n }\n\n private resolveComponent(gui: GuiOptions | any) {\n return gui?.component ?? gui;\n }\n\n private resolveGuiId(gui: GuiOptions | any, component: any) {\n return gui?.name || gui?.id || component?.name || component?.__name;\n }\n\n private resolveAttachToSprite(gui: GuiOptions | any, component: any) {\n return !!(gui?.attachToSprite || gui?.rpgAttachToSprite || component?.attachToSprite || component?.rpgAttachToSprite);\n }\n\n private toGuiState(gui: GuiInstance, display = gui.display(), data = gui.data()): GuiState {\n return {\n name: gui.name,\n component: gui.component,\n display,\n data,\n attachToSprite: gui.attachToSprite || false,\n };\n }\n\n private clearPendingActions(guiId: string) {\n this.pendingActions.delete(guiId);\n }\n\n private applyReducers(guiId: string, data: any, actions: GuiAction[]) {\n const reducers = this.optimisticReducers.get(guiId);\n if (!reducers || reducers.length === 0) return data;\n let next = data;\n for (const action of actions) {\n for (const reducer of reducers) {\n const updated = reducer(next, action);\n if (updated !== undefined && updated !== null && updated !== next) {\n next = updated;\n }\n }\n }\n return next;\n }\n\n private applyOptimisticAction(action: GuiAction) {\n const guiInstance = this.get(action.guiId);\n if (!guiInstance) return;\n const reducers = this.optimisticReducers.get(action.guiId);\n if (!reducers || reducers.length === 0) return;\n const currentData = guiInstance.data();\n const nextData = this.applyReducers(action.guiId, currentData, [action]);\n if (nextData === currentData) return;\n guiInstance.data.set(nextData);\n const pending = this.pendingActions.get(action.guiId) || [];\n pending.push(action);\n this.pendingActions.set(action.guiId, pending);\n if (this.isVueComponent(action.guiId)) {\n this._notifyVueGui(action.guiId, guiInstance.display(), nextData);\n }\n }\n\n private applyServerUpdate(guiId: string, data: any, clientActionId?: string) {\n const guiInstance = this.get(guiId);\n if (!guiInstance) return;\n let pending = this.pendingActions.get(guiId) || [];\n if (clientActionId) {\n pending = pending.filter(action => action.clientActionId !== clientActionId);\n } else {\n pending = [];\n }\n let nextData = data;\n if (pending.length) {\n nextData = this.applyReducers(guiId, nextData, pending);\n }\n guiInstance.data.set(nextData);\n this.pendingActions.set(guiId, pending);\n if (this.isVueComponent(guiId)) {\n this._notifyVueGui(guiId, guiInstance.display(), nextData);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqEA,IAAM,cAAc,OAAe;CACjC,MAAM,iBAAiB,GAAG;;AAG5B,IAAM,sBAAsB,OAAc,OAAe;CAC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O,OAAO,YAAY,SAAS,EAAE,SAAS;;CAIrE,kBAA0B,OAAe,MAAW,gBAAyB;EAC3E,MAAM,cAAc,KAAK,IAAI,MAAM;EACnC,IAAI,CAAC,aAAa;EAClB,IAAI,UAAU,KAAK,eAAe,IAAI,MAAM,IAAI,EAAE;EAClD,IAAI,gBACF,UAAU,QAAQ,QAAO,WAAU,OAAO,mBAAmB,eAAe;OAE5E,UAAU,EAAE;EAEd,IAAI,WAAW;EACf,IAAI,QAAQ,QACV,WAAW,KAAK,cAAc,OAAO,UAAU,QAAQ;EAEzD,YAAY,KAAK,IAAI,SAAS;EAC9B,KAAK,eAAe,IAAI,OAAO,QAAQ;EACvC,IAAI,KAAK,eAAe,MAAM,EAC5B,KAAK,cAAc,OAAO,YAAY,SAAS,EAAE,SAAS"}
@@ -0,0 +1 @@
1
+ export {};
package/dist/Resource.js CHANGED
@@ -61,7 +61,7 @@ var RpgResource = class RpgResource {
61
61
  RpgResource._spritesheets.clear();
62
62
  RpgResource.engine.spritesheets.forEach((spritesheet, id) => {
63
63
  const imageLink = spritesheet?.image || spritesheet?.imageSource || void 0;
64
- if (imageLink) RpgResource._spritesheets.set(id, imageLink);
64
+ if (imageLink) RpgResource._spritesheets.set(String(id), imageLink);
65
65
  });
66
66
  RpgResource._sounds.clear();
67
67
  RpgResource.engine.sounds.forEach((sound, id) => {
@@ -1 +1 @@
1
- {"version":3,"file":"Resource.js","names":[],"sources":["../src/Resource.ts"],"sourcesContent":["import { RpgClientEngine } from './RpgClientEngine';\n\n/**\n * RpgResource class\n * \n * Provides a unified API to access resource file links (images and sounds) in the game.\n * Resources are stored as Maps of resource IDs to file paths/URLs.\n * \n * ## Design\n * \n * RpgResource acts as a facade over the engine's resource storage, providing\n * easy access to resource file links. It maintains Maps that are synchronized\n * with the engine's internal storage, but only stores the file paths/URLs,\n * not the full resource objects.\n * \n * @example\n * ```ts\n * import { RpgResource } from '@rpgjs/client'\n * \n * // Get spritesheet image link\n * const imageLink = RpgResource.spritesheets.get('hero')\n * \n * // Get sound file link\n * const soundLink = RpgResource.sounds.get('town-music')\n * \n * // Set a new resource link\n * RpgResource.spritesheets.set('new-sprite', './assets/new-sprite.png')\n * ```\n */\nexport class RpgResource {\n private static engine: RpgClientEngine | null = null;\n private static _spritesheets: Map<string, string> = new Map();\n private static _sounds: Map<string, string> = new Map();\n\n /**\n * Initialize RpgResource with the engine instance\n * \n * This is called automatically by the engine during initialization.\n * It synchronizes the resource Maps with the engine's internal storage.\n * \n * @param engine - The RpgClientEngine instance\n */\n static init(engine: RpgClientEngine): void {\n RpgResource.engine = engine;\n RpgResource.syncResources();\n }\n\n /**\n * Synchronize resource Maps with the engine's internal storage\n * \n * Extracts file links from spritesheets and sounds stored in the engine\n * and updates the Maps accordingly.\n * \n * @private\n */\n private static syncResources(): void {\n if (!RpgResource.engine) {\n return;\n }\n\n // Sync spritesheets\n RpgResource._spritesheets.clear();\n RpgResource.engine.spritesheets.forEach((spritesheet, id) => {\n // Extract image path from spritesheet\n const imageLink = spritesheet?.image || spritesheet?.imageSource || undefined;\n if (imageLink) {\n RpgResource._spritesheets.set(id, imageLink);\n }\n });\n\n // Sync sounds\n RpgResource._sounds.clear();\n RpgResource.engine.sounds.forEach((sound, id) => {\n // Extract src path from sound\n let soundLink: string | undefined;\n \n // If it's a Howler instance, try to get src from _src or src property\n if (sound && typeof sound === 'object') {\n if (sound._src && Array.isArray(sound._src) && sound._src.length > 0) {\n soundLink = sound._src[0];\n } else if (sound.src && typeof sound.src === 'string') {\n soundLink = sound.src;\n } else if (sound.src && Array.isArray(sound.src) && sound.src.length > 0) {\n soundLink = sound.src[0];\n }\n }\n \n if (soundLink) {\n RpgResource._sounds.set(id, soundLink);\n }\n });\n }\n\n /**\n * Get/Set image links for spritesheets\n * \n * Map of spritesheet IDs to their image file paths/URLs.\n * This Map is synchronized with the engine's spritesheet storage.\n * \n * @type {Map<string, string>}\n * \n * @example\n * ```ts\n * // Get an image link\n * const imageLink = RpgResource.spritesheets.get('hero')\n * \n * // Set a new image link\n * RpgResource.spritesheets.set('new-sprite', './assets/new-sprite.png')\n * \n * // Check if a spritesheet exists\n * if (RpgResource.spritesheets.has('monster')) {\n * const link = RpgResource.spritesheets.get('monster')\n * }\n * ```\n */\n static get spritesheets(): Map<string, string> {\n // Sync before returning to ensure we have the latest data\n RpgResource.syncResources();\n return RpgResource._spritesheets;\n }\n\n /**\n * Get/Set sound file links\n * \n * Map of sound IDs to their audio file paths/URLs.\n * This Map is synchronized with the engine's sound storage.\n * \n * @type {Map<string, string>}\n * \n * @example\n * ```ts\n * // Get a sound link\n * const soundLink = RpgResource.sounds.get('town-music')\n * \n * // Set a new sound link\n * RpgResource.sounds.set('new-sound', './assets/new-sound.ogg')\n * \n * // Iterate over all sounds\n * RpgResource.sounds.forEach((link, id) => {\n * console.log(`Sound ${id}: ${link}`)\n * })\n * ```\n */\n static get sounds(): Map<string, string> {\n // Sync before returning to ensure we have the latest data\n RpgResource.syncResources();\n return RpgResource._sounds;\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAa,cAAb,MAAa,YAAY;;gBACyB;;;uCACI,IAAI,KAAK;;;iCACf,IAAI,KAAK;;;;;;;;;;CAUvD,OAAO,KAAK,QAA+B;EACzC,YAAY,SAAS;EACrB,YAAY,eAAe;;;;;;;;;;CAW7B,OAAe,gBAAsB;EACnC,IAAI,CAAC,YAAY,QACf;EAIF,YAAY,cAAc,OAAO;EACjC,YAAY,OAAO,aAAa,SAAS,aAAa,OAAO;GAE3D,MAAM,YAAY,aAAa,SAAS,aAAa,eAAe,KAAA;GACpE,IAAI,WACF,YAAY,cAAc,IAAI,IAAI,UAAU;IAE9C;EAGF,YAAY,QAAQ,OAAO;EAC3B,YAAY,OAAO,OAAO,SAAS,OAAO,OAAO;GAE/C,IAAI;GAGJ,IAAI,SAAS,OAAO,UAAU;QACxB,MAAM,QAAQ,MAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,KAAK,SAAS,GACjE,YAAY,MAAM,KAAK;SAClB,IAAI,MAAM,OAAO,OAAO,MAAM,QAAQ,UAC3C,YAAY,MAAM;SACb,IAAI,MAAM,OAAO,MAAM,QAAQ,MAAM,IAAI,IAAI,MAAM,IAAI,SAAS,GACrE,YAAY,MAAM,IAAI;;GAI1B,IAAI,WACF,YAAY,QAAQ,IAAI,IAAI,UAAU;IAExC;;;;;;;;;;;;;;;;;;;;;;;;CAyBJ,WAAW,eAAoC;EAE7C,YAAY,eAAe;EAC3B,OAAO,YAAY;;;;;;;;;;;;;;;;;;;;;;;;CAyBrB,WAAW,SAA8B;EAEvC,YAAY,eAAe;EAC3B,OAAO,YAAY"}
1
+ {"version":3,"file":"Resource.js","names":[],"sources":["../src/Resource.ts"],"sourcesContent":["import { RpgClientEngine } from './RpgClientEngine';\n\n/**\n * RpgResource class\n * \n * Provides a unified API to access resource file links (images and sounds) in the game.\n * Resources are stored as Maps of resource IDs to file paths/URLs.\n * \n * ## Design\n * \n * RpgResource acts as a facade over the engine's resource storage, providing\n * easy access to resource file links. It maintains Maps that are synchronized\n * with the engine's internal storage, but only stores the file paths/URLs,\n * not the full resource objects.\n * \n * @example\n * ```ts\n * import { RpgResource } from '@rpgjs/client'\n * \n * // Get spritesheet image link\n * const imageLink = RpgResource.spritesheets.get('hero')\n * \n * // Get sound file link\n * const soundLink = RpgResource.sounds.get('town-music')\n * \n * // Set a new resource link\n * RpgResource.spritesheets.set('new-sprite', './assets/new-sprite.png')\n * ```\n */\nexport class RpgResource {\n private static engine: RpgClientEngine | null = null;\n private static _spritesheets: Map<string, string> = new Map();\n private static _sounds: Map<string, string> = new Map();\n\n /**\n * Initialize RpgResource with the engine instance\n * \n * This is called automatically by the engine during initialization.\n * It synchronizes the resource Maps with the engine's internal storage.\n * \n * @param engine - The RpgClientEngine instance\n */\n static init(engine: RpgClientEngine): void {\n RpgResource.engine = engine;\n RpgResource.syncResources();\n }\n\n /**\n * Synchronize resource Maps with the engine's internal storage\n * \n * Extracts file links from spritesheets and sounds stored in the engine\n * and updates the Maps accordingly.\n * \n * @private\n */\n private static syncResources(): void {\n if (!RpgResource.engine) {\n return;\n }\n\n // Sync spritesheets\n RpgResource._spritesheets.clear();\n RpgResource.engine.spritesheets.forEach((spritesheet, id) => {\n // Extract image path from spritesheet\n const imageLink = spritesheet?.image || spritesheet?.imageSource || undefined;\n if (imageLink) {\n RpgResource._spritesheets.set(String(id), imageLink);\n }\n });\n\n // Sync sounds\n RpgResource._sounds.clear();\n RpgResource.engine.sounds.forEach((sound, id) => {\n // Extract src path from sound\n let soundLink: string | undefined;\n \n // If it's a Howler instance, try to get src from _src or src property\n if (sound && typeof sound === 'object') {\n if (sound._src && Array.isArray(sound._src) && sound._src.length > 0) {\n soundLink = sound._src[0];\n } else if (sound.src && typeof sound.src === 'string') {\n soundLink = sound.src;\n } else if (sound.src && Array.isArray(sound.src) && sound.src.length > 0) {\n soundLink = sound.src[0];\n }\n }\n \n if (soundLink) {\n RpgResource._sounds.set(id, soundLink);\n }\n });\n }\n\n /**\n * Get/Set image links for spritesheets\n * \n * Map of spritesheet IDs to their image file paths/URLs.\n * This Map is synchronized with the engine's spritesheet storage.\n * \n * @type {Map<string, string>}\n * \n * @example\n * ```ts\n * // Get an image link\n * const imageLink = RpgResource.spritesheets.get('hero')\n * \n * // Set a new image link\n * RpgResource.spritesheets.set('new-sprite', './assets/new-sprite.png')\n * \n * // Check if a spritesheet exists\n * if (RpgResource.spritesheets.has('monster')) {\n * const link = RpgResource.spritesheets.get('monster')\n * }\n * ```\n */\n static get spritesheets(): Map<string, string> {\n // Sync before returning to ensure we have the latest data\n RpgResource.syncResources();\n return RpgResource._spritesheets;\n }\n\n /**\n * Get/Set sound file links\n * \n * Map of sound IDs to their audio file paths/URLs.\n * This Map is synchronized with the engine's sound storage.\n * \n * @type {Map<string, string>}\n * \n * @example\n * ```ts\n * // Get a sound link\n * const soundLink = RpgResource.sounds.get('town-music')\n * \n * // Set a new sound link\n * RpgResource.sounds.set('new-sound', './assets/new-sound.ogg')\n * \n * // Iterate over all sounds\n * RpgResource.sounds.forEach((link, id) => {\n * console.log(`Sound ${id}: ${link}`)\n * })\n * ```\n */\n static get sounds(): Map<string, string> {\n // Sync before returning to ensure we have the latest data\n RpgResource.syncResources();\n return RpgResource._sounds;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAa,cAAb,MAAa,YAAY;;gBACyB;;;uCACI,IAAI,KAAK;;;iCACf,IAAI,KAAK;;;;;;;;;;CAUvD,OAAO,KAAK,QAA+B;EACzC,YAAY,SAAS;EACrB,YAAY,eAAe;;;;;;;;;;CAW7B,OAAe,gBAAsB;EACnC,IAAI,CAAC,YAAY,QACf;EAIF,YAAY,cAAc,OAAO;EACjC,YAAY,OAAO,aAAa,SAAS,aAAa,OAAO;GAE3D,MAAM,YAAY,aAAa,SAAS,aAAa,eAAe,KAAA;GACpE,IAAI,WACF,YAAY,cAAc,IAAI,OAAO,GAAG,EAAE,UAAU;IAEtD;EAGF,YAAY,QAAQ,OAAO;EAC3B,YAAY,OAAO,OAAO,SAAS,OAAO,OAAO;GAE/C,IAAI;GAGJ,IAAI,SAAS,OAAO,UAAU;QACxB,MAAM,QAAQ,MAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,KAAK,SAAS,GACjE,YAAY,MAAM,KAAK;SAClB,IAAI,MAAM,OAAO,OAAO,MAAM,QAAQ,UAC3C,YAAY,MAAM;SACb,IAAI,MAAM,OAAO,MAAM,QAAQ,MAAM,IAAI,IAAI,MAAM,IAAI,SAAS,GACrE,YAAY,MAAM,IAAI;;GAI1B,IAAI,WACF,YAAY,QAAQ,IAAI,IAAI,UAAU;IAExC;;;;;;;;;;;;;;;;;;;;;;;;CAyBJ,WAAW,eAAoC;EAE7C,YAAY,eAAe;EAC3B,OAAO,YAAY;;;;;;;;;;;;;;;;;;;;;;;;CAyBrB,WAAW,SAA8B;EAEvC,YAAY,eAAe;EAC3B,OAAO,YAAY"}