-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
1602 lines (1354 loc) · 49.2 KB
/
renderer.js
File metadata and controls
1602 lines (1354 loc) · 49.2 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
const { ipcRenderer } = require('electron');
const Modal = require('./components/modal');
const Editor = require('./components/editor');
const NoteCard = require('./components/noteCard');
const PasswordCard = require('./components/passwordCard');
const PasswordModal = require('./components/passwordModal');
const PasswordManager = require('./utils/passwordManager');
const ReminderManager = require('./utils/reminder');
// State
let notes = [];
let passwords = [];
let currentNote = null;
let currentPassword = null;
let isCollapsed = true;
let searchQuery = '';
// Components
let modal = new Modal();
let passwordModal = new PasswordModal();
let passwordManager = new PasswordManager();
let editor = null;
let reminderManager = null;
// DOM Elements
const sidebar = document.getElementById('sidebar');
const arrowTab = document.getElementById('arrow-tab');
const searchInput = document.getElementById('search-input');
const notesContainer = document.getElementById('notes-container');
const editorElement = document.getElementById('editor');
const newNoteBtn = document.getElementById('new-note-btn');
// Initialize
async function init() {
// Ensure arrow tab is visible (fix for macOS logout/login issue)
ensureArrowTabVisible();
// Initialize editor
editor = new Editor(editorElement);
editor.onChange = saveCurrentNote;
// Load notes and passwords
await loadNotes();
await loadPasswords();
// Setup event listeners
setupEventListeners();
// Setup IPC listeners
setupIpcListeners();
// Track mouse for click-through
setupMouseTracking();
// Initialize reminder manager with callback
reminderManager = new ReminderManager(checkReminders);
reminderManager.start();
console.log('[Init] ReminderManager initialized and started');
// Check notification permissions
checkNotificationPermissions();
// Open the most recently updated note by default
if (notes.length === 0) {
createNewNote();
} else {
// Sort notes by updated date (most recent first)
const sortedNotes = [...notes].sort((a, b) =>
new Date(b.updated) - new Date(a.updated)
);
openNote(sortedNotes[0]);
}
}
async function checkNotificationPermissions() {
const isSupported = await ipcRenderer.invoke('check-notification-permission');
if (!isSupported) {
console.warn('Notifications are not supported on this system');
}
}
function setupEventListeners() {
// Arrow tab toggle
arrowTab.addEventListener('click', toggleSidebar);
// Search
searchInput.addEventListener('input', handleSearch);
// New note button
newNoteBtn.addEventListener('click', createNewNote);
// New password button
const newPasswordBtn = document.getElementById('new-password-btn');
if (newPasswordBtn) {
newPasswordBtn.addEventListener('click', async () => {
const result = await passwordModal.show();
if (result && result.action === 'create') {
await passwordManager.createPassword(result.data);
await loadPasswords();
showMessage('Password created', 'success');
}
});
}
// Tab switching
const tabs = document.querySelectorAll('.sidebar-tab');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const tabName = tab.dataset.tab;
switchTab(tabName);
});
});
// Toolbar buttons
document.getElementById('btn-bold').addEventListener('click', () => {
if (editor) editor.execCommand('bold');
});
document.getElementById('btn-italic').addEventListener('click', () => {
if (editor) editor.execCommand('italic');
});
document.getElementById('btn-underline').addEventListener('click', () => {
if (editor) editor.execCommand('underline');
});
// Setup all dropdowns
setupAllDropdowns();
// Image upload
document.getElementById('btn-image').addEventListener('click', () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = async (e) => {
const file = e.target.files[0];
if (file) {
await editor.insertImage(file);
saveCurrentNote();
}
};
input.click();
});
// Color picker
document.getElementById('btn-color').addEventListener('click', showColorPicker);
// Reminder button
document.getElementById('btn-reminder').addEventListener('click', () => {
if (currentNote) {
showReminderModal(currentNote);
}
});
// Password field button
document.getElementById('btn-password').addEventListener('click', () => {
if (currentNote) {
showPasswordModal();
}
});
// Import markdown
document.getElementById('btn-import-md').addEventListener('click', importMarkdown);
// Drag and drop for images
editorElement.addEventListener('dragover', (e) => {
e.preventDefault();
});
editorElement.addEventListener('drop', async (e) => {
e.preventDefault();
const files = Array.from(e.dataTransfer.files);
for (const file of files) {
if (file.type.startsWith('image/')) {
await editor.insertImage(file);
}
}
saveCurrentNote();
});
}
function setupIpcListeners() {
ipcRenderer.on('init-settings', (event, settings) => {
applyTheme(settings.theme);
});
ipcRenderer.on('theme-changed', (event, theme) => {
applyTheme(theme);
});
ipcRenderer.on('new-note', () => {
createNewNote();
});
ipcRenderer.on('reload-notes', async () => {
await loadNotes();
renderNotes();
});
ipcRenderer.on('show-message', (event, { type, message }) => {
showMessage(message, type);
});
ipcRenderer.on('collapse-sidebar', () => {
if (!isCollapsed) {
toggleSidebar();
}
});
ipcRenderer.on('expand-sidebar', () => {
if (isCollapsed) {
toggleSidebar();
}
});
ipcRenderer.on('open-note', (event, noteId) => {
const note = notes.find(n => n.id === noteId);
if (note) {
if (isCollapsed) {
toggleSidebar();
}
openNote(note);
}
});
ipcRenderer.on('check-reminders', () => {
// Don't reload notes - use current in-memory notes to avoid race conditions
checkReminders();
});
ipcRenderer.on('show-update-notes', (event, updateInfo) => {
showUpdateNotesModal(updateInfo);
});
}
function ensureArrowTabVisible() {
// Explicitly ensure the arrow tab is visible and properly styled
// This fixes an issue where the arrow tab disappears after macOS logout/login
if (arrowTab) {
arrowTab.style.display = 'flex';
arrowTab.style.position = 'fixed';
arrowTab.style.left = '0';
arrowTab.style.zIndex = '1000';
// Ensure the arrow icon is visible
const arrowIcon = document.getElementById('arrow-icon');
if (arrowIcon) {
arrowIcon.style.display = 'block';
}
console.log('Arrow tab visibility ensured');
}
}
function setupMouseTracking() {
document.addEventListener('mousemove', (e) => {
if (isCollapsed) {
// When collapsed, the window is only 30px wide, so any mouse movement is in the arrow tab
ipcRenderer.send('set-ignore-mouse', false);
} else {
// When expanded, don't ignore mouse events
ipcRenderer.send('set-ignore-mouse', false);
}
});
}
function toggleSidebar() {
isCollapsed = !isCollapsed;
if (isCollapsed) {
sidebar.classList.remove('expanded');
sidebar.classList.add('collapsed');
arrowTab.classList.remove('expanded');
// Collapsed: 30px width, 80px height (arrow tab size)
ipcRenderer.send('resize-window', { width: 30, height: 80 });
} else {
sidebar.classList.remove('collapsed');
sidebar.classList.add('expanded');
arrowTab.classList.add('expanded');
// Expanded: 800px width, 80% of screen height
const screenHeight = window.screen.availHeight;
const windowHeight = Math.floor(screenHeight * 0.8);
ipcRenderer.send('resize-window', { width: 800, height: windowHeight });
}
ipcRenderer.send('set-collapsed', isCollapsed);
}
async function loadNotes() {
notes = await ipcRenderer.invoke('get-notes');
renderNotes();
}
async function loadPasswords() {
passwords = await passwordManager.loadPasswords();
renderPasswords();
}
function renderPasswords() {
const passwordsContainer = document.getElementById('passwords-container');
const passwordsCount = document.getElementById('passwords-count');
if (!passwordsContainer || !passwordsCount) return;
passwordsContainer.innerHTML = '';
passwordsCount.textContent = passwords.length;
if (passwords.length === 0) {
const empty = document.createElement('div');
empty.className = 'empty-state';
empty.style.padding = 'var(--spacing-md)';
empty.innerHTML = `
<div class="empty-state-icon" style="font-size: 32px;">🔐</div>
<div class="empty-state-text">No passwords yet</div>
`;
passwordsContainer.appendChild(empty);
return;
}
passwords.forEach(password => {
const passwordCard = new PasswordCard(password, {
onClick: openPassword,
onDelete: deletePassword,
onToggleFavorite: togglePasswordFavorite,
isActive: currentPassword && currentPassword.id === password.id
});
passwordsContainer.appendChild(passwordCard.render());
});
}
async function openPassword(password) {
currentPassword = password;
renderPasswords();
const result = await passwordModal.show(password);
if (result) {
if (result.action === 'delete') {
await deletePassword(password);
} else if (result.action === 'update') {
await passwordManager.updatePassword(result.data);
await loadPasswords();
}
}
currentPassword = null;
renderPasswords();
}
async function deletePassword(password) {
if (confirm('Delete this password? This action cannot be undone.')) {
await passwordManager.deletePassword(password.id);
await loadPasswords();
showMessage('Password deleted', 'success');
}
}
async function togglePasswordFavorite(password) {
password.isFavorite = !password.isFavorite;
await passwordManager.updatePassword(password);
await loadPasswords();
}
async function saveNotes() {
await ipcRenderer.invoke('save-notes', notes);
}
function switchTab(tabName) {
// Update tab buttons
document.querySelectorAll('.sidebar-tab').forEach(tab => {
if (tab.dataset.tab === tabName) {
tab.classList.add('active');
} else {
tab.classList.remove('active');
}
});
// Update tab content
document.querySelectorAll('.tab-content').forEach(content => {
if (content.dataset.content === tabName) {
content.classList.add('active');
} else {
content.classList.remove('active');
}
});
}
function renderNotes() {
notesContainer.innerHTML = '';
// Update notes count
const notesCount = document.getElementById('notes-count');
if (notesCount) {
notesCount.textContent = notes.length;
}
let filteredNotes = notes;
if (searchQuery) {
filteredNotes = notes.filter(note => {
const content = note.content.replace(/<[^>]*>/g, '').toLowerCase();
return content.includes(searchQuery.toLowerCase());
});
}
// Sort notes: favorites first, then by updated date
filteredNotes.sort((a, b) => {
// If one is favorite and the other isn't, favorite comes first
if (a.isFavorite && !b.isFavorite) return -1;
if (!a.isFavorite && b.isFavorite) return 1;
// If both are favorites or both are not, maintain current order
// (order is already set by user's drag and drop)
return 0;
});
if (filteredNotes.length === 0) {
const empty = document.createElement('div');
empty.className = 'empty-state';
empty.innerHTML = `
<div class="empty-state-icon">📝</div>
<div class="empty-state-text">${searchQuery ? 'No notes found' : 'No notes yet'}</div>
`;
notesContainer.appendChild(empty);
return;
}
filteredNotes.forEach(note => {
const noteCard = new NoteCard(note, {
onClick: openNote,
onDelete: deleteNote,
onSetReminder: showReminderModal,
onReorder: reorderNotes,
onToggleFavorite: toggleNoteFavorite,
isActive: currentNote && currentNote.id === note.id
});
notesContainer.appendChild(noteCard.render());
});
}
function toggleNoteFavorite(note) {
note.isFavorite = !note.isFavorite;
saveNotes();
renderNotes();
}
function reorderNotes(draggedNoteId, targetNoteId, insertBefore) {
// Find the indices of the dragged and target notes
const draggedIndex = notes.findIndex(n => n.id === draggedNoteId);
const targetIndex = notes.findIndex(n => n.id === targetNoteId);
if (draggedIndex === -1 || targetIndex === -1) return;
const draggedNote = notes[draggedIndex];
const targetNote = notes[targetIndex];
// Prevent moving non-favorite notes above favorite notes
// and favorite notes below non-favorite notes
if (draggedNote.isFavorite && !targetNote.isFavorite) {
// Can't move favorite below non-favorite
if (!insertBefore) return;
}
if (!draggedNote.isFavorite && targetNote.isFavorite) {
// Can't move non-favorite above favorite
if (insertBefore) return;
}
// Remove the dragged note from its current position
notes.splice(draggedIndex, 1);
// Calculate the new index
let newIndex = notes.findIndex(n => n.id === targetNoteId);
// Insert at the appropriate position
if (insertBefore) {
notes.splice(newIndex, 0, draggedNote);
} else {
notes.splice(newIndex + 1, 0, draggedNote);
}
// Save and re-render
saveNotes();
renderNotes();
}
function createNewNote() {
const note = {
id: Date.now().toString(),
content: '',
backgroundColor: null,
created: new Date().toISOString(),
updated: new Date().toISOString(),
reminders: []
};
notes.unshift(note);
saveNotes();
openNote(note);
renderNotes();
if (isCollapsed) {
toggleSidebar();
}
}
function openNote(note) {
currentNote = note;
editor.setContent(note.content);
renderNotes();
// Apply background color to editor
if (note.backgroundColor) {
editorElement.style.backgroundColor = note.backgroundColor;
// Calculate brightness from rgba color
const rgb = rgbaToRgb(note.backgroundColor);
const brightness = (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
// Use dark text for light backgrounds, light text for dark backgrounds
const textColor = brightness > 180 ? '#1a1a1a' : '#e0e0e0';
const linkColor = brightness > 180 ? '#0066cc' : '#66b3ff';
editorElement.style.color = textColor;
// Update link colors
editorElement.querySelectorAll('a').forEach(link => {
link.style.color = linkColor;
});
// Add style for future links
let styleId = 'editor-link-style';
let existingStyle = document.getElementById(styleId);
if (existingStyle) {
existingStyle.remove();
}
const style = document.createElement('style');
style.id = styleId;
style.textContent = `
#editor a {
color: ${linkColor} !important;
}
#editor a:hover {
color: ${brightness > 180 ? '#0052a3' : '#88ccff'} !important;
}
`;
document.head.appendChild(style);
} else {
editorElement.style.backgroundColor = '';
editorElement.style.color = '';
// Remove custom link style
let styleId = 'editor-link-style';
let existingStyle = document.getElementById(styleId);
if (existingStyle) {
existingStyle.remove();
}
}
}
function saveCurrentNote() {
if (!currentNote) return;
currentNote.content = editor.getContent();
currentNote.updated = new Date().toISOString();
saveNotes();
renderNotes();
}
function deleteNote(note) {
if (confirm('Delete this note?')) {
notes = notes.filter(n => n.id !== note.id);
saveNotes();
if (currentNote && currentNote.id === note.id) {
if (notes.length > 0) {
openNote(notes[0]);
} else {
currentNote = null;
editor.clear();
}
}
renderNotes();
}
}
function handleSearch(e) {
searchQuery = e.target.value;
renderNotes();
}
function setupAllDropdowns() {
// Store the selection when dropdown button is clicked
let savedSelection = null;
const dropdowns = [
{
buttonId: 'heading-dropdown',
items: {
'H1': () => {
if (editor) editor.insertHeading(1);
},
'H2': () => {
if (editor) editor.insertHeading(2);
},
'H3': () => {
if (editor) editor.insertHeading(3);
}
}
},
{
buttonId: 'insert-dropdown',
items: {
'Code': () => {
if (editor) editor.insertCode();
},
'Code Block': () => {
if (editor) editor.insertCodeBlock();
},
'Blockquote': () => {
if (editor) editor.insertBlockquote();
},
'Link': () => {
if (editor) editor.insertLink();
},
'Table': () => {
if (editor) editor.insertTable();
}
}
},
{
buttonId: 'list-dropdown',
items: {
'Bullet List': () => {
if (editor) editor.insertList('bullet');
},
'Numbered List': () => {
if (editor) editor.insertList('numbered');
},
'Task List': () => {
if (editor) editor.insertTaskList();
}
}
}
];
// Setup each dropdown
dropdowns.forEach(({ buttonId, items }) => {
const button = document.getElementById(buttonId);
if (!button) {
console.error('Button not found:', buttonId);
return;
}
const dropdown = button.nextElementSibling;
if (!dropdown) {
console.error('Dropdown not found for button:', buttonId);
return;
}
// Clear any existing items
dropdown.innerHTML = '';
// Populate dropdown items
Object.entries(items).forEach(([label, action]) => {
const item = document.createElement('div');
item.className = 'dropdown-item';
item.textContent = label;
// Use mousedown instead of click to preserve selection
item.addEventListener('mousedown', (e) => {
e.preventDefault(); // Prevent losing focus
e.stopPropagation();
console.log('Dropdown item clicked:', label);
// Restore the saved selection before executing action
if (savedSelection) {
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(savedSelection);
}
// Execute the action
action();
// Close dropdown
dropdown.classList.add('hidden');
// Clear saved selection
savedSelection = null;
});
dropdown.appendChild(item);
});
// Button click handler
button.addEventListener('mousedown', (e) => {
e.preventDefault(); // Prevent losing focus
e.stopPropagation();
console.log('Dropdown button clicked:', buttonId);
// Save current selection
const selection = window.getSelection();
if (selection.rangeCount > 0) {
savedSelection = selection.getRangeAt(0).cloneRange();
console.log('Selection saved:', savedSelection.toString());
}
// Close all other dropdowns
document.querySelectorAll('.dropdown-menu').forEach(d => {
if (d !== dropdown) {
d.classList.add('hidden');
}
});
// Toggle this dropdown
dropdown.classList.toggle('hidden');
console.log('Dropdown hidden state:', dropdown.classList.contains('hidden'));
});
});
// Single document-level click handler to close all dropdowns
document.addEventListener('click', (e) => {
// Check if click is outside all dropdowns
const clickedInsideDropdown = e.target.closest('.dropdown');
if (!clickedInsideDropdown) {
document.querySelectorAll('.dropdown-menu').forEach(d => {
d.classList.add('hidden');
});
savedSelection = null;
}
});
}
function showColorPicker() {
const colors = [
'rgba(255, 182, 193, 1)', // Light Pink - brighter
'rgba(255, 218, 185, 1)', // Peach - brighter
'rgba(255, 253, 208, 1)', // Cream - brighter
'rgba(221, 255, 221, 1)', // Mint - brighter
'rgba(173, 216, 230, 1)', // Light Blue - brighter
'rgba(221, 160, 221, 1)', // Plum - brighter
'rgba(255, 228, 196, 1)', // Bisque - brighter
'rgba(176, 224, 230, 1)', // Powder Blue - brighter
'rgba(255, 192, 203, 1)', // Pink - brighter
'rgba(230, 230, 250, 1)', // Lavender - brighter
'rgba(240, 255, 240, 1)', // Honeydew - brighter
'rgba(255, 240, 245, 1)' // Lavender Blush - brighter
];
const content = document.createElement('div');
content.className = 'color-picker-container';
colors.forEach(color => {
const option = document.createElement('div');
option.className = 'color-option';
option.style.backgroundColor = color;
if (currentNote && currentNote.backgroundColor === color) {
option.classList.add('active');
}
option.addEventListener('click', () => {
if (currentNote) {
currentNote.backgroundColor = color;
saveCurrentNote();
openNote(currentNote);
modal.close();
}
});
content.appendChild(option);
});
// Add clear option
const clearOption = document.createElement('div');
clearOption.className = 'color-option';
clearOption.style.backgroundColor = 'transparent';
clearOption.style.border = '2px dashed var(--border-color)';
clearOption.textContent = '✕';
clearOption.style.display = 'flex';
clearOption.style.alignItems = 'center';
clearOption.style.justifyContent = 'center';
clearOption.addEventListener('click', () => {
if (currentNote) {
currentNote.backgroundColor = null;
saveCurrentNote();
openNote(currentNote);
modal.close();
}
});
content.appendChild(clearOption);
modal.create('Choose Background Color', content);
}
function showPasswordModal() {
const PasswordField = require('./components/passwordField');
const content = document.createElement('div');
content.style.maxWidth = '500px';
const form = document.createElement('form');
form.innerHTML = `
<div class="form-group">
<label class="form-label">Label *</label>
<input type="text" id="pwd-label" class="input" placeholder="e.g., Gmail Account" required>
</div>
<div class="form-group">
<label class="form-label">Username/Email</label>
<input type="text" id="pwd-username" class="input" placeholder="username@example.com">
</div>
<div class="form-group">
<label class="form-label">Password *</label>
<div style="display: flex; gap: 8px;">
<input type="password" id="pwd-password" class="input" placeholder="Enter password" required style="flex: 1;">
<button type="button" id="toggle-pwd-visibility" class="btn" style="padding: 8px 12px;">👁️</button>
<button type="button" id="generate-pwd" class="btn" style="padding: 8px 12px;">🎲</button>
</div>
<div id="password-strength" style="margin-top: 8px; font-size: 12px;"></div>
</div>
<div class="form-group">
<label class="form-label">Description</label>
<textarea id="pwd-description" class="input" placeholder="Optional notes about this password" rows="2"></textarea>
</div>
<div style="display: flex; gap: 10px;">
<button type="submit" class="btn btn-primary" style="flex: 1;">Add Password Field</button>
<button type="button" id="cancel-pwd" class="btn" style="padding: 8px 16px;">Cancel</button>
</div>
`;
const passwordInput = form.querySelector('#pwd-password');
const toggleBtn = form.querySelector('#toggle-pwd-visibility');
const generateBtn = form.querySelector('#generate-pwd');
const strengthDiv = form.querySelector('#password-strength');
const cancelBtn = form.querySelector('#cancel-pwd');
// Toggle password visibility
toggleBtn.addEventListener('click', () => {
if (passwordInput.type === 'password') {
passwordInput.type = 'text';
toggleBtn.textContent = '👁️🗨️';
} else {
passwordInput.type = 'password';
toggleBtn.textContent = '👁️';
}
});
// Generate password
generateBtn.addEventListener('click', async () => {
const result = await ipcRenderer.invoke('generate-password', 16, {
uppercase: true,
lowercase: true,
numbers: true,
symbols: true
});
if (result.success) {
passwordInput.value = result.password;
passwordInput.type = 'text';
toggleBtn.textContent = '👁️🗨️';
updatePasswordStrength(result.password);
}
});
// Password strength indicator
function updatePasswordStrength(password) {
if (!password) {
strengthDiv.textContent = '';
strengthDiv.style.color = '';
return;
}
let strength = 0;
let feedback = [];
// Length check
if (password.length >= 12) strength += 2;
else if (password.length >= 8) strength += 1;
else feedback.push('Use at least 8 characters');
// Character variety
if (/[a-z]/.test(password)) strength += 1;
if (/[A-Z]/.test(password)) strength += 1;
if (/[0-9]/.test(password)) strength += 1;
if (/[^a-zA-Z0-9]/.test(password)) strength += 1;
if (!/[a-z]/.test(password)) feedback.push('Add lowercase letters');
if (!/[A-Z]/.test(password)) feedback.push('Add uppercase letters');
if (!/[0-9]/.test(password)) feedback.push('Add numbers');
if (!/[^a-zA-Z0-9]/.test(password)) feedback.push('Add symbols');
let strengthText = '';
let color = '';
if (strength >= 5) {
strengthText = '🟢 Strong password';
color = '#4caf50';
} else if (strength >= 3) {
strengthText = '🟡 Moderate password';
color = '#ff9800';
} else {
strengthText = '🔴 Weak password';
color = '#f44336';
}
if (feedback.length > 0) {
strengthText += ' - ' + feedback.join(', ');
}
strengthDiv.textContent = strengthText;
strengthDiv.style.color = color;
}
passwordInput.addEventListener('input', (e) => {
updatePasswordStrength(e.target.value);
});
cancelBtn.addEventListener('click', () => {
modal.close();
});
form.onsubmit = async (e) => {
e.preventDefault();
const passwordData = {
label: form.querySelector('#pwd-label').value,
username: form.querySelector('#pwd-username').value,
password: form.querySelector('#pwd-password').value,
description: form.querySelector('#pwd-description').value
};
try {
const passwordField = new PasswordField(passwordData);
const passwordElement = passwordField.render();
// Insert into editor
const selection = window.getSelection();
const range = selection.getRangeCount > 0 ? selection.getRangeAt(0) : null;
if (range) {
range.deleteContents();
range.insertNode(passwordElement);
// Move cursor after the password field
const newRange = document.createRange();
newRange.setStartAfter(passwordElement);
newRange.collapse(true);
selection.removeAllRanges();
selection.addRange(newRange);
} else {
editorElement.appendChild(passwordElement);
}
// Save the note
saveCurrentNote();
modal.close();
showMessage('Password field added (will be encrypted on save)', 'success');
} catch (error) {
console.error('Error adding password field:', error);
showMessage('Failed to add password field', 'error');
}
};
content.appendChild(form);
modal.create('Add Password Field', content);
// Focus the label input
setTimeout(() => {
form.querySelector('#pwd-label').focus();
}, 100);
}
function showReminderModal(note) {
const content = document.createElement('div');
// Show current date/time at the top
const currentDateTime = document.createElement('div');
currentDateTime.style.padding = '10px';
currentDateTime.style.backgroundColor = 'var(--bg-secondary)';
currentDateTime.style.borderRadius = '4px';
currentDateTime.style.marginBottom = '20px';
currentDateTime.style.fontSize = '14px';
currentDateTime.style.color = 'var(--text-secondary)';
const now = new Date();
const dateStr = now.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
const timeStr = now.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
second: '2-digit'
});
currentDateTime.innerHTML = `
<div style="font-weight: 500; margin-bottom: 4px;">Current Date & Time</div>