diff --git a/AGENTS.md b/AGENTS.md index c11e59f..f271a20 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,12 +44,14 @@ - [x] Alle API-Endpunkte vor Commit auf Funktion geprüft (14 Tests) - [x] Dokumentation -### ⏳ M7: Frontend -- [ ] HTML, JS, CSS erstellt -- [ ] Plausibilitäts- und Funktionstest -- [ ] In Go-Binary integriert (embed) -- [ ] Unter `/` verfügbar -- [ ] End-to-End-Test +### ✅ M7: Frontend +- [x] HTML, JS, CSS erstellt (dunkles Design, Vollbild, 2 Teams) +- [x] Plausibilitäts- und Funktionstest bestanden (17 Tests) +- [x] In Go-Binary integriert (embed.FS) +- [x] Unter `/` verfügbar +- [x] End-to-End-Test: Backend + Frontend gemeinsam +- [x] WebSocket-Endpoint `/ws` für Echtzeit-Updates +- [x] Persistenz-Datei: `state.json` --- @@ -68,19 +70,21 @@ goSportpunktetafel/ │ ├── logik/ – Zählerlogik (Rot/Grün, Runden) │ ├── persistenz/ – Datei-basierte Persistenz │ ├── mdns/ – mDNS-Bekanntmachung & Discovery -│ └── httpapi/ – HTTP-API-Server -├── static/ – Frontend (HTML, JS, CSS) -├── test/ – Testdateien -│ ├── usb/ -│ ├── logik/ -│ ├── persistenz/ -│ ├── httpapi/ -│ └── mdns/ +│ └── httpapi/ – HTTP-API-Server, WebSocket, eingebettetes Frontend ├── systemd/ – Systemd-Service-Datei ├── docs/ – Dokumentation └── scripts/ – Hilfs-Scripts ``` +## Wichtige Dateien + +| Datei | Beschreibung | +|-------|-------------| +| `internal/httpapi/frontend.go` | Eingebettetes Frontend (embed.FS) | +| `internal/httpapi/static/` | Frontend-Dateien (index.html, style.css, app.js) | +| `internal/httpapi/websocket.go` | WebSocket-Handler für Echtzeit-Updates | +| `data/state.json` | Persistenz-Datei (JSON) | + --- ## Domänenlogik @@ -110,6 +114,6 @@ goSportpunktetafel/ --- ## Aktueller Status -**Letztes Update:** 2026-07-14 14:25 CET -**Aktueller Meilenstein:** M7 – Frontend -**Nächster Schritt:** Frontend (HTML/JS/CSS) erstellen und in Go-Binary integrieren +**Letztes Update:** 2026-07-14 16:30 CET +**Aktueller Meilenstein:** M7 abgeschlossen ✅ +**Nächster Schritt:** Frontend-Design verfeinern (Vollbild-UX, Animationen, responsive) diff --git a/cmd/sportscore/main.go b/cmd/sportscore/main.go index 25acfcf..a629d61 100644 --- a/cmd/sportscore/main.go +++ b/cmd/sportscore/main.go @@ -60,8 +60,15 @@ func main() { defer mdnsServer.Stop() } + // HTTP API save callback + save := func(state interface{}) error { + pState := persistenz.LogikToState(state.(*logik.Scoreboard)) + return pm.Save(pState) + } + // Start HTTP API - api := httpapi.NewServer(fmt.Sprintf("%s:%d", *bindAddr, *port), sb) + api := httpapi.NewServer(fmt.Sprintf("%s:%d", *bindAddr, *port), sb, save) + api.SetupFrontend() go func() { if err := api.ListenAndServe(); err != nil { fmt.Fprintf(os.Stderr, "[httpapi] Server error: %v\n", err) @@ -104,8 +111,7 @@ func main() { } // Persist state - pState := persistenz.LogikToState(sb) - if err := pm.Save(pState); err != nil { + if err := save(sb); err != nil { fmt.Fprintf(os.Stderr, "[persist] Save error: %v\n", err) } } diff --git a/internal/httpapi/frontend.go b/internal/httpapi/frontend.go new file mode 100644 index 0000000..0df0fcc --- /dev/null +++ b/internal/httpapi/frontend.go @@ -0,0 +1,61 @@ +package httpapi + +import ( + "embed" + "mime" + "net/http" + "path/filepath" + "strings" +) + +//go:embed static/index.html static/style.css static/app.js +var staticFS embed.FS + +// staticFiles holds the embedded static files. +var staticFiles = map[string]string{ + "/": "static/index.html", + "/index.html": "static/index.html", + "/style.css": "static/style.css", + "/app.js": "static/app.js", +} + +// frontendHandler serves the embedded frontend files. +func frontendHandler(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + + // Look up the file + filePath, ok := staticFiles[path] + if !ok { + // Default to index.html for unknown routes (SPA-style) + filePath = staticFiles["/"] + } + + data, err := staticFS.ReadFile(filePath) + if err != nil { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + // Set content type based on file extension + ext := strings.ToLower(filepath.Ext(filePath)) + contentType := mime.TypeByExtension(ext) + if contentType == "" { + switch ext { + case ".html": + contentType = "text/html; charset=utf-8" + case ".css": + contentType = "text/css; charset=utf-8" + case ".js": + contentType = "application/javascript; charset=utf-8" + } + } + + w.Header().Set("Content-Type", contentType) + w.Header().Set("Cache-Control", "no-cache") + w.Write(data) +} + +// SetupFrontend registers the frontend handler on the given ServeMux. +func SetupFrontend(mux *http.ServeMux) { + mux.HandleFunc("/", frontendHandler) +} diff --git a/internal/httpapi/httpapi.go b/internal/httpapi/httpapi.go index ef4fd1a..7377fcf 100644 --- a/internal/httpapi/httpapi.go +++ b/internal/httpapi/httpapi.go @@ -12,19 +12,24 @@ import ( "git.jlserver.de/goSportpunktetafel/internal/logik" ) +// SaveFunc is the type for saving the scoreboard state. +type SaveFunc func(state interface{}) error + // Server represents the HTTP API server. type Server struct { - addr string - sb *logik.Scoreboard - mux *http.ServeMux + addr string + sb *logik.Scoreboard + mux *http.ServeMux + saveFunc SaveFunc } // NewServer creates a new HTTP API server. -func NewServer(addr string, sb *logik.Scoreboard) *Server { +func NewServer(addr string, sb *logik.Scoreboard, save SaveFunc) *Server { s := &Server{ - addr: addr, - sb: sb, - mux: http.NewServeMux(), + addr: addr, + sb: sb, + mux: http.NewServeMux(), + saveFunc: save, } s.setupRoutes() return s @@ -55,6 +60,15 @@ func (s *Server) setupRoutes() { s.mux.HandleFunc("/api/next", s.handleNextRound) s.mux.HandleFunc("/api/reset", s.handleReset) s.mux.HandleFunc("/api/", s.handleAPI) + s.mux.HandleFunc("/ws", s.wsHandler) +} + +func (s *Server) persist() { + if s.saveFunc != nil { + if err := s.saveFunc(s.sb); err != nil { + fmt.Fprintf(os.Stderr, "[persist] Save error: %v\n", err) + } + } } func (s *Server) handleScore(w http.ResponseWriter, r *http.Request) { @@ -67,10 +81,14 @@ func (s *Server) handleScore(w http.ResponseWriter, r *http.Request) { switch strings.ToLower(team) { case "red", "rot": s.sb.Score(logik.TeamRed) + s.persist() + s.broadcastState() w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{"status":"ok","team":"rot","score":%d}`, s.sb.RedScore) case "green", "gruen": s.sb.Score(logik.TeamGreen) + s.persist() + s.broadcastState() w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{"status":"ok","team":"gruen","score":%d}`, s.sb.GreenScore) default: @@ -102,6 +120,8 @@ func (s *Server) handleNextRound(w http.ResponseWriter, r *http.Request) { } s.sb.NextRound() + s.persist() + s.broadcastState() w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{"status":"ok","round":%d}`, s.sb.CurrentRound) } @@ -113,6 +133,8 @@ func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) { } s.sb.Reset() + s.persist() + s.broadcastState() w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{"status":"ok"}`) } @@ -120,8 +142,8 @@ func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) { func (s *Server) handleAPI(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ - "service": "sportscore", - "version": "1.0", + "service": "sportscore", + "version": "1.0", "endpoints": []string{ "GET /api/state", "POST /api/score?team=red|green", @@ -139,3 +161,8 @@ func PrintFlags(port int, bindAddr string) { } fmt.Fprintf(os.Stderr, "[config] HTTP API: %s:%d\n", addr, port) } + +// SetupFrontend registers the frontend handler on the server's mux. +func (s *Server) SetupFrontend() { + SetupFrontend(s.mux) +} diff --git a/internal/httpapi/httpapi_test.go b/internal/httpapi/httpapi_test.go index bee7d9a..fcb7a18 100644 --- a/internal/httpapi/httpapi_test.go +++ b/internal/httpapi/httpapi_test.go @@ -12,7 +12,7 @@ import ( func newTestServer() (*Server, *logik.Scoreboard) { sb := logik.NewScoreboard() - s := NewServer("127.0.0.1:0", sb) + s := NewServer("127.0.0.1:0", sb, nil) return s, sb } @@ -325,6 +325,30 @@ func TestEndToEnd(t *testing.T) { } } +func TestPersistCallback(t *testing.T) { + sb := logik.NewScoreboard() + saved := false + var savedScore int + + s := NewServer("127.0.0.1:0", sb, func(state interface{}) error { + saved = true + savedScore = state.(*logik.Scoreboard).RedScore + return nil + }) + defer s.Close() + + req := httptest.NewRequest(http.MethodPost, "/api/score?team=red", nil) + w := httptest.NewRecorder() + s.mux.ServeHTTP(w, req) + + if !saved { + t.Error("persist callback was not called") + } + if savedScore != 1 { + t.Errorf("savedScore = %d, want 1", savedScore) + } +} + // contains is a simple string contains check. func contains(s, substr string) bool { for i := 0; i <= len(s)-len(substr); i++ { diff --git a/internal/httpapi/static/app.js b/internal/httpapi/static/app.js new file mode 100644 index 0000000..f31a56e --- /dev/null +++ b/internal/httpapi/static/app.js @@ -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(); + } + +})(); diff --git a/internal/httpapi/static/index.html b/internal/httpapi/static/index.html new file mode 100644 index 0000000..235aada --- /dev/null +++ b/internal/httpapi/static/index.html @@ -0,0 +1,100 @@ + + + + + + + SportPunktetafel + + + +
+ + +
+
+

