menu command api

This commit is contained in:
jonny 2021-06-21 18:22:31 +02:00
parent 979ae73d8d
commit ba1bcf226a
9 changed files with 381 additions and 252 deletions

View File

@ -65,3 +65,26 @@ WA.room.onLeaveZone('myZone', () => {
helloWorldPopup.close(); helloWorldPopup.close();
}); });
``` ```
### register additional menu entries
adds an additional Entry to the main menu , these exist until the map is unloaded
```typescript
registerMenuCommand(menuCommand: string, callback: (menuCommand: string) => void): void
```
Example:
```javascript
WA.registerMenuCommand("test", () => {
WA.sendChatMessage("test clicked", "menu cmd")
})
```
<div class="col">
<img src="./assets/menu-command.png" class="figure-img img-fluid rounded" alt="" />
</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

View File

@ -6,12 +6,14 @@ import type { ClosePopupEvent } from './ClosePopupEvent';
import type { EnterLeaveEvent } from './EnterLeaveEvent'; import type { EnterLeaveEvent } from './EnterLeaveEvent';
import type { GoToPageEvent } from './GoToPageEvent'; import type { GoToPageEvent } from './GoToPageEvent';
import type { LoadPageEvent } from './LoadPageEvent'; import type { LoadPageEvent } from './LoadPageEvent';
import type { LoadSoundEvent } from "./LoadSoundEvent";
import type { OpenCoWebSiteEvent } from './OpenCoWebSiteEvent'; import type { OpenCoWebSiteEvent } from './OpenCoWebSiteEvent';
import type { OpenPopupEvent } from './OpenPopupEvent'; import type { OpenPopupEvent } from './OpenPopupEvent';
import type { OpenTabEvent } from './OpenTabEvent'; import type { OpenTabEvent } from './OpenTabEvent';
import type { PlaySoundEvent } from "./PlaySoundEvent";
import type { MenuItemClickedEvent } from './ui/MenuItemClickedEvent';
import type { MenuItemRegisterEvent } from './ui/MenuItemRegisterEvent';
import type { UserInputChatEvent } from './UserInputChatEvent'; import type { UserInputChatEvent } from './UserInputChatEvent';
import type { LoadSoundEvent} from "./LoadSoundEvent";
import type {PlaySoundEvent} from "./PlaySoundEvent";
export interface TypedMessageEvent<T> extends MessageEvent { export interface TypedMessageEvent<T> extends MessageEvent {
@ -36,6 +38,7 @@ export type IframeEventMap = {
loadSound: LoadSoundEvent loadSound: LoadSoundEvent
playSound: PlaySoundEvent playSound: PlaySoundEvent
stopSound: null, stopSound: null,
registerMenuCommand: MenuItemRegisterEvent
} }
export interface IframeEvent<T extends keyof IframeEventMap> { export interface IframeEvent<T extends keyof IframeEventMap> {
type: T; type: T;
@ -52,6 +55,7 @@ export interface IframeResponseEventMap {
leaveEvent: EnterLeaveEvent leaveEvent: EnterLeaveEvent
buttonClickedEvent: ButtonClickedEvent buttonClickedEvent: ButtonClickedEvent
// gameState: GameStateEvent // gameState: GameStateEvent
menuItemClicked: MenuItemClickedEvent
} }
export interface IframeResponseEvent<T extends keyof IframeResponseEventMap> { export interface IframeResponseEvent<T extends keyof IframeResponseEventMap> {
type: T; type: T;

View File

@ -0,0 +1,21 @@
import * as tg from "generic-type-guard";
import { iframeListener } from '../../IframeListener';
export const isMenuItemClickedEvent =
new tg.IsInterface().withProperties({
menuItem: tg.isString
}).get();
/**
* A message sent from the game to the iFrame when a menu item is clicked.
*/
export type MenuItemClickedEvent = tg.GuardedType<typeof isMenuItemClickedEvent>;
export function sendMenuClickedEvent(menuItem: string) {
iframeListener.postMessage({
'type': 'menuItemClicked',
'data': {
menuItem: menuItem,
} as MenuItemClickedEvent
});
}

View File

@ -0,0 +1,25 @@
import * as tg from "generic-type-guard";
import { Subject } from 'rxjs';
export const isMenuItemRegisterEvent =
new tg.IsInterface().withProperties({
menutItem: tg.isString
}).get();
/**
* A message sent from the iFrame to the game to add a new menu item.
*/
export type MenuItemRegisterEvent = tg.GuardedType<typeof isMenuItemRegisterEvent>;
export const isMenuItemRegisterIframeEvent =
new tg.IsInterface().withProperties({
type: tg.isSingletonString("registerMenuCommand"),
data: isMenuItemRegisterEvent
}).get();
const _registerMenuCommandStream: Subject<string> = new Subject();
export const registerMenuCommandStream = _registerMenuCommandStream.asObservable();
export function handleMenuItemRegistrationEvent(event: MenuItemRegisterEvent) {
_registerMenuCommandStream.next(event.menutItem)
}

View File

@ -1,21 +1,22 @@
import { Subject } from "rxjs"; import { Subject } from "rxjs";
import { ChatEvent, isChatEvent } from "./Events/ChatEvent";
import { HtmlUtils } from "../WebRtc/HtmlUtils"; import { HtmlUtils } from "../WebRtc/HtmlUtils";
import type { ButtonClickedEvent } from "./Events/ButtonClickedEvent";
import { ChatEvent, isChatEvent } from "./Events/ChatEvent";
import { ClosePopupEvent, isClosePopupEvent } from "./Events/ClosePopupEvent";
import type { EnterLeaveEvent } from "./Events/EnterLeaveEvent"; import type { EnterLeaveEvent } from "./Events/EnterLeaveEvent";
import { GoToPageEvent, isGoToPageEvent } from "./Events/GoToPageEvent";
import { IframeEvent, IframeEventMap, IframeResponseEvent, IframeResponseEventMap, isIframeEventWrapper, TypedMessageEvent } from "./Events/IframeEvent";
import { isLoadPageEvent } from './Events/LoadPageEvent';
import { isLoadSoundEvent, LoadSoundEvent } from "./Events/LoadSoundEvent";
import { isOpenCoWebsite, OpenCoWebSiteEvent } from "./Events/OpenCoWebSiteEvent";
import { isOpenPopupEvent, OpenPopupEvent } from "./Events/OpenPopupEvent"; import { isOpenPopupEvent, OpenPopupEvent } from "./Events/OpenPopupEvent";
import { isOpenTabEvent, OpenTabEvent } from "./Events/OpenTabEvent"; import { isOpenTabEvent, OpenTabEvent } from "./Events/OpenTabEvent";
import type { ButtonClickedEvent } from "./Events/ButtonClickedEvent"; import { isPlaySoundEvent, PlaySoundEvent } from "./Events/PlaySoundEvent";
import { ClosePopupEvent, isClosePopupEvent } from "./Events/ClosePopupEvent"; import { isStopSoundEvent, StopSoundEvent } from "./Events/StopSoundEvent";
import { scriptUtils } from "./ScriptUtils"; import { handleMenuItemRegistrationEvent, isMenuItemRegisterIframeEvent } from './Events/ui/MenuItemRegisterEvent';
import { GoToPageEvent, isGoToPageEvent } from "./Events/GoToPageEvent";
import { isOpenCoWebsite, OpenCoWebSiteEvent } from "./Events/OpenCoWebSiteEvent";
import { IframeEventMap, IframeEvent, IframeResponseEvent, IframeResponseEventMap, isIframeEventWrapper, TypedMessageEvent } from "./Events/IframeEvent";
import type { UserInputChatEvent } from "./Events/UserInputChatEvent"; import type { UserInputChatEvent } from "./Events/UserInputChatEvent";
import { isLoadPageEvent } from './Events/LoadPageEvent'; import { scriptUtils } from "./ScriptUtils";
import {isPlaySoundEvent, PlaySoundEvent} from "./Events/PlaySoundEvent";
import {isStopSoundEvent, StopSoundEvent} from "./Events/StopSoundEvent";
import {isLoadSoundEvent, LoadSoundEvent} from "./Events/LoadSoundEvent";
/** /**
* Listens to messages from iframes and turn those messages into easy to use observables. * Listens to messages from iframes and turn those messages into easy to use observables.
* Also allows to send messages to those iframes. * Also allows to send messages to those iframes.
@ -137,9 +138,11 @@ class IframeListener {
} }
else if (payload.type === 'removeBubble') { else if (payload.type === 'removeBubble') {
this._removeBubbleStream.next(); this._removeBubbleStream.next();
}else if (payload.type === 'loadPage' && isLoadPageEvent(payload.data)){ } else if (payload.type === 'loadPage' && isLoadPageEvent(payload.data)) {
this._loadPageStream.next(payload.data.url); this._loadPageStream.next(payload.data.url);
} } else if (isMenuItemRegisterIframeEvent(payload)) [
handleMenuItemRegistrationEvent(payload.data)
]
} }
@ -263,7 +266,7 @@ class IframeListener {
/** /**
* Sends the message... to all allowed iframes. * Sends the message... to all allowed iframes.
*/ */
private postMessage(message: IframeResponseEvent<keyof IframeResponseEventMap>) { public postMessage(message: IframeResponseEvent<keyof IframeResponseEventMap>) {
for (const iframe of this.iframes) { for (const iframe of this.iframes) {
iframe.contentWindow?.postMessage(message, '*'); iframe.contentWindow?.postMessage(message, '*');
} }

View File

@ -1,14 +1,17 @@
import { isButtonClickedEvent } from '../Events/ButtonClickedEvent'; import { isButtonClickedEvent } from '../Events/ButtonClickedEvent';
import type { ClosePopupEvent } from '../Events/ClosePopupEvent'; import { isMenuItemClickedEvent } from '../Events/ui/MenuItemClickedEvent';
import type { MenuItemRegisterEvent } from '../Events/ui/MenuItemRegisterEvent';
import { IframeApiContribution, sendToWorkadventure } from './IframeApiContribution'; import { IframeApiContribution, sendToWorkadventure } from './IframeApiContribution';
import { apiCallback } from "./registeredCallbacks"; import { apiCallback } from "./registeredCallbacks";
import {Popup} from "./Ui/Popup"; import type { ButtonClickedCallback, ButtonDescriptor } from "./Ui/ButtonDescriptor";
import type {ButtonClickedCallback, ButtonDescriptor} from "./Ui/ButtonDescriptor"; import { Popup } from "./Ui/Popup";
let popupId = 0; let popupId = 0;
const popups: Map<number, Popup> = new Map<number, Popup>(); const popups: Map<number, Popup> = new Map<number, Popup>();
const popupCallbacks: Map<number, Map<number, ButtonClickedCallback>> = new Map<number, Map<number, ButtonClickedCallback>>(); const popupCallbacks: Map<number, Map<number, ButtonClickedCallback>> = new Map<number, Map<number, ButtonClickedCallback>>();
const menuCallbacks: Map<string, (command: string) => void> = new Map()
interface ZonedPopupOptions { interface ZonedPopupOptions {
zone: string zone: string
objectLayerName?: string, objectLayerName?: string,
@ -33,6 +36,16 @@ class WorkAdventureUiCommands extends IframeApiContribution<WorkAdventureUiComma
callback(popup); callback(popup);
} }
} }
}),
apiCallback({
type: "menuItemClicked",
typeChecker: isMenuItemClickedEvent,
callback: event => {
const callback = menuCallbacks.get(event.menuItem);
if (callback) {
callback(event.menuItem)
}
}
})]; })];
@ -71,6 +84,16 @@ class WorkAdventureUiCommands extends IframeApiContribution<WorkAdventureUiComma
return popup; return popup;
} }
registerMenuCommand(commandDescriptor: string, callback: (commandDescriptor: string) => void) {
menuCallbacks.set(commandDescriptor, callback);
sendToWorkadventure({
'type': 'registerMenuCommand',
'data': {
menutItem: commandDescriptor
} as MenuItemRegisterEvent
});
}
displayBubble(): void { displayBubble(): void {
sendToWorkadventure({ 'type': 'displayBubble', data: null }); sendToWorkadventure({ 'type': 'displayBubble', data: null });
} }

