Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2227 lines (1886 loc) · 75.6 KB
/
Copy pathapp.js
File metadata and controls
2227 lines (1886 loc) · 75.6 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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ========================================
// Daily Use Dashboard - Main JavaScript
// ========================================
// ========================================
// IndexedDB Wrapper Module
// ========================================
const DBManager = {
dbName: 'DashboardDB',
version: 1,
db: null,
/**
* Initialize IndexedDB
*/
async init() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbName, this.version);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
this.db = request.result;
resolve(this.db);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create object stores if they don't exist
if (!db.objectStoreNames.contains('items')) {
db.createObjectStore('items', { keyPath: 'id' });
}
if (!db.objectStoreNames.contains('settings')) {
db.createObjectStore('settings', { keyPath: 'key' });
}
if (!db.objectStoreNames.contains('files')) {
const fileStore = db.createObjectStore('files', { keyPath: 'id', autoIncrement: true });
fileStore.createIndex('timestamp', 'timestamp', { unique: false });
}
if (!db.objectStoreNames.contains('timer')) {
db.createObjectStore('timer', { keyPath: 'id' });
}
};
});
},
/**
* Get all items from a store
*/
async getAll(storeName) {
if (!this.db) await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([storeName], 'readonly');
const store = transaction.objectStore(storeName);
const request = store.getAll();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
},
/**
* Get a single item by key
*/
async get(storeName, key) {
if (!this.db) await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([storeName], 'readonly');
const store = transaction.objectStore(storeName);
const request = store.get(key);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
},
/**
* Add or update an item
*/
async put(storeName, item) {
if (!this.db) await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([storeName], 'readwrite');
const store = transaction.objectStore(storeName);
const request = store.put(item);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
},
/**
* Delete an item
*/
async delete(storeName, key) {
if (!this.db) await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([storeName], 'readwrite');
const store = transaction.objectStore(storeName);
const request = store.delete(key);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
},
/**
* Clear all data from a store
*/
async clear(storeName) {
if (!this.db) await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([storeName], 'readwrite');
const store = transaction.objectStore(storeName);
const request = store.clear();
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
}
};
// ========================================
// WebRTC File Sharing Module
// ========================================
/**
* File Share Manager using PeerJS with Room Code
*/
const FileShareManager = {
peer: null,
connection: null,
roomCode: null,
receivedChunks: [],
fileMetadata: null,
onProgressCallback: null,
onFileReceivedCallback: null,
onConnectionStateCallback: null,
myRole: null, // 'host' or 'client'
connectionAttempts: 0,
maxAttempts: 10,
/**
* Initialize PeerJS and connect to room
*/
async connect(roomCode) {
this.roomCode = roomCode;
this.connectionAttempts = 0;
// Try to be the host first
const hostPeerId = `room-${roomCode}-host`;
return new Promise((resolve, reject) => {
this.peer = new Peer(hostPeerId, {
config: {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' }
]
}
});
this.peer.on('open', (id) => {
console.log('Peer initialized as HOST:', id);
this.myRole = 'host';
this.updateConnectionState('waiting-for-peer');
resolve();
});
this.peer.on('error', (error) => {
console.error('Peer error:', error);
// If host ID is taken, join as client
if (error.type === 'unavailable-id') {
console.log('Host exists, joining as client...');
this.joinAsClient(roomCode).then(resolve).catch(reject);
} else {
this.updateConnectionState('error');
reject(error);
}
});
this.peer.on('connection', (conn) => {
console.log('Incoming connection from:', conn.peer);
this.setupConnection(conn);
});
});
},
/**
* Join room as client (when host already exists)
*/
async joinAsClient(roomCode) {
return new Promise((resolve, reject) => {
// Close existing peer if any
if (this.peer) {
this.peer.destroy();
}
const clientPeerId = `room-${roomCode}-client-${Date.now()}`;
this.peer = new Peer(clientPeerId, {
config: {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' }
]
}
});
this.peer.on('open', (id) => {
console.log('Peer initialized as CLIENT:', id);
this.myRole = 'client';
this.updateConnectionState('looking-for-peer');
// Wait a moment before connecting to ensure host is ready
setTimeout(() => {
this.connectToHost(roomCode);
}, 500);
resolve();
});
this.peer.on('error', (error) => {
console.error('Client peer error:', error);
this.updateConnectionState('error');
reject(error);
});
this.peer.on('connection', (conn) => {
console.log('Incoming connection from:', conn.peer);
this.setupConnection(conn);
});
});
},
/**
* Connect to host peer
*/
connectToHost(roomCode) {
const hostPeerId = `room-${roomCode}-host`;
const attemptConnection = () => {
if (this.connectionAttempts >= this.maxAttempts) {
console.error('Max connection attempts reached');
this.updateConnectionState('error');
return;
}
this.connectionAttempts++;
console.log(`Attempting to connect to host... (${this.connectionAttempts}/${this.maxAttempts})`);
try {
const conn = this.peer.connect(hostPeerId, {
reliable: true
});
conn.on('open', () => {
console.log('Successfully connected to host!');
this.setupConnection(conn);
});
conn.on('error', (error) => {
console.error('Connection error:', error);
// Retry after delay
setTimeout(attemptConnection, 2000);
});
} catch (error) {
console.error('Failed to initiate connection:', error);
setTimeout(attemptConnection, 2000);
}
};
// Start connection attempts
attemptConnection();
},
/**
* Setup connection event handlers
*/
setupConnection(conn) {
if (this.connection && this.connection.open) {
console.log('Already have an active connection');
return;
}
this.connection = conn;
conn.on('open', () => {
console.log('Connection established with:', conn.peer);
this.updateConnectionState('connected');
});
conn.on('data', (data) => {
if (data.type === 'metadata') {
console.log('Receiving file:', data.name);
this.fileMetadata = data;
this.receivedChunks = [];
if (this.onProgressCallback) {
this.onProgressCallback(0, data.size);
}
} else if (data.type === 'chunk') {
this.receivedChunks.push(data.chunk);
const receivedSize = this.receivedChunks.reduce((acc, chunk) => acc + chunk.byteLength, 0);
if (this.onProgressCallback && this.fileMetadata) {
this.onProgressCallback(receivedSize, this.fileMetadata.size);
}
if (this.fileMetadata && receivedSize >= this.fileMetadata.size) {
this.saveReceivedFile();
}
} else if (data.type === 'transfer-complete') {
console.log('Transfer acknowledged by receiver');
// Reset progress on sender side
if (this.onProgressCallback) {
this.onProgressCallback(0, 1);
}
}
});
conn.on('close', () => {
console.log('Connection closed');
this.connection = null;
this.updateConnectionState('disconnected');
});
conn.on('error', (error) => {
console.error('Connection error:', error);
this.connection = null;
this.updateConnectionState('error');
});
},
/**
* Send file through connection
*/
async sendFile(file) {
if (!this.connection || !this.connection.open) {
throw new Error('No active connection. Make sure both devices are connected.');
}
console.log('Sending file:', file.name);
// Send metadata
const metadata = {
type: 'metadata',
name: file.name,
fileType: file.type,
size: file.size
};
this.connection.send(metadata);
// Wait a bit for metadata to be processed
await new Promise(resolve => setTimeout(resolve, 100));
// Send file in chunks
const chunkSize = 16384; // 16KB
let offset = 0;
while (offset < file.size) {
const chunk = file.slice(offset, offset + chunkSize);
const arrayBuffer = await chunk.arrayBuffer();
this.connection.send({
type: 'chunk',
chunk: arrayBuffer
});
offset += chunkSize;
if (this.onProgressCallback) {
this.onProgressCallback(Math.min(offset, file.size), file.size);
}
// Small delay to prevent overwhelming the connection
await new Promise(resolve => setTimeout(resolve, 10));
}
console.log('File sent successfully');
},
/**
* Save received file
*/
async saveReceivedFile() {
const blob = new Blob(this.receivedChunks, { type: this.fileMetadata.fileType });
const fileData = {
name: this.fileMetadata.name,
type: this.fileMetadata.fileType,
size: this.fileMetadata.size,
blob: blob,
timestamp: Date.now()
};
await DBManager.put('files', fileData);
// Send acknowledgment to sender
if (this.connection && this.connection.open) {
this.connection.send({ type: 'transfer-complete' });
}
if (this.onFileReceivedCallback) {
this.onFileReceivedCallback(fileData);
}
// Clear state for next transfer
this.receivedChunks = [];
this.fileMetadata = null;
},
/**
* Close connection
*/
close() {
if (this.connection) {
this.connection.close();
this.connection = null;
}
if (this.peer) {
this.peer.destroy();
this.peer = null;
}
this.roomCode = null;
this.updateConnectionState('disconnected');
},
/**
* Update connection state
*/
updateConnectionState(state) {
if (this.onConnectionStateCallback) {
this.onConnectionStateCallback(state);
}
}
};
/**
* Application State Management
*/
const DashboardApp = {
// Storage keys
STORAGE_KEYS: {
ITEMS: 'dashboardItems',
TIMER: 'dashboardTimer',
DARK_MODE: 'dashboardDarkMode'
},
// Category mappings
CATEGORIES: {
todo: { id: 'todo', label: 'To Do', icon: '📝' },
running: { id: 'running', label: 'Running Tasks', icon: '🏃' },
ideas: { id: 'ideas', label: 'Ideas', icon: '💡' },
completed: { id: 'completed', label: 'Completed Tasks', icon: '✅' },
reminder: { id: 'reminder', label: 'Reminder', icon: '🔔' },
exam: { id: 'exam', label: 'Exam Schedule', icon: '📚' },
problems: { id: 'problems', label: 'Problem List', icon: '🧩' },
learn: { id: 'learn', label: 'New Things to Learn', icon: '🎓' }
},
// Timer state
timer: {
interval: null,
seconds: 0,
running: false
},
// Modal state
modal: {
currentCategory: null
},
/**
* Initialize the application
*/
async init() {
// Initialize IndexedDB first
await DBManager.init();
// Migrate data from localStorage if needed
await this.migrateFromLocalStorage();
await this.loadDarkMode();
this.setupEventListeners();
// Only initialize dashboard features on index.html
if (document.querySelector('.dashboard')) {
await this.loadItems();
await this.loadTimer();
this.startTimerIfRunning();
await this.loadSharedFiles();
this.setupFileSharing();
}
},
/**
* Migrate data from localStorage to IndexedDB
*/
async migrateFromLocalStorage() {
try {
// Check if migration is needed
const migrated = await DBManager.get('settings', 'migrated');
if (migrated && migrated.value) return;
// Migrate items
const itemsStr = localStorage.getItem(this.STORAGE_KEYS.ITEMS);
if (itemsStr) {
const items = JSON.parse(itemsStr);
for (const item of items) {
await DBManager.put('items', item);
}
}
// Migrate timer
const timerStr = localStorage.getItem(this.STORAGE_KEYS.TIMER);
if (timerStr) {
const timerData = JSON.parse(timerStr);
await DBManager.put('timer', { id: 'current', ...timerData });
}
// Migrate dark mode
const darkMode = localStorage.getItem(this.STORAGE_KEYS.DARK_MODE);
if (darkMode !== null) {
await DBManager.put('settings', { key: 'darkMode', value: darkMode === 'true' });
}
// Mark as migrated
await DBManager.put('settings', { key: 'migrated', value: true });
console.log('Data migrated from localStorage to IndexedDB');
} catch (error) {
console.error('Error migrating data:', error);
}
},
/**
* Setup event listeners
*/
setupEventListeners() {
// Dark mode toggle
const darkModeToggle = document.getElementById('darkModeToggle');
if (darkModeToggle) {
darkModeToggle.addEventListener('click', () => this.toggleDarkMode());
}
// Timer controls (only on dashboard)
const timerStart = document.getElementById('timerStart');
const timerPause = document.getElementById('timerPause');
const timerReset = document.getElementById('timerReset');
if (timerStart) {
timerStart.addEventListener('click', () => this.startTimer());
}
if (timerPause) {
timerPause.addEventListener('click', () => this.pauseTimer());
}
if (timerReset) {
timerReset.addEventListener('click', () => this.resetTimer());
}
// Modal controls
const modalClose = document.getElementById('modalClose');
const modalOverlay = document.getElementById('modalOverlay');
const modalAddItem = document.getElementById('modalAddItem');
const cancelQuickAdd = document.getElementById('cancelQuickAdd');
const quickAddForm = document.getElementById('quickAddForm');
if (modalClose) {
modalClose.addEventListener('click', () => this.closeModal());
}
if (modalOverlay) {
modalOverlay.addEventListener('click', (e) => {
if (e.target === modalOverlay) {
this.closeModal();
}
});
}
if (modalAddItem) {
modalAddItem.addEventListener('click', () => this.showQuickAddForm());
}
if (cancelQuickAdd) {
cancelQuickAdd.addEventListener('click', () => this.hideQuickAddForm());
}
if (quickAddForm) {
quickAddForm.addEventListener('submit', (e) => this.handleQuickAdd(e));
}
// Make cards clickable (except timer and file share cards)
document.querySelectorAll('.card:not(.card-timer):not(.card-fileshare):not(.card-fileview)').forEach(card => {
const category = card.getAttribute('data-category');
if (category) {
card.addEventListener('click', async (e) => {
// Don't open modal if clicking on item action buttons or buttons
if (!e.target.closest('.item-action') && !e.target.closest('button')) {
await this.openModal(category);
}
});
}
});
// Make File View card clickable
const fileViewCard = document.querySelector('.card-fileview');
if (fileViewCard) {
fileViewCard.addEventListener('click', async (e) => {
// Don't open modal if clicking on item action buttons or buttons
if (!e.target.closest('.item-action') && !e.target.closest('button')) {
await this.openFilesModal();
}
});
}
// Data export/import/clear
const exportBtn = document.getElementById('exportData');
const importBtn = document.getElementById('importData');
const clearBtn = document.getElementById('clearData');
const importFileInput = document.getElementById('importFileInput');
if (exportBtn) {
exportBtn.addEventListener('click', () => this.exportData());
}
if (importBtn) {
importBtn.addEventListener('click', () => {
if (importFileInput) {
importFileInput.click();
}
});
}
if (clearBtn) {
clearBtn.addEventListener('click', () => this.clearAllData());
}
if (importFileInput) {
importFileInput.addEventListener('change', (e) => this.importData(e));
}
},
// ========================================
// Dark Mode Management
// ========================================
/**
* Load dark mode preference from IndexedDB
*/
async loadDarkMode() {
const setting = await DBManager.get('settings', 'darkMode');
const isDarkMode = setting && setting.value === true;
if (isDarkMode) {
document.body.classList.add('dark-mode');
this.updateDarkModeIcon(true);
}
},
/**
* Toggle dark mode
*/
async toggleDarkMode() {
const isDarkMode = document.body.classList.toggle('dark-mode');
await DBManager.put('settings', { key: 'darkMode', value: isDarkMode });
this.updateDarkModeIcon(isDarkMode);
},
/**
* Update dark mode toggle icon
*/
updateDarkModeIcon(isDarkMode) {
const toggle = document.getElementById('darkModeToggle');
if (toggle) {
toggle.textContent = isDarkMode ? '☀️' : '🌙';
toggle.title = isDarkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode';
}
},
// ========================================
// Data Management
// ========================================
/**
* Get all items from IndexedDB
*/
async getItems() {
const items = await DBManager.getAll('items');
return items || [];
},
/**
* Save items to IndexedDB
*/
async saveItems(items) {
// Clear existing items and save new ones
await DBManager.clear('items');
for (const item of items) {
await DBManager.put('items', item);
}
},
/**
* Delete an item by ID
*/
async deleteItem(itemId) {
const items = await this.getItems();
const item = items.find(i => i.id === itemId);
if (item) {
await DBManager.delete('items', itemId);
await this.loadItems();
// Reload modal if open
if (this.modal.currentCategory) {
await this.loadModalItems(this.modal.currentCategory);
}
}
},
/**
* Toggle item completion status
*/
async toggleComplete(itemId) {
const items = await this.getItems();
const item = items.find(item => item.id === itemId);
if (item) {
item.completed = !item.completed;
// Move to completed category if not already there
if (item.completed && item.category !== 'completed') {
item.category = 'completed';
}
await DBManager.put('items', item);
await this.loadItems();
// Reload modal if open
if (this.modal.currentCategory) {
await this.loadModalItems(this.modal.currentCategory);
}
}
},
// ========================================
// Item Rendering
// ========================================
/**
* Load and render all items
*/
async loadItems() {
const items = await this.getItems();
// Clear all lists
Object.keys(this.CATEGORIES).forEach(category => {
const listElement = document.getElementById(`${category}-list`);
if (listElement) {
listElement.innerHTML = '';
}
});
// Group items by category
const itemsByCategory = {};
Object.keys(this.CATEGORIES).forEach(cat => {
itemsByCategory[cat] = [];
});
items.forEach(item => {
if (itemsByCategory[item.category]) {
itemsByCategory[item.category].push(item);
}
});
// Render items for each category
Object.keys(this.CATEGORIES).forEach(category => {
this.renderCategory(category, itemsByCategory[category]);
});
},
/**
* Render items for a specific category
*/
renderCategory(category, items) {
const listElement = document.getElementById(`${category}-list`);
const countElement = document.getElementById(`${category}-count`);
if (!listElement) return;
// Update count
if (countElement) {
countElement.textContent = items.length;
}
// Show empty state if no items
if (items.length === 0) {
listElement.innerHTML = '<p class="empty-state">No items yet</p>';
return;
}
// Sort items by priority (for todo/reminder), then by date and creation time
items.sort((a, b) => {
// Sort by priority first for todo and reminder categories
if (category === 'todo' || category === 'reminder') {
const priorityA = parseInt(a.priority) || 999;
const priorityB = parseInt(b.priority) || 999;
if (priorityA !== priorityB) {
return priorityA - priorityB;
}
}
// Then sort by date
if (a.date && b.date) {
return new Date(a.date) - new Date(b.date);
}
// Finally by creation time
return new Date(b.createdAt) - new Date(a.createdAt);
});
// Render each item
items.forEach(item => {
const itemElement = this.createItemElement(item, category);
listElement.appendChild(itemElement);
});
},
/**
* Create an item DOM element
*/
createItemElement(item, category) {
const itemDiv = document.createElement('div');
itemDiv.className = `item${item.completed ? ' completed' : ''}`;
// Item header with title and actions
const headerDiv = document.createElement('div');
headerDiv.className = 'item-header';
const titleDiv = document.createElement('div');
titleDiv.className = 'item-title';
// Add priority indicator for todo and reminder
if ((category === 'todo' || category === 'reminder') && item.priority) {
const priorityDot = document.createElement('span');
priorityDot.className = `priority-indicator p${item.priority}`;
titleDiv.appendChild(priorityDot);
}
const titleText = document.createElement('span');
titleText.textContent = item.title;
titleDiv.appendChild(titleText);
const actionsDiv = document.createElement('div');
actionsDiv.className = 'item-actions';
// Edit button
const editBtn = document.createElement('button');
editBtn.className = 'item-action';
editBtn.innerHTML = '✏️';
editBtn.title = 'Edit';
editBtn.addEventListener('click', () => this.editItem(item.id, itemDiv));
actionsDiv.appendChild(editBtn);
// Complete/Uncomplete button (only for applicable categories)
if (['todo', 'running', 'completed'].includes(category)) {
const completeBtn = document.createElement('button');
completeBtn.className = 'item-action';
completeBtn.innerHTML = item.completed ? '↩️' : '✅';
completeBtn.title = item.completed ? 'Mark as incomplete' : 'Mark as complete';
completeBtn.addEventListener('click', () => this.toggleComplete(item.id));
actionsDiv.appendChild(completeBtn);
}
// Delete button
const deleteBtn = document.createElement('button');
deleteBtn.className = 'item-action';
deleteBtn.innerHTML = '🗑️';
deleteBtn.title = 'Delete';
deleteBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to delete this item?')) {
this.deleteItem(item.id);
}
});
actionsDiv.appendChild(deleteBtn);
headerDiv.appendChild(titleDiv);
headerDiv.appendChild(actionsDiv);
itemDiv.appendChild(headerDiv);
// Description
if (item.description) {
const descDiv = document.createElement('div');
descDiv.className = 'item-description';
descDiv.textContent = item.description;
itemDiv.appendChild(descDiv);
}
// Date
if (item.date) {
const dateDiv = document.createElement('div');
dateDiv.className = 'item-date';
const dateInfo = this.formatDateWithStatus(item.date);
let dateTimeText = `📅 <span class="date-badge ${dateInfo.className}">${dateInfo.text}</span>`;
// Add time if available
if (item.time) {
dateTimeText += ` <span class="time-badge">🕐 ${this.formatTime(item.time)}</span>`;
}
dateDiv.innerHTML = dateTimeText;
itemDiv.appendChild(dateDiv);
}
return itemDiv;
},
/**
* Format date with status badge
*/
formatDateWithStatus(dateString) {
const itemDate = new Date(dateString);
const today = new Date();
today.setHours(0, 0, 0, 0);
itemDate.setHours(0, 0, 0, 0);
const diffTime = itemDate - today;
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
const options = { month: 'short', day: 'numeric', year: 'numeric' };
const formattedDate = itemDate.toLocaleDateString('en-US', options);
if (diffDays < 0) {
return {
text: `${formattedDate} (Overdue)`,
className: 'date-overdue'
};
} else if (diffDays === 0) {
return {
text: `${formattedDate} (Today)`,
className: 'date-today'
};
} else if (diffDays <= 7) {
return {
text: `${formattedDate} (${diffDays} days)`,
className: 'date-upcoming'
};
} else {
return {
text: formattedDate,
className: ''
};
}
},
/**
* Format time in 12-hour format
*/
formatTime(timeString) {
if (!timeString) return '';
const [hours, minutes] = timeString.split(':');
const hour = parseInt(hours);
const ampm = hour >= 12 ? 'PM' : 'AM';
const displayHour = hour % 12 || 12;
return `${displayHour}:${minutes} ${ampm}`;
},
// ========================================
// Timer Management
// ========================================
/**
* Load timer state from IndexedDB
*/
async loadTimer() {
const timerData = await DBManager.get('timer', 'current');
if (timerData) {
this.timer.seconds = timerData.seconds || 0;
this.timer.running = timerData.running || false;
this.updateTimerDisplay();
}
},
/**
* Save timer state to IndexedDB
*/
async saveTimer() {
await DBManager.put('timer', {
id: 'current',
seconds: this.timer.seconds,
running: this.timer.running
});
},
/**
* Start timer if it was running
*/
startTimerIfRunning() {
if (this.timer.running) {
this.startTimer();
}
},
/**
* Start the timer
*/
startTimer() {