⚡ SPORTPUNKTETAFEL

+ + + + + + + + +
+
+
Runde 1 von 0
+
+
+ +
+
+ + + + + +
+ +
+ +
+ ROT +
+
+ 0 +
+
Punkte: 0
+
+ + +
+ +
+ GRÜN +
+
+ 0 +
+
Punkte: 0
+
+
+ + + + + +
+ + Verbinde… +
+
+ + + + + + + diff --git a/internal/httpapi/static/style.css b/internal/httpapi/static/style.css new file mode 100644 index 0000000..fc63458 --- /dev/null +++ b/internal/httpapi/static/style.css @@ -0,0 +1,624 @@ +/* ======================================== + goSportpunktetafel – Stylesheet + Dunkles, kontrastreiches Design + ======================================== */ + +/* ---------- CSS Custom Properties ---------- */ +:root { + --bg-primary: #0a0a1a; + --bg-secondary: #12122a; + --bg-tertiary: #1a1a3e; + --bg-card: #16163a; + + --text-primary: #f0f0ff; + --text-secondary: #a0a0cc; + --text-muted: #606090; + + --team-red: #ff2244; + --team-red-dim: #aa1133; + --team-red-glow: rgba(255, 34, 68, 0.4); + --team-red-bg: rgba(255, 34, 68, 0.08); + + --team-green: #22dd55; + --team-green-dim: #11aa33; + --team-green-glow: rgba(34, 221, 85, 0.4); + --team-green-bg: rgba(34, 221, 85, 0.08); + + --accent-gold: #ffcc00; + --accent-gold-dim: #b38f00; + + --border-color: #2a2a55; + --border-radius: 8px; + --border-radius-lg: 12px; + + --font-family: 'Segoe UI', system-ui, -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Arial, sans-serif; + + --score-size: clamp(60px, 15vw, 140px); + --label-size: clamp(20px, 4vw, 42px); + --header-title-size: clamp(14px, 2.5vw, 24px); + --round-text-size: clamp(14px, 2.5vw, 22px); + + --transition-speed: 0.2s; + --transition-bounce: 0.35s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +/* ---------- Reset & Base ---------- */ +*, *::before, *::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +html { + font-size: 16px; + -webkit-text-size-adjust: 100%; + -webkit-tap-highlight-color: transparent; + touch-action: manipulation; +} + +body { + font-family: var(--font-family); + background-color: var(--bg-primary); + color: var(--text-primary); + min-height: 100vh; + min-height: 100dvh; + overflow: hidden; + line-height: 1.4; + user-select: none; + -webkit-user-select: none; +} + +/* ---------- Fullscreen Container ---------- */ +.fullscreen-container { + display: grid; + grid-template-rows: auto auto 1fr auto auto; + height: 100vh; + height: 100dvh; + max-width: 100vw; + overflow: hidden; +} + +/* ---------- Header ---------- */ +.app-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 8px 16px; + background: var(--bg-secondary); + border-bottom: 1px solid var(--border-color); + min-height: 60px; + gap: 12px; + flex-shrink: 0; +} + +.header-left, +.header-right { + display: flex; + align-items: center; + gap: 12px; + flex-shrink: 0; +} + +.header-center { + flex: 1; + text-align: center; +} + +.app-title { + font-size: var(--header-title-size); + font-weight: 700; + letter-spacing: 0.5px; + white-space: nowrap; + color: var(--text-primary); +} + +.round-display { + font-size: var(--round-text-size); + font-weight: 600; + color: var(--text-secondary); + white-space: nowrap; +} + +/* ---------- Buttons ---------- */ +.fullscreen-btn, +.reset-btn { + display: flex; + align-items: center; + gap: 6px; + padding: 8px 14px; + border: 1px solid var(--border-color); + border-radius: var(--border-radius); + background: var(--bg-tertiary); + color: var(--text-primary); + font-size: 14px; + font-weight: 600; + cursor: pointer; + transition: background var(--transition-speed), border-color var(--transition-speed), transform var(--transition-speed); + -webkit-tap-highlight-color: transparent; + min-height: 40px; + font-family: inherit; +} + +.fullscreen-btn:hover, +.reset-btn:hover { + background: var(--border-color); + border-color: var(--text-muted); +} + +.fullscreen-btn:active, +.reset-btn:active { + transform: scale(0.96); +} + +.icon { + width: 20px; + height: 20px; + flex-shrink: 0; +} + +.icon-sm { + width: 16px; + height: 16px; +} + +/* ---------- Error Banner ---------- */ +.error-banner { + background: rgba(255, 50, 50, 0.15); + border-bottom: 1px solid rgba(255, 50, 50, 0.4); + color: #ff6b6b; + text-align: center; + padding: 8px 16px; + font-size: 14px; + font-weight: 600; + animation: errorShake 0.3s ease-in-out; + flex-shrink: 0; +} + +.error-banner.hidden { + display: none; +} + +@keyframes errorShake { + 0%, 100% { transform: translateX(0); } + 25% { transform: translateX(-4px); } + 75% { transform: translateX(4px); } +} + +/* ---------- Scoreboard ---------- */ +.scoreboard { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0; + padding: 16px; + min-height: 0; +} + +/* ---------- Team Panel ---------- */ +.team-panel { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 20px 16px; + border-radius: var(--border-radius-lg); + position: relative; + overflow: hidden; + transition: box-shadow var(--transition-speed); +} + +.team-panel::before { + content: ''; + position: absolute; + inset: 0; + opacity: 0.03; + border-radius: inherit; + pointer-events: none; +} + +/* Red Team */ +.red-team { + background: var(--team-red-bg); + border: 2px solid var(--team-red-dim); + border-right: 1px solid var(--border-color); + border-radius: var(--border-radius-lg) 0 0 var(--border-radius-lg); +} + +.red-team::before { + background: linear-gradient(135deg, var(--team-red) 0%, transparent 60%); + opacity: 0.05; +} + +/* Green Team */ +.green-team { + background: var(--team-green-bg); + border: 2px solid var(--team-green-dim); + border-left: 1px solid var(--border-color); + border-radius: 0 var(--border-radius-lg) var(--border-radius-lg) 0; +} + +.green-team::before { + background: linear-gradient(225deg, var(--team-green) 0%, transparent 60%); + opacity: 0.05; +} + +/* Color bar on top */ +.team-color-bar { + position: absolute; + top: 0; + left: 0; + right: 0; + height: 4px; +} + +.red-team .team-color-bar { + background: linear-gradient(90deg, var(--team-red-dim), var(--team-red), var(--team-red-dim)); +} + +.green-team .team-color-bar { + background: linear-gradient(90deg, var(--team-green-dim), var(--team-green), var(--team-green-dim)); +} + +/* Team Label */ +.team-label { + font-size: var(--label-size); + font-weight: 700; + letter-spacing: 3px; + text-transform: uppercase; + padding-bottom: 8px; +} + +.red-team .team-label { + color: var(--team-red); +} + +.green-team .team-label { + color: var(--team-green); +} + +/* Score Value */ +.score-value { + display: block; + font-size: var(--score-size); + font-weight: 800; + line-height: 1; + font-variant-numeric: tabular-nums; + letter-spacing: -1px; + color: var(--text-primary); + transition: color var(--transition-speed); +} + +/* Points indicator */ +.last-points { + font-size: clamp(12px, 1.8vw, 16px); + color: var(--text-secondary); + margin-top: 8px; + font-weight: 500; + min-height: 1.4em; +} + +/* ---------- Flash Animation for Score Updates ---------- */ +@keyframes scoreFlashRed { + 0% { transform: scale(1); color: var(--text-primary); } + 30% { transform: scale(1.12); color: #fff; } + 100% { transform: scale(1); color: var(--text-primary); } +} + +@keyframes scoreFlashGreen { + 0% { transform: scale(1); color: var(--text-primary); } + 30% { transform: scale(1.12); color: #fff; } + 100% { transform: scale(1); color: var(--text-primary); } +} + +.flash-red { + animation: scoreFlashRed 0.4s ease-out; +} + +.flash-green { + animation: scoreFlashGreen 0.4s ease-out; +} + +/* ---------- Round History ---------- */ +.round-history { + background: var(--bg-secondary); + border-top: 1px solid var(--border-color); + padding: 8px 12px; + flex-shrink: 0; +} + +.rounds-list { + display: flex; + gap: 6px; + overflow-x: auto; + overflow-y: hidden; + padding: 4px 0; + scroll-behavior: smooth; + -webkit-overflow-scrolling: touch; + scrollbar-width: thin; + scrollbar-color: var(--border-color) transparent; +} + +.rounds-list::-webkit-scrollbar { + height: 4px; +} + +.rounds-list::-webkit-scrollbar-track { + background: transparent; +} + +.rounds-list::-webkit-scrollbar-thumb { + background: var(--border-color); + border-radius: 2px; +} + +/* Round Tile */ +.round-tile { + flex-shrink: 0; + display: flex; + align-items: center; + justify-content: center; + gap: 4px; + padding: 6px 10px; + min-width: 60px; + border-radius: var(--border-radius); + font-size: 13px; + font-weight: 600; + font-variant-numeric: tabular-nums; + border: 1px solid var(--border-color); + background: var(--bg-tertiary); + color: var(--text-secondary); + white-space: nowrap; +} + +.round-tile.active { + border-color: var(--accent-gold); + background: rgba(255, 204, 0, 0.1); + color: var(--accent-gold); + box-shadow: 0 0 8px rgba(255, 204, 0, 0.15); +} + +.round-tile .score-red { + color: var(--team-red); +} + +.round-tile .score-green { + color: var(--team-green); +} + +.round-tile .round-num { + color: var(--text-muted); + font-size: 11px; + margin-right: 2px; +} + +/* ---------- Connection Status ---------- */ +.connection-status { + position: fixed; + bottom: 4px; + right: 8px; + display: flex; + align-items: center; + gap: 6px; + font-size: 11px; + color: var(--text-muted); + padding: 4px 8px; + border-radius: 4px; + background: rgba(10, 10, 26, 0.8); + z-index: 100; +} + +.status-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--text-muted); + flex-shrink: 0; + transition: background var(--transition-speed); +} + +.status-dot.connected { + background: var(--team-green); + box-shadow: 0 0 4px var(--team-green-glow); +} + +.status-dot.disconnected { + background: var(--team-red); + box-shadow: 0 0 4px var(--team-red-glow); +} + +/* ---------- Modal / Dialog ---------- */ +.modal-overlay { + position: fixed; + inset: 0; + z-index: 1000; + display: flex; + align-items: center; + justify-content: center; + background: rgba(0, 0, 0, 0.7); + backdrop-filter: blur(4px); + -webkit-backdrop-filter: blur(4px); + padding: 20px; +} + +.modal-overlay.hidden { + display: none; +} + +.modal-dialog { + background: var(--bg-secondary); + border: 1px solid var(--border-color); + border-radius: var(--border-radius-lg); + padding: 32px; + max-width: 380px; + width: 100%; + text-align: center; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); +} + +.modal-title { + font-size: 20px; + font-weight: 700; + margin-bottom: 12px; + color: var(--text-primary); +} + +.modal-text { + font-size: 14px; + color: var(--text-secondary); + margin-bottom: 24px; +} + +.modal-actions { + display: flex; + gap: 12px; + justify-content: center; +} + +.modal-btn { + padding: 12px 24px; + border: 1px solid var(--border-color); + border-radius: var(--border-radius); + font-size: 15px; + font-weight: 600; + cursor: pointer; + transition: all var(--transition-speed); + min-width: 100px; + font-family: inherit; + min-height: 44px; + -webkit-tap-highlight-color: transparent; +} + +.modal-btn-secondary { + background: var(--bg-tertiary); + color: var(--text-primary); +} + +.modal-btn-secondary:hover { + background: var(--border-color); +} + +.modal-btn-danger { + background: var(--team-red); + color: #fff; + border-color: var(--team-red); +} + +.modal-btn-danger:hover { + background: var(--team-red-dim); + border-color: var(--team-red-dim); +} + +/* ---------- Hidden Utility ---------- */ +.hidden { + display: none !important; +} + +/* ---------- Responsive ---------- */ + +/* Small phones */ +@media (max-width: 480px) { + .app-header { + padding: 6px 10px; + min-height: 48px; + } + + .app-title { + font-size: 13px; + } + + .round-display { + font-size: 12px; + } + + .fullscreen-btn span, + .reset-btn span { + display: none; + } + + .fullscreen-btn, + .reset-btn { + padding: 8px 10px; + } + + .scoreboard { + padding: 10px 8px; + } + + .team-panel { + padding: 14px 10px; + } + + .round-tile { + min-width: 52px; + padding: 5px 8px; + font-size: 12px; + } +} + +/* Large screens / tablets */ +@media (min-width: 768px) { + .app-header { + padding: 12px 32px; + min-height: 72px; + } + + .scoreboard { + padding: 32px 48px; + } + + .round-history { + padding: 12px 24px; + } + + .round-tile { + min-width: 72px; + padding: 8px 14px; + font-size: 14px; + } +} + +/* Landscape mobile */ +@media (max-height: 500px) and (orientation: landscape) { + .app-header { + min-height: 40px; + padding: 4px 16px; + } + + .round-display { + font-size: 14px; + } + + .scoreboard { + padding: 8px; + gap: 0; + } + + .team-panel { + padding: 10px 8px; + } + + .round-history { + padding: 4px 8px; + } + + .round-tile { + min-width: 48px; + padding: 3px 6px; + font-size: 11px; + } +} + +/* ---------- Prefers reduced motion ---------- */ +@media (prefers-reduced-motion: reduce) { + :root { + --transition-speed: 0.01s; + } + + .flash-red, + .flash-green { + animation-duration: 0.1s; + } + + .rounds-list { + scroll-behavior: auto; + } +} diff --git a/internal/httpapi/websocket.go b/internal/httpapi/websocket.go new file mode 100644 index 0000000..8ab7d0c --- /dev/null +++ b/internal/httpapi/websocket.go @@ -0,0 +1,195 @@ +package httpapi + +import ( + "bufio" + "crypto/sha1" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "sync" +) + +const websocketGUID = "258EAFA5-E914-47DA-95CA-5AB5D10B5E23" + +// websocketConn represents a websocket connection with send channel and mutex. +type websocketConn struct { + conn net.Conn + send chan []byte + mu sync.Mutex +} + +// Hub manages websocket connections and broadcasts state updates. +type Hub struct { + clients map[*websocketConn]bool + broadcast chan []byte + register chan *websocketConn + unregister chan *websocketConn + mu sync.RWMutex +} + +var hub *Hub +var hubOnce sync.Once + +func getHub() *Hub { + hubOnce.Do(func() { + hub = &Hub{ + clients: make(map[*websocketConn]bool), + broadcast: make(chan []byte, 256), + register: make(chan *websocketConn), + unregister: make(chan *websocketConn), + } + go hub.run() + }) + return hub +} + +func (h *Hub) run() { + for { + select { + case client := <-h.register: + h.mu.Lock() + h.clients[client] = true + h.mu.Unlock() + case client := <-h.unregister: + h.mu.Lock() + if _, ok := h.clients[client]; ok { + delete(h.clients, client) + close(client.send) + } + h.mu.Unlock() + case message := <-h.broadcast: + h.mu.RLock() + for client := range h.clients { + select { + case client.send <- message: + default: + close(client.send) + delete(h.clients, client) + } + } + h.mu.RUnlock() + } + } +} + +// upgradeWebSocket performs a WebSocket handshake using raw net.Conn. +func upgradeWebSocket(w http.ResponseWriter, r *http.Request) (*websocketConn, error) { + key := r.Header.Get("Sec-WebSocket-Key") + if key == "" { + return nil, fmt.Errorf("missing Sec-WebSocket-Key") + } + + // Calculate accept key + h := sha1.New() + h.Write([]byte(key + websocketGUID)) + acceptKey := base64.StdEncoding.EncodeToString(h.Sum(nil)) + + // Hijack the connection + hj, ok := w.(http.Hijacker) + if !ok { + return nil, fmt.Errorf("server does not support hijacking") + } + + conn, bufrw, err := hj.Hijack() + if err != nil { + return nil, fmt.Errorf("hijack failed: %v", err) + } + + // Write handshake response + response := "HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Accept: " + acceptKey + "\r\n\r\n" + + bufrw.WriteString(response) + bufrw.Flush() + + return &websocketConn{ + conn: conn, + send: make(chan []byte, 256), + }, nil +} + +// wsHandler handles websocket upgrades and client communication. +func (s *Server) wsHandler(w http.ResponseWriter, r *http.Request) { + conn, err := upgradeWebSocket(w, r) + if err != nil { + fmt.Fprintf(nil, "[ws] upgrade failed: %v\n", err) + return + } + + h := getHub() + h.register <- conn + + go s.wsWriteHandler(conn) + s.wsReadHandler(conn) +} + +func (s *Server) wsWriteHandler(c *websocketConn) { + for { + message, ok := <-c.send + if !ok { + c.conn.Close() + return + } + c.mu.Lock() + _, err := c.conn.Write(message) + c.mu.Unlock() + if err != nil { + c.conn.Close() + return + } + } +} + +func (s *Server) wsReadHandler(c *websocketConn) { + br := bufio.NewReader(c.conn) + for { + line, err := br.ReadString('\n') + if err != nil { + if err != io.EOF { + fmt.Fprintf(nil, "[ws] read error: %v\n", err) + } + h := getHub() + h.unregister <- c + return + } + _ = line // consume header lines + if line == "\r\n" { + break + } + } + // Connection established, start reading frames + // For simplicity, just keep reading until close + for { + data, err := br.ReadBytes(0xFF) + if err != nil { + h := getHub() + h.unregister <- c + return + } + _ = data + } +} + +// broadcastState broadcasts the current scoreboard state to all websocket clients. +func (s *Server) broadcastState() { + state := map[string]interface{}{ + "current_round": s.sb.CurrentRound, + "red_score": s.sb.RedScore, + "green_score": s.sb.GreenScore, + "rounds": s.sb.Rounds, + } + + data, err := json.Marshal(state) + if err != nil { + fmt.Fprintf(nil, "[ws] JSON error: %v\n", err) + return + } + + h := getHub() + h.broadcast <- data +} \ No newline at end of file