View File

@ -1,4 +1,10 @@
import {gameManager, HasMovedEvent} from "./GameManager"; import { Queue } from 'queue-typescript';
import type { Subscription } from "rxjs";
import { ConsoleGlobalMessageManager } from "../../Administration/ConsoleGlobalMessageManager";
import { GlobalMessageManager } from "../../Administration/GlobalMessageManager";
import { userMessageManager } from "../../Administration/UserMessageManager";
import { iframeListener } from "../../Api/IframeListener";
import { connectionManager } from "../../Connexion/ConnectionManager";
import type { import type {
GroupCreatedUpdatedMessageInterface, GroupCreatedUpdatedMessageInterface,
MessageUserJoined, MessageUserJoined,
@ -9,13 +15,50 @@ import type {
PositionInterface, PositionInterface,
RoomJoinedMessageInterface RoomJoinedMessageInterface
} from "../../Connexion/ConnexionModels"; } from "../../Connexion/ConnexionModels";
import {hasMovedEventName, Player, requestEmoteEventName} from "../Player/Player"; import { localUserStore } from "../../Connexion/LocalUserStore";
import { Room } from "../../Connexion/Room";
import type { RoomConnection } from "../../Connexion/RoomConnection";
import { worldFullMessageStream } from "../../Connexion/WorldFullMessageStream";
import { import {
DEBUG_MODE, DEBUG_MODE,
JITSI_PRIVATE_MODE, JITSI_PRIVATE_MODE,
MAX_PER_GROUP, MAX_PER_GROUP,
POSITION_DELAY, POSITION_DELAY
} from "../../Enum/EnvironmentVariable"; } from "../../Enum/EnvironmentVariable";
import { TextureError } from "../../Exception/TextureError";
import type { UserMovedMessage } from "../../Messages/generated/messages_pb";
import { ProtobufClientUtils } from "../../Network/ProtobufClientUtils";
import { peerStore } from "../../Stores/PeerStore";
import { touchScreenManager } from "../../Touch/TouchScreenManager";
import { urlManager } from "../../Url/UrlManager";
import { audioManager } from "../../WebRtc/AudioManager";
import { coWebsiteManager } from "../../WebRtc/CoWebsiteManager";
import { HtmlUtils } from "../../WebRtc/HtmlUtils";
import { jitsiFactory } from "../../WebRtc/JitsiFactory";
import {
AUDIO_LOOP_PROPERTY, AUDIO_VOLUME_PROPERTY, CenterListener,
JITSI_MESSAGE_PROPERTIES,
layoutManager,
LayoutMode,
ON_ACTION_TRIGGER_BUTTON,
TRIGGER_JITSI_PROPERTIES,
TRIGGER_WEBSITE_PROPERTIES,
WEBSITE_MESSAGE_PROPERTIES
} from "../../WebRtc/LayoutManager";
import { mediaManager } from "../../WebRtc/MediaManager";
import { SimplePeer, UserSimplePeerInterface } from "../../WebRtc/SimplePeer";
import { lazyLoadCompanionResource } from "../Companion/CompanionTexturesLoadingManager";
import { ChatModeIcon } from "../Components/ChatModeIcon";
import { addLoader } from "../Components/Loader";
import { joystickBaseImg, joystickBaseKey, joystickThumbImg, joystickThumbKey } from "../Components/MobileJoystick";
import { OpenChatIcon, openChatIconName } from "../Components/OpenChatIcon";
import { PresentationModeIcon } from "../Components/PresentationModeIcon";
import { TextUtils } from "../Components/TextUtils";
import { lazyLoadPlayerCharacterTextures, loadCustomTexture } from "../Entity/PlayerTexturesLoadingManager";
import { RemotePlayer } from "../Entity/RemotePlayer";
import type { ActionableItem } from "../Items/ActionableItem";
import type { ItemFactoryInterface } from "../Items/ItemFactoryInterface";
import { SelectCharacterScene, SelectCharacterSceneName } from "../Login/SelectCharacterScene";
import type { import type {
ITiledMap, ITiledMap,
ITiledMapLayer, ITiledMapLayer,
@ -24,80 +67,35 @@ import type {
ITiledMapTileLayer, ITiledMapTileLayer,
ITiledTileSet ITiledTileSet
} from "../Map/ITiledMap"; } from "../Map/ITiledMap";
import type {AddPlayerInterface} from "./AddPlayerInterface"; import { MenuScene, MenuSceneName } from '../Menu/MenuScene';
import {PlayerAnimationDirections} from "../Player/Animation"; import { PlayerAnimationDirections } from "../Player/Animation";
import {PlayerMovement} from "./PlayerMovement"; import { hasMovedEventName, Player, requestEmoteEventName } from "../Player/Player";
import {PlayersPositionInterpolator} from "./PlayersPositionInterpolator"; import { ErrorSceneName } from "../Reconnecting/ErrorScene";
import {RemotePlayer} from "../Entity/RemotePlayer"; import { ReconnectingSceneName } from "../Reconnecting/ReconnectingScene";
import {Queue} from 'queue-typescript'; import { waScaleManager } from "../Services/WaScaleManager";
import {SimplePeer, UserSimplePeerInterface} from "../../WebRtc/SimplePeer"; import { PinchManager } from "../UserInput/PinchManager";
import {ReconnectingSceneName} from "../Reconnecting/ReconnectingScene"; import { UserInputManager } from "../UserInput/UserInputManager";
import {lazyLoadPlayerCharacterTextures, loadCustomTexture} from "../Entity/PlayerTexturesLoadingManager"; import type { AddPlayerInterface } from "./AddPlayerInterface";
import { import { DEPTH_OVERLAY_INDEX } from "./DepthIndexes";
CenterListener, import { DirtyScene } from "./DirtyScene";
JITSI_MESSAGE_PROPERTIES, import { EmoteManager } from "./EmoteManager";
layoutManager, import { gameManager, HasMovedEvent } from "./GameManager";
LayoutMode, import { GameMap } from "./GameMap";
ON_ACTION_TRIGGER_BUTTON, import { PlayerMovement } from "./PlayerMovement";
TRIGGER_JITSI_PROPERTIES, import { PlayersPositionInterpolator } from "./PlayersPositionInterpolator";
TRIGGER_WEBSITE_PROPERTIES, import { soundManager } from "./SoundManager";
WEBSITE_MESSAGE_PROPERTIES,
AUDIO_VOLUME_PROPERTY,
AUDIO_LOOP_PROPERTY
} from "../../WebRtc/LayoutManager";
import {GameMap} from "./GameMap";
import {coWebsiteManager} from "../../WebRtc/CoWebsiteManager";
import {mediaManager} from "../../WebRtc/MediaManager";
import type {ItemFactoryInterface} from "../Items/ItemFactoryInterface";
import type {ActionableItem} from "../Items/ActionableItem";
import {UserInputManager} from "../UserInput/UserInputManager";
import {soundManager} from "./SoundManager";
import type {UserMovedMessage} from "../../Messages/generated/messages_pb";
import {ProtobufClientUtils} from "../../Network/ProtobufClientUtils";
import {connectionManager} from "../../Connexion/ConnectionManager";
import type {RoomConnection} from "../../Connexion/RoomConnection";
import {GlobalMessageManager} from "../../Administration/GlobalMessageManager";
import {userMessageManager} from "../../Administration/UserMessageManager";
import {ConsoleGlobalMessageManager} from "../../Administration/ConsoleGlobalMessageManager";
import {ResizableScene} from "../Login/ResizableScene";
import {Room} from "../../Connexion/Room";
import {jitsiFactory} from "../../WebRtc/JitsiFactory";
import {urlManager} from "../../Url/UrlManager";
import {audioManager} from "../../WebRtc/AudioManager";
import {PresentationModeIcon} from "../Components/PresentationModeIcon";
import {ChatModeIcon} from "../Components/ChatModeIcon";
import {OpenChatIcon, openChatIconName} from "../Components/OpenChatIcon";
import {SelectCharacterScene, SelectCharacterSceneName} from "../Login/SelectCharacterScene";
import {TextureError} from "../../Exception/TextureError";
import {addLoader} from "../Components/Loader";
import {ErrorSceneName} from "../Reconnecting/ErrorScene";
import {localUserStore} from "../../Connexion/LocalUserStore";
import {iframeListener} from "../../Api/IframeListener";
import {HtmlUtils} from "../../WebRtc/HtmlUtils";
import Texture = Phaser.Textures.Texture; import Texture = Phaser.Textures.Texture;
import Sprite = Phaser.GameObjects.Sprite; import Sprite = Phaser.GameObjects.Sprite;
import CanvasTexture = Phaser.Textures.CanvasTexture; import CanvasTexture = Phaser.Textures.CanvasTexture;
import GameObject = Phaser.GameObjects.GameObject; import GameObject = Phaser.GameObjects.GameObject;
import FILE_LOAD_ERROR = Phaser.Loader.Events.FILE_LOAD_ERROR; import FILE_LOAD_ERROR = Phaser.Loader.Events.FILE_LOAD_ERROR;
import DOMElement = Phaser.GameObjects.DOMElement; import DOMElement = Phaser.GameObjects.DOMElement;
import EVENT_TYPE =Phaser.Scenes.Events import EVENT_TYPE = Phaser.Scenes.Events
import type {Subscription} from "rxjs";
import {worldFullMessageStream} from "../../Connexion/WorldFullMessageStream";
import { lazyLoadCompanionResource } from "../Companion/CompanionTexturesLoadingManager";
import RenderTexture = Phaser.GameObjects.RenderTexture; import RenderTexture = Phaser.GameObjects.RenderTexture;
import Tilemap = Phaser.Tilemaps.Tilemap; import Tilemap = Phaser.Tilemaps.Tilemap;
import {DirtyScene} from "./DirtyScene";
import {TextUtils} from "../Components/TextUtils";
import {touchScreenManager} from "../../Touch/TouchScreenManager";
import {PinchManager} from "../UserInput/PinchManager";
import {joystickBaseImg, joystickBaseKey, joystickThumbImg, joystickThumbKey} from "../Components/MobileJoystick";
import {DEPTH_OVERLAY_INDEX} from "./DepthIndexes";
import {waScaleManager} from "../Services/WaScaleManager";
import {peerStore} from "../../Stores/PeerStore";
import {EmoteManager} from "./EmoteManager";
export interface GameSceneInitInterface { export interface GameSceneInitInterface {
initPosition: PointInterface|null, initPosition: PointInterface | null,
reconnecting: boolean reconnecting: boolean
} }
@ -134,10 +132,10 @@ interface DeleteGroupEventInterface {
const defaultStartLayerName = 'start'; const defaultStartLayerName = 'start';
export class GameScene extends DirtyScene implements CenterListener { export class GameScene extends DirtyScene implements CenterListener {
Terrains : Array<Phaser.Tilemaps.Tileset>; Terrains: Array<Phaser.Tilemaps.Tileset>;
CurrentPlayer!: Player; CurrentPlayer!: Player;
MapPlayers!: Phaser.Physics.Arcade.Group; MapPlayers!: Phaser.Physics.Arcade.Group;
MapPlayersByKey : Map<number, RemotePlayer> = new Map<number, RemotePlayer>(); MapPlayersByKey: Map<number, RemotePlayer> = new Map<number, RemotePlayer>();
Map!: Phaser.Tilemaps.Tilemap; Map!: Phaser.Tilemaps.Tilemap;
Layers!: Array<Phaser.Tilemaps.TilemapLayer>; Layers!: Array<Phaser.Tilemaps.TilemapLayer>;
Objects!: Array<Phaser.Physics.Arcade.Sprite>; Objects!: Array<Phaser.Physics.Arcade.Sprite>;
@ -147,10 +145,10 @@ export class GameScene extends DirtyScene implements CenterListener {
startY!: number; startY!: number;
circleTexture!: CanvasTexture; circleTexture!: CanvasTexture;
circleRedTexture!: CanvasTexture; circleRedTexture!: CanvasTexture;
pendingEvents: Queue<InitUserPositionEventInterface|AddPlayerEventInterface|RemovePlayerEventInterface|UserMovedEventInterface|GroupCreatedUpdatedEventInterface|DeleteGroupEventInterface> = new Queue<InitUserPositionEventInterface|AddPlayerEventInterface|RemovePlayerEventInterface|UserMovedEventInterface|GroupCreatedUpdatedEventInterface|DeleteGroupEventInterface>(); pendingEvents: Queue<InitUserPositionEventInterface | AddPlayerEventInterface | RemovePlayerEventInterface | UserMovedEventInterface | GroupCreatedUpdatedEventInterface | DeleteGroupEventInterface> = new Queue<InitUserPositionEventInterface | AddPlayerEventInterface | RemovePlayerEventInterface | UserMovedEventInterface | GroupCreatedUpdatedEventInterface | DeleteGroupEventInterface>();
private initPosition: PositionInterface|null = null; private initPosition: PositionInterface | null = null;
private playersPositionInterpolator = new PlayersPositionInterpolator(); private playersPositionInterpolator = new PlayersPositionInterpolator();
public connection: RoomConnection|undefined; public connection: RoomConnection | undefined;
private simplePeer!: SimplePeer; private simplePeer!: SimplePeer;
private GlobalMessageManager!: GlobalMessageManager; private GlobalMessageManager!: GlobalMessageManager;
public ConsoleGlobalMessageManager!: ConsoleGlobalMessageManager; public ConsoleGlobalMessageManager!: ConsoleGlobalMessageManager;
@ -159,7 +157,7 @@ export class GameScene extends DirtyScene implements CenterListener {
// A promise that will resolve when the "create" method is called (signaling loading is ended) // A promise that will resolve when the "create" method is called (signaling loading is ended)
private createPromise: Promise<void>; private createPromise: Promise<void>;
private createPromiseResolve!: (value?: void | PromiseLike<void>) => void; private createPromiseResolve!: (value?: void | PromiseLike<void>) => void;
private iframeSubscriptionList! : Array<Subscription>; private iframeSubscriptionList!: Array<Subscription>;
private peerStoreUnsubscribe!: () => void; private peerStoreUnsubscribe!: () => void;
MapUrlFile: string; MapUrlFile: string;
RoomId: string; RoomId: string;
@ -179,22 +177,22 @@ export class GameScene extends DirtyScene implements CenterListener {
private gameMap!: GameMap; private gameMap!: GameMap;
private actionableItems: Map<number, ActionableItem> = new Map<number, ActionableItem>(); private actionableItems: Map<number, ActionableItem> = new Map<number, ActionableItem>();
// The item that can be selected by pressing the space key. // The item that can be selected by pressing the space key.
private outlinedItem: ActionableItem|null = null; private outlinedItem: ActionableItem | null = null;
public userInputManager!: UserInputManager; public userInputManager!: UserInputManager;
private isReconnecting: boolean|undefined = undefined; private isReconnecting: boolean | undefined = undefined;
private startLayerName!: string | null; private startLayerName!: string | null;
private openChatIcon!: OpenChatIcon; private openChatIcon!: OpenChatIcon;
private playerName!: string; private playerName!: string;
private characterLayers!: string[]; private characterLayers!: string[];
private companion!: string|null; private companion!: string | null;
private messageSubscription: Subscription|null = null; private messageSubscription: Subscription | null = null;
private popUpElements : Map<number, DOMElement> = new Map<number, Phaser.GameObjects.DOMElement>(); private popUpElements: Map<number, DOMElement> = new Map<number, Phaser.GameObjects.DOMElement>();
private originalMapUrl: string|undefined; private originalMapUrl: string | undefined;
private pinchManager: PinchManager|undefined; private pinchManager: PinchManager | undefined;
private mapTransitioning: boolean = false; //used to prevent transitions happenning at the same time. private mapTransitioning: boolean = false; //used to prevent transitions happenning at the same time.
private emoteManager!: EmoteManager; private emoteManager!: EmoteManager;
constructor(private room: Room, MapUrlFile: string, customKey?: string|undefined) { constructor(private room: Room, MapUrlFile: string, customKey?: string | undefined) {
super({ super({
key: customKey ?? room.id key: customKey ?? room.id
}); });
@ -234,13 +232,13 @@ export class GameScene extends DirtyScene implements CenterListener {
//this.load.audio('audio-report-message', '/resources/objects/report-message.mp3'); //this.load.audio('audio-report-message', '/resources/objects/report-message.mp3');
this.sound.pauseOnBlur = false; this.sound.pauseOnBlur = false;
this.load.on(FILE_LOAD_ERROR, (file: {src: string}) => { this.load.on(FILE_LOAD_ERROR, (file: { src: string }) => {
// If we happen to be in HTTP and we are trying to load a URL in HTTPS only... (this happens only in dev environments) // If we happen to be in HTTP and we are trying to load a URL in HTTPS only... (this happens only in dev environments)
if (window.location.protocol === 'http:' && file.src === this.MapUrlFile && file.src.startsWith('http:') && this.originalMapUrl === undefined) { if (window.location.protocol === 'http:' && file.src === this.MapUrlFile && file.src.startsWith('http:') && this.originalMapUrl === undefined) {
this.originalMapUrl = this.MapUrlFile; this.originalMapUrl = this.MapUrlFile;
this.MapUrlFile = this.MapUrlFile.replace('http://', 'https://'); this.MapUrlFile = this.MapUrlFile.replace('http://', 'https://');
this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile); this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile);
this.load.on('filecomplete-tilemapJSON-'+this.MapUrlFile, (key: string, type: string, data: unknown) => { this.load.on('filecomplete-tilemapJSON-' + this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.onMapLoad(data); this.onMapLoad(data);
}); });
return; return;
@ -254,7 +252,7 @@ export class GameScene extends DirtyScene implements CenterListener {
this.originalMapUrl = this.MapUrlFile; this.originalMapUrl = this.MapUrlFile;
this.MapUrlFile = this.MapUrlFile.replace('https://', 'http://'); this.MapUrlFile = this.MapUrlFile.replace('https://', 'http://');
this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile); this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile);
this.load.on('filecomplete-tilemapJSON-'+this.MapUrlFile, (key: string, type: string, data: unknown) => { this.load.on('filecomplete-tilemapJSON-' + this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.onMapLoad(data); this.onMapLoad(data);
}); });
return; return;
@ -266,7 +264,7 @@ export class GameScene extends DirtyScene implements CenterListener {
message: this.originalMapUrl ?? file.src message: this.originalMapUrl ?? file.src
}); });
}); });
this.load.on('filecomplete-tilemapJSON-'+this.MapUrlFile, (key: string, type: string, data: unknown) => { this.load.on('filecomplete-tilemapJSON-' + this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.onMapLoad(data); this.onMapLoad(data);
}); });
//TODO strategy to add access token //TODO strategy to add access token
@ -278,7 +276,7 @@ export class GameScene extends DirtyScene implements CenterListener {
this.onMapLoad(data); this.onMapLoad(data);
} }
this.load.spritesheet('layout_modes', 'resources/objects/layout_modes.png', {frameWidth: 32, frameHeight: 32}); this.load.spritesheet('layout_modes', 'resources/objects/layout_modes.png', { frameWidth: 32, frameHeight: 32 });
this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml'); this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
//eslint-disable-next-line @typescript-eslint/no-explicit-any //eslint-disable-next-line @typescript-eslint/no-explicit-any
(this.load as any).rexWebFont({ (this.load as any).rexWebFont({
@ -315,7 +313,7 @@ export class GameScene extends DirtyScene implements CenterListener {
for (const layer of this.mapFile.layers) { for (const layer of this.mapFile.layers) {
if (layer.type === 'objectgroup') { if (layer.type === 'objectgroup') {
for (const object of layer.objects) { for (const object of layer.objects) {
let objectsOfType: ITiledMapObject[]|undefined; let objectsOfType: ITiledMapObject[] | undefined;
if (!objects.has(object.type)) { if (!objects.has(object.type)) {
objectsOfType = new Array<ITiledMapObject>(); objectsOfType = new Array<ITiledMapObject>();
} else { } else {
@ -378,7 +376,7 @@ export class GameScene extends DirtyScene implements CenterListener {
} }
//hook initialisation //hook initialisation
init(initData : GameSceneInitInterface) { init(initData: GameSceneInitInterface) {
if (initData.initPosition !== undefined) { if (initData.initPosition !== undefined) {
this.initPosition = initData.initPosition; //todo: still used? this.initPosition = initData.initPosition; //todo: still used?
} }
@ -457,7 +455,7 @@ export class GameScene extends DirtyScene implements CenterListener {
this.Objects = new Array<Phaser.Physics.Arcade.Sprite>(); this.Objects = new Array<Phaser.Physics.Arcade.Sprite>();
//initialise list of other player //initialise list of other player
this.MapPlayers = this.physics.add.group({immovable: true}); this.MapPlayers = this.physics.add.group({ immovable: true });
//create input to move //create input to move
@ -723,16 +721,16 @@ export class GameScene extends DirtyScene implements CenterListener {
} }
private safeParseJSONstring(jsonString: string|undefined, propertyName: string) { private safeParseJSONstring(jsonString: string | undefined, propertyName: string) {
try { try {
return jsonString ? JSON.parse(jsonString) : {}; return jsonString ? JSON.parse(jsonString) : {};
} catch(e) { } catch (e) {
console.warn('Invalid JSON found in property "' + propertyName + '" of the map:' + jsonString, e); console.warn('Invalid JSON found in property "' + propertyName + '" of the map:' + jsonString, e);
return {} return {}
} }
} }
private triggerOnMapLayerPropertyChange(){ private triggerOnMapLayerPropertyChange() {
this.gameMap.onPropertyChange('exitSceneUrl', (newValue, oldValue) => { this.gameMap.onPropertyChange('exitSceneUrl', (newValue, oldValue) => {
if (newValue) this.onMapExit(newValue as string); if (newValue) this.onMapExit(newValue as string);
}); });
@ -743,22 +741,22 @@ export class GameScene extends DirtyScene implements CenterListener {
if (newValue === undefined) { if (newValue === undefined) {
layoutManager.removeActionButton('openWebsite', this.userInputManager); layoutManager.removeActionButton('openWebsite', this.userInputManager);
coWebsiteManager.closeCoWebsite(); coWebsiteManager.closeCoWebsite();
}else{ } else {
const openWebsiteFunction = () => { const openWebsiteFunction = () => {
coWebsiteManager.loadCoWebsite(newValue as string, this.MapUrlFile, allProps.get('openWebsiteAllowApi') as boolean | undefined, allProps.get('openWebsitePolicy') as string | undefined); coWebsiteManager.loadCoWebsite(newValue as string, this.MapUrlFile, allProps.get('openWebsiteAllowApi') as boolean | undefined, allProps.get('openWebsitePolicy') as string | undefined);
layoutManager.removeActionButton('openWebsite', this.userInputManager); layoutManager.removeActionButton('openWebsite', this.userInputManager);
}; };
const openWebsiteTriggerValue = allProps.get(TRIGGER_WEBSITE_PROPERTIES); const openWebsiteTriggerValue = allProps.get(TRIGGER_WEBSITE_PROPERTIES);
if(openWebsiteTriggerValue && openWebsiteTriggerValue === ON_ACTION_TRIGGER_BUTTON) { if (openWebsiteTriggerValue && openWebsiteTriggerValue === ON_ACTION_TRIGGER_BUTTON) {
let message = allProps.get(WEBSITE_MESSAGE_PROPERTIES); let message = allProps.get(WEBSITE_MESSAGE_PROPERTIES);
if(message === undefined){ if (message === undefined) {
message = 'Press SPACE or touch here to open web site'; message = 'Press SPACE or touch here to open web site';
} }
layoutManager.addActionButton('openWebsite', message.toString(), () => { layoutManager.addActionButton('openWebsite', message.toString(), () => {
openWebsiteFunction(); openWebsiteFunction();
}, this.userInputManager); }, this.userInputManager);
}else{ } else {
openWebsiteFunction(); openWebsiteFunction();
} }
} }
@ -767,12 +765,12 @@ export class GameScene extends DirtyScene implements CenterListener {
if (newValue === undefined) { if (newValue === undefined) {
layoutManager.removeActionButton('jitsiRoom', this.userInputManager); layoutManager.removeActionButton('jitsiRoom', this.userInputManager);
this.stopJitsi(); this.stopJitsi();
}else{ } else {
const openJitsiRoomFunction = () => { const openJitsiRoomFunction = () => {
const roomName = jitsiFactory.getRoomName(newValue.toString(), this.instance); const roomName = jitsiFactory.getRoomName(newValue.toString(), this.instance);
const jitsiUrl = allProps.get("jitsiUrl") as string|undefined; const jitsiUrl = allProps.get("jitsiUrl") as string | undefined;
if (JITSI_PRIVATE_MODE && !jitsiUrl) { if (JITSI_PRIVATE_MODE && !jitsiUrl) {
const adminTag = allProps.get("jitsiRoomAdminTag") as string|undefined; const adminTag = allProps.get("jitsiRoomAdminTag") as string | undefined;
this.connection?.emitQueryJitsiJwtMessage(roomName, adminTag); this.connection?.emitQueryJitsiJwtMessage(roomName, adminTag);
} else { } else {
@ -782,7 +780,7 @@ export class GameScene extends DirtyScene implements CenterListener {
} }
const jitsiTriggerValue = allProps.get(TRIGGER_JITSI_PROPERTIES); const jitsiTriggerValue = allProps.get(TRIGGER_JITSI_PROPERTIES);
if(jitsiTriggerValue && jitsiTriggerValue === ON_ACTION_TRIGGER_BUTTON) { if (jitsiTriggerValue && jitsiTriggerValue === ON_ACTION_TRIGGER_BUTTON) {
let message = allProps.get(JITSI_MESSAGE_PROPERTIES); let message = allProps.get(JITSI_MESSAGE_PROPERTIES);
if (message === undefined) { if (message === undefined) {
message = 'Press SPACE or touch here to enter Jitsi Meet room'; message = 'Press SPACE or touch here to enter Jitsi Meet room';
@ -790,7 +788,7 @@ export class GameScene extends DirtyScene implements CenterListener {
layoutManager.addActionButton('jitsiRoom', message.toString(), () => { layoutManager.addActionButton('jitsiRoom', message.toString(), () => {
openJitsiRoomFunction(); openJitsiRoomFunction();
}, this.userInputManager); }, this.userInputManager);
}else{ } else {
openJitsiRoomFunction(); openJitsiRoomFunction();
} }
} }
@ -803,8 +801,8 @@ export class GameScene extends DirtyScene implements CenterListener {
} }
}); });
this.gameMap.onPropertyChange('playAudio', (newValue, oldValue, allProps) => { this.gameMap.onPropertyChange('playAudio', (newValue, oldValue, allProps) => {
const volume = allProps.get(AUDIO_VOLUME_PROPERTY) as number|undefined; const volume = allProps.get(AUDIO_VOLUME_PROPERTY) as number | undefined;
const loop = allProps.get(AUDIO_LOOP_PROPERTY) as boolean|undefined; const loop = allProps.get(AUDIO_LOOP_PROPERTY) as boolean | undefined;
newValue === undefined ? audioManager.unloadAudio() : audioManager.playAudio(newValue, this.getMapDirUrl(), volume, loop); newValue === undefined ? audioManager.unloadAudio() : audioManager.playAudio(newValue, this.getMapDirUrl(), volume, loop);
}); });
// TODO: This legacy property should be removed at some point // TODO: This legacy property should be removed at some point
@ -826,9 +824,9 @@ export class GameScene extends DirtyScene implements CenterListener {
this.iframeSubscriptionList = []; this.iframeSubscriptionList = [];
this.iframeSubscriptionList.push(iframeListener.openPopupStream.subscribe((openPopupEvent) => { this.iframeSubscriptionList.push(iframeListener.openPopupStream.subscribe((openPopupEvent) => {
let objectLayerSquare : ITiledMapObject; let objectLayerSquare: ITiledMapObject;
const targetObjectData = this.getObjectLayerData(openPopupEvent.targetObject); const targetObjectData = this.getObjectLayerData(openPopupEvent.targetObject);
if (targetObjectData !== undefined){ if (targetObjectData !== undefined) {
objectLayerSquare = targetObjectData; objectLayerSquare = targetObjectData;
} else { } else {
console.error("Error while opening a popup. Cannot find an object on the map with name '" + openPopupEvent.targetObject + "'. The first parameter of WA.openPopup() must be the name of a rectangle object in your map."); console.error("Error while opening a popup. Cannot find an object on the map with name '" + openPopupEvent.targetObject + "'. The first parameter of WA.openPopup() must be the name of a rectangle object in your map.");
@ -846,10 +844,10 @@ ${escapedMessage}
id++; id++;
} }
html += '</div>'; html += '</div>';
const domElement = this.add.dom(objectLayerSquare.x , const domElement = this.add.dom(objectLayerSquare.x,
objectLayerSquare.y).createFromHTML(html); objectLayerSquare.y).createFromHTML(html);
const container : HTMLDivElement = domElement.getChildByID("container") as HTMLDivElement; const container: HTMLDivElement = domElement.getChildByID("container") as HTMLDivElement;
container.style.width = objectLayerSquare.width + "px"; container.style.width = objectLayerSquare.width + "px";
domElement.scale = 0; domElement.scale = 0;
domElement.setClassName('popUpElement'); domElement.setClassName('popUpElement');
@ -869,10 +867,10 @@ ${escapedMessage}
id++; id++;
} }
this.tweens.add({ this.tweens.add({
targets : domElement , targets: domElement,
scale : 1, scale: 1,
ease : "EaseOut", ease: "EaseOut",
duration : 400, duration: 400,
}); });
this.popUpElements.set(openPopupEvent.popupId, domElement); this.popUpElements.set(openPopupEvent.popupId, domElement);
@ -881,61 +879,58 @@ ${escapedMessage}
this.iframeSubscriptionList.push(iframeListener.closePopupStream.subscribe((closePopupEvent) => { this.iframeSubscriptionList.push(iframeListener.closePopupStream.subscribe((closePopupEvent) => {
const popUpElement = this.popUpElements.get(closePopupEvent.popupId); const popUpElement = this.popUpElements.get(closePopupEvent.popupId);
if (popUpElement === undefined) { if (popUpElement === undefined) {
console.error('Could not close popup with ID ', closePopupEvent.popupId,'. Maybe it has already been closed?'); console.error('Could not close popup with ID ', closePopupEvent.popupId, '. Maybe it has already been closed?');
} }
this.tweens.add({ this.tweens.add({
targets : popUpElement , targets: popUpElement,
scale : 0, scale: 0,
ease : "EaseOut", ease: "EaseOut",
duration : 400, duration: 400,
onComplete : () => { onComplete: () => {
popUpElement?.destroy(); popUpElement?.destroy();
this.popUpElements.delete(closePopupEvent.popupId); this.popUpElements.delete(closePopupEvent.popupId);
}, },
}); });
})); }));
this.iframeSubscriptionList.push(iframeListener.disablePlayerControlStream.subscribe(()=>{ this.iframeSubscriptionList.push(iframeListener.disablePlayerControlStream.subscribe(() => {
this.userInputManager.disableControls(); this.userInputManager.disableControls();
})); }));
this.iframeSubscriptionList.push(iframeListener.playSoundStream.subscribe((playSoundEvent)=> this.iframeSubscriptionList.push(iframeListener.playSoundStream.subscribe((playSoundEvent) => {
{
const url = new URL(playSoundEvent.url, this.MapUrlFile); const url = new URL(playSoundEvent.url, this.MapUrlFile);
soundManager.playSound(this.load,this.sound,url.toString(),playSoundEvent.config); soundManager.playSound(this.load, this.sound, url.toString(), playSoundEvent.config);
})) }))
this.iframeSubscriptionList.push(iframeListener.stopSoundStream.subscribe((stopSoundEvent)=> this.iframeSubscriptionList.push(iframeListener.stopSoundStream.subscribe((stopSoundEvent) => {
{
const url = new URL(stopSoundEvent.url, this.MapUrlFile); const url = new URL(stopSoundEvent.url, this.MapUrlFile);
soundManager.stopSound(this.sound,url.toString()); soundManager.stopSound(this.sound, url.toString());
})) }))
this.iframeSubscriptionList.push(iframeListener.loadSoundStream.subscribe((loadSoundEvent)=> this.iframeSubscriptionList.push(iframeListener.loadSoundStream.subscribe((loadSoundEvent) => {
{
const url = new URL(loadSoundEvent.url, this.MapUrlFile); const url = new URL(loadSoundEvent.url, this.MapUrlFile);
soundManager.loadSound(this.load,this.sound,url.toString()); soundManager.loadSound(this.load, this.sound, url.toString());
})) }))
this.iframeSubscriptionList.push(iframeListener.enablePlayerControlStream.subscribe(()=>{ this.iframeSubscriptionList.push(iframeListener.enablePlayerControlStream.subscribe(() => {
this.userInputManager.restoreControls(); this.userInputManager.restoreControls();
})); }));
this.iframeSubscriptionList.push(iframeListener.loadPageStream.subscribe((url:string)=>{ this.iframeSubscriptionList.push(iframeListener.loadPageStream.subscribe((url: string) => {
this.loadNextGame(url).then(()=>{ this.loadNextGame(url).then(() => {
this.events.once(EVENT_TYPE.POST_UPDATE,()=>{ this.events.once(EVENT_TYPE.POST_UPDATE, () => {
this.onMapExit(url); this.onMapExit(url);
}) })
}) })
})); }));
let scriptedBubbleSprite : Sprite; let scriptedBubbleSprite: Sprite;
this.iframeSubscriptionList.push(iframeListener.displayBubbleStream.subscribe(()=>{ this.iframeSubscriptionList.push(iframeListener.displayBubbleStream.subscribe(() => {
scriptedBubbleSprite = new Sprite(this,this.CurrentPlayer.x + 25,this.CurrentPlayer.y,'circleSprite-white'); scriptedBubbleSprite = new Sprite(this, this.CurrentPlayer.x + 25, this.CurrentPlayer.y, 'circleSprite-white');
scriptedBubbleSprite.setDisplayOrigin(48, 48); scriptedBubbleSprite.setDisplayOrigin(48, 48);
this.add.existing(scriptedBubbleSprite); this.add.existing(scriptedBubbleSprite);
})); }));
this.iframeSubscriptionList.push(iframeListener.removeBubbleStream.subscribe(()=>{ this.iframeSubscriptionList.push(iframeListener.removeBubbleStream.subscribe(() => {
scriptedBubbleSprite.destroy(); scriptedBubbleSprite.destroy();
})); }));
@ -948,9 +943,11 @@ ${escapedMessage}
private onMapExit(exitKey: string) { private onMapExit(exitKey: string) {
if (this.mapTransitioning) return; if (this.mapTransitioning) return;
this.mapTransitioning = true; this.mapTransitioning = true;
const {roomId, hash} = Room.getIdFromIdentifier(exitKey, this.MapUrlFile, this.instance); const { roomId, hash } = Room.getIdFromIdentifier(exitKey, this.MapUrlFile, this.instance);
if (!roomId) throw new Error('Could not find the room from its exit key: '+exitKey); if (!roomId) throw new Error('Could not find the room from its exit key: ' + exitKey);
urlManager.pushStartLayerNameToUrl(hash); urlManager.pushStartLayerNameToUrl(hash);
const menuScene: MenuScene = this.scene.get(MenuSceneName) as MenuScene
menuScene.reset()
if (roomId !== this.scene.key) { if (roomId !== this.scene.key) {
if (this.scene.get(roomId) === null) { if (this.scene.get(roomId) === null) {
console.error("next room not loaded", exitKey); console.error("next room not loaded", exitKey);
@ -992,7 +989,7 @@ ${escapedMessage}
mediaManager.hideGameOverlay(); mediaManager.hideGameOverlay();
for(const iframeEvents of this.iframeSubscriptionList){ for (const iframeEvents of this.iframeSubscriptionList) {
iframeEvents.unsubscribe(); iframeEvents.unsubscribe();
} }
} }
@ -1012,7 +1009,7 @@ ${escapedMessage}
private switchLayoutMode(): void { private switchLayoutMode(): void {
//if discussion is activated, this layout cannot be activated //if discussion is activated, this layout cannot be activated
if(mediaManager.activatedDiscussion){ if (mediaManager.activatedDiscussion) {
return; return;
} }
const mode = layoutManager.getLayoutMode(); const mode = layoutManager.getLayoutMode();
@ -1053,24 +1050,24 @@ ${escapedMessage}
private initPositionFromLayerName(layerName: string) { private initPositionFromLayerName(layerName: string) {
for (const layer of this.gameMap.layersIterator) { for (const layer of this.gameMap.layersIterator) {
if ((layerName === layer.name || layer.name.endsWith('/'+layerName)) && layer.type === 'tilelayer' && (layerName === defaultStartLayerName || this.isStartLayer(layer))) { if ((layerName === layer.name || layer.name.endsWith('/' + layerName)) && layer.type === 'tilelayer' && (layerName === defaultStartLayerName || this.isStartLayer(layer))) {
const startPosition = this.startUser(layer); const startPosition = this.startUser(layer);
this.startX = startPosition.x + this.mapFile.tilewidth/2; this.startX = startPosition.x + this.mapFile.tilewidth / 2;
this.startY = startPosition.y + this.mapFile.tileheight/2; this.startY = startPosition.y + this.mapFile.tileheight / 2;
} }
} }
} }
private getExitUrl(layer: ITiledMapLayer): string|undefined { private getExitUrl(layer: ITiledMapLayer): string | undefined {
return this.getProperty(layer, "exitUrl") as string|undefined; return this.getProperty(layer, "exitUrl") as string | undefined;
} }
/** /**
* @deprecated the map property exitSceneUrl is deprecated * @deprecated the map property exitSceneUrl is deprecated
*/ */
private getExitSceneUrl(layer: ITiledMapLayer): string|undefined { private getExitSceneUrl(layer: ITiledMapLayer): string | undefined {
return this.getProperty(layer, "exitSceneUrl") as string|undefined; return this.getProperty(layer, "exitSceneUrl") as string | undefined;
} }
private isStartLayer(layer: ITiledMapLayer): boolean { private isStartLayer(layer: ITiledMapLayer): boolean {
@ -1081,8 +1078,8 @@ ${escapedMessage}
return (this.getProperties(map, "script") as string[]).map((script) => (new URL(script, this.MapUrlFile)).toString()); return (this.getProperties(map, "script") as string[]).map((script) => (new URL(script, this.MapUrlFile)).toString());
} }
private getProperty(layer: ITiledMapLayer|ITiledMap, name: string): string|boolean|number|undefined { private getProperty(layer: ITiledMapLayer | ITiledMap, name: string): string | boolean | number | undefined {
const properties: ITiledMapLayerProperty[]|undefined = layer.properties; const properties: ITiledMapLayerProperty[] | undefined = layer.properties;
if (!properties) { if (!properties) {
return undefined; return undefined;
} }
@ -1093,8 +1090,8 @@ ${escapedMessage}
return obj.value; return obj.value;
} }
private getProperties(layer: ITiledMapLayer|ITiledMap, name: string): (string|number|boolean|undefined)[] { private getProperties(layer: ITiledMapLayer | ITiledMap, name: string): (string | number | boolean | undefined)[] {
const properties: ITiledMapLayerProperty[]|undefined = layer.properties; const properties: ITiledMapLayerProperty[] | undefined = layer.properties;
if (!properties) { if (!properties) {
return []; return [];
} }
@ -1103,29 +1100,29 @@ ${escapedMessage}
//todo: push that into the gameManager //todo: push that into the gameManager
private loadNextGame(exitSceneIdentifier: string): Promise<void> { private loadNextGame(exitSceneIdentifier: string): Promise<void> {
const {roomId, hash} = Room.getIdFromIdentifier(exitSceneIdentifier, this.MapUrlFile, this.instance); const { roomId, hash } = Room.getIdFromIdentifier(exitSceneIdentifier, this.MapUrlFile, this.instance);
const room = new Room(roomId); const room = new Room(roomId);
return gameManager.loadMap(room, this.scene).catch(() => {}); return gameManager.loadMap(room, this.scene).catch(() => { });
} }
private startUser(layer: ITiledMapTileLayer): PositionInterface { private startUser(layer: ITiledMapTileLayer): PositionInterface {
const tiles = layer.data; const tiles = layer.data;
if (typeof(tiles) === 'string') { if (typeof (tiles) === 'string') {
throw new Error('The content of a JSON map must be filled as a JSON array, not as a string'); throw new Error('The content of a JSON map must be filled as a JSON array, not as a string');
} }
const possibleStartPositions : PositionInterface[] = []; const possibleStartPositions: PositionInterface[] = [];
tiles.forEach((objectKey : number, key: number) => { tiles.forEach((objectKey: number, key: number) => {
if(objectKey === 0){ if (objectKey === 0) {
return; return;
} }
const y = Math.floor(key / layer.width); const y = Math.floor(key / layer.width);
const x = key % layer.width; const x = key % layer.width;
possibleStartPositions.push({x: x * this.mapFile.tilewidth, y: y * this.mapFile.tilewidth}); possibleStartPositions.push({ x: x * this.mapFile.tilewidth, y: y * this.mapFile.tilewidth });
}); });
// Get a value at random amongst allowed values // Get a value at random amongst allowed values
if (possibleStartPositions.length === 0) { if (possibleStartPositions.length === 0) {
console.warn('The start layer "'+layer.name+'" for this map is empty.'); console.warn('The start layer "' + layer.name + '" for this map is empty.');
return { return {
x: 0, x: 0,
y: 0 y: 0
@ -1137,12 +1134,12 @@ ${escapedMessage}
//todo: in a dedicated class/function? //todo: in a dedicated class/function?
initCamera() { initCamera() {
this.cameras.main.setBounds(0,0, this.Map.widthInPixels, this.Map.heightInPixels); this.cameras.main.setBounds(0, 0, this.Map.widthInPixels, this.Map.heightInPixels);
this.cameras.main.startFollow(this.CurrentPlayer, true); this.cameras.main.startFollow(this.CurrentPlayer, true);
this.updateCameraOffset(); this.updateCameraOffset();
} }
addLayer(Layer : Phaser.Tilemaps.TilemapLayer){ addLayer(Layer: Phaser.Tilemaps.TilemapLayer) {
this.Layers.push(Layer); this.Layers.push(Layer);
} }
@ -1152,7 +1149,7 @@ ${escapedMessage}
this.physics.add.collider(this.CurrentPlayer, Layer, (object1: GameObject, object2: GameObject) => { this.physics.add.collider(this.CurrentPlayer, Layer, (object1: GameObject, object2: GameObject) => {
//this.CurrentPlayer.say("Collision with layer : "+ (object2 as Tile).layer.name) //this.CurrentPlayer.say("Collision with layer : "+ (object2 as Tile).layer.name)
}); });
Layer.setCollisionByProperty({collides: true}); Layer.setCollisionByProperty({ collides: true });
if (DEBUG_MODE) { if (DEBUG_MODE) {
//debug code to see the collision hitbox of the object in the top layer //debug code to see the collision hitbox of the object in the top layer
Layer.renderDebug(this.add.graphics(), { Layer.renderDebug(this.add.graphics(), {
@ -1164,7 +1161,7 @@ ${escapedMessage}
}); });
} }
createCurrentPlayer(){ createCurrentPlayer() {
//TODO create animation moving between exit and start //TODO create animation moving between exit and start
const texturesPromise = lazyLoadPlayerCharacterTextures(this.load, this.characterLayers); const texturesPromise = lazyLoadPlayerCharacterTextures(this.load, this.characterLayers);
try { try {
@ -1189,8 +1186,8 @@ ${escapedMessage}
this.CurrentPlayer.on(requestEmoteEventName, (emoteKey: string) => { this.CurrentPlayer.on(requestEmoteEventName, (emoteKey: string) => {
this.connection?.emitEmoteEvent(emoteKey); this.connection?.emitEmoteEvent(emoteKey);
}) })
}catch (err){ } catch (err) {
if(err instanceof TextureError) { if (err instanceof TextureError) {
gameManager.leaveGame(this, SelectCharacterSceneName, new SelectCharacterScene()); gameManager.leaveGame(this, SelectCharacterSceneName, new SelectCharacterScene());
} }
throw err; throw err;
@ -1251,7 +1248,7 @@ ${escapedMessage}
} }
let shortestDistance: number = Infinity; let shortestDistance: number = Infinity;
let selectedItem: ActionableItem|null = null; let selectedItem: ActionableItem | null = null;
for (const item of this.actionableItems.values()) { for (const item of this.actionableItems.values()) {
const distance = item.actionableDistance(x, y); const distance = item.actionableDistance(x, y);
if (distance !== null && distance < shortestDistance) { if (distance !== null && distance < shortestDistance) {
@ -1285,7 +1282,7 @@ ${escapedMessage}
* @param time * @param time
* @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/ */
update(time: number, delta: number) : void { update(time: number, delta: number): void {
this.dirty = false; this.dirty = false;
mediaManager.updateScene(); mediaManager.updateScene();
this.currentTick = time; this.currentTick = time;
@ -1345,8 +1342,8 @@ ${escapedMessage}
const currentPlayerId = this.connection?.getUserId(); const currentPlayerId = this.connection?.getUserId();
this.removeAllRemotePlayers(); this.removeAllRemotePlayers();
// load map // load map
usersPosition.forEach((userPosition : MessageUserPositionInterface) => { usersPosition.forEach((userPosition: MessageUserPositionInterface) => {
if(userPosition.userId === currentPlayerId){ if (userPosition.userId === currentPlayerId) {
return; return;
} }
this.addPlayer(userPosition); this.addPlayer(userPosition);
@ -1356,16 +1353,16 @@ ${escapedMessage}
/** /**
* Called by the connexion when a new player arrives on a map * Called by the connexion when a new player arrives on a map
*/ */
public addPlayer(addPlayerData : AddPlayerInterface) : void { public addPlayer(addPlayerData: AddPlayerInterface): void {
this.pendingEvents.enqueue({ this.pendingEvents.enqueue({
type: "AddPlayerEvent", type: "AddPlayerEvent",
event: addPlayerData event: addPlayerData
}); });
} }
private doAddPlayer(addPlayerData : AddPlayerInterface): void { private doAddPlayer(addPlayerData: AddPlayerInterface): void {
//check if exist player, if exist, move position //check if exist player, if exist, move position
if(this.MapPlayersByKey.has(addPlayerData.userId)){ if (this.MapPlayersByKey.has(addPlayerData.userId)) {
this.updatePlayerPosition({ this.updatePlayerPosition({
userId: addPlayerData.userId, userId: addPlayerData.userId,
position: addPlayerData.position position: addPlayerData.position
@ -1427,10 +1424,10 @@ ${escapedMessage}
} }
private doUpdatePlayerPosition(message: MessageUserMovedInterface): void { private doUpdatePlayerPosition(message: MessageUserMovedInterface): void {
const player : RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId); const player: RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId);
if (player === undefined) { if (player === undefined) {
//throw new Error('Cannot find player with ID "' + message.userId +'"'); //throw new Error('Cannot find player with ID "' + message.userId +'"');
console.error('Cannot update position of player with ID "' + message.userId +'": player not found'); console.error('Cannot update position of player with ID "' + message.userId + '": player not found');
return; return;
} }
@ -1474,7 +1471,7 @@ ${escapedMessage}
doDeleteGroup(groupId: number): void { doDeleteGroup(groupId: number): void {
const group = this.groups.get(groupId); const group = this.groups.get(groupId);
if(!group){ if (!group) {
return; return;
} }
group.destroy(); group.destroy();
@ -1503,7 +1500,7 @@ ${escapedMessage}
bottom: camera.scrollY + camera.height, bottom: camera.scrollY + camera.height,
}); });
} }
private getObjectLayerData(objectName : string) : ITiledMapObject| undefined{ private getObjectLayerData(objectName: string): ITiledMapObject | undefined {
for (const layer of this.mapFile.layers) { for (const layer of this.mapFile.layers) {
if (layer.type === 'objectgroup' && layer.name === 'floorLayer') { if (layer.type === 'objectgroup' && layer.name === 'floorLayer') {
for (const object of layer.objects) { for (const object of layer.objects) {
@ -1537,7 +1534,7 @@ ${escapedMessage}
const game = HtmlUtils.querySelectorOrFail<HTMLCanvasElement>('#game canvas'); const game = HtmlUtils.querySelectorOrFail<HTMLCanvasElement>('#game canvas');
// Let's put this in Game coordinates by applying the zoom level: // Let's put this in Game coordinates by applying the zoom level:
this.cameras.main.setFollowOffset((xCenter - game.offsetWidth/2) * window.devicePixelRatio / this.scale.zoom , (yCenter - game.offsetHeight/2) * window.devicePixelRatio / this.scale.zoom); this.cameras.main.setFollowOffset((xCenter - game.offsetWidth / 2) * window.devicePixelRatio / this.scale.zoom, (yCenter - game.offsetHeight / 2) * window.devicePixelRatio / this.scale.zoom);
} }
public onCenterChange(): void { public onCenterChange(): void {
@ -1546,16 +1543,16 @@ ${escapedMessage}
public startJitsi(roomName: string, jwt?: string): void { public startJitsi(roomName: string, jwt?: string): void {
const allProps = this.gameMap.getCurrentProperties(); const allProps = this.gameMap.getCurrentProperties();
const jitsiConfig = this.safeParseJSONstring(allProps.get("jitsiConfig") as string|undefined, 'jitsiConfig'); const jitsiConfig = this.safeParseJSONstring(allProps.get("jitsiConfig") as string | undefined, 'jitsiConfig');
const jitsiInterfaceConfig = this.safeParseJSONstring(allProps.get("jitsiInterfaceConfig") as string|undefined, 'jitsiInterfaceConfig'); const jitsiInterfaceConfig = this.safeParseJSONstring(allProps.get("jitsiInterfaceConfig") as string | undefined, 'jitsiInterfaceConfig');
const jitsiUrl = allProps.get("jitsiUrl") as string|undefined; const jitsiUrl = allProps.get("jitsiUrl") as string | undefined;
jitsiFactory.start(roomName, this.playerName, jwt, jitsiConfig, jitsiInterfaceConfig, jitsiUrl); jitsiFactory.start(roomName, this.playerName, jwt, jitsiConfig, jitsiInterfaceConfig, jitsiUrl);
this.connection?.setSilent(true); this.connection?.setSilent(true);
mediaManager.hideGameOverlay(); mediaManager.hideGameOverlay();
//permit to stop jitsi when user close iframe //permit to stop jitsi when user close iframe
mediaManager.addTriggerCloseJitsiFrameButton('close-jisi',() => { mediaManager.addTriggerCloseJitsiFrameButton('close-jisi', () => {
this.stopJitsi(); this.stopJitsi();
}); });
} }
@ -1569,7 +1566,7 @@ ${escapedMessage}
} }
//todo: put this into an 'orchestrator' scene (EntryScene?) //todo: put this into an 'orchestrator' scene (EntryScene?)
private bannedUser(){ private bannedUser() {
this.cleanupClosingScene(); this.cleanupClosingScene();
this.userInputManager.disableControls(); this.userInputManager.disableControls();
this.scene.start(ErrorSceneName, { this.scene.start(ErrorSceneName, {
@ -1580,22 +1577,22 @@ ${escapedMessage}
} }
//todo: put this into an 'orchestrator' scene (EntryScene?) //todo: put this into an 'orchestrator' scene (EntryScene?)
private showWorldFullError(message: string|null): void { private showWorldFullError(message: string | null): void {
this.cleanupClosingScene(); this.cleanupClosingScene();
this.scene.stop(ReconnectingSceneName); this.scene.stop(ReconnectingSceneName);
this.scene.remove(ReconnectingSceneName); this.scene.remove(ReconnectingSceneName);
this.userInputManager.disableControls(); this.userInputManager.disableControls();
//FIX ME to use status code //FIX ME to use status code
if(message == undefined){ if (message == undefined) {
this.scene.start(ErrorSceneName, { this.scene.start(ErrorSceneName, {
title: 'Connection rejected', title: 'Connection rejected',
subTitle: 'The world you are trying to join is full. Try again later.', subTitle: 'The world you are trying to join is full. Try again later.',
message: 'If you want more information, you may contact us at: workadventure@thecodingmachine.com' message: 'If you want more information, you may contact us at: workadventure@thecodingmachine.com'
}); });
}else{ } else {
this.scene.start(ErrorSceneName, { this.scene.start(ErrorSceneName, {
title: 'Connection rejected', title: 'Connection rejected',
subTitle: 'You cannot join the World. Try again later. \n\r \n\r Error: '+message+'.', subTitle: 'You cannot join the World. Try again later. \n\r \n\r Error: ' + message + '.',
message: 'If you want more information, you may contact administrator or contact us at: workadventure@thecodingmachine.com' message: 'If you want more information, you may contact administrator or contact us at: workadventure@thecodingmachine.com'
}); });
} }

View File

@ -1,16 +1,20 @@
import {LoginScene, LoginSceneName} from "../Login/LoginScene"; import { Subscription } from 'rxjs';
import {SelectCharacterScene, SelectCharacterSceneName} from "../Login/SelectCharacterScene"; import { sendMenuClickedEvent } from '../../Api/Events/ui/MenuItemClickedEvent';
import {SelectCompanionScene, SelectCompanionSceneName} from "../Login/SelectCompanionScene"; import { registerMenuCommandStream } from '../../Api/Events/ui/MenuItemRegisterEvent';
import {gameManager} from "../Game/GameManager"; import { connectionManager } from "../../Connexion/ConnectionManager";
import {localUserStore} from "../../Connexion/LocalUserStore"; import { localUserStore } from "../../Connexion/LocalUserStore";
import {mediaManager} from "../../WebRtc/MediaManager"; import { worldFullWarningStream } from "../../Connexion/WorldFullWarningStream";
import {gameReportKey, gameReportRessource, ReportMenu} from "./ReportMenu"; import { videoConstraintStore } from "../../Stores/MediaStore";
import {connectionManager} from "../../Connexion/ConnectionManager"; import { menuIconVisible } from "../../Stores/MenuStore";
import {GameConnexionTypes} from "../../Url/UrlManager"; import { GameConnexionTypes } from "../../Url/UrlManager";
import {WarningContainer, warningContainerHtml, warningContainerKey} from "../Components/WarningContainer"; import { HtmlUtils } from '../../WebRtc/HtmlUtils';
import {worldFullWarningStream} from "../../Connexion/WorldFullWarningStream"; import { mediaManager } from "../../WebRtc/MediaManager";
import {menuIconVisible} from "../../Stores/MenuStore"; import { WarningContainer, warningContainerHtml, warningContainerKey } from "../Components/WarningContainer";
import {videoConstraintStore} from "../../Stores/MediaStore"; import { gameManager } from "../Game/GameManager";
import { LoginScene, LoginSceneName } from "../Login/LoginScene";
import { SelectCharacterScene, SelectCharacterSceneName } from "../Login/SelectCharacterScene";
import { SelectCompanionScene, SelectCompanionSceneName } from "../Login/SelectCompanionScene";
import { gameReportKey, gameReportRessource, ReportMenu } from "./ReportMenu";
export const MenuSceneName = 'MenuScene'; export const MenuSceneName = 'MenuScene';
const gameMenuKey = 'gameMenu'; const gameMenuKey = 'gameMenu';
@ -37,15 +41,38 @@ export class MenuScene extends Phaser.Scene {
private menuButton!: Phaser.GameObjects.DOMElement; private menuButton!: Phaser.GameObjects.DOMElement;
private warningContainer: WarningContainer | null = null; private warningContainer: WarningContainer | null = null;
private warningContainerTimeout: NodeJS.Timeout | null = null; private warningContainerTimeout: NodeJS.Timeout | null = null;
private subscriptions = new Subscription()
constructor() { constructor() {
super({key: MenuSceneName}); super({ key: MenuSceneName });
this.gameQualityValue = localUserStore.getGameQualityValue(); this.gameQualityValue = localUserStore.getGameQualityValue();
this.videoQualityValue = localUserStore.getVideoQualityValue(); this.videoQualityValue = localUserStore.getVideoQualityValue();
this.subscriptions.add(registerMenuCommandStream.subscribe(menuCommand => {
this.addMenuOption(menuCommand);
}))
} }
preload () { reset() {
const addedMenuItems = [...this.menuElement.node.querySelectorAll(".fromApi")];
for (let index = addedMenuItems.length - 1; index >= 0; index--) {
addedMenuItems[index].remove()
}
}
public addMenuOption(menuText: string) {
const wrappingSection = document.createElement("section")
const escapedHtml = HtmlUtils.escapeHtml(menuText);
wrappingSection.innerHTML = `<button class="fromApi" id="${escapedHtml}">${escapedHtml}</button>`
const menuItemContainer = this.menuElement.node.querySelector("#gameMenu main");
if (menuItemContainer) {
menuItemContainer.querySelector(`#${escapedHtml}.fromApi`)?.remove()
menuItemContainer.insertBefore(wrappingSection, menuItemContainer.querySelector("#socialLinks"))
}
}
preload() {
this.load.html(gameMenuKey, 'resources/html/gameMenu.html'); this.load.html(gameMenuKey, 'resources/html/gameMenu.html');
this.load.html(gameMenuIconKey, 'resources/html/gameMenuIcon.html'); this.load.html(gameMenuIconKey, 'resources/html/gameMenuIcon.html');
this.load.html(gameSettingsMenuKey, 'resources/html/gameQualityMenu.html'); this.load.html(gameSettingsMenuKey, 'resources/html/gameQualityMenu.html');
@ -68,11 +95,11 @@ export class MenuScene extends Phaser.Scene {
this.gameShareElement = this.add.dom(middleX, -400).createFromCache(gameShare); this.gameShareElement = this.add.dom(middleX, -400).createFromCache(gameShare);
MenuScene.revealMenusAfterInit(this.gameShareElement, gameShare); MenuScene.revealMenusAfterInit(this.gameShareElement, gameShare);
this.gameShareElement.addListener('click'); this.gameShareElement.addListener('click');
this.gameShareElement.on('click', (event:MouseEvent) => { this.gameShareElement.on('click', (event: MouseEvent) => {
event.preventDefault(); event.preventDefault();
if((event?.target as HTMLInputElement).id === 'gameShareFormSubmit') { if ((event?.target as HTMLInputElement).id === 'gameShareFormSubmit') {
this.copyLink(); this.copyLink();
}else if((event?.target as HTMLInputElement).id === 'gameShareFormCancel') { } else if ((event?.target as HTMLInputElement).id === 'gameShareFormCancel') {
this.closeGameShare(); this.closeGameShare();
} }
}); });
@ -179,28 +206,28 @@ export class MenuScene extends Phaser.Scene {
this.settingsMenuOpened = true; this.settingsMenuOpened = true;
const gameQualitySelect = this.gameQualityMenuElement.getChildByID('select-game-quality') as HTMLInputElement; const gameQualitySelect = this.gameQualityMenuElement.getChildByID('select-game-quality') as HTMLInputElement;
gameQualitySelect.value = ''+this.gameQualityValue; gameQualitySelect.value = '' + this.gameQualityValue;
const videoQualitySelect = this.gameQualityMenuElement.getChildByID('select-video-quality') as HTMLInputElement; const videoQualitySelect = this.gameQualityMenuElement.getChildByID('select-video-quality') as HTMLInputElement;
videoQualitySelect.value = ''+this.videoQualityValue; videoQualitySelect.value = '' + this.videoQualityValue;
this.gameQualityMenuElement.addListener('click'); this.gameQualityMenuElement.addListener('click');
this.gameQualityMenuElement.on('click', (event:MouseEvent) => { this.gameQualityMenuElement.on('click', (event: MouseEvent) => {
event.preventDefault(); event.preventDefault();
if ((event?.target as HTMLInputElement).id === 'gameQualityFormSubmit') { if ((event?.target as HTMLInputElement).id === 'gameQualityFormSubmit') {
const gameQualitySelect = this.gameQualityMenuElement.getChildByID('select-game-quality') as HTMLInputElement; const gameQualitySelect = this.gameQualityMenuElement.getChildByID('select-game-quality') as HTMLInputElement;
const videoQualitySelect = this.gameQualityMenuElement.getChildByID('select-video-quality') as HTMLInputElement; const videoQualitySelect = this.gameQualityMenuElement.getChildByID('select-video-quality') as HTMLInputElement;
this.saveSetting(parseInt(gameQualitySelect.value), parseInt(videoQualitySelect.value)); this.saveSetting(parseInt(gameQualitySelect.value), parseInt(videoQualitySelect.value));
} else if((event?.target as HTMLInputElement).id === 'gameQualityFormCancel') { } else if ((event?.target as HTMLInputElement).id === 'gameQualityFormCancel') {
this.closeGameQualityMenu(); this.closeGameQualityMenu();
} }
}); });
let middleY = this.scale.height / 2 - 392/2; let middleY = this.scale.height / 2 - 392 / 2;
if(middleY < 0){ if (middleY < 0) {
middleY = 0; middleY = 0;
} }
let middleX = this.scale.width / 2 - 457/2; let middleX = this.scale.width / 2 - 457 / 2;
if(middleX < 0){ if (middleX < 0) {
middleX = 0; middleX = 0;
} }
this.tweens.add({ this.tweens.add({
@ -226,7 +253,7 @@ export class MenuScene extends Phaser.Scene {
} }
private openGameShare(): void{ private openGameShare(): void {
if (this.gameShareOpened) { if (this.gameShareOpened) {
this.closeGameShare(); this.closeGameShare();
return; return;
@ -240,11 +267,11 @@ export class MenuScene extends Phaser.Scene {
this.gameShareOpened = true; this.gameShareOpened = true;
let middleY = this.scale.height / 2 - 85; let middleY = this.scale.height / 2 - 85;
if(middleY < 0){ if (middleY < 0) {
middleY = 0; middleY = 0;
} }
let middleX = this.scale.width / 2 - 200; let middleX = this.scale.width / 2 - 200;
if(middleX < 0){ if (middleX < 0) {
middleX = 0; middleX = 0;
} }
this.tweens.add({ this.tweens.add({
@ -256,7 +283,7 @@ export class MenuScene extends Phaser.Scene {
}); });
} }
private closeGameShare(): void{ private closeGameShare(): void {
const gameShareInfo = this.gameShareElement.getChildByID('gameShareInfo') as HTMLParagraphElement; const gameShareInfo = this.gameShareElement.getChildByID('gameShareInfo') as HTMLParagraphElement;
gameShareInfo.innerText = ''; gameShareInfo.innerText = '';
gameShareInfo.style.display = 'none'; gameShareInfo.style.display = 'none';
@ -269,12 +296,18 @@ export class MenuScene extends Phaser.Scene {
}); });
} }
private onMenuClick(event:MouseEvent) { private onMenuClick(event: MouseEvent) {
if((event?.target as HTMLInputElement).classList.contains('not-button')){ const htmlMenuItem = (event?.target as HTMLInputElement);
if (htmlMenuItem.classList.contains('not-button')) {
return; return;
} }
event.preventDefault(); event.preventDefault();
if (htmlMenuItem.classList.contains("fromApi")) {
sendMenuClickedEvent(htmlMenuItem.id)
return
}
switch ((event?.target as HTMLInputElement).id) { switch ((event?.target as HTMLInputElement).id) {
case 'changeNameButton': case 'changeNameButton':
this.closeSideMenu(); this.closeSideMenu();
@ -316,7 +349,7 @@ export class MenuScene extends Phaser.Scene {
gameShareInfo.style.display = 'block'; gameShareInfo.style.display = 'block';
} }
private saveSetting(valueGame: number, valueVideo: number){ private saveSetting(valueGame: number, valueVideo: number) {
if (valueGame !== this.gameQualityValue) { if (valueGame !== this.gameQualityValue) {
this.gameQualityValue = valueGame; this.gameQualityValue = valueGame;
localUserStore.setGameQualityValue(valueGame); localUserStore.setGameQualityValue(valueGame);
@ -337,7 +370,7 @@ export class MenuScene extends Phaser.Scene {
window.open(sparkHost, '_blank'); window.open(sparkHost, '_blank');
} }
private closeAll(){ private closeAll() {
this.closeGameQualityMenu(); this.closeGameQualityMenu();
this.closeGameShare(); this.closeGameShare();
this.gameReportElement.close(); this.gameReportElement.close();