This commit is contained in:
2026-02-11 22:40:34 +01:00
parent 88ba970316
commit ed35f3cfd7
3 changed files with 218 additions and 288 deletions

View File

@@ -23,7 +23,7 @@
</div>
<!-- SEZIONE AGGIUNTA TODO -->
<div id="addTodoSection" class="add-todo-box" style="display: none;">
<div id="addTodoSection" class="add-todo-box nascosto">
<h2> Aggiungi Nuovo TODO</h2>
<div class="input-group">
<input type="text" id="todoInput" placeholder="Scrivi un nuovo TODO...">
@@ -32,60 +32,15 @@
</div>
<!-- LOADING -->
<div id="loading" class="loading" style="display: none;">
<div id="loading" class="loading nascosto">
⏳ Caricamento...
</div>
<!-- COUNTER -->
<div id="counter" class="counter" style="display: none;"></div>
<div id="counter" class="counter nascosto"></div>
<!-- LISTA TODO -->
<div id="todosContainer" class="todos-container"></div>
<!-- ISTRUZIONI -->
<div class="instructions">
<h2>📝 Cosa Devi Fare</h2>
<p style="margin-bottom: 15px;"><strong>Questa è l'esercitazione finale!</strong> Devi implementare TUTTE le operazioni CRUD:</p>
<h3>1⃣ Carica TODO (GET)</h3>
<ul style="margin-left: 20px; margin-bottom: 15px;">
<li>Fai una GET a <code>/todos?userId={id}</code> per ottenere i TODO dell'utente</li>
<li>Visualizza la lista</li>
</ul>
<h3>2⃣ Aggiungi TODO (POST)</h3>
<ul style="margin-left: 20px; margin-bottom: 15px;">
<li>Fai una POST a <code>/todos</code> con: <code>{userId, titolo, completato: false}</code></li>
<li>Ricarica la lista</li>
</ul>
<h3>3⃣ Modifica TODO (PUT)</h3>
<ul style="margin-left: 20px; margin-bottom: 15px;">
<li>Fai una PUT a <code>/todos/{id}</code> con: <code>{completato: !currentValue}</code></li>
<li>Aggiorna la lista</li>
</ul>
<h3>4⃣ Elimina TODO (DELETE)</h3>
<ul style="margin-left: 20px; margin-bottom: 15px;">
<li>Fai una DELETE a <code>/todos/{id}</code></li>
<li>Rimuovi dalla lista</li>
</ul>
<div class="hint">
<strong>💡 Struttura del codice:</strong>
<pre>// Funzioni che devi implementare:
loadUserTodos(userId) // GET
addTodo() // POST
toggleTodo(id, current) // PUT
deleteTodo(id) // DELETE
displayTodos(todos) // Visualizza (già fatto)</pre>
</div>
<div class="challenge">
<strong>🎯 Bonus Challenge:</strong>
<p>Aggiungi un riepilogo: quanti TODO sono completati vs quanti rimangono?</p>
</div>
</div>
</div>
<script src="script.js"></script>

View File

