73 lines
1.8 KiB
JavaScript
73 lines
1.8 KiB
JavaScript
// lobby.js - lobby page logic
|
|
|
|
import { joinLobby } from "./api.js";
|
|
import {
|
|
clearGameState,
|
|
getLobbyName,
|
|
getPlayerName,
|
|
savePlayerName,
|
|
} from "./storage.js";
|
|
|
|
document.addEventListener("DOMContentLoaded", () => {
|
|
const input = document.getElementById("username");
|
|
const btn = document.getElementById("btn-start");
|
|
const errMsg = document.getElementById("name-error");
|
|
|
|
// Display the current lobby name
|
|
const lobbyNameEl = document.getElementById("lobby-name-display");
|
|
if (lobbyNameEl) {
|
|
lobbyNameEl.textContent = getLobbyName();
|
|
}
|
|
|
|
/**
|
|
* Validate the username input and navigate to the game.
|
|
* Shows an inline error message on invalid input.
|
|
*/
|
|
btn.addEventListener("click", async () => {
|
|
const name = input.value.trim();
|
|
const lobbyName = getLobbyName();
|
|
|
|
if (!name) {
|
|
errMsg.textContent = "Please enter a username to continue.";
|
|
input.classList.add("input--error");
|
|
input.focus();
|
|
return;
|
|
}
|
|
if (name.length < 2) {
|
|
errMsg.textContent = "Username must be at least 2 characters.";
|
|
input.classList.add("input--error");
|
|
input.focus();
|
|
return;
|
|
}
|
|
|
|
try {
|
|
btn.disabled = true;
|
|
await joinLobby(lobbyName, name);
|
|
savePlayerName(name);
|
|
clearGameState();
|
|
location.href = "game.html";
|
|
} catch (error) {
|
|
errMsg.textContent =
|
|
error instanceof Error ? error.message : "Could not join lobby.";
|
|
btn.disabled = false;
|
|
}
|
|
});
|
|
|
|
// Clear validation state on every keystroke
|
|
input.addEventListener("input", () => {
|
|
errMsg.textContent = "";
|
|
input.classList.remove("input--error");
|
|
});
|
|
|
|
// Allow form submission via Enter key
|
|
input.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter") btn.click();
|
|
});
|
|
|
|
// Pre-fill username if the player has played before
|
|
const existing = getPlayerName();
|
|
if (existing && existing !== "Anonymous") {
|
|
input.value = existing;
|
|
}
|
|
});
|