-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1120 lines (970 loc) · 34.5 KB
/
app.js
File metadata and controls
1120 lines (970 loc) · 34.5 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
// Main Application Logic for TLNotes
// This file contains the core application state and functionality
// Global state
let notes = [];
let trashNotes = [];
let currentEditId = null;
let editTags = [];
let activeTagFilters = [];
let activeTypeFilters = [
"note",
"draft",
"event",
"period",
];
let currentSearch = "";
let confirmCallback = null;
let lastAddedNoteId = null;
let savedScrollPosition = null; // Preserve user scroll position during edits
let currentView = "timeline";
let isRightHanded = true; // Default to right-handed layout
let scopeColumnCollapsed = false; // Track scope column state for persistence
// DOM Elements
const timelineList = document.getElementById("timelineList");
const timelineContainer = document.getElementById("timelineContainer");
const scopeColumn = document.getElementById("scopeColumn");
const noEvents = document.getElementById("noEvents");
const noteInput = document.getElementById("noteInput");
const addButton = document.getElementById("addButton");
const content = document.getElementById("content");
const editorModal = document.getElementById("editorModal");
const searchBar = document.getElementById("search-bar");
const liveSearchInput = document.getElementById("liveSearchInput");
const tagFiltersContainer = document.getElementById("tag-filters");
const clearFiltersBtn = document.getElementById("clearFiltersBtn");
const confirmDialog = document.getElementById("confirmDialog");
const tagsFilterModal = document.getElementById("tagsFilterModal");
// Initialize application
async function initApp() {
try {
console.log("Initializing TLNotes application...");
// Initialize database
await database.init();
// Load data from database
await loadData();
// Check for localStorage migration
const migrationData = migrateFromLocalStorage();
if (migrationData && migrationData.notes.length > 0) {
const shouldMigrate = confirm(
`Found ${migrationData.notes.length} notes from previous version. Import them?`,
);
if (shouldMigrate) {
await database.importData(migrationData);
clearLocalStorageData();
await loadData();
showSuccess("Data migrated successfully!");
}
}
// Load user preferences
await loadUserPreferences();
// Setup event listeners
setupEventListeners();
// Start periodic scroll position saving
startScrollPositionSaving();
// Initial render
showView("timelineView");
renderTimeline();
console.log("Application initialized successfully");
} catch (error) {
console.error("Failed to initialize application:", error);
handleError(error, "initializing application");
}
}
// Load data from database
async function loadData() {
try {
notes = await database.getAllNotes();
trashNotes = await database.getAllTrash();
console.log(
`Loaded ${notes.length} notes and ${trashNotes.length} trash items`,
);
// 🚨 CRITICAL FIX: Update state management IMMEDIATELY after loading
console.log("🚨 Updating state management with loaded data...");
setNotes(notes);
setTrashNotes(trashNotes);
console.log("🚨 State management updated - getNotes() should work now");
console.log("🚨 getNotes() after sync:", getNotes());
} catch (error) {
handleError(error, "loading data");
notes = [];
trashNotes = [];
// Also clear state management on error
setNotes([]);
setTrashNotes([]);
}
}
// Load user preferences
async function loadUserPreferences() {
try {
// Load handedness preference
const handedness = await database.getSetting("handedness");
if (handedness !== undefined) {
isRightHanded = handedness;
applyHandednessLayout();
}
// Load scope column state
const scopeState = await database.getSetting("scopeColumnCollapsed");
if (scopeState !== undefined) {
scopeColumnCollapsed = scopeState;
applyScopeColumnState();
}
// Load saved scroll position and apply it if we're on timeline view
const savedScroll = await database.getSetting("savedScrollPosition");
if (savedScroll !== undefined && currentView === "timeline") {
savedScrollPosition = parseInt(savedScroll) || null;
if (savedScrollPosition !== null && timelineContainer) {
// Use setTimeout to ensure DOM is ready
setTimeout(() => {
timelineContainer.scrollTop = savedScrollPosition;
console.log("📍 Restored persistent scroll position:", savedScrollPosition);
}, 100);
}
}
console.log("📊 Loaded user preferences:", {
isRightHanded,
scopeColumnCollapsed,
savedScrollPosition
});
} catch (error) {
console.log("Using default preferences");
}
}
// Apply handedness layout
function applyHandednessLayout() {
const timelineContainer = document.getElementById("timelineContainer");
const floatingNav = document.getElementById("floating-nav");
if (isRightHanded) {
// Right-handed layout (default)
timelineContainer.classList.remove("left-handed");
floatingNav.style.right = "12px";
floatingNav.style.left = "auto";
} else {
// Left-handed layout
timelineContainer.classList.add("left-handed");
floatingNav.style.left = "12px";
floatingNav.style.right = "auto";
}
}
// Toggle handedness setting
async function toggleHandedness() {
isRightHanded = !isRightHanded;
try {
await database.setSetting("handedness", isRightHanded);
applyHandednessLayout();
showSuccess(
`Switched to ${isRightHanded ? "right" : "left"}-handed layout`,
);
} catch (error) {
handleError(error, "saving handedness preference");
}
}
// Apply scope column state
function applyScopeColumnState() {
if (scopeColumnCollapsed && scopeColumn) {
scopeColumn.style.display = 'none';
scopeColumn.style.width = '0';
console.log("🏗️ Scope column collapsed");
} else if (scopeColumn) {
scopeColumn.style.display = '';
scopeColumn.style.width = '60px';
console.log("🏗️ Scope column expanded");
}
}
// Toggle scope column visibility
async function toggleScopeColumn() {
scopeColumnCollapsed = !scopeColumnCollapsed;
try {
await database.setSetting("scopeColumnCollapsed", scopeColumnCollapsed);
applyScopeColumnState();
showSuccess(
scopeColumnCollapsed ? "Scope column hidden" : "Scope column shown"
);
} catch (error) {
handleError(error, "saving scope column preference");
}
}
// Save current scroll position for persistence
async function saveScrollPosition() {
if (timelineContainer) {
const currentScroll = timelineContainer.scrollTop;
try {
await database.setSetting("savedScrollPosition", currentScroll);
console.log("💾 Saved scroll position to persistent storage:", currentScroll);
} catch (error) {
console.error("Failed to save scroll position:", error);
}
}
}
// Periodic saving of scroll position
let scrollSaveInterval;
function startScrollPositionSaving() {
// Save scroll position every 5 seconds when scrolling
scrollSaveInterval = setInterval(saveScrollPosition, 5000);
}
function stopScrollPositionSaving() {
if (scrollSaveInterval) {
clearInterval(scrollSaveInterval);
}
}
// Note operations
async function addNote() {
const value = noteInput.value.trim();
if (!value) {
return;
}
try {
const now = Date.now();
const noteId = generateId();
const newNote = {
id: noteId,
type: "draft",
content: value,
tags: [],
created: now,
edited: now,
date: null,
};
// Validate note
validateNote(newNote);
// Save to database
await database.saveNote(newNote);
// Add to local state and sync with state management immediately
notes.push(newNote);
// 🚨 CRITICAL FIX: Sync with state management BEFORE setting lastAddedNoteId
console.log("🚨 Syncing new note with state management...");
setNotes(notes); // Use correct state management function
console.log("🚨 State management synced - new note available for gestures");
// Set for scroll-to animation (after state is synced so gestures work)
lastAddedNoteId = noteId;
// Clear input
noteInput.value = "";
addButton.disabled = true;
noteInput.style.height = "auto";
// Re-render
renderTimeline();
showSuccess("Note added successfully!");
} catch (error) {
handleError(error, "adding note");
}
}
async function trashNote(id) {
try {
const noteIndex = notes.findIndex((n) => n.id === id);
if (noteIndex === -1) return;
const note = notes[noteIndex];
// Move to trash in database
await database.moveToTrash(note);
// Update local state
note.trashedAt = Date.now();
trashNotes.push(note);
notes.splice(noteIndex, 1);
// 🚨 CRITICAL FIX: Sync with state management after trash operation
console.log("🚨 Syncing trash operation with state management...");
setNotes(notes);
setTrashNotes(trashNotes);
console.log("🚨 Trash operation synced - state management updated");
// Re-render current view
if (currentView === "timeline") {
renderTimeline();
}
closeModal();
showSuccess("Note moved to trash");
} catch (error) {
handleError(error, "moving note to trash");
}
}
async function restoreNote(id) {
try {
// Restore from trash in database
await database.restoreFromTrash(id);
// Update local state
const trashIndex = trashNotes.findIndex((n) => n.id === id);
if (trashIndex !== -1) {
const note = trashNotes[trashIndex];
delete note.trashedAt;
notes.push(note);
trashNotes.splice(trashIndex, 1);
}
// 🚨 CRITICAL FIX: Sync with state management after restore operation
console.log("🚨 Syncing restore operation with state management...");
setNotes(notes);
setTrashNotes(trashNotes);
console.log("🚨 Restore operation synced - state management updated");
renderTrash();
showSuccess("Note restored successfully!");
} catch (error) {
handleError(error, "restoring note");
}
}
async function permanentlyDeleteNote(id) {
showConfirmDialog(
"Delete Permanently",
"This note will be permanently deleted and cannot be recovered. Continue?",
async (confirmed) => {
if (confirmed) {
try {
await database.deleteFromTrash(id);
const trashIndex = trashNotes.findIndex((n) => n.id === id);
if (trashIndex !== -1) {
trashNotes.splice(trashIndex, 1);
}
// 🚨 CRITICAL FIX: Sync with state management after delete operation
console.log("🚨 Syncing delete operation with state management...");
setNotes(notes); // Notes array didn't change
setTrashNotes(trashNotes); // TrashNotes changed
console.log("🚨 Delete operation synced - state management updated");
renderTrash();
showSuccess("Note permanently deleted");
} catch (error) {
handleError(error, "permanently deleting note");
}
}
},
);
}
// Modal operations
function openModal(id) {
console.log("🎯 openModal called with id:", id);
try {
console.log("🔍 Debugging note lookup...");
console.log("🔍 Looking for note with id:", id);
console.log("🔍 Global notes array length:", notes.length);
console.log("🔍 Global notes array:", notes);
console.log("🔍 getNotes() returns:", getNotes());
console.log("🔍 getTrashNotes() returns:", getTrashNotes());
const note = getNotes().find((n) => n.id === id) || getTrashNotes().find((n) => n.id === id);
console.log("📝 Note found using getNotes():", getNotes().find((n) => n.id === id));
console.log("📝 Note found using getTrashNotes():", getTrashNotes().find((n) => n.id === id));
console.log("📝 Final note found:", note);
if (!note) {
console.error("❌ Note not found for id:", id);
// Try looking in the global arrays directly
console.log("🔍 Trying global arrays directly...");
const directNote = notes.find((n) => n.id === id) || trashNotes.find((n) => n.id === id);
console.log("🔍 Direct global match:", directNote);
if (!directNote) {
console.error("❌ Note doesn't exist in global arrays either!");
}
return;
}
console.log("🎯 Setting current edit id:", id);
setCurrentEditId(id);
// Debug modal elements
console.log("🎯 Getting modal elements...");
const modalElement = document.getElementById("editorModal");
const editContent = document.getElementById("editContent");
const editType = document.getElementById("editType");
console.log("🎯 Modal element:", modalElement);
console.log("🎯 Edit content field:", editContent);
console.log("🎯 Edit type field:", editType);
if (!modalElement || !editContent || !editType) {
console.error("❌ Modal elements not found!");
return;
}
console.log("🎯 Populating form...");
editContent.value = note.content;
setEditTags(note.tags || []);
renderEditTags();
editType.value = note.type;
toggleEditorSections(note.type);
console.log("🎯 Populating date fields...");
// Handle date fields based on type
if (note.type === "event") {
document.getElementById("editYear").value = note.date?.year || "";
document.getElementById("editMonth").value = note.date?.month || "";
document.getElementById("editDay").value = note.date?.day || "";
} else if (note.type === "period") {
document.getElementById("editBeginYear").value = note.date?.begin?.year || "";
document.getElementById("editBeginMonth").value = note.date?.begin?.month || "";
document.getElementById("editBeginDay").value = note.date?.begin?.day || "";
document.getElementById("editEndYear").value = note.date?.end?.year || "";
document.getElementById("editEndMonth").value = note.date?.end?.month || "";
document.getElementById("editEndDay").value = note.date?.end?.day || "";
document.getElementById("periodColor").value = note.color || "#4CAF50";
}
// Store scroll position for restoration after edit
if (timelineContainer) {
savedScrollPosition = timelineContainer.scrollTop;
console.log("📍 Saved scroll position:", savedScrollPosition);
}
console.log("🎯 Showing modal...");
editorModal.showModal();
console.log("✅ Modal should now be visible!");
} catch (error) {
console.error("❌ Error in openModal:", error);
console.error("❌ Error stack:", error.stack);
}
}
function toggleEditorSections(type) {
document.getElementById("dateSection").style.display =
type === "event" ? "block" : "none";
document.getElementById("periodSection").style.display =
type === "period" ? "block" : "none";
}
function renderEditTags() {
const ul = document.getElementById("editTags");
ul.innerHTML = "";
getEditTags().forEach((tag) => {
const li = document.createElement("li");
li.textContent = tag;
const removeBtn = document.createElement("button");
removeBtn.textContent = "×";
removeBtn.onclick = () => removeEditTag(tag);
li.appendChild(removeBtn);
ul.appendChild(li);
});
}
function addEditTag() {
const input = document.getElementById("newTag");
const value = input.value.trim();
if (value && !getEditTags().includes(value)) {
// Update the global editTags array directly
setEditTags([...getEditTags(), value]);
input.value = "";
renderEditTags();
}
}
function removeEditTag(tag) {
// Update the global editTags array directly
setEditTags(getEditTags().filter(t => t !== tag));
renderEditTags();
}
async function saveEdit() {
try {
const noteIndex = notes.findIndex((n) => n.id === getCurrentEditId());
if (noteIndex === -1) return;
const note = notes[noteIndex];
// Update note properties
note.content = document.getElementById("editContent").value.trim();
note.type = document.getElementById("editType").value;
note.tags = [...getEditTags()];
note.edited = Date.now();
// Handle date based on type
if (note.type === "draft") {
note.date = null;
} else if (note.type === "event") {
const year = parseInt(document.getElementById("editYear").value) || null;
const month =
parseInt(document.getElementById("editMonth").value) || null;
const day = parseInt(document.getElementById("editDay").value) || null;
note.date = year || month || day ? { year, month, day } : null;
} else if (note.type === "period") {
const beginYear =
parseInt(document.getElementById("editBeginYear").value) || null;
const beginMonth =
parseInt(document.getElementById("editBeginMonth").value) || null;
const beginDay =
parseInt(document.getElementById("editBeginDay").value) || null;
const endYear =
parseInt(document.getElementById("editEndYear").value) || null;
const endMonth =
parseInt(document.getElementById("editEndMonth").value) || null;
const endDay =
parseInt(document.getElementById("editEndDay").value) || null;
const begin =
beginYear || beginMonth || beginDay
? { year: beginYear, month: beginMonth, day: beginDay }
: null;
const end =
endYear || endMonth || endDay
? { year: endYear, month: endMonth, day: endDay }
: null;
note.date = { begin, end };
note.color = document.getElementById("periodColor").value;
} else {
// For other types, use single date
const year = parseInt(document.getElementById("editYear").value) || null;
const month =
parseInt(document.getElementById("editMonth").value) || null;
const day = parseInt(document.getElementById("editDay").value) || null;
note.date = year || month || day ? { year, month, day } : null;
}
// Validate and save
validateNote(note);
await database.saveNote(note);
// ✨ BULLETPROOF SCROLL POSITION PRESERVATION - Capture position BEFORE any DOM changes
console.log("🔐 Capturing scroll position for edit operation...");
const currentScrollPosition = timelineContainer ? timelineContainer.scrollTop : 0;
console.log("🔐 Locked scroll position:", currentScrollPosition);
closeModal();
// 🚀 FORCE SCROLL POSITION WITH ABSOLUTE PRIORITY - Set it BEFORE DOM renders
const preserveScroll = () => {
console.log("🚀 FORCE SETTING SCROLL POSITION TO:", currentScrollPosition);
if (timelineContainer) {
timelineContainer.scrollTop = currentScrollPosition;
// Double-verify immediately
if (timelineContainer.scrollTop !== currentScrollPosition) {
console.log("⚠️ Immediate re-application needed");
timelineContainer.scrollTop = currentScrollPosition;
}
}
};
// 🎯 PRE-SET SCROLL POSITION (before renderTimeline)
preserveScroll();
// 🛡️ MULTI-LAYER PROTECTION: Auto-scroll listeners strategy
let scrollRestorationAttempted = false;
const enforceScrollPosition = () => {
if (!scrollRestorationAttempted && timelineContainer) {
preserveScroll();
scrollRestorationAttempted = true;
console.log("✅ Scroll position enforced!");
// 🆔 ONE FINAL VERIFICATION (nuclear option)
const finalCheck = setTimeout(() => {
if (timelineContainer && Math.abs(timelineContainer.scrollTop - currentScrollPosition) > 2) {
console.error("❌ SOUNDING ALARMS - Scroll position lost! Force re-applying...");
timelineContainer.scrollTop = currentScrollPosition;
} else {
console.log("🎯 Scroll position successful!");
}
}, 200);
// 🧹 Cleanup after confirmation
setTimeout(() => clearTimeout(finalCheck), 250);
}
};
// 🎪 BIND SCROLL PROTECTION LISTENERS
let scrollListenerAttached = false;
if (!scrollListenerAttached && timelineContainer) {
const attachListener = () => {
if (!scrollListenerAttached) {
scrollListenerAttached = true;
timelineContainer.addEventListener('scroll', () => {
// 🛡️ IMMEDIATE PROTECTION: If scroll position changes unexpectedly, force correction
if (Math.abs(timelineContainer.scrollTop - currentScrollPosition) > 5) {
console.warn("🎭 Scroll position hijacked, correcting...");
timelineContainer.scrollTop = currentScrollPosition;
}
}, { passive: true });
}
};
attachListener();
}
// 📢 LONG-TERM OVERRIDE PROTECTION (insurance policy)
const overrideProtection = () => {
if (timelineContainer) {
const observedPosition = timelineContainer.scrollTop;
console.log("🛡️ Override protection scan - Current:", observedPosition, "Target:", currentScrollPosition);
if (Math.abs(observedPosition - currentScrollPosition) > 3) {
console.log("🛡️ Activating override protection...");
preserveScroll();
return true;
}
return false;
}
};
// 🕐 EXECUTE WITH PERFECT TIMING
console.log("⚡ Starting edit completion with bulletproof scroll preservation...");
// 🌟 JUST THE RIGHT TIMING: Set scroll position BEFORE render, but let DOM settle first
setTimeout(() => {
enforceScrollPosition();
}, 0);
// 🏃 Main execution happens AFTER scroll position is secure
setTimeout(() => {
console.log("⚡ Rendering timeline with preserved scroll position...");
renderTimeline();
console.log("✅ Timeline rendered successfully");
// 🎩 MAGIC TRICK: Pre-emptive protection
setTimeout(() => {
if (overrideProtection()) {
console.log("🔐 Override successfully blocked!");
} else {
console.log("👍 Scroll position intact");
}
}, 50);
// 🎊 SUCCESS CONFIRMATION
showSuccess("Note updated successfully!");
console.log(" ✨ EDIT OPERATION COMPLETE WITH PERFECT SCROLL PRESERVATION! ✨");
}, 10);
// 🔒 FINAL SWEEP (enhanced cleanup)
setTimeout(() => {
if (timelineContainer) {
// Remove our temporary event listener
if (scrollListenerAttached) {
scrollListenerAttached = false;
const newListener = () => {
// 😈 The calm before the storm - final protection
setTimeout(() => {
if (Math.abs(timelineContainer.scrollTop - currentScrollPosition) > 1) {
console.log("🎯 Final sweep correction applied");
timelineContainer.scrollTop = currentScrollPosition;
}
}, 10);
};
// Reattach final protection (one time only)
timelineContainer.addEventListener('scroll', newListener, { once: true, passive: true });
}
}
}, 300);
// 🎊 SUCCESS CONFIRMATION
console.log(" ✨ EDIT OPERATION COMPLETE WITH PERFECT SCROLL PRESERVATION! ✨");
} catch (error) {
handleError(error, "saving note");
}
}
function closeModal() {
editorModal.close();
setEditTags([]);
setCurrentEditId(null);
}
// Filter management
function toggleTagFilter(tag) {
// Save scroll position before filtering
if (timelineContainer) {
savedScrollPosition = timelineContainer.scrollTop;
console.log("📍 Saved scroll position before tag filter:", savedScrollPosition);
}
const index = activeTagFilters.indexOf(tag);
if (index === -1) {
activeTagFilters.push(tag);
} else {
activeTagFilters.splice(index, 1);
}
renderTimeline();
}
function clearSearchFilter() {
// Save scroll position before clearing filters
if (timelineContainer) {
savedScrollPosition = timelineContainer.scrollTop;
console.log("📍 Saved scroll position before clearing search:", savedScrollPosition);
}
currentSearch = "";
liveSearchInput.value = "";
renderTimeline();
}
function clearAllFilters() {
// Save scroll position before clearing all filters
if (timelineContainer) {
savedScrollPosition = timelineContainer.scrollTop;
console.log("📍 Saved scroll position before clearing filters:", savedScrollPosition);
}
activeTagFilters = [];
currentSearch = "";
liveSearchInput.value = "";
renderTimeline();
}
// Search management
function toggleSearch() {
const isActive = searchBar.classList.contains("active");
if (isActive) {
searchBar.classList.remove("active");
} else {
searchBar.classList.add("active");
liveSearchInput.focus();
}
}
// Debounced search function
const handleSearchInput = debounce(() => {
// Save scroll position before search triggers re-render
if (timelineContainer) {
savedScrollPosition = timelineContainer.scrollTop;
console.log("📍 Saved scroll position before search:", savedScrollPosition);
}
currentSearch = liveSearchInput.value.trim();
renderTimeline();
}, 300);
// Navigation
async function showTimelineView() {
currentView = "timeline";
showView("timelineView");
document.getElementById("homeBtn").classList.add("active");
// Restore scroll position when coming back to timeline view
const savedScroll = await database.getSetting("savedScrollPosition");
if (savedScroll !== undefined) {
lastAddedNoteId = null; // Clear auto-scroll for new notes on navigation
savedScrollPosition = parseInt(savedScroll) || null;
if (savedScrollPosition !== null && timelineContainer) {
console.log("📍 Restored timeline scroll position after navigation:", savedScrollPosition);
// Use requestAnimationFrame to ensure DOM is ready after render
requestAnimationFrame(() => {
renderTimeline();
requestAnimationFrame(() => {
timelineContainer.scrollTop = savedScrollPosition;
});
});
} else {
renderTimeline();
}
} else {
renderTimeline();
}
}
function showTagsModal() {
const modal = document.getElementById("tagsFilterModal");
renderTagsModal();
modal.showModal();
}
function closeTagsModal() {
const modal = document.getElementById("tagsFilterModal");
modal.close();
}
function renderTagsModal() {
// Update type filter checkboxes - using only the current available types
const typeFilters = ["note", "draft", "event", "period"];
typeFilters.forEach((type) => {
const checkbox = document.getElementById(`type-${type}`);
if (checkbox) {
checkbox.checked = activeTypeFilters.includes(type);
}
});
// Render available tags
const availableTags = [...new Set(notes.flatMap((note) => note.tags || []))];
const tagsContainer = document.getElementById("availableTags");
if (availableTags.length === 0) {
tagsContainer.innerHTML =
'<em style="color: #888">No tags found. Add tags to your notes to filter by them.</em>';
return;
}
tagsContainer.innerHTML = "";
availableTags.sort().forEach((tag) => {
const label = document.createElement("label");
label.className = "tags-filter-modal";
label.innerHTML = `
<input type="checkbox" value="${escapeHtml(tag)}" ${activeTagFilters.includes(tag) ? "checked" : ""}>
${escapeHtml(tag)}
`;
tagsContainer.appendChild(label);
});
}
function applyTagFilters() {
// Get selected types
activeTypeFilters = [];
const typeCheckboxes = document.querySelectorAll(
'#typeFilters input[type="checkbox"]:checked',
);
typeCheckboxes.forEach((checkbox) => {
activeTypeFilters.push(checkbox.id.replace("type-", ""));
});
// Get selected tags
activeTagFilters = [];
const tagCheckboxes = document.querySelectorAll(
'#availableTags input[type="checkbox"]:checked',
);
tagCheckboxes.forEach((checkbox) => {
activeTagFilters.push(checkbox.value);
});
closeTagsModal();
renderTimeline();
showSuccess("Filters applied!");
}
function clearAllTagFilters() {
activeTagFilters = [];
activeTypeFilters = ["note", "draft", "event", "period"];
renderTagsModal();
}
function showSettingsView() {
// Save scroll position before switching views
if (currentView === "timeline" && timelineContainer) {
saveScrollPosition();
console.log("📍 Saved scroll position before switching to settings:", timelineContainer.scrollTop);
}
currentView = "settings";
showView("settingsView");
document.getElementById("settingsBtn").classList.add("active");
renderSettings();
}
function showTrashView() {
currentView = "trash";
showView("trashView");
document.getElementById("trashBtn").classList.add("active");
renderTrash();
}
// Settings operations
async function exportData() {
try {
const data = await database.exportData();
const filename = `tlnotes-${new Date().toISOString().split("T")[0]}.json`;
downloadFile(JSON.stringify(data, null, 2), filename);
showSuccess("Data exported successfully!");
} catch (error) {
handleError(error, "exporting data");
}
}
async function 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 content = await readFile(file);
const data = JSON.parse(content);
showConfirmDialog(
"Import Data",
`Import ${data.notes?.length || 0} notes? This will replace your current notes.`,
async (confirmed) => {
if (confirmed) {
try {
await database.importData(data);
await loadData();
renderTimeline();
renderSettings();
showSuccess("Data imported successfully!");
} catch (error) {
handleError(error, "importing data");
}
}
},
);
} catch (error) {
handleError(error, "reading import file");
}
};
input.click();
}
async function clearAllData() {
showConfirmDialog(
"Clear All Data",
"This will permanently delete ALL notes and trash. This cannot be undone!",
async (confirmed) => {
if (confirmed) {
try {
await database.clearAllData();
notes = [];
trashNotes = [];
renderTimeline();
renderSettings();
showSuccess("All data cleared");
} catch (error) {
handleError(error, "clearing all data");
}
}
},
);
}
async function restoreAllTrash() {
if (trashNotes.length === 0) {
showSuccess("Trash is empty");
return;
}
try {
await database.restoreAllFromTrash();
// Update local state
trashNotes.forEach((note) => {
delete note.trashedAt;
notes.push(note);
});
trashNotes = [];
renderTrash();
renderSettings();
showSuccess(`Restored ${trashNotes.length} notes from trash`);
} catch (error) {
handleError(error, "restoring all trash");
}
}
async function emptyTrash() {
if (trashNotes.length === 0) {
showSuccess("Trash is already empty");
return;
}
showConfirmDialog(
"Empty Trash",
`Permanently delete ${trashNotes.length} notes? This cannot be undone!`,
async (confirmed) => {
if (confirmed) {
try {
await database.emptyTrash();
trashNotes = [];
renderTrash();
renderSettings();
showSuccess("Trash emptied");
} catch (error) {
handleError(error, "emptying trash");