Files
Pac-Man/web/pages/+onPageTransitionEnd.ts
Xevion e017a87e12 fix(web): prevent stopGame from being called on non-game page transitions
Only stop the game when navigating away from the game page (/) to avoid
WASM runtime errors when navigating between /leaderboard and /download.
Add error handling to gracefully handle crashes during page transitions.
2025-12-29 14:53:42 -06:00

49 lines
1.5 KiB
TypeScript

import type { OnPageTransitionEndAsync } from "vike/types";
import { getPacmanWindow } from "@/lib/pacman";
import { setPendingNavigation } from "@/lib/navigation";
export const onPageTransitionEnd: OnPageTransitionEndAsync = async (pageContext) => {
console.log("Page transition end");
setPendingNavigation(null);
document.querySelector("body")?.classList.remove("page-is-transitioning");
// Restart the game loop when returning to the game page
if (pageContext.urlPathname === "/") {
// Defer game restart to allow fade-in animation to complete first
// This prevents the heavy WebGL initialization from blocking the UI
requestAnimationFrame(() => {
setTimeout(() => {
restartGame();
}, 0);
});
}
};
function restartGame() {
const win = getPacmanWindow();
const module = win.Module;
if (!module?._restart_game) {
console.warn("Game restart function not available (WASM may not be initialized)");
return;
}
const canvas = document.getElementById("canvas") as HTMLCanvasElement | null;
if (!canvas) {
console.error("Canvas element not found during game restart");
return;
}
// Update canvas reference BEFORE restart - App::new() will read from Module.canvas
module.canvas = canvas;
// SDL2's Emscripten backend reads this for canvas lookup
win.SDL_CANVAS_ID = "#canvas";
try {
console.log("Restarting game with fresh App instance");
module._restart_game();
} catch (error) {
console.error("Failed to restart game:", error);
}
}