40 lines
1.4 KiB
JavaScript
40 lines
1.4 KiB
JavaScript
// Get gameId and playerId from meta tags generated by the server
|
|
const gameIdMeta = document.querySelector('meta[name="gameId"]');
|
|
const playerIdMeta = document.querySelector('meta[name="playerId"]');
|
|
if (!gameIdMeta || !playerIdMeta) {
|
|
console.error('Game ID or Player ID meta tags not found.');
|
|
}
|
|
const gameId = gameIdMeta.content;
|
|
const playerId = playerIdMeta.content;
|
|
|
|
// Dynamically construct WebSocket URL
|
|
const wsUrl = `ws://${window.location.host}/ws?gameId=${gameId}&playerId=${playerId}`;
|
|
|
|
// Get the game container element
|
|
const gameContainer = document.getElementById('game-container');
|
|
|
|
// Set the ws-connect attribute
|
|
gameContainer.setAttribute('ws-connect', wsUrl);
|
|
|
|
// Tell HTMX to connect the WebSocket
|
|
htmx.trigger(gameContainer, ' and connect');
|
|
|
|
// Update the game link input
|
|
const gameLinkInput = document.getElementById('game-link');
|
|
if (!gameLinkInput) {
|
|
console.error('Missing game-link element.');
|
|
}
|
|
gameLinkInput.value =
|
|
window.location.origin + window.location.pathname + `?gameId=${gameId}`;
|
|
|
|
// Update the WebSocket status indicator
|
|
const wsStatusDiv = document.getElementById('ws-status');
|
|
|
|
gameContainer.addEventListener('htmx:wsClose', function () {
|
|
if (wsStatusDiv) wsStatusDiv.textContent = 'Disconnected';
|
|
});
|
|
|
|
gameContainer.addEventListener('htmx:wsError', function () {
|
|
if (wsStatusDiv) wsStatusDiv.textContent = 'Connection Error';
|
|
});
|