-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
650 lines (553 loc) · 20.2 KB
/
popup.js
File metadata and controls
650 lines (553 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
// Popup script for Link Fetch extension
document.addEventListener('DOMContentLoaded', function() {
// Get UI elements
const fetchButton = document.getElementById('fetchLinks');
const copyButton = document.getElementById('copyLinks');
const clearButton = document.getElementById('clearLinks');
const filterInput = document.getElementById('filterInput');
const sortOption = document.getElementById('sortOption');
const linksList = document.getElementById('linksList');
const statusElement = document.getElementById('status');
const statsBar = document.getElementById('statsBar');
const linkCountElement = document.getElementById('linkCount');
const domainCountElement = document.getElementById('domainCount');
const themeToggle = document.getElementById('themeToggle');
const linksContainer = document.querySelector('.links-container');
const emptyState = document.getElementById('emptyState');
// Store links
let links = [];
let linkTimestamps = {};
function setEmptyState(isEmpty) {
if (!linksContainer || !emptyState) {
return;
}
linksContainer.classList.toggle('is-collapsed', isEmpty);
linksContainer.classList.toggle('has-content', !isEmpty);
emptyState.hidden = !isEmpty;
}
function toError(err) {
if (!err) {
return new Error('Unknown error');
}
if (err instanceof Error) {
return err;
}
if (typeof err === 'string') {
return new Error(err);
}
return new Error(err.message || 'Unknown error');
}
function injectContentScript(tabId, callback) {
chrome.scripting.executeScript({
target: { tabId },
files: ['content.js']
}, () => {
if (chrome.runtime.lastError) {
callback(toError(chrome.runtime.lastError));
} else {
callback();
}
});
}
function requestLinksFromTab(tabId, callback) {
if (typeof tabId !== 'number') {
callback(new Error('No active tab available'));
return;
}
const message = { action: 'getLinks' };
chrome.tabs.sendMessage(tabId, message, (response) => {
const firstError = chrome.runtime.lastError;
if (firstError && firstError.message && firstError.message.includes('Receiving end does not exist')) {
injectContentScript(tabId, (injectError) => {
if (injectError) {
callback(injectError);
return;
}
chrome.tabs.sendMessage(tabId, message, (retryResponse) => {
if (chrome.runtime.lastError) {
callback(toError(chrome.runtime.lastError));
} else {
callback(null, retryResponse);
}
});
});
} else if (firstError) {
callback(toError(firstError));
} else {
callback(null, response);
}
});
}
// Check if dark mode is enabled
function initTheme() {
chrome.storage.local.get(['darkMode'], function(result) {
if (result.darkMode) {
document.body.classList.add('dark-theme');
themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
themeToggle.title = 'Switch to light mode';
} else {
document.body.classList.remove('dark-theme');
themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
themeToggle.title = 'Switch to dark mode';
}
});
}
// Initialize theme
initTheme();
// Toggle dark mode
themeToggle.addEventListener('click', function() {
const isDarkMode = document.body.classList.contains('dark-theme');
if (isDarkMode) {
document.body.classList.remove('dark-theme');
themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
themeToggle.title = 'Switch to dark mode';
chrome.storage.local.set({ 'darkMode': false });
} else {
document.body.classList.add('dark-theme');
themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
themeToggle.title = 'Switch to light mode';
chrome.storage.local.set({ 'darkMode': true });
}
// Add animation to theme toggle button
themeToggle.classList.add('pulse-animation');
setTimeout(() => {
themeToggle.classList.remove('pulse-animation');
}, 300);
});
// Load saved links
chrome.storage.local.get(['links', 'linkTimestamps'], function(result) {
if (result.links && result.links.length > 0) {
links = result.links;
linkTimestamps = result.linkTimestamps || {};
setEmptyState(false);
displayLinks(links);
updateStats(links);
} else {
showEmptyMessage();
}
});
// Add check links button to verify if links are still working
const checkLinksButton = document.createElement('button');
checkLinksButton.innerHTML = '<i class="fas fa-check-circle"></i> Check Links';
checkLinksButton.title = 'Check for broken links';
checkLinksButton.id = 'checkLinks';
checkLinksButton.style.marginTop = '12px';
checkLinksButton.style.width = '100%';
checkLinksButton.style.background = 'var(--success-color)';
checkLinksButton.className = 'success-button';
// Add the button after the stats bar
statsBar.parentNode.insertBefore(checkLinksButton, statsBar.nextSibling);
// Check links functionality
checkLinksButton.addEventListener('click', function() {
if (links.length === 0) {
showStatus('No links to check', 'error');
return;
}
// Show loading state with animation
checkLinksButton.disabled = true;
checkLinksButton.innerHTML = '<span class="loading-spinner"></span> Checking...';
checkLinksButton.classList.add('pulse-animation');
// We'll send the links to the background script to check them
chrome.runtime.sendMessage({
action: "checkLinks",
links: links
}, function(response) {
// Reset button state
checkLinksButton.disabled = false;
checkLinksButton.innerHTML = '<i class="fas fa-check-circle"></i> Check Links';
checkLinksButton.classList.remove('pulse-animation');
if (response && response.results) {
// Update the UI to reflect broken links
markBrokenLinks(response.results);
const brokenCount = Object.values(response.results).filter(status => !status).length;
if (brokenCount > 0) {
showStatus(`Found ${brokenCount} broken link${brokenCount !== 1 ? 's' : ''}`, 'warning');
// Highlight the broken links with a pulse animation
const brokenLinks = document.querySelectorAll('.broken-link');
brokenLinks.forEach(link => {
link.classList.add('pulse-animation');
setTimeout(() => link.classList.remove('pulse-animation'), 1000);
});
} else {
showStatus('All links are working!');
}
} else {
showStatus('Failed to check links', 'error');
}
});
});
// Function to mark broken links in the UI
function markBrokenLinks(results) {
// Find all link items in the list
const linkItems = document.querySelectorAll('#linksList li');
linkItems.forEach(item => {
// Get the URL from the link item's text content
const linkText = item.querySelector('.link-item').textContent;
// If we have a result for this link and it's broken
if (results[linkText] === false) {
// Add a broken link indicator
item.classList.add('broken-link');
// Add a warning icon
const warningIcon = document.createElement('span');
warningIcon.className = 'broken-link-icon';
warningIcon.innerHTML = '<i class="fas fa-exclamation-triangle"></i>';
warningIcon.title = 'This link appears to be broken';
// Add it after the favicon
const linkItem = item.querySelector('.link-item');
if (linkItem.querySelector('.favicon')) {
linkItem.insertBefore(warningIcon, linkItem.querySelector('.favicon').nextSibling);
} else {
linkItem.insertBefore(warningIcon, linkItem.firstChild);
}
}
});
}
// Fetch links from current tab
fetchButton.addEventListener('click', function() {
// Show loading state
fetchButton.disabled = true;
fetchButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Fetching...';
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
const activeTab = tabs && tabs[0];
requestLinksFromTab(activeTab ? activeTab.id : undefined, (error, response) => {
// Reset button state
fetchButton.disabled = false;
fetchButton.innerHTML = '<i class="fas fa-download"></i> Fetch Links';
if (error) {
showStatus('Error: ' + error.message, 'error');
return;
}
const newLinks = (response && response.links) ? response.links : [];
// Replace stored links with the current tab's results, keeping unique order
const uniqueLinks = [];
const seen = new Set();
newLinks.forEach(link => {
if (!seen.has(link)) {
seen.add(link);
uniqueLinks.push(link);
}
});
links = uniqueLinks;
// Build timestamps for date sorting while preserving order
const timestampBase = Date.now();
const newTimestamps = {};
uniqueLinks.forEach((link, index) => {
newTimestamps[link] = timestampBase + index;
});
// Save links and timestamps
linkTimestamps = newTimestamps;
chrome.storage.local.set({
'links': links,
'linkTimestamps': linkTimestamps
});
// Display links
displayLinks(links);
updateStats(links);
// Update badge
chrome.runtime.sendMessage({ action: "updateBadge" });
// Show success message with count
const newCount = uniqueLinks.length;
if (newCount > 0) {
showStatus(`Found ${newCount} link${newCount !== 1 ? 's' : ''}`);
} else {
showStatus('No new links found');
}
});
});
});
// Copy all links
copyButton.addEventListener('click', function() {
if (links.length === 0) {
showStatus('No links to copy', 'error');
return;
}
// Get filtered links if filter is active
const filterText = filterInput.value.toLowerCase();
const linksToCopy = filterText ?
links.filter(link => link.toLowerCase().includes(filterText)) :
links;
const textToCopy = linksToCopy.join('\n');
navigator.clipboard.writeText(textToCopy)
.then(() => {
// Visual feedback
copyButton.innerHTML = '<i class="fas fa-check"></i> Copied!';
setTimeout(() => {
copyButton.innerHTML = '<i class="fas fa-copy"></i> Copy All';
}, 1500);
showStatus(`Copied ${linksToCopy.length} links to clipboard`);
})
.catch(err => {
showStatus('Failed to copy: ' + err, 'error');
});
});
// Clear all links
clearButton.addEventListener('click', function() {
if (links.length === 0) {
showStatus('No links to clear', 'error');
return;
}
// Add confirmation
if (confirm(`Are you sure you want to clear all ${links.length} links?`)) {
links = [];
chrome.storage.local.set({ 'links': links, 'linkTimestamps': {} });
showEmptyMessage();
statsBar.style.display = 'none';
showStatus('All links cleared');
// Update badge
chrome.runtime.sendMessage({ action: "updateBadge" });
}
});
// Filter links
filterInput.addEventListener('input', function() {
const filterText = this.value.toLowerCase();
const filteredLinks = links.filter(link =>
link.toLowerCase().includes(filterText)
);
displayLinks(filteredLinks);
// Update the link count in stats bar to show filtered count
if (filterText) {
linkCountElement.textContent = `${filteredLinks.length} of ${links.length} links`;
} else {
updateStats(links);
}
});
// Sort links
sortOption.addEventListener('change', function() {
displayLinks(links);
});
// Keyboard shortcuts
window.addEventListener('keydown', function(event) {
// Ctrl+F or Cmd+F to focus the filter input
if ((event.ctrlKey || event.metaKey) && event.key === 'f') {
event.preventDefault(); // Prevent browser's find function
filterInput.focus();
}
// Escape to clear filter
if (event.key === 'Escape' && document.activeElement === filterInput) {
filterInput.value = '';
displayLinks(links);
updateStats(links);
}
});
// Function to update stats bar
function updateStats(linksArr) {
if (linksArr.length === 0) {
statsBar.style.display = 'none';
return;
}
// Count unique domains
const domains = new Set();
linksArr.forEach(link => {
try {
const url = new URL(link);
domains.add(url.hostname);
} catch (e) {
// Skip invalid URLs
}
});
// Update stats display
linkCountElement.textContent = `${linksArr.length} link${linksArr.length !== 1 ? 's' : ''}`;
domainCountElement.textContent = `${domains.size} domain${domains.size !== 1 ? 's' : ''}`;
statsBar.style.display = 'flex';
}
// Function to display links
function displayLinks(linksToDisplay) {
linksList.innerHTML = '';
if (linksToDisplay.length === 0) {
if (links.length === 0) {
showEmptyMessage();
} else {
setEmptyState(false);
const emptyFilter = document.createElement('li');
emptyFilter.className = 'empty-filter';
emptyFilter.textContent = 'No links match your current filters.';
linksList.appendChild(emptyFilter);
}
return;
}
setEmptyState(false);
const sortType = sortOption.value;
let sortedLinks = [...linksToDisplay];
// Sort according to selection
if (sortType === 'alphabetical') {
sortedLinks.sort();
} else if (sortType === 'domain') {
// Group by domain
const linksByDomain = {};
sortedLinks.forEach(link => {
try {
const url = new URL(link);
const domain = url.hostname;
if (!linksByDomain[domain]) {
linksByDomain[domain] = [];
}
linksByDomain[domain].push(link);
} catch (e) {
// Skip invalid URLs
}
});
// Display domain groups
const frag = document.createDocumentFragment();
Object.keys(linksByDomain).sort().forEach(domain => {
const domainLinks = linksByDomain[domain];
// Create domain header
const domainGroup = document.createElement('div');
domainGroup.className = 'domain-group';
domainGroup.setAttribute('aria-label', `Domain group: ${domain} with ${domainLinks.length} links`);
// Add favicon
const favicon = document.createElement('img');
favicon.src = `https://www.google.com/s2/favicons?domain=${domain}&sz=16`;
favicon.className = 'favicon';
favicon.alt = '';
domainGroup.appendChild(favicon);
// Add domain text
domainGroup.appendChild(document.createTextNode(' ' + domain + ' '));
// Add count badge
const badge = document.createElement('span');
badge.className = 'badge';
badge.textContent = domainLinks.length;
domainGroup.appendChild(badge);
frag.appendChild(domainGroup);
// Add links for this domain
domainLinks.forEach(link => {
frag.appendChild(addLinkItem(link));
});
});
linksList.appendChild(frag);
return; // We've handled the display
} else if (sortType === 'date') {
// If we have stored timestamps, sort by those (newest first)
const timestamps = linkTimestamps;
sortedLinks.sort((a, b) => {
const timeA = timestamps[a] || 0;
const timeB = timestamps[b] || 0;
return timeB - timeA; // Descending order (newest first)
});
const frag = document.createDocumentFragment();
sortedLinks.forEach(link => {
frag.appendChild(addLinkItem(link));
});
linksList.appendChild(frag);
return;
}
// Default display (for default or alphabetical sort)
const frag = document.createDocumentFragment();
sortedLinks.forEach(link => {
frag.appendChild(addLinkItem(link));
});
linksList.appendChild(frag);
}
// Function to add a single link item to the list
function addLinkItem(link) {
// Create list item
const li = document.createElement('li');
li.tabIndex = 0; // Make focusable for keyboard navigation
// Create link display area
const linkItem = document.createElement('div');
linkItem.className = 'link-item';
// Try to extract domain for favicon
let domain = '';
try {
const url = new URL(link);
domain = url.hostname;
} catch (e) {
// If not a valid URL, skip favicon
}
// Add favicon if we have a domain
if (domain) {
const favicon = document.createElement('img');
favicon.src = `https://www.google.com/s2/favicons?domain=${domain}&sz=16`;
favicon.className = 'favicon';
favicon.alt = '';
linkItem.appendChild(favicon);
}
// Add text content (the URL)
linkItem.appendChild(document.createTextNode(link));
// Add click handler to copy link
linkItem.addEventListener('click', function() {
navigator.clipboard.writeText(link).then(() => {
showStatus(`Copied: ${link}`);
});
});
li.appendChild(linkItem);
// Create action buttons container
const actions = document.createElement('div');
actions.className = 'link-actions';
// Copy button
const copyBtn = document.createElement('button');
copyBtn.innerHTML = '<i class="fas fa-copy"></i>';
copyBtn.title = 'Copy link';
copyBtn.setAttribute('aria-label', 'Copy link');
copyBtn.addEventListener('click', function(e) {
e.stopPropagation(); // Prevent triggering the li click
navigator.clipboard.writeText(link).then(() => {
showStatus(`Copied: ${link}`);
});
});
actions.appendChild(copyBtn);
// Open button
const openBtn = document.createElement('button');
openBtn.innerHTML = '<i class="fas fa-external-link-alt"></i>';
openBtn.title = 'Open link in new tab';
openBtn.setAttribute('aria-label', 'Open link in new tab');
openBtn.addEventListener('click', function(e) {
e.stopPropagation(); // Prevent triggering the li click
chrome.tabs.create({ url: link });
});
actions.appendChild(openBtn);
// Delete button
const deleteBtn = document.createElement('button');
deleteBtn.innerHTML = '<i class="fas fa-times"></i>';
deleteBtn.title = 'Remove link';
deleteBtn.setAttribute('aria-label', 'Remove link');
deleteBtn.addEventListener('click', function(e) {
e.stopPropagation(); // Prevent triggering the li click
// Remove from array
const index = links.indexOf(link);
if (index > -1) {
const [removed] = links.splice(index, 1);
if (removed) {
delete linkTimestamps[removed];
}
// Update storage
chrome.storage.local.set({ 'links': links, 'linkTimestamps': linkTimestamps }, function() {
// Update UI
li.classList.add('removing');
// Animate removal
setTimeout(() => {
li.remove();
// Update stats
updateStats(links);
if (links.length === 0) {
showEmptyMessage();
}
}, 300);
showStatus('Link removed');
// Update badge
chrome.runtime.sendMessage({ action: "updateBadge" });
});
}
});
actions.appendChild(deleteBtn);
li.appendChild(actions);
return li;
}
// Show empty message
function showEmptyMessage() {
setEmptyState(true);
if (linksList) {
linksList.innerHTML = '';
}
}
// Show status message
function showStatus(message, type = 'success') {
statusElement.textContent = message;
statusElement.className = 'status ' + type;
// Show the message
statusElement.style.opacity = '1';
// Hide after delay
setTimeout(() => {
statusElement.style.opacity = '0';
}, 3000);
}
});