-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
563 lines (482 loc) · 20.8 KB
/
Copy pathapp.js
File metadata and controls
563 lines (482 loc) · 20.8 KB
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// Permalist Ultra - SQL.js Powered Todo App
class PermalistUltra {
constructor() {
this.db = null;
this.currentPriority = 'low';
this.currentFilter = 'all';
this.init();
}
async init() {
// Initialize SQL.js database
await this.initDatabase();
// Load todos from database
await this.loadTodos();
// Setup event listeners
this.setupEventListeners();
// Update stats
this.updateStats();
// Set initial theme
this.setThemeFromPreference();
}
async initDatabase() {
try {
// Initialize SQL.js
const SQL = await initSqlJs({
locateFile: file => `./${file}`
});
// Create or open database
this.db = new SQL.Database();
// Create todos table if it doesn't exist
this.db.run(`
CREATE TABLE IF NOT EXISTS todos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
completed BOOLEAN DEFAULT 0,
priority TEXT DEFAULT 'low',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
completed_at DATETIME
)
`);
console.log('SQL.js database initialized successfully');
} catch (error) {
console.error('Failed to initialize SQL.js:', error);
this.showToast('Failed to initialize database. Using fallback storage.', 'error');
// Fallback to localStorage
this.useLocalStorageFallback();
}
}
useLocalStorageFallback() {
this.db = {
run: (sql, params = []) => {
console.log('Fallback: run', sql, params);
return { changes: 0 };
},
exec: (sql, params = []) => {
console.log('Fallback: exec', sql, params);
return { columns: [], values: [] };
},
prepare: (sql, params = []) => ({
getAsObject: () => ({}),
bind: () => {},
step: () => false,
free: () => {}
})
};
// Load from localStorage
const storedTodos = localStorage.getItem('permalist_todos');
if (storedTodos) {
try {
const todos = JSON.parse(storedTodos);
todos.forEach(todo => {
const sql = `INSERT INTO todos (id, title, completed, priority, created_at) VALUES (?, ?, ?, ?, ?)`;
this.db.run(sql, [todo.id, todo.title, todo.completed ? 1 : 0, todo.priority, todo.created_at]);
});
} catch (e) {
console.error('Failed to load from localStorage:', e);
}
}
}
async loadTodos() {
try {
const result = this.db.exec(`
SELECT id, title, completed, priority,
datetime(created_at) as created_at,
datetime(completed_at) as completed_at
FROM todos
ORDER BY
CASE priority
WHEN 'critical' THEN 1
WHEN 'high' THEN 2
WHEN 'medium' THEN 3
WHEN 'low' THEN 4
END,
created_at DESC
`);
const todos = result.values ? result.values.map(row => ({
id: row[0],
title: row[1],
completed: Boolean(row[2]),
priority: row[3],
created_at: row[4],
completed_at: row[5]
})) : [];
this.renderTodos(todos);
} catch (error) {
console.error('Failed to load todos:', error);
}
}
renderTodos(todos) {
const todoList = document.getElementById('todo-list');
const filteredTodos = this.filterTodos(todos);
if (filteredTodos.length === 0) {
todoList.innerHTML = `
<div class="empty-state">
<i class="fas fa-clipboard-list"></i>
<h3>No missions found</h3>
<p>${this.currentFilter === 'all' ? 'Add your first mission to get started!' : 'No missions match your filter'}</p>
</div>
`;
return;
}
todoList.innerHTML = filteredTodos.map(todo => `
<div class="todo-item ${todo.completed ? 'completed' : ''}" data-id="${todo.id}">
<div class="todo-checkbox ${todo.completed ? 'checked' : ''}"
onclick="app.toggleTodo(${todo.id})"></div>
<div class="todo-content">
<div class="todo-title">${this.escapeHtml(todo.title)}</div>
<div class="todo-meta">
<span class="priority-badge ${todo.priority}">${this.formatPriority(todo.priority)}</span>
<span class="todo-date">${this.formatDate(todo.created_at)}</span>
</div>
</div>
<div class="todo-actions">
<button class="todo-action-btn" onclick="app.editTodo(${todo.id})" title="Edit">
<i class="fas fa-edit"></i>
</button>
<button class="todo-action-btn" onclick="app.deleteTodo(${todo.id})" title="Delete">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
`).join('');
}
filterTodos(todos) {
switch (this.currentFilter) {
case 'active':
return todos.filter(todo => !todo.completed);
case 'completed':
return todos.filter(todo => todo.completed);
case 'high':
return todos.filter(todo => todo.priority === 'high' || todo.priority === 'critical');
default:
return todos;
}
}
async addTodo(title) {
if (!title.trim()) {
this.showToast('Please enter a mission title', 'warning');
return;
}
try {
const sql = `INSERT INTO todos (title, priority) VALUES (?, ?)`;
this.db.run(sql, [title.trim(), this.currentPriority]);
this.showToast('Mission added successfully!', 'success');
document.getElementById('new-todo').value = '';
await this.loadTodos();
this.updateStats();
this.triggerConfetti();
} catch (error) {
console.error('Failed to add todo:', error);
this.showToast('Failed to add mission', 'error');
}
}
async toggleTodo(id) {
try {
const todo = this.getTodoById(id);
if (!todo) return;
const completed = !todo.completed;
const completed_at = completed ? new Date().toISOString() : null;
const sql = `UPDATE todos SET completed = ?, completed_at = ? WHERE id = ?`;
this.db.run(sql, [completed ? 1 : 0, completed_at, id]);
if (completed) {
this.showToast('Mission completed! 🎉', 'success');
this.triggerConfetti();
}
await this.loadTodos();
this.updateStats();
} catch (error) {
console.error('Failed to toggle todo:', error);
}
}
async editTodo(id) {
const todo = this.getTodoById(id);
if (!todo) return;
const newTitle = prompt('Edit mission:', todo.title);
if (newTitle !== null && newTitle.trim() !== '') {
try {
const sql = `UPDATE todos SET title = ? WHERE id = ?`;
this.db.run(sql, [newTitle.trim(), id]);
this.showToast('Mission updated successfully!', 'success');
await this.loadTodos();
} catch (error) {
console.error('Failed to edit todo:', error);
this.showToast('Failed to update mission', 'error');
}
}
}
async deleteTodo(id) {
if (!confirm('Are you sure you want to delete this mission?')) return;
try {
const sql = `DELETE FROM todos WHERE id = ?`;
this.db.run(sql, [id]);
this.showToast('Mission deleted successfully!', 'success');
await this.loadTodos();
this.updateStats();
} catch (error) {
console.error('Failed to delete todo:', error);
this.showToast('Failed to delete mission', 'error');
}
}
getTodoById(id) {
try {
const stmt = this.db.prepare(`SELECT * FROM todos WHERE id = ?`);
stmt.bind([id]);
const result = stmt.getAsObject();
stmt.free();
return result.id ? result : null;
} catch (error) {
console.error('Failed to get todo:', error);
return null;
}
}
updateStats() {
try {
// Get total and completed counts
const totalResult = this.db.exec(`SELECT COUNT(*) as count FROM todos`);
const completedResult = this.db.exec(`SELECT COUNT(*) as count FROM todos WHERE completed = 1`);
const total = totalResult.values ? totalResult.values[0][0] : 0;
const completed = completedResult.values ? completedResult.values[0][0] : 0;
const progress = total > 0 ? Math.round((completed / total) * 100) : 0;
// Update UI
document.getElementById('total-tasks').textContent = total;
document.getElementById('completed-tasks').textContent = completed;
document.getElementById('productivity').textContent = `${progress}%`;
document.getElementById('total-count').textContent = total;
document.getElementById('completed-count').textContent = completed;
document.getElementById('progress-percent').textContent = `${progress}%`;
document.getElementById('progress-fill').style.width = `${progress}%`;
// Update today's focus (missions created today)
const today = new Date().toISOString().split('T')[0];
const todayResult = this.db.exec(`SELECT COUNT(*) as count FROM todos WHERE date(created_at) = ?`, [today]);
const todayFocus = todayResult.values ? todayResult.values[0][0] : 0;
document.getElementById('today-focus').textContent = `${todayFocus} missions`;
// Update streak (consecutive days with completed missions)
const streakResult = this.db.exec(`
WITH RECURSIVE dates(date) AS (
SELECT date('now')
UNION ALL
SELECT date(date, '-1 day')
FROM dates
LIMIT 30
)
SELECT COUNT(*) as streak
FROM dates d
WHERE EXISTS (
SELECT 1 FROM todos
WHERE date(completed_at) = d.date
)
AND NOT EXISTS (
SELECT 1 FROM dates d2
WHERE d2.date = date(d.date, '-1 day')
AND NOT EXISTS (
SELECT 1 FROM todos
WHERE date(completed_at) = d2.date
)
)
ORDER BY d.date DESC
LIMIT 1
`);
const streak = streakResult.values ? streakResult.values[0][0] : 0;
document.getElementById('streak').textContent = `${streak} days`;
// Update achievements
const achievements = this.calculateAchievements(total, completed, progress);
document.getElementById('achievements').textContent = `${achievements} unlocked`;
} catch (error) {
console.error('Failed to update stats:', error);
}
}
calculateAchievements(total, completed, progress) {
let achievements = 0;
if (total >= 1) achievements++; // First mission
if (total >= 10) achievements++; // Mission master
if (completed >= 5) achievements++; // Task completer
if (completed >= 25) achievements++; // Productivity pro
if (progress >= 100 && total > 0) achievements++; // Perfect day
return achievements;
}
setupEventListeners() {
// Add todo button
document.getElementById('add-todo').addEventListener('click', () => {
const input = document.getElementById('new-todo');
this.addTodo(input.value);
});
// Enter key in input
document.getElementById('new-todo').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.addTodo(e.target.value);
}
});
// Priority buttons
document.querySelectorAll('.priority-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
document.querySelectorAll('.priority-btn').forEach(b => b.classList.remove('active'));
e.currentTarget.classList.add('active');
this.currentPriority = e.currentTarget.dataset.priority;
});
});
// Filter buttons
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
e.currentTarget.classList.add('active');
this.currentFilter = e.currentTarget.dataset.filter;
this.loadTodos();
});
});
// Theme toggle
document.getElementById('theme-toggle').addEventListener('click', () => {
this.toggleTheme();
});
// Voice input (placeholder)
document.getElementById('voice-input').addEventListener('click', () => {
this.showToast('Voice input coming soon!', 'info');
});
// Export data
document.getElementById('export-btn').addEventListener('click', () => {
this.exportData();
});
// Import data
document.getElementById('import-btn').addEventListener('click', () => {
this.importData();
});
// Clear all
document.getElementById('clear-btn').addEventListener('click', () => {
this.clearAll();
});
}
toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('permalist_theme', newTheme);
this.showToast(`Switched to ${newTheme} theme`, 'info');
}
setThemeFromPreference() {
const savedTheme = localStorage.getItem('permalist_theme') || 'light';
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme = savedTheme === 'system' ? (prefersDark ? 'dark' : 'light') : savedTheme;
document.documentElement.setAttribute('data-theme', theme);
}
exportData() {
try {
const result = this.db.exec(`SELECT * FROM todos`);
const data = result.values ? result.values.map(row => ({
id: row[0],
title: row[1],
completed: Boolean(row[2]),
priority: row[3],
created_at: row[4],
completed_at: row[5]
})) : [];
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `permalist-backup-${new Date().toISOString().split('T')[0]}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
this.showToast('Data exported successfully!', 'success');
} catch (error) {
console.error('Failed to export data:', error);
this.showToast('Failed to export data', 'error');
}
}
importData() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) return;
try {
const text = await file.text();
const data = JSON.parse(text);
// Clear existing data
this.db.run(`DELETE FROM todos`);
// Import new data
data.forEach(todo => {
this.db.run(
`INSERT INTO todos (id, title, completed, priority, created_at, completed_at) VALUES (?, ?, ?, ?, ?, ?)`,
[todo.id, todo.title, todo.completed ? 1 : 0, todo.priority, todo.created_at, todo.completed_at]
);
});
this.showToast('Data imported successfully!', 'success');
await this.loadTodos();
this.updateStats();
} catch (error) {
console.error('Failed to import data:', error);
this.showToast('Failed to import data. Invalid file format.', 'error');
}
};
input.click();
}
async clearAll() {
if (!confirm('Are you sure you want to clear ALL missions? This cannot be undone.')) return;
try {
this.db.run(`DELETE FROM todos`);
this.showToast('All missions cleared!', 'success');
await this.loadTodos();
this.updateStats();
} catch (error) {
console.error('Failed to clear data:', error);
this.showToast('Failed to clear data', 'error');
}
}
showToast(message, type = 'info') {
const toast = document.getElementById('toast');
const toastMessage = toast.querySelector('.toast-message');
// Set message and type
toastMessage.textContent = message;
toast.className = 'toast';
toast.classList.add(type);
// Show toast
toast.classList.add('show');
// Hide after 3 seconds
setTimeout(() => {
toast.classList.remove('show');
}, 3000);
}
triggerConfetti() {
// Simple confetti effect using emojis in toast
this.showToast('🎉 Mission completed! 🎉', 'success');
}
// Helper methods
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
formatPriority(priority) {
const priorities = {
'low': 'Low',
'medium': 'Medium',
'high': 'High',
'critical': 'Critical'
};
return priorities[priority] || priority;
}
formatDate(dateString) {
if (!dateString) return 'Just now';
const date = new Date(dateString);
const now = new Date();
const diffMs = now - date;
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'Just now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays < 7) return `${diffDays}d ago`;
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: diffDays > 365 ? 'numeric' : undefined
});
}
}
// Initialize the app when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
window.app = new PermalistUltra();
});