Reverting changes regarding single quotes

This commit is contained in:
David Négrier 2021-07-23 14:59:56 +02:00
parent a146065cc6
commit 3d5c222957
6 changed files with 401 additions and 401 deletions

View File

@ -1,29 +1,29 @@
import type { GameStateEvent } from './GameStateEvent'; import type { GameStateEvent } from "./GameStateEvent";
import type { ButtonClickedEvent } from './ButtonClickedEvent'; import type { ButtonClickedEvent } from "./ButtonClickedEvent";
import type { ChatEvent } from './ChatEvent'; import type { ChatEvent } from "./ChatEvent";
import type { ClosePopupEvent } from './ClosePopupEvent'; 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 { 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 { UserInputChatEvent } from './UserInputChatEvent'; import type { UserInputChatEvent } from "./UserInputChatEvent";
import type { DataLayerEvent } from './DataLayerEvent'; import type { DataLayerEvent } from "./DataLayerEvent";
import type { LayerEvent } from './LayerEvent'; import type { LayerEvent } from "./LayerEvent";
import type { SetPropertyEvent } from './setPropertyEvent'; import type { SetPropertyEvent } from "./setPropertyEvent";
import type { LoadSoundEvent } from './LoadSoundEvent'; import type { LoadSoundEvent } from "./LoadSoundEvent";
import type { PlaySoundEvent } from './PlaySoundEvent'; import type { PlaySoundEvent } from "./PlaySoundEvent";
import type { MenuItemClickedEvent } from './ui/MenuItemClickedEvent'; import type { MenuItemClickedEvent } from "./ui/MenuItemClickedEvent";
import type { MenuItemRegisterEvent } from './ui/MenuItemRegisterEvent'; import type { MenuItemRegisterEvent } from "./ui/MenuItemRegisterEvent";
import type { HasPlayerMovedEvent } from './HasPlayerMovedEvent'; import type { HasPlayerMovedEvent } from "./HasPlayerMovedEvent";
import type { SetTilesEvent } from './SetTilesEvent'; import type { SetTilesEvent } from "./SetTilesEvent";
import type { import type {
MessageReferenceEvent, MessageReferenceEvent,
removeTriggerMessage, removeTriggerMessage,
triggerMessage, triggerMessage,
TriggerMessageEvent, TriggerMessageEvent,
} from './ui/TriggerMessageEvent'; } from "./ui/TriggerMessageEvent";
export interface TypedMessageEvent<T> extends MessageEvent { export interface TypedMessageEvent<T> extends MessageEvent {
data: T; data: T;
@ -67,7 +67,7 @@ export interface IframeEvent<T extends keyof IframeEventMap> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isIframeEventWrapper = (event: any): event is IframeEvent<keyof IframeEventMap> => export const isIframeEventWrapper = (event: any): event is IframeEvent<keyof IframeEventMap> =>
typeof event.type === 'string'; typeof event.type === "string";
export interface IframeResponseEventMap { export interface IframeResponseEventMap {
userInputChat: UserInputChatEvent; userInputChat: UserInputChatEvent;
@ -87,7 +87,7 @@ export interface IframeResponseEvent<T extends keyof IframeResponseEventMap> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isIframeResponseEventWrapper = (event: { export const isIframeResponseEventWrapper = (event: {
type?: string; type?: string;
}): event is IframeResponseEvent<keyof IframeResponseEventMap> => typeof event.type === 'string'; }): event is IframeResponseEvent<keyof IframeResponseEventMap> => typeof event.type === "string";
/** /**
* List event types sent from an iFrame to WorkAdventure that expect a unique answer from WorkAdventure along the type for the answer from WorkAdventure to the iFrame * List event types sent from an iFrame to WorkAdventure that expect a unique answer from WorkAdventure along the type for the answer from WorkAdventure to the iFrame
@ -111,7 +111,7 @@ export type IframeQueryMap = {
export interface IframeQuery<T extends keyof IframeQueryMap> { export interface IframeQuery<T extends keyof IframeQueryMap> {
type: T; type: T;
data: IframeQueryMap[T]['query']; data: IframeQueryMap[T]["query"];
} }
export interface IframeQueryWrapper<T extends keyof IframeQueryMap> { export interface IframeQueryWrapper<T extends keyof IframeQueryMap> {
@ -120,22 +120,22 @@ export interface IframeQueryWrapper<T extends keyof IframeQueryMap> {
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isIframeQuery = (event: any): event is IframeQuery<keyof IframeQueryMap> => typeof event.type === 'string'; export const isIframeQuery = (event: any): event is IframeQuery<keyof IframeQueryMap> => typeof event.type === "string";
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isIframeQueryWrapper = (event: any): event is IframeQueryWrapper<keyof IframeQueryMap> => export const isIframeQueryWrapper = (event: any): event is IframeQueryWrapper<keyof IframeQueryMap> =>
typeof event.id === 'number' && isIframeQuery(event.query); typeof event.id === "number" && isIframeQuery(event.query);
export interface IframeAnswerEvent<T extends keyof IframeQueryMap> { export interface IframeAnswerEvent<T extends keyof IframeQueryMap> {
id: number; id: number;
type: T; type: T;
data: IframeQueryMap[T]['answer']; data: IframeQueryMap[T]["answer"];
} }
export const isIframeAnswerEvent = (event: { export const isIframeAnswerEvent = (event: {
type?: string; type?: string;
id?: number; id?: number;
}): event is IframeAnswerEvent<keyof IframeQueryMap> => typeof event.type === 'string' && typeof event.id === 'number'; }): event is IframeAnswerEvent<keyof IframeQueryMap> => typeof event.type === "string" && typeof event.id === "number";
export interface IframeErrorAnswerEvent { export interface IframeErrorAnswerEvent {
id: number; id: number;
@ -148,4 +148,4 @@ export const isIframeErrorAnswerEvent = (event: {
id?: number; id?: number;
error?: string; error?: string;
}): event is IframeErrorAnswerEvent => }): event is IframeErrorAnswerEvent =>
typeof event.type === 'string' && typeof event.id === 'number' && typeof event.error === 'string'; typeof event.type === "string" && typeof event.id === "number" && typeof event.error === "string";

View File

@ -1,15 +1,15 @@
import { Subject } from 'rxjs'; import { Subject } from "rxjs";
import type * as tg from 'generic-type-guard'; import type * as tg from "generic-type-guard";
import { ChatEvent, isChatEvent } from './Events/ChatEvent'; import { ChatEvent, isChatEvent } from "./Events/ChatEvent";
import { HtmlUtils } from '../WebRtc/HtmlUtils'; import { HtmlUtils } from "../WebRtc/HtmlUtils";
import type { EnterLeaveEvent } from './Events/EnterLeaveEvent'; import type { EnterLeaveEvent } from "./Events/EnterLeaveEvent";
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 type { ButtonClickedEvent } from "./Events/ButtonClickedEvent";
import { ClosePopupEvent, isClosePopupEvent } from './Events/ClosePopupEvent'; import { ClosePopupEvent, isClosePopupEvent } from "./Events/ClosePopupEvent";
import { scriptUtils } from './ScriptUtils'; import { scriptUtils } from "./ScriptUtils";
import { GoToPageEvent, isGoToPageEvent } from './Events/GoToPageEvent'; import { GoToPageEvent, isGoToPageEvent } from "./Events/GoToPageEvent";
import { isOpenCoWebsite, OpenCoWebSiteEvent } from './Events/OpenCoWebSiteEvent'; import { isOpenCoWebsite, OpenCoWebSiteEvent } from "./Events/OpenCoWebSiteEvent";
import { import {
IframeErrorAnswerEvent, IframeErrorAnswerEvent,
IframeEvent, IframeEvent,
@ -21,24 +21,24 @@ import {
isIframeEventWrapper, isIframeEventWrapper,
isIframeQueryWrapper, isIframeQueryWrapper,
TypedMessageEvent, TypedMessageEvent,
} from './Events/IframeEvent'; } from "./Events/IframeEvent";
import type { UserInputChatEvent } from './Events/UserInputChatEvent'; import type { UserInputChatEvent } from "./Events/UserInputChatEvent";
import { isPlaySoundEvent, PlaySoundEvent } from './Events/PlaySoundEvent'; import { isPlaySoundEvent, PlaySoundEvent } from "./Events/PlaySoundEvent";
import { isStopSoundEvent, StopSoundEvent } from './Events/StopSoundEvent'; import { isStopSoundEvent, StopSoundEvent } from "./Events/StopSoundEvent";
import { isLoadSoundEvent, LoadSoundEvent } from './Events/LoadSoundEvent'; import { isLoadSoundEvent, LoadSoundEvent } from "./Events/LoadSoundEvent";
import { isSetPropertyEvent, SetPropertyEvent } from './Events/setPropertyEvent'; import { isSetPropertyEvent, SetPropertyEvent } from "./Events/setPropertyEvent";
import { isLayerEvent, LayerEvent } from './Events/LayerEvent'; import { isLayerEvent, LayerEvent } from "./Events/LayerEvent";
import { isMenuItemRegisterEvent } from './Events/ui/MenuItemRegisterEvent'; import { isMenuItemRegisterEvent } from "./Events/ui/MenuItemRegisterEvent";
import type { DataLayerEvent } from './Events/DataLayerEvent'; import type { DataLayerEvent } from "./Events/DataLayerEvent";
import type { GameStateEvent } from './Events/GameStateEvent'; import type { GameStateEvent } from "./Events/GameStateEvent";
import type { HasPlayerMovedEvent } from './Events/HasPlayerMovedEvent'; import type { HasPlayerMovedEvent } from "./Events/HasPlayerMovedEvent";
import { isLoadPageEvent } from './Events/LoadPageEvent'; import { isLoadPageEvent } from "./Events/LoadPageEvent";
import { handleMenuItemRegistrationEvent, isMenuItemRegisterIframeEvent } from './Events/ui/MenuItemRegisterEvent'; import { handleMenuItemRegistrationEvent, isMenuItemRegisterIframeEvent } from "./Events/ui/MenuItemRegisterEvent";
import { SetTilesEvent, isSetTilesEvent } from './Events/SetTilesEvent'; import { SetTilesEvent, isSetTilesEvent } from "./Events/SetTilesEvent";
type AnswererCallback<T extends keyof IframeQueryMap> = ( type AnswererCallback<T extends keyof IframeQueryMap> = (
query: IframeQueryMap[T]['query'] query: IframeQueryMap[T]["query"]
) => IframeQueryMap[T]['answer'] | Promise<IframeQueryMap[T]['answer']>; ) => IframeQueryMap[T]["answer"] | Promise<IframeQueryMap[T]["answer"]>;
/** /**
* 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.
@ -122,7 +122,7 @@ class IframeListener {
init() { init() {
window.addEventListener( window.addEventListener(
'message', "message",
<T extends keyof IframeEventMap, U extends keyof IframeQueryMap>( <T extends keyof IframeEventMap, U extends keyof IframeQueryMap>(
message: TypedMessageEvent<IframeEvent<T | U>> message: TypedMessageEvent<IframeEvent<T | U>>
) => { ) => {
@ -144,10 +144,10 @@ class IframeListener {
if (foundSrc === undefined || iframe === undefined) { if (foundSrc === undefined || iframe === undefined) {
if (isIframeEventWrapper(payload)) { if (isIframeEventWrapper(payload)) {
console.warn( console.warn(
'It seems an iFrame is trying to communicate with WorkAdventure but was not explicitly granted the permission to do so. ' + "It seems an iFrame is trying to communicate with WorkAdventure but was not explicitly granted the permission to do so. " +
'If you are looking to use the WorkAdventure Scripting API inside an iFrame, you should allow the ' + "If you are looking to use the WorkAdventure Scripting API inside an iFrame, you should allow the " +
'iFrame to communicate with WorkAdventure by using the "openWebsiteAllowApi" property in your map (or passing "true" as a second' + 'iFrame to communicate with WorkAdventure by using the "openWebsiteAllowApi" property in your map (or passing "true" as a second' +
'parameter to WA.nav.openCoWebSite())' "parameter to WA.nav.openCoWebSite())"
); );
} }
return; return;
@ -172,7 +172,7 @@ class IframeListener {
type: query.type, type: query.type,
error: errorMsg, error: errorMsg,
} as IframeErrorAnswerEvent, } as IframeErrorAnswerEvent,
'*' "*"
); );
return; return;
} }
@ -185,11 +185,11 @@ class IframeListener {
type: query.type, type: query.type,
data: value, data: value,
}, },
'*' "*"
); );
}) })
.catch((reason) => { .catch((reason) => {
console.error('An error occurred while responding to an iFrame query.', reason); console.error("An error occurred while responding to an iFrame query.", reason);
let reasonMsg: string; let reasonMsg: string;
if (reason instanceof Error) { if (reason instanceof Error) {
reasonMsg = reason.message; reasonMsg = reason.message;
@ -203,54 +203,54 @@ class IframeListener {
type: query.type, type: query.type,
error: reasonMsg, error: reasonMsg,
} as IframeErrorAnswerEvent, } as IframeErrorAnswerEvent,
'*' "*"
); );
}); });
} else if (isIframeEventWrapper(payload)) { } else if (isIframeEventWrapper(payload)) {
if (payload.type === 'showLayer' && isLayerEvent(payload.data)) { if (payload.type === "showLayer" && isLayerEvent(payload.data)) {
this._showLayerStream.next(payload.data); this._showLayerStream.next(payload.data);
} else if (payload.type === 'hideLayer' && isLayerEvent(payload.data)) { } else if (payload.type === "hideLayer" && isLayerEvent(payload.data)) {
this._hideLayerStream.next(payload.data); this._hideLayerStream.next(payload.data);
} else if (payload.type === 'setProperty' && isSetPropertyEvent(payload.data)) { } else if (payload.type === "setProperty" && isSetPropertyEvent(payload.data)) {
this._setPropertyStream.next(payload.data); this._setPropertyStream.next(payload.data);
} else if (payload.type === 'chat' && isChatEvent(payload.data)) { } else if (payload.type === "chat" && isChatEvent(payload.data)) {
this._chatStream.next(payload.data); this._chatStream.next(payload.data);
} else if (payload.type === 'openPopup' && isOpenPopupEvent(payload.data)) { } else if (payload.type === "openPopup" && isOpenPopupEvent(payload.data)) {
this._openPopupStream.next(payload.data); this._openPopupStream.next(payload.data);
} else if (payload.type === 'closePopup' && isClosePopupEvent(payload.data)) { } else if (payload.type === "closePopup" && isClosePopupEvent(payload.data)) {
this._closePopupStream.next(payload.data); this._closePopupStream.next(payload.data);
} else if (payload.type === 'openTab' && isOpenTabEvent(payload.data)) { } else if (payload.type === "openTab" && isOpenTabEvent(payload.data)) {
scriptUtils.openTab(payload.data.url); scriptUtils.openTab(payload.data.url);
} else if (payload.type === 'goToPage' && isGoToPageEvent(payload.data)) { } else if (payload.type === "goToPage" && isGoToPageEvent(payload.data)) {
scriptUtils.goToPage(payload.data.url); scriptUtils.goToPage(payload.data.url);
} 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 (payload.type === 'playSound' && isPlaySoundEvent(payload.data)) { } else if (payload.type === "playSound" && isPlaySoundEvent(payload.data)) {
this._playSoundStream.next(payload.data); this._playSoundStream.next(payload.data);
} else if (payload.type === 'stopSound' && isStopSoundEvent(payload.data)) { } else if (payload.type === "stopSound" && isStopSoundEvent(payload.data)) {
this._stopSoundStream.next(payload.data); this._stopSoundStream.next(payload.data);
} else if (payload.type === 'loadSound' && isLoadSoundEvent(payload.data)) { } else if (payload.type === "loadSound" && isLoadSoundEvent(payload.data)) {
this._loadSoundStream.next(payload.data); this._loadSoundStream.next(payload.data);
} else if (payload.type === 'openCoWebSite' && isOpenCoWebsite(payload.data)) { } else if (payload.type === "openCoWebSite" && isOpenCoWebsite(payload.data)) {
scriptUtils.openCoWebsite( scriptUtils.openCoWebsite(
payload.data.url, payload.data.url,
foundSrc, foundSrc,
payload.data.allowApi, payload.data.allowApi,
payload.data.allowPolicy payload.data.allowPolicy
); );
} else if (payload.type === 'closeCoWebSite') { } else if (payload.type === "closeCoWebSite") {
scriptUtils.closeCoWebSite(); scriptUtils.closeCoWebSite();
} else if (payload.type === 'disablePlayerControls') { } else if (payload.type === "disablePlayerControls") {
this._disablePlayerControlStream.next(); this._disablePlayerControlStream.next();
} else if (payload.type === 'restorePlayerControls') { } else if (payload.type === "restorePlayerControls") {
this._enablePlayerControlStream.next(); this._enablePlayerControlStream.next();
} else if (payload.type === 'displayBubble') { } else if (payload.type === "displayBubble") {
this._displayBubbleStream.next(); this._displayBubbleStream.next();
} else if (payload.type === 'removeBubble') { } else if (payload.type === "removeBubble") {
this._removeBubbleStream.next(); this._removeBubbleStream.next();
} else if (payload.type == 'onPlayerMove') { } else if (payload.type == "onPlayerMove") {
this.sendPlayerMove = true; this.sendPlayerMove = true;
} else if (payload.type == 'getDataLayer') { } else if (payload.type == "getDataLayer") {
this._dataLayerChangeStream.next(); this._dataLayerChangeStream.next();
} else if (isMenuItemRegisterIframeEvent(payload)) { } else if (isMenuItemRegisterIframeEvent(payload)) {
const data = payload.data.menutItem; const data = payload.data.menutItem;
@ -259,7 +259,7 @@ class IframeListener {
this._unregisterMenuCommandStream.next(data); this._unregisterMenuCommandStream.next(data);
}); });
handleMenuItemRegistrationEvent(payload.data); handleMenuItemRegistrationEvent(payload.data);
} else if (payload.type == 'setTiles' && isSetTilesEvent(payload.data)) { } else if (payload.type == "setTiles" && isSetTilesEvent(payload.data)) {
this._setTilesStream.next(payload.data); this._setTilesStream.next(payload.data);
} }
} }
@ -270,7 +270,7 @@ class IframeListener {
sendDataLayerEvent(dataLayerEvent: DataLayerEvent) { sendDataLayerEvent(dataLayerEvent: DataLayerEvent) {
this.postMessage({ this.postMessage({
type: 'dataLayer', type: "dataLayer",
data: dataLayerEvent, data: dataLayerEvent,
}); });
} }
@ -291,18 +291,18 @@ class IframeListener {
} }
registerScript(scriptUrl: string): void { registerScript(scriptUrl: string): void {
console.log('Loading map related script at ', scriptUrl); console.log("Loading map related script at ", scriptUrl);
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') { if (!process.env.NODE_ENV || process.env.NODE_ENV === "development") {
// Using external iframe mode ( // Using external iframe mode (
const iframe = document.createElement('iframe'); const iframe = document.createElement("iframe");
iframe.id = IframeListener.getIFrameId(scriptUrl); iframe.id = IframeListener.getIFrameId(scriptUrl);
iframe.style.display = 'none'; iframe.style.display = "none";
iframe.src = '/iframe.html?script=' + encodeURIComponent(scriptUrl); iframe.src = "/iframe.html?script=" + encodeURIComponent(scriptUrl);
// We are putting a sandbox on this script because it will run in the same domain as the main website. // We are putting a sandbox on this script because it will run in the same domain as the main website.
iframe.sandbox.add('allow-scripts'); iframe.sandbox.add("allow-scripts");
iframe.sandbox.add('allow-top-navigation-by-user-activation'); iframe.sandbox.add("allow-top-navigation-by-user-activation");
document.body.prepend(iframe); document.body.prepend(iframe);
@ -310,31 +310,31 @@ class IframeListener {
this.registerIframe(iframe); this.registerIframe(iframe);
} else { } else {
// production code // production code
const iframe = document.createElement('iframe'); const iframe = document.createElement("iframe");
iframe.id = IframeListener.getIFrameId(scriptUrl); iframe.id = IframeListener.getIFrameId(scriptUrl);
iframe.style.display = 'none'; iframe.style.display = "none";
// We are putting a sandbox on this script because it will run in the same domain as the main website. // We are putting a sandbox on this script because it will run in the same domain as the main website.
iframe.sandbox.add('allow-scripts'); iframe.sandbox.add("allow-scripts");
iframe.sandbox.add('allow-top-navigation-by-user-activation'); iframe.sandbox.add("allow-top-navigation-by-user-activation");
//iframe.src = "data:text/html;charset=utf-8," + escape(html); //iframe.src = "data:text/html;charset=utf-8," + escape(html);
iframe.srcdoc = iframe.srcdoc =
'<!doctype html>\n' + "<!doctype html>\n" +
'\n' + "\n" +
'<html lang="en">\n' + '<html lang="en">\n' +
'<head>\n' + "<head>\n" +
'<script src="' + '<script src="' +
window.location.protocol + window.location.protocol +
'//' + "//" +
window.location.host + window.location.host +
'/iframe_api.js" ></script>\n' + '/iframe_api.js" ></script>\n' +
'<script src="' + '<script src="' +
scriptUrl + scriptUrl +
'" ></script>\n' + '" ></script>\n' +
'<title></title>\n' + "<title></title>\n" +
'</head>\n' + "</head>\n" +
'</html>\n'; "</html>\n";
document.body.prepend(iframe); document.body.prepend(iframe);
@ -353,7 +353,7 @@ class IframeListener {
} }
private static getIFrameId(scriptUrl: string): string { private static getIFrameId(scriptUrl: string): string {
return 'script' + btoa(scriptUrl); return "script" + btoa(scriptUrl);
} }
unregisterScript(scriptUrl: string): void { unregisterScript(scriptUrl: string): void {
@ -370,7 +370,7 @@ class IframeListener {
sendUserInputChat(message: string) { sendUserInputChat(message: string) {
this.postMessage({ this.postMessage({
type: 'userInputChat', type: "userInputChat",
data: { data: {
message: message, message: message,
} as UserInputChatEvent, } as UserInputChatEvent,
@ -379,7 +379,7 @@ class IframeListener {
sendEnterEvent(name: string) { sendEnterEvent(name: string) {
this.postMessage({ this.postMessage({
type: 'enterEvent', type: "enterEvent",
data: { data: {
name: name, name: name,
} as EnterLeaveEvent, } as EnterLeaveEvent,
@ -388,7 +388,7 @@ class IframeListener {
sendLeaveEvent(name: string) { sendLeaveEvent(name: string) {
this.postMessage({ this.postMessage({
type: 'leaveEvent', type: "leaveEvent",
data: { data: {
name: name, name: name,
} as EnterLeaveEvent, } as EnterLeaveEvent,
@ -398,7 +398,7 @@ class IframeListener {
hasPlayerMoved(event: HasPlayerMovedEvent) { hasPlayerMoved(event: HasPlayerMovedEvent) {
if (this.sendPlayerMove) { if (this.sendPlayerMove) {
this.postMessage({ this.postMessage({
type: 'hasPlayerMoved', type: "hasPlayerMoved",
data: event, data: event,
}); });
} }
@ -406,7 +406,7 @@ class IframeListener {
sendButtonClickedEvent(popupId: number, buttonId: number): void { sendButtonClickedEvent(popupId: number, buttonId: number): void {
this.postMessage({ this.postMessage({
type: 'buttonClickedEvent', type: "buttonClickedEvent",
data: { data: {
popupId, popupId,
buttonId, buttonId,
@ -419,7 +419,7 @@ class IframeListener {
*/ */
public 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, "*");
} }
} }
@ -431,7 +431,7 @@ class IframeListener {
* @param key The "type" of the query we are answering * @param key The "type" of the query we are answering
* @param callback * @param callback
*/ */
public registerAnswerer<T extends keyof IframeQueryMap, Guard extends tg.TypeGuard<IframeQueryMap[T]['query']>>( public registerAnswerer<T extends keyof IframeQueryMap, Guard extends tg.TypeGuard<IframeQueryMap[T]["query"]>>(
key: T, key: T,
callback: AnswererCallback<T>, callback: AnswererCallback<T>,
typeChecker?: Guard typeChecker?: Guard

View File

@ -1,6 +1,6 @@
import Axios from 'axios'; import Axios from "axios";
import { PUSHER_URL } from '../Enum/EnvironmentVariable'; import { PUSHER_URL } from "../Enum/EnvironmentVariable";
import type { CharacterTexture } from './LocalUser'; import type { CharacterTexture } from "./LocalUser";
export class MapDetail { export class MapDetail {
constructor(public readonly mapUrl: string, public readonly textures: CharacterTexture[] | undefined) {} constructor(public readonly mapUrl: string, public readonly textures: CharacterTexture[] | undefined) {}
@ -15,19 +15,19 @@ export class Room {
private _search: URLSearchParams; private _search: URLSearchParams;
constructor(id: string) { constructor(id: string) {
const url = new URL(id, 'https://example.com'); const url = new URL(id, "https://example.com");
this.id = url.pathname; this.id = url.pathname;
if (this.id.startsWith('/')) { if (this.id.startsWith("/")) {
this.id = this.id.substr(1); this.id = this.id.substr(1);
} }
if (this.id.startsWith('_/')) { if (this.id.startsWith("_/")) {
this.isPublic = true; this.isPublic = true;
} else if (this.id.startsWith('@/')) { } else if (this.id.startsWith("@/")) {
this.isPublic = false; this.isPublic = false;
} else { } else {
throw new Error('Invalid room ID'); throw new Error("Invalid room ID");
} }
this._search = new URLSearchParams(url.search); this._search = new URLSearchParams(url.search);
@ -38,16 +38,16 @@ export class Room {
baseUrl: string, baseUrl: string,
currentInstance: string currentInstance: string
): { roomId: string; hash: string | null } { ): { roomId: string; hash: string | null } {
let roomId = ''; let roomId = "";
let hash = null; let hash = null;
if (!identifier.startsWith('/_/') && !identifier.startsWith('/@/')) { if (!identifier.startsWith("/_/") && !identifier.startsWith("/@/")) {
//relative file link //relative file link
//Relative identifier can be deep enough to rewrite the base domain, so we cannot use the variable 'baseUrl' as the actual base url for the URL objects. //Relative identifier can be deep enough to rewrite the base domain, so we cannot use the variable 'baseUrl' as the actual base url for the URL objects.
//We instead use 'workadventure' as a dummy base value. //We instead use 'workadventure' as a dummy base value.
const baseUrlObject = new URL(baseUrl); const baseUrlObject = new URL(baseUrl);
const absoluteExitSceneUrl = new URL( const absoluteExitSceneUrl = new URL(
identifier, identifier,
'http://workadventure/_/' + currentInstance + '/' + baseUrlObject.hostname + baseUrlObject.pathname "http://workadventure/_/" + currentInstance + "/" + baseUrlObject.hostname + baseUrlObject.pathname
); );
roomId = absoluteExitSceneUrl.pathname; //in case of a relative url, we need to create a public roomId roomId = absoluteExitSceneUrl.pathname; //in case of a relative url, we need to create a public roomId
roomId = roomId.substring(1); //remove the leading slash roomId = roomId.substring(1); //remove the leading slash
@ -58,7 +58,7 @@ export class Room {
} }
} else { } else {
//absolute room Id //absolute room Id
const parts = identifier.split('#'); const parts = identifier.split("#");
roomId = parts[0]; roomId = parts[0];
roomId = roomId.substring(1); //remove the leading slash roomId = roomId.substring(1); //remove the leading slash
if (parts.length > 1) { if (parts.length > 1) {
@ -78,7 +78,7 @@ export class Room {
if (this.isPublic) { if (this.isPublic) {
const match = /_\/[^/]+\/(.+)/.exec(this.id); const match = /_\/[^/]+\/(.+)/.exec(this.id);
if (!match) throw new Error('Could not extract url from "' + this.id + '"'); if (!match) throw new Error('Could not extract url from "' + this.id + '"');
this.mapUrl = window.location.protocol + '//' + match[1]; this.mapUrl = window.location.protocol + "//" + match[1];
resolve(new MapDetail(this.mapUrl, this.textures)); resolve(new MapDetail(this.mapUrl, this.textures));
return; return;
} else { } else {
@ -89,7 +89,7 @@ export class Room {
params: urlParts, params: urlParts,
}) })
.then(({ data }) => { .then(({ data }) => {
console.log('Map ', this.id, ' resolves to URL ', data.mapUrl); console.log("Map ", this.id, " resolves to URL ", data.mapUrl);
resolve(data); resolve(data);
return; return;
}) })
@ -118,7 +118,7 @@ export class Room {
} else { } else {
const match = /@\/([^/]+)\/([^/]+)\/.+/.exec(this.id); const match = /@\/([^/]+)\/([^/]+)\/.+/.exec(this.id);
if (!match) throw new Error('Could not extract instance from "' + this.id + '"'); if (!match) throw new Error('Could not extract instance from "' + this.id + '"');
this.instance = match[1] + '/' + match[2]; this.instance = match[1] + "/" + match[2];
return this.instance; return this.instance;
} }
} }
@ -127,7 +127,7 @@ export class Room {
const regex = /@\/([^/]+)\/([^/]+)(?:\/([^/]*))?/gm; const regex = /@\/([^/]+)\/([^/]+)(?:\/([^/]*))?/gm;
const match = regex.exec(url); const match = regex.exec(url);
if (!match) { if (!match) {
throw new Error('Invalid URL ' + url); throw new Error("Invalid URL " + url);
} }
const results: { organizationSlug: string; worldSlug: string; roomSlug?: string } = { const results: { organizationSlug: string; worldSlug: string; roomSlug?: string } = {
organizationSlug: match[1], organizationSlug: match[1],
@ -140,8 +140,8 @@ export class Room {
} }
public isDisconnected(): boolean { public isDisconnected(): boolean {
const alone = this._search.get('alone'); const alone = this._search.get("alone");
if (alone && alone !== '0' && alone.toLowerCase() !== 'false') { if (alone && alone !== "0" && alone.toLowerCase() !== "false") {
return true; return true;
} }
return false; return false;

View File

@ -1,8 +1,8 @@
import type { Subscription } from 'rxjs'; import type { Subscription } from "rxjs";
import { GlobalMessageManager } from '../../Administration/GlobalMessageManager'; import { GlobalMessageManager } from "../../Administration/GlobalMessageManager";
import { userMessageManager } from '../../Administration/UserMessageManager'; import { userMessageManager } from "../../Administration/UserMessageManager";
import { iframeListener } from '../../Api/IframeListener'; import { iframeListener } from "../../Api/IframeListener";
import { connectionManager } from '../../Connexion/ConnectionManager'; import { connectionManager } from "../../Connexion/ConnectionManager";
import type { import type {
GroupCreatedUpdatedMessageInterface, GroupCreatedUpdatedMessageInterface,
MessageUserJoined, MessageUserJoined,
@ -12,10 +12,10 @@ import type {
PointInterface, PointInterface,
PositionInterface, PositionInterface,
RoomJoinedMessageInterface, RoomJoinedMessageInterface,
} from '../../Connexion/ConnexionModels'; } from "../../Connexion/ConnexionModels";
import { DEBUG_MODE, JITSI_PRIVATE_MODE, MAX_PER_GROUP, POSITION_DELAY } from '../../Enum/EnvironmentVariable'; import { DEBUG_MODE, JITSI_PRIVATE_MODE, MAX_PER_GROUP, POSITION_DELAY } from "../../Enum/EnvironmentVariable";
import { Queue } from 'queue-typescript'; import { Queue } from "queue-typescript";
import { import {
AUDIO_LOOP_PROPERTY, AUDIO_LOOP_PROPERTY,
AUDIO_VOLUME_PROPERTY, AUDIO_VOLUME_PROPERTY,
@ -26,72 +26,72 @@ import {
TRIGGER_JITSI_PROPERTIES, TRIGGER_JITSI_PROPERTIES,
TRIGGER_WEBSITE_PROPERTIES, TRIGGER_WEBSITE_PROPERTIES,
WEBSITE_MESSAGE_PROPERTIES, WEBSITE_MESSAGE_PROPERTIES,
} from '../../WebRtc/LayoutManager'; } from "../../WebRtc/LayoutManager";
import { coWebsiteManager } from '../../WebRtc/CoWebsiteManager'; import { coWebsiteManager } from "../../WebRtc/CoWebsiteManager";
import type { UserMovedMessage } from '../../Messages/generated/messages_pb'; import type { UserMovedMessage } from "../../Messages/generated/messages_pb";
import { ProtobufClientUtils } from '../../Network/ProtobufClientUtils'; import { ProtobufClientUtils } from "../../Network/ProtobufClientUtils";
import type { RoomConnection } from '../../Connexion/RoomConnection'; import type { RoomConnection } from "../../Connexion/RoomConnection";
import { Room } from '../../Connexion/Room'; import { Room } from "../../Connexion/Room";
import { jitsiFactory } from '../../WebRtc/JitsiFactory'; import { jitsiFactory } from "../../WebRtc/JitsiFactory";
import { urlManager } from '../../Url/UrlManager'; import { urlManager } from "../../Url/UrlManager";
import { audioManager } from '../../WebRtc/AudioManager'; import { audioManager } from "../../WebRtc/AudioManager";
import { TextureError } from '../../Exception/TextureError'; import { TextureError } from "../../Exception/TextureError";
import { localUserStore } from '../../Connexion/LocalUserStore'; import { localUserStore } from "../../Connexion/LocalUserStore";
import { HtmlUtils } from '../../WebRtc/HtmlUtils'; import { HtmlUtils } from "../../WebRtc/HtmlUtils";
import { mediaManager } from '../../WebRtc/MediaManager'; import { mediaManager } from "../../WebRtc/MediaManager";
import { SimplePeer } from '../../WebRtc/SimplePeer'; import { SimplePeer } from "../../WebRtc/SimplePeer";
import { addLoader } from '../Components/Loader'; import { addLoader } from "../Components/Loader";
import { OpenChatIcon, openChatIconName } from '../Components/OpenChatIcon'; import { OpenChatIcon, openChatIconName } from "../Components/OpenChatIcon";
import { lazyLoadPlayerCharacterTextures, loadCustomTexture } from '../Entity/PlayerTexturesLoadingManager'; import { lazyLoadPlayerCharacterTextures, loadCustomTexture } from "../Entity/PlayerTexturesLoadingManager";
import { RemotePlayer } from '../Entity/RemotePlayer'; import { RemotePlayer } from "../Entity/RemotePlayer";
import type { ActionableItem } from '../Items/ActionableItem'; import type { ActionableItem } from "../Items/ActionableItem";
import type { ItemFactoryInterface } from '../Items/ItemFactoryInterface'; import type { ItemFactoryInterface } from "../Items/ItemFactoryInterface";
import { SelectCharacterScene, SelectCharacterSceneName } from '../Login/SelectCharacterScene'; import { SelectCharacterScene, SelectCharacterSceneName } from "../Login/SelectCharacterScene";
import type { import type {
ITiledMap, ITiledMap,
ITiledMapLayer, ITiledMapLayer,
ITiledMapLayerProperty, ITiledMapLayerProperty,
ITiledMapObject, ITiledMapObject,
ITiledTileSet, ITiledTileSet,
} from '../Map/ITiledMap'; } from "../Map/ITiledMap";
import { MenuScene, MenuSceneName } from '../Menu/MenuScene'; import { MenuScene, MenuSceneName } from "../Menu/MenuScene";
import { PlayerAnimationDirections } from '../Player/Animation'; import { PlayerAnimationDirections } from "../Player/Animation";
import { hasMovedEventName, Player, requestEmoteEventName } from '../Player/Player'; import { hasMovedEventName, Player, requestEmoteEventName } from "../Player/Player";
import { ErrorSceneName } from '../Reconnecting/ErrorScene'; import { ErrorSceneName } from "../Reconnecting/ErrorScene";
import { ReconnectingSceneName } from '../Reconnecting/ReconnectingScene'; import { ReconnectingSceneName } from "../Reconnecting/ReconnectingScene";
import { UserInputManager } from '../UserInput/UserInputManager'; import { UserInputManager } from "../UserInput/UserInputManager";
import type { AddPlayerInterface } from './AddPlayerInterface'; import type { AddPlayerInterface } from "./AddPlayerInterface";
import { gameManager } from './GameManager'; import { gameManager } from "./GameManager";
import { GameMap } from './GameMap'; import { GameMap } from "./GameMap";
import { PlayerMovement } from './PlayerMovement'; import { PlayerMovement } from "./PlayerMovement";
import { PlayersPositionInterpolator } from './PlayersPositionInterpolator'; import { PlayersPositionInterpolator } from "./PlayersPositionInterpolator";
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 { worldFullMessageStream } from '../../Connexion/WorldFullMessageStream'; import { worldFullMessageStream } from "../../Connexion/WorldFullMessageStream";
import { lazyLoadCompanionResource } from '../Companion/CompanionTexturesLoadingManager'; import { lazyLoadCompanionResource } from "../Companion/CompanionTexturesLoadingManager";
import { DirtyScene } from './DirtyScene'; import { DirtyScene } from "./DirtyScene";
import { TextUtils } from '../Components/TextUtils'; import { TextUtils } from "../Components/TextUtils";
import { touchScreenManager } from '../../Touch/TouchScreenManager'; import { touchScreenManager } from "../../Touch/TouchScreenManager";
import { PinchManager } from '../UserInput/PinchManager'; import { PinchManager } from "../UserInput/PinchManager";
import { joystickBaseImg, joystickBaseKey, joystickThumbImg, joystickThumbKey } from '../Components/MobileJoystick'; import { joystickBaseImg, joystickBaseKey, joystickThumbImg, joystickThumbKey } from "../Components/MobileJoystick";
import { waScaleManager } from '../Services/WaScaleManager'; import { waScaleManager } from "../Services/WaScaleManager";
import { EmoteManager } from './EmoteManager'; import { EmoteManager } from "./EmoteManager";
import EVENT_TYPE = Phaser.Scenes.Events; import EVENT_TYPE = Phaser.Scenes.Events;
import RenderTexture = Phaser.GameObjects.RenderTexture; import RenderTexture = Phaser.GameObjects.RenderTexture;
import Tilemap = Phaser.Tilemaps.Tilemap; import Tilemap = Phaser.Tilemaps.Tilemap;
import type { HasPlayerMovedEvent } from '../../Api/Events/HasPlayerMovedEvent'; import type { HasPlayerMovedEvent } from "../../Api/Events/HasPlayerMovedEvent";
import AnimatedTiles from 'phaser-animated-tiles'; import AnimatedTiles from "phaser-animated-tiles";
import { StartPositionCalculator } from './StartPositionCalculator'; import { StartPositionCalculator } from "./StartPositionCalculator";
import { soundManager } from './SoundManager'; import { soundManager } from "./SoundManager";
import { peerStore, screenSharingPeerStore } from '../../Stores/PeerStore'; import { peerStore, screenSharingPeerStore } from "../../Stores/PeerStore";
import { videoFocusStore } from '../../Stores/VideoFocusStore'; import { videoFocusStore } from "../../Stores/VideoFocusStore";
import { biggestAvailableAreaStore } from '../../Stores/BiggestAvailableAreaStore'; import { biggestAvailableAreaStore } from "../../Stores/BiggestAvailableAreaStore";
import { isMessageReferenceEvent, isTriggerMessageEvent } from '../../Api/Events/ui/TriggerMessageEvent'; import { isMessageReferenceEvent, isTriggerMessageEvent } from "../../Api/Events/ui/TriggerMessageEvent";
export interface GameSceneInitInterface { export interface GameSceneInitInterface {
initPosition: PointInterface | null; initPosition: PointInterface | null;
@ -99,32 +99,32 @@ export interface GameSceneInitInterface {
} }
interface InitUserPositionEventInterface { interface InitUserPositionEventInterface {
type: 'InitUserPositionEvent'; type: "InitUserPositionEvent";
event: MessageUserPositionInterface[]; event: MessageUserPositionInterface[];
} }
interface AddPlayerEventInterface { interface AddPlayerEventInterface {
type: 'AddPlayerEvent'; type: "AddPlayerEvent";
event: AddPlayerInterface; event: AddPlayerInterface;
} }
interface RemovePlayerEventInterface { interface RemovePlayerEventInterface {
type: 'RemovePlayerEvent'; type: "RemovePlayerEvent";
userId: number; userId: number;
} }
interface UserMovedEventInterface { interface UserMovedEventInterface {
type: 'UserMovedEvent'; type: "UserMovedEvent";
event: MessageUserMovedInterface; event: MessageUserMovedInterface;
} }
interface GroupCreatedUpdatedEventInterface { interface GroupCreatedUpdatedEventInterface {
type: 'GroupCreatedUpdatedEvent'; type: "GroupCreatedUpdatedEvent";
event: GroupCreatedUpdatedMessageInterface; event: GroupCreatedUpdatedMessageInterface;
} }
interface DeleteGroupEventInterface { interface DeleteGroupEventInterface {
type: 'DeleteGroupEvent'; type: "DeleteGroupEvent";
groupId: number; groupId: number;
} }
@ -177,7 +177,7 @@ export class GameScene extends DirtyScene {
currentTick!: number; currentTick!: number;
lastSentTick!: number; // The last tick at which a position was sent. lastSentTick!: number; // The last tick at which a position was sent.
lastMoveEventSent: HasPlayerMovedEvent = { lastMoveEventSent: HasPlayerMovedEvent = {
direction: '', direction: "",
moving: false, moving: false,
x: -1000, x: -1000,
y: -1000, y: -1000,
@ -231,29 +231,29 @@ export class GameScene extends DirtyScene {
} }
} }
this.load.image(openChatIconName, 'resources/objects/talk.png'); this.load.image(openChatIconName, "resources/objects/talk.png");
if (touchScreenManager.supportTouchScreen) { if (touchScreenManager.supportTouchScreen) {
this.load.image(joystickBaseKey, joystickBaseImg); this.load.image(joystickBaseKey, joystickBaseImg);
this.load.image(joystickThumbKey, joystickThumbImg); this.load.image(joystickThumbKey, joystickThumbImg);
} }
this.load.audio('audio-webrtc-in', '/resources/objects/webrtc-in.mp3'); this.load.audio("audio-webrtc-in", "/resources/objects/webrtc-in.mp3");
this.load.audio('audio-webrtc-out', '/resources/objects/webrtc-out.mp3'); this.load.audio("audio-webrtc-out", "/resources/objects/webrtc-out.mp3");
//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 ( if (
window.location.protocol === 'http:' && window.location.protocol === "http:" &&
file.src === this.MapUrlFile && file.src === this.MapUrlFile &&
file.src.startsWith('http:') && file.src.startsWith("http:") &&
this.originalMapUrl === undefined 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( this.load.on(
'filecomplete-tilemapJSON-' + this.MapUrlFile, "filecomplete-tilemapJSON-" + this.MapUrlFile,
(key: string, type: string, data: unknown) => { (key: string, type: string, data: unknown) => {
this.onMapLoad(data); this.onMapLoad(data);
} }
@ -264,18 +264,18 @@ export class GameScene extends DirtyScene {
// So if we are in https, we can still try to load a HTTP local resource (can be useful for testing purposes) // So if we are in https, we can still try to load a HTTP local resource (can be useful for testing purposes)
// See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#when_is_a_context_considered_secure // See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#when_is_a_context_considered_secure
const url = new URL(file.src); const url = new URL(file.src);
const host = url.host.split(':')[0]; const host = url.host.split(":")[0];
if ( if (
window.location.protocol === 'https:' && window.location.protocol === "https:" &&
file.src === this.MapUrlFile && file.src === this.MapUrlFile &&
(host === '127.0.0.1' || host === 'localhost' || host.endsWith('.localhost')) && (host === "127.0.0.1" || host === "localhost" || host.endsWith(".localhost")) &&
this.originalMapUrl === undefined this.originalMapUrl === undefined
) { ) {
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( this.load.on(
'filecomplete-tilemapJSON-' + this.MapUrlFile, "filecomplete-tilemapJSON-" + this.MapUrlFile,
(key: string, type: string, data: unknown) => { (key: string, type: string, data: unknown) => {
this.onMapLoad(data); this.onMapLoad(data);
} }
@ -284,17 +284,17 @@ export class GameScene extends DirtyScene {
} }
//once preloading is over, we don't want loading errors to crash the game, so we need to disable this behavior after preloading. //once preloading is over, we don't want loading errors to crash the game, so we need to disable this behavior after preloading.
console.error('Error when loading: ', file); console.error("Error when loading: ", file);
if (this.preloading) { if (this.preloading) {
this.scene.start(ErrorSceneName, { this.scene.start(ErrorSceneName, {
title: 'Network error', title: "Network error",
subTitle: 'An error occurred while loading resource:', subTitle: "An error occurred while loading resource:",
message: this.originalMapUrl ?? file.src, message: this.originalMapUrl ?? file.src,
}); });
} }
}); });
this.load.scenePlugin('AnimatedTiles', AnimatedTiles, 'animatedTiles', 'animatedTiles'); this.load.scenePlugin("AnimatedTiles", AnimatedTiles, "animatedTiles", "animatedTiles");
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
@ -306,13 +306,13 @@ export class GameScene extends DirtyScene {
this.onMapLoad(data); this.onMapLoad(data);
} }
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({
custom: { custom: {
families: ['Press Start 2P'], families: ["Press Start 2P"],
urls: ['/resources/fonts/fonts.css'], urls: ["/resources/fonts/fonts.css"],
testString: 'abcdefg', testString: "abcdefg",
}, },
}); });
@ -326,9 +326,9 @@ export class GameScene extends DirtyScene {
// Triggered when the map is loaded // Triggered when the map is loaded
// Load tiles attached to the map recursively // Load tiles attached to the map recursively
this.mapFile = data.data; this.mapFile = data.data;
const url = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/')); const url = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf("/"));
this.mapFile.tilesets.forEach((tileset) => { this.mapFile.tilesets.forEach((tileset) => {
if (typeof tileset.name === 'undefined' || typeof tileset.image === 'undefined') { if (typeof tileset.name === "undefined" || typeof tileset.image === "undefined") {
console.warn("Don't know how to handle tileset ", tileset); console.warn("Don't know how to handle tileset ", tileset);
return; return;
} }
@ -340,7 +340,7 @@ export class GameScene extends DirtyScene {
const objects = new Map<string, ITiledMapObject[]>(); const objects = new Map<string, ITiledMapObject[]>();
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)) {
@ -348,7 +348,7 @@ export class GameScene extends DirtyScene {
} else { } else {
objectsOfType = objects.get(object.type); objectsOfType = objects.get(object.type);
if (objectsOfType === undefined) { if (objectsOfType === undefined) {
throw new Error('Unexpected object type not found'); throw new Error("Unexpected object type not found");
} }
} }
objectsOfType.push(object); objectsOfType.push(object);
@ -363,8 +363,8 @@ export class GameScene extends DirtyScene {
let itemFactory: ItemFactoryInterface; let itemFactory: ItemFactoryInterface;
switch (itemType) { switch (itemType) {
case 'computer': { case "computer": {
const module = await import('../Items/Computer/computer'); const module = await import("../Items/Computer/computer");
itemFactory = module.default; itemFactory = module.default;
break; break;
} }
@ -376,7 +376,7 @@ export class GameScene extends DirtyScene {
itemFactory.preload(this.load); itemFactory.preload(this.load);
this.load.start(); // Let's manually start the loader because the import might be over AFTER the loading ends. this.load.start(); // Let's manually start the loader because the import might be over AFTER the loading ends.
this.load.on('complete', () => { this.load.on("complete", () => {
// FIXME: the factory might fail because the resources might not be loaded yet... // FIXME: the factory might fail because the resources might not be loaded yet...
// We would need to add a loader ended event in addition to the createPromise // We would need to add a loader ended event in addition to the createPromise
this.createPromise.then(async () => { this.createPromise.then(async () => {
@ -432,7 +432,7 @@ export class GameScene extends DirtyScene {
const playerName = gameManager.getPlayerName(); const playerName = gameManager.getPlayerName();
if (!playerName) { if (!playerName) {
throw 'playerName is not set'; throw "playerName is not set";
} }
this.playerName = playerName; this.playerName = playerName;
this.characterLayers = gameManager.getCharacterLayers(); this.characterLayers = gameManager.getCharacterLayers();
@ -440,7 +440,7 @@ export class GameScene extends DirtyScene {
//initalise map //initalise map
this.Map = this.add.tilemap(this.MapUrlFile); this.Map = this.add.tilemap(this.MapUrlFile);
const mapDirUrl = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/')); const mapDirUrl = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf("/"));
this.mapFile.tilesets.forEach((tileset: ITiledTileSet) => { this.mapFile.tilesets.forEach((tileset: ITiledTileSet) => {
this.Terrains.push( this.Terrains.push(
this.Map.addTilesetImage( this.Map.addTilesetImage(
@ -460,7 +460,7 @@ export class GameScene extends DirtyScene {
//add layer on map //add layer on map
this.gameMap = new GameMap(this.mapFile, this.Map, this.Terrains); this.gameMap = new GameMap(this.mapFile, this.Map, this.Terrains);
for (const layer of this.gameMap.flatLayers) { for (const layer of this.gameMap.flatLayers) {
if (layer.type === 'tilelayer') { if (layer.type === "tilelayer") {
const exitSceneUrl = this.getExitSceneUrl(layer); const exitSceneUrl = this.getExitSceneUrl(layer);
if (exitSceneUrl !== undefined) { if (exitSceneUrl !== undefined) {
this.loadNextGame(exitSceneUrl); this.loadNextGame(exitSceneUrl);
@ -470,7 +470,7 @@ export class GameScene extends DirtyScene {
this.loadNextGame(exitUrl); this.loadNextGame(exitUrl);
} }
} }
if (layer.type === 'objectgroup') { if (layer.type === "objectgroup") {
for (const object of layer.objects) { for (const object of layer.objects) {
if (object.text) { if (object.text) {
TextUtils.createTextFromITiledMapObject(this, object); TextUtils.createTextFromITiledMapObject(this, object);
@ -501,7 +501,7 @@ export class GameScene extends DirtyScene {
mediaManager.setUserInputManager(this.userInputManager); mediaManager.setUserInputManager(this.userInputManager);
if (localUserStore.getFullscreen()) { if (localUserStore.getFullscreen()) {
document.querySelector('body')?.requestFullscreen(); document.querySelector("body")?.requestFullscreen();
} }
//notify game manager can to create currentUser in map //notify game manager can to create currentUser in map
@ -511,7 +511,7 @@ export class GameScene extends DirtyScene {
this.initCamera(); this.initCamera();
this.animatedTiles.init(this.Map); this.animatedTiles.init(this.Map);
this.events.on('tileanimationupdate', () => (this.dirty = true)); this.events.on("tileanimationupdate", () => (this.dirty = true));
this.initCirclesCanvas(); this.initCirclesCanvas();
@ -561,11 +561,11 @@ export class GameScene extends DirtyScene {
this.peerStoreUnsubscribe = peerStore.subscribe((peers) => { this.peerStoreUnsubscribe = peerStore.subscribe((peers) => {
const newPeerNumber = peers.size; const newPeerNumber = peers.size;
if (newPeerNumber > oldPeerNumber) { if (newPeerNumber > oldPeerNumber) {
this.sound.play('audio-webrtc-in', { this.sound.play("audio-webrtc-in", {
volume: 0.2, volume: 0.2,
}); });
} else if (newPeerNumber < oldPeerNumber) { } else if (newPeerNumber < oldPeerNumber) {
this.sound.play('audio-webrtc-out', { this.sound.play("audio-webrtc-out", {
volume: 0.2, volume: 0.2,
}); });
} }
@ -613,7 +613,7 @@ export class GameScene extends DirtyScene {
this.connection.onUserMoved((message: UserMovedMessage) => { this.connection.onUserMoved((message: UserMovedMessage) => {
const position = message.getPosition(); const position = message.getPosition();
if (position === undefined) { if (position === undefined) {
throw new Error('Position missing from UserMovedMessage'); throw new Error("Position missing from UserMovedMessage");
} }
const messageUserMoved: MessageUserMovedInterface = { const messageUserMoved: MessageUserMovedInterface = {
@ -641,10 +641,10 @@ export class GameScene extends DirtyScene {
}); });
this.connection.onServerDisconnected(() => { this.connection.onServerDisconnected(() => {
console.log('Player disconnected from server. Reloading scene.'); console.log("Player disconnected from server. Reloading scene.");
this.cleanupClosingScene(); this.cleanupClosingScene();
const gameSceneKey = 'somekey' + Math.round(Math.random() * 10000); const gameSceneKey = "somekey" + Math.round(Math.random() * 10000);
const game: Phaser.Scene = new GameScene(this.room, this.MapUrlFile, gameSceneKey); const game: Phaser.Scene = new GameScene(this.room, this.MapUrlFile, gameSceneKey);
this.scene.add(gameSceneKey, game, true, { this.scene.add(gameSceneKey, game, true, {
initPosition: { initPosition: {
@ -723,34 +723,34 @@ export class GameScene extends DirtyScene {
private initCirclesCanvas(): void { private initCirclesCanvas(): void {
// Let's generate the circle for the group delimiter // Let's generate the circle for the group delimiter
let circleElement = Object.values(this.textures.list).find( let circleElement = Object.values(this.textures.list).find(
(object: Texture) => object.key === 'circleSprite-white' (object: Texture) => object.key === "circleSprite-white"
); );
if (circleElement) { if (circleElement) {
this.textures.remove('circleSprite-white'); this.textures.remove("circleSprite-white");
} }
circleElement = Object.values(this.textures.list).find((object: Texture) => object.key === 'circleSprite-red'); circleElement = Object.values(this.textures.list).find((object: Texture) => object.key === "circleSprite-red");
if (circleElement) { if (circleElement) {
this.textures.remove('circleSprite-red'); this.textures.remove("circleSprite-red");
} }
//create white circle canvas use to create sprite //create white circle canvas use to create sprite
this.circleTexture = this.textures.createCanvas('circleSprite-white', 96, 96); this.circleTexture = this.textures.createCanvas("circleSprite-white", 96, 96);
const context = this.circleTexture.context; const context = this.circleTexture.context;
context.beginPath(); context.beginPath();
context.arc(48, 48, 48, 0, 2 * Math.PI, false); context.arc(48, 48, 48, 0, 2 * Math.PI, false);
// context.lineWidth = 5; // context.lineWidth = 5;
context.strokeStyle = '#ffffff'; context.strokeStyle = "#ffffff";
context.stroke(); context.stroke();
this.circleTexture.refresh(); this.circleTexture.refresh();
//create red circle canvas use to create sprite //create red circle canvas use to create sprite
this.circleRedTexture = this.textures.createCanvas('circleSprite-red', 96, 96); this.circleRedTexture = this.textures.createCanvas("circleSprite-red", 96, 96);
const contextRed = this.circleRedTexture.context; const contextRed = this.circleRedTexture.context;
contextRed.beginPath(); contextRed.beginPath();
contextRed.arc(48, 48, 48, 0, 2 * Math.PI, false); contextRed.arc(48, 48, 48, 0, 2 * Math.PI, false);
//context.lineWidth = 5; //context.lineWidth = 5;
contextRed.strokeStyle = '#ff0000'; contextRed.strokeStyle = "#ff0000";
contextRed.stroke(); contextRed.stroke();
this.circleRedTexture.refresh(); this.circleRedTexture.refresh();
} }
@ -765,35 +765,35 @@ export class GameScene extends DirtyScene {
} }
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);
}); });
this.gameMap.onPropertyChange('exitUrl', (newValue, oldValue) => { this.gameMap.onPropertyChange("exitUrl", (newValue, oldValue) => {
if (newValue) this.onMapExit(newValue as string); if (newValue) this.onMapExit(newValue as string);
}); });
this.gameMap.onPropertyChange('openWebsite', (newValue, oldValue, allProps) => { this.gameMap.onPropertyChange("openWebsite", (newValue, oldValue, allProps) => {
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( coWebsiteManager.loadCoWebsite(
newValue as string, newValue as string,
this.MapUrlFile, this.MapUrlFile,
allProps.get('openWebsiteAllowApi') as boolean | undefined, allProps.get("openWebsiteAllowApi") as boolean | undefined,
allProps.get('openWebsitePolicy') as string | 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( layoutManager.addActionButton(
'openWebsite', "openWebsite",
message.toString(), message.toString(),
() => { () => {
openWebsiteFunction(); openWebsiteFunction();
@ -805,32 +805,32 @@ export class GameScene extends DirtyScene {
} }
} }
}); });
this.gameMap.onPropertyChange('jitsiRoom', (newValue, oldValue, allProps) => { this.gameMap.onPropertyChange("jitsiRoom", (newValue, oldValue, allProps) => {
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 {
this.startJitsi(roomName, undefined); this.startJitsi(roomName, undefined);
} }
layoutManager.removeActionButton('jitsiRoom', this.userInputManager); layoutManager.removeActionButton("jitsiRoom", this.userInputManager);
}; };
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";
} }
layoutManager.addActionButton( layoutManager.addActionButton(
'jitsiRoom', "jitsiRoom",
message.toString(), message.toString(),
() => { () => {
openJitsiRoomFunction(); openJitsiRoomFunction();
@ -842,14 +842,14 @@ export class GameScene extends DirtyScene {
} }
} }
}); });
this.gameMap.onPropertyChange('silent', (newValue, oldValue) => { this.gameMap.onPropertyChange("silent", (newValue, oldValue) => {
if (newValue === undefined || newValue === false || newValue === '') { if (newValue === undefined || newValue === false || newValue === "") {
this.connection?.setSilent(false); this.connection?.setSilent(false);
} else { } else {
this.connection?.setSilent(true); this.connection?.setSilent(true);
} }
}); });
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 newValue === undefined
@ -857,14 +857,14 @@ export class GameScene extends DirtyScene {
: audioManager.playAudio(newValue, this.getMapDirUrl(), volume, loop); : 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
this.gameMap.onPropertyChange('playAudioLoop', (newValue, oldValue) => { this.gameMap.onPropertyChange("playAudioLoop", (newValue, oldValue) => {
newValue === undefined newValue === undefined
? audioManager.unloadAudio() ? audioManager.unloadAudio()
: audioManager.playAudio(newValue, this.getMapDirUrl(), undefined, true); : audioManager.playAudio(newValue, this.getMapDirUrl(), undefined, true);
}); });
this.gameMap.onPropertyChange('zone', (newValue, oldValue) => { this.gameMap.onPropertyChange("zone", (newValue, oldValue) => {
if (newValue === undefined || newValue === false || newValue === '') { if (newValue === undefined || newValue === false || newValue === "") {
iframeListener.sendLeaveEvent(oldValue as string); iframeListener.sendLeaveEvent(oldValue as string);
} else { } else {
iframeListener.sendEnterEvent(newValue as string); iframeListener.sendEnterEvent(newValue as string);
@ -897,17 +897,17 @@ ${escapedMessage}
let id = 0; let id = 0;
for (const button of openPopupEvent.buttons) { for (const button of openPopupEvent.buttons) {
html += `<button type="button" class="nes-btn is-${HtmlUtils.escapeHtml( html += `<button type="button" class="nes-btn is-${HtmlUtils.escapeHtml(
button.className ?? '' button.className ?? ""
)}" id="popup-${openPopupEvent.popupId}-${id}">${HtmlUtils.escapeHtml(button.label)}</button>`; )}" id="popup-${openPopupEvent.popupId}-${id}">${HtmlUtils.escapeHtml(button.label)}</button>`;
id++; id++;
} }
html += '</div>'; html += "</div>";
const domElement = this.add.dom(objectLayerSquare.x, objectLayerSquare.y).createFromHTML(html); const domElement = this.add.dom(objectLayerSquare.x, 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");
setTimeout(() => { setTimeout(() => {
container.hidden = false; container.hidden = false;
@ -928,7 +928,7 @@ ${escapedMessage}
this.tweens.add({ this.tweens.add({
targets: domElement, targets: domElement,
scale: 1, scale: 1,
ease: 'EaseOut', ease: "EaseOut",
duration: 400, duration: 400,
}); });
@ -941,16 +941,16 @@ ${escapedMessage}
const popUpElement = this.popUpElements.get(closePopupEvent.popupId); const popUpElement = this.popUpElements.get(closePopupEvent.popupId);
if (popUpElement === undefined) { if (popUpElement === undefined) {
console.error( console.error(
'Could not close popup with ID ', "Could not close popup with ID ",
closePopupEvent.popupId, closePopupEvent.popupId,
'. Maybe it has already been closed?' ". 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();
@ -1008,7 +1008,7 @@ ${escapedMessage}
this, this,
this.CurrentPlayer.x + 25, this.CurrentPlayer.x + 25,
this.CurrentPlayer.y, this.CurrentPlayer.y,
'circleSprite-white' "circleSprite-white"
); );
scriptedBubbleSprite.setDisplayOrigin(48, 48); scriptedBubbleSprite.setDisplayOrigin(48, 48);
this.add.existing(scriptedBubbleSprite); this.add.existing(scriptedBubbleSprite);
@ -1045,7 +1045,7 @@ ${escapedMessage}
}) })
); );
iframeListener.registerAnswerer('getState', () => { iframeListener.registerAnswerer("getState", () => {
return { return {
mapUrl: this.MapUrlFile, mapUrl: this.MapUrlFile,
startLayerName: this.startPositionCalculator.startLayerName, startLayerName: this.startPositionCalculator.startLayerName,
@ -1064,7 +1064,7 @@ ${escapedMessage}
); );
iframeListener.registerAnswerer( iframeListener.registerAnswerer(
'triggerMessage', "triggerMessage",
(message) => (message) =>
new Promise((resolver) => { new Promise((resolver) => {
layoutManager.addActionButton( layoutManager.addActionButton(
@ -1081,7 +1081,7 @@ ${escapedMessage}
); );
iframeListener.registerAnswerer( iframeListener.registerAnswerer(
'removeTriggerMessage', "removeTriggerMessage",
(message) => { (message) => {
layoutManager.removeActionButton(message.uuid, this.userInputManager); layoutManager.removeActionButton(message.uuid, this.userInputManager);
}, },
@ -1121,14 +1121,14 @@ ${escapedMessage}
} }
private getMapDirUrl(): string { private getMapDirUrl(): string {
return this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/')); return this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf("/"));
} }
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);
if (hash) { if (hash) {
urlManager.pushStartLayerNameToUrl(hash); urlManager.pushStartLayerNameToUrl(hash);
} }
@ -1136,7 +1136,7 @@ ${escapedMessage}
menuScene.reset(); 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);
return; return;
} }
this.cleanupClosingScene(); this.cleanupClosingScene();
@ -1173,7 +1173,7 @@ ${escapedMessage}
this.emoteManager.destroy(); this.emoteManager.destroy();
this.peerStoreUnsubscribe(); this.peerStoreUnsubscribe();
this.biggestAvailableAreaStoreUnsubscribe(); this.biggestAvailableAreaStoreUnsubscribe();
iframeListener.unregisterAnswerer('getState'); iframeListener.unregisterAnswerer("getState");
mediaManager.hideGameOverlay(); mediaManager.hideGameOverlay();
@ -1196,18 +1196,18 @@ ${escapedMessage}
} }
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 getScriptUrls(map: ITiledMap): string[] { private getScriptUrls(map: ITiledMap): string[] {
return (this.getProperties(map, 'script') as string[]).map((script) => return (this.getProperties(map, "script") as string[]).map((script) =>
new URL(script, this.MapUrlFile).toString() new URL(script, this.MapUrlFile).toString()
); );
} }
@ -1285,7 +1285,7 @@ ${escapedMessage}
this.companion, this.companion,
this.companion !== null ? lazyLoadCompanionResource(this.load, this.companion) : undefined this.companion !== null ? lazyLoadCompanionResource(this.load, this.companion) : undefined
); );
this.CurrentPlayer.on('pointerdown', (pointer: Phaser.Input.Pointer) => { this.CurrentPlayer.on("pointerdown", (pointer: Phaser.Input.Pointer) => {
if (pointer.wasTouch && (pointer.event as TouchEvent).touches.length > 1) { if (pointer.wasTouch && (pointer.event as TouchEvent).touches.length > 1) {
return; //we don't want the menu to open when pinching on a touch screen. return; //we don't want the menu to open when pinching on a touch screen.
} }
@ -1403,22 +1403,22 @@ ${escapedMessage}
this.dirty = true; this.dirty = true;
const event = this.pendingEvents.dequeue(); const event = this.pendingEvents.dequeue();
switch (event.type) { switch (event.type) {
case 'InitUserPositionEvent': case "InitUserPositionEvent":
this.doInitUsersPosition(event.event); this.doInitUsersPosition(event.event);
break; break;
case 'AddPlayerEvent': case "AddPlayerEvent":
this.doAddPlayer(event.event); this.doAddPlayer(event.event);
break; break;
case 'RemovePlayerEvent': case "RemovePlayerEvent":
this.doRemovePlayer(event.userId); this.doRemovePlayer(event.userId);
break; break;
case 'UserMovedEvent': case "UserMovedEvent":
this.doUpdatePlayerPosition(event.event); this.doUpdatePlayerPosition(event.event);
break; break;
case 'GroupCreatedUpdatedEvent': case "GroupCreatedUpdatedEvent":
this.doShareGroupPosition(event.event); this.doShareGroupPosition(event.event);
break; break;
case 'DeleteGroupEvent': case "DeleteGroupEvent":
this.doDeleteGroup(event.groupId); this.doDeleteGroup(event.groupId);
break; break;
} }
@ -1440,7 +1440,7 @@ ${escapedMessage}
*/ */
private initUsersPosition(usersPosition: MessageUserPositionInterface[]): void { private initUsersPosition(usersPosition: MessageUserPositionInterface[]): void {
this.pendingEvents.enqueue({ this.pendingEvents.enqueue({
type: 'InitUserPositionEvent', type: "InitUserPositionEvent",
event: usersPosition, event: usersPosition,
}); });
} }
@ -1465,7 +1465,7 @@ ${escapedMessage}
*/ */
public addPlayer(addPlayerData: AddPlayerInterface): void { public addPlayer(addPlayerData: AddPlayerInterface): void {
this.pendingEvents.enqueue({ this.pendingEvents.enqueue({
type: 'AddPlayerEvent', type: "AddPlayerEvent",
event: addPlayerData, event: addPlayerData,
}); });
} }
@ -1504,7 +1504,7 @@ ${escapedMessage}
*/ */
public removePlayer(userId: number) { public removePlayer(userId: number) {
this.pendingEvents.enqueue({ this.pendingEvents.enqueue({
type: 'RemovePlayerEvent', type: "RemovePlayerEvent",
userId, userId,
}); });
} }
@ -1512,7 +1512,7 @@ ${escapedMessage}
private doRemovePlayer(userId: number) { private doRemovePlayer(userId: number) {
const player = this.MapPlayersByKey.get(userId); const player = this.MapPlayersByKey.get(userId);
if (player === undefined) { if (player === undefined) {
console.error('Cannot find user with id ', userId); console.error("Cannot find user with id ", userId);
} else { } else {
player.destroy(); player.destroy();
@ -1528,7 +1528,7 @@ ${escapedMessage}
public updatePlayerPosition(message: MessageUserMovedInterface): void { public updatePlayerPosition(message: MessageUserMovedInterface): void {
this.pendingEvents.enqueue({ this.pendingEvents.enqueue({
type: 'UserMovedEvent', type: "UserMovedEvent",
event: message, event: message,
}); });
} }
@ -1554,7 +1554,7 @@ ${escapedMessage}
public shareGroupPosition(groupPositionMessage: GroupCreatedUpdatedMessageInterface) { public shareGroupPosition(groupPositionMessage: GroupCreatedUpdatedMessageInterface) {
this.pendingEvents.enqueue({ this.pendingEvents.enqueue({
type: 'GroupCreatedUpdatedEvent', type: "GroupCreatedUpdatedEvent",
event: groupPositionMessage, event: groupPositionMessage,
}); });
} }
@ -1569,7 +1569,7 @@ ${escapedMessage}
this, this,
Math.round(groupPositionMessage.position.x), Math.round(groupPositionMessage.position.x),
Math.round(groupPositionMessage.position.y), Math.round(groupPositionMessage.position.y),
groupPositionMessage.groupSize === MAX_PER_GROUP ? 'circleSprite-red' : 'circleSprite-white' groupPositionMessage.groupSize === MAX_PER_GROUP ? "circleSprite-red" : "circleSprite-white"
); );
sprite.setDisplayOrigin(48, 48); sprite.setDisplayOrigin(48, 48);
this.add.existing(sprite); this.add.existing(sprite);
@ -1579,7 +1579,7 @@ ${escapedMessage}
deleteGroup(groupId: number): void { deleteGroup(groupId: number): void {
this.pendingEvents.enqueue({ this.pendingEvents.enqueue({
type: 'DeleteGroupEvent', type: "DeleteGroupEvent",
groupId, groupId,
}); });
} }
@ -1615,7 +1615,7 @@ ${escapedMessage}
} }
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) {
if (object.name === objectName) { if (object.name === objectName) {
return object; return object;
@ -1640,7 +1640,7 @@ ${escapedMessage}
const xCenter = (array.xEnd - array.xStart) / 2 + array.xStart; const xCenter = (array.xEnd - array.xStart) / 2 + array.xStart;
const yCenter = (array.yEnd - array.yStart) / 2 + array.yStart; const yCenter = (array.yEnd - array.yStart) / 2 + array.yStart;
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( this.cameras.main.setFollowOffset(
@ -1651,19 +1651,19 @@ ${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( const jitsiInterfaceConfig = this.safeParseJSONstring(
allProps.get('jitsiInterfaceConfig') as string | undefined, allProps.get("jitsiInterfaceConfig") as string | undefined,
'jitsiInterfaceConfig' "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();
}); });
} }
@ -1673,7 +1673,7 @@ ${escapedMessage}
jitsiFactory.stop(); jitsiFactory.stop();
mediaManager.showGameOverlay(); mediaManager.showGameOverlay();
mediaManager.removeTriggerCloseJitsiFrameButton('close-jisi'); mediaManager.removeTriggerCloseJitsiFrameButton("close-jisi");
} }
//todo: put this into an 'orchestrator' scene (EntryScene?) //todo: put this into an 'orchestrator' scene (EntryScene?)
@ -1681,9 +1681,9 @@ ${escapedMessage}
this.cleanupClosingScene(); this.cleanupClosingScene();
this.userInputManager.disableControls(); this.userInputManager.disableControls();
this.scene.start(ErrorSceneName, { this.scene.start(ErrorSceneName, {
title: 'Banned', title: "Banned",
subTitle: 'You were banned from WorkAdventure', subTitle: "You were banned from WorkAdventure",
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",
}); });
} }
@ -1696,16 +1696,16 @@ ${escapedMessage}
//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: message:
'If you want more information, you may contact administrator or contact us at: workadventure@thecodingmachine.com', "If you want more information, you may contact administrator or contact us at: workadventure@thecodingmachine.com",
}); });
} }
} }

View File

@ -1,4 +1,4 @@
import { registeredCallbacks } from './Api/iframe/registeredCallbacks'; import { registeredCallbacks } from "./Api/iframe/registeredCallbacks";
import { import {
IframeResponseEvent, IframeResponseEvent,
IframeResponseEventMap, IframeResponseEventMap,
@ -6,19 +6,19 @@ import {
isIframeErrorAnswerEvent, isIframeErrorAnswerEvent,
isIframeResponseEventWrapper, isIframeResponseEventWrapper,
TypedMessageEvent, TypedMessageEvent,
} from './Api/Events/IframeEvent'; } from "./Api/Events/IframeEvent";
import chat from './Api/iframe/chat'; import chat from "./Api/iframe/chat";
import type { IframeCallback } from './Api/iframe/IframeApiContribution'; import type { IframeCallback } from "./Api/iframe/IframeApiContribution";
import nav from './Api/iframe/nav'; import nav from "./Api/iframe/nav";
import controls from './Api/iframe/controls'; import controls from "./Api/iframe/controls";
import ui from './Api/iframe/ui'; import ui from "./Api/iframe/ui";
import sound from './Api/iframe/sound'; import sound from "./Api/iframe/sound";
import room from './Api/iframe/room'; import room from "./Api/iframe/room";
import player from './Api/iframe/player'; import player from "./Api/iframe/player";
import type { ButtonDescriptor } from './Api/iframe/Ui/ButtonDescriptor'; import type { ButtonDescriptor } from "./Api/iframe/Ui/ButtonDescriptor";
import type { Popup } from './Api/iframe/Ui/Popup'; import type { Popup } from "./Api/iframe/Ui/Popup";
import type { Sound } from './Api/iframe/Sound/Sound'; import type { Sound } from "./Api/iframe/Sound/Sound";
import { answerPromises, sendToWorkadventure } from './Api/iframe/IframeApiContribution'; import { answerPromises, sendToWorkadventure } from "./Api/iframe/IframeApiContribution";
const wa = { const wa = {
ui, ui,
@ -36,7 +36,7 @@ const wa = {
* @deprecated Use WA.chat.sendChatMessage instead * @deprecated Use WA.chat.sendChatMessage instead
*/ */
sendChatMessage(message: string, author: string): void { sendChatMessage(message: string, author: string): void {
console.warn('Method WA.sendChatMessage is deprecated. Please use WA.chat.sendChatMessage instead'); console.warn("Method WA.sendChatMessage is deprecated. Please use WA.chat.sendChatMessage instead");
chat.sendChatMessage(message, author); chat.sendChatMessage(message, author);
}, },
@ -45,7 +45,7 @@ const wa = {
*/ */
disablePlayerControls(): void { disablePlayerControls(): void {
console.warn( console.warn(
'Method WA.disablePlayerControls is deprecated. Please use WA.controls.disablePlayerControls instead' "Method WA.disablePlayerControls is deprecated. Please use WA.controls.disablePlayerControls instead"
); );
controls.disablePlayerControls(); controls.disablePlayerControls();
}, },
@ -55,7 +55,7 @@ const wa = {
*/ */
restorePlayerControls(): void { restorePlayerControls(): void {
console.warn( console.warn(
'Method WA.restorePlayerControls is deprecated. Please use WA.controls.restorePlayerControls instead' "Method WA.restorePlayerControls is deprecated. Please use WA.controls.restorePlayerControls instead"
); );
controls.restorePlayerControls(); controls.restorePlayerControls();
}, },
@ -64,7 +64,7 @@ const wa = {
* @deprecated Use WA.ui.displayBubble instead * @deprecated Use WA.ui.displayBubble instead
*/ */
displayBubble(): void { displayBubble(): void {
console.warn('Method WA.displayBubble is deprecated. Please use WA.ui.displayBubble instead'); console.warn("Method WA.displayBubble is deprecated. Please use WA.ui.displayBubble instead");
ui.displayBubble(); ui.displayBubble();
}, },
@ -72,7 +72,7 @@ const wa = {
* @deprecated Use WA.ui.removeBubble instead * @deprecated Use WA.ui.removeBubble instead
*/ */
removeBubble(): void { removeBubble(): void {
console.warn('Method WA.removeBubble is deprecated. Please use WA.ui.removeBubble instead'); console.warn("Method WA.removeBubble is deprecated. Please use WA.ui.removeBubble instead");
ui.removeBubble(); ui.removeBubble();
}, },
@ -80,7 +80,7 @@ const wa = {
* @deprecated Use WA.nav.openTab instead * @deprecated Use WA.nav.openTab instead
*/ */
openTab(url: string): void { openTab(url: string): void {
console.warn('Method WA.openTab is deprecated. Please use WA.nav.openTab instead'); console.warn("Method WA.openTab is deprecated. Please use WA.nav.openTab instead");
nav.openTab(url); nav.openTab(url);
}, },
@ -88,7 +88,7 @@ const wa = {
* @deprecated Use WA.sound.loadSound instead * @deprecated Use WA.sound.loadSound instead
*/ */
loadSound(url: string): Sound { loadSound(url: string): Sound {
console.warn('Method WA.loadSound is deprecated. Please use WA.sound.loadSound instead'); console.warn("Method WA.loadSound is deprecated. Please use WA.sound.loadSound instead");
return sound.loadSound(url); return sound.loadSound(url);
}, },
@ -96,7 +96,7 @@ const wa = {
* @deprecated Use WA.nav.goToPage instead * @deprecated Use WA.nav.goToPage instead
*/ */
goToPage(url: string): void { goToPage(url: string): void {
console.warn('Method WA.goToPage is deprecated. Please use WA.nav.goToPage instead'); console.warn("Method WA.goToPage is deprecated. Please use WA.nav.goToPage instead");
nav.goToPage(url); nav.goToPage(url);
}, },
@ -104,15 +104,15 @@ const wa = {
* @deprecated Use WA.nav.goToRoom instead * @deprecated Use WA.nav.goToRoom instead
*/ */
goToRoom(url: string): void { goToRoom(url: string): void {
console.warn('Method WA.goToRoom is deprecated. Please use WA.nav.goToRoom instead'); console.warn("Method WA.goToRoom is deprecated. Please use WA.nav.goToRoom instead");
nav.goToRoom(url); nav.goToRoom(url);
}, },
/** /**
* @deprecated Use WA.nav.openCoWebSite instead * @deprecated Use WA.nav.openCoWebSite instead
*/ */
openCoWebSite(url: string, allowApi: boolean = false, allowPolicy: string = ''): void { openCoWebSite(url: string, allowApi: boolean = false, allowPolicy: string = ""): void {
console.warn('Method WA.openCoWebSite is deprecated. Please use WA.nav.openCoWebSite instead'); console.warn("Method WA.openCoWebSite is deprecated. Please use WA.nav.openCoWebSite instead");
nav.openCoWebSite(url, allowApi, allowPolicy); nav.openCoWebSite(url, allowApi, allowPolicy);
}, },
@ -120,7 +120,7 @@ const wa = {
* @deprecated Use WA.nav.closeCoWebSite instead * @deprecated Use WA.nav.closeCoWebSite instead
*/ */
closeCoWebSite(): void { closeCoWebSite(): void {
console.warn('Method WA.closeCoWebSite is deprecated. Please use WA.nav.closeCoWebSite instead'); console.warn("Method WA.closeCoWebSite is deprecated. Please use WA.nav.closeCoWebSite instead");
nav.closeCoWebSite(); nav.closeCoWebSite();
}, },
@ -128,28 +128,28 @@ const wa = {
* @deprecated Use WA.controls.restorePlayerControls instead * @deprecated Use WA.controls.restorePlayerControls instead
*/ */
openPopup(targetObject: string, message: string, buttons: ButtonDescriptor[]): Popup { openPopup(targetObject: string, message: string, buttons: ButtonDescriptor[]): Popup {
console.warn('Method WA.openPopup is deprecated. Please use WA.ui.openPopup instead'); console.warn("Method WA.openPopup is deprecated. Please use WA.ui.openPopup instead");
return ui.openPopup(targetObject, message, buttons); return ui.openPopup(targetObject, message, buttons);
}, },
/** /**
* @deprecated Use WA.chat.onChatMessage instead * @deprecated Use WA.chat.onChatMessage instead
*/ */
onChatMessage(callback: (message: string) => void): void { onChatMessage(callback: (message: string) => void): void {
console.warn('Method WA.onChatMessage is deprecated. Please use WA.chat.onChatMessage instead'); console.warn("Method WA.onChatMessage is deprecated. Please use WA.chat.onChatMessage instead");
chat.onChatMessage(callback); chat.onChatMessage(callback);
}, },
/** /**
* @deprecated Use WA.room.onEnterZone instead * @deprecated Use WA.room.onEnterZone instead
*/ */
onEnterZone(name: string, callback: () => void): void { onEnterZone(name: string, callback: () => void): void {
console.warn('Method WA.onEnterZone is deprecated. Please use WA.room.onEnterZone instead'); console.warn("Method WA.onEnterZone is deprecated. Please use WA.room.onEnterZone instead");
room.onEnterZone(name, callback); room.onEnterZone(name, callback);
}, },
/** /**
* @deprecated Use WA.room.onLeaveZone instead * @deprecated Use WA.room.onLeaveZone instead
*/ */
onLeaveZone(name: string, callback: () => void): void { onLeaveZone(name: string, callback: () => void): void {
console.warn('Method WA.onLeaveZone is deprecated. Please use WA.room.onLeaveZone instead'); console.warn("Method WA.onLeaveZone is deprecated. Please use WA.room.onLeaveZone instead");
room.onLeaveZone(name, callback); room.onLeaveZone(name, callback);
}, },
}; };
@ -166,7 +166,7 @@ declare global {
window.WA = wa; window.WA = wa;
window.addEventListener( window.addEventListener(
'message', "message",
<T extends keyof IframeResponseEventMap>(message: TypedMessageEvent<IframeResponseEvent<T>>) => { <T extends keyof IframeResponseEventMap>(message: TypedMessageEvent<IframeResponseEvent<T>>) => {
if (message.source !== window.parent) { if (message.source !== window.parent) {
return; // Skip message in this event listener return; // Skip message in this event listener
@ -181,7 +181,7 @@ window.addEventListener(
const resolver = answerPromises.get(queryId); const resolver = answerPromises.get(queryId);
if (resolver === undefined) { if (resolver === undefined) {
throw new Error('In Iframe API, got an answer for a question that we have no track of.'); throw new Error("In Iframe API, got an answer for a question that we have no track of.");
} }
resolver.resolve(payloadData); resolver.resolve(payloadData);
@ -192,7 +192,7 @@ window.addEventListener(
const resolver = answerPromises.get(queryId); const resolver = answerPromises.get(queryId);
if (resolver === undefined) { if (resolver === undefined) {
throw new Error('In Iframe API, got an error answer for a question that we have no track of.'); throw new Error("In Iframe API, got an error answer for a question that we have no track of.");
} }
resolver.reject(payloadError); resolver.reject(payloadError);

View File

@ -1,89 +1,89 @@
import 'jasmine'; import "jasmine";
import { Room } from '../../../src/Connexion/Room'; import { Room } from "../../../src/Connexion/Room";
describe('Room getIdFromIdentifier()', () => { describe("Room getIdFromIdentifier()", () => {
it('should work with an absolute room id and no hash as parameter', () => { it("should work with an absolute room id and no hash as parameter", () => {
const { roomId, hash } = Room.getIdFromIdentifier('/_/global/maps.workadventu.re/test2.json', '', ''); const { roomId, hash } = Room.getIdFromIdentifier("/_/global/maps.workadventu.re/test2.json", "", "");
expect(roomId).toEqual('_/global/maps.workadventu.re/test2.json'); expect(roomId).toEqual("_/global/maps.workadventu.re/test2.json");
expect(hash).toEqual(null); expect(hash).toEqual(null);
}); });
it('should work with an absolute room id and a hash as parameters', () => { it("should work with an absolute room id and a hash as parameters", () => {
const { roomId, hash } = Room.getIdFromIdentifier('/_/global/maps.workadventu.re/test2.json#start', '', ''); const { roomId, hash } = Room.getIdFromIdentifier("/_/global/maps.workadventu.re/test2.json#start", "", "");
expect(roomId).toEqual('_/global/maps.workadventu.re/test2.json'); expect(roomId).toEqual("_/global/maps.workadventu.re/test2.json");
expect(hash).toEqual('start'); expect(hash).toEqual("start");
}); });
it('should work with an absolute room id, regardless of baseUrl or instance', () => { it("should work with an absolute room id, regardless of baseUrl or instance", () => {
const { roomId, hash } = Room.getIdFromIdentifier( const { roomId, hash } = Room.getIdFromIdentifier(
'/_/global/maps.workadventu.re/test2.json', "/_/global/maps.workadventu.re/test2.json",
'https://another.domain/_/global/test.json', "https://another.domain/_/global/test.json",
'lol' "lol"
); );
expect(roomId).toEqual('_/global/maps.workadventu.re/test2.json'); expect(roomId).toEqual("_/global/maps.workadventu.re/test2.json");
expect(hash).toEqual(null); expect(hash).toEqual(null);
}); });
it('should work with a relative file link and no hash as parameters', () => { it("should work with a relative file link and no hash as parameters", () => {
const { roomId, hash } = Room.getIdFromIdentifier( const { roomId, hash } = Room.getIdFromIdentifier(
'./test2.json', "./test2.json",
'https://maps.workadventu.re/test.json', "https://maps.workadventu.re/test.json",
'global' "global"
); );
expect(roomId).toEqual('_/global/maps.workadventu.re/test2.json'); expect(roomId).toEqual("_/global/maps.workadventu.re/test2.json");
expect(hash).toEqual(null); expect(hash).toEqual(null);
}); });
it('should work with a relative file link with no dot', () => { it("should work with a relative file link with no dot", () => {
const { roomId, hash } = Room.getIdFromIdentifier( const { roomId, hash } = Room.getIdFromIdentifier(
'test2.json', "test2.json",
'https://maps.workadventu.re/test.json', "https://maps.workadventu.re/test.json",
'global' "global"
); );
expect(roomId).toEqual('_/global/maps.workadventu.re/test2.json'); expect(roomId).toEqual("_/global/maps.workadventu.re/test2.json");
expect(hash).toEqual(null); expect(hash).toEqual(null);
}); });
it('should work with a relative file link two levels deep', () => { it("should work with a relative file link two levels deep", () => {
const { roomId, hash } = Room.getIdFromIdentifier( const { roomId, hash } = Room.getIdFromIdentifier(
'../floor1/Floor1.json', "../floor1/Floor1.json",
'https://maps.workadventu.re/floor0/Floor0.json', "https://maps.workadventu.re/floor0/Floor0.json",
'global' "global"
); );
expect(roomId).toEqual('_/global/maps.workadventu.re/floor1/Floor1.json'); expect(roomId).toEqual("_/global/maps.workadventu.re/floor1/Floor1.json");
expect(hash).toEqual(null); expect(hash).toEqual(null);
}); });
it('should work with a relative file link that rewrite the map domain', () => { it("should work with a relative file link that rewrite the map domain", () => {
const { roomId, hash } = Room.getIdFromIdentifier( const { roomId, hash } = Room.getIdFromIdentifier(
'../../maps.workadventure.localhost/Floor1/floor1.json', "../../maps.workadventure.localhost/Floor1/floor1.json",
'https://maps.workadventu.re/floor0/Floor0.json', "https://maps.workadventu.re/floor0/Floor0.json",
'global' "global"
); );
expect(roomId).toEqual('_/global/maps.workadventure.localhost/Floor1/floor1.json'); expect(roomId).toEqual("_/global/maps.workadventure.localhost/Floor1/floor1.json");
expect(hash).toEqual(null); expect(hash).toEqual(null);
}); });
it('should work with a relative file link that rewrite the map instance', () => { it("should work with a relative file link that rewrite the map instance", () => {
const { roomId, hash } = Room.getIdFromIdentifier( const { roomId, hash } = Room.getIdFromIdentifier(
'../../../notglobal/maps.workadventu.re/Floor1/floor1.json', "../../../notglobal/maps.workadventu.re/Floor1/floor1.json",
'https://maps.workadventu.re/floor0/Floor0.json', "https://maps.workadventu.re/floor0/Floor0.json",
'global' "global"
); );
expect(roomId).toEqual('_/notglobal/maps.workadventu.re/Floor1/floor1.json'); expect(roomId).toEqual("_/notglobal/maps.workadventu.re/Floor1/floor1.json");
expect(hash).toEqual(null); expect(hash).toEqual(null);
}); });
it('should work with a relative file link that change the map type', () => { it("should work with a relative file link that change the map type", () => {
const { roomId, hash } = Room.getIdFromIdentifier( const { roomId, hash } = Room.getIdFromIdentifier(
'../../../../@/tcm/is/great', "../../../../@/tcm/is/great",
'https://maps.workadventu.re/floor0/Floor0.json', "https://maps.workadventu.re/floor0/Floor0.json",
'global' "global"
); );
expect(roomId).toEqual('@/tcm/is/great'); expect(roomId).toEqual("@/tcm/is/great");
expect(hash).toEqual(null); expect(hash).toEqual(null);
}); });
it('should work with a relative file link and a hash as parameters', () => { it("should work with a relative file link and a hash as parameters", () => {
const { roomId, hash } = Room.getIdFromIdentifier( const { roomId, hash } = Room.getIdFromIdentifier(
'./test2.json#start', "./test2.json#start",
'https://maps.workadventu.re/test.json', "https://maps.workadventu.re/test.json",
'global' "global"
); );
expect(roomId).toEqual('_/global/maps.workadventu.re/test2.json'); expect(roomId).toEqual("_/global/maps.workadventu.re/test2.json");
expect(hash).toEqual('start'); expect(hash).toEqual("start");
}); });
}); });