Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2157 lines (1794 loc) · 78 KB
/
Copy pathscript.js
File metadata and controls
2157 lines (1794 loc) · 78 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
class DailyJournal {
constructor() {
this.directoryEntries = this.loadCachedDirectoryEntries();
this.files = [];
this.activeFileIndex = 0;
this.currentFilter = 'yesterday';
this.currentCalendarYear = new Date().getFullYear();
this.similarEntriesTimeout = null;
this.selectedDate = new Date();
this.selectedDirectory = null;
this.foundFiles = [];
// BM25+ indices, keyed by file.path
this.bm25Indices = new Map();
this.bm25PersistTimer = null;
// Configurable past entry periods
this.pastPeriods = this.loadPastPeriods();
this.editingPeriodId = null;
// Theme management
this.currentTheme = this.loadTheme();
this.init();
}
// Default past periods configuration
getDefaultPastPeriods() {
return [
{ id: '1d', label: '1d', unit: 'days', value: 1 },
{ id: '1w', label: '1w', unit: 'weeks', value: 1 },
{ id: '2w', label: '2w', unit: 'weeks', value: 2 },
{ id: '1mo', label: '1mo', unit: 'months', value: 1 },
{ id: '3mo', label: '3mo', unit: 'months', value: 3 },
{ id: '6mo', label: '6mo', unit: 'months', value: 6 },
{ id: '1y', label: '1y', unit: 'years', value: 1 },
];
}
loadPastPeriods() {
const stored = localStorage.getItem('journey.pastPeriods');
return stored ? JSON.parse(stored) : this.getDefaultPastPeriods();
}
// Theme management methods
loadTheme() {
const stored = localStorage.getItem('journey.theme');
return stored || 'light';
}
saveTheme(theme) {
localStorage.setItem('journey.theme', theme);
}
applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
this.currentTheme = theme;
// Update theme toggle button icon(s)
const icon = theme === 'dark' ? '☀️' : '🌙';
const themeToggle = document.getElementById('themeToggle');
if (themeToggle) {
themeToggle.textContent = icon;
}
}
toggleTheme() {
const newTheme = this.currentTheme === 'light' ? 'dark' : 'light';
this.applyTheme(newTheme);
this.saveTheme(newTheme);
}
initializeTheme() {
this.applyTheme(this.currentTheme);
// Check for system preference if no saved theme
if (!localStorage.getItem('journey.theme')) {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const systemTheme = prefersDark ? 'dark' : 'light';
this.applyTheme(systemTheme);
}
}
savePastPeriods() {
localStorage.setItem('journey.pastPeriods', JSON.stringify(this.pastPeriods));
}
renderFilterButtons() {
const container = document.querySelector('.time-filters');
container.innerHTML = '';
this.pastPeriods.forEach(period => {
const button = document.createElement('button');
button.className = `filter-btn ${period.id === this.currentFilter ? 'active' : ''}`;
button.dataset.filter = period.id;
button.textContent = period.label;
// Disable button if no entry exists for this period
if (!this.hasEntryForPeriod(period)) {
button.disabled = true;
}
button.addEventListener('click', () => this.filterPastEntries(period.id));
container.appendChild(button);
});
}
async init() {
this.initializeTheme();
this.registerServiceWorker();
this.initializeDatePicker();
this.bindEvents();
this.initSwipeNavigation();
this.initializeFiles();
await this.initializeBM25Indices();
this.renderFilterButtons();
this.selectFirstAvailablePeriod();
this.renderFileTabs();
this.refreshView();
this.loadDirectorySettings();
// Restore the previously selected directory (auto if permission is still
// granted, otherwise via the one-click "Restore Directory" button)
await this.tryAutoRestoreDirectory();
}
registerServiceWorker() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js').then((registration) => {
console.log('ServiceWorker registered with scope:', registration.scope);
// Determine if we're in development mode
const isDevelopment = !this.isRunningAsPWA() || window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
// Send the mode to the service worker
if (registration.active) {
registration.active.postMessage({
type: 'SET_MODE',
isDevelopment: isDevelopment
});
} else if (registration.installing) {
registration.installing.addEventListener('statechange', () => {
if (registration.active) {
registration.active.postMessage({
type: 'SET_MODE',
isDevelopment: isDevelopment
});
}
});
}
// Listen for update notifications in production
if (!isDevelopment) {
this.setupUpdateNotifications(registration);
}
// Handle updates
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
// New service worker is available, waiting to activate
if (!isDevelopment) {
this.showUpdateNotification();
}
}
});
});
}).catch((error) => {
console.log('ServiceWorker registration failed:', error);
});
// Listen for messages from service worker
navigator.serviceWorker.addEventListener('message', (event) => {
if (event.data && event.data.type === 'UPDATE_AVAILABLE') {
this.showUpdateNotification();
}
});
}
}
setupUpdateNotifications(registration) {
// Listen for controller changes (service worker was updated)
navigator.serviceWorker.addEventListener('controllerchange', () => {
// Reload the page when the new service worker activates
window.location.reload();
});
}
showUpdateNotification() {
// Check if notification already exists
if (document.getElementById('updateNotification')) {
return;
}
const notification = document.createElement('div');
notification.id = 'updateNotification';
notification.className = 'update-notification';
notification.innerHTML = `
<div class="update-notification-content">
<span>A new version is available!</span>
<div class="update-notification-actions">
<button id="updateNowBtn">Update Now</button>
<button id="updateLaterBtn">Later</button>
</div>
</div>
`;
document.body.appendChild(notification);
document.getElementById('updateNowBtn').addEventListener('click', () => {
// Tell the service worker to skip waiting
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({
type: 'SKIP_WAITING'
});
}
});
document.getElementById('updateLaterBtn').addEventListener('click', () => {
notification.remove();
});
}
isRunningAsPWA() {
// Check if running in standalone mode (PWA)
return window.matchMedia('(display-mode: standalone)').matches ||
window.navigator.standalone === true;
}
// IndexedDB helpers for persisting the directory handle across reloads
async getDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open('journey-pwa-storage', 1);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains('handles')) {
db.createObjectStore('handles');
}
};
});
}
async saveDirectoryHandle(handle) {
if (!handle) return;
try {
const db = await this.getDB();
const tx = db.transaction('handles', 'readwrite');
tx.objectStore('handles').put(handle, 'directoryHandle');
await new Promise((resolve, reject) => {
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
} catch (error) {
console.warn('Failed to save directory handle:', error);
}
}
async getDirectoryHandle() {
try {
const db = await this.getDB();
return new Promise((resolve, reject) => {
const tx = db.transaction('handles', 'readonly');
const request = tx.objectStore('handles').get('directoryHandle');
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
} catch (error) {
console.warn('Failed to get directory handle:', error);
return null;
}
}
async clearDirectoryHandle() {
try {
const db = await this.getDB();
const tx = db.transaction('handles', 'readwrite');
tx.objectStore('handles').delete('directoryHandle');
await new Promise((resolve, reject) => {
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
} catch (error) {
console.warn('Failed to clear directory handle:', error);
}
}
// On startup, try to silently restore the previously selected directory.
// If permission is still granted (Chrome remembers it per origin), restore
// automatically; otherwise surface a one-click "Restore Directory" button,
// since requestPermission() must run inside a user gesture.
async tryAutoRestoreDirectory() {
try {
const directoryHandle = await this.getDirectoryHandle();
if (!directoryHandle) return;
const permission = await directoryHandle.queryPermission({ mode: 'readwrite' });
if (permission === 'granted') {
await this.applyRestoredDirectory(directoryHandle);
return;
}
// Permission needs a user gesture — show the restore button.
this._pendingRestoreHandle = directoryHandle;
const restoreBtn = document.getElementById('restoreDirectoryBtn');
if (restoreBtn) restoreBtn.style.display = 'inline-block';
} catch (error) {
console.warn('Failed to auto-restore directory:', error);
}
}
// Triggered by the "Restore Directory" button (user gesture).
async restoreDirectoryWithPermission() {
const directoryHandle = this._pendingRestoreHandle;
if (!directoryHandle) return;
try {
const permission = await directoryHandle.requestPermission({ mode: 'readwrite' });
if (permission !== 'granted') {
this.showMessage('Directory permission not granted', 'info');
return;
}
await this.applyRestoredDirectory(directoryHandle);
} catch (error) {
console.warn('Failed to restore directory:', error);
} finally {
this._pendingRestoreHandle = null;
const restoreBtn = document.getElementById('restoreDirectoryBtn');
if (restoreBtn) restoreBtn.style.display = 'none';
}
}
// Apply a restored directory: set state, update UI, scan, and re-attach file
// handles so edits write to the OS files again.
async applyRestoredDirectory(directoryHandle) {
this.selectedDirectory = directoryHandle;
const directoryInfo = document.getElementById('directoryInfo');
const directoryPath = document.getElementById('selectedDirectoryPath');
const clearBtn = document.getElementById('clearDirectoryBtn');
directoryPath.textContent = directoryHandle.name;
directoryInfo.style.display = 'block';
clearBtn.disabled = false;
// Scan for files
await this.scanDirectoryFiles();
// Auto-load previously selected files (this re-attaches FileSystemFileHandles)
const savedFilePaths = this.getSavedSelectedFilePaths();
if (savedFilePaths && savedFilePaths.length > 0) {
await this.autoLoadPreviouslySelectedFiles(savedFilePaths);
this.showMessage(`Restored ${savedFilePaths.length} files from previous session`, 'success');
}
}
initializeFiles() {
// 1. Default Journal (Tab 0)
const defaultEntries = this.loadEntriesFromLocalStorage();
this.files.push({
name: 'My Journal',
type: 'local',
path: 'local',
entries: defaultEntries,
content: '' // Not used for local type
});
// 2. Load cached directory files as tabs
Object.keys(this.directoryEntries).forEach(path => {
const content = this.directoryEntries[path];
// Extract filename from path
const name = path.split('/').pop() || path;
const entries = this.parseContentToEntries(content);
this.files.push({
name: name,
type: 'file',
path: path,
content: content,
entries: entries
});
});
// Resume the previously active file tab if it still exists
this.restoreActiveFile();
}
get entries() {
return this.files[this.activeFileIndex].entries;
}
refreshView() {
this.loadSelectedEntry();
this.displayPastEntries();
this.generateYearTabs();
this.generateActivityCalendar();
// Re-calculate similar entries with current text and new entries
const currentText = document.getElementById('entryText').value;
this.findSimilarEntries(currentText);
}
initializeDatePicker() {
const datePicker = document.getElementById('datePicker');
datePicker.value = this.getDateString(this.selectedDate);
}
bindEvents() {
// Theme toggle
document.getElementById('themeToggle').addEventListener('click', () => this.toggleTheme());
// Import/Export panel toggle (hidden by default)
const importExportToggle = document.getElementById('importExportToggle');
if (importExportToggle) {
importExportToggle.addEventListener('click', () => {
const section = document.querySelector('.import-export');
const open = section.classList.toggle('open');
importExportToggle.classList.toggle('active', open);
importExportToggle.title = open ? 'Hide import / export' : 'Show import / export';
});
}
document.getElementById('datePicker').addEventListener('change', (e) => this.onDateChange(e));
document.getElementById('clearEntry').addEventListener('click', () => this.clearEntry());
document.getElementById('entryText').addEventListener('input', (e) => this.onEntryInput(e));
document.getElementById('entryText').addEventListener('blur', () => this.checkAndSaveEntry());
document.getElementById('importBtn').addEventListener('click', () => this.importJournal());
document.getElementById('exportBtn').addEventListener('click', () => this.exportJournal());
document.getElementById('importFile').addEventListener('change', (e) => this.handleFileImport(e));
document.getElementById('selectDirectoryBtn').addEventListener('click', () => this.selectDirectory());
const restoreBtn = document.getElementById('restoreDirectoryBtn');
if (restoreBtn) {
restoreBtn.addEventListener('click', () => this.restoreDirectoryWithPermission());
}
document.getElementById('updateFilesBtn').addEventListener('click', () => this.updateSelectedFiles());
document.getElementById('clearDirectoryBtn').addEventListener('click', () => this.clearDirectory());
document.getElementById('selectAllFilesBtn').addEventListener('click', () => this.selectAllFiles());
document.getElementById('selectNoneFilesBtn').addEventListener('click', () => this.selectNoneFiles());
document.getElementById('fileFilterInput').addEventListener('input', (e) => this.filterFileList(e.target.value));
// Configuration Modal Events
document.getElementById('configurePastEntriesBtn').addEventListener('click', () => this.openConfigModal());
document.getElementById('closeConfigModal').addEventListener('click', () => this.closeConfigModal());
document.getElementById('configModal').addEventListener('click', (e) => {
if (e.target === document.getElementById('configModal')) this.closeConfigModal();
});
document.getElementById('addPeriodBtn').addEventListener('click', () => this.addPeriod());
document.getElementById('cancelEditBtn').addEventListener('click', () => this.cancelEdit());
// Close mobile menu when clicking outside
document.addEventListener('click', (e) => {
const container = document.getElementById('sidebar');
// Ignore the synthetic click that sometimes follows a swipe gesture
if (Date.now() - (this._lastSwipeTime || 0) < 400) return;
if (container.classList.contains('open') &&
!container.contains(e.target)) {
container.classList.remove('open');
}
});
// Keep the textarea height in sync when the viewport changes
window.addEventListener('resize', () => this.autoResizeEntry());
}
initSwipeNavigation() {
const container = document.getElementById('sidebar');
const EDGE = 40; // px from left edge where an open-swipe may begin
const WIDTH = 250; // drawer width (matches CSS)
const SNAP_FRACTION = 0.15; // fraction of width required to commit a swipe
const LOCK_AXIS = 10; // movement before locking horizontal vs vertical
let dragging = false;
let locked = false;
let horizontal = false;
let startX = 0;
let startY = 0;
let deltaX = 0;
let openedViaDrag = false;
document.addEventListener('touchstart', (e) => {
if (window.innerWidth > 600) return;
if (dragging) return; // ignore additional fingers mid-drag
const touch = e.touches[0];
const open = container.classList.contains('open');
// Start a drag when the drawer is open (close from anywhere)
// or when the touch begins near the left edge (open from closed).
if (open || touch.clientX <= EDGE) {
dragging = true;
locked = false;
horizontal = false;
startX = touch.clientX;
startY = touch.clientY;
deltaX = 0;
openedViaDrag = !open;
}
}, { passive: true });
document.addEventListener('touchmove', (e) => {
if (!dragging) return;
const touch = e.touches[0];
const dx = touch.clientX - startX;
const dy = touch.clientY - startY;
if (!locked) {
// For edge-originated swipes, claim the gesture as soon as it
// leans horizontal, otherwise the browser's back-swipe wins.
const threshold = openedViaDrag ? 2 : LOCK_AXIS;
if (Math.abs(dx) <= threshold && Math.abs(dy) <= threshold) return;
locked = true;
horizontal = Math.abs(dx) > Math.abs(dy);
if (horizontal) container.style.transition = 'none';
}
// Let vertical gestures pass through (page scroll); take over
// horizontal ones and cancel the browser default (back navigation).
if (!horizontal) return;
e.preventDefault();
deltaX = dx;
let offset;
if (openedViaDrag) {
// Closed drawer slides in from -WIDTH toward 0.
offset = Math.min(0, Math.max(-WIDTH, dx - WIDTH));
} else {
// Open drawer slides out from 0 toward -WIDTH.
offset = Math.min(0, Math.max(-WIDTH, dx));
}
container.style.transform = `translateX(${offset}px)`;
}, { passive: false });
const finish = () => {
if (!dragging) return;
dragging = false;
const wasHorizontal = horizontal;
horizontal = false;
locked = false;
container.style.transition = '';
container.style.transform = '';
if (!wasHorizontal) return;
if (openedViaDrag && deltaX > WIDTH * SNAP_FRACTION) {
container.classList.add('open');
} else if (!openedViaDrag && deltaX < -WIDTH * SNAP_FRACTION) {
container.classList.remove('open');
}
this._lastSwipeTime = Date.now();
};
document.addEventListener('touchend', finish, { passive: true });
document.addEventListener('touchcancel', finish, { passive: true });
}
renderFileTabs() {
const tabsContainer = document.getElementById('fileTabs');
tabsContainer.innerHTML = '';
if (this.files.length <= 1) {
tabsContainer.style.display = 'none';
return;
}
tabsContainer.style.display = '';
this.files.forEach((file, index) => {
const tab = document.createElement('div');
tab.className = `file-tab ${index === this.activeFileIndex ? 'active' : ''}`;
const nameSpan = document.createElement('span');
nameSpan.textContent = file.name;
tab.appendChild(nameSpan);
// Add close button for non-default tabs
if (index > 0) {
const closeBtn = document.createElement('span');
closeBtn.className = 'close-tab';
closeBtn.innerHTML = '×';
closeBtn.title = 'Close file';
closeBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.closeFileTab(index);
});
tab.appendChild(closeBtn);
}
tab.addEventListener('click', () => this.switchFileTab(index));
tabsContainer.appendChild(tab);
});
}
switchFileTab(index) {
if (index === this.activeFileIndex) return;
this.activeFileIndex = index;
this.saveActiveFilePath();
this.renderFileTabs();
this.refreshView();
// Close mobile menu if open
document.getElementById('sidebar').classList.remove('open');
}
closeFileTab(index) {
if (index === 0) return; // Cannot close default journal
const fileToRemove = this.files[index];
// Remove from directoryEntries
if (fileToRemove.type === 'file') {
delete this.directoryEntries[fileToRemove.path];
}
// Drop the BM25 index for the closed file
this.removeBM25Index(fileToRemove.path);
// Remove from files array
this.files.splice(index, 1);
// Adjust active index
if (this.activeFileIndex === index) {
this.activeFileIndex = Math.max(0, index - 1);
} else if (this.activeFileIndex > index) {
this.activeFileIndex--;
}
this.renderFileTabs();
this.refreshView();
this.updateLoadButtonState();
this.persistDirectoryEntries();
this.saveActiveFilePath();
this.showMessage(`Closed ${fileToRemove.name}`, 'info');
}
onDateChange(e) {
// Parse the date string (YYYY-MM-DD) and create a date in local time
const [year, month, day] = e.target.value.split('-').map(Number);
this.selectedDate = new Date(year, month - 1, day);
this.loadSelectedEntry();
this.findSimilarEntries(document.getElementById('entryText').value);
this.selectFirstAvailablePeriod();
this.displayPastEntries();
}
selectFirstAvailablePeriod() {
const firstWithEntry = this.pastPeriods.find(p => this.hasEntryForPeriod(p));
// Fall back to the first period so currentFilter is always valid,
// even when no period has an entry yet.
const target = firstWithEntry || this.pastPeriods[0];
if (target) {
this.currentFilter = target.id;
}
document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active'));
const activeBtn = document.querySelector(`[data-filter="${this.currentFilter}"]`);
if (activeBtn) activeBtn.classList.add('active');
}
getDateString(date = new Date()) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
loadEntriesFromLocalStorage() {
const stored = localStorage.getItem('journey.journalEntries');
return stored ? JSON.parse(stored) : {};
}
loadCachedDirectoryEntries() {
try {
const stored = localStorage.getItem('journey.directoryEntries');
return stored ? JSON.parse(stored) : {};
} catch {
return {};
}
}
persistDirectoryEntries() {
try {
localStorage.setItem('journey.directoryEntries', JSON.stringify(this.directoryEntries));
} catch (error) {
console.warn('Failed to persist directory entries:', error);
}
}
// Persist/restore the active file tab (by path, which is stable across reloads)
loadActiveFilePath() {
return localStorage.getItem('journey.activeFilePath');
}
saveActiveFilePath() {
const file = this.files[this.activeFileIndex];
if (file) {
localStorage.setItem('journey.activeFilePath', file.path);
}
}
restoreActiveFile() {
const savedPath = this.loadActiveFilePath();
if (!savedPath) return;
const index = this.files.findIndex(f => f.path === savedPath);
if (index >= 0) {
this.activeFileIndex = index;
}
}
async saveCurrentEntries() {
const currentFile = this.files[this.activeFileIndex];
if (currentFile.type === 'local') {
localStorage.setItem('journey.journalEntries', JSON.stringify(currentFile.entries));
} else if (currentFile.type === 'file') {
// Regenerate content string from entries
// This assumes a simple Markdown format for saving back
const newContent = this.entriesToMarkdown(currentFile.entries);
currentFile.content = newContent;
// Update directoryEntries
this.directoryEntries[currentFile.path] = newContent;
this.persistDirectoryEntries();
// Write to disk if handle is available
if (currentFile.handle) {
try {
const writable = await currentFile.handle.createWritable();
await writable.write(newContent);
await writable.close();
} catch (error) {
console.error('Failed to write to disk:', error);
this.showMessage('Failed to save to disk', 'error');
}
}
}
}
entriesToMarkdown(entries) {
// Sort dates
const sortedDates = Object.keys(entries).sort();
return sortedDates.map(date => `# ${date}\n\n${entries[date]}`).join('\n\n');
}
loadSelectedEntry() {
const selectedDateStr = this.getDateString(this.selectedDate);
const entry = this.entries[selectedDateStr] || '';
document.getElementById('entryText').value = entry;
this.autoResizeEntry();
this.setSaveIndicator('saved');
}
checkAndSaveEntry() {
const selectedDateStr = this.getDateString(this.selectedDate);
const savedText = this.entries[selectedDateStr] || '';
const currentText = document.getElementById('entryText').value.trim();
if (savedText !== currentText) {
this.saveEntry();
} else {
this.setSaveIndicator('saved');
}
}
async saveEntry() {
const selectedDateStr = this.getDateString(this.selectedDate);
const entryText = document.getElementById('entryText').value.trim();
const currentEntries = this.entries; // Get current file's entries
let saved = false;
let mutated = false;
if (entryText) {
const previous = currentEntries[selectedDateStr];
currentEntries[selectedDateStr] = entryText;
await this.saveCurrentEntries();
saved = true;
mutated = previous !== entryText;
} else if (currentEntries[selectedDateStr]) {
delete currentEntries[selectedDateStr];
await this.saveCurrentEntries();
saved = true;
mutated = true;
}
if (mutated) {
this.updateBM25Document(selectedDateStr, entryText);
}
this.refreshView();
if (saved) this.setSaveIndicator('saved');
}
// state: 'saved' (✅) or 'dirty' (♻️ unsaved changes pending)
setSaveIndicator(state) {
const el = document.getElementById('saveIndicator');
if (!el) return;
if (state === 'dirty') {
el.textContent = '✏️';
el.title = 'Unsaved changes';
} else {
el.textContent = '✔️';
el.title = 'Saved';
}
}
clearEntry() {
document.getElementById('entryText').value = '';
this.autoResizeEntry();
this.setSaveIndicator('dirty');
document.getElementById('similarEntriesContainer').innerHTML = '';
}
onEntryInput(e) {
const text = e.target.value;
this.autoResizeEntry();
this.setSaveIndicator('dirty');
if (this.similarEntriesTimeout) {
clearTimeout(this.similarEntriesTimeout);
}
this.similarEntriesTimeout = setTimeout(() => {
this.findSimilarEntries(text);
}, 150);
}
autoResizeEntry() {
const el = document.getElementById('entryText');
if (!el) return;
el.style.height = 'auto';
el.style.height = `${el.scrollHeight}px`;
}
findSimilarEntries(currentText) {
if (currentText.length < 3) {
document.getElementById('similarEntriesContainer').innerHTML = '';
return;
}
const index = this.getActiveBM25Index();
if (!index || index.docCount === 0) {
document.getElementById('similarEntriesContainer').innerHTML = '';
return;
}
const selectedDateStr = this.getDateString(this.selectedDate);
const results = index.search(currentText, {
excludeId: selectedDateStr,
limit: 5,
});
if (results.length === 0) {
document.getElementById('similarEntriesContainer').innerHTML = '';
return;
}
const currentEntries = this.entries;
const similar = results
.map(r => {
const content = currentEntries[r.docId];
if (!content) return null;
return { date: r.docId, content, similarity: r.score };
})
.filter(Boolean);
this.displaySimilarEntries(similar);
}
// --- BM25+ index management ---
getActiveBM25Index() {
const file = this.files[this.activeFileIndex];
if (!file) return null;
return this.bm25Indices.get(file.path) || null;
}
async initializeBM25Indices() {
for (const file of this.files) {
await this.loadOrBuildBM25Index(file);
}
}
async loadOrBuildBM25Index(file) {
if (!file || this.bm25Indices.has(file.path)) return;
let index = null;
try {
const stored = await window.BM25.idbGet(file.path);
if (stored && stored.version === 1) {
index = window.BM25.Index.fromJSON(stored);
// Invalidate if the document set no longer matches.
if (index.docCount !== Object.keys(file.entries).length) {
index = null;
}
}
} catch (error) {
console.warn(`Failed to load BM25 index for ${file.path}:`, error);
}
if (!index) {
index = new window.BM25.Index();
index.rebuild(file.entries);
this.scheduleBM25Persist(file.path);
}
this.bm25Indices.set(file.path, index);
}
// Synchronize a single document in the active file's index.
updateBM25Document(dateStr, text) {
const file = this.files[this.activeFileIndex];
if (!file) return;
const index = this.bm25Indices.get(file.path);
if (!index) return;
if (text) {
index.addDocument(dateStr, text);
} else {
index.removeDocument(dateStr);
}
this.scheduleBM25Persist(file.path);
}
// Rebuild the index for a file from scratch (used after bulk imports).
rebuildBM25ForFile(file) {
if (!file) return;
let index = this.bm25Indices.get(file.path);
if (!index) {
index = new window.BM25.Index();
this.bm25Indices.set(file.path, index);
}
index.rebuild(file.entries);
this.scheduleBM25Persist(file.path);
}
removeBM25Index(path) {
if (!this.bm25Indices.has(path)) return;
this.bm25Indices.delete(path);
window.BM25.idbDelete(path);
}
scheduleBM25Persist(path) {
if (this.bm25PersistTimer) clearTimeout(this.bm25PersistTimer);
this.bm25PersistTimer = setTimeout(() => this.persistBM25Index(path), 1000);
}
async persistBM25Index(path) {
const index = this.bm25Indices.get(path);
if (!index) return;
try {
await window.BM25.idbSet(path, index.toJSON());
} catch (error) {
console.warn(`Failed to persist BM25 index for ${path}:`, error);
}
}
displaySimilarEntries(entries) {
const container = document.getElementById('similarEntriesContainer');
if (entries.length === 0) {
container.innerHTML = '';
return;
}
container.innerHTML = entries.map(entry => `
<div class="entry-item similar-entry" data-date="${entry.date}" role="button" tabindex="0">
<div class="entry-date">${this.formatDate(entry.date)}</div>
<div class="entry-content">${entry.content}</div>
</div>
`).join('');
container.querySelectorAll('.similar-entry').forEach(el => {
const loadDate = () => {
const datePicker = document.getElementById('datePicker');
datePicker.value = el.dataset.date;
datePicker.dispatchEvent(new Event('change'));
};
el.addEventListener('click', loadDate);
el.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
loadDate();
}
});
});
}
filterPastEntries(filter) {
this.currentFilter = filter;
document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active'));
document.querySelector(`[data-filter="${filter}"]`).classList.add('active');
this.displayPastEntries();
}
displayPastEntries() {
const container = document.getElementById('pastEntriesContainer');
const filteredEntries = this.getFilteredEntries();
if (filteredEntries.length === 0) {
container.innerHTML = '<div class="no-entries">No entries found for this time period.</div>';
} else {
container.innerHTML = filteredEntries.map(entry => `
<div class="entry-item">
<div class="entry-date">${this.formatDate(entry.date)}</div>
<div class="entry-content">${entry.content}</div>