Repository navigation
Expand file tree
/
Copy pathfloat.js
More file actions
648 lines (586 loc) · 19.4 KB
/
Copy pathfloat.js
File metadata and controls
648 lines (586 loc) · 19.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
// Storage keys
const STORAGE_KEYS = {
HISTORY: 'recentTabsHistory',
CONFIG: 'recentTabsConfig'
};
// i18n helper. The float UI is injected into the host page, where
// chrome.i18n is still available (content scripts have extension APIs).
function t(key, ...substitutions) {
if (typeof chrome !== 'undefined' && chrome.i18n && chrome.i18n.getMessage) {
const msg = chrome.i18n.getMessage(key, substitutions);
if (msg) return msg;
}
return key;
}
let container = null;
let isInjected = false;
// Track tab selection for cycling
let recentTabs = [];
let filteredTabs = [];
let selectedIndex = -1;
let searchQuery = '';
// Inject the floating UI
function injectUI() {
if (isInjected) return;
// Create container
container = document.createElement('div');
container.id = 'ert-float-container';
container.innerHTML = `
<div id="ert-float-content">
<div id="ert-float-header">
<h1>${t('recentTabs')}</h1>
<div id="ert-settings">
<label for="ert-history-size">${t('sizeLabel')}</label>
<select id="ert-history-size">
<option value="10">10</option>
<option value="20" selected>20</option>
<option value="30">30</option>
<option value="50">50</option>
</select>
<label class="ert-toggle-label">
<input type="checkbox" id="ert-auto-activate">
<span>${t('autoActivate')}</span>
</label>
</div>
<button id="ert-close-btn" title="${t('close')}">×</button>
</div>
<div id="ert-float-search">
<svg class="ert-search-icon" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M7 12A5 5 0 1 0 7 2a5 5 0 0 0 0 10Zm3.5-1.5L14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
</svg>
<input type="text" id="ert-search-input" placeholder="${t('searchPlaceholder')}" autocomplete="off" spellcheck="false">
<button id="ert-search-clear" title="${t('clear')}" hidden>×</button>
</div>
<div id="ert-float-list">
<div class="ert-loading">${t('loading')}</div>
</div>
<div id="ert-float-footer">
<div class="ert-shortcuts">
<span class="ert-shortcut">
<kbd>Alt</kbd>+<kbd>Q</kbd> ${t('cycleTabs')}
</span>
<span class="ert-shortcut">
<kbd>↑</kbd><kbd>↓</kbd> ${t('navigate')}
</span>
<span class="ert-shortcut">
<kbd>Enter</kbd> ${t('open')}
</span>
<span class="ert-shortcut">
<kbd>Esc</kbd> ${t('close')}
</span>
</div>
<button id="ert-clean-idle" class="ert-clean-idle" title="${t('cleanIdle')}" hidden>
<span class="ert-clean-idle-label">${t('cleanIdle')}</span>
<span class="ert-clean-idle-badge" id="ert-clean-idle-badge">0</span>
</button>
</div>
</div>
`;
// Add to DOM and mark as injected
document.body.appendChild(container);
isInjected = true;
// Add event listeners AFTER container is in DOM
document.getElementById('ert-close-btn').addEventListener('click', hideUI);
container.addEventListener('click', (e) => {
if (e.target === container) hideUI();
});
document.getElementById('ert-history-size').addEventListener('change', async (e) => {
const size = parseInt(e.target.value, 10);
const result = await chrome.storage.local.get(STORAGE_KEYS.CONFIG);
const config = result[STORAGE_KEYS.CONFIG] || { maxHistorySize: 20 };
config.maxHistorySize = size;
await chrome.storage.local.set({ [STORAGE_KEYS.CONFIG]: config });
});
document.getElementById('ert-auto-activate').addEventListener('change', async (e) => {
const autoActivate = e.target.checked;
const result = await chrome.storage.local.get(STORAGE_KEYS.CONFIG);
const config = result[STORAGE_KEYS.CONFIG] || { maxHistorySize: 20 };
config.autoActivateOnTimeout = autoActivate;
await chrome.storage.local.set({ [STORAGE_KEYS.CONFIG]: config });
});
const searchInput = document.getElementById('ert-search-input');
const searchClear = document.getElementById('ert-search-clear');
searchInput.addEventListener('input', (e) => {
setSearchQuery(e.target.value);
});
searchInput.addEventListener('keydown', handleSearchKeydown);
searchClear.addEventListener('click', () => {
setSearchQuery('');
searchInput.focus();
});
const cleanIdleBtn = document.getElementById('ert-clean-idle');
cleanIdleBtn.addEventListener('click', async () => {
cleanIdleBtn.disabled = true;
try {
const response = await chrome.runtime.sendMessage({ action: 'runIdleCleanupNow' });
if (response && response.success) {
flashCleanIdleResult(response.processed || 0, response.mode);
}
} catch (error) {
console.error('[ERT] Clean idle failed:', error);
} finally {
cleanIdleBtn.disabled = false;
await refreshIdleBadge();
}
});
// Keyboard events - add AFTER container is in DOM
document.addEventListener('keydown', handleKeydown);
}
// Remove the floating UI
function removeUI() {
if (container) {
container.remove();
container = null;
}
isInjected = false;
document.removeEventListener('keydown', handleKeydown);
}
// Show the floating UI
async function showUI(initialIndex = 0) {
console.log('[ERT] showUI called, isInjected:', isInjected, 'container:', !!container, 'initialIndex:', initialIndex);
if (!isInjected) {
injectUI();
}
container.classList.add('show');
recentTabs = await getRecentTabs();
console.log('[ERT] recentTabs loaded:', recentTabs.length, 'tabs');
// Reset search state on each open
const input = document.getElementById('ert-search-input');
const clearBtn = document.getElementById('ert-search-clear');
if (input) input.value = '';
if (clearBtn) clearBtn.hidden = true;
searchQuery = '';
selectedIndex = initialIndex;
await renderTabs();
// Focus the search input so typing starts filtering immediately.
// Defer to next frame so the browser accepts focus after the display change.
if (input) {
requestAnimationFrame(() => {
try { input.focus({ preventScroll: true }); } catch (_) { input.focus(); }
});
}
// Refresh the idle-cleanup badge in the footer.
refreshIdleBadge();
console.log('[ERT] showUI completed, selectedIndex:', selectedIndex);
}
// Ask the background script for the current idle-cleanup count and update the
// footer button's badge. Hides the button entirely when the feature is off.
async function refreshIdleBadge() {
const btn = document.getElementById('ert-clean-idle');
const badge = document.getElementById('ert-clean-idle-badge');
if (!btn || !badge) return;
try {
const response = await chrome.runtime.sendMessage({ action: 'getIdleState' });
if (!response || !response.success) {
btn.hidden = true;
return;
}
if (!response.enabled) {
btn.hidden = true;
return;
}
// Outside the configured active windows: hide the button entirely. The
// engine is paused, so offering a "Clean idle" action would be misleading.
if (response.inActiveWindow === false) {
btn.hidden = true;
return;
}
const count = response.idleCount || 0;
badge.textContent = String(count);
btn.hidden = false;
btn.title = response.mode === 'close'
? t('floatCleanIdleTitleClose', count, response.timeoutMinutes)
: t('floatCleanIdleTitleDiscard', count, response.timeoutMinutes);
} catch (error) {
// Background script may be unavailable (e.g. on restricted pages); just hide.
btn.hidden = true;
}
}
// Briefly show a result message on the clean-idle button.
function flashCleanIdleResult(n, mode) {
const btn = document.getElementById('ert-clean-idle');
if (!btn) return;
const label = btn.querySelector('.ert-clean-idle-label');
if (!label) return;
const original = label.textContent;
const text = n > 0
? (mode === 'close' ? t('statusTabsClosed', n) : t('statusTabsDiscarded', n))
: t('statusNothingToClean');
label.textContent = text;
setTimeout(() => { label.textContent = original; }, 1800);
}
// Hide the floating UI
function hideUI() {
if (container) {
container.classList.remove('show');
// Notify background script that popup is closed
chrome.runtime.sendMessage({ action: 'popupClosed' });
}
}
// Toggle the floating UI
async function toggleUI() {
if (container && container.classList.contains('show')) {
hideUI();
} else {
await showUI();
}
}
// Handle keydown events (global, when popup is open but focus isn't in search)
function handleKeydown(e) {
if (!container || !container.classList.contains('show')) {
return;
}
// When focus is inside the search input, handleSearchKeydown owns the key handling.
const searchInput = document.getElementById('ert-search-input');
if (searchInput && document.activeElement === searchInput) {
return;
}
// Escape closes
if (e.key === 'Escape') {
e.preventDefault();
e.stopPropagation();
hideUI();
return;
}
// Arrow navigation
if (e.key === 'ArrowDown') {
e.preventDefault();
e.stopPropagation();
moveSelection(1);
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
e.stopPropagation();
moveSelection(-1);
return;
}
// Enter to activate selected tab
if (e.key === 'Enter' && selectedIndex >= 0) {
e.preventDefault();
e.stopPropagation();
activateSelectedTab();
}
}
// Handle keydown while the search input is focused
function handleSearchKeydown(e) {
if (e.key === 'ArrowDown') {
e.preventDefault();
moveSelection(1);
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
moveSelection(-1);
return;
}
if (e.key === 'Enter') {
e.preventDefault();
if (selectedIndex >= 0) activateSelectedTab();
return;
}
if (e.key === 'Escape') {
e.preventDefault();
if (searchQuery) {
setSearchQuery('');
} else {
hideUI();
}
}
}
// Move selection within filteredTabs
function moveSelection(delta) {
if (filteredTabs.length === 0) return;
selectedIndex = (selectedIndex + delta + filteredTabs.length) % filteredTabs.length;
updateSelection();
}
// Update the search query, refilter, and cancel any auto-activate timer in the background
function setSearchQuery(query) {
const previous = searchQuery;
searchQuery = query;
const input = document.getElementById('ert-search-input');
const clearBtn = document.getElementById('ert-search-clear');
if (input && input.value !== query) input.value = query;
if (clearBtn) clearBtn.hidden = !query;
// Once the user starts searching, the Alt+Q cycle context is no longer meaningful.
// Tell the background script so it stops the auto-activate timer.
if (query && !previous) {
try {
chrome.runtime.sendMessage({ action: 'cancelCycleTimer' });
} catch (_) {
// background may be sleeping; safe to ignore
}
}
applyFilter();
renderList();
}
// Rebuild filteredTabs from recentTabs + searchQuery
function applyFilter() {
if (!searchQuery.trim()) {
filteredTabs = recentTabs.map((tab, originalIndex) => ({
tab,
originalIndex,
score: 0,
titleMatches: [],
urlMatches: []
}));
if (filteredTabs.length === 0) {
selectedIndex = -1;
} else if (selectedIndex < 0 || selectedIndex >= filteredTabs.length) {
selectedIndex = 0;
}
return;
}
const query = searchQuery.trim();
const results = [];
for (let i = 0; i < recentTabs.length; i++) {
const tab = recentTabs[i];
const titleMatch = fuzzyMatch(query, tab.title || '');
const urlMatch = fuzzyMatch(query, tab.url || '');
if (!titleMatch && !urlMatch) continue;
// Weight title matches higher than URL matches
const titleScore = titleMatch ? titleMatch.score : -Infinity;
const urlScore = urlMatch ? urlMatch.score - 15 : -Infinity;
const score = Math.max(titleScore, urlScore);
results.push({
tab,
originalIndex: i,
score,
titleMatches: titleMatch ? titleMatch.positions : [],
urlMatches: urlMatch ? urlMatch.positions : []
});
}
results.sort((a, b) => b.score - a.score);
filteredTabs = results;
selectedIndex = filteredTabs.length > 0 ? 0 : -1;
}
// Fuzzy match: return {score, positions} or null.
// Rewards: consecutive matches, matches at word boundaries, matches near start.
function fuzzyMatch(query, text) {
if (!query) return { score: 0, positions: [] };
if (!text) return null;
const q = query.toLowerCase();
const t = text.toLowerCase();
// Fast path: substring hit is the best possible, reward it strongly.
const substringIdx = t.indexOf(q);
if (substringIdx !== -1) {
const positions = [];
for (let i = 0; i < q.length; i++) positions.push(substringIdx + i);
let score = 100 + q.length * 4;
if (substringIdx === 0) score += 20;
else if (!isWordChar(t[substringIdx - 1])) score += 10;
return { score, positions };
}
// Subsequence match with bonuses
const positions = [];
let qi = 0;
let score = 0;
let prevMatchIdx = -2;
for (let ti = 0; ti < t.length && qi < q.length; ti++) {
if (t[ti] === q[qi]) {
positions.push(ti);
let bonus = 1;
if (ti === prevMatchIdx + 1) bonus += 5; // consecutive
if (ti === 0 || !isWordChar(t[ti - 1])) bonus += 3; // word boundary
if (ti < 4) bonus += 2; // near start
score += bonus;
prevMatchIdx = ti;
qi++;
}
}
if (qi < q.length) return null;
// Penalize spread — first-to-last distance vs query length
const spread = positions[positions.length - 1] - positions[0];
score -= Math.max(0, spread - q.length) * 0.2;
return { score, positions };
}
function isWordChar(ch) {
if (!ch) return false;
return /[a-z0-9]/i.test(ch);
}
// Update the visual selection
function updateSelection() {
const items = document.querySelectorAll('.ert-tab-item');
items.forEach((item, index) => {
if (index === selectedIndex) {
item.classList.add('selected');
item.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
} else {
item.classList.remove('selected');
}
});
}
// Activate the currently selected tab
async function activateSelectedTab() {
if (selectedIndex < 0 || selectedIndex >= filteredTabs.length) {
hideUI();
return;
}
const tab = filteredTabs[selectedIndex].tab;
try {
const response = await chrome.runtime.sendMessage({
action: 'switchToTab',
tabId: tab.id
});
if (response && response.success) {
hideUI();
}
} catch (error) {
console.error('Error switching to tab:', error);
hideUI();
}
}
// Get recent tabs from storage
async function getRecentTabs() {
const result = await chrome.storage.local.get(STORAGE_KEYS.HISTORY);
return result[STORAGE_KEYS.HISTORY] || [];
}
// Get config from storage
async function getConfig() {
const result = await chrome.storage.local.get(STORAGE_KEYS.CONFIG);
return result[STORAGE_KEYS.CONFIG] || { maxHistorySize: 20 };
}
// Create a tab item element
function createTabItem(entry) {
const { tab, titleMatches, urlMatches } = entry;
const item = document.createElement('div');
item.className = 'ert-tab-item';
// Favicon
const favicon = document.createElement('div');
favicon.className = 'ert-favicon';
if (tab.favIconUrl) {
const img = document.createElement('img');
img.src = tab.favIconUrl;
img.alt = '';
img.width = 20;
img.height = 20;
favicon.appendChild(img);
} else {
favicon.classList.add('missing');
favicon.textContent = '📄';
}
// Tab info
const tabInfo = document.createElement('div');
tabInfo.className = 'ert-tab-info';
const title = document.createElement('div');
title.className = 'ert-tab-title';
renderHighlighted(title, tab.title || t('untitled'), titleMatches);
const url = document.createElement('div');
url.className = 'ert-tab-url';
renderHighlighted(url, tab.url || '', urlMatches);
tabInfo.appendChild(title);
tabInfo.appendChild(url);
item.appendChild(favicon);
item.appendChild(tabInfo);
// Click handler - switch to tab
item.addEventListener('click', async () => {
try {
const response = await chrome.runtime.sendMessage({
action: 'switchToTab',
tabId: tab.id
});
if (response && response.success) {
hideUI();
}
} catch (error) {
console.error('Error switching to tab:', error);
}
});
return item;
}
// Render text into `el`, wrapping matched character positions in <mark>
function renderHighlighted(el, text, positions) {
el.textContent = '';
if (!positions || positions.length === 0) {
el.textContent = text;
return;
}
const set = new Set(positions);
let i = 0;
while (i < text.length) {
if (set.has(i)) {
const mark = document.createElement('mark');
mark.className = 'ert-match';
let j = i;
while (j < text.length && set.has(j)) j++;
mark.textContent = text.slice(i, j);
el.appendChild(mark);
i = j;
} else {
let j = i;
while (j < text.length && !set.has(j)) j++;
el.appendChild(document.createTextNode(text.slice(i, j)));
i = j;
}
}
}
// Render the tabs list from filteredTabs
function renderList() {
const list = document.getElementById('ert-float-list');
if (!list) return;
list.innerHTML = '';
if (recentTabs.length === 0) {
list.innerHTML = `
<div class="ert-empty">
<p>${t('noRecentTabs')}</p>
<p class="ert-hint">${t('startBrowsingHint')}</p>
</div>
`;
return;
}
if (filteredTabs.length === 0) {
const empty = document.createElement('div');
empty.className = 'ert-empty';
const p1 = document.createElement('p');
p1.textContent = t('noMatches');
const p2 = document.createElement('p');
p2.className = 'ert-hint';
p2.textContent = t('noMatchHint', searchQuery);
empty.appendChild(p1);
empty.appendChild(p2);
list.appendChild(empty);
return;
}
filteredTabs.forEach((entry) => {
list.appendChild(createTabItem(entry));
});
updateSelection();
}
// Render the tabs list and settings state (called on show / when config loads)
async function renderTabs() {
applyFilter();
renderList();
const config = await getConfig();
const selector = document.getElementById('ert-history-size');
if (selector) {
selector.value = config.maxHistorySize || 20;
}
const autoActivateCheckbox = document.getElementById('ert-auto-activate');
if (autoActivateCheckbox) {
autoActivateCheckbox.checked = config.autoActivateOnTimeout || false;
}
}
// Listen for messages from background script
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
console.log('[ERT] Received message:', message);
if (message.action === 'showFloat') {
showUI(message.initialIndex || 0);
sendResponse({ success: true });
} else if (message.action === 'cycleSelection') {
console.log('[ERT] Cycling selection to index:', message.selectedIndex);
// Cycle acts on the full recent-tabs list. If a search filter is active, clear it first.
if (searchQuery) {
setSearchQuery('');
}
selectedIndex = message.selectedIndex;
updateSelection();
sendResponse({ success: true });
} else if (message.action === 'hideFloat') {
hideUI();
sendResponse({ success: true });
} else if (message.action === 'toggleFloat') {
toggleUI();
sendResponse({ success: true });
}
return true; // Keep message channel open for async response
});