M7: Frontend - HTML/JS/CSS mit dunklem Design, Vollbild, WebSocket-Updates, embed.FS-Integration
- Frontend: index.html, style.css, app.js - Dunkles Kontrast-Design mit Team-Farben (Rot/Grün) - Vollbild-Toggle, Responsive Design - Echtzeit-Updates über WebSocket + Polling-Fallback - Tastatur-Shortcuts (R/G für Punkte, N für nächste Runde) - Rundenverlauf mit Farbcodierung - Go-Integration: - frontend.go: embed.FS für statische Dateien - websocket.go: WebSocket-Handler (/ws) für State-Broadcast - httpapi.go: broadcastState() nach jeder Mutation, /ws-Route - main.go: api.SetupFrontend() für Frontend-Einbettung - Frontend unter '/' verfügbar, API unter '/api/' - Tests: 17 End-to-End-Tests bestanden - Alle HTTP-Endpunkte funktionsfähig - Frontend-Assets korrekt eingebettet - Persistenz (state.json) funktioniert
This commit is contained in:
@@ -0,0 +1,598 @@
|
||||
/**
|
||||
* goSportpunktetafel – Frontend JavaScript
|
||||
*
|
||||
* Verbindet sich mit der Go-HTTP-API (Polling + WebSocket-Fallback)
|
||||
* und aktualisiert die Anzeige in Echtzeit.
|
||||
*/
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// ========================================
|
||||
// Konfiguration
|
||||
// ========================================
|
||||
const CONFIG = {
|
||||
apiBase: 'http://localhost:3000',
|
||||
pollingInterval: 2000, // ms
|
||||
wsUrl: 'ws://localhost:3000/ws',
|
||||
wsReconnectDelay: 3000, // ms
|
||||
wsMaxReconnectDelay: 30000,
|
||||
};
|
||||
|
||||
// ========================================
|
||||
// DOM-Elemente
|
||||
// ========================================
|
||||
const dom = {
|
||||
redScore: document.getElementById('red-score'),
|
||||
greenScore: document.getElementById('green-score'),
|
||||
roundDisplay: document.getElementById('round-display'),
|
||||
redPoints: document.getElementById('red-points'),
|
||||
greenPoints: document.getElementById('green-points'),
|
||||
roundsList: document.getElementById('rounds-list'),
|
||||
errorBanner: document.getElementById('error-banner'),
|
||||
errorMessage: document.getElementById('error-message'),
|
||||
resetBtn: document.getElementById('reset-btn'),
|
||||
fullscreenToggle: document.getElementById('fullscreen-toggle'),
|
||||
statusDot: document.getElementById('status-dot'),
|
||||
statusText: document.getElementById('status-text'),
|
||||
confirmDialog: document.getElementById('confirm-dialog'),
|
||||
cancelReset: document.getElementById('cancel-reset'),
|
||||
confirmReset: document.getElementById('confirm-reset'),
|
||||
redPanel: document.getElementById('red-panel'),
|
||||
greenPanel: document.getElementById('green-panel'),
|
||||
};
|
||||
|
||||
// ========================================
|
||||
// State
|
||||
// ========================================
|
||||
let state = {
|
||||
current_round: 0,
|
||||
red_score: 0,
|
||||
green_score: 0,
|
||||
rounds: [],
|
||||
};
|
||||
|
||||
// Vorheriger State für Flash-Animation
|
||||
let prevState = { ...state };
|
||||
|
||||
// Polling / WebSocket
|
||||
let pollingTimer = null;
|
||||
let ws = null;
|
||||
let wsReconnectTimer = null;
|
||||
let wsReconnectAttempts = 0;
|
||||
let isConnected = false;
|
||||
let useWebSocket = false;
|
||||
|
||||
// ========================================
|
||||
// API-Funktionen
|
||||
// ========================================
|
||||
|
||||
/**
|
||||
* State von der API abrufen
|
||||
*/
|
||||
async function fetchState() {
|
||||
try {
|
||||
const response = await fetch(`${CONFIG.apiBase}/api/state`, {
|
||||
method: 'GET',
|
||||
headers: { 'Accept': 'application/json' },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Fehler beim Abrufen des States:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Punkt für ein Team verbuchen
|
||||
*/
|
||||
async function postScore(team) {
|
||||
try {
|
||||
const response = await fetch(`${CONFIG.apiBase}/api/score?team=${team}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`Fehler bei /api/score?team=${team}:`, error);
|
||||
showError(`Punkt für ${team} fehlgeschlagen`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Nächste Runde
|
||||
*/
|
||||
async function postNext() {
|
||||
try {
|
||||
const response = await fetch(`${CONFIG.apiBase}/api/next`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('Fehler bei /api/next:', error);
|
||||
showError('Nächste Runde fehlgeschlagen');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset
|
||||
*/
|
||||
async function postReset() {
|
||||
try {
|
||||
const response = await fetch(`${CONFIG.apiBase}/api/reset`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('Fehler bei /api/reset:', error);
|
||||
showError('Reset fehlgeschlagen');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// UI-Aktualisierung
|
||||
// ========================================
|
||||
|
||||
/**
|
||||
* State in der UI anzeigen
|
||||
*/
|
||||
function renderState(newState) {
|
||||
const wasConnected = isConnected;
|
||||
|
||||
// State aktualisieren
|
||||
prevState = { ...state };
|
||||
state = { ...newState };
|
||||
|
||||
// Red Score
|
||||
const redScoreEl = dom.redScore;
|
||||
const redScoreStr = String(newState.red_score);
|
||||
if (redScoreEl.textContent !== redScoreStr) {
|
||||
redScoreEl.textContent = redScoreStr;
|
||||
|
||||
// Flash-Animation wenn sich der Score geändert hat
|
||||
if (prevState.red_score !== newState.red_score) {
|
||||
triggerFlash(dom.redPanel, 'flash-red');
|
||||
}
|
||||
}
|
||||
|
||||
// Green Score
|
||||
const greenScoreEl = dom.greenScore;
|
||||
const greenScoreStr = String(newState.green_score);
|
||||
if (greenScoreEl.textContent !== greenScoreStr) {
|
||||
greenScoreEl.textContent = greenScoreStr;
|
||||
|
||||
if (prevState.green_score !== newState.green_score) {
|
||||
triggerFlash(dom.greenPanel, 'flash-green');
|
||||
}
|
||||
}
|
||||
|
||||
// Round Display
|
||||
const totalRounds = Math.max(state.rounds.length, state.current_round);
|
||||
if (totalRounds > 0) {
|
||||
dom.roundDisplay.textContent = `Runde ${state.current_round} von ${totalRounds}`;
|
||||
} else {
|
||||
dom.roundDisplay.textContent = 'Bereit';
|
||||
}
|
||||
|
||||
// Letzte Punkte Anzeige (aus letzter abgeschlossener Runde)
|
||||
if (newState.rounds && newState.rounds.length > 0) {
|
||||
const lastRound = newState.rounds[newState.rounds.length - 1];
|
||||
if (lastRound) {
|
||||
const redPts = lastRound.Red || lastRound.red_score || 0;
|
||||
const greenPts = lastRound.Green || lastRound.green_score || 0;
|
||||
dom.redPoints.textContent = `Letzte: ${redPts}`;
|
||||
dom.greenPoints.textContent = `Letzte: ${greenPts}`;
|
||||
}
|
||||
} else {
|
||||
dom.redPoints.textContent = 'Punkte: 0';
|
||||
dom.greenPoints.textContent = 'Punkte: 0';
|
||||
}
|
||||
|
||||
// Rundenverlauf
|
||||
renderRoundHistory(newState.rounds || []);
|
||||
|
||||
// Verbindung status aktualisieren
|
||||
if (!wasConnected && newState !== null) {
|
||||
isConnected = true;
|
||||
updateConnectionStatus(true);
|
||||
hideError();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rundenverlauf rendern
|
||||
*/
|
||||
function renderRoundHistory(rounds) {
|
||||
const container = dom.roundsList;
|
||||
container.innerHTML = '';
|
||||
|
||||
rounds.forEach(function (round, index) {
|
||||
const tile = document.createElement('div');
|
||||
tile.className = 'round-tile';
|
||||
tile.setAttribute('role', 'listitem');
|
||||
tile.setAttribute('data-round', index + 1);
|
||||
|
||||
// Runde als aktiv markieren wenn es die aktuelle ist
|
||||
if (index + 1 === state.current_round) {
|
||||
tile.classList.add('active');
|
||||
}
|
||||
|
||||
const roundNum = document.createElement('span');
|
||||
roundNum.className = 'round-num';
|
||||
roundNum.textContent = `R${index + 1}`;
|
||||
|
||||
const scoreRed = document.createElement('span');
|
||||
scoreRed.className = 'score-red';
|
||||
scoreRed.textContent = round.Red || round.red_score || 0;
|
||||
|
||||
const separator = document.createTextNode(' : ');
|
||||
|
||||
const scoreGreen = document.createElement('span');
|
||||
scoreGreen.className = 'score-green';
|
||||
scoreGreen.textContent = round.Green || round.green_score || 0;
|
||||
|
||||
tile.appendChild(roundNum);
|
||||
tile.appendChild(scoreRed);
|
||||
tile.appendChild(separator);
|
||||
tile.appendChild(scoreGreen);
|
||||
|
||||
container.appendChild(tile);
|
||||
});
|
||||
|
||||
// Zum letzten Element scrollen
|
||||
requestAnimationFrame(function () {
|
||||
container.scrollLeft = container.scrollWidth;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Flash-Animation für Score-Update
|
||||
*/
|
||||
function triggerFlash(panel, animationClass) {
|
||||
// Alte Animation entfernen
|
||||
panel.classList.remove(animationClass);
|
||||
|
||||
// Reflow erzwingen
|
||||
void panel.offsetWidth;
|
||||
|
||||
// Neue Animation starten
|
||||
panel.classList.add(animationClass);
|
||||
|
||||
// Animation nach Ablauf entfernen
|
||||
panel.addEventListener('animationend', function handler() {
|
||||
panel.classList.remove(animationClass);
|
||||
panel.removeEventListener('animationend', handler);
|
||||
}, { once: true });
|
||||
|
||||
// Fallback: Timeout nach Animation
|
||||
setTimeout(function () {
|
||||
panel.classList.remove(animationClass);
|
||||
}, 500);
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Fehler & Status
|
||||
// ========================================
|
||||
|
||||
function showError(message) {
|
||||
dom.errorMessage.textContent = message;
|
||||
dom.errorBanner.classList.remove('hidden');
|
||||
|
||||
// Nach 5 Sekunden automatisch ausblenden
|
||||
setTimeout(hideError, 5000);
|
||||
}
|
||||
|
||||
function hideError() {
|
||||
dom.errorBanner.classList.add('hidden');
|
||||
}
|
||||
|
||||
function updateConnectionStatus(connected) {
|
||||
if (connected) {
|
||||
dom.statusDot.className = 'status-dot connected';
|
||||
dom.statusText.textContent = useWebSocket ? 'Echtzeit' : 'Verbunden';
|
||||
} else {
|
||||
dom.statusDot.className = 'status-dot disconnected';
|
||||
dom.statusText.textContent = 'Getrennt';
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// WebSocket
|
||||
// ========================================
|
||||
|
||||
function connectWebSocket() {
|
||||
// Falls bereits verbunden, nichts tun
|
||||
if (ws && (ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
ws = new WebSocket(CONFIG.wsUrl);
|
||||
} catch (e) {
|
||||
console.warn('WebSocket nicht verfügbar, nutze Polling:', e);
|
||||
return;
|
||||
}
|
||||
|
||||
ws.onopen = function () {
|
||||
console.log('WebSocket verbunden');
|
||||
useWebSocket = true;
|
||||
isConnected = true;
|
||||
wsReconnectAttempts = 0;
|
||||
updateConnectionStatus(true);
|
||||
hideError();
|
||||
};
|
||||
|
||||
ws.onmessage = function (event) {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
renderState(data);
|
||||
} catch (e) {
|
||||
console.error('Fehler beim Verarbeiten der WebSocket-Nachricht:', e);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = function (event) {
|
||||
console.log(`WebSocket geschlossen (${event.code})`);
|
||||
useWebSocket = false;
|
||||
isConnected = false;
|
||||
updateConnectionStatus(false);
|
||||
scheduleWebSocketReconnect();
|
||||
};
|
||||
|
||||
ws.onerror = function () {
|
||||
console.warn('WebSocket-Fehler');
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleWebSocketReconnect() {
|
||||
if (wsReconnectTimer) {
|
||||
clearTimeout(wsReconnectTimer);
|
||||
}
|
||||
|
||||
// Exponentieller Backoff mit Maximalwert
|
||||
const delay = Math.min(
|
||||
CONFIG.wsReconnectDelay * Math.pow(2, wsReconnectAttempts),
|
||||
CONFIG.wsMaxReconnectDelay
|
||||
);
|
||||
|
||||
wsReconnectAttempts++;
|
||||
console.log(`WebSocket-Wiederverbindung in ${delay}ms (Versuch ${wsReconnectAttempts})`);
|
||||
|
||||
wsReconnectTimer = setTimeout(function () {
|
||||
connectWebSocket();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Polling
|
||||
// ========================================
|
||||
|
||||
function startPolling() {
|
||||
stopPolling();
|
||||
|
||||
// Sofortigen ersten Abruf
|
||||
poll();
|
||||
|
||||
pollingTimer = setInterval(poll, CONFIG.pollingInterval);
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollingTimer) {
|
||||
clearInterval(pollingTimer);
|
||||
pollingTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
const data = await fetchState();
|
||||
if (data) {
|
||||
renderState(data);
|
||||
} else {
|
||||
if (!useWebSocket) {
|
||||
updateConnectionStatus(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Vollbild
|
||||
// ========================================
|
||||
|
||||
function toggleFullscreen() {
|
||||
if (!document.fullscreenElement) {
|
||||
document.documentElement.requestFullscreen().catch(function (err) {
|
||||
console.warn('Vollbild konnte nicht aktiviert werden:', err);
|
||||
showError('Vollbild nicht verfügbar');
|
||||
});
|
||||
} else {
|
||||
document.exitFullscreen().catch(function (err) {
|
||||
console.warn('Vollbild konnte nicht deaktiviert werden:', err);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function updateFullscreenButton() {
|
||||
const isFullscreen = !!document.fullscreenElement;
|
||||
dom.fullscreenToggle.title = isFullscreen ? 'Vollbild verlassen (F11)' : 'Vollbild aktivieren (F11)';
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Reset-Dialog
|
||||
// ========================================
|
||||
|
||||
function showResetConfirm() {
|
||||
dom.confirmDialog.classList.remove('hidden');
|
||||
// Fokus auf Bestätigungs-Button setzen
|
||||
setTimeout(function () {
|
||||
dom.confirmReset.focus();
|
||||
}, 100);
|
||||
}
|
||||
|
||||
function hideResetConfirm() {
|
||||
dom.confirmDialog.classList.add('hidden');
|
||||
}
|
||||
|
||||
async function executeReset() {
|
||||
hideResetConfirm();
|
||||
const result = await postReset();
|
||||
if (result) {
|
||||
// State neu laden
|
||||
const data = await fetchState();
|
||||
if (data) {
|
||||
renderState(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Tastatur-Shortcuts
|
||||
// ========================================
|
||||
|
||||
function handleKeyboard(event) {
|
||||
// Nicht verarbeiten wenn Dialog offen ist (außer Escape)
|
||||
if (!dom.confirmDialog.classList.contains('hidden')) {
|
||||
if (event.key === 'Escape') {
|
||||
hideResetConfirm();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Esc: Reset-Dialog öffnen
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
showResetConfirm();
|
||||
return;
|
||||
}
|
||||
|
||||
// F11: Vollbild
|
||||
if (event.key === 'F11') {
|
||||
// Browser macht das normalerweise selbst, aber wir können den Button aktualisieren
|
||||
return;
|
||||
}
|
||||
|
||||
// Buchstabentasten (case-insensitive)
|
||||
const key = event.key.toUpperCase();
|
||||
|
||||
switch (key) {
|
||||
case 'R':
|
||||
event.preventDefault();
|
||||
postScore('red');
|
||||
break;
|
||||
case 'G':
|
||||
event.preventDefault();
|
||||
postScore('green');
|
||||
break;
|
||||
case 'N':
|
||||
event.preventDefault();
|
||||
postNext();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Initialisierung
|
||||
// ========================================
|
||||
|
||||
function init() {
|
||||
// Event Listener
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
// Initialen State laden
|
||||
poll();
|
||||
|
||||
// Polling starten
|
||||
startPolling();
|
||||
|
||||
// WebSocket versuchen (falls API WS unterstützt)
|
||||
connectWebSocket();
|
||||
|
||||
// Reset-Button
|
||||
dom.resetBtn.addEventListener('click', showResetConfirm);
|
||||
dom.cancelReset.addEventListener('click', hideResetConfirm);
|
||||
dom.confirmReset.addEventListener('click', executeReset);
|
||||
|
||||
// Dialog-Auflösen mit Klick auf Overlay
|
||||
dom.confirmDialog.addEventListener('click', function (event) {
|
||||
if (event.target === dom.confirmDialog) {
|
||||
hideResetConfirm();
|
||||
}
|
||||
});
|
||||
|
||||
// Vollbild-Toggle
|
||||
dom.fullscreenToggle.addEventListener('click', toggleFullscreen);
|
||||
|
||||
// Vollbild-Status-Update bei Änderungen
|
||||
document.addEventListener('fullscreenchange', updateFullscreenButton);
|
||||
document.addEventListener('webkitfullscreenchange', updateFullscreenButton);
|
||||
|
||||
// Tastatur-Shortcuts
|
||||
document.addEventListener('keydown', handleKeyboard);
|
||||
|
||||
// Touch-Bereiche für Score-Updates (große Touch-Targets)
|
||||
dom.redPanel.addEventListener('click', function () {
|
||||
postScore('red');
|
||||
});
|
||||
|
||||
dom.greenPanel.addEventListener('click', function () {
|
||||
postScore('green');
|
||||
});
|
||||
|
||||
// Double-click für nächste Runde
|
||||
dom.redPanel.addEventListener('dblclick', function (event) {
|
||||
event.stopPropagation();
|
||||
postNext();
|
||||
});
|
||||
|
||||
dom.greenPanel.addEventListener('dblclick', function (event) {
|
||||
event.stopPropagation();
|
||||
postNext();
|
||||
});
|
||||
|
||||
// Verbindung prüfen
|
||||
const testPoll = setInterval(function () {
|
||||
fetchState().then(function (data) {
|
||||
if (data) {
|
||||
clearInterval(testPoll);
|
||||
}
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
setTimeout(function () {
|
||||
clearInterval(testPoll);
|
||||
}, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
// App starten
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
|
||||
})();
|
||||
Reference in New Issue
Block a user