@@ -1,174 +1,31 @@
// ⚠️ COMPILARE PRIMA DI INIZIARE
// ⚠️ COMPILARE E CONTROLLARE PRIMA DI INIZIARE ⚠️
const BASE_URL = 'http://localhost:3000/api';
const userId = document.querySelector('#userId');
const todoInput = document.querySelector('#todoInput');
const btnAddTodo = document.querySelector('#btnAddTodo');
const addTodoSection = document.querySelector('#addTodoSection');
const btnLoadTodos = document.querySelector('#btnLoadTodos');
const todosContainer = document.querySelector('#todosContainer');
const loading = document.querySelector('#loading');
const counter = document.querySelector('#counter');
// ===== VARIABILE DI STATO =====
// Tiene traccia dell'ID utente attualmente caricato
// Viene usata per sapere a quale utente associare i nuovi TODO
// DA COMPLETARE: Carica questa variabile dal localStorage (se presente)
let currentUserId = null;
/**
* ESERCIZIO 4: Todo App CRUD Completa
*
* Devi implementare 4 funzioni:
* 1. loadUserTodos() - GET /todos?userId={id}
* 2. addTodo() - POST /todos
* 3. toggleTodo() - PUT /todos/{id}
* 4. deleteTodo() - DELETE /todos/{id}
*/
// ======== 1⃣ CARICA TODO (GET) ========
/**
* Leggi l'ID utente, fai GET a /todos?userId={id}
* Mostra la lista con displayTodos()
*/
async function loadUserTodos() {
const userId = document.getElementById('userId').value;
if (!userId || userId < 1 || userId > 40) {
alert('Inserisci un ID valido tra 1 e 40');
return;
}
currentUserId = userId;
const loading = document.getElementById('loading');
const container = document.getElementById('todosContainer');
const addSection = document.getElementById('addTodoSection');
const counter = document.getElementById('counter');
loading.style.display = 'block';
container.innerHTML = '';
counter.style.display = 'none';
try {
// 👇 SCRIVI QUI - Fai fetch GET a /todos con query parameter userId
// const response = await fetch(BASE_URL + '/todos?userId=' + userId);
// const todos = await response.json();
// displayTodos(todos);
throw new Error('Codice non implementato - Completa loadUserTodos()');
} catch (error) {
container.innerHTML = `<div class="error">❌ ${error.message}</div>`;
console.error('Errore:', error);
} finally {
loading.style.display = 'none';
addSection.style.display = 'block';
}
}
// ======== 2⃣ AGGIUNGI TODO (POST) ========
/**
* Leggi il testo dall'input
* Fai POST a /todos con {userId, titolo, completato: false}
* Ricarica la lista
*/
async function addTodo() {
if (!currentUserId) {
alert('Carica prima una lista di TODO!');
return;
}
const input = document.getElementById('todoInput');
const titolo = input.value.trim();
if (!titolo) {
alert('Scrivi un TODO!');
return;
}
try {
// 👇 SCRIVI QUI - Fai fetch POST
// const response = await fetch(BASE_URL + '/todos', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ userId: currentUserId, titolo, completato: false })
// });
// input.value = '';
// loadUserTodos();
throw new Error('Codice non implementato - Completa addTodo()');
} catch (error) {
alert('Errore: ' + error.message);
console.error('Errore:', error);
}
}
// ======== 3⃣ MODIFICA TODO (PUT) ========
/**
* Fai PUT a /todos/{id} con {completato: !currentValue}
* Ricarica la lista
*/
async function toggleTodo(id, currentCompleted) {
try {
// 👇 SCRIVI QUI - Fai fetch PUT
// const response = await fetch(BASE_URL + '/todos/' + id, {
// method: 'PUT',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ completato: !currentCompleted })
// });
// loadUserTodos();
throw new Error('Codice non implementato - Completa toggleTodo()');
} catch (error) {
alert('Errore: ' + error.message);
console.error('Errore:', error);
}
}
// ======== 4⃣ ELIMINA TODO (DELETE) ========
/**
* Chiedi conferma con confirm()
* Fai DELETE a /todos/{id}
* Ricarica la lista
*/
async function deleteTodo(id) {
if (!confirm('Sei sicuro di voler eliminare questo TODO?')) {
return;
}
try {
// 👇 SCRIVI QUI - Fai fetch DELETE
// const response = await fetch(BASE_URL + '/todos/' + id, {
// method: 'DELETE'
// });
// loadUserTodos();
throw new Error('Codice non implementato - Completa deleteTodo()');
} catch (error) {
alert('Errore: ' + error.message);
console.error('Errore:', error);
}
}
/**
* Visualizza i TODO
* (Questa funzione è già fatta - non modificare)
* FUNZIONE: Crea la card HTML per tutti i TODO passati come parametro
*/
function displayTodos(todos) {
const container = document.getElementById('todosContainer');
const counter = document.getElementById('counter');
if (!Array.isArray(todos) || todos.length === 0) {
container.innerHTML = '<div class="empty">Nessun TODO. Creane uno!</div>';
counter.style.display = 'none';
return;
}
// CONTA COMPLETATI E NON
const completed = todos.filter(t => t.completato).length;
const pending = todos.length - completed;
// MOSTRA COUNTER
counter.innerHTML = `
📊 Totale: <strong>${todos.length}</strong> |
✅ Completati: <strong>${completed}</strong> |
⏳ In Sospeso: <strong>${pending}</strong>
`;
counter.style.display = 'block';
// CREA CARD TODO
const todosHTML = todos.map(todo => `
<div class="todo-item ${todo.completato ? 'completed' : ''}">
function creaCardTodos(todoList) {
allTodos = todoList.map((todo) => `
<div class="todo-item ${todo.completato ? 'completed' : ''}">
<div class="todo-checkbox">
<input type="checkbox"
${todo.completato ? 'checked' : ''}
@@ -182,15 +39,135 @@ function displayTodos(todos) {
</div>
`).join('');
container.innerHTML = todosHTML;
todosContainer.innerHTML = allTodos;
}
// ======== COLLEGA GLI EVENTI ========
document.getElementById('btnLoadTodos').addEventListener('click', loadUserTodos);
document.getElementById('btnAddTodo').addEventListener('click', addTodo);
/**
* FUNZIONE: Gestione errori
*
* Mostra un messaggio di errore e logga in console
*/
function handleError(message) {
todosContainer.innerHTML = `
<div class="error">
<strong>❌ ${message}</strong>
</div>
`;
console.error('Errore:', message);
}
/**
* ESERCIZIO 4: Todo App CRUD Completa
*
* Devi implementare 4 funzioni:
* 1. fetchTodosUtente() - GET /todos?userId={id}
* 2. addTodo() - POST /todos
* 3. toggleTodo() - PUT /todos/{id}
* 4. deleteTodo() - DELETE /todos/{id}
*/
/**
* FUNZIONE 1⃣: Carica TODO (GET)
*
* Passi:
* 1. Leggi l'ID utente dall'input
* 2. Valida che sia un numero tra 1 e 40
* 3. Mostra lo spinner di caricamento
* 4. Apri un blocco try/catch
* 5. Fai una GET a /todos?userId={id}
* 6. Se non OK, mostra errore e return
* 7. Converti la risposta in JSON
* 8. Chiama displayTodos() per visualizzare
* 9. Nascondi lo spinner e mostra addTodoSection
* 10. Salva l'ID utente in currentUserId (e localStorage)
*/
async function fetchTodosUtente() {
}
/**
* FUNZIONE 2⃣: Aggiungi TODO (POST)
*
* Passi:
* 1. Verifica che un utente sia stato caricato (currentUserId)
* 2. Leggi il testo dal campo di input del nuovo TODO
* 3. Valida con trim che non sia vuoto
* 4. Mostra lo spinner di caricamento
* 5. Apri un blocco try/catch
* 6. Fai una POST a /todos con body: {userId, titolo, completato: false}
* 7. Se non OK, mostra errore
* 8. Se OK, svuota l'input
* 9. Ricarica la lista chiamando fetchTodosUtente()
*/
async function addTodo() {
}
/**
* FUNZIONE 3⃣: Modifica TODO (PUT)
*
* Passi:
* 1. Ricevi id e currentCompleted come parametri
* 2. Fai una PUT a /todos/{id} con body: {completato: !currentCompleted}
* 3. Se non OK, mostra errore
* 4. Se OK, ricarica la lista chiamando fetchTodosUtente()
*/
async function toggleTodo(id, currentCompleted) {
}
/**
* FUNZIONE 4⃣: Elimina TODO (DELETE)
*
* Passi:
* 1. Chiedi conferma con confirm("Sicuro?")
* 2. Se l'utente cancella, return
* 3. Fai una DELETE a /todos/{id}
* 4. Se non OK, mostra errore
* 5. Se OK, ricarica la lista chiamando fetchTodosUtente()
*/
async function deleteTodo(id) {
}
/**
* FUNZIONE: Visualizza i TODO
* Funzione già fatta - non modificare
*/
function displayTodos(todos) {
if (!Array.isArray(todos) || todos.length === 0) {
todosContainer.innerHTML = '<div class="empty">Nessun TODO. Creane uno!</div>';
counter.classList.add('nascosto');
return;
}
// CONTA COMPLETATI E NON
const completed = todos.filter(t => t.completato).length;
const pending = todos.length - completed;
// MOSTRA COUNTER
counter.innerHTML = `
📊 Totale: <strong>${todos.length}</strong> |
✅ Completati: <strong>${completed}</strong> |
⏳ In Sospeso: <strong>${pending}</strong>
`;
counter.classList.remove('nascosto');
// CREA CARD TODO
const todosHTML = todos.map(todo => creaCardTodos(todo)).join('');
todosContainer.innerHTML = todosHTML;
}
// ===== COLLEGA GLI EVENTI =====
btnLoadTodos.addEventListener('click', fetchTodosUtente);
btnAddTodo.addEventListener('click', addTodo);
// PERMETTI ENTER per aggiungere TODO
document.getElementById('todoInput').addEventListener('keypress', (e) => {
todoInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
addTodo();
}

View File

@@ -33,18 +33,28 @@ h1 {
font-size: 1rem;
}
.config-box, .add-todo-box {
.config-box,
.add-todo-box {
background: #f9f9f9;
padding: 20px;
border-radius: 10px;
margin-bottom: 25px;
}
.config-box label, .add-todo-box label {
.config-box h2,
.add-todo-box h2 {
color: #333;
margin: 0 0 15px 0;
font-size: 1.1rem;
}
.config-box label,
.add-todo-box label {
display: block;
color: #555;
font-weight: 600;
margin-bottom: 10px;
font-size: 0.95rem;
}
.input-group {
@@ -54,7 +64,7 @@ h1 {
.input-group input {
flex: 1;
padding: 12px;
padding: 10px;
border: 2px solid #ddd;
border-radius: 6px;
font-size: 15px;
@@ -64,6 +74,7 @@ h1 {
.input-group input:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 5px rgba(0, 123, 255, 0.2);
}
.input-group button {
@@ -74,6 +85,8 @@ h1 {
border-radius: 6px;
font-weight: bold;
cursor: pointer;
transition: background 0.2s;
font-size: 15px;
}
.input-group button:hover {
@@ -82,8 +95,9 @@ h1 {
.loading {
text-align: center;
color: white;
font-si#666
color: #666;
font-size: 1rem;
padding: 30px;
animation: pulse 1s infinite;
}
@@ -93,40 +107,42 @@ h1 {
}
.counter {
background: rgba(255, 255, 255, 0.2);
color: white;
padding: 15p#f0f0f0;
background: #f0f8ff;
color: #333;
padding: 12px;
padding: 15px;
border-radius: 6px;
margin-bottom: 20px;
font-weight: bold;
text-align: center
font-weight: 500;
text-align: center;
border-left: 4px solid #007bff;
}
.todos-container {
display: flex;
flex-direction: column;
gap: 12px;
margin-bottom: 50px;
}0px;
margin-bottom: 3
margin-bottom: 30px;
}
.todo-item {
background: white;
padding: 15p#f9f9f9;
padding: 12px;
padding: 15px;
border-radius: 6px;
display: flex;
gap: 12px;
align-items: center;
border-left: 4px solid #007bff;
animation: slideIn 0.2s ease-out
animation: slideIn 0.2s ease-out;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.todo-item.completed {
background: #f5f5f5;
border-left-color: #4caf50;
border-left-color: #28a745;
opacity: 0.7;
}0f0f0;
opacity: 0.7;
border-left-color: #28a745eted .todo-title {
}
.todo-item.completed .todo-title {
text-decoration: line-through;
color: #999;
}
@@ -136,7 +152,7 @@ h1 {
opacity: 0;
transform: translateX(-20px);
}
to {1
to {
opacity: 1;
transform: translateX(0);
}
@@ -149,8 +165,8 @@ h1 {
.todo-checkbox input {
width: 20px;
height: 20px;
cursor:18px;
height: 18
cursor: pointer;
}
.todo-content {
flex: 1;
@@ -159,51 +175,51 @@ h1 {
.todo-title {
color: #333;
font-weight: 500;
font-size: 1em;
margin-bottom: 4px;
}margin: 0
.todo-id {
color: #999;
font-size: 0.8em;
font-size: 1rem;
margin: 0 0 4px 0;
}
.btn-delete {rem;
margin: 2px 0 0 0
padding: 8px 12px;
background: #fee;
color: #c6px 10px;
.todo-id {
color: #999;
font-size: 0.8rem;
margin: 0;
}
.btn-delete {
padding: 6px 12px;
background: #fee;
color: #c00;
border: 1px solid #fcc;
border-radius: 4px;
cursor: pointer;
font-weight: 500
font-weight: 500;
transition: background 0.2s;
}
.btn-delete:hover {
background: #fcc;
color: #800;
}
.empty {
background: white;
color: #999;
padding: 40p#f0f0f0;
color: #999;
padding: 30px;
text-align: center;
border-radius: 6px;
border: 1
border: 1px solid #eee;
}
.error {
background: #fee;
color: #c00;
padding: 15px;
border-radius: 8px;
border-radius: 6px;
border-left: 4px solid #c00;
font-weight: 506px;
border-left: 4px solid #c
font-weight: 500;
}
.instructions {
background: rgba(255, 255, 255, 0.95);
padding: 25px;
border-ra-box {
background: #f9f9f9;
padding: 20px;
border-radius: 10px;
@@ -211,29 +227,30 @@ h1 {
margin-top: 30px;
}
.instructions-box h2 {
.instructions h2 {
color: #333;
margin: 0 0 15px 0;
font-size: 1.1rem;
}
.instructions-box h3 {
.instructions h3 {
color: #555;
margin: 15px 0 10px 0;
font-size: 1rem;
}
.instructions-box ol, .instructions-box ul {
.instructions ol,
.instructions ul {
margin-left: 20px;
color: #555;
line-height: 1.7;
}
.instructions-box li {
.instructions li {
margin-bottom: 8px;
}
.instructions-box code {
.instructions code {
background: white;
padding: 2px 5px;
border-radius: 3px;
@@ -242,25 +259,6 @@ h1 {
font-size: 0.9em;
}
.hint {
background: white;
border: 1px solid #ddd;
padding: 15px;
border-radius: 6px;
margin-top: 15px;
.nascosto {
display: none;
}
.hint strong {
color: #007bff;
display: block;
margin-bottom: 10px;
}
.hint pre {
background: #f0f0f0;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 0.8em;
color: #333;
margin: 0