Skip to content

Commit

Permalink
fix: remain focused on canvas on load
Browse files Browse the repository at this point in the history
  • Loading branch information
0xAlcibiades committed Dec 28, 2024
1 parent ff2b071 commit c7b88dc
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -282,12 +282,30 @@ <h1>RUSTY PONG</h1>
playButton.textContent = "Click to Load Game";
gameContainer.appendChild(playButton);

// Helper function to move canvas into container
// Helper function to move canvas into container and focus it
const moveCanvas = () => {
const canvases = document.getElementsByTagName("canvas");
for (let canvas of canvases) {
if (canvas.parentElement !== gameContainer) {
gameContainer.appendChild(canvas);
// Add tabindex to make canvas focusable
canvas.setAttribute("tabindex", "0");
// Focus the canvas
canvas.focus();
// Maintain focus when clicking on canvas
canvas.addEventListener("mousedown", (e) => {
e.preventDefault();
canvas.focus();
});
// Prevent focus loss on mobile touch
canvas.addEventListener(
"touchstart",
(e) => {
e.preventDefault();
canvas.focus();
},
{ passive: false },
);
}
}
};
Expand All @@ -304,13 +322,15 @@ <h1>RUSTY PONG</h1>
window.webkitAudioContext)();
await audioContext.resume();

// Watch for canvas creation and move it to container
// Enhanced observer to handle canvas creation and focus
observer = new MutationObserver((mutations) => {
for (let mutation of mutations) {
if (mutation.addedNodes) {
mutation.addedNodes.forEach((node) => {
if (node.nodeName === "CANVAS") {
gameContainer.appendChild(node);
node.setAttribute("tabindex", "0");
node.focus();
}
});
}
Expand All @@ -324,21 +344,18 @@ <h1>RUSTY PONG</h1>
const { default: init } = await import("./rusty_pong.js");
await init();

// Ensure canvas is in the right place
// Ensure canvas is in the right place and focused
moveCanvas();
} catch (error) {
// Handle Bevy's control flow exception (not a real error)
if (error.message?.includes("Using exceptions for control flow")) {
loading.style.display = "none";
} else {
// Handle actual errors
console.error("Failed to load WASM:", error);
loading.textContent =
"Failed to load game. Please refresh and try again.";
loading.style.color = "#e43d1a";
}
} finally {
// Clean up observer if it was created
if (observer) {
observer.disconnect();
}
Expand Down

0 comments on commit c7b88dc

Please sign in to comment.