Spaces:
Sleeping
Sleeping
File size: 9,545 Bytes
cce1e0e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | // DOM Elements
const itemForm = document.getElementById('item-form');
const formTitle = document.getElementById('form-title');
const itemIdInput = document.getElementById('item-id');
const titleInput = document.getElementById('title');
const descriptionInput = document.getElementById('description');
const completedCheckbox = document.getElementById('completed');
const submitBtn = document.getElementById('submit-btn');
const cancelBtn = document.getElementById('cancel-btn');
const itemsTableBody = document.getElementById('items-table-body');
const noItemsMessage = document.getElementById('no-items-message');
const createFirstItemBtn = document.getElementById('create-first-item-btn');
const loadingSpinner = document.getElementById('loading-spinner');
const toastElement = document.getElementById('toast');
const toastTitle = document.getElementById('toast-title');
const toastMessage = document.getElementById('toast-message');
const toastIcon = document.getElementById('toast-icon');
// Create Bootstrap toast instance
const toast = new bootstrap.Toast(toastElement, {
delay: 3000
});
// API Endpoints
const API_URL = '/api/items';
// App State
let isEditing = false;
let items = [];
// Event Listeners
document.addEventListener('DOMContentLoaded', fetchItems);
itemForm.addEventListener('submit', handleFormSubmit);
cancelBtn.addEventListener('click', resetForm);
if (createFirstItemBtn) {
createFirstItemBtn.addEventListener('click', () => {
window.scrollTo({
top: itemForm.offsetTop - 100,
behavior: 'smooth'
});
titleInput.focus();
});
}
// Functions
async function fetchItems() {
try {
showLoading(true);
const response = await fetch(API_URL);
const data = await response.json();
// Keep a reference to all items
items = data;
renderItems(items);
showLoading(false);
} catch (error) {
console.error('Error fetching items:', error);
showToast('Error', 'Failed to load items. Please try again.', 'error');
showLoading(false);
}
}
function renderItems(items) {
itemsTableBody.innerHTML = '';
if (items.length === 0) {
noItemsMessage.style.display = 'block';
document.querySelector('.table-responsive').style.display = 'none';
return;
}
noItemsMessage.style.display = 'none';
document.querySelector('.table-responsive').style.display = 'block';
items.forEach(item => {
const row = document.createElement('tr');
row.id = `item-row-${item.id}`;
row.innerHTML = `
<td>${item.id}</td>
<td class="fw-medium">${escapeHtml(item.title)}</td>
<td>${escapeHtml(item.description || '-')}</td>
<td>
<span class="badge completed-${item.completed}">
${item.completed ?
'<i class="bi bi-check-circle me-1"></i>Completed' :
'<i class="bi bi-clock me-1"></i>Pending'}
</span>
</td>
<td class="text-center">
<div class="d-flex justify-content-center">
<button class="action-btn edit-btn" data-id="${item.id}" title="Edit Item">
<i class="bi bi-pencil-square"></i>
</button>
<button class="action-btn delete-btn" data-id="${item.id}" title="Delete Item">
<i class="bi bi-trash"></i>
</button>
</div>
</td>
`;
itemsTableBody.appendChild(row);
// Add event listeners to buttons
const editBtn = row.querySelector('.edit-btn');
const deleteBtn = row.querySelector('.delete-btn');
editBtn.addEventListener('click', () => editItem(item));
deleteBtn.addEventListener('click', () => deleteItem(item.id));
});
}
async function handleFormSubmit(event) {
event.preventDefault();
const itemData = {
title: titleInput.value.trim(),
description: descriptionInput.value.trim(),
completed: completedCheckbox.checked
};
if (!itemData.title) {
showToast('Validation Error', 'Title is required', 'error');
titleInput.focus();
return;
}
try {
showLoading(true);
if (isEditing) {
// Update existing item
const itemId = parseInt(itemIdInput.value);
await updateItem(itemId, itemData);
showToast('Success', 'Item updated successfully!', 'success');
} else {
// Create new item
await createItem(itemData);
showToast('Success', 'New item created successfully!', 'success');
}
resetForm();
fetchItems();
} catch (error) {
console.error('Error saving item:', error);
showToast('Error', 'Failed to save item. Please try again.', 'error');
showLoading(false);
}
}
async function createItem(itemData) {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(itemData)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Failed to create item');
}
return await response.json();
}
async function updateItem(itemId, itemData) {
const response = await fetch(`${API_URL}/${itemId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(itemData)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Failed to update item');
}
return await response.json();
}
async function deleteItem(itemId) {
// Create custom confirm dialog
if (!confirm('Are you sure you want to delete this item? This action cannot be undone.')) {
return;
}
try {
showLoading(true);
const response = await fetch(`${API_URL}/${itemId}`, {
method: 'DELETE'
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Failed to delete item');
}
showToast('Success', 'Item deleted successfully!', 'success');
// Remove item from local array
items = items.filter(item => item.id !== itemId);
// Re-render items
renderItems(items);
showLoading(false);
} catch (error) {
console.error('Error deleting item:', error);
showToast('Error', 'Failed to delete item. Please try again.', 'error');
showLoading(false);
}
}
function editItem(item) {
// Set form to edit mode
isEditing = true;
formTitle.innerHTML = '<i class="bi bi-pencil-square me-2"></i>Edit Item';
submitBtn.innerHTML = '<i class="bi bi-save me-2"></i>Update';
cancelBtn.style.display = 'block';
// Populate form with item data
itemIdInput.value = item.id;
titleInput.value = item.title;
descriptionInput.value = item.description || '';
completedCheckbox.checked = item.completed;
// Scroll to form
window.scrollTo({
top: itemForm.offsetTop - 100,
behavior: 'smooth'
});
// Add highlight class to row
const row = document.getElementById(`item-row-${item.id}`);
if (row) {
row.classList.add('highlight-row');
setTimeout(() => {
row.classList.remove('highlight-row');
}, 2000);
}
// Focus on title input
titleInput.focus();
}
function resetForm() {
// Reset form state
isEditing = false;
formTitle.innerHTML = '<i class="bi bi-plus-circle me-2"></i>Add New Item';
submitBtn.innerHTML = '<i class="bi bi-save me-2"></i>Save';
cancelBtn.style.display = 'none';
// Clear form inputs
itemForm.reset();
itemIdInput.value = '';
}
function showToast(title, message, type = 'info') {
toastTitle.textContent = title;
toastMessage.textContent = message;
// Remove any existing classes
toastElement.classList.remove('bg-success', 'bg-danger', 'bg-info', 'bg-warning', 'text-white');
toastIcon.classList.remove('bi-check-circle-fill', 'bi-exclamation-triangle-fill', 'bi-info-circle-fill');
// Add appropriate styling based on type
if (type === 'success') {
toastElement.classList.add('bg-success', 'text-white');
toastIcon.classList.add('bi-check-circle-fill');
} else if (type === 'error') {
toastElement.classList.add('bg-danger', 'text-white');
toastIcon.classList.add('bi-exclamation-triangle-fill');
} else {
toastElement.classList.add('bg-info', 'text-white');
toastIcon.classList.add('bi-info-circle-fill');
}
toast.show();
}
function showLoading(isLoading) {
if (isLoading) {
loadingSpinner.style.display = 'inline-block';
} else {
loadingSpinner.style.display = 'none';
}
}
// Utility function to prevent XSS
function escapeHtml(str) {
if (!str) return '';
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
} |