-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1244 lines (1093 loc) · 39.5 KB
/
app.js
File metadata and controls
1244 lines (1093 loc) · 39.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
// --- NEW DB HELPER (Vanilla IndexedDB) ---
const DB_NAME = 'NoteVaultDB';
const DB_VERSION = 1;
const STORE_NAME = 'notes_store';
let CURRENT_PROFILE_KEY = 'default_notes';
const LEGACY_STORAGE_KEY = "notevault.v1.notes";
const db = {
_db: null,
open() {
return new Promise((resolve, reject) => {
if (this._db) return resolve(this._db);
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = (e) => {
console.error('Error opening IndexedDB', e);
reject(new Error('Could not open database.'));
};
request.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
};
request.onsuccess = (e) => {
this._db = e.target.result;
resolve(this._db);
};
});
},
async get(key) {
const db = await this.open();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readonly');
const store = transaction.objectStore(STORE_NAME);
const request = store.get(key);
request.onerror = (e) => reject(new Error('Could not get notes.'));
request.onsuccess = (e) => {
resolve(e.target.result);
};
});
},
async set(key, data) {
const db = await this.open();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.put(data, key);
request.onerror = (e) => reject(new Error('Could not save notes.'));
request.onsuccess = (e) => resolve(e.target.result);
});
},
async getAllKeys() {
const db = await this.open();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readonly');
const store = transaction.objectStore(STORE_NAME);
const request = store.getAllKeys();
request.onerror = (e) => reject(new Error('Could not get keys.'));
request.onsuccess = (e) => resolve(e.target.result);
});
},
async deleteKey(key) {
const db = await this.open();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.delete(key);
request.onerror = (e) => reject(new Error('Could not delete profile.'));
request.onsuccess = (e) => resolve();
});
}
};
// --- END DB HELPER ---
/** @type {Note[]} */
let notes = [];
let selectedNoteId = null;
let selectedImageId = null;
let imageViewerZoom = 1;
const els = {
notesList: document.getElementById("notesList"),
searchInput: document.getElementById("searchInput"),
appMain: document.querySelector(".app-main"),
viewer: document.getElementById("viewer"),
viewerTitle: document.getElementById("viewerTitle"),
addNoteBtn: document.getElementById("addNoteBtn"),
copyNoteBtn: document.getElementById("copyNoteBtn"),
saveNoteBtn: document.getElementById("saveNoteBtn"),
deleteNoteBtn: document.getElementById("deleteNoteBtn"),
partIdInput: document.getElementById("partIdInput"),
notesInput: document.getElementById("notesInput"),
addImageBtn: document.getElementById("addImageBtn"),
imageInput: document.getElementById("imageInput"),
imagesContainer: document.getElementById("imagesContainer"),
imageCaptionInput: document.getElementById("imageCaptionInput"),
noteListItemTemplate: document.getElementById("noteListItemTemplate"),
expandBtn: document.getElementById("expandBtn"),
printBtn: document.getElementById("printBtn"),
// Profile Buttons
exportDataBtn: document.getElementById("exportDataBtn"),
importDataBtn: document.getElementById("importDataBtn"),
currentProfileBtn: document.getElementById("currentProfileBtn"),
// Theme Buttons
themeLightBtn: document.getElementById("themeLightBtn"),
themeDarkBtn: document.getElementById("themeDarkBtn"),
// Profile Modal
profileModal: document.getElementById("profileModal"),
profileCloseBtn: document.getElementById("profileCloseBtn"),
profileList: document.getElementById("profileList"),
newProfileInput: document.getElementById("newProfileInput"),
createProfileBtn: document.getElementById("createProfileBtn"),
// NEW: App Alert Modal
appAlertModal: document.getElementById("appAlertModal"),
appAlertTitle: document.getElementById("appAlertTitle"),
appAlertMessage: document.getElementById("appAlertMessage"),
appAlertCloseBtn: document.getElementById("appAlertCloseBtn"),
appAlertOkBtn: document.getElementById("appAlertOkBtn"),
// NEW: App Confirm Modal
appConfirmModal: document.getElementById("appConfirmModal"),
appConfirmTitle: document.getElementById("appConfirmTitle"),
appConfirmMessage: document.getElementById("appConfirmMessage"),
appConfirmCancelBtn: document.getElementById("appConfirmCancelBtn"),
appConfirmOkBtn: document.getElementById("appConfirmOkBtn"),
// Cropper
cropperModal: document.getElementById("cropperModal"),
cropperImage: document.getElementById("cropperImage"),
cropperStage: document.querySelector(".cropper-stage"),
cropBox: document.getElementById("cropBox"),
cropSizeRange: document.getElementById("cropSizeRange"),
cropperCloseBtn: document.getElementById("cropperCloseBtn"),
cropperCancelBtn: document.getElementById("cropperCancelBtn"),
cropperApplyBtn: document.getElementById("cropperApplyBtn"),
cropMinusBtn: document.getElementById("cropMinusBtn"),
cropPlusBtn: document.getElementById("cropPlusBtn"),
cropCenterBtn: document.getElementById("cropCenterBtn"),
// Image Viewer
imageViewerModal: document.getElementById("imageViewerModal"),
modalViewerImage: document.getElementById("modalViewerImage"),
modalViewerCloseBtn: document.getElementById("modalViewerCloseBtn"),
};
// --- UTILS ---
// Debounce helper for autosave
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// --- THEME TOGGLE LOGIC ---
function setTheme(theme) {
// Set Attribute
if (theme === 'light') {
document.documentElement.setAttribute('data-theme', 'light');
els.themeLightBtn.classList.add('active');
els.themeDarkBtn.classList.remove('active');
} else {
document.documentElement.removeAttribute('data-theme');
els.themeDarkBtn.classList.add('active');
els.themeLightBtn.classList.remove('active');
}
// Save Preference
localStorage.setItem('app_theme', theme);
}
els.themeLightBtn.addEventListener("click", () => setTheme('light'));
els.themeDarkBtn.addEventListener("click", () => setTheme('dark'));
// Load saved theme on startup
const savedTheme = localStorage.getItem('app_theme');
if (savedTheme) {
setTheme(savedTheme);
} else {
setTheme('dark'); // Default
}
// --- INTERNAL MODAL SYSTEM ---
let confirmCallback = null;
function showAppAlert(title, message) {
els.appAlertTitle.textContent = title;
els.appAlertMessage.textContent = message;
els.appAlertModal.setAttribute("aria-hidden", "false");
els.appAlertOkBtn.focus();
}
function closeAppAlert() {
els.appAlertModal.setAttribute("aria-hidden", "true");
}
function showAppConfirm(title, message, onConfirm, danger = false) {
confirmCallback = onConfirm;
els.appConfirmTitle.textContent = title;
els.appConfirmMessage.textContent = message;
if (danger) {
els.appConfirmOkBtn.classList.add("danger");
els.appConfirmOkBtn.classList.remove("primary");
} else {
els.appConfirmOkBtn.classList.add("primary");
els.appConfirmOkBtn.classList.remove("danger");
}
els.appConfirmModal.setAttribute("aria-hidden", "false");
els.appConfirmCancelBtn.focus();
}
function closeAppConfirm() {
confirmCallback = null;
els.appConfirmModal.setAttribute("aria-hidden", "true");
}
els.appAlertCloseBtn.addEventListener("click", closeAppAlert);
els.appAlertOkBtn.addEventListener("click", closeAppAlert);
els.appConfirmCancelBtn.addEventListener("click", closeAppConfirm);
els.appConfirmOkBtn.addEventListener("click", () => {
if (confirmCallback) confirmCallback();
closeAppConfirm();
});
// --- END MODAL SYSTEM ---
// --- CROPPER LOGIC ---
let cropperState = {
imageId: null,
naturalWidth: 0,
naturalHeight: 0,
imgRect: null,
crop: { x: 0, y: 0, size: 100 },
zoom: 1,
};
async function openCropper(imgObj) {
if (!imgObj.originalDataUrl) {
imgObj.originalDataUrl = imgObj.dataUrl;
await saveNotes();
}
els.cropperImage.src = imgObj.originalDataUrl || imgObj.dataUrl;
cropperState.imageId = imgObj.id;
els.cropperModal.setAttribute("aria-hidden", "false");
selectedImageId = imgObj.id;
setZoom(1);
requestAnimationFrame(() => {
const rect = getDisplayedImageRect();
cropperState.imgRect = rect;
cropperState.naturalWidth = els.cropperImage.naturalWidth;
cropperState.naturalHeight = els.cropperImage.naturalHeight;
if (imgObj.lastCrop) {
const s = imgObj.lastCrop.relSize * rect.width;
const x = rect.left + (imgObj.lastCrop.relX * rect.width);
const y = rect.top + (imgObj.lastCrop.relY * rect.height);
positionCropBox(x, y, s);
} else {
const size = Math.min(rect.width, rect.height) * 0.6;
const x = rect.left + (rect.width - size) / 2;
const y = rect.top + (rect.height - size) / 2;
positionCropBox(x, y, size);
}
syncCropControls();
});
}
function closeCropper() {
els.cropperModal.setAttribute("aria-hidden", "true");
}
function positionCropBox(viewX, viewY, viewSize) {
const container = els.cropperStage.getBoundingClientRect();
const imageRect = getDisplayedImageRect();
const cb = els.cropBox;
const maxSize = Math.min(imageRect.width, imageRect.height);
const size = Math.max(20, Math.min(viewSize, maxSize));
const minLeft = imageRect.left;
const minTop = imageRect.top;
const maxLeft = imageRect.right - size;
const maxTop = imageRect.bottom - size;
const x = Math.max(minLeft, Math.min(viewX, maxLeft));
const y = Math.max(minTop, Math.min(viewY, maxTop));
cb.style.left = `${x - container.left}px`;
cb.style.top = `${y - container.top}px`;
cb.style.width = `${size}px`;
cb.style.height = `${size}px`;
cropperState.crop = { x, y, size };
syncCropControls();
}
const interaction = {
active: false,
mode: null,
startX: 0,
startY: 0,
startRect: null,
resizeAnchor: { x: 0, y: 0 },
resizeCorner: null
};
els.cropBox.addEventListener("pointerdown", (e) => {
e.preventDefault();
e.stopPropagation();
const target = e.target;
const isHandle = target.classList.contains('handle');
interaction.active = true;
interaction.startX = e.clientX;
interaction.startY = e.clientY;
interaction.startRect = els.cropBox.getBoundingClientRect();
if (isHandle) {
interaction.mode = 'resize';
interaction.resizeCorner = target.dataset.corner || (target.classList.contains('nw') ? 'nw' : target.classList.contains('ne') ? 'ne' : target.classList.contains('sw') ? 'sw' : 'se');
const rect = interaction.startRect;
if (interaction.resizeCorner === 'nw') interaction.resizeAnchor = { x: rect.right, y: rect.bottom };
if (interaction.resizeCorner === 'ne') interaction.resizeAnchor = { x: rect.left, y: rect.bottom };
if (interaction.resizeCorner === 'sw') interaction.resizeAnchor = { x: rect.right, y: rect.top };
if (interaction.resizeCorner === 'se') interaction.resizeAnchor = { x: rect.left, y: rect.top };
} else {
interaction.mode = 'move';
}
els.cropBox.setPointerCapture(e.pointerId);
});
window.addEventListener("pointermove", (e) => {
if (!interaction.active) return;
e.preventDefault();
if (interaction.mode === 'move') {
const dx = e.clientX - interaction.startX;
const dy = e.clientY - interaction.startY;
positionCropBox(interaction.startRect.left + dx, interaction.startRect.top + dy, interaction.startRect.width);
}
else if (interaction.mode === 'resize') {
const imgRect = els.cropperImage.getBoundingClientRect();
const cx = Math.max(imgRect.left, Math.min(e.clientX, imgRect.right));
const cy = Math.max(imgRect.top, Math.min(e.clientY, imgRect.bottom));
const newSize = Math.max(20, Math.min(
Math.min(imgRect.width, imgRect.height),
Math.max(Math.abs(cx - interaction.resizeAnchor.x), Math.abs(cy - interaction.resizeAnchor.y))
));
let x = interaction.resizeAnchor.x;
let y = interaction.resizeAnchor.y;
if (interaction.resizeCorner === 'nw') { x = interaction.resizeAnchor.x - newSize; y = interaction.resizeAnchor.y - newSize; }
if (interaction.resizeCorner === 'ne') { x = interaction.resizeAnchor.x; y = interaction.resizeAnchor.y - newSize; }
if (interaction.resizeCorner === 'sw') { x = interaction.resizeAnchor.x - newSize; y = interaction.resizeAnchor.y; }
if (interaction.resizeCorner === 'se') { x = interaction.resizeAnchor.x; y = interaction.resizeAnchor.y; }
positionCropBox(x, y, newSize);
}
});
window.addEventListener("pointerup", (e) => {
interaction.active = false;
interaction.mode = null;
});
els.cropBox.addEventListener(
"wheel",
(e) => {
e.preventDefault();
const delta = Math.sign(e.deltaY);
const rect = els.cropBox.getBoundingClientRect();
const newSize = rect.width * (1 - 0.08 * delta);
positionCropBox(rect.left, rect.top, newSize);
},
{ passive: false }
);
els.cropperImage.addEventListener("click", (e) => {
const stage = getDisplayedImageRect();
const cbRect = els.cropBox.getBoundingClientRect();
const size = cbRect.width;
const targetX = e.clientX - size / 2;
const targetY = e.clientY - size / 2;
positionCropBox(targetX, targetY, size);
});
els.cropBox.addEventListener("keydown", (e) => {
const rect = els.cropBox.getBoundingClientRect();
const step = e.shiftKey ? 10 : 2;
if (e.key === "ArrowLeft") {
e.preventDefault();
positionCropBox(rect.left - step, rect.top, rect.width);
}
if (e.key === "ArrowRight") {
e.preventDefault();
positionCropBox(rect.left + step, rect.top, rect.width);
}
if (e.key === "ArrowUp") {
e.preventDefault();
positionCropBox(rect.left, rect.top - step, rect.width);
}
if (e.key === "ArrowDown") {
e.preventDefault();
positionCropBox(rect.left, rect.top + step, rect.width);
}
if (e.key === "-" || e.key === "_") {
e.preventDefault();
positionCropBox(rect.left, rect.top, rect.width * 0.92);
}
if (e.key === "=" || e.key === "+") {
e.preventDefault();
positionCropBox(rect.left, rect.top, rect.width * 1.08);
}
});
function syncCropControls() {
const stage = getDisplayedImageRect();
const minSize = Math.max(
40,
Math.min(80, Math.min(stage.width, stage.height) * 0.08)
);
const maxSize = Math.min(stage.width, stage.height);
els.cropSizeRange.min = String(Math.floor(minSize));
els.cropSizeRange.max = String(Math.floor(maxSize));
els.cropSizeRange.value = String(
Math.floor(els.cropBox.getBoundingClientRect().width)
);
}
els.cropMinusBtn?.addEventListener("click", () => {
const rect = els.cropBox.getBoundingClientRect();
positionCropBox(rect.left, rect.top, rect.width * 0.92);
});
els.cropPlusBtn?.addEventListener("click", () => {
const rect = els.cropBox.getBoundingClientRect();
positionCropBox(rect.left, rect.top, rect.width * 1.08);
});
els.cropCenterBtn?.addEventListener("click", () => {
const stage = getDisplayedImageRect();
const size = els.cropBox.getBoundingClientRect().width;
const x = stage.left + (stage.width - size) / 2;
const y = stage.top + (stage.height - size) / 2;
positionCropBox(x, y, size);
});
els.cropSizeRange?.addEventListener("input", (e) => {
const rect = els.cropBox.getBoundingClientRect();
const size = Number(e.target.value) || rect.width;
positionCropBox(rect.left, rect.top, size);
});
function setZoom(z) {
const zoom = Math.max(0.25, Math.min(z, 3));
cropperState.zoom = zoom;
els.cropperImage.style.setProperty('--crop-zoom', String(zoom));
const rect = els.cropBox.getBoundingClientRect();
positionCropBox(rect.left, rect.top, rect.width);
}
if (!els.cropBox.querySelector('.handle')) {
['nw','ne','sw','se'].forEach(dir => {
const h = document.createElement('div');
h.className = `handle ${dir}`;
h.dataset.corner = dir;
els.cropBox.appendChild(h);
});
}
function getDisplayedImageRect() {
const stage = els.cropperStage.getBoundingClientRect();
const natW = cropperState.naturalWidth || 1;
const natH = cropperState.naturalHeight || 1;
const fit = Math.min(stage.width / natW, stage.height / natH) * cropperState.zoom;
const w = natW * fit;
const h = natH * fit;
const left = stage.left + (stage.width - w) / 2;
const top = stage.top + (stage.height - h) / 2;
return { left, top, width: w, height: h, right: left + w, bottom: top + h };
}
els.cropperApplyBtn.addEventListener("click", async () => {
const note = notes.find((n) => n.id === selectedNoteId);
if (!note) return;
const img = note.images.find((i) => i.id === cropperState.imageId);
if (!img) return;
const stage = getDisplayedImageRect();
const { x, y, size } = cropperState.crop;
const relX = (x - stage.left) / stage.width;
const relY = (y - stage.top) / stage.height;
const relSize = size / stage.width;
const sx = Math.max(
0,
Math.min(cropperState.naturalWidth - 1, relX * cropperState.naturalWidth)
);
const sy = Math.max(
0,
Math.min(cropperState.naturalHeight - 1, relY * cropperState.naturalHeight)
);
const sSize = Math.min(
cropperState.naturalWidth,
cropperState.naturalHeight,
relSize * cropperState.naturalWidth
);
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 1024;
const ctx = canvas.getContext("2d");
ctx.imageSmoothingQuality = "high";
ctx.drawImage(els.cropperImage, sx, sy, sSize, sSize, 0, 0, 1024, 1024);
img.dataUrl = canvas.toDataURL("image/jpeg", 0.92);
img.lastCrop = { relX, relY, relSize };
note.updatedAt = Date.now();
await saveNotes();
closeCropper();
renderAll();
});
els.cropperCloseBtn.addEventListener("click", closeCropper);
els.cropperCancelBtn.addEventListener("click", closeCropper);
// --- IMAGE VIEWER LOGIC ---
function closeImageViewer() {
els.imageViewerModal.setAttribute("aria-hidden", "true");
els.modalViewerImage.src = "";
imageViewerZoom = 1;
els.modalViewerImage.style.transform = 'scale(1)';
}
els.modalViewerCloseBtn.addEventListener("click", closeImageViewer);
els.imageViewerModal.addEventListener("click", (e) => {
if (e.target === els.imageViewerModal) {
closeImageViewer();
}
});
els.imageViewerModal.addEventListener("wheel", (e) => {
e.preventDefault();
const delta = e.deltaY > 0 ? -0.1 : 0.1;
imageViewerZoom = Math.max(0.5, Math.min(imageViewerZoom + delta, 5));
els.modalViewerImage.style.transform = `scale(${imageViewerZoom})`;
}, { passive: false });
// --- PRINT TO PDF ---
els.printBtn.addEventListener("click", () => {
const { ipcRenderer } = require('electron');
const note = notes.find(n => n.id === selectedNoteId);
const partId = note ? note.partId : 'Note';
ipcRenderer.send('print-to-pdf', partId);
});
// --- EXPORT / IMPORT LISTENERS ---
els.exportDataBtn.addEventListener("click", () => {
const { ipcRenderer } = require('electron');
const filename = `${CURRENT_PROFILE_KEY}_notevault.json`;
ipcRenderer.send('export-data', notes, filename);
});
els.importDataBtn.addEventListener("click", () => {
const { ipcRenderer } = require('electron');
ipcRenderer.send('import-data');
});
const { ipcRenderer } = require('electron');
// --- NEW LISTENERS FOR PDF LOADER STATE ---
ipcRenderer.on('pdf-export-started', () => {
const header = document.querySelector('.viewer-header');
if (header) header.classList.add('printing');
});
ipcRenderer.on('pdf-export-complete', () => {
const header = document.querySelector('.viewer-header');
if (header) header.classList.remove('printing');
});
// ----------------------------------------
ipcRenderer.on('data-loaded', async (event, jsonContent) => {
try {
const loadedData = JSON.parse(jsonContent);
if (!Array.isArray(loadedData)) {
showAppAlert("Error", "The selected file does not contain a valid list of notes.");
return;
}
showAppConfirm(
"Import Profile?",
`Found ${loadedData.length} notes in file.\n\nWARNING: This will overwrite ALL notes in the current profile: '${CURRENT_PROFILE_KEY}'.\n\nAre you sure?`,
async () => {
notes = loadedData;
await saveNotes();
selectedNoteId = null;
selectedImageId = null;
renderAll();
showAppAlert("Success", "Your profile has been imported successfully.");
},
true // Danger
);
} catch (e) {
console.error("Import failed:", e);
showAppAlert("Error", "Error parsing file. Is it a valid JSON file?");
}
});
// --- INITIAL LOAD ---
async function loadNotes() {
const notesFromDB = await db.get(CURRENT_PROFILE_KEY);
return Array.isArray(notesFromDB) ? notesFromDB : [];
}
async function saveNotes() {
try {
await db.set(CURRENT_PROFILE_KEY, notes);
} catch (e) {
console.error("Fatal error saving to IndexedDB:", e);
showAppAlert("Database Error", "FATAL ERROR: Could not save notes. " + e.message);
}
}
// --- PROFILE MANAGEMENT LOGIC ---
function updateProfileUI() {
els.currentProfileBtn.textContent = `Profile: ${CURRENT_PROFILE_KEY}`;
}
async function switchProfile(newKey, close = true) {
if (newKey === CURRENT_PROFILE_KEY) {
if (!close) renderProfileList();
return;
}
await saveNotes();
CURRENT_PROFILE_KEY = newKey;
localStorage.setItem('last_profile', newKey);
selectedNoteId = null;
notes = await loadNotes();
renderAll();
updateProfileUI();
if (close) {
closeProfileModal();
} else {
renderProfileList();
els.newProfileInput.value = "";
els.newProfileInput.focus();
}
}
function deleteProfile(keyToDelete) {
if (keyToDelete === CURRENT_PROFILE_KEY) {
showAppAlert("Cannot Delete", "You cannot delete the active profile. Switch to another one first.");
return;
}
showAppConfirm(
"Delete Profile?",
`Are you sure you want to delete profile "${keyToDelete}"? This cannot be undone.`,
async () => {
await db.deleteKey(keyToDelete);
await renderProfileList();
setTimeout(() => {
if (els.newProfileInput) els.newProfileInput.focus();
}, 50);
},
true
);
}
async function createProfile() {
const name = els.newProfileInput.value.trim();
if (!name) return;
const safeName = name.replace(/[^a-z0-9-_ ]/gi, "_");
const keys = await db.getAllKeys();
if (keys.includes(safeName)) {
showAppAlert("Error", "Profile name already exists.");
return;
}
await db.set(safeName, []);
await switchProfile(safeName, false);
}
async function renderProfileList() {
els.profileList.innerHTML = "";
const keys = await db.getAllKeys();
keys.forEach(key => {
if (key === 'default_notes' || key === 'all_notes') {
return;
}
const item = document.createElement('div');
item.className = 'profile-list-item';
const switchBtn = document.createElement('button');
switchBtn.className = `profile-switch-btn ${key === CURRENT_PROFILE_KEY ? 'active' : ''}`;
switchBtn.textContent = key;
switchBtn.onclick = () => switchProfile(key, false);
const delBtn = document.createElement('button');
delBtn.className = 'profile-delete-btn danger';
delBtn.textContent = 'Delete';
delBtn.onclick = () => deleteProfile(key);
if (keys.length === 1) delBtn.disabled = true;
item.appendChild(switchBtn);
item.appendChild(delBtn);
els.profileList.appendChild(item);
});
}
function openProfileModal() {
renderProfileList();
els.profileModal.setAttribute("aria-hidden", "false");
}
function closeProfileModal() {
els.profileModal.setAttribute("aria-hidden", "true");
}
els.currentProfileBtn.addEventListener("click", openProfileModal);
els.profileCloseBtn.addEventListener("click", closeProfileModal);
els.createProfileBtn.addEventListener("click", createProfile);
// --- STANDARD APP LOGIC ---
function generateId(prefix) {
return `${prefix}_${Math.random().toString(36).slice(2, 9)}_${Date.now().toString(36)}`;
}
function ensureSelection() {
const note = notes.find((n) => n.id === selectedNoteId);
if (!note) {
const filterText = els.searchInput.value.toLowerCase().trim();
const filteredNotes = notes.filter(n => {
if (filterText === "") return true;
// CHANGED: .startsWith() for filtering
return n.partId.toLowerCase().startsWith(filterText);
});
selectedNoteId = (filteredNotes.length > 0) ? filteredNotes[0].id : null;
}
}
function createNoteContentView(note) {
const frag = document.createDocumentFragment();
const partId = document.createElement("div");
partId.className = "print-part-id";
partId.textContent = note.partId || "Untitled";
frag.appendChild(partId);
const body = document.createElement("div");
body.className = "note-body";
body.textContent = note.body || "";
frag.appendChild(body);
const imagesWrap = document.createElement("div");
imagesWrap.className = "images";
note.images.forEach((img) => {
const card = document.createElement("div");
card.className = "image-card";
const frame = document.createElement("div");
frame.className = "image-frame";
const image = document.createElement("img");
image.src = img.dataUrl;
frame.appendChild(image);
card.appendChild(frame);
const captionText = (img.caption || "").trim();
if (captionText.length > 0) {
const cap = document.createElement("div");
cap.className = "caption";
cap.textContent = captionText;
card.appendChild(cap);
}
imagesWrap.appendChild(card);
card.addEventListener("click", () => {
els.modalViewerImage.src = img.dataUrl;
els.imageViewerModal.setAttribute("aria-hidden", "false");
});
});
frag.appendChild(imagesWrap);
return frag;
}
function renderNotesList() {
const filterText = els.searchInput.value.toLowerCase().trim();
els.notesList.innerHTML = "";
// Sorting added here
notes
.filter(note => {
if (filterText === "") return true;
// CHANGED: .startsWith() for filtering
return note.partId.toLowerCase().startsWith(filterText);
})
.sort((a, b) => {
const idA = (a.partId || "").toLowerCase();
const idB = (b.partId || "").toLowerCase();
// Use localeCompare for "natural" sort order (so "Part 2" comes before "Part 10")
return idA.localeCompare(idB, undefined, { numeric: true, sensitivity: 'base' });
})
.forEach((note) => {
const clone = els.noteListItemTemplate.content.firstElementChild.cloneNode(true);
const thumb = clone.querySelector(".thumb");
const content = createNoteContentView(note);
const scaleWrapper = document.createElement('div');
scaleWrapper.className = 'thumb-scale-wrap';
scaleWrapper.appendChild(content);
thumb.innerHTML = "";
thumb.appendChild(scaleWrapper);
const title = clone.querySelector(".title");
if (note.id === selectedNoteId) clone.classList.add("active");
els.notesList.appendChild(clone);
if (title) {
title.textContent = note.partId || "Untitled";
requestAnimationFrame(() => {
title.style.fontSize = '14px';
let fontSize = 14;
const containerWidth = title.clientWidth;
let textWidth = title.scrollWidth;
while (textWidth > containerWidth && fontSize > 8) {
fontSize--;
title.style.fontSize = `${fontSize}px`;
textWidth = title.scrollWidth;
}
});
}
clone.addEventListener("click", () => {
selectedNoteId = note.id;
selectedImageId = null;
renderAll();
});
});
}
function renderViewer() {
const note = notes.find((n) => n.id === selectedNoteId);
if (!note) {
els.viewerTitle.textContent = "—";
els.viewer.innerHTML = '<div class="muted">Select or create a note to view.</div>';
return;
}
els.viewerTitle.textContent = note.partId || "Untitled";
const content = createNoteContentView(note);
els.viewer.innerHTML = "";
els.viewer.appendChild(content);
}
function renderEditor() {
const note = notes.find((n) => n.id === selectedNoteId);
const isNew = !note;
els.deleteNoteBtn.disabled = isNew;
if (isNew) {
els.partIdInput.value = "";
els.notesInput.value = "";
els.imagesContainer.innerHTML = "";
return;
}
els.partIdInput.value = note.partId;
els.notesInput.value = note.body;
els.imagesContainer.innerHTML = "";
note.images.forEach((img) => {
const card = document.createElement("div");
card.className = "img-card";
if (img.id === selectedImageId) card.classList.add("active");
const image = document.createElement("img");
image.src = img.dataUrl;
const caption = document.createElement("div");
caption.className = "caption";
caption.textContent = img.caption || "";
const actions = document.createElement("div");
actions.className = "img-actions";
const cropBtn = document.createElement("button");
cropBtn.textContent = "Crop";
cropBtn.type = "button";
const delBtn = document.createElement("button");
delBtn.textContent = "Delete";
delBtn.className = "danger";
delBtn.type = "button";
actions.appendChild(cropBtn);
actions.appendChild(delBtn);
card.appendChild(image);
card.appendChild(actions);
card.appendChild(caption);
card.addEventListener("click", () => {
selectedImageId = img.id;
els.imageCaptionInput.value = img.caption || "";
renderEditor();
});
cropBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
openCropper(img);
});
delBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
removeImage(img.id);
});
els.imagesContainer.appendChild(card);
});
const selectedImg = note.images.find((i) => i.id === selectedImageId);
els.imageCaptionInput.value = selectedImg ? selectedImg.caption || "" : "";
}
function renderAll() {
// Removed sorting to honor natural order
ensureSelection();
renderNotesList();
renderViewer();
renderEditor();
updateProfileUI();
}
async function createNote() {
const newNote = {
id: generateId("note"),
partId: "",
createdAt: Date.now(),
updatedAt: Date.now(),
body: "",
images: [],
};
notes.unshift(newNote);
selectedNoteId = newNote.id;
selectedImageId = null;
await saveNotes();
renderAll();
}
async function saveCurrentNote() {
const note = notes.find((n) => n.id === selectedNoteId);
if (!note) return;
note.partId = els.partIdInput.value.trim() || "Untitled";
note.body = els.notesInput.value;
note.updatedAt = Date.now();
await saveNotes();
renderAll();
}
// --- UPDATED DELETE FUNCTION WITH CONFIRMATION ---
function deleteCurrentNote() {
if (!selectedNoteId) return;
showAppConfirm(
"Delete Note?",
"Are you sure you want to delete this note? This action cannot be undone.",
async () => {
const idx = notes.findIndex((n) => n.id === selectedNoteId);
if (idx >= 0) notes.splice(idx, 1);
selectedNoteId = null;
selectedImageId = null;
await saveNotes();
renderAll();
},
true // Danger mode
);
}
// --- NEW COPY FUNCTION ---
async function copyCurrentNote() {
const originalNote = notes.find(n => n.id === selectedNoteId);
if (!originalNote) return;
// Deep copy images including lastCrop properties
const newImages = originalNote.images.map(img => {
const clone = { ...img, id: generateId("img") };
if (img.lastCrop) clone.lastCrop = { ...img.lastCrop };
return clone;
});