diff --git a/src/client/ClientGameRunner.ts b/src/client/ClientGameRunner.ts index 590bb58e5e..f2ded071e3 100644 --- a/src/client/ClientGameRunner.ts +++ b/src/client/ClientGameRunner.ts @@ -63,22 +63,12 @@ export interface LobbyConfig { gameRecord?: GameRecord; } -// Module-level reference to the current game runner -let currentGameRunner: ClientGameRunner | null = null; - -export function shouldPreventUnload(): boolean { - if (currentGameRunner) { - return currentGameRunner.shouldPreventWindowClose(); - } - return false; -} - export function joinLobby( eventBus: EventBus, lobbyConfig: LobbyConfig, onPrestart: () => void, onJoin: () => void, -): () => void { +): () => boolean { console.log( `joining lobby: gameID: ${lobbyConfig.gameID}, clientID: ${lobbyConfig.clientID}`, ); @@ -88,6 +78,8 @@ export function joinLobby( const transport = new Transport(lobbyConfig, eventBus); + let currentGameRunner: ClientGameRunner | null = null; + const onconnect = () => { console.log(`Joined game lobby ${lobbyConfig.gameID}`); transport.joinGame(0); @@ -141,9 +133,13 @@ export function joinLobby( }; transport.connect(onconnect, onmessage); return () => { + if (currentGameRunner && currentGameRunner.shouldPreventWindowClose()) { + return false; + } console.log("leaving game"); currentGameRunner = null; transport.leaveGame(); + return true; }; } diff --git a/src/client/Main.ts b/src/client/Main.ts index c468227572..e9df5666e7 100644 --- a/src/client/Main.ts +++ b/src/client/Main.ts @@ -6,7 +6,7 @@ import { ServerConfig } from "../core/configuration/Config"; import { getServerConfigFromClient } from "../core/configuration/ConfigLoader"; import { UserSettings } from "../core/game/UserSettings"; import "./AccountModal"; -import { joinLobby, shouldPreventUnload } from "./ClientGameRunner"; +import { joinLobby } from "./ClientGameRunner"; import { fetchCosmetics } from "./Cosmetics"; import "./DarkModeButton"; import { DarkModeButton } from "./DarkModeButton"; @@ -80,7 +80,7 @@ export interface JoinLobbyEvent { } class Client { - private gameStop: (() => void) | null = null; + private gameStop: (() => boolean) | null = null; private eventBus: EventBus = new EventBus(); private usernameInput: UsernameInput | null = null; @@ -154,16 +154,11 @@ class Client { this.publicLobby = document.querySelector("public-lobby") as PublicLobby; window.addEventListener("beforeunload", (e) => { - // Check if we should prevent unload (player is alive) - if (shouldPreventUnload()) { + if (this.gameStop && !this.gameStop()) { e.preventDefault(); return ""; } - // Otherwise, cleanup the game normally console.log("Browser is closing"); - if (this.gameStop !== null) { - this.gameStop(); - } }); document.addEventListener("join-lobby", this.handleJoinLobby.bind(this));