-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.js
534 lines (464 loc) · 18.3 KB
/
app.js
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// DOM Elements
const todoForm = document.getElementById('todoForm');
const todoInput = document.getElementById('todoInput');
const todoList = document.getElementById('todoList');
const themeToggle = document.getElementById('themeToggle');
const moonIcon = themeToggle.querySelector('.moon');
const sunIcon = themeToggle.querySelector('.sun');
const toast = document.getElementById('toast');
const pinModal = document.getElementById('pinModal');
const pinInputs = [...document.querySelectorAll('.pin-input')];
const pinError = document.getElementById('pinError');
const clearCompletedBtn = document.getElementById('clearCompleted');
const listSelector = document.getElementById('listSelector');
const renameListBtn = document.getElementById('renameList');
const deleteListBtn = document.getElementById('deleteList');
const addListBtn = document.getElementById('addList');
// Set up list selector event handlers once
const selectorContainer = listSelector.parentElement;
// Show/hide custom select on click
function handleSelectorClick(e) {
e.preventDefault();
e.stopPropagation();
const customSelect = selectorContainer.querySelector('.custom-select');
if (customSelect) {
const isHidden = customSelect.style.display === 'none' || !customSelect.style.display;
customSelect.style.display = isHidden ? 'block' : 'none';
}
}
// Hide custom select when clicking outside
function handleOutsideClick(e) {
const customSelect = selectorContainer.querySelector('.custom-select');
if (customSelect && !selectorContainer.contains(e.target)) {
customSelect.style.display = 'none';
}
}
// Handle keyboard navigation
function handleKeyboard(e) {
const customSelect = selectorContainer.querySelector('.custom-select');
if (customSelect) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
customSelect.style.display = customSelect.style.display === 'none' ? 'block' : 'none';
} else if (e.key === 'Escape') {
customSelect.style.display = 'none';
}
}
}
// Initialize dropdown event listeners after data is loaded
function initializeDropdown() {
listSelector.addEventListener('mousedown', handleSelectorClick);
document.addEventListener('click', handleOutsideClick);
listSelector.addEventListener('keydown', handleKeyboard);
}
// State
let todos = {};
let currentList = 'List 1';
// List Management
function initializeLists(data) {
if (!data || Object.keys(data).length === 0) {
// Only create List 1 when there are no lists at all
todos = { 'List 1': [] };
currentList = 'List 1';
} else {
// Convert only numeric keys, preserve custom names
const convertedData = {};
Object.entries(data).forEach(([key, value]) => {
// Only convert numeric keys
if (/^\d+$/.test(key)) {
const newKey = `List ${Object.keys(convertedData).length + 1}`;
convertedData[newKey] = value;
} else {
convertedData[key] = value;
}
});
todos = convertedData;
currentList = Object.keys(convertedData)[0];
}
updateListSelector();
renderTodos();
}
function updateListSelector() {
// Sort the list keys to ensure List 1 comes first
const sortedKeys = Object.keys(todos).sort((a, b) => {
if (a === 'List 1') return -1;
if (b === 'List 1') return 1;
return a.localeCompare(b);
});
// Update the native select
listSelector.innerHTML = sortedKeys.map(listId =>
`<option value="${listId}"${listId === currentList ? ' selected' : ''}>${listId}</option>`
).join('');
// Create a custom select
const customSelect = document.createElement('div');
customSelect.className = 'custom-select';
customSelect.style.display = 'none'; // Explicitly set initial state
sortedKeys.forEach(listId => {
const item = document.createElement('div');
item.className = `list-item ${listId === 'List 1' ? 'list-1' : ''}`;
item.dataset.value = listId;
const nameSpan = document.createElement('span');
nameSpan.textContent = listId;
item.appendChild(nameSpan);
if (listId !== 'List 1') {
const deleteBtn = document.createElement('button');
deleteBtn.type = 'button';
deleteBtn.className = 'delete-btn';
deleteBtn.setAttribute('aria-label', `Delete ${listId}`);
deleteBtn.innerHTML = `
<svg viewBox="0 0 24 24">
<path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
`;
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation();
deleteList(listId);
});
item.appendChild(deleteBtn);
}
item.addEventListener('click', () => {
if (listId !== currentList) {
switchList(listId);
customSelect.style.display = 'none';
}
});
customSelect.appendChild(item);
});
// Replace the existing custom select if any
const existingCustomSelect = selectorContainer.querySelector('.custom-select');
if (existingCustomSelect) {
const wasVisible = existingCustomSelect.style.display === 'block';
selectorContainer.removeChild(existingCustomSelect);
if (wasVisible) {
customSelect.style.display = 'block';
}
}
selectorContainer.appendChild(customSelect);
}
function switchList(listId) {
currentList = listId;
listSelector.value = listId; // Update the native select value
renderTodos();
}
function addNewList() {
const listCount = Object.keys(todos).length + 1;
const newListId = `List ${listCount}`;
todos[newListId] = [];
currentList = newListId;
updateListSelector();
renderTodos();
saveTodos();
showToast('New list added');
}
async function renameCurrentList() {
const newName = prompt('Enter new list name:', currentList);
if (newName && newName.trim() && newName !== currentList && !todos[newName]) {
const oldName = currentList;
const oldTodos = { ...todos }; // Keep a full backup
try {
// Update the data structure
todos[newName] = todos[currentList];
delete todos[currentList];
currentList = newName;
// Update UI
updateListSelector();
// Save changes
await saveTodos();
showToast('List renamed');
} catch (error) {
// Revert all changes on failure
todos = oldTodos;
currentList = oldName;
updateListSelector();
showToast('Failed to save list name change');
}
}
}
async function deleteList(listId) {
// Don't allow deleting the last list or List 1
if (Object.keys(todos).length <= 1 || listId === 'List 1') {
showToast('Cannot delete this list');
return;
}
if (confirm(`Are you sure you want to delete "${listId}" and all its tasks?`)) {
const oldTodos = { ...todos };
try {
// Remove the list
delete todos[listId];
// If we're deleting the current list, switch to another one
if (listId === currentList) {
currentList = Object.keys(todos)[0];
}
// Update UI
updateListSelector();
renderTodos();
// Save changes
await saveTodos();
showToast('List deleted');
} catch (error) {
// Revert changes on failure
todos = oldTodos;
updateListSelector();
renderTodos();
showToast('Failed to delete list');
}
}
}
// Event Listeners for List Management
listSelector.addEventListener('change', (e) => {
switchList(e.target.value);
});
renameListBtn.addEventListener('click', renameCurrentList);
addListBtn.addEventListener('click', addNewList);
// Enhanced fetch with auth headers
async function fetchWithAuth(url, options = {}) {
return fetch(url, options);
}
// Theme Management
function updateThemeIcons() {
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
moonIcon.style.display = isDark ? 'none' : 'block';
sunIcon.style.display = isDark ? 'block' : 'none';
}
// Initialize theme icons once DOM is loaded
document.addEventListener('DOMContentLoaded', updateThemeIcons);
themeToggle.addEventListener('click', () => {
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
const newTheme = isDark ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateThemeIcons();
});
// Toast Notification
function showToast(message, duration = 3000) {
toast.textContent = message;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), duration);
}
// Todo Management
async function loadTodos() {
try {
const response = await fetchWithAuth('/api/todos');
if (!response.ok) throw new Error('Failed to load todos');
const data = await response.json();
initializeLists(data);
initializeDropdown(); // Initialize dropdown after data is loaded
} catch (error) {
showToast('Failed to load todos');
console.error(error);
}
}
async function saveTodos() {
try {
const response = await fetchWithAuth('/api/todos', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(todos)
});
if (!response.ok) throw new Error('Failed to save todos');
return true;
} catch (error) {
showToast('Failed to save todos');
console.error(error);
throw error; // Re-throw to handle in calling function
}
}
function createTodoElement(todo) {
const li = document.createElement('li');
li.className = `todo-item ${todo.completed ? 'completed' : ''}`;
// Add drag attributes only for non-completed items
if (!todo.completed) {
li.draggable = true;
li.setAttribute('data-todo-id', todo.text); // Using text as a simple identifier
}
li.innerHTML = `
<div class="checkbox-wrapper">
<input type="checkbox" ${todo.completed ? 'checked' : ''}>
</div>
<span class="todo-text">${linkifyText(todo.text)}</span>
<button class="delete-btn" aria-label="Delete todo">×</button>
`;
const checkbox = li.querySelector('input');
const checkboxWrapper = li.querySelector('.checkbox-wrapper');
const todoText = li.querySelector('.todo-text');
// Add click handler to the wrapper
checkboxWrapper.addEventListener('click', (e) => {
// Only trigger if clicking the wrapper (not the checkbox directly)
if (e.target === checkboxWrapper) {
checkbox.checked = !checkbox.checked;
todo.completed = checkbox.checked;
renderTodos();
saveTodos();
showToast(todo.completed ? 'Task completed! 🎉' : 'Task uncompleted');
}
});
checkbox.addEventListener('change', () => {
todo.completed = checkbox.checked;
renderTodos();
saveTodos();
showToast(todo.completed ? 'Task completed! 🎉' : 'Task uncompleted');
});
// Make text editable on click
todoText.addEventListener('click', (e) => {
// Don't trigger edit if clicking a link
if (e.target.tagName === 'A') return;
const input = document.createElement('input');
input.type = 'text';
input.value = todo.text;
input.className = 'edit-input';
const originalText = todoText.innerHTML;
todoText.replaceWith(input);
input.focus();
function saveEdit() {
const newText = input.value.trim();
if (newText && newText !== todo.text) {
todo.text = newText;
renderTodos();
saveTodos();
showToast('Task updated');
} else {
input.replaceWith(todoText);
todoText.innerHTML = originalText;
}
}
input.addEventListener('blur', saveEdit);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
saveEdit();
} else if (e.key === 'Escape') {
input.replaceWith(todoText);
todoText.innerHTML = originalText;
}
});
});
const deleteBtn = li.querySelector('.delete-btn');
deleteBtn.addEventListener('click', () => {
li.remove();
todos[currentList] = todos[currentList].filter(t => t !== todo);
saveTodos();
showToast('Task deleted');
});
// Add drag and drop event listeners for non-completed items
if (!todo.completed) {
li.addEventListener('dragstart', (e) => {
e.dataTransfer.setData('text/plain', todo.text);
li.classList.add('dragging');
// Set a custom drag image (optional)
const dragImage = li.cloneNode(true);
dragImage.style.position = 'absolute';
dragImage.style.top = '-1000px';
document.body.appendChild(dragImage);
e.dataTransfer.setDragImage(dragImage, 0, 0);
setTimeout(() => document.body.removeChild(dragImage), 0);
});
li.addEventListener('dragend', () => {
li.classList.remove('dragging');
});
li.addEventListener('dragover', (e) => {
e.preventDefault();
const draggingItem = document.querySelector('.dragging');
if (draggingItem && !li.classList.contains('dragging') && !todo.completed) {
const items = [...todoList.querySelectorAll('.todo-item:not(.completed)')];
const currentPos = items.indexOf(draggingItem);
const newPos = items.indexOf(li);
if (currentPos !== newPos) {
const rect = li.getBoundingClientRect();
const midY = rect.top + rect.height / 2;
const mouseY = e.clientY;
if (mouseY < midY) {
li.parentNode.insertBefore(draggingItem, li);
} else {
li.parentNode.insertBefore(draggingItem, li.nextSibling);
}
// Update the todos array to match the new order
const activeTodos = todos[currentList].filter(t => !t.completed);
const completedTodos = todos[currentList].filter(t => t.completed);
const newOrder = [...document.querySelectorAll('.todo-item:not(.completed)')].map(item => {
return activeTodos.find(t => t.text === item.getAttribute('data-todo-id'));
});
todos[currentList] = [...newOrder, ...completedTodos];
saveTodos();
}
}
});
}
return li;
}
// Helper function to convert URLs in text to clickable links
function linkifyText(text) {
// Updated regex that doesn't include trailing punctuation in the URL
const urlRegex = /(https?:\/\/[^\s)]+)([)\s]|$)/g;
return text.replace(urlRegex, (match, url, endChar) => {
// Return the URL as a link plus any trailing character
return `<a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>${endChar}`;
});
}
function renderTodos() {
todoList.innerHTML = '';
const currentTodos = todos[currentList] || [];
// Separate todos into active and completed
const activeTodos = currentTodos.filter(todo => !todo.completed);
const completedTodos = currentTodos.filter(todo => todo.completed);
// Create a container for active todos
const activeTodosContainer = document.createElement('div');
activeTodosContainer.className = 'active-todos';
activeTodosContainer.addEventListener('dragover', (e) => {
e.preventDefault();
const draggingItem = document.querySelector('.dragging');
if (draggingItem) {
const items = [...activeTodosContainer.querySelectorAll('.todo-item')];
if (items.length === 0) {
activeTodosContainer.appendChild(draggingItem);
}
}
});
todoList.appendChild(activeTodosContainer);
// Render active todos
activeTodos.forEach(todo => {
activeTodosContainer.appendChild(createTodoElement(todo));
});
// Add divider if there are both active and completed todos
if (activeTodos.length > 0 && completedTodos.length > 0) {
const divider = document.createElement('li');
divider.className = 'todo-divider';
divider.textContent = 'Completed';
todoList.appendChild(divider);
}
// Render completed todos
completedTodos.forEach(todo => {
todoList.appendChild(createTodoElement(todo));
});
}
// Event Listeners
todoForm.addEventListener('submit', (e) => {
e.preventDefault();
const text = todoInput.value.trim();
if (text) {
const todo = { text, completed: false };
todos[currentList].push(todo);
renderTodos();
saveTodos();
todoInput.value = '';
showToast('Task added');
}
});
// Clear completed tasks
clearCompletedBtn.addEventListener('click', () => {
const currentTodos = todos[currentList];
const completedCount = currentTodos.filter(todo => todo.completed).length;
if (completedCount === 0) {
showToast('No completed tasks to clear');
return;
}
if (confirm(`Are you sure you want to delete ${completedCount} completed task${completedCount === 1 ? '' : 's'}?`)) {
todos[currentList] = currentTodos.filter(todo => !todo.completed);
renderTodos();
saveTodos();
showToast(`Cleared ${completedCount} completed task${completedCount === 1 ? '' : 's'}`);
}
});
// Initialize
loadTodos();