4 Commits

6 changed files with 196 additions and 776 deletions
+29
View File
@@ -7,6 +7,35 @@ e questo progetto aderisce al [Versionamento Semantico](https://semver.org/lang/
--- ---
## [2.0.0] - 2026-05-12
### Aggiunto
- Architettura client-server con WebSocket: server Express (`server.js`) + handler (`src/websocket-handler.js`) come unica fonte di verità; display e controller sono client separati sincronizzati in tempo reale
- Interfaccia display (`/display`) e controller (`/controller`) su porta singola `:3000`
- Robustezza connessione WebSocket: reconnect automatico con backoff esponenziale, indicatore stato connessione sul display
- Supporto query parameter `?wsHost=` per scenari WSL2 / development remoto
- Validazione cambi giocatori già in formazione lato client
- Sintesi vocale inoltrata dal controller al display via WebSocket
- Dialog set vinto sul controller al raggiungimento dei 25 punti: mostra il vincitore, permette di annullare l'ultimo punto (INDIETRO) o avanzare al set successivo con reset automatico formazioni
- Struttura striscia ottimizzata: array di set `[{ serv, r[] }]` che registra la sequenza dei punti e preserva la storia di tutti i set; elimina `storicoServizio`
- Persistenza stato su `.segnapunti/state.json`: salvato ad ogni azione, ricaricato all'avvio del server
- Suite di test completa: unit (Vitest), integration, component (Vue Test Utils + Happy-DOM), stress (50+ client), E2E (Playwright su Chromium, Firefox, Mobile Chrome)
- Dockerfile multi-stage (builder + runtime minimale) e docker-compose con volume per persistenza stato; immagine pubblicata su registro Gitea
### Modificato
- `applyAction` usa `structuredClone` al posto di `JSON.parse/stringify`
- Calcolo cambio palla deduplicato in `applyAction`
- Undo punto (`decPunt`) ricostruisce il servizio precedente dalla storia `r[]`
- `nuovoSet` come azione dedicata per la progressione regolare tra set
### Rimosso
- Terminal controller CLI (`cli.js`)
- Dipendenze inutilizzate: `wave-ui`, `vue-router`, `concurrently`
- Script npm ridondanti: `preview`, `start`, `cli`, `cli:dev`
- Asset template Vite: `vite.svg`, `vue.svg`, `serve.png`
---
## [1.0.0] - 2026-02-10 ## [1.0.0] - 2026-02-10
Rilascio iniziale di **Segnapunti Anto**, un'applicazione web Progressive Web App (PWA) professionale per il tracciamento in tempo reale dei punteggi durante partite di pallavolo. Rilascio iniziale di **Segnapunti Anto**, un'applicazione web Progressive Web App (PWA) professionale per il tracciamento in tempo reale dei punteggi durante partite di pallavolo.
+10 -14
View File
@@ -4,15 +4,13 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Purpose ## Project Purpose
**Segnapunti Anto** is a real-time volleyball scoreboard PWA. An Express/WebSocket server hosts the game state; two separate web interfaces — a **display** (public scoreboard) and a **controller** (operator panel) — stay in sync via WebSocket. A terminal CLI (`cli.js`) provides an alternative controller interface. **Segnapunti Anto** is a real-time volleyball scoreboard PWA. An Express/WebSocket server hosts the game state; two separate web interfaces — a **display** (public scoreboard) and a **controller** (operator panel) — stay in sync via WebSocket.
## Commands ## Commands
```bash ```bash
npm run dev # Vite dev server — display: :5173, controller: :5173/controller.html (proxied on :3001) npm run dev # Vite dev server — display: :5173/display, controller: :5173/controller
npm run serve # Build + run production — display: :3000, controller: :3001 npm run serve # Build + run production — display: :3000/display, controller: :3000/controller
npm run cli # Terminal controller (connects to production :3000)
npm run cli:dev # Terminal controller (connects to dev :5173)
npm run test # Vitest watch mode npm run test # Vitest watch mode
npm run test:all # All Vitest suites once (unit, integration, component, stress) npm run test:all # All Vitest suites once (unit, integration, component, stress)
@@ -28,19 +26,20 @@ npm run test:e2e:ui # Playwright with interactive UI
``` ```
Controller (Vue) ──WebSocket──┐ Controller (Vue) ──WebSocket──┐
Display (Vue) ──WebSocket──┤── websocket-handler.js ── gameState.js Display (Vue) ──WebSocket──┤── websocket-handler.js ── gameState.js
CLI (Node) ──WebSocket──┘ │ │
│ └── persist.js ── .segnapunti/state.json
``` ```
All game logic lives in `src/gameState.js` as three pure functions: All game logic lives in `src/gameState.js` as three pure functions:
- `createInitialState()` — returns the initial state - `createInitialState()` — returns the initial state
- `applyAction(state, action)` — immutable reducer (deep-clones via `JSON.parse/stringify`) - `applyAction(state, action)` — immutable reducer (deep-clones via `structuredClone`)
- `checkVittoria(state)` — volleyball win conditions (25-point sets with 2-point margin, 15-point final set) - `checkVittoria(state)` — volleyball win conditions (25-point sets with 2-point margin, 15-point final set)
`src/websocket-handler.js` receives actions, validates that the sender is a registered controller (not just a display), calls `applyAction`, then broadcasts the new state to all clients. `src/websocket-handler.js` receives actions, validates that the sender is a registered controller (not just a display), calls `applyAction`, broadcasts the new state to all clients, then calls `onStateChange` to persist state to disk.
Two production HTTP servers are started by `server.js` (Express): port 3000 serves `dist/index.html` (display), port 3001 serves `dist/controller.html` (controller). Both share a single WebSocket endpoint at `/ws`. `server.js` (Express) serves both interfaces on port 3000: `/display``dist/index.html`, `/controller``dist/controller.html`. Single WebSocket endpoint at `/ws`.
In development, `vite-plugin-websocket.js` is a custom Vite plugin that embeds the WebSocket server inside the Vite dev server and proxies port 3001 traffic back to Vite. In development, `vite-plugin-websocket.js` embeds the WebSocket server inside the Vite dev server with URL rewrite middleware for `/display` and `/controller`.
## Key Design Constraints ## Key Design Constraints
@@ -48,6 +47,7 @@ In development, `vite-plugin-websocket.js` is a custom Vite plugin that embeds t
- **Role-based WebSocket** — clients register as `display` or `controller`; only controllers may send actions. - **Role-based WebSocket** — clients register as `display` or `controller`; only controllers may send actions.
- **Immutable state** — `applyAction` never mutates; always returns a new state object. - **Immutable state** — `applyAction` never mutates; always returns a new state object.
- **Single-controller intent** — the design targets one active controller and one display; no conflict resolution exists for simultaneous controllers. - **Single-controller intent** — the design targets one active controller and one display; no conflict resolution exists for simultaneous controllers.
- **Persistent state** — `src/persist.js` saves state to `.segnapunti/state.json` after every action and loads it on server startup.
## Test Layout ## Test Layout
@@ -60,7 +60,3 @@ In development, `vite-plugin-websocket.js` is a custom Vite plugin that embeds t
| E2E | `tests/e2e/` | Playwright (Chromium, Firefox, Mobile Chrome) | | E2E | `tests/e2e/` | Playwright (Chromium, Firefox, Mobile Chrome) |
E2E tests run serially (`workers: 1`) to avoid WebSocket state races. Run `npm run serve` before `npm run test:e2e`. E2E tests run serially (`workers: 1`) to avoid WebSocket state races. Run `npm run serve` before `npm run test:e2e`.
## Simplification Goals (Current Work)
The intended architecture is: **one host acts as both WebSocket server and display; one connected device acts as controller**. Complexity reduction should be evaluated against this constraint — anything that supports multi-controller scenarios, complex client topologies, or unneeded abstractions is a candidate for removal.
+156 -154
View File
@@ -1,213 +1,215 @@
# Segnapunti Anto # Segnapunti
Applicazione web **fullstack real-time** per il tracciamento dei punteggi di partite di pallavolo, installabile come PWA. ![Version](https://img.shields.io/badge/versione-2.0.0-blue)
![Node](https://img.shields.io/badge/node-%3E%3D18-green)
![Docker](https://img.shields.io/badge/docker-ready-2496ED?logo=docker&logoColor=white)
![License](https://img.shields.io/badge/licenza-privata-lightgrey)
Segnapunti digitale in tempo reale per partite di pallavolo. Un server centrale gestisce lo stato della partita; un **display** mostra il tabellone pubblico e un **controller** (smartphone o tablet) permette all'operatore di gestire punti, formazioni e cambi.
--- ---
## Panoramica ## Indice
**Segnapunti Anto** è un'applicazione fullstack per il tracciamento del punteggio durante partite di pallavolo, ottimizzata per tablet e smartphone in contesto sportivo. - [Architettura](#architettura)
- [Guida utente](#guida-utente)
- [Funzionalità](#funzionalità)
- [Shortcuts tastiera](#shortcuts-tastiera)
- [Deploy con Docker](#deploy-con-docker)
- [Sviluppo](#sviluppo)
- [Test](#test)
### Architettura ---
Il sistema è composto da un **backend Node.js/Express** e due interfacce web separate: ## Architettura
| Interfaccia | Porta | Ruolo | ```
|-------------|-------|-------| Controller (smartphone) ──WebSocket──┐
| **Display** | 3000 | Tabellone pubblico — mostra punteggi, formazioni e storico | ├── Server Node.js ── gameState.js
| **Controller** | 3001 | Pannello operatore — invia azioni e gestisce la partita | Display (schermo) ──WebSocket──┘ │
└── .segnapunti/state.json
```
Le due interfacce comunicano tramite **WebSocket** (`/ws`): ogni azione del Controller viene elaborata dal server e trasmessa in broadcast a tutti i client connessi. Il server è l'unica fonte di verità. Ogni azione del controller viene elaborata e trasmessa in broadcast a tutti i client connessi. Lo stato viene salvato su disco ad ogni azione e ricaricato all'avvio, sopravvivendo ai riavvii del server.
La logica di gioco risiede interamente **lato server** (`gameState.js`), con aggiornamenti di stato immutabili. Il frontend Vue 3 è puramente reattivo: riceve lo stato e lo visualizza senza gestirne la consistenza. | Percorso | Ruolo |
|---|---|
| `http://<host>:3000/display` | Tabellone pubblico — sola lettura |
| `http://<host>:3000/controller` | Pannello operatore — gestione partita |
| `ws://<host>:3000/ws` | WebSocket endpoint |
In produzione, entrambi i server sono gestiti da un unico processo Node.js (`server.js`) e l'intera applicazione è containerizzabile via Docker. Il frontend è installabile come **PWA** (service worker, manifest, modalità fullscreen landscape) per utilizzo kiosk su dispositivi sportivi. ---
## Guida utente
### Scenario tipico: schermo fisso + smartphone operatore
#### 1. Avvia il server
```bash
docker compose up -d
```
All'avvio il terminale mostra gli URL locali e di rete.
#### 2. Apri il display
Collega il PC/server allo schermo via HDMI e apri il browser a schermo intero:
```
http://localhost:3000/display
```
Se il display è su un dispositivo separato nella stessa rete:
```
http://<IP-del-server>:3000/display
```
> **Trovare l'IP:** il server lo stampa all'avvio. In alternativa usa `ip a` su Linux.
#### 3. Apri il controller sullo smartphone
Connetti il telefono alla stessa rete Wi-Fi e apri:
```
http://<IP-del-server>:3000/controller
```
> **Installazione come app:** nel browser tocca *"Aggiungi a schermata Home"* per avere il controller come icona dedicata.
--- ---
## Funzionalità ## Funzionalità
### Gestione partita in tempo reale ### Display
- Tracciamento punti home/guest con indicatore di servizio
- Gestione set e storico punti (striscia) - Nomi squadre con indicatore di servizio
- Blocco azioni quando il set è già vinto - Punteggio del set corrente (grande, leggibile da lontano)
- Contatore set vinti
- Striscia storica punti del set in corso, scorrevole verso destra
- Modalità formazioni: posizioni dei 6 giocatori in campo
- Indicatore connessione WebSocket (scompare quando connesso, rosso lampeggiante se disconnesso)
### Controller
- **Punti** — `+1` per casa e ospite, con annullamento dell'ultimo punto
- **Dialog set vinto** — appare automaticamente al raggiungimento dei 25 punti (o 15 nel tie-break); permette di confermare il set o annullare l'ultimo punto
- **Formazioni** — configura i numeri di maglia; la rotazione avviene automaticamente al cambio palla
- **Cambi** — dialog `IN → OUT` con validazione
- **Servizio** — cambio manuale (disponibile solo a 0-0)
- **Visualizzazione** — alterna tra punteggio grande e formazioni in campo
- **Striscia** — mostra/nasconde lo storico punti sul display
- **Reset** — azzera la partita (richiede conferma)
### Regole pallavolo integrate ### Regole pallavolo integrate
- Set normali: vittoria a 25 con almeno 2 punti di scarto
- Set decisivo (5° set): vittoria a 15 con almeno 2 punti di scarto
- Modalità partita `2/3` o `3/5`
### Formazioni e cambi | Set | Condizione di vittoria |
- Gestione formazione a 6 giocatori per squadra |---|---|
- Rotazione automatica al cambio palla | Set 14 (modalità 3/5) o 12 (modalità 2/3) | Primo a **25** con almeno 2 punti di scarto |
- Dialog cambi con validazione `IN → OUT` | Set decisivo (tie-break) | Primo a **15** con almeno 2 punti di scarto |
### Controlli e personalizzazione
- Configurazione nomi squadre
- Inversione ordine di visualizzazione squadre
- Toggle punteggio/formazioni e visibilità striscia storico
- Sintesi vocale del punteggio (Web Speech API)
--- ---
## Requisiti ## Shortcuts tastiera
### Ambiente di sviluppo > Valide sul controller da browser desktop.
| Requisito | Versione minima | Consigliata | | Tasto | Azione |
|-----------|-----------------|-------------| |---|---|
| **Node.js** | `>= 18.19.0` | `24 LTS` | | `Ctrl + ↑` | Punto casa |
| **npm** | `>= 9` | — | | `Ctrl + ↓` | Annulla ultimo punto |
| **RAM** | 2 GB | 4 GB | | `Shift + ↑` | Punto ospite |
| **OS** | Linux, macOS, Windows | — | | `Ctrl + ←` | Cambia servizio (solo a 0-0) |
| `Ctrl + M` | Apri configurazione |
| `Ctrl + C` | Cambi squadra casa |
| `Shift + C` | Cambi squadra ospite |
| `Ctrl + Z` | Toggle punteggio / formazioni |
| `Ctrl + S` | Annuncio vocale punteggio |
| `Ctrl + B` | Mostra/nascondi barra pulsanti |
| `Ctrl + F` | Fullscreen |
### Test E2E ---
I test end-to-end richiedono i browser Playwright. Su Linux potrebbero essere necessarie dipendenze di sistema aggiuntive. ## Deploy con Docker
### Prima installazione
```bash ```bash
npx playwright install chromium firefox docker compose up -d
# Linux (con dipendenze di sistema):
# npx playwright install --with-deps chromium firefox
``` ```
### Requisiti browser (utente finale) Lo stato viene salvato nel volume Docker `segnapunti-state` e sopravvive ai riavvii del container.
| API | Utilizzo | Necessità | ### Aggiornamento a nuova versione
|-----|----------|-----------|
| JavaScript ES6+ | Moduli, async/await | Obbligatorio |
| WebSocket | Sincronizzazione stato live | Obbligatorio |
| Service Worker | Supporto PWA offline | Consigliato |
| Web Speech API | Annunci vocali punteggio | Opzionale |
**Browser testati:** Chrome/Chromium, Firefox, Mobile Chrome (Playwright Pixel 5).
---
## Installazione
```bash ```bash
git clone https://santantonio.sytes.net/attilio/segnapunti.git docker compose pull && docker compose up -d
cd segnapunti ```
npm install
### Build e pubblicazione immagine
```bash
docker build \
-t santantonio.sytes.net/attilio/segnapunti:2.0.0 \
-t santantonio.sytes.net/attilio/segnapunti:latest .
docker push santantonio.sytes.net/attilio/segnapunti:2.0.0
docker push santantonio.sytes.net/attilio/segnapunti:latest
``` ```
--- ---
## Sviluppo ## Sviluppo
### Dev server ### Requisiti
```bash | Strumento | Versione minima |
npm run dev |---|---|
``` | Node.js | >= 18 |
| npm | >= 9 |
Avvia il server Vite con hot reload:
- `http://localhost:5173/` — Display
- `http://localhost:5173/controller.html` — Controller
### Build di produzione
```bash
npm run build
```
Genera la cartella `dist/` con asset ottimizzati, manifest e service worker PWA.
### Avvio in produzione (locale)
```bash
npm run serve
```
Espone i due server:
- `http://localhost:3000` — Display
- `http://localhost:3001` — Controller
---
## Terminal Controller (CLI)
Il CLI è un controller da terminale che si connette al server via WebSocket e permette di gestire la partita senza browser.
### Avvio ### Avvio
```bash ```bash
# Modalità produzione (server su porta 3000) npm install
npm run cli npm run dev
# Modalità sviluppo (server Vite su porta 5173)
npm run cli:dev
# Porta custom
node cli.js <porta>
``` ```
Il CLI richiede che il server sia già in esecuzione in un altro terminale. | URL | Interfaccia |
|---|---|
| `http://localhost:5173/display` | Display |
| `http://localhost:5173/controller` | Controller |
Lo stato viene salvato in `.segnapunti/state.json` anche in modalità dev.
### Comandi disponibili ### Comandi disponibili
#### Punteggio | Comando | Descrizione |
|---|---|
| Comando | Alias | Effetto | | `npm run dev` | Dev server con hot reload |
|---------|-------|---------| | `npm run build` | Build di produzione in `dist/` |
| `punto casa` | `+`, `pc` | Assegna un punto alla squadra di casa | | `npm run serve` | Build + avvio server produzione |
| `punto ospite` | `-`, `po` | Assegna un punto alla squadra ospite |
| `undo` | `u` | Annulla l'ultimo punto assegnato |
#### Set
| Comando | Effetto |
|---------|---------|
| `set casa` | Incrementa il contatore set della squadra di casa |
| `set ospite` | Incrementa il contatore set della squadra ospite |
#### Partita
| Comando | Effetto |
|---------|---------|
| `serv` | Cambia il servizio (disponibile solo se il punteggio è 0-0) |
| `reset` | Resetta la partita — chiede conferma prima di procedere |
| `nomi <casa> <ospite>` | Imposta i nomi delle squadre (es. `nomi Antoniana Teate`) |
| `modalita 2/3` | Imposta la modalità best-of-3 |
| `modalita 3/5` | Imposta la modalità best-of-5 |
#### Informazioni
| Comando | Alias | Effetto |
|---------|-------|---------|
| `stato` | — | Mostra il punteggio corrente nel terminale |
| `help` | — | Mostra la lista dei comandi |
| `exit` | `q` | Chiude il CLI |
### Note
- **Tab**: completamento automatico dei comandi
- **Freccia su/giù**: navigazione nella history dei comandi (ultime 100 voci)
- Il Display nel browser si aggiorna in tempo reale ad ogni comando inviato
--- ---
## Test ## Test
La suite di test copre tutti i livelli dell'applicazione: | Comando | Descrizione |
|---|---|
| `npm run test:unit` | Unit + integration (Vitest) |
| `npm run test:component` | Componenti Vue (Happy-DOM) |
| `npm run test:stress` | Load test WebSocket (50+ client) |
| `npm run test:all` | Tutti i test tranne E2E |
| `npm run test:e2e` | Playwright — Chromium, Firefox, Mobile Chrome |
| Suite | Comando | Descrizione | > I test E2E richiedono il server in esecuzione (`npm run serve`) e i browser Playwright installati:
|-------|---------|-------------| > ```bash
| Tutti | `npm run test:all` | Unit + integration + component + stress | > npx playwright install chromium firefox
| Unit + integration | `npm run test:unit` | Logica di gioco e WebSocket | > ```
| Component | `npm run test:component` | Componenti Vue |
| Stress | `npm run test:stress` | Load test WebSocket |
| E2E | `npm run test:e2e` | Playwright (chromium, firefox, mobile) |
Per la guida completa ai test, consultare [`tests/README.md`](tests/README.md).
--- ---
## Docker ## Changelog
```bash Vedere [CHANGELOG.md](CHANGELOG.md) per la storia delle versioni.
docker-compose up --build
```
Espone le porte `3000` (Display) e `3001` (Controller).
-302
View File
@@ -1,302 +0,0 @@
import { WebSocket } from 'ws';
import readline from 'readline';
// ---------------------------------------------------------------------------
// ANSI helpers
// ---------------------------------------------------------------------------
const c = {
reset: '\x1b[0m',
bold: '\x1b[1m',
dim: '\x1b[2m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
cyan: '\x1b[36m',
brightWhite: '\x1b[97m',
};
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
const port = process.argv[2] || process.env.PORT || 3000;
const url = `ws://localhost:${port}/ws`;
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
let currentState = null;
let connected = false;
// ---------------------------------------------------------------------------
// Startup banner
// ---------------------------------------------------------------------------
console.log(`\n${c.bold}${c.cyan} Segnapunti Anto — Terminal Controller${c.reset}`);
console.log(`${c.dim} Connessione a ${url}...${c.reset}\n`);
// ---------------------------------------------------------------------------
// WebSocket
// ---------------------------------------------------------------------------
const ws = new WebSocket(url);
ws.on('error', (err) => {
console.error(`${c.red}Errore di connessione: ${err.message}${c.reset}`);
console.error(`${c.dim}Assicurati che il server sia avviato su ${url}${c.reset}`);
process.exit(1);
});
ws.on('open', () => {
connected = true;
console.log(` ${c.green}Connesso.${c.reset} Digita ${c.bold}help${c.reset} per i comandi disponibili.\n`);
ws.send(JSON.stringify({ type: 'register', role: 'controller' }));
});
ws.on('message', (data) => {
try {
const msg = JSON.parse(data.toString());
if (msg.type === 'state') {
currentState = msg.state;
printState(currentState);
} else if (msg.type === 'error') {
clearLine();
console.error(` ${c.red}Errore server: ${msg.message}${c.reset}`);
}
} catch {
// ignora messaggi malformati
}
rl.prompt(true);
});
ws.on('close', () => {
console.log(`\n${c.dim} Connessione chiusa.${c.reset}\n`);
process.exit(0);
});
// ---------------------------------------------------------------------------
// Output helpers
// ---------------------------------------------------------------------------
/** Cancella la riga corrente del terminale (evita di sovrascrivere il prompt). */
function clearLine() {
process.stdout.write('\r\x1b[K');
}
function printState(s) {
if (!s) return;
const { nomi, punt, set, servHome } = s.sp;
const homeServ = servHome ? `${c.yellow}${c.reset}` : ' ';
const guestServ = !servHome ? `${c.yellow}${c.reset}` : ' ';
const homeName = nomi.home.padEnd(15);
const guestName = nomi.guest.padEnd(15);
const homeScore = String(punt.home).padStart(3);
const guestScore = String(punt.guest).padStart(3);
clearLine();
console.log(
` ${homeServ} ${c.bold}${homeName}${c.reset}` +
`${c.brightWhite}${homeScore}${c.reset} ${c.dim}(set ${set.home})${c.reset}` +
` ${c.dim}${c.reset} ` +
`${c.brightWhite}${guestScore}${c.reset} ${c.dim}(set ${set.guest})${c.reset}` +
` ${c.bold}${guestName}${c.reset} ${guestServ}` +
` ${c.dim}[${s.modalitaPartita}]${c.reset}`
);
}
function printHelp() {
console.log(`
${c.bold} Punteggio${c.reset}
${c.cyan}+${c.reset} / ${c.cyan}pc${c.reset} Punto casa (shortcut)
${c.cyan}-${c.reset} / ${c.cyan}po${c.reset} Punto ospite (shortcut)
${c.cyan}punto casa${c.reset} Punto casa
${c.cyan}punto ospite${c.reset} Punto ospite
${c.cyan}undo${c.reset} / ${c.cyan}u${c.reset} Annulla ultimo punto
${c.bold} Set${c.reset}
${c.cyan}set casa${c.reset} Incrementa set casa
${c.cyan}set ospite${c.reset} Incrementa set ospite
${c.bold} Partita${c.reset}
${c.cyan}serv${c.reset} Cambia servizio (solo se 0-0)
${c.cyan}reset${c.reset} Resetta la partita (chiede conferma)
${c.cyan}nomi <casa> <ospite>${c.reset} Imposta nomi squadre
${c.cyan}modalita 2/3${c.reset} Imposta modalità best-of-3
${c.cyan}modalita 3/5${c.reset} Imposta modalità best-of-5
${c.bold} Informazioni${c.reset}
${c.cyan}stato${c.reset} Mostra punteggio attuale
${c.cyan}help${c.reset} Mostra questo aiuto
${c.cyan}exit${c.reset} / ${c.cyan}q${c.reset} Esci
${c.dim}Suggerimento: usa Tab per il completamento automatico dei comandi.${c.reset}
`);
}
// ---------------------------------------------------------------------------
// Command dispatch
// ---------------------------------------------------------------------------
function sendAction(action) {
if (!connected || ws.readyState !== WebSocket.OPEN) {
console.error(` ${c.red}Non connesso al server.${c.reset}`);
rl.prompt();
return;
}
ws.send(JSON.stringify({ type: 'action', action }));
}
function parseCommand(line) {
const parts = line.trim().split(/\s+/);
const cmd = parts[0].toLowerCase();
switch (cmd) {
case '+':
case 'pc':
sendAction({ type: 'incPunt', team: 'home' });
break;
case '-':
case 'po':
sendAction({ type: 'incPunt', team: 'guest' });
break;
case 'punto': {
const team = parts[1]?.toLowerCase();
if (team === 'casa' || team === 'home') {
sendAction({ type: 'incPunt', team: 'home' });
} else if (team === 'ospite' || team === 'guest') {
sendAction({ type: 'incPunt', team: 'guest' });
} else {
console.error(` ${c.red}Uso: punto casa | punto ospite${c.reset}`);
rl.prompt();
}
break;
}
case 'undo':
case 'u':
sendAction({ type: 'decPunt' });
break;
case 'set': {
const team = parts[1]?.toLowerCase();
if (team === 'casa' || team === 'home') {
sendAction({ type: 'incSet', team: 'home' });
} else if (team === 'ospite' || team === 'guest') {
sendAction({ type: 'incSet', team: 'guest' });
} else {
console.error(` ${c.red}Uso: set casa | set ospite${c.reset}`);
rl.prompt();
}
break;
}
case 'serv':
sendAction({ type: 'cambiaPalla' });
break;
case 'reset':
rl.question(` ${c.yellow}Confermi reset partita? (s/N) ${c.reset}`, (answer) => {
if (answer.trim().toLowerCase() === 's') {
sendAction({ type: 'resetta' });
} else {
console.log(` ${c.dim}Reset annullato.${c.reset}`);
rl.prompt();
}
});
return;
case 'nomi': {
const home = parts[1];
const guest = parts[2];
if (!home) {
console.error(` ${c.red}Uso: nomi <casa> <ospite>${c.reset}`);
rl.prompt();
break;
}
const payload = { type: 'setNomi', home };
if (guest) payload.guest = guest;
sendAction(payload);
break;
}
case 'modalita': {
const m = parts[1];
if (m !== '2/3' && m !== '3/5') {
console.error(` ${c.red}Uso: modalita 2/3 | modalita 3/5${c.reset}`);
rl.prompt();
break;
}
sendAction({ type: 'setModalita', modalita: m });
break;
}
case 'stato':
printState(currentState);
rl.prompt();
break;
case 'help':
printHelp();
rl.prompt();
break;
case 'exit':
case 'q':
ws.close();
break;
default:
console.error(
` ${c.red}Comando non riconosciuto: "${cmd}"${c.reset}` +
` — digita ${c.bold}help${c.reset} per la lista`
);
rl.prompt();
}
}
// ---------------------------------------------------------------------------
// REPL
// ---------------------------------------------------------------------------
const TAB_COMPLETIONS = [
'+', '-', 'pc', 'po',
'punto casa', 'punto ospite',
'undo', 'u',
'set casa', 'set ospite',
'serv',
'reset',
'nomi',
'modalita 2/3', 'modalita 3/5',
'stato', 'help',
'exit', 'q',
];
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: '> ',
historySize: 100,
completer(line) {
const hits = TAB_COMPLETIONS.filter((entry) => entry.startsWith(line));
return [hits.length ? hits : TAB_COMPLETIONS, line];
},
});
rl.on('line', (line) => {
if (!line.trim()) {
rl.prompt();
return;
}
parseCommand(line.trim());
});
rl.on('close', () => {
ws.close();
});
+1 -3
View File
@@ -1,14 +1,12 @@
{ {
"name": "segnapuntianto", "name": "segnapuntianto",
"private": true, "private": true,
"version": "0.0.0", "version": "2.0.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"serve": "vite build && node server.js", "serve": "vite build && node server.js",
"cli": "node cli.js",
"cli:dev": "node cli.js 5173",
"test": "vitest", "test": "vitest",
"test:unit": "vitest run tests/unit tests/integration", "test:unit": "vitest run tests/unit tests/integration",
"test:component": "vitest run tests/component", "test:component": "vitest run tests/component",
-303
View File
@@ -1,303 +0,0 @@
import { vi, describe, it, expect, beforeAll, beforeEach } from 'vitest'
// vi.hoisted garantisce che refs sia disponibile nelle factory dei mock,
// che vengono hoistate prima degli import statici.
const refs = vi.hoisted(() => ({ ws: null, rl: null }))
// ---------------------------------------------------------------------------
// Mock: ws
// ---------------------------------------------------------------------------
vi.mock('ws', async () => {
const { EventEmitter } = await import('events')
class WebSocket extends EventEmitter {
static OPEN = 1
constructor() {
super()
this.readyState = 1
this.send = vi.fn()
this.close = vi.fn()
refs.ws = this
}
}
return { WebSocket }
})
// ---------------------------------------------------------------------------
// Mock: readline
// ---------------------------------------------------------------------------
vi.mock('readline', async () => {
const { EventEmitter } = await import('events')
return {
default: {
createInterface: vi.fn(() => {
const rl = new EventEmitter()
rl.prompt = vi.fn()
rl.question = vi.fn()
rl.close = vi.fn()
refs.rl = rl
return rl
}),
},
}
})
// ---------------------------------------------------------------------------
// Silenzia output e blocca process.exit durante i test
// ---------------------------------------------------------------------------
vi.spyOn(process, 'exit').mockImplementation(() => {})
vi.spyOn(process.stdout, 'write').mockReturnValue(true)
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
// ---------------------------------------------------------------------------
// Importa cli.js — esegue gli effetti collaterali con le dipendenze mockate
// ---------------------------------------------------------------------------
beforeAll(async () => {
await import('../../cli.js')
refs.ws.emit('open')
})
// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------
function sendLine(line) {
refs.rl.emit('line', line)
}
function lastSent() {
const calls = refs.ws.send.mock.calls
return calls.length ? JSON.parse(calls[calls.length - 1][0]) : null
}
// ---------------------------------------------------------------------------
// Test
// ---------------------------------------------------------------------------
describe('CLI — Registrazione', () => {
it('invia register con ruolo controller all\'apertura del WebSocket', () => {
const call = refs.ws.send.mock.calls.find((c) => {
try { return JSON.parse(c[0]).type === 'register' } catch { return false }
})
expect(call).toBeDefined()
expect(JSON.parse(call[0])).toEqual({ type: 'register', role: 'controller' })
})
})
describe('CLI — Ricezione messaggi', () => {
beforeEach(() => {
refs.rl.prompt.mockClear()
vi.mocked(console.error).mockClear()
})
it('ripristina il prompt dopo un messaggio "state"', () => {
const state = {
sp: { nomi: { home: 'A', guest: 'B' }, punt: { home: 0, guest: 0 }, set: { home: 0, guest: 0 }, servHome: true },
modalitaPartita: '3/5',
}
refs.ws.emit('message', JSON.stringify({ type: 'state', state }))
expect(refs.rl.prompt).toHaveBeenCalled()
})
it('mostra un errore alla ricezione di un messaggio "error"', () => {
refs.ws.emit('message', JSON.stringify({ type: 'error', message: 'azione non valida' }))
expect(console.error).toHaveBeenCalled()
})
})
describe('CLI — Comandi punteggio', () => {
beforeEach(() => refs.ws.send.mockClear())
it('"+" → incPunt home', () => {
sendLine('+')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'incPunt', team: 'home' } })
})
it('"pc" → incPunt home (shortcut)', () => {
sendLine('pc')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'incPunt', team: 'home' } })
})
it('"-" → incPunt guest', () => {
sendLine('-')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'incPunt', team: 'guest' } })
})
it('"po" → incPunt guest (shortcut)', () => {
sendLine('po')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'incPunt', team: 'guest' } })
})
it('"punto casa" → incPunt home', () => {
sendLine('punto casa')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'incPunt', team: 'home' } })
})
it('"punto ospite" → incPunt guest', () => {
sendLine('punto ospite')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'incPunt', team: 'guest' } })
})
it('"punto" senza squadra → errore, nessun invio', () => {
sendLine('punto')
expect(refs.ws.send).not.toHaveBeenCalled()
expect(console.error).toHaveBeenCalled()
})
it('"undo" → decPunt', () => {
sendLine('undo')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'decPunt' } })
})
it('"u" → decPunt (shortcut)', () => {
sendLine('u')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'decPunt' } })
})
})
describe('CLI — Comandi set', () => {
beforeEach(() => refs.ws.send.mockClear())
it('"set casa" → incSet home', () => {
sendLine('set casa')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'incSet', team: 'home' } })
})
it('"set ospite" → incSet guest', () => {
sendLine('set ospite')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'incSet', team: 'guest' } })
})
it('"set" senza squadra → errore, nessun invio', () => {
sendLine('set')
expect(refs.ws.send).not.toHaveBeenCalled()
expect(console.error).toHaveBeenCalled()
})
})
describe('CLI — Comandi partita', () => {
beforeEach(() => refs.ws.send.mockClear())
it('"serv" → cambiaPalla', () => {
sendLine('serv')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'cambiaPalla' } })
})
it('"nomi <casa> <ospite>" → setNomi con entrambi i nomi', () => {
sendLine('nomi Antoniana Riviera')
expect(lastSent()).toMatchObject({
type: 'action',
action: { type: 'setNomi', home: 'Antoniana', guest: 'Riviera' },
})
})
it('"nomi <casa>" → setNomi con solo nome casa', () => {
sendLine('nomi Antoniana')
const sent = lastSent()
expect(sent).toMatchObject({ type: 'action', action: { type: 'setNomi', home: 'Antoniana' } })
expect(sent.action.guest).toBeUndefined()
})
it('"nomi" senza argomenti → errore, nessun invio', () => {
sendLine('nomi')
expect(refs.ws.send).not.toHaveBeenCalled()
expect(console.error).toHaveBeenCalled()
})
it('"modalita 2/3" → setModalita 2/3', () => {
sendLine('modalita 2/3')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'setModalita', modalita: '2/3' } })
})
it('"modalita 3/5" → setModalita 3/5', () => {
sendLine('modalita 3/5')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'setModalita', modalita: '3/5' } })
})
it('"modalita" con valore non valido → errore, nessun invio', () => {
sendLine('modalita 4/7')
expect(refs.ws.send).not.toHaveBeenCalled()
expect(console.error).toHaveBeenCalled()
})
})
describe('CLI — Comando reset (con conferma)', () => {
beforeEach(() => {
refs.ws.send.mockClear()
refs.rl.question.mockClear()
})
it('conferma "s" → invia resetta', () => {
refs.rl.question.mockImplementationOnce((_msg, cb) => cb('s'))
sendLine('reset')
expect(lastSent()).toMatchObject({ type: 'action', action: { type: 'resetta' } })
})
it('risposta "n" → non invia nulla', () => {
refs.rl.question.mockImplementationOnce((_msg, cb) => cb('n'))
sendLine('reset')
expect(refs.ws.send).not.toHaveBeenCalled()
})
it('risposta vuota → non invia nulla', () => {
refs.rl.question.mockImplementationOnce((_msg, cb) => cb(''))
sendLine('reset')
expect(refs.ws.send).not.toHaveBeenCalled()
})
})
describe('CLI — Comandi informativi', () => {
beforeEach(() => {
refs.ws.send.mockClear()
vi.mocked(console.log).mockClear()
})
it('"help" → stampa aiuto, nessun invio', () => {
sendLine('help')
expect(console.log).toHaveBeenCalled()
expect(refs.ws.send).not.toHaveBeenCalled()
})
it('"stato" → nessun invio', () => {
sendLine('stato')
expect(refs.ws.send).not.toHaveBeenCalled()
})
it('comando sconosciuto → messaggio di errore, nessun invio', () => {
sendLine('xyzzy')
expect(refs.ws.send).not.toHaveBeenCalled()
expect(console.error).toHaveBeenCalled()
})
it('riga vuota → nessun invio', () => {
refs.rl.emit('line', ' ')
expect(refs.ws.send).not.toHaveBeenCalled()
})
})
describe('CLI — Uscita', () => {
it('"exit" → chiude il WebSocket', () => {
refs.ws.close.mockClear()
sendLine('exit')
expect(refs.ws.close).toHaveBeenCalled()
})
it('"q" → chiude il WebSocket (shortcut)', () => {
refs.ws.close.mockClear()
sendLine('q')
expect(refs.ws.close).toHaveBeenCalled()
})
it('chiusura readline → chiude il WebSocket', () => {
refs.ws.close.mockClear()
refs.rl.emit('close')
expect(refs.ws.close).toHaveBeenCalled()
})
})