diff --git a/cmd/chessd/main.go b/cmd/chessd/main.go index 7411a37..86987ff 100644 --- a/cmd/chessd/main.go +++ b/cmd/chessd/main.go @@ -1,4 +1,3 @@ -// FILE: cmd/chessd/main.go package main import ( @@ -7,6 +6,7 @@ import ( "chess/internal/processor" "chess/internal/service" "chess/internal/storage" + "chess/internal/webserver" "flag" "fmt" "log" @@ -27,12 +27,18 @@ func main() { // Command-line flags var ( - host = flag.String("host", "localhost", "Server host") - port = flag.Int("port", 8080, "Server port") + // API server flags (renamed) + apiHost = flag.String("api-host", "localhost", "API server host") + apiPort = flag.Int("api-port", 8080, "API server port") dev = flag.Bool("dev", false, "Development mode (relaxed rate limits)") storagePath = flag.String("storage-path", "", "Path to SQLite database file (disables persistence if empty)") pidPath = flag.String("pid", "", "Optional path to write PID file") pidLock = flag.Bool("pid-lock", false, "Lock PID file to allow only one instance (requires -pid)") + + // Web UI server flags + serve = flag.Bool("serve", false, "Enable web UI server") + webHost = flag.String("web-host", "localhost", "Web UI server host") + webPort = flag.Int("web-port", 9090, "Web UI server port") ) flag.Parse() @@ -56,7 +62,7 @@ func main() { if *storagePath != "" { log.Printf("Initializing persistent storage at: %s", *storagePath) var err error - store, err = storage.NewStore(*storagePath, *dev) // CHANGED: Added *dev parameter + store, err = storage.NewStore(*storagePath, *dev) if err != nil { log.Fatalf("Failed to initialize storage: %v", err) } @@ -90,13 +96,13 @@ func main() { // 4. Initialize the Fiber App/HTTP Handler, injecting processor and service app := http.NewFiberApp(proc, svc, *dev) - // Server configuration - addr := fmt.Sprintf("%s:%d", *host, *port) + // API Server configuration + apiAddr := fmt.Sprintf("%s:%d", *apiHost, *apiPort) - // Start server in a goroutine + // Start API server in a goroutine go func() { log.Printf("Chess API Server starting...") - log.Printf("Listening on: http://%s", addr) + log.Printf("API Listening on: http://%s", apiAddr) log.Printf("API Version: v1") if *dev { log.Printf("Rate Limit: 20 requests/second per IP (DEV MODE)") @@ -108,26 +114,41 @@ func main() { } else { log.Printf("Storage: Disabled") } - log.Printf("Endpoints: http://%s/api/v1/games", addr) - log.Printf("Health: http://%s/health", addr) + log.Printf("API Endpoints: http://%s/api/v1/games", apiAddr) + log.Printf("Health: http://%s/health", apiAddr) - if err := app.Listen(addr); err != nil { - // This log often prints on graceful shutdown, which is normal. - log.Printf("Server listen error: %v", err) + if err := app.Listen(apiAddr); err != nil { + log.Printf("API server listen error: %v", err) } }() + // 5. Start Web UI server if requested + if *serve { + webAddr := fmt.Sprintf("%s:%d", *webHost, *webPort) + apiURL := fmt.Sprintf("http://%s", apiAddr) + + go func() { + log.Printf("Web UI Server starting...") + log.Printf("Web UI Listening on: http://%s", webAddr) + log.Printf("Web UI API target: %s", apiURL) + + if err := webserver.Start(*webHost, *webPort, apiURL); err != nil { + log.Printf("Web UI server error: %v", err) + } + }() + } + // Wait for an interrupt signal to gracefully shut down quit := make(chan os.Signal, 1) signal.Notify(quit, os.Interrupt, syscall.SIGTERM) <-quit - log.Println("Shutting down server...") + log.Println("Shutting down servers...") // Graceful shutdown with a timeout if err := app.ShutdownWithTimeout(5 * time.Second); err != nil { log.Printf("Server forced to shutdown: %v", err) } - log.Println("Server exited") + log.Println("Servers exited") } \ No newline at end of file diff --git a/internal/webserver/server.go b/internal/webserver/server.go new file mode 100644 index 0000000..877b6e3 --- /dev/null +++ b/internal/webserver/server.go @@ -0,0 +1,87 @@ +package webserver + +import ( + "embed" + "fmt" + "io/fs" + "strings" + "time" + + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/cors" + "github.com/gofiber/fiber/v2/middleware/logger" +) + +//go:embed web +var webFS embed.FS + +// Start initializes and starts the web UI server +func Start(host string, port int, apiURL string) error { + app := fiber.New(fiber.Config{ + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + IdleTimeout: 30 * time.Second, + }) + + // Middleware + app.Use(logger.New(logger.Config{ + Format: "${time} WEB ${status} ${method} ${path} ${latency}\n", + })) + app.Use(cors.New()) + + // Create a sub-filesystem that points to the 'web' directory + webContent, err := fs.Sub(webFS, "web") + if err != nil { + return fmt.Errorf("failed to create web sub-filesystem: %w", err) + } + + // API config endpoint, served before the static file handler + app.Get("/config", func(c *fiber.Ctx) error { + return c.JSON(fiber.Map{ + "apiUrl": apiURL, + }) + }) + + // Serve static files from the embedded 'web' directory + app.Get("*", func(c *fiber.Ctx) error { + path := c.Path() + + // Default to index.html for the root path + if path == "/" { + path = "/index.html" + } + + // The path for the embedded filesystem must not have a leading slash + fsPath := strings.TrimPrefix(path, "/") + + // Try to read the file + data, err := fs.ReadFile(webContent, fsPath) + if err != nil { + // If the file isn't found, serve index.html for SPA-style routing. + // This handles client-side routes that don't correspond to a file. + data, err = fs.ReadFile(webContent, "index.html") + if err != nil { + return c.Status(fiber.StatusInternalServerError).SendString("index.html not found") + } + c.Set("Content-Type", "text/html; charset=utf-8") + return c.Send(data) + } + + // Set the correct Content-Type based on file extension + contentType := "application/octet-stream" + switch { + case strings.HasSuffix(fsPath, ".html"): + contentType = "text/html; charset=utf-8" + case strings.HasSuffix(fsPath, ".js"): + contentType = "application/javascript; charset=utf-8" + case strings.HasSuffix(fsPath, ".css"): + contentType = "text/css; charset=utf-8" + } + c.Set("Content-Type", contentType) + + return c.Send(data) + }) + + addr := fmt.Sprintf("%s:%d", host, port) + return app.Listen(addr) +} \ No newline at end of file diff --git a/internal/webserver/web/app.js b/internal/webserver/web/app.js new file mode 100644 index 0000000..b3abb4d --- /dev/null +++ b/internal/webserver/web/app.js @@ -0,0 +1,615 @@ +// FILE: internal/webserver/web/app.js +// Game state management +let gameState = { + gameId: null, + fen: null, + turn: 'w', + isPlayerWhite: true, + isLocked: false, + pollInterval: null, + apiUrl: '', + selectedSquare: null, + healthCheckInterval: null, + networkError: false, + moveList: [], +}; + +// Chess piece Unicode +const pieceMap = { + 'p': '♙', 'r': '♜', 'n': '♞', 'b': '♝', 'q': '♛', 'k': '♚', + 'P': '♙', 'R': '♜', 'N': '♞', 'B': '♝', 'Q': '♛', 'K': '♚' +}; + +// Initialize on page load +document.addEventListener('DOMContentLoaded', async () => { + const config = await getConfig(); + gameState.apiUrl = config.apiUrl; + + document.getElementById('new-game-btn').addEventListener('click', showNewGameModal); + document.getElementById('undo-btn').addEventListener('click', undoMoves); + document.getElementById('start-game-btn').addEventListener('click', startNewGame); + document.getElementById('cancel-btn').addEventListener('click', hideNewGameModal); + document.getElementById('copy-fen').addEventListener('click', copyFEN); + document.getElementById('copy-history').addEventListener('click', copyHistory); + + const levelSlider = document.getElementById('computer-level'); + const levelValue = document.getElementById('level-value'); + levelSlider.addEventListener('input', () => { levelValue.textContent = levelSlider.value; }); + + const timeSlider = document.getElementById('search-time'); + const timeValue = document.getElementById('time-value'); + timeSlider.addEventListener('input', () => { timeValue.textContent = timeSlider.value; }); + + startHealthCheck(); + // Don't auto-show modal on load +}); + +async function getConfig() { + try { + const response = await fetch('/config'); + return await response.json(); + } catch (error) { + console.error('Failed to get config:', error); + return { apiUrl: 'http://localhost:8080' }; + } +} + +function startHealthCheck() { + const checkHealth = async () => { + try { + const response = await fetch(`${gameState.apiUrl}/health`); + if (response.ok) { + const health = await response.json(); + updateServerIndicator(health.status === 'healthy' ? 'healthy' : 'degraded'); + updateStorageIndicator(health.storage || 'unknown'); + gameState.networkError = false; + } else { + updateServerIndicator('degraded'); + updateStorageIndicator('unknown'); + } + } catch (error) { + updateServerIndicator('degraded'); + updateStorageIndicator('unknown'); + gameState.networkError = true; + } + }; + + checkHealth(); + gameState.healthCheckInterval = setInterval(checkHealth, 10000); +} + +function updateServerIndicator(status) { + const indicator = document.getElementById('server-indicator'); + const light = indicator.querySelector('.light'); + light.setAttribute('data-status', status); + indicator.setAttribute('data-status', status); +} + +function updateStorageIndicator(status) { + const indicator = document.getElementById('storage-indicator'); + const light = indicator.querySelector('.light'); + light.setAttribute('data-status', status); + indicator.setAttribute('data-status', status); +} + +function updateTurnIndicator(state, turn) { + const indicator = document.getElementById('turn-indicator'); + const light = indicator.querySelector('.light'); + + let status = ''; + let tooltip = 'Turn: '; + + if (gameState.networkError) { + status = 'network-error'; + tooltip += 'Network Error'; + } else if (state === 'pending' || gameState.isLocked) { + status = 'thinking'; + tooltip += 'Computer Thinking'; + } else if (state && isGameOver(state)) { + switch(state) { + case 'white wins': + status = 'white-wins'; + tooltip = 'White Wins'; + break; + case 'black wins': + status = 'black-wins'; + tooltip = 'Black Wins'; + break; + case 'stalemate': + status = 'stalemate'; + tooltip = 'Stalemate'; + break; + case 'draw': + status = 'draw'; + tooltip = 'Draw'; + break; + default: + status = 'unknown'; + tooltip = 'Game Over'; + } + } else if (turn === 'w') { + status = 'white'; + tooltip += 'White'; + } else { + status = 'black'; + tooltip += 'Black'; + } + + light.setAttribute('data-status', status); + indicator.setAttribute('data-status', tooltip.split(': ')[0]); +} + +function showNewGameModal() { + const modal = document.getElementById('modal-overlay'); + modal.classList.add('show'); + setupModalKeyboardNav(); +} + +function hideNewGameModal() { + const modal = document.getElementById('modal-overlay'); + modal.classList.remove('show'); + teardownModalKeyboardNav(); +} + +function setupModalKeyboardNav() { + document.addEventListener('keydown', handleModalKeydown); +} + +function teardownModalKeyboardNav() { + document.removeEventListener('keydown', handleModalKeydown); +} + +function handleModalKeydown(e) { + const modal = document.getElementById('modal-overlay'); + if (!modal.classList.contains('show')) return; + + switch(e.key) { + case 'Enter': + e.preventDefault(); + startNewGame(); + break; + case 'Escape': + e.preventDefault(); + hideNewGameModal(); + break; + case 'w': + case 'W': + e.preventDefault(); + document.querySelector('input[name="player-color"][value="white"]').checked = true; + break; + case 'b': + case 'B': + e.preventDefault(); + document.querySelector('input[name="player-color"][value="black"]').checked = true; + break; + case 'l': + case 'L': + e.preventDefault(); + document.getElementById('computer-level').focus(); + break; + case 's': + case 'S': + e.preventDefault(); + document.getElementById('search-time').focus(); + break; + case 'ArrowLeft': + handleSliderNav(e, -1); + break; + case 'ArrowRight': + handleSliderNav(e, 1); + break; + } +} + +function handleSliderNav(e, direction) { + const activeEl = document.activeElement; + if (activeEl.id === 'computer-level') { + e.preventDefault(); + activeEl.value = Math.max(0, Math.min(20, parseInt(activeEl.value) + direction)); + activeEl.dispatchEvent(new Event('input')); + } else if (activeEl.id === 'search-time') { + e.preventDefault(); + activeEl.value = Math.max(100, Math.min(10000, parseInt(activeEl.value) + direction * 100)); + activeEl.dispatchEvent(new Event('input')); + } +} + +function copyFEN() { + const fenText = document.getElementById('fen-display').textContent; + navigator.clipboard.writeText(fenText).then(() => { + const btn = document.getElementById('copy-fen'); + btn.classList.add('copied'); + setTimeout(() => { + btn.classList.remove('copied'); + }, 2000); + }); +} + +function copyHistory() { + const moves = gameState.moveList; + let pgn = ''; + for (let i = 0; i < moves.length; i++) { + if (i % 2 === 0) { + pgn += `${Math.floor(i / 2) + 1}. `; + } + pgn += moves[i] + ' '; + } + + navigator.clipboard.writeText(pgn.trim()).then(() => { + const btn = document.getElementById('copy-history'); + btn.classList.add('copied'); + setTimeout(() => { + btn.classList.remove('copied'); + }, 2000); + }); +} + +async function startNewGame() { + const playerColor = document.querySelector('input[name="player-color"]:checked').value; + const computerLevel = parseInt(document.getElementById('computer-level').value); + const searchTime = parseInt(document.getElementById('search-time').value); + gameState.isPlayerWhite = (playerColor === 'white'); + + const whiteConfig = gameState.isPlayerWhite ? { type: 1 } : { type: 2, level: computerLevel, searchTime: searchTime }; + const blackConfig = gameState.isPlayerWhite ? { type: 2, level: computerLevel, searchTime: searchTime } : { type: 1 }; + + try { + const response = await fetch(`${gameState.apiUrl}/api/v1/games`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ white: whiteConfig, black: blackConfig }) + }); + if (!response.ok) throw new Error('Failed to create game'); + + const game = await response.json(); + gameState.gameId = game.gameId; + gameState.moveList = []; + hideNewGameModal(); + initializeBoard(); + updateGameDisplay(game); + document.getElementById('undo-btn').disabled = false; + if (!gameState.isPlayerWhite) triggerComputerMove(); + + } catch (error) { + console.error('Error starting game:', error); + alert('Failed to start new game'); + gameState.networkError = true; + updateTurnIndicator('', ''); + } +} + +function initializeBoard() { + const boardEl = document.getElementById('board'); + boardEl.innerHTML = ''; + const isBlackPov = !gameState.isPlayerWhite; + + // Update coordinate labels based on perspective + const topCoords = document.querySelector('.coordinates.top'); + const leftCoords = document.querySelector('.coordinates.left'); + + if (isBlackPov) { + topCoords.innerHTML = 'hgfedcba'; + leftCoords.innerHTML = '12345678'; + } else { + topCoords.innerHTML = 'abcdefgh'; + leftCoords.innerHTML = '87654321'; + } + + for (let i = 0; i < 64; i++) { + const square = document.createElement('div'); + const rank = 7 - Math.floor(i / 8); + const file = i % 8; + const squareName = `${String.fromCharCode(97 + file)}${rank + 1}`; + + const displayRank = isBlackPov ? 7 - rank : rank; + const displayFile = isBlackPov ? 7 - file : file; + + square.className = `square ${(displayRank + displayFile) % 2 === 0 ? 'dark' : 'light'}`; + square.dataset.square = squareName; + square.addEventListener('click', handleSquareClick); + boardEl.appendChild(square); + } +} + +function renderBoardFromFEN(fen) { + const fenBoard = fen.split(' ')[0]; + + // Clear board and remove checkmate indicators + document.querySelectorAll('.square').forEach(s => { + s.textContent = ''; + s.classList.remove('white-piece', 'black-piece', 'mated-king'); + delete s.dataset.pieceColor; + }); + + let rank = 7, file = 0; + for (const char of fenBoard) { + if (char === '/') { + rank--; file = 0; + } else if (/\d/.test(char)) { + file += parseInt(char, 10); + } else { + const squareName = `${String.fromCharCode(97 + file)}${rank + 1}`; + const squareEl = document.querySelector(`[data-square="${squareName}"]`); + if (squareEl) { + const pieceColor = (char === char.toUpperCase()) ? 'w' : 'b'; + squareEl.textContent = pieceMap[char === 'P' ? 'P' : char.toLowerCase()] || ''; + squareEl.classList.add(pieceColor === 'w' ? 'white-piece' : 'black-piece'); + squareEl.dataset.pieceColor = pieceColor; + squareEl.dataset.pieceType = char.toLowerCase(); + } + file++; + } + } +} + +function handleSquareClick(e) { + if (gameState.isLocked) return; + + // Block moves after game over + if (isGameOver(gameState.state)) return; + + const squareEl = e.currentTarget; + const { square, pieceColor } = squareEl.dataset; + const playerTurnColor = gameState.isPlayerWhite ? 'w' : 'b'; + + if (gameState.turn !== playerTurnColor) return; + + if (gameState.selectedSquare) { + const from = gameState.selectedSquare; + const fromEl = document.querySelector(`[data-square="${from}"]`); + fromEl.classList.remove('selected'); + gameState.selectedSquare = null; + + if (from !== square) { + handleHumanMove(from, square); + } + } else if (pieceColor === playerTurnColor) { + gameState.selectedSquare = square; + squareEl.classList.add('selected'); + } else { + // Flash red for invalid piece selection + flashSquare(squareEl, false); + } +} + +function flashSquare(element, success = true) { + const className = success ? 'flash-green' : 'flash-red'; + element.classList.add(className); + setTimeout(() => element.classList.remove(className), 400); +} + +async function handleHumanMove(from, to) { + const move = from + to; + const fromEl = document.querySelector(`[data-square="${from}"]`); + const toEl = document.querySelector(`[data-square="${to}"]`); + + try { + const response = await fetch(`${gameState.apiUrl}/api/v1/games/${gameState.gameId}/moves`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ move }) + }); + + const game = await response.json(); + if (!response.ok) { + // Invalid move - flash both squares red + flashSquare(fromEl, false); + flashSquare(toEl, false); + renderBoardFromFEN(gameState.fen); + return; + } + + // Valid move - flash both squares green + flashSquare(fromEl, true); + flashSquare(toEl, true); + + updateGameDisplay(game); + if (!isGameOver(game.state)) { + triggerComputerMove(); + } + } catch (error) { + console.error('Error making move:', error); + gameState.networkError = true; + updateTurnIndicator('', gameState.turn); + } +} + +async function triggerComputerMove() { + lockBoard(); + try { + await fetch(`${gameState.apiUrl}/api/v1/games/${gameState.gameId}/moves`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ move: 'cccc' }) + }); + gameState.networkError = false; + startPolling(); + } catch (error) { + console.error('Error triggering computer move:', error); + gameState.networkError = true; + updateTurnIndicator('', gameState.turn); + unlockBoard(); + } +} + +function startPolling() { + gameState.pollInterval = setInterval(async () => { + try { + const response = await fetch(`${gameState.apiUrl}/api/v1/games/${gameState.gameId}`); + if (!response.ok) throw new Error('Failed to get game state'); + + const game = await response.json(); + if (game.state !== 'pending') { + stopPolling(); + updateGameDisplay(game); + unlockBoard(); + } + gameState.networkError = false; + } catch (error) { + console.error('Error polling game state:', error); + gameState.networkError = true; + updateTurnIndicator('', gameState.turn); + stopPolling(); + unlockBoard(); + } + }, 1500); +} + +function stopPolling() { + clearInterval(gameState.pollInterval); + gameState.pollInterval = null; +} + +function lockBoard() { + gameState.isLocked = true; + updateTurnIndicator('pending', gameState.turn); +} + +function unlockBoard() { + gameState.isLocked = false; + updateTurnIndicator('', gameState.turn); +} + +async function undoMoves() { + if (gameState.isLocked) return; + try { + const response = await fetch(`${gameState.apiUrl}/api/v1/games/${gameState.gameId}/undo`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ count: 2 }) + }); + if (!response.ok) throw new Error('Failed to undo moves'); + const game = await response.json(); + + // Clear checkmate state + gameState.state = game.state; + + updateGameDisplay(game); + } catch (error) { + console.error('Error undoing moves:', error); + gameState.networkError = true; + updateTurnIndicator('', gameState.turn); + } +} + +function renderMoveHistory(moves) { + const grid = document.getElementById('move-grid'); + grid.innerHTML = ''; + + let startsWithBlack = false; + if (gameState.fen) { + const fenParts = gameState.fen.split(' '); + const moveNum = parseInt(fenParts[5]) || 1; + const activeColor = fenParts[1]; + startsWithBlack = (moveNum === 1 && activeColor === 'b' && moves.length === 0); + } + + for (let i = 0; i < moves.length; i++) { + const isWhiteMove = (i % 2 === 0); + const moveNumber = Math.floor(i / 2) + 1; + + if (i === 0 || i % 2 === 0) { + const numEl = document.createElement('div'); + numEl.className = 'move-number'; + numEl.textContent = moveNumber + '.'; + grid.appendChild(numEl); + + const whiteEl = document.createElement('div'); + if (isWhiteMove && !startsWithBlack) { + whiteEl.className = 'move-white'; + whiteEl.textContent = moves[i]; + } else if (!isWhiteMove && startsWithBlack) { + whiteEl.className = 'move-empty'; + whiteEl.textContent = '...'; + } else { + whiteEl.className = 'move-empty'; + whiteEl.textContent = ''; + } + grid.appendChild(whiteEl); + + const blackEl = document.createElement('div'); + if (i + 1 < moves.length && !startsWithBlack) { + blackEl.className = 'move-black'; + blackEl.textContent = moves[i + 1]; + i++; + } else if (isWhiteMove && startsWithBlack) { + blackEl.className = 'move-black'; + blackEl.textContent = moves[i]; + } else { + blackEl.className = 'move-empty'; + blackEl.textContent = ''; + } + grid.appendChild(blackEl); + } + } + + const historyContainer = document.getElementById('move-history'); + historyContainer.scrollTop = historyContainer.scrollHeight; +} + +function updateGameDisplay(game) { + gameState.fen = game.fen; + gameState.turn = game.turn; + gameState.state = game.state; + gameState.moveList = game.moves || []; + + renderBoardFromFEN(game.fen); + updateTurnIndicator(game.state, game.turn); + + // Clear previous checkmate indicators + document.querySelectorAll('.mated-king').forEach(el => { + el.classList.remove('mated-king'); + }); + + // Highlight last move + document.querySelectorAll('.last-move-from, .last-move-to').forEach(el => { + el.classList.remove('last-move-from', 'last-move-to'); + }); + + if (game.lastMove && game.lastMove.move) { + const from = game.lastMove.move.substring(0, 2); + const to = game.lastMove.move.substring(2, 4); + const fromEl = document.querySelector(`[data-square="${from}"]`); + const toEl = document.querySelector(`[data-square="${to}"]`); + if (fromEl) fromEl.classList.add('last-move-from'); + if (toEl) toEl.classList.add('last-move-to'); + } + + // Update FEN display + document.getElementById('fen-display').textContent = game.fen || '-'; + + // Update move history + renderMoveHistory(game.moves || []); + + // Update undo button + document.getElementById('undo-btn').disabled = !game.moves || game.moves.length < 2; + + // Handle checkmate visually + if (game.state === 'white wins' || game.state === 'black wins') { + markMatedKing(game); + } +} + +function markMatedKing(game) { + // Find and mark the mated king + const matedColor = game.state === 'white wins' ? 'b' : 'w'; + document.querySelectorAll('.square').forEach(square => { + if (square.dataset.pieceType === 'k' && square.dataset.pieceColor === matedColor) { + square.classList.add('mated-king'); + } + }); +} + +function isGameOver(state) { + return ['white wins', 'black wins', 'stalemate', 'draw'].includes(state); +} + +function getGameOverText(state) { + switch(state) { + case 'white wins': return 'White Wins'; + case 'black wins': return 'Black Wins'; + case 'stalemate': return 'Stalemate'; + case 'draw': return 'Draw'; + default: return state; + } +} \ No newline at end of file diff --git a/internal/webserver/web/index.html b/internal/webserver/web/index.html new file mode 100644 index 0000000..6ef1450 --- /dev/null +++ b/internal/webserver/web/index.html @@ -0,0 +1,101 @@ + + + + + + + Chess Game + + + +
+
+
+
+
+
+
+ abcd + efgh +
+
+ 8765 + 4321 +
+
+
+
+
+
-
+ +
+
+ + +
+
+
+ + + + + + + \ No newline at end of file diff --git a/internal/webserver/web/style.css b/internal/webserver/web/style.css new file mode 100644 index 0000000..725501e --- /dev/null +++ b/internal/webserver/web/style.css @@ -0,0 +1,659 @@ +/* FILE: internal/webserver/web/style.css */ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +:root { + /* Tokyo Night colors */ + --tokyo-bg: #1a1b26; + --tokyo-bg-dark: #16161e; + --tokyo-fg: #a9b1d6; + --tokyo-cyan: #7dcfff; + --tokyo-blue: #7aa2f7; + --tokyo-purple: #bb9af7; + --tokyo-green: #9ece6a; + --tokyo-yellow: #e0af68; + --tokyo-red: #f7768e; + --tokyo-border: #3b4261; + + /* Board colors */ + --square-light: #f0d9b5; + --square-dark: #b58863; + --square-selected: #6a994e; + --move-from: #5090d3; + --move-to: #81b3f0; +} + +/* Base Layout */ +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; + background: #11111b; + min-height: 100vh; + width: 100vw; + margin: 0; + display: flex; + justify-content: center; + align-items: center; + overflow-x: hidden; + overflow-y: auto; +} + +.outer-container { + width: 100%; + min-height: 100vh; + padding: 8px; + display: flex; + justify-content: center; + align-items: center; + overflow: visible; +} + +.container { + background: var(--tokyo-bg); + border-radius: 12px; + box-shadow: 0 20px 40px rgba(0,0,0,0.4); + padding: 1.5rem; + width: 100%; + max-width: 1100px; + min-height: 600px; + max-height: calc(100vh - 16px); + color: var(--tokyo-fg); + display: flex; + flex-direction: column; + overflow: visible; +} + +main { + display: grid; + grid-template-columns: 1fr 340px; + gap: 1.5rem; + height: 100%; + min-height: 0; +} + +/* Game Area */ +.game-area { + display: flex; + flex-direction: column; + gap: 0.75rem; + min-width: 0; + min-height: 0; +} + +/* Board and Coordinates */ +.board-container { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + min-height: 0; +} + +.board-wrapper { + position: relative; + width: 100%; + max-width: min(100%, calc(100vh - 200px)); + aspect-ratio: 1; + margin: 0 auto; +} + +.coordinates { + position: absolute; + display: flex; + color: var(--tokyo-border); + font-size: 0.75rem; + font-weight: 500; + user-select: none; +} + +.coordinates.top { + top: -20px; + left: 0; + right: 0; + justify-content: space-around; + padding: 0 2px; +} + +.coordinates.left { + left: -20px; + top: 0; + bottom: 0; + flex-direction: column; + justify-content: space-around; + padding: 2px 0; +} + +#board { + position: absolute; + inset: 0; + display: grid; + grid-template-columns: repeat(8, 1fr); + grid-template-rows: repeat(8, 1fr); + border: 3px solid var(--tokyo-border); + border-radius: 4px; +} + +.square { + display: flex; + justify-content: center; + align-items: center; + font-size: clamp(24px, 5vw, 36px); + cursor: pointer; + user-select: none; + position: relative; +} + +.square.light { background-color: var(--square-light); } +.square.dark { background-color: var(--square-dark); } +.square.selected { background-color: var(--square-selected) !important; } +.square.last-move-from { background-color: var(--move-from) !important; } +.square.last-move-to { background-color: var(--move-to) !important; } +.square.white-piece { color: #ffffff; text-shadow: 1px 1px 2px rgba(0,0,0,0.5); } +.square.black-piece { color: #2c2c2c; text-shadow: 1px 1px 2px rgba(255,255,255,0.2); } + +/* Move feedback animations */ +@keyframes flashGreen { + 0%, 100% { background-color: inherit; } + 50% { background-color: rgba(154, 206, 106, 0.8); } +} + +@keyframes flashRed { + 0%, 100% { background-color: inherit; } + 50% { background-color: rgba(247, 118, 142, 0.8); } +} + +.square.flash-green { + animation: flashGreen 0.4s ease-out; +} + +.square.flash-red { + animation: flashRed 0.4s ease-out; +} + +/* Checkmate indicator */ +.square.mated-king::after { + content: ''; + position: absolute; + inset: 4px; + border: 3px solid var(--tokyo-red); + border-radius: 2px; + pointer-events: none; + z-index: 1; +} + +.square.mated-king.black-piece { + color: #8b0000 !important; +} + +.square.mated-king.white-piece { + color: #dc143c !important; +} + +/* FEN Display */ +.fen-container { + position: relative; + height: 40px; + flex-shrink: 0; +} + +.fen-display { + height: 100%; + padding: 0.5rem 3rem 0.5rem 0.5rem; + font-family: 'Courier New', monospace; + font-size: 0.75rem; + background: var(--tokyo-bg-dark); + border-radius: 4px; + border: 1px solid var(--tokyo-border); + color: var(--tokyo-fg); + white-space: nowrap; + overflow-x: auto; + overflow-y: hidden; + display: flex; + align-items: center; + scrollbar-width: none; +} + +.fen-display::-webkit-scrollbar { + display: none; +} + +.fen-display::-webkit-scrollbar-track { + background: var(--tokyo-bg-dark); +} + +.fen-display::-webkit-scrollbar-thumb { + background: var(--tokyo-border); + border-radius: 2px; +} + +/* Copy Buttons */ +.copy-btn { + position: absolute; + right: 8px; + top: 50%; + transform: translateY(-50%); + width: 24px; + height: 24px; + padding: 4px; + background: var(--tokyo-border); + border: none; + border-radius: 4px; + color: var(--tokyo-fg); + cursor: pointer; + opacity: 0; + transition: opacity 0.2s, background 0.2s; + display: flex; + align-items: center; + justify-content: center; +} + +.fen-container:hover .copy-btn, +.move-history-container:hover .copy-btn { + opacity: 0.7; +} + +.copy-btn:hover { + opacity: 1 !important; + background: var(--tokyo-blue); +} + +.copy-btn.copied { + background: var(--tokyo-green); + opacity: 1; +} + +.copy-btn.copied svg { + display: none; +} + +.copy-btn.copied::after { + content: '✓'; + font-size: 14px; +} + +/* Info Panel */ +.info-panel { + background: var(--tokyo-bg-dark); + border-radius: 8px; + padding: 1rem; + display: flex; + flex-direction: column; + gap: 1rem; + min-height: 0; +} + +/* Status Indicators */ +.status-indicators { + display: flex; + justify-content: space-evenly; + align-items: center; + padding: 0.75rem; + background: var(--tokyo-bg); + border-radius: 6px; + border: 1px solid var(--tokyo-border); + flex-shrink: 0; + height: 60px; +} + +.indicator { + position: relative; + display: flex; + align-items: center; + justify-content: center; + height: 100%; +} + +.indicator .light { + font-size: 1.75rem; + transition: all 0.3s; + line-height: 1; +} + +.indicator .light[data-status="white-wins"]::before, +.indicator .light[data-status="black-wins"]::before { + content: ''; + position: absolute; + inset: -8px; + border: 2px solid var(--tokyo-red); + border-radius: 50%; + animation: pulseRed 2s infinite; + pointer-events: none; +} + +/* Status colors */ +.indicator .light[data-status="healthy"] { color: var(--tokyo-green); } +.indicator .light[data-status="disabled"] { color: var(--tokyo-yellow); } +.indicator .light[data-status="degraded"] { color: var(--tokyo-red); } +.indicator .light[data-status="unknown"] { color: var(--tokyo-border); } +.indicator .light[data-status="white"] { color: #ffffff; } +.indicator .light[data-status="black"] { color: #2c2c2c; } +.indicator .light[data-status="thinking"] { + color: var(--tokyo-yellow); + animation: pulse 1.5s infinite; +} +.indicator .light[data-status="network-error"] { color: var(--tokyo-red); } + +/* Win indicator */ +@keyframes pulseRed { + 0%, 100% { + opacity: 0.3; + transform: scale(1); + } + 50% { + opacity: 0.8; + transform: scale(1.1); + } +} + +.indicator .light[data-status="white-wins"], +.indicator .light[data-status="black-wins"] { + animation: goldPulse 2s infinite; +} + +.indicator .light[data-status="draw"], +.indicator .light[data-status="stalemate"] { + color: var(--tokyo-yellow); +} + +@keyframes pulse { + 0%, 100% { opacity: 1; transform: scale(1); } + 50% { opacity: 0.6; transform: scale(0.95); } +} + +.indicator:hover::after { + content: attr(data-tooltip) ": " attr(data-status); + position: absolute; + bottom: -30px; + left: 50%; + transform: translateX(-50%); + background: #313244; + color: var(--tokyo-fg); + padding: 0.25rem 0.5rem; + border-radius: 4px; + font-size: 0.75rem; + white-space: nowrap; + z-index: 10; + pointer-events: none; +} + +/* Move History */ +.move-history-container { + flex: 1; + min-height: 0; + position: relative; + background: var(--tokyo-bg); + border-radius: 6px; + border: 1px solid var(--tokyo-border); +} + +.move-history-container .copy-btn { + right: 8px; + top: 8px; + transform: none; +} + +.move-history { + height: 100%; + overflow-y: auto; + overflow-x: hidden; + padding: 0.75rem; +} + +.move-history::-webkit-scrollbar { + width: 6px; +} + +.move-history::-webkit-scrollbar-track { + background: transparent; +} + +.move-history::-webkit-scrollbar-thumb { + background: var(--tokyo-border); + border-radius: 3px; +} + +.move-grid { + display: grid; + grid-template-columns: 2.5rem 1fr 1fr; + gap: 0.25rem 0.5rem; + font-family: 'Courier New', monospace; + font-size: 0.9rem; + align-items: center; +} + +.move-number { + color: var(--tokyo-blue); + text-align: right; + font-weight: 600; +} + +.move-white, +.move-black { + padding: 0.25rem 0.5rem; + border-radius: 3px; + transition: background 0.2s; +} + +.move-white:hover, +.move-black:hover { + background: var(--tokyo-border); +} + +.move-white { color: var(--tokyo-fg); } +.move-black { color: var(--tokyo-cyan); } + +/* Controls */ +.controls { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0.75rem; + flex-shrink: 0; +} + +.btn { + padding: 0.75rem; + border: none; + border-radius: 6px; + font-size: 0.9rem; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; +} + +.btn-primary { + background: var(--tokyo-blue); + color: var(--tokyo-bg); +} + +.btn-primary:hover { + background: var(--tokyo-cyan); + transform: translateY(-1px); +} + +.btn-secondary { + background: #313244; + color: var(--tokyo-fg); +} + +.btn-secondary:hover:not(:disabled) { + background: var(--tokyo-border); + transform: translateY(-1px); +} + +.btn:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +/* Modal */ +.modal-overlay { + display: none; + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.7); + z-index: 2000; + justify-content: center; + align-items: center; + backdrop-filter: blur(4px); +} + +.modal-overlay.show { + display: flex; +} + +.modal { + background: var(--tokyo-bg); + border: 1px solid var(--tokyo-border); + border-radius: 12px; + padding: 2rem; + width: 90%; + max-width: 400px; + color: var(--tokyo-fg); +} + +.modal h2 { + margin-bottom: 1.5rem; + color: var(--tokyo-blue); + text-align: center; +} + +.form-group { + margin-bottom: 1.5rem; +} + +.form-group label { + display: block; + margin-bottom: 0.5rem; + color: var(--tokyo-cyan); +} + +.form-group .group-label { + text-align: center; +} + +.radio-group { + display: flex; + gap: 1.5rem; + justify-content: center; +} + +.radio-group label { + display: flex; + align-items: center; + gap: 0.5rem; + margin: 0; + color: var(--tokyo-fg); +} + +input[type="range"] { + width: 100%; + height: 4px; + background: var(--tokyo-border); + border-radius: 2px; + outline: none; +} + +input[type="range"]::-webkit-slider-thumb { + appearance: none; + width: 16px; + height: 16px; + background: var(--tokyo-blue); + border-radius: 50%; + cursor: pointer; +} + +.modal-buttons { + display: flex; + justify-content: center; + gap: 1rem; + margin-top: 2rem; +} + +/* Mobile/Responsive */ +@media (max-width: 900px) { + body { + min-height: 100vh; + overflow-y: auto; + overflow-x: hidden; + } + + .outer-container { + padding: 8px; + min-height: 100vh; + height: auto; + align-items: flex-start; + padding-top: 20px; + } + + .container { + border-radius: 0; + height: auto; + min-height: auto; + max-height: none; + padding: 0.5rem; + margin-bottom: 20px; + } + + main { + grid-template-columns: 1fr; + grid-template-rows: auto auto; + gap: 0.5rem; + height: auto; + min-height: auto; + } + + .board-container { + height: auto; + padding: 20px 0; + } + + .board-wrapper { + max-width: calc(100vw - 56px); + max-height: calc(100vw - 56px); + margin: 0 auto; + } + + .coordinates.top { + top: -18px; + } + + .coordinates.left { + left: -18px; + } + + .square { + font-size: clamp(20px, 8vw, 32px); + } + + .fen-container { + display: none; + } + + .info-panel { + grid-template-columns: 1fr; + gap: 0.5rem; + padding: 0.5rem; + height: auto; + } + + .status-indicators { + padding: 0.5rem; + height: 50px; + } + + .move-history-container { + max-height: 30vh; + min-height: 150px; + } + + .controls { + grid-template-columns: 1fr 1fr; + } + + .btn { + padding: 0.5rem; + font-size: 0.85rem; + } +} \ No newline at end of file