-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch-renderer.js
More file actions
706 lines (596 loc) · 21.4 KB
/
Copy pathsearch-renderer.js
File metadata and controls
706 lines (596 loc) · 21.4 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
const { ipcRenderer, clipboard } = require('electron');
const PasswordManager = require('./utils/passwordManager');
const ClipManager = require('./utils/clipManager');
const { TEMPLATES } = require('./utils/noteTemplates');
const { extractTags } = require('./utils/noteTags');
const { fuzzyScore } = require('./utils/fuzzy');
const { escapeHtml } = require('./utils/sanitize');
const { copySecret } = require('./utils/secureClipboard');
// State
let notes = [];
let passwords = [];
let clips = [];
let filteredResults = []; // Combined notes, passwords and clips
let selectedIndex = -1;
let passwordManager = new PasswordManager();
let clipManager = new ClipManager();
// DOM Elements
const searchInput = document.getElementById('search-input');
const resultsContainer = document.getElementById('results-container');
// Initialize
async function init() {
await applyAppTheme();
await loadNotes();
await loadPasswords();
await loadClips();
setupEventListeners();
}
// The search window reuses the app theme (Dark/Light/Paper) instead of being
// hardcoded dark — jarring when the rest of the app is in Light/Paper.
async function applyAppTheme() {
try {
const settings = await ipcRenderer.invoke('get-settings');
const theme = (settings && settings.theme) || 'dark';
document.body.classList.toggle('light-theme', theme === 'light');
document.body.classList.toggle('paper-theme', theme === 'paper');
} catch (error) {
console.error('Failed to load theme for search window:', error);
}
}
async function loadNotes() {
notes = await ipcRenderer.invoke('get-notes');
}
async function loadPasswords() {
passwords = await passwordManager.loadPasswords();
}
async function loadClips() {
clips = await clipManager.loadClips();
}
function setupEventListeners() {
// Search input
searchInput.addEventListener('input', handleSearch);
// Keyboard navigation
searchInput.addEventListener('keydown', handleKeyDown);
// Escape should close the window regardless of what has focus (e.g. after
// clicking a result item moved focus away from the input), not just when
// the search input itself is focused.
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeWindow();
}
});
// IPC listeners
ipcRenderer.on('focus-search', async () => {
// The search window is created once and reused (shown/hidden), so
// refresh data on every reopen or newly created notes/passwords/clips
// would stay invisible until the app was restarted. Theme too — it may
// have changed since the window was created.
await applyAppTheme();
await loadNotes();
await loadPasswords();
await loadClips();
searchInput.focus();
searchInput.select();
});
}
function handleSearch(e) {
const query = e.target.value.trim();
if (!query) {
showEmptyState();
return;
}
const lowerQuery = query.toLowerCase();
// ":n" creates a blank note immediately; ":t" instead lists templates to
// pick from (handled like any other result set, so arrow keys/Enter work).
if (lowerQuery === ':n') {
ipcRenderer.send('create-note-from-search');
closeWindow();
return;
}
if (lowerQuery === ':t') {
showTemplatePicker();
return;
}
// "tag:xyz" / "title:xyz" filter notes only, bypassing the general
// title-or-content search below.
const tagOperator = query.match(/^tag:(\S+)/i);
if (tagOperator) {
const tag = tagOperator[1].toLowerCase();
filteredResults = notes
.filter(note => extractTags(note.content).includes(tag))
.map(note => ({ type: 'note', data: note, titleMatch: true }));
sortResults(filteredResults);
selectedIndex = filteredResults.length > 0 ? 0 : -1;
renderResults(query);
return;
}
const titleOperator = query.match(/^title:(.+)/i);
if (titleOperator) {
const titleQuery = titleOperator[1].trim().toLowerCase();
filteredResults = notes
.filter(note => (note.title || '').toLowerCase().includes(titleQuery))
.map(note => ({ type: 'note', data: note, titleMatch: true }));
sortResults(filteredResults);
selectedIndex = filteredResults.length > 0 ? 0 : -1;
renderResults(query);
return;
}
// Match notes on title OR content. Track titleMatch so title hits rank first.
const matchedNotes = notes.reduce((acc, note) => {
const title = (note.title || '').toLowerCase();
const content = stripHtml(note.content).toLowerCase();
const titleMatch = title.includes(lowerQuery);
const contentMatch = content.includes(lowerQuery);
if (titleMatch || contentMatch) {
acc.push({ type: 'note', data: note, titleMatch });
}
return acc;
}, []);
const matchedPasswords = passwords.filter(password => {
const label = (password.label || '').toLowerCase();
return label.includes(lowerQuery);
}).map(password => ({ type: 'password', data: password, titleMatch: true }));
const matchedClips = clips.filter(clip => {
return clip.text.toLowerCase().includes(lowerQuery);
}).map(clip => ({ type: 'clip', data: clip, titleMatch: false }));
const matchedLinks = notes.flatMap(extractLinksFromNote)
.filter(link => link.label.toLowerCase().includes(lowerQuery))
.map(link => ({ type: 'link', data: link, titleMatch: true }));
filteredResults = [...matchedLinks, ...matchedNotes, ...matchedPasswords, ...matchedClips];
// Fuzzy fallback: when plain substring matching finds nothing, try
// subsequence matching ("wr" → "Weekly Review") before giving up.
if (filteredResults.length === 0) {
const fuzzyNotes = notes
.map(note => ({
type: 'note',
data: note,
titleMatch: true,
score: Math.max(
fuzzyScore(lowerQuery, note.title || ''),
fuzzyScore(lowerQuery, stripHtml(note.content)) * 0.5
)
}))
.filter(r => r.score > 0);
const fuzzyPasswords = passwords
.map(p => ({ type: 'password', data: p, titleMatch: true, score: fuzzyScore(lowerQuery, p.label || '') }))
.filter(r => r.score > 0);
const fuzzyClips = clips
.map(c => ({ type: 'clip', data: c, titleMatch: false, score: fuzzyScore(lowerQuery, c.text) }))
.filter(r => r.score > 0);
filteredResults = [...fuzzyNotes, ...fuzzyPasswords, ...fuzzyClips];
filteredResults.sort((a, b) => b.score - a.score);
}
sortResults(filteredResults);
selectedIndex = filteredResults.length > 0 ? 0 : -1;
renderResults(query);
}
// Sort: pinned first, then favorites, then title matches above content
// matches, then recency. Passwords/clips/links have no isPinned/isFavorite,
// so they naturally fall after any matching pinned/favorite notes.
function sortResults(results) {
results.sort((a, b) => {
// Fuzzy-scored results rank purely by match quality.
if (a.score != null && b.score != null && a.score !== b.score) {
return b.score - a.score;
}
const aPin = a.data.isPinned || false;
const bPin = b.data.isPinned || false;
if (aPin && !bPin) return -1;
if (!aPin && bPin) return 1;
const aFav = a.data.isFavorite || false;
const bFav = b.data.isFavorite || false;
if (aFav && !bFav) return -1;
if (!aFav && bFav) return 1;
if (a.titleMatch && !b.titleMatch) return -1;
if (!a.titleMatch && b.titleMatch) return 1;
const aDate = new Date(a.data.updated || a.data.created);
const bDate = new Date(b.data.updated || b.data.created);
return bDate - aDate;
});
}
function handleKeyDown(e) {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
if (filteredResults.length > 0) {
selectedIndex = (selectedIndex + 1) % filteredResults.length;
updateSelection();
}
break;
case 'ArrowUp':
e.preventDefault();
if (filteredResults.length > 0) {
selectedIndex = selectedIndex <= 0 ? filteredResults.length - 1 : selectedIndex - 1;
updateSelection();
}
break;
case 'Enter':
e.preventDefault();
if (selectedIndex >= 0 && filteredResults[selectedIndex]) {
handleResultAction(filteredResults[selectedIndex]);
}
break;
}
}
function renderResults(query) {
resultsContainer.innerHTML = '';
if (filteredResults.length === 0) {
const emptyState = document.createElement('div');
emptyState.className = 'empty-state';
emptyState.innerHTML = `
<div class="empty-state-icon">🔍</div>
<div class="empty-state-text">No results found</div>
`;
resultsContainer.appendChild(emptyState);
return;
}
filteredResults.forEach((result, index) => {
let resultItem;
if (result.type === 'note') {
resultItem = createNoteResultItem(result.data, query, index === selectedIndex);
} else if (result.type === 'password') {
resultItem = createPasswordResultItem(result.data, query, index === selectedIndex);
} else if (result.type === 'link') {
resultItem = createLinkResultItem(result.data, query, index === selectedIndex, index);
} else {
resultItem = createClipResultItem(result.data, query, index === selectedIndex);
}
resultsContainer.appendChild(resultItem);
});
}
function handleResultAction(result) {
if (result.type === 'note') {
openNote(result.data.id);
} else if (result.type === 'password') {
// For passwords, copy to clipboard
copyPassword(result.data);
} else if (result.type === 'clip') {
copyClip(result.data);
} else if (result.type === 'link') {
copyLink(result.data);
} else if (result.type === 'template') {
useTemplate(result.data.id);
}
}
function showTemplatePicker() {
resultsContainer.innerHTML = '';
const header = document.createElement('div');
header.className = 'results-section-header';
header.textContent = 'New note from template';
resultsContainer.appendChild(header);
filteredResults = TEMPLATES.map(t => ({ type: 'template', data: t, titleMatch: true }));
selectedIndex = 0;
filteredResults.forEach((result, index) => {
resultsContainer.appendChild(createTemplateResultItem(result.data, index === selectedIndex));
});
}
function createTemplateResultItem(template, isSelected) {
const item = document.createElement('div');
item.className = 'result-item';
if (isSelected) {
item.classList.add('selected');
}
item.innerHTML = `
<div class="result-icon">${template.icon}</div>
<div class="result-details">
<div class="result-title">${template.label}</div>
<div class="result-subtitle">Create a new note from this template</div>
</div>
`;
item.addEventListener('click', () => useTemplate(template.id));
item.addEventListener('mouseenter', () => {
selectedIndex = filteredResults.findIndex(r => r.type === 'template' && r.data.id === template.id);
updateSelection();
});
return item;
}
function useTemplate(templateId) {
ipcRenderer.send('create-note-from-template', templateId);
closeWindow();
}
function copyClip(clip) {
clipboard.writeText(clip.text);
showToast('Copied to clipboard');
setTimeout(() => closeWindow(), 500);
}
function copyLink(link) {
clipboard.writeText(link.url);
showToast('Link copied to clipboard');
setTimeout(() => closeWindow(), 500);
}
function createLinkResultItem(link, query, isSelected, index) {
const item = document.createElement('div');
item.className = 'result-item';
if (isSelected) {
item.classList.add('selected');
}
const label = highlightText(link.label, query);
item.innerHTML = `
<div class="result-icon">🔗</div>
<div class="result-details">
<div class="result-title">${label}</div>
<div class="result-subtitle">${escapeHtml(link.url)} — ${escapeHtml(link.noteTitle)}</div>
</div>
<button class="copy-password-btn" title="Copy link">📋</button>
`;
const copyBtn = item.querySelector('.copy-password-btn');
copyBtn.addEventListener('click', (e) => {
e.stopPropagation();
copyLink(link);
});
item.addEventListener('click', () => copyLink(link));
item.addEventListener('mouseenter', () => {
selectedIndex = index;
updateSelection();
});
return item;
}
async function copyPassword(password) {
try {
const result = await passwordManager.getDecryptedPassword(password.id);
if (result.success && result.data.password) {
await copySecret(result.data.password);
showToast('Password copied — clipboard clears in 30s');
// Close window after a brief delay
setTimeout(() => closeWindow(), 500);
} else {
showToast('Failed to decrypt password', 'error');
}
} catch (error) {
console.error('Error copying password:', error);
showToast('Failed to copy password', 'error');
}
}
function createNoteResultItem(note, query, isSelected) {
const item = document.createElement('div');
item.className = 'result-item';
if (isSelected) {
item.classList.add('selected');
}
const rawTitle = (note.title || '').trim() || 'Untitled';
// highlightText escapes even without a query — never insert rawTitle raw.
const title = highlightText(rawTitle, query);
let snippet = stripHtml(note.content).replace(/\s+/g, ' ').trim();
if (snippet.length > 120) snippet = snippet.substring(0, 120) + '…';
if (query && snippet) snippet = highlightText(snippet, query);
let icon = '📝';
if (note.isFavorite) {
icon = '⭐';
} else if (note.reminders && note.reminders.some(r => r.enabled)) {
icon = '🔔';
}
item.innerHTML = `
<div class="result-icon">${icon}</div>
<div class="result-details">
<div class="result-title">${title}</div>
${snippet ? `<div class="result-subtitle">${snippet}</div>` : ''}
</div>
`;
// Click handler
item.addEventListener('click', () => {
openNote(note.id);
});
// Hover handler
item.addEventListener('mouseenter', () => {
selectedIndex = filteredResults.findIndex(r => r.type === 'note' && r.data.id === note.id);
updateSelection();
});
return item;
}
function createPasswordResultItem(password, query, isSelected) {
const item = document.createElement('div');
item.className = 'result-item password-result';
if (isSelected) {
item.classList.add('selected');
}
// Get label (highlightText escapes even without a query)
const label = highlightText(password.label || 'Untitled Password', query);
// Build icon
const icon = password.isFavorite ? '⭐' : '🔐';
// Subtitle - show username if available (escaped — user-controlled text)
let subtitle = '';
if (password.username) {
subtitle = `<div class="result-subtitle">${escapeHtml(password.username)}</div>`;
}
item.innerHTML = `
<div class="result-icon">${icon}</div>
<div class="result-details">
<div class="result-title">${label}</div>
${subtitle}
</div>
<button class="copy-password-btn" title="Copy password">📋</button>
`;
const copyBtn = item.querySelector('.copy-password-btn');
// Click handler for copy button
copyBtn.addEventListener('click', async (e) => {
e.stopPropagation();
await copyPassword(password);
});
// Click handler for item (also copies)
item.addEventListener('click', async () => {
await copyPassword(password);
});
// Hover handler
item.addEventListener('mouseenter', () => {
selectedIndex = filteredResults.findIndex(r => r.type === 'password' && r.data.id === password.id);
updateSelection();
});
return item;
}
function createClipResultItem(clip, query, isSelected) {
const item = document.createElement('div');
item.className = 'result-item';
if (isSelected) {
item.classList.add('selected');
}
let snippet = clip.text.replace(/\s+/g, ' ').trim();
if (snippet.length > 100) snippet = snippet.substring(0, 100) + '…';
if (query) snippet = highlightText(snippet, query);
item.innerHTML = `
<div class="result-icon">📋</div>
<div class="result-details">
<div class="result-content">${snippet}</div>
</div>
`;
item.addEventListener('click', () => copyClip(clip));
item.addEventListener('mouseenter', () => {
selectedIndex = filteredResults.findIndex(r => r.type === 'clip' && r.data.id === clip.id);
updateSelection();
});
return item;
}
function updateSelection() {
const items = resultsContainer.querySelectorAll('.result-item');
items.forEach((item, index) => {
if (index === selectedIndex) {
item.classList.add('selected');
item.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
} else {
item.classList.remove('selected');
}
});
}
function openNote(noteId) {
ipcRenderer.send('open-note-from-search', noteId);
}
function closeWindow() {
searchInput.value = '';
showEmptyState();
ipcRenderer.send('close-search-window');
}
function showEmptyState() {
resultsContainer.innerHTML = '';
const recent = [...notes]
.sort((a, b) => new Date(b.updated || b.created) - new Date(a.updated || a.created))
.slice(0, 5);
if (recent.length === 0) {
resultsContainer.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📝</div>
<div class="empty-state-text">No notes yet</div>
</div>
`;
filteredResults = [];
selectedIndex = -1;
return;
}
const header = document.createElement('div');
header.className = 'results-section-header';
header.textContent = 'Recent';
resultsContainer.appendChild(header);
filteredResults = recent.map(note => ({ type: 'note', data: note, titleMatch: true }));
selectedIndex = 0;
filteredResults.forEach((result, index) => {
const item = createNoteResultItem(result.data, '', index === selectedIndex);
resultsContainer.appendChild(item);
});
}
function showToast(message, type = 'success') {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.textContent = message;
toast.style.position = 'fixed';
toast.style.top = '20px';
toast.style.right = '20px';
toast.style.padding = '12px 20px';
toast.style.borderRadius = '4px';
toast.style.backgroundColor = type === 'error' ? '#f44336' : '#4caf50';
toast.style.color = 'white';
toast.style.fontSize = '14px';
toast.style.zIndex = '10000';
toast.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
document.body.appendChild(toast);
setTimeout(() => {
toast.remove();
}, 2000);
}
// Utility functions
function stripHtml(html) {
const tmp = document.createElement('div');
tmp.innerHTML = html;
// Handle password fields specially - remove completely from preview
const passwordFields = tmp.querySelectorAll('.password-field-container');
passwordFields.forEach(field => {
field.remove();
});
// Also remove any stray password field related content
const passwordFieldElements = tmp.querySelectorAll('[class*="password-field"]');
passwordFieldElements.forEach(el => {
el.remove();
});
return tmp.textContent || tmp.innerText || '';
}
// Pulls every link out of a note so it can be found and copied directly
// from search, without opening the note first. A link's label is its own
// text when it has one (e.g. selecting "docs" before Cmd+K to insert a
// link makes "docs" the label) — otherwise, for a bare auto-linked URL,
// the plain text right before it on the line ("docs: https://…") is used
// as a fallback label so a natural writing style still works.
function extractLinksFromNote(note) {
const tmp = document.createElement('div');
tmp.innerHTML = note.content || '';
tmp.querySelectorAll('.password-field-container, [class*="password-field"]').forEach(el => el.remove());
const links = [];
tmp.querySelectorAll('a[href]').forEach(a => {
const url = a.getAttribute('href');
if (!url) return;
let label = (a.textContent || '').trim();
if (!label || label === url) {
const prev = a.previousSibling;
if (prev && prev.nodeType === Node.TEXT_NODE) {
const match = prev.textContent.match(/([A-Za-z0-9][A-Za-z0-9 _-]{0,40})[:\-–]\s*$/);
if (match) label = match[1].trim();
}
}
if (!label) label = url;
links.push({
label,
url,
noteId: note.id,
noteTitle: note.title || 'Untitled',
isFavorite: note.isFavorite || false,
updated: note.updated,
created: note.created
});
});
return links;
}
// SECURITY: everything returned here is injected via innerHTML, and note
// titles/snippets/usernames are attacker-controlled strings (an imported or
// pasted note can contain literal markup). Escape first, then highlight the
// escaped query — never insert raw text.
function highlightText(text, query) {
const safeText = escapeHtml(text);
if (!query) return safeText;
const safeQuery = escapeHtml(query);
const regex = new RegExp(`(${escapeRegex(safeQuery)})`, 'gi');
return safeText.replace(regex, '<span class="highlight">$1</span>');
}
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function formatDate(date) {
const now = new Date();
const diff = now - date;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (seconds < 60) {
return 'Just now';
} else if (minutes < 60) {
return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
} else if (hours < 24) {
return `${hours} hour${hours > 1 ? 's' : ''} ago`;
} else if (days < 7) {
return `${days} day${days > 1 ? 's' : ''} ago`;
} else {
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined
});
}
}
// Initialize on load
document.addEventListener('DOMContentLoaded', init);