-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathentries-tab.js
716 lines (621 loc) · 23.3 KB
/
entries-tab.js
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
import { filterEntries, addToArchiveBox, downloadCsv, downloadJson } from './utils.js';
export async function renderEntries(filterText = '', tagFilter = '') {
const { entries = [] } = await chrome.storage.local.get('entries');
if (!window.location.search.includes(filterText)) {
window.history.pushState({}, '', `?search=${filterText}`);
}
// Apply filters
let filteredEntries = entries;
if (tagFilter) {
filteredEntries = entries.filter(entry => entry.tags.includes(tagFilter));
}
filteredEntries = filterEntries(filteredEntries, filterText);
// Display filtered entries
const entriesList = document.getElementById('entriesList');
entriesList.innerHTML = filteredEntries.map(entry => `
<div class="list-group-item">
<div class="row">
<small class="col-lg-2" style="display: block;min-width: 151px;text-align: center;">
${new Date(entry.timestamp).toISOString().replace('T', ' ').split('.')[0]}
</small>
<h5 class="col-lg-7">
<a href="${entry.url}" target="_blank" name="${entry.id}" id="${entry.id}"><img src="${entry.favicon}" class="favicon"/><code>${entry.url}</code></a>
</h5>
<div class="col-lg-3">
${entry.tags.length ? `
<p class="mb-1">
${entry.tags.map(tag =>
`<span class="badge bg-secondary me-1 tag-filter" role="button" data-tag="${tag}">${tag}</span>`
).join('')}
</p>
` : ''}
</div>
</div>
</div>
`).join('');
// Add click handlers for tag filtering
document.querySelectorAll('.tag-filter').forEach(tag => {
tag.addEventListener('click', () => {
const tagText = tag.dataset.tag;
const filterInput = document.getElementById('filterInput');
filterInput.value = tagText;
renderEntries(tagText);
});
});
}
export function initializeEntriesTab() {
let selectedEntries = new Set();
let filteredTags = [];
let selectedTagIndex = -1;
// Initialize tag autocomplete and modal functionality
async function initializeTagModal() {
const modal = document.getElementById('editTagsModal');
const input = document.getElementById('addTagInput');
const dropdown = document.getElementById('tagAutocomplete');
const currentTagsList = document.getElementById('currentTagsList');
// Update current tags whenever modal is shown
modal.addEventListener('show.bs.modal', async () => {
await updateCurrentTagsList();
input.value = '';
dropdown.style.display = 'none';
});
// Handle tag input with autocomplete
input.addEventListener('input', async () => {
const inputValue = input.value.toLowerCase().trim();
if (!inputValue) {
dropdown.style.display = 'none';
return;
}
const allTags = await getAllUniqueTags();
const currentTags = getCurrentModalTags();
// Filter tags that match input and aren't already used
filteredTags = allTags
.filter(tag =>
tag.toLowerCase().includes(inputValue) &&
!currentTags.includes(tag)
)
.slice(0, 5); // Limit to 5 suggestions
if (filteredTags.length === 0) {
dropdown.style.display = 'none';
} else {
dropdown.innerHTML = filteredTags
.map((tag, index) => `
<div class="dropdown-item ${index === selectedTagIndex ? 'active' : ''}"
role="button" data-tag="${tag}">
${tag}
</div>
`)
.join('');
dropdown.style.display = 'block';
}
});
// Handle keyboard navigation
input.addEventListener('keydown', async (e) => {
if (e.key === 'Escape') {
dropdown.style.display = 'none';
selectedTagIndex = -1;
return;
}
if (e.key === 'Enter') {
e.preventDefault();
if (selectedTagIndex >= 0 && filteredTags.length > 0) {
await addTagToModal(filteredTags[selectedTagIndex]);
} else if (input.value.trim()) {
await addTagToModal(input.value.trim());
}
input.value = '';
dropdown.style.display = 'none';
selectedTagIndex = -1;
return;
}
if (!filteredTags.length) return;
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
selectedTagIndex = Math.min(selectedTagIndex + 1, filteredTags.length - 1);
updateDropdownSelection();
break;
case 'ArrowUp':
e.preventDefault();
selectedTagIndex = Math.max(selectedTagIndex - 1, -1);
updateDropdownSelection();
break;
}
});
// Handle click selection in dropdown
dropdown.addEventListener('click', async (e) => {
const item = e.target.closest('.dropdown-item');
if (item) {
await addTagToModal(item.dataset.tag);
input.value = '';
dropdown.style.display = 'none';
selectedTagIndex = -1;
}
});
// Save changes button
document.getElementById('saveTagChanges').addEventListener('click', async () => {
const { entries = [] } = await chrome.storage.local.get('entries');
const newTags = getCurrentModalTags();
// Update tags for all selected entries
entries.forEach(entry => {
if (selectedEntries.has(entry.id)) {
entry.tags = [...newTags];
}
});
await chrome.storage.local.set({ entries });
// Close modal and refresh view
const modalInstance = bootstrap.Modal.getInstance(modal);
modalInstance.hide();
await renderEntries();
});
}
async function getAllUniqueTags() {
const { entries = [] } = await chrome.storage.local.get('entries');
return [...new Set(entries.flatMap(entry => entry.tags))]
.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
}
function getCurrentModalTags() {
return Array.from(
document.getElementById('currentTagsList')
.querySelectorAll('.badge')
).map(badge => badge.dataset.tag);
}
function updateDropdownSelection() {
const dropdown = document.getElementById('tagAutocomplete');
dropdown.querySelectorAll('.dropdown-item').forEach((item, index) => {
item.classList.toggle('active', index === selectedTagIndex);
});
}
async function updateCurrentTagsList() {
const { entries = [] } = await chrome.storage.local.get('entries');
const selectedEntriesArray = entries.filter(e => selectedEntries.has(e.id));
// Get tags that exist in ALL selected entries
const commonTags = selectedEntriesArray.reduce((acc, entry) => {
if (!acc) return new Set(entry.tags);
return new Set([...acc].filter(tag => entry.tags.includes(tag)));
}, null);
const tagsList = document.getElementById('currentTagsList');
tagsList.innerHTML = commonTags ?
Array.from(commonTags)
.map(tag => `
<span class="badge bg-secondary me-1 mb-1" role="button" data-tag="${tag}">
${tag} <i class="bi bi-x"></i>
</span>
`)
.join('') : '';
// Add click handlers for tag removal
tagsList.querySelectorAll('.badge').forEach(badge => {
badge.addEventListener('click', () => {
badge.remove();
});
});
}
async function addTagToModal(tag) {
const currentTags = getCurrentModalTags();
if (!currentTags.includes(tag)) {
const tagsList = document.getElementById('currentTagsList');
const newTag = document.createElement('span');
newTag.className = 'badge bg-secondary me-1 mb-1';
newTag.setAttribute('role', 'button');
newTag.dataset.tag = tag;
newTag.innerHTML = `${tag} <i class="bi bi-x"></i>`;
newTag.addEventListener('click', () => newTag.remove());
tagsList.appendChild(newTag);
}
}
function updateSelectionCount() {
const count = selectedEntries.size;
// Update count in main view
document.getElementById('selectedUrlCount').textContent = count;
// Update count in modal
document.getElementById('selectedUrlCountModal').textContent = count;
}
function updateActionButtonStates() {
const hasSelection = selectedEntries.size > 0;
// Update all action buttons based on selection state
[
'downloadCsv',
'downloadJson',
'deleteFiltered',
'syncFiltered',
'editTags'
].forEach(buttonId => {
const button = document.getElementById(buttonId);
if (button) {
button.disabled = !hasSelection;
// Add visual feedback for disabled state
button.classList.toggle('opacity-50', !hasSelection);
}
});
}
// Add handler for "Select All" checkbox in header if it exists
const selectAllCheckbox = document.getElementById('selectAllUrls');
if (selectAllCheckbox) {
selectAllCheckbox.addEventListener('click', async () => {
const { entries = [] } = await chrome.storage.local.get('entries');
const filterText = document.getElementById('filterInput').value.toLowerCase();
// Get currently filtered entries
const filteredEntries = entries.filter(entry => {
const searchableText = [
entry.url,
entry.title,
entry.id,
...entry.tags
].join(' ').toLowerCase();
return searchableText.includes(filterText);
});
// If all filtered entries are selected, deselect all
const allFilteredSelected = filteredEntries.every(entry =>
selectedEntries.has(entry.id)
);
if (allFilteredSelected) {
// Deselect only the filtered entries
filteredEntries.forEach(entry => {
selectedEntries.delete(entry.id);
});
} else {
// Select all filtered entries
filteredEntries.forEach(entry => {
selectedEntries.add(entry.id);
});
}
await renderEntries();
});
}
// Add handler for "Deselect All" button
const deselectAllButton = document.getElementById('deselectAllUrls');
if (deselectAllButton) {
deselectAllButton.addEventListener('click', () => {
selectedEntries.clear();
renderEntries();
});
}
// Add handler for individual checkbox changes
document.getElementById('entriesList').addEventListener('change', (e) => {
if (e.target.classList.contains('entry-checkbox')) {
if (e.target.checked) {
selectedEntries.add(e.target.value);
} else {
selectedEntries.delete(e.target.value);
}
updateSelectionCount();
updateActionButtonStates();
}
});
// Get initial filter value from URL
function getInitialFilter() {
const params = new URLSearchParams(window.location.search);
return params.get('search') || '';
}
// Update URL with current filter
function updateFilterUrl(filterText) {
const newUrl = filterText
? `${window.location.pathname}?search=${encodeURIComponent(filterText)}`
: window.location.pathname;
window.history.pushState({}, '', newUrl);
}
async function renderTagsList(filteredEntries) {
const tagsList = document.getElementById('tagsList');
// Count occurrences of each tag in filtered entries only
const tagCounts = filteredEntries.reduce((acc, entry) => {
entry.tags.forEach(tag => {
acc[tag] = (acc[tag] || 0) + 1;
});
return acc;
}, {});
// Sort tags by frequency (descending) then alphabetically
const sortedTags = Object.entries(tagCounts)
.sort(([tagA, countA], [tagB, countB]) => {
if (countB !== countA) return countB - countA;
return tagA.localeCompare(tagB);
});
// Get current filter to highlight active tag if any
const currentFilter = document.getElementById('filterInput').value.toLowerCase();
// Render tags list with counts
tagsList.innerHTML = sortedTags.map(([tag, count]) => `
<a href="#" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center tag-filter ${
tag.toLowerCase() === currentFilter ? 'active' : ''
}" data-tag="${tag}">
${tag}
<span class="badge bg-secondary rounded-pill">${count}</span>
</a>
`).join('');
// Add click handlers for tag filtering
tagsList.querySelectorAll('.tag-filter').forEach(tagElement => {
tagElement.addEventListener('click', (e) => {
e.preventDefault();
const tag = tagElement.dataset.tag;
const filterInput = document.getElementById('filterInput');
// Toggle tag filter
if (filterInput.value.toLowerCase() === tag.toLowerCase()) {
filterInput.value = ''; // Clear filter if clicking active tag
} else {
filterInput.value = tag;
}
renderEntries();
});
});
}
// Modify existing renderEntries function
async function renderEntries() {
const { entries = [], archivebox_server_url } = await chrome.storage.local.get(['entries', 'archivebox_server_url']);
const filterText = document.getElementById('filterInput').value.toLowerCase();
const entriesList = document.getElementById('entriesList');
// Update URL when filter changes
updateFilterUrl(filterText);
// Filter entries based on search text
const filteredEntries = entries.filter(entry => {
const searchableText = [
entry.url,
entry.title,
entry.id,
...entry.tags
].join(' ').toLowerCase();
return searchableText.includes(filterText);
});
// Add CSS for URL truncation if not already present
if (!document.getElementById('entriesListStyles')) {
const style = document.createElement('style');
style.id = 'entriesListStyles';
style.textContent = `
.entry-url {
max-width: 800px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
}
.entry-title-line {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.entry-title {
font-size: 0.9em;
color: #666;
margin-bottom: 4px;
}
.entry-link-to-archivebox {
font-size: 0.7em;
color: #888;
padding-right: 20px;
}
.entry-timestamp {
font-size: 0.8em;
color: #888;
margin-left: 8px;
}
.entry-content {
display: flex;
flex-direction: column;
gap: 2px;
}
.entry-url-line {
display: flex;
align-items: center;
gap: 8px;
}
`;
document.head.appendChild(style);
}
// Render entries list
entriesList.innerHTML = filteredEntries.map(entry => `
<div class="list-group-item d-flex align-items-start gap-2">
<input type="checkbox"
class="entry-checkbox form-check-input mt-2"
value="${entry.id}"
${selectedEntries.has(entry.id) ? 'checked' : ''}>
<div class="entry-content flex-grow-1">
<div class="entry-title-line">
<div class="entry-title">${entry.title || 'Untitled'}</div>
${(()=>{
return archivebox_server_url ?
`<div class="entry-link-to-archivebox">
<a href=${archivebox_server_url}/archive/${entry.url}>
View entry
</a>
</div>`
: '' })()
}
</div>
<div class="entry-url-line">
<img class="favicon" src="${entry.favicon || 'static/icon128.png'}"
onerror="this.src='static/icon128.png'"
width="16" height="16">
<code class="entry-url">${entry.url}</code>
<span class="entry-timestamp">
${new Date(entry.timestamp).toLocaleString()}
</span>
</div>
<div class="small text-muted mt-1">
${entry.tags.map(tag =>
`<span class="badge bg-secondary me-1">${tag}</span>`
).join('')}
</div>
</div>
</div>
`).join('');
// Update selection count and action buttons
updateSelectionCount();
updateActionButtonStates();
// Update tags list with filtered entries
await renderTagsList(filteredEntries);
}
// Initialize filter input with URL parameter and trigger initial render
const filterInput = document.getElementById('filterInput');
filterInput.value = getInitialFilter();
// Handle filter input changes with debounce
let filterTimeout;
filterInput.addEventListener('input', () => {
clearTimeout(filterTimeout);
filterTimeout = setTimeout(() => {
renderEntries();
}, 300);
});
// Handle browser back/forward
window.addEventListener('popstate', () => {
filterInput.value = getInitialFilter();
renderEntries();
});
// Initialize the tag modal when the entries tab is initialized
initializeTagModal();
// Initial render
renderEntries();
// Export to CSV
document.getElementById('downloadCsv').addEventListener('click', async () => {
const { entries = [] } = await chrome.storage.local.get('entries');
const selectedItems = entries.filter(e => selectedEntries.has(e.id));
if (!selectedItems.length) {
alert('No entries selected');
return;
}
// CSV Header
const csvRows = [
['ID', 'Timestamp', 'URL', 'Title', 'Tags'].join(',')
];
// CSV Data Rows
selectedItems.forEach(entry => {
const row = [
entry.id,
entry.timestamp,
`"${entry.url.replace(/"/g, '""')}"`, // Escape quotes in URL
`"${(entry.title || '').replace(/"/g, '""')}"`, // Escape quotes in title
`"${entry.tags.join(', ')}"` // Join tags with comma
];
csvRows.push(row.join(','));
});
// Create and trigger download
const csvContent = csvRows.join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', `archivebox-export-${new Date().toISOString().slice(0,10)}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
});
// Export to JSON
document.getElementById('downloadJson').addEventListener('click', async () => {
const { entries = [] } = await chrome.storage.local.get('entries');
const selectedItems = entries.filter(e => selectedEntries.has(e.id));
if (!selectedItems.length) {
alert('No entries selected');
return;
}
// Create formatted JSON with selected fields
const exportData = selectedItems.map(entry => ({
id: entry.id,
timestamp: entry.timestamp,
url: entry.url,
title: entry.title || '',
tags: entry.tags
}));
// Create and trigger download
const jsonContent = JSON.stringify(exportData, null, 2); // Pretty print with 2 spaces
const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', `archivebox-export-${new Date().toISOString().slice(0,10)}.json`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
});
// Delete entries
document.getElementById('deleteFiltered').addEventListener('click', async () => {
const { entries = [] } = await chrome.storage.local.get('entries');
const selectedItems = entries.filter(e => selectedEntries.has(e.id));
console.log(`deleting ${selectedItems.length} items from local storage`)
if (!selectedItems.length) {
alert('No entries to delete');
return;
}
const message = `Delete ${selectedItems.length} entries?`
if (!confirm(message)) return;
const idsToDelete = new Set(selectedItems.map(e => e.id));
const remainingEntries = entries.filter(e => !idsToDelete.has(e.id));
await chrome.storage.local.set({ entries: remainingEntries });
// Refresh the view
await renderEntries('');
});
// Sync entries
document.getElementById('syncFiltered').addEventListener('click', async () => {
const { entries = [] } = await chrome.storage.local.get('entries');
const selectedItems = entries.filter(e => selectedEntries.has(e.id));
console.log(`syncing ${selectedItems.length} items to ArchiveBox server`)
if (!selectedItems.length) {
alert('No selectedItems to sync');
return;
}
const syncBtn = document.getElementById('syncFiltered');
syncBtn.disabled = true;
syncBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Syncing...';
// Process selectedItems one at a time
for (const item of selectedItems) {
const row = document.querySelector(`input[value="${item.id}"]`);
if (!row) continue;
const entryTitle = row.parentElement.querySelector('.entry-title');
// Add status indicator if it doesn't exist
let statusIndicator = entryTitle.querySelector('.sync-status');
if (!statusIndicator) {
statusIndicator = document.createElement('span');
statusIndicator.className = 'sync-status status-indicator';
statusIndicator.style.marginLeft = '10px';
entryTitle.appendChild(statusIndicator);
}
// Update status to "in progress"
statusIndicator.className = 'sync-status status-indicator';
statusIndicator.style.backgroundColor = '#ffc107'; // yellow
// Send to ArchiveBox
const addCommandArgs = JSON.stringify({urls: [item.url], tag: item.tags.join(',')});
const response = await addToArchiveBox(addCommandArgs);
// Update status indicator
statusIndicator.className = `sync-status status-indicator status-${response.ok ? 'success' : 'error'}`;
statusIndicator.style.backgroundColor = response.ok ? '#28a745' : '#dc3545';
statusIndicator.title = response.status;
// Wait 1s before next request
await new Promise(resolve => setTimeout(resolve, 1000));
}
// Reset button state
syncBtn.disabled = false;
syncBtn.textContent = 'SYNC'; });
}
// // Helper function to sync a single entry to ArchiveBox
// async function syncToArchiveBox(entry) {
// const { archivebox_server_url, archivebox_api_key } = await chrome.storage.local.get([
// 'archivebox_server_url',
// 'archivebox_api_key'
// ]);
// if (!archivebox_server_url || !archivebox_api_key) {
// return { ok: false, status: 'Server not configured' };
// }
// try {
// const response = await fetch(`${archivebox_server_url}/api/v1/cli/add`, {
// method: 'POST',
// mode: 'cors',
// credentials: 'omit',
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json',
// 'x-archivebox-api-key': archivebox_api_key,
// },
// body: JSON.stringify({
// urls: [entry.url],
// tag: entry.tags.join(','),
// depth: 0,
// update: false,
// update_all: false,
// }),
// });
// return {
// ok: response.ok,
// status: `${response.status} ${response.statusText}`
// };
// } catch (err) {
// return { ok: false, status: `Connection failed ${err}` };
// }
// }