-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcontent.js
More file actions
1552 lines (1354 loc) · 50.5 KB
/
content.js
File metadata and controls
1552 lines (1354 loc) · 50.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
// content.js
(() => {
const TRACE = Boolean(window.__CMD_BAR_TRACE);
const now = () => (typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now());
const trace = (...args) => {
if (!TRACE) return;
console.log('[CmdBarTrace]', ...args);
};
const scriptStart = now();
console.log('Content script loading...');
if (window.__cmdBarInjected) {
console.log('Content script already injected, skipping');
return;
}
window.__cmdBarInjected = true;
console.log('Content script injected successfully');
// Detect when running inside the extension popup so we can render the command bar there.
const extensionOrigin = chrome?.runtime?.id ? `chrome-extension://${chrome.runtime.id}` : '';
const isExtensionPage = window.location?.origin === extensionOrigin;
const isPopupContext = Boolean(window.__CMD_BAR_POPUP) || (isExtensionPage && window.location?.pathname?.endsWith('/popup.html'));
trace('loaded', { isPopupContext, isExtensionPage, href: window.location?.href, t: now() - scriptStart });
// Constants
const CONSTANTS = {
CONFIRM_TIMEOUT: 2000,
MAX_SUBTITLE_LENGTH: 60,
FALLBACK_ICON: chrome.runtime.getURL('link_18dp_E3E3E3.svg'),
BOOKMARK_ICON: chrome.runtime.getURL('bookmark_18dp_E3E3E3.svg'),
HISTORY_ICON: chrome.runtime.getURL('history_18dp_E3E3E3.svg'),
DEFAULT_STATUS_MSG: '↑ / ↓ navigate • ⌫ close/delete • c copy link'
};
// Message service to avoid DRY violations
const messageService = {
send: (type, data = {}) => chrome.runtime.sendMessage({ type, ...data }),
sendWithCallback: (type, data = {}, callback) => chrome.runtime.sendMessage({ type, ...data }, callback),
recent: (callback) => messageService.sendWithCallback('RECENT', {}, callback),
search: (query, callback) => messageService.sendWithCallback('SEARCH', { query }, callback),
open: (item) => messageService.send('OPEN', { item }),
delete: (item) => messageService.send('DELETE', { item })
};
// UI State Manager for better organization
const uiState = {
overlay: null,
input: null,
listEl: null,
statusBar: null,
pinnedTabsEl: null,
pinnedTabs: [],
items: [],
selectedIdx: -1,
idleTimer: null,
deleteConfirm: false,
lastConfirmIdx: -1,
confirmTimer: null,
reset() {
this.items = [];
this.selectedIdx = -1;
this.deleteConfirm = false;
this.lastConfirmIdx = -1;
this.clearTimers();
},
clearTimers() {
if (this.idleTimer) {
clearTimeout(this.idleTimer);
this.idleTimer = null;
}
if (this.confirmTimer) {
clearTimeout(this.confirmTimer);
this.confirmTimer = null;
}
},
setItems(newItems) {
this.items = this.sortItems(newItems || []);
this.selectedIdx = -1;
},
sortItems(items) {
const typeOrder = {
'tab': 1,
'bookmark': 2,
'history': 3
};
return items.sort((a, b) => {
const aType = a.type || a.source;
const bType = b.type || b.source;
const aOrder = typeOrder[aType] || 4;
const bOrder = typeOrder[bType] || 4;
if (aOrder !== bOrder) {
return aOrder - bOrder;
}
// Get last visited time for each item
const getLastVisited = (item) => {
if (item.lastAccessed) return item.lastAccessed; // tabs
if (item.lastVisitTime) return item.lastVisitTime; // history
if (item.dateAdded) return item.dateAdded; // bookmarks fallback
return 0; // fallback for items without time data
};
const aTime = getLastVisited(a);
const bTime = getLastVisited(b);
// Sort in descending order (most recent first)
return bTime - aTime;
});
}
};
// Legacy global variables for backward compatibility
let overlay, input, listEl, statusBar, items, selectedIdx, idleTimer;
let deleteConfirm, lastConfirmIdx, confirmTimer;
let stylesInjected = false;
function createOverlay() {
const tCreateStart = now();
// Update state references
overlay = uiState.overlay;
input = uiState.input;
listEl = uiState.listEl;
statusBar = uiState.statusBar;
items = uiState.items;
selectedIdx = uiState.selectedIdx;
deleteConfirm = uiState.deleteConfirm;
lastConfirmIdx = uiState.lastConfirmIdx;
confirmTimer = uiState.confirmTimer;
idleTimer = uiState.idleTimer;
// Load CSS into the document once
if (!stylesInjected) {
if (isPopupContext) {
// popup.html links shadow-overlay.css directly for faster paint
stylesInjected = true;
} else {
const styleElement = document.createElement('style');
styleElement.id = 'prd-stv-cmd-bar-styles';
const tCssStart = now();
fetch(chrome.runtime.getURL('shadow-overlay.css'))
.then(response => response.text())
.then(css => {
styleElement.textContent = css;
document.head.appendChild(styleElement);
stylesInjected = true;
trace('css_loaded', { ms: now() - tCssStart });
})
.catch(err => {
console.error('Failed to load shadow-overlay.css:', err);
// Fallback: use inline styles if CSS file fails to load
styleElement.textContent = `
#prd-stv-cmd-bar-overlay {
position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
backdrop-filter: blur(8px); background: rgba(0, 0, 0, 0.3);
display: flex; align-items: center; justify-content: center;
z-index: 2147483647;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
`;
document.head.appendChild(styleElement);
stylesInjected = true;
});
}
}
// Create overlay inside shadow DOM
uiState.overlay = document.createElement('div');
uiState.overlay.id = 'prd-stv-cmd-bar-overlay';
const container = document.createElement('div');
container.id = 'prd-stv-cmd-bar-container';
uiState.input = document.createElement('input');
uiState.input.id = 'prd-stv-cmd-bar-input';
uiState.input.type = 'text';
uiState.input.placeholder = 'Type to search tabs, bookmarks, history...';
uiState.listEl = document.createElement('div');
uiState.listEl.id = 'prd-stv-cmd-bar-list';
uiState.statusBar = document.createElement('div');
uiState.statusBar.id = 'prd-stv-status-bar';
// Create tab counter container
const tabCounterContainer = document.createElement('div');
tabCounterContainer.style.display = 'flex';
tabCounterContainer.style.alignItems = 'center';
tabCounterContainer.style.marginRight = '8px';
// Create tab counter element
const tabCounter = document.createElement('span');
tabCounter.id = 'prd-stv-tab-counter';
tabCounter.textContent = '0';
tabCounterContainer.appendChild(tabCounter);
tabCounterContainer.appendChild(document.createTextNode(' tabs'));
// Create status message element
const statusMessageEl = document.createElement('span');
statusMessageEl.id = 'prd-stv-status-message';
statusMessageEl.textContent = CONSTANTS.DEFAULT_STATUS_MSG;
uiState.statusBar.appendChild(tabCounterContainer);
uiState.statusBar.appendChild(statusMessageEl);
uiState.statusBar.style.display = 'flex';
uiState.statusBar.style.alignItems = 'center';
// Update legacy references
overlay = uiState.overlay;
input = uiState.input;
listEl = uiState.listEl;
statusBar = uiState.statusBar;
// Create pinned tabs container (same as sidepanel)
uiState.pinnedTabsEl = document.createElement('div');
uiState.pinnedTabsEl.id = 'pinned-tabs-container';
uiState.pinnedTabsEl.className = 'prd-stv-pinned-tabs';
uiState.pinnedTabsEl.style.cssText = 'display:none;';
container.appendChild(uiState.pinnedTabsEl);
container.appendChild(uiState.input);
container.appendChild(uiState.listEl);
container.appendChild(uiState.statusBar);
uiState.overlay.appendChild(container);
// Close overlay when user clicks outside the container
uiState.overlay.addEventListener('mousedown', (ev) => {
if (ev.target === uiState.overlay) {
destroyOverlay();
}
});
// Prevent clicks inside the container from bubbling to overlay handler
container.addEventListener('mousedown', (ev) => ev.stopPropagation());
// Append overlay directly to document body
document.body.appendChild(uiState.overlay);
trace('overlay_appended', { ms: now() - tCreateStart });
// listeners
uiState.input.addEventListener('keydown', onKeyDown);
document.addEventListener('keydown', onGlobalKeyDown);
document.addEventListener('keyup', onGlobalKeyUp);
uiState.input.addEventListener('input', onInput);
uiState.input.focus();
// Initial data (tabs + pinned tabs + count) in one roundtrip to reduce cold-start overhead.
const statusMessage = document.getElementById('prd-stv-status-message');
if (statusMessage) statusMessage.textContent = 'Loading…';
const tInitStart = now();
chrome.runtime.sendMessage({ type: 'GET_INITIAL_STATE' }, (response) => {
const err = chrome.runtime.lastError?.message;
trace('initial_state', { ms: now() - tInitStart, ok: response?.success, err });
if (err || !response || response.success === false) {
// Fallback to legacy init paths if the background doesn't support GET_INITIAL_STATE.
loadPinnedTabs();
messageService.recent((res) => {
uiState.setItems(res);
items = uiState.items;
selectedIdx = uiState.selectedIdx;
renderList();
if (statusMessage) statusMessage.textContent = CONSTANTS.DEFAULT_STATUS_MSG;
});
updateTabCount();
return;
}
if (Array.isArray(response.pinnedTabs)) {
renderPinnedTabs(response.pinnedTabs);
}
if (typeof response.tabCount === 'number') {
applyTabCount(response.tabCount);
}
if (Array.isArray(response.recent)) {
uiState.setItems(response.recent);
items = uiState.items;
selectedIdx = uiState.selectedIdx;
renderList();
}
if (statusMessage) statusMessage.textContent = CONSTANTS.DEFAULT_STATUS_MSG;
});
}
function destroyOverlay() {
cancelAutoOpen();
document.removeEventListener('keydown', onGlobalKeyDown);
document.removeEventListener('keyup', onGlobalKeyUp);
uiState.overlay = null;
overlay = null;
if (isPopupContext) {
window.close();
}
}
function toggleOverlay() {
// First invocation opens the overlay
if (!overlay) {
createOverlay();
return;
}
// Overlay already visible -> move selection down and schedule auto-open
if (items.length === 0) return;
input.blur();
selectedIdx = (selectedIdx + 1) % items.length;
renderList();
}
function onGlobalKeyDown(e) {
if (e.target === input) return; // already handled by onKeyDown
const handled = handleKey(e);
if (handled) {
e.stopPropagation();
e.preventDefault();
}
}
function onGlobalKeyUp(e) {
if (e.target === input) return;
handleKeyUp(e);
}
function onKeyDown(e) {
// If the input is focused and the key is a printable character, allow normal input behavior
if (e.target === input) {
// For printable keys, we allow default behavior but prevent propagation to the page
const isPrintableKey = e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey;
if (isPrintableKey) {
// Allow the input to receive the character
e.stopPropagation();
return;
}
// For special keys (arrows, enter, etc.) when input is focused, handle them specially
const handled = handleKey(e);
if (handled) {
e.stopPropagation();
}
return;
}
// For keys when input is not focused, handle normally
const handled = handleKey(e);
if (handled) {
e.stopPropagation();
}
}
// Key handler functions - Split for better SRP compliance
const keyHandlers = {
escape: () => {
destroyOverlay();
},
navigation: (e) => {
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return false;
e.preventDefault();
hideDeleteConfirm();
removeProgressBars();
const dir = e.key === 'ArrowDown' ? 1 : -1;
// Handle boundary cases - focus input when at edges
if (e.key === 'ArrowUp' && selectedIdx === 0) {
selectedIdx = -1;
renderList();
input.focus();
return true;
}
if (e.key === 'ArrowDown' && selectedIdx === items.length - 1) {
selectedIdx = -1;
renderList();
input.focus();
return true;
}
// Handle navigation from input (selectedIdx === -1)
if (selectedIdx === -1) {
selectedIdx = e.key === 'ArrowDown' ? 0 : items.length - 1;
} else {
selectedIdx = (selectedIdx + dir + items.length) % items.length;
}
renderList();
cancelAutoOpen();
// Blur input so backspace won't edit text - use requestAnimationFrame to ensure proper timing
requestAnimationFrame(() => {
if (document.activeElement === input) {
input.blur();
}
});
return true;
},
metaNavigation: (e) => {
if (!e.metaKey) return false;
if (e.key === 'ArrowUp') {
e.preventDefault();
input.focus();
return true;
}
if (e.key === 'ArrowDown') {
e.preventDefault();
if (items.length) {
selectedIdx = items.length - 1;
renderList();
cancelAutoOpen();
requestAnimationFrame(() => {
if (document.activeElement === input) {
input.blur();
}
});
}
return true;
}
return false;
},
deletion: (e) => {
if (e.key !== 'Backspace') {
return false;
}
const activeEl = document.activeElement;
// Allow normal backspace behavior when input is focused and has text
if (activeEl === input && input.value !== '') {
return false; // Don't handle - allow default backspace behavior
}
e.preventDefault();
const item = items[selectedIdx];
if (!item) return true;
if (!deleteConfirm || lastConfirmIdx !== selectedIdx) {
// First press shows confirmation + bounce
deleteConfirm = true;
lastConfirmIdx = selectedIdx;
showDeleteConfirm();
} else {
// Second press performs deletion
messageService.delete(item);
hideDeleteConfirm();
performItemDeletion();
}
return true;
},
copy: (e) => {
if (e.key !== 'c' || e.metaKey || e.ctrlKey || e.altKey) return false;
const item = items[selectedIdx];
if (!item) return false;
e.preventDefault();
copyLinkToClipboard(item);
destroyOverlay();
return true;
},
activation: (e) => {
if (e.key !== 'Enter') return false;
e.preventDefault();
const item = items[selectedIdx];
if (item) {
messageService.open(item);
destroyOverlay();
}
return true;
}
};
// Extracted deletion animation logic
function performItemDeletion() {
const el = listEl.querySelector(`[data-idx="${selectedIdx}"]`);
if (el) {
el.classList.add('prd-stv-remove');
el.addEventListener('animationend', () => {
removeItemFromList();
}, { once: true });
} else {
removeItemFromList();
}
}
function removeItemFromList(index = selectedIdx) {
if (index < 0 || index >= items.length) return;
items.splice(index, 1);
if (selectedIdx >= items.length) {
selectedIdx = items.length - 1;
} else if (selectedIdx > index) {
selectedIdx = Math.max(0, selectedIdx - 1);
}
renderList();
// Update tab count after removing an item
updateTabCount();
}
// Simplified and centralized key handling
function handleKey(e) {
// Always allow Esc to close the palette
if (e.key === 'Escape') {
keyHandlers.escape();
return true;
}
// Ignore all other keys if the palette isn't open
if (!overlay) return false;
// If input is focused and it's a printable character, don't process with our handlers
if (e.target === input) {
const isPrintableKey = e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey;
if (isPrintableKey) {
return false; // Let the input handle printable characters normally
}
}
// Try each handler in order - return true if handled, false otherwise
if (keyHandlers.navigation(e)) return true;
if (keyHandlers.metaNavigation(e)) return true;
if (keyHandlers.copy(e)) return true;
if (keyHandlers.deletion(e)) return true;
if (keyHandlers.activation(e)) return true;
return false; // Key not handled, allow default behavior
}
function handleKeyUp(e) {
// Open tab when the modifier/shortcut key is released (e.g., Meta, Alt, Control)
if (!overlay) return;
if (['Meta', 'Alt', 'Control'].includes(e.key)) {
const item = items[selectedIdx];
if (item) {
messageService.open(item);
destroyOverlay();
}
}
}
function onInput(e) {
e.stopPropagation(); // Prevent the input event from affecting the page
hideDeleteConfirm();
// User is typing -> cancel pending auto open
cancelAutoOpen();
const q = input.value.trim();
if (!q) {
messageService.recent((res) => {
uiState.setItems(res);
items = uiState.items;
selectedIdx = uiState.selectedIdx;
renderList();
});
return;
}
messageService.search(q, (res) => {
uiState.setItems(res);
items = uiState.items;
selectedIdx = uiState.selectedIdx;
renderList();
});
}
function hideDeleteConfirm() {
uiState.deleteConfirm = false;
deleteConfirm = false;
if (uiState.confirmTimer) {
clearTimeout(uiState.confirmTimer);
uiState.confirmTimer = null;
confirmTimer = null;
}
const statusMessage = document.getElementById('prd-stv-status-message');
if (statusMessage) {
statusMessage.textContent = CONSTANTS.DEFAULT_STATUS_MSG;
statusMessage.classList.remove('confirm');
}
}
function removeProgressBars() {
uiState.listEl?.querySelectorAll('.prd-stv-prog').forEach(el => el.remove());
}
function cancelAutoOpen() {
if (uiState.idleTimer) {
clearTimeout(uiState.idleTimer);
uiState.idleTimer = null;
idleTimer = null;
}
removeProgressBars();
}
function showDeleteConfirm() {
const statusMessage = document.getElementById('prd-stv-status-message');
if (!statusMessage) return;
statusMessage.textContent = 'Press backspace again to confirm';
statusMessage.classList.add('confirm');
// Bounce animation on the currently selected item
const activeEl = uiState.listEl?.querySelector('.prd-stv-cmd-item.prd-stv-active');
if (activeEl) {
activeEl.classList.add('prd-stv-bounce');
activeEl.addEventListener('animationend', () => {
activeEl.classList.remove('prd-stv-bounce');
}, { once: true });
}
uiState.confirmTimer = setTimeout(() => hideDeleteConfirm(), CONSTANTS.CONFIRM_TIMEOUT);
confirmTimer = uiState.confirmTimer;
}
// Extracted item rendering logic for better modularity
function createItemElement(item, index) {
const div = document.createElement('div');
const isHistory = item.type === 'history' || item.source === 'history';
div.className = 'prd-stv-cmd-item' + (index === selectedIdx ? ' prd-stv-active' : '') + (isHistory ? ' prd-stv-history-item' : '');
div.dataset.idx = index;
const iconHtml = getIconHtml(item);
// Add controls (check + 3-dots). In popup context, tabs get a close button on the left.
const isBookmark = item.type === 'bookmark';
const isTab = item.type === 'tab';
const showCloseBtn = isPopupContext && isTab;
const controlsHtml = (isBookmark || isTab) ? `
<div class="prd-stv-item-controls" style="opacity:0;transition:opacity 0.2s ease;margin-left:auto;padding-left:8px;">
${showCloseBtn ? `<button class="prd-stv-close-btn" title="Close tab" data-close-tab-id="${item.id}"><span class="material-icons-round">check</span></button>` : ''}
<button class="prd-stv-menu-btn" title="More options" ${isBookmark ? `data-bookmark-id="${item.id}"` : `data-tab-id="${item.id}"`}
style="background:transparent;border:none;color:#9b9b9b;font-size:16px;cursor:pointer;padding:4px;border-radius:15px;">⋯</button>
</div>
` : '';
// Use custom title if available, otherwise use original title
const displayTitle = item.customTitle || item.title || item.url;
div.innerHTML = `
<div style="display:flex;align-items:center;width:100%;">
${iconHtml}
<div style="display:flex;flex-direction:row; gap: 5px;flex:1;min-width:0;">
<span class="prd-stv-title" style="text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">${highlightMatches(displayTitle, input?.value.trim())}</span>
<span class="prd-stv-url" style="text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">${getSubtitle(item)}</span>
</div>
${controlsHtml}
</div>
`;
// // Add error handling for favicon images
// const favicon = div.querySelector('.prd-stv-favicon');
// if (favicon) {
// favicon.addEventListener('error', () => {
// favicon.src = CONSTANTS.FALLBACK_ICON;
// }, { once: true });
// }
// Add click handler
div.addEventListener('click', (e) => {
if (e.target.classList.contains('prd-stv-close-btn')) {
e.stopPropagation();
if (item.type === 'tab') {
messageService.delete(item);
removeItemFromList(index);
}
} else if (e.target.classList.contains('prd-stv-menu-btn')) {
e.stopPropagation();
if (item.type === 'bookmark') {
showBookmarkContextMenu(e, item, div);
} else if (item.type === 'tab') {
showTabContextMenu(e, item, div);
}
} else {
messageService.open(item);
destroyOverlay();
}
});
// Show menu button on hover
div.addEventListener('mouseenter', () => {
const controls = div.querySelector('.prd-stv-item-controls');
if (controls) controls.style.opacity = '1';
});
div.addEventListener('mouseleave', () => {
const controls = div.querySelector('.prd-stv-item-controls');
if (controls) controls.style.opacity = '0';
});
return div;
}
function scrollToActiveItem() {
const activeEl = listEl.querySelector('.prd-stv-cmd-item.prd-stv-active');
if (activeEl) {
activeEl.scrollIntoView({ block: 'nearest' });
}
}
function renderList() {
listEl.innerHTML = '';
items.forEach((item, index) => {
const itemElement = createItemElement(item, index);
listEl.appendChild(itemElement);
});
// Ensure the selected item is visible within the scroll container
scrollToActiveItem();
}
function getIconHtml(it) {
// For bookmarks and history, use Google's favicon service
if ((it.type === 'bookmark' || it.type === 'history') && it.url) {
const faviconUrl = `https://www.google.com/s2/favicons?domain=${encodeURIComponent(new URL(it.url).hostname)}&sz=32`;
return `<img class="prd-stv-favicon" src="${faviconUrl}" onerror="this.src='${CONSTANTS.FALLBACK_ICON}'" />`;
}
// For tabs, use the favicon if available
const actual = it.icon || '';
if (actual) {
return `<img class="prd-stv-favicon" src="${actual}" />`;
}
// No favicon available → fallback icon
return `<img class="prd-stv-favicon" src="${CONSTANTS.FALLBACK_ICON}" />`;
}
function typeGlyph(it) {
if (it.type === 'bookmark') return `<img src="${CONSTANTS.BOOKMARK_ICON}" class="prd-stv-type-icon" />`;
if (it.type === 'history') return `<img src="${CONSTANTS.HISTORY_ICON}" class="prd-stv-type-icon" />`;
return '';
}
function getSubtitle(it) {
if (it.source === 'history' && it.lastVisitTime) {
const rel = escapeHtml(timeAgo(it.lastVisitTime));
const glyph = typeGlyph(it);
return glyph ? `${glyph} ${rel}` : rel;
}
if (it.source === 'bookmark' && it.folder) {
const glyph = typeGlyph(it);
return glyph ? `${glyph} ${escapeHtml(it.folder)}` : escapeHtml(it.folder);
}
return highlightMatches(truncateMiddle(it.url), input?.value.trim());
}
function showToast(message, duration = 2000) {
const existing = document.getElementById('prd-stv-toast');
existing?.remove();
const div = document.createElement('div');
div.id = 'prd-stv-toast';
div.textContent = message;
document.body.appendChild(div);
setTimeout(() => div.remove(), duration);
}
async function copyLinkToClipboard(item) {
try {
await navigator.clipboard.writeText(item.url || '');
showToast('Link copied!');
} catch (e) {
// Fallback: create temp textarea
const ta = document.createElement('textarea');
ta.value = item.url || '';
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); } catch (err) {}
ta.remove();
showToast('Link copied!');
}
}
function timeAgo(ms) {
const diff = Date.now() - ms;
const s = Math.floor(diff / 1000);
const m = Math.floor(s / 60);
const h = Math.floor(m / 60);
const d = Math.floor(h / 24);
if (d > 0) return `${d}d ago`;
if (h > 0) return `${h}h ago`;
if (m > 0) return `${m}m ago`;
return `${s}s ago`;
}
function escapeHtml(str) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return str?.replace(/[&<>"']/g, (c) => map[c]) || '';
}
// Highlight occurrences of the current query within text
function highlightMatches(text, query) {
if (!query) return escapeHtml(text);
const escaped = escapeHtml(text || '');
// Escape regex special chars in query
const safeQuery = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
try {
const regex = new RegExp(safeQuery, 'ig');
return escaped.replace(regex, (m) => `<span class="prd-stv-hl">${m}</span>`);
} catch (e) {
return escaped;
}
}
// Truncate long strings in the middle so they fit on a single line
// Example: "https://verylongdomain.com/path/to/resource" (maxLen 40)
// becomes "https://verylo.../path/to/resource"
function truncateMiddle(str, maxLen = CONSTANTS.MAX_SUBTITLE_LENGTH) {
if (!str || str.length <= maxLen) return str || '';
const part = Math.floor((maxLen - 3) / 2);
return str.slice(0, part) + '...' + str.slice(str.length - part);
}
function applyTabCount(count) {
const tabCounter = document.getElementById('prd-stv-tab-counter');
if (!tabCounter || typeof count !== 'number') return;
const oldCount = parseInt(tabCounter.textContent) || 0;
const newCount = count;
if (oldCount !== newCount) {
tabCounter.textContent = newCount;
tabCounter.classList.remove('prd-stv-tab-count-update');
void tabCounter.offsetWidth; // reflow to restart animation
tabCounter.classList.add('prd-stv-tab-count-update');
}
}
// Update the tab counter in the status bar
function updateTabCount() {
chrome.runtime.sendMessage({ type: "GET_TAB_COUNT" }, (response) => {
if (chrome.runtime.lastError) {
console.error('Error getting tab count:', chrome.runtime.lastError);
return;
}
if (response && response.count !== undefined) {
applyTabCount(response.count);
}
});
}
// Bookmark context menu for content.js overlay
function showBookmarkContextMenu(event, bookmark, itemElement) {
if (!window.itemContextMenu) {
showBookmarkContextMenuLegacy(event, bookmark, itemElement);
return;
}
const computeHasDate = async () => {
try {
if (!window.datedLinksModule) return false;
return await window.datedLinksModule.hasDate(bookmark.url);
} catch (error) {
console.warn('Failed to check dated status:', error);
return false;
}
};
(async () => {
const hasDate = await computeHasDate();
const handleDateAction = async (action) => {
if (!window.datedLinksModule) {
showToast('Date feature not available');
return true;
}
const itemData = {
url: bookmark.url,
title: bookmark.title || 'Untitled',
favicon: bookmark.favicon || '',
itemType: 'bookmark',
itemId: bookmark.id
};
if (action === 'add-date-tomorrow') {
const dates = window.itemContextMenu.getQuickDates();
await window.datedLinksModule.addDate(itemData, dates.tomorrow);
showToast('Date set to tomorrow');
} else if (action === 'add-date-next-week') {
const dates = window.itemContextMenu.getQuickDates();
await window.datedLinksModule.addDate(itemData, dates.nextWeek);
showToast('Date set to next week');
} else if (action === 'add-date-someday') {
const dates = window.itemContextMenu.getQuickDates();
await window.datedLinksModule.addDate(itemData, dates.someday);
showToast('Date set to someday');
} else if (action === 'add-date-custom') {
if (!window.dateModal) {
showToast('Date picker not available');
return true;
}
window.dateModal.show(itemData);
return true;
} else if (action === 'remove-date') {
await window.datedLinksModule.removeDate(bookmark.url);
showToast('Date removed');
}
return true;
};
const dateRow = window.itemContextMenu.createDateIconRow(hasDate, handleDateAction);
const renameItem = window.itemContextMenu.createMenuItem('Rename', 'rename');
const moveItem = window.itemContextMenu.createMenuItem('Move to...', 'move');
const menu = window.itemContextMenu.showMenuAtEvent(event, [dateRow, renameItem, moveItem]);
menu.addEventListener('click', (e) => {
const action = e.target.closest('.prd-stv-context-item')?.dataset.action;
if (action === 'rename') {
startBookmarkRename(bookmark, itemElement);
} else if (action === 'move') {
showBookmarkMoveDialog(bookmark);
}
window.itemContextMenu.close();
});
})();
}
function closeBookmarkContextMenu() {
window.itemContextMenu?.close?.();
document.getElementById('prd-stv-bookmark-context-menu')?.remove();
}
function startBookmarkRename(bookmark, itemElement) {
const titleElement = itemElement.querySelector('.prd-stv-title') || itemElement.querySelector('span');
const currentTitle = bookmark.title;
// Create input element
const input = document.createElement('input');
input.type = 'text';
input.value = currentTitle;
input.style.cssText = 'background:#3a3a3a;border:1px solid #b9a079;color:#fff;padding:2px 4px;border-radius:15px;font-size:14px;outline:none;width:100%;';
// Replace title with input
titleElement.innerHTML = '';
titleElement.appendChild(input);
input.focus();
input.select();
const finishRename = async (save = false) => {
const newTitle = input.value.trim();
if (save && newTitle && newTitle !== currentTitle) {
try {
await chrome.runtime.sendMessage({
type: 'RENAME_BOOKMARK',
bookmarkId: bookmark.id,
newTitle: newTitle
});
bookmark.title = newTitle; // Update local state
showToast('Bookmark renamed');
} catch (error) {
console.error('Failed to rename bookmark:', error);
showToast('Failed to rename bookmark');
}
}
// Restore original title display
titleElement.innerHTML = highlightMatches(bookmark.title || bookmark.url, input?.value.trim() || '');
};
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
finishRename(true);
} else if (e.key === 'Escape') {
e.preventDefault();
finishRename(false);
}
});
input.addEventListener('blur', () => finishRename(true));
}
function showBookmarkMoveDialog(bookmark) {
if (!window.folderSelectorModal?.show) {
showToast('Folder selector not available');
return;
}