Repository navigation
Expand file tree
/
Copy pathnewtab.js
More file actions
804 lines (687 loc) · 29.4 KB
/
Copy pathnewtab.js
File metadata and controls
804 lines (687 loc) · 29.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
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
// Main logic for New Tab
document.addEventListener('DOMContentLoaded', () => {
// ---- Elements ----
const timeEl = document.getElementById('current-time');
const dateEl = document.getElementById('current-date');
const weatherInfoEl = document.getElementById('weather-info');
const weatherDescEl = document.getElementById('weather-desc');
// Settings elements
const triggerBtn = document.getElementById('settings-trigger');
const closeBtn = document.getElementById('close-settings');
const drawer = document.getElementById('settings-drawer');
const backdrop = document.getElementById('settings-backdrop');
const themeSelect = document.getElementById('theme-select');
const bgTypeSelect = document.getElementById('bg-type');
const bgColorPick = document.getElementById('bg-color-pick');
const bgGradPresets = document.getElementById('bg-gradient-presets');
const bgGradCustom = document.getElementById('bg-gradient-custom');
const bgImageContainer = document.getElementById('bg-image-container');
const bgImageFile = document.getElementById('bg-image-file');
const clearImageBtn = document.getElementById('clear-image-btn');
const pinSizeSelect = document.getElementById('pin-size-select');
const refreshFaviconsBtn = document.getElementById('refresh-favicons-btn');
const resetBtn = document.getElementById('reset-settings');
// Pins Elements
const pinsGrid = document.getElementById('pins-grid');
const addPinBtn = document.getElementById('add-pin-btn');
const pinModal = document.getElementById('pin-modal');
const pinModalBackdrop = document.getElementById('pin-modal-backdrop');
const cancelPinBtn = document.getElementById('cancel-pin');
const savePinBtn = document.getElementById('save-pin');
const pinUrlInput = document.getElementById('pin-url');
const pinNameInput = document.getElementById('pin-name');
const pinModalTitle = document.getElementById('pin-modal-title');
// Context Menu Elements
const ctxMenu = document.getElementById('context-menu');
const ctxOpen = document.getElementById('ctx-open');
const ctxOpenNew = document.getElementById('ctx-open-new');
const ctxRefetch = document.getElementById('ctx-refetch');
const ctxEdit = document.getElementById('ctx-edit');
const ctxRemove = document.getElementById('ctx-remove');
// Search Elements
const searchInput = document.getElementById('search-input');
const searchDropdown = document.getElementById('search-dropdown');
const searchResults = document.getElementById('search-results');
// Recent Pins Elements
const recentPinsWrapper = document.getElementById('recent-pins-wrapper');
const recentPinsScroll = document.getElementById('recent-pins-scroll');
let currentEditingPinId = null;
let contextTargetId = null;
let selectedSearchIndex = -1;
let currentSearchResults = [];
// ---- Favicon Management & Multi-Tier Fallback System ----
function extractDomain(url) {
if (!url) return '';
let target = url.trim();
if (!target.startsWith('http://') && !target.startsWith('https://')) {
target = 'https://' + target;
}
try {
const parsed = new URL(target);
return parsed.hostname || '';
} catch (e) {
const match = target.match(/(?:https?:\/\/)?(?:www\.)?([^/\s:]+)/i);
return match ? match[1] : '';
}
}
function getChromeFaviconUrl(url, size = 64) {
if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.getURL && url) {
let targetUrl = url.trim();
if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
targetUrl = 'https://' + targetUrl;
}
return chrome.runtime.getURL(`/_favicon/?pageUrl=${encodeURIComponent(targetUrl)}&size=${size}`);
}
return '';
}
function getFaviconFallbackUrls(pageUrl, customFavicon = null) {
const urls = [];
// If custom non-Google favicon provided, test it first
if (customFavicon && customFavicon.trim() && !customFavicon.includes('google.com/s2/favicons')) {
urls.push(customFavicon.trim());
}
// 1. Chrome Native Local Favicon Cache (MV3 _favicon API)
if (pageUrl) {
const chromeFav = getChromeFaviconUrl(pageUrl, 64);
if (chromeFav) urls.push(chromeFav);
}
const domain = extractDomain(pageUrl);
const localFallback = (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.getURL)
? chrome.runtime.getURL('icons/default-favicon.svg')
: 'icons/default-favicon.svg';
if (domain) {
// 2. Direct domain favicon
urls.push(`https://${domain}/favicon.ico`);
// 3. DuckDuckGo Icons API
urls.push(`https://icons.duckduckgo.com/ip3/${encodeURIComponent(domain)}.ico`);
// 4. Vemetric Favicon API
urls.push(`https://favicon.vemetric.com/${encodeURIComponent(domain)}`);
// 5. Favicone API
urls.push(`https://favicone.com/${encodeURIComponent(domain)}`);
// 6. Google Favicon API (validated on load)
urls.push(`https://www.google.com/s2/favicons?domain=${encodeURIComponent(domain)}&sz=64`);
}
// 7. Local default SVG fallback icon
urls.push(localFallback);
return urls;
}
function setupFaviconFallback(imgElement, pageUrl, customFavicon = null) {
const urls = getFaviconFallbackUrls(pageUrl, customFavicon);
let index = 0;
function tryNext() {
index++;
if (index < urls.length) {
imgElement.src = urls[index];
} else {
imgElement.onload = null;
imgElement.onerror = null;
}
}
imgElement.onload = () => {
const currentUrl = urls[index] || '';
// Detect if Google Favicon API returned its 16x16 default blue/gray globe placeholder image
if (currentUrl.includes('google.com/s2/favicons') && imgElement.naturalWidth <= 16) {
tryNext();
}
};
imgElement.onerror = () => {
tryNext();
};
imgElement.src = urls[0];
}
// ---- Clock & Date ----
function updateClock() {
const now = new Date();
const hrs = now.getHours().toString().padStart(2, '0');
const mins = now.getMinutes().toString().padStart(2, '0');
timeEl.textContent = `${hrs}:${mins}`;
const options = { weekday: 'long', month: 'long', day: 'numeric' };
dateEl.textContent = now.toLocaleDateString('en-US', options);
}
setInterval(updateClock, 1000);
updateClock();
// ---- Weather ----
function initWeather() {
if (!navigator.geolocation) {
weatherDescEl.textContent = "Geolocation not supported";
return;
}
// Check cache (30 mins)
chrome.storage.local.get(['weatherCache'], (res) => {
const cache = res.weatherCache;
const now = Date.now();
if (cache && cache.timestamp > now - 30 * 60 * 1000 && cache.data) {
displayWeather(cache.data);
return;
}
navigator.geolocation.getCurrentPosition(success, error);
});
function success(position) {
const lat = position.coords.latitude;
const long = position.coords.longitude;
fetchWeather(lat, long);
}
function error() {
weatherDescEl.textContent = "Location Permission Denied";
}
}
async function fetchWeather(lat, long) {
try {
const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${long}¤t_weather=true&temperature_unit=celsius`);
if (!response.ok) throw new Error('Weather API Error');
const data = await response.json();
let locationName = "Local";
if (data.timezone) {
const parts = data.timezone.split('/');
locationName = parts[parts.length - 1].replace(/_/g, ' ');
}
const payload = { temp: Math.round(data.current_weather.temperature), location: locationName };
chrome.storage.local.set({
weatherCache: { timestamp: Date.now(), data: payload }
});
displayWeather(payload);
} catch (err) {
weatherDescEl.textContent = "Weather API Error";
console.error(err);
}
}
function displayWeather(data) {
weatherInfoEl.innerHTML = `
<span id="weather-desc">${data.location}: ${data.temp}°C</span>
`;
}
setTimeout(initWeather, 500);
// ---- Settings UI Binding ----
function initSettingsUI() {
themeSelect.value = window.SettingsState.theme;
const bg = window.SettingsState.background;
bgTypeSelect.value = bg.type;
if (bg.type === 'custom_color') bgColorPick.value = bg.value;
if (bg.type === 'gradient_preset') bgGradPresets.value = bg.value;
if (bg.type === 'gradient_custom') bgGradCustom.value = bg.value;
if (bg.type === 'image' && bg.value) clearImageBtn.style.display = 'inline-block';
pinSizeSelect.value = window.SettingsState.pinSize || 'medium';
updateBgInputsVisibility();
}
function updateBgInputsVisibility() {
const type = bgTypeSelect.value;
bgColorPick.classList.toggle('hidden', type !== 'custom_color');
bgGradPresets.classList.toggle('hidden', type !== 'gradient_preset');
bgGradCustom.classList.toggle('hidden', type !== 'gradient_custom');
bgImageContainer.classList.toggle('hidden', type !== 'image');
}
// Settings Listeners
bgTypeSelect.addEventListener('change', (e) => {
updateBgInputsVisibility();
const type = e.target.value;
let val = '';
if (type === 'custom_color') val = bgColorPick.value;
if (type === 'gradient_preset') val = bgGradPresets.value;
if (type === 'gradient_custom') val = bgGradCustom.value;
if (type === 'image') return; // Handled file input separately
updateSetting('background', { type, value: val });
});
bgColorPick.addEventListener('input', (e) => updateSetting('background', { type: 'custom_color', value: e.target.value }));
bgGradPresets.addEventListener('change', (e) => updateSetting('background', { type: 'gradient_preset', value: e.target.value }));
bgGradCustom.addEventListener('input', (e) => updateSetting('background', { type: 'gradient_custom', value: e.target.value }));
themeSelect.addEventListener('change', (e) => updateSetting('theme', e.target.value));
pinSizeSelect.addEventListener('change', (e) => updateSetting('pinSize', e.target.value));
// Handle Image Upload with Canvas Compression to bypass quota limits
bgImageFile.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
const maxSize = 1920;
if (width > maxSize || height > maxSize) {
if (width > height) {
height = Math.round(height * (maxSize / width));
width = maxSize;
} else {
width = Math.round(width * (maxSize / height));
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
const dataUrl = canvas.toDataURL('image/jpeg', 0.6); // 60% quality jpeg
try {
updateSetting('background', { type: 'image', value: dataUrl });
clearImageBtn.style.display = 'inline-block';
} catch (err) {
alert("Image is still too large. Please select a highly compressed or smaller image.");
}
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
clearImageBtn.addEventListener('click', () => {
bgImageFile.value = '';
clearImageBtn.style.display = 'none';
updateSetting('background', { type: 'image', value: '' });
});
// Refresh / Reset all pin favicons
if (refreshFaviconsBtn) {
refreshFaviconsBtn.addEventListener('click', () => {
pins = pins.map(pin => {
const { favicon, ...rest } = pin;
return rest;
});
savePins();
alert("All pinned icons have been refreshed with the new multi-tier fallback system!");
});
}
// Reset settings
resetBtn.addEventListener('click', () => {
if(confirm("Are you sure you want to reset all settings?")) {
chrome.storage.local.clear(() => {
chrome.runtime.reload();
});
}
});
// Drawer toggles
function openDrawer() {
initSettingsUI();
drawer.classList.add('open');
backdrop.classList.add('open');
}
function closeDrawerFunc() {
drawer.classList.remove('open');
backdrop.classList.remove('open');
}
triggerBtn.addEventListener('click', openDrawer);
closeBtn.addEventListener('click', closeDrawerFunc);
backdrop.addEventListener('click', closeDrawerFunc);
// ---- Pins Management ----
let pins = [];
let dragSourceId = null;
function loadPins() {
chrome.storage.local.get(['pins'], (res) => {
if (res.pins && Array.isArray(res.pins)) {
let hasMigrated = false;
pins = res.pins.map(pin => {
// If pin contains legacy hardcoded single-tier favicon URL, remove it to enable the multi-tier fallback system
if (pin.favicon && (pin.favicon.includes('google.com/s2/favicons') || pin.favicon.includes('vemetric') || pin.favicon.includes('favicone') || pin.favicon.includes('duckduckgo'))) {
const { favicon, ...rest } = pin;
hasMigrated = true;
return rest;
}
return pin;
});
if (hasMigrated) {
savePins();
} else {
renderPins();
}
}
});
}
function savePins() {
chrome.storage.local.set({ pins }, renderPins);
}
function trackPinClick(pinId) {
if (!pinId) return;
chrome.storage.local.get(['pinStats'], (res) => {
const stats = res.pinStats || {};
const curr = stats[pinId] || { clicks: 0, lastUsed: 0 };
stats[pinId] = {
clicks: curr.clicks + 1,
lastUsed: Date.now()
};
chrome.storage.local.set({ pinStats: stats }, () => {
renderRecentApps();
});
});
}
function renderRecentApps() {
if (!recentPinsScroll || !pins) return;
if (pins.length === 0) {
if (recentPinsWrapper) recentPinsWrapper.classList.add('hidden');
return;
}
chrome.storage.local.get(['pinStats'], (res) => {
const stats = res.pinStats || {};
// Sort pins by lastUsed descending, then by clicks descending
const sortedPins = [...pins].sort((a, b) => {
const statA = stats[a.id] || { clicks: 0, lastUsed: 0 };
const statB = stats[b.id] || { clicks: 0, lastUsed: 0 };
if (statB.lastUsed !== statA.lastUsed) {
return statB.lastUsed - statA.lastUsed;
}
return statB.clicks - statA.clicks;
});
// Display top 10 recent / most used apps
const recentPins = sortedPins.slice(0, 10);
recentPinsScroll.innerHTML = '';
recentPins.forEach(pin => {
const chip = document.createElement('a');
chip.className = 'recent-pin-chip';
chip.href = pin.url;
const img = document.createElement('img');
img.alt = pin.name;
setupFaviconFallback(img, pin.url, pin.favicon);
const span = document.createElement('span');
span.textContent = pin.name;
chip.appendChild(img);
chip.appendChild(span);
chip.addEventListener('click', () => {
trackPinClick(pin.id);
});
recentPinsScroll.appendChild(chip);
});
if (recentPinsWrapper) {
recentPinsWrapper.classList.remove('hidden');
}
});
}
// Convert vertical mouse wheel scrolling to horizontal scrolling for top recent pins bar
if (recentPinsScroll) {
recentPinsScroll.addEventListener('wheel', (e) => {
if (e.deltaY !== 0) {
e.preventDefault();
recentPinsScroll.scrollLeft += e.deltaY * 0.8;
}
}, { passive: false });
}
function renderPins() {
// Clear all except the add button
Array.from(pinsGrid.children).forEach(child => {
if (child.id !== 'add-pin-btn') child.remove();
});
pins.forEach(pin => {
const el = document.createElement('a');
el.className = 'pin-card';
el.href = pin.url;
el.dataset.id = pin.id;
const img = document.createElement('img');
img.className = 'pin-icon';
img.alt = pin.name;
setupFaviconFallback(img, pin.url, pin.favicon);
const label = document.createElement('span');
label.className = 'pin-label';
label.textContent = pin.name;
el.appendChild(img);
el.appendChild(label);
el.addEventListener('click', () => {
trackPinClick(pin.id);
});
// Drag and Drop Logic
el.setAttribute('draggable', 'true');
el.addEventListener('dragstart', function(e) {
dragSourceId = pin.id;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', dragSourceId);
setTimeout(() => el.classList.add('dragging'), 0);
});
el.addEventListener('dragover', function(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
});
el.addEventListener('drop', function(e) {
e.preventDefault();
e.stopPropagation();
if (dragSourceId && dragSourceId !== pin.id) {
const srcIndex = pins.findIndex(p => p.id === dragSourceId);
const tgtIndex = pins.findIndex(p => p.id === pin.id);
if (srcIndex > -1 && tgtIndex > -1) {
const draggedPin = pins.splice(srcIndex, 1)[0];
pins.splice(tgtIndex, 0, draggedPin);
savePins(); // which handles re-rendering
}
}
});
el.addEventListener('dragend', function() {
el.classList.remove('dragging');
dragSourceId = null;
});
// Make sure Add Button does not steal drops inappropriately
addPinBtn.addEventListener('dragover', e => e.preventDefault());
addPinBtn.addEventListener('drop', e => {
e.preventDefault();
const srcIndex = pins.findIndex(p => p.id === dragSourceId);
if (srcIndex > -1) {
const draggedPin = pins.splice(srcIndex, 1)[0];
pins.push(draggedPin); // drop at the very end
savePins();
}
});
el.addEventListener('contextmenu', (e) => {
e.preventDefault();
showContextMenu(e.pageX, e.pageY, pin.id);
});
pinsGrid.insertBefore(el, addPinBtn);
});
renderRecentApps();
}
// Pin Modal Methods
function openPinModal(editId = null) {
currentEditingPinId = editId;
if (editId) {
const pin = pins.find(p => p.id === editId);
pinUrlInput.value = pin.url;
pinNameInput.value = pin.name;
pinModalTitle.textContent = "Edit Pin";
} else {
pinUrlInput.value = '';
pinNameInput.value = '';
pinModalTitle.textContent = "Add Pin";
}
pinModal.classList.remove('hidden');
pinModalBackdrop.classList.remove('hidden');
pinUrlInput.focus();
}
function closePinModal() {
pinModal.classList.add('hidden');
pinModalBackdrop.classList.add('hidden');
}
addPinBtn.addEventListener('click', () => openPinModal(null));
cancelPinBtn.addEventListener('click', closePinModal);
pinModalBackdrop.addEventListener('click', closePinModal);
savePinBtn.addEventListener('click', () => {
let url = pinUrlInput.value.trim();
let name = pinNameInput.value.trim();
if (!url) return alert("URL is required");
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url;
}
try {
const hostname = extractDomain(url);
if (!name) name = hostname || url;
if (currentEditingPinId) {
const pin = pins.find(p => p.id === currentEditingPinId);
if (pin) {
pin.url = url;
pin.name = name;
}
} else {
pins.push({
id: Date.now().toString() + Math.random().toString(36).slice(2, 6),
url,
name
});
}
savePins();
closePinModal();
} catch (e) {
alert("Invalid URL structure: " + e.message);
}
});
// Context Menu Logic
function showContextMenu(x, y, id) {
contextTargetId = id;
ctxMenu.style.left = `${x}px`;
ctxMenu.style.top = `${y}px`;
ctxMenu.classList.remove('hidden');
}
document.addEventListener('click', (e) => {
if (!ctxMenu.contains(e.target)) {
ctxMenu.classList.add('hidden');
}
});
ctxOpen.addEventListener('click', () => {
const pin = pins.find(p => p.id === contextTargetId);
if (pin) {
trackPinClick(pin.id);
window.location.href = pin.url;
}
ctxMenu.classList.add('hidden');
});
ctxOpenNew.addEventListener('click', () => {
const pin = pins.find(p => p.id === contextTargetId);
if (pin) {
trackPinClick(pin.id);
window.open(pin.url, '_blank');
}
ctxMenu.classList.add('hidden');
});
if (ctxRefetch) {
ctxRefetch.addEventListener('click', () => {
const pin = pins.find(p => p.id === contextTargetId);
if (pin) {
delete pin.favicon;
savePins();
}
ctxMenu.classList.add('hidden');
});
}
ctxEdit.addEventListener('click', () => {
openPinModal(contextTargetId);
ctxMenu.classList.add('hidden');
});
ctxRemove.addEventListener('click', () => {
pins = pins.filter(p => p.id !== contextTargetId);
savePins();
ctxMenu.classList.add('hidden');
});
loadPins();
// ---- Search Logic ----
let searchDebounce;
function renderSearchResults(results) {
searchResults.innerHTML = '';
currentSearchResults = results;
selectedSearchIndex = -1;
if (results.length === 0) {
const q = searchInput.value;
if (q) {
const li = document.createElement('li');
li.className = 'search-result-item';
li.innerHTML = `<span class="result-title">Search Google for "${q}"</span>`;
li.onclick = () => doGoogleSearch(q);
searchResults.appendChild(li);
currentSearchResults = [{ type: 'google', query: q }];
}
searchDropdown.classList.toggle('hidden', results.length === 0 && !q);
return;
}
results.forEach((res, index) => {
const li = document.createElement('li');
li.className = 'search-result-item';
const img = document.createElement('img');
img.className = 'result-icon';
img.alt = res.title || 'Result';
setupFaviconFallback(img, res.url, res.favicon);
const textDiv = document.createElement('div');
textDiv.className = 'result-text';
const titleSpan = document.createElement('span');
titleSpan.className = 'result-title';
titleSpan.textContent = res.title;
const urlSpan = document.createElement('span');
urlSpan.className = 'result-url';
urlSpan.textContent = res.url;
textDiv.appendChild(titleSpan);
textDiv.appendChild(urlSpan);
li.appendChild(img);
li.appendChild(textDiv);
li.onclick = () => window.location.href = res.url;
searchResults.appendChild(li);
});
searchDropdown.classList.remove('hidden');
}
function doGoogleSearch(query) {
window.location.href = `https://www.google.com/search?q=${encodeURIComponent(query)}`;
}
searchInput.addEventListener('input', (e) => {
const q = e.target.value.toLowerCase().trim();
clearTimeout(searchDebounce);
if (!q) {
searchDropdown.classList.add('hidden');
return;
}
searchDebounce = setTimeout(() => {
// Find matches in pins
const pinMatches = pins.filter(p => p.name.toLowerCase().includes(q) || p.url.toLowerCase().includes(q)).map(p => ({
title: p.name,
url: p.url,
favicon: p.favicon
}));
// Find matches in bookmarks
if (chrome.bookmarks) {
chrome.bookmarks.search(q, (bmTree) => {
const bmMatches = bmTree.filter(bm => bm.url && (bm.title.toLowerCase().includes(q) || bm.url.toLowerCase().includes(q))).slice(0, 5).map(bm => ({
title: bm.title || bm.url,
url: bm.url,
favicon: null
}));
const finalResults = [...pinMatches, ...bmMatches].slice(0, 8);
renderSearchResults(finalResults);
});
} else {
renderSearchResults(pinMatches);
}
}, 150);
});
// Keyboard Navigation for Search
searchInput.addEventListener('keydown', (e) => {
const items = searchResults.querySelectorAll('.search-result-item');
if (!items.length) {
if (e.key === 'Enter' && searchInput.value) {
doGoogleSearch(searchInput.value);
}
return;
}
if (e.key === 'ArrowDown') {
e.preventDefault();
selectedSearchIndex = (selectedSearchIndex + 1) % items.length;
updateSearchSelection(items);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
selectedSearchIndex = (selectedSearchIndex - 1 + items.length) % items.length;
updateSearchSelection(items);
} else if (e.key === 'Enter') {
e.preventDefault();
if (selectedSearchIndex === -1) {
const res = currentSearchResults[0];
if (res.type === 'google') doGoogleSearch(res.query);
else window.location.href = res.url;
} else {
const res = currentSearchResults[selectedSearchIndex];
if (res.type === 'google') doGoogleSearch(res.query);
else window.location.href = res.url;
}
}
});
function updateSearchSelection(items) {
items.forEach((item, idx) => {
if (idx === selectedSearchIndex) {
item.classList.add('selected');
item.scrollIntoView({ block: 'nearest' });
} else {
item.classList.remove('selected');
}
});
}
// Hide dropdown when clicking outside
document.addEventListener('click', (e) => {
if (!searchInput.contains(e.target) && !searchDropdown.contains(e.target)) {
searchDropdown.classList.add('hidden');
}
});
});