-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathpopup.js
646 lines (564 loc) · 18.4 KB
/
popup.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
// popup.js
window.popup_element = null; // Global reference to popup element
window.hide_timer = null;
window.closePopup = function () {
document.querySelector(".archive-box-iframe")?.remove();
window.popup_element = null;
console.log("close popup");
};
// handle escape key when popup doesn't have focus
document.addEventListener('keydown', (e)=>{
if (e.key == 'Escape') {
closePopup();
}
});
async function getAllTags() {
const { entries = [] } = await chrome.storage.local.get('entries');
return [...new Set(entries.flatMap(entry => entry.tags))]
.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
}
async function sendToArchiveBox(url, tags) {
try {
console.log('i Sending to ArchiveBox', { method: 'POST', url, tags });
const addCommandArgs = JSON.stringify({
urls: [url],
tag: tags.join(','),
});
const response = await new Promise((resolve, reject) => {
chrome.runtime.sendMessage({
type: 'archivebox_add',
body: addCommandArgs
}, (result) => {
if (!result.ok) {
console.log(`ArchiveBox request failed: ${result.errorMessage}`);
reject(`${result.errorMessage}`);
}
resolve(result);
});
})
return { ok: response.ok, status: `${response.status} ${response.statusText}`};
} catch (error) {
console.log(`ArchiveBox request failed: ${error}`);
return { ok: false, status: `Failed to archive: ${error}` };
}
}
window.getCurrentEntry = async function() {
const { entries = [] } = await chrome.storage.local.get('entries');
let current_entry = entries.find(entry => entry.url === window.location.href);
if (!current_entry) {
current_entry = {
id: crypto.randomUUID(),
url: String(window.location.href),
timestamp: new Date().toISOString(),
tags: [],
title: document.title,
notes: '',
};
entries.push(current_entry);
await chrome.storage.local.set({ entries }); // Save immediately
}
current_entry.id = current_entry.id || crypto.randomUUID();
current_entry.url = current_entry.url || window.location.href;
current_entry.timestamp = current_entry.timestamp || new Date().toISOString();
current_entry.tags = current_entry.tags || [];
current_entry.title = current_entry.title || document.title;
current_entry.notes = current_entry.notes || '';
console.log('i Loaded current ArchiveBox snapshot', current_entry);
return { current_entry, entries }; // Return both for atomic updates
}
window.getSuggestedTags = async function() {
const { current_entry, entries } = await getCurrentEntry();
// Get all unique tags sorted by recency, excluding current entry's tags
return [...new Set(
[
window.location.hostname.replace('www.', '').replace('.com', ''),
...entries
.filter(entry => entry.url !== current_entry.url) // Better way to exclude current
.reverse()
.flatMap(entry => entry.tags),
]
)]
.filter(tag => !current_entry.tags.includes(tag))
.slice(0, 4);
}
window.updateCurrentTags = async function() {
if (!popup_element) return;
const current_tags_div = popup_element.querySelector('.ARCHIVEBOX__current-tags');
const status_div = popup_element.querySelector('small');
const { current_entry } = await getCurrentEntry();
const result = await sendToArchiveBox(current_entry.url, current_entry.tags);
current_tags_div.innerHTML = current_entry.tags.length
? `${current_entry.tags
.map(tag => `<span class="ARCHIVEBOX__tag-badge current" data-tag="${tag}">${tag}</span>`)
.join(' ')}`
: '';
status_div.innerHTML = `
<span class="status-indicator ${result.ok ? 'success' : 'error'}"></span>
${result.status}
`;
// Add click handlers for removing tags
current_tags_div.querySelectorAll('.ARCHIVEBOX__tag-badge.current').forEach(badge => {
badge.addEventListener('click', async (e) => {
if (e.target.classList.contains('current')) {
const { current_entry, entries } = await getCurrentEntry();
const tag_to_remove = e.target.dataset.tag;
current_entry.tags = current_entry.tags.filter(tag => tag !== tag_to_remove);
await chrome.storage.local.set({ entries });
await updateCurrentTags();
await updateSuggestions();
}
});
});
}
window.updateSuggestions = async function() {
if (!popup_element) return;
const suggestions_div = popup_element.querySelector('.ARCHIVEBOX__tag-suggestions');
const suggested_tags = await getSuggestedTags();
suggestions_div.innerHTML = suggested_tags.length
? `${suggested_tags
.map(tag => `<span class="ARCHIVEBOX__tag-badge suggestion">${tag}</span>`)
.join(' ')}`
: '';
}
window.createPopup = async function() {
const { current_entry } = await getCurrentEntry();
// Create iframe container
document.querySelector('.archive-box-iframe')?.remove();
const iframe = document.createElement('iframe');
iframe.className = 'archive-box-iframe';
// Set iframe styles for positioning
Object.assign(iframe.style, {
position: 'fixed',
top: '20px',
right: '20px',
zIndex: '2147483647',
background: 'transparent',
borderRadius: '6px',
border: '0px',
margin: '0px',
padding: '0px',
transform: 'translateY(0px)',
boxSizing: 'border-box',
width: '550px', // Initial width
height: '200px', // Initial height
transition: 'height 0.2s ease-out' // Smooth height transitions
});
document.body.appendChild(iframe);
// Function to resize iframe based on content
function resizeIframe() {
const doc = iframe.contentDocument || iframe.contentWindow.document;
const content = doc.querySelector('.archive-box-popup');
if (content) {
const height = content.offsetHeight;
const dropdown = doc.querySelector('.ARCHIVEBOX__autocomplete-dropdown');
const dropdownHeight = dropdown && dropdown.style.display !== 'none' ? dropdown.offsetHeight : 0;
iframe.style.height = (height + dropdownHeight + 20) + 'px'; // Add padding
}
}
// Create popup content inside iframe
const doc = iframe.contentDocument || iframe.contentWindow.document;
// Add styles to iframe
const style = doc.createElement('style');
style.textContent = `
html, body {
margin: 0;
padding: 0;
font-family: system-ui, -apple-system, sans-serif;
font-size: 16px;
width: 100%;
height: auto;
overflow: visible;
}
.archive-box-popup {
border-radius: 13px;
min-height: 90px;
background: #bf7070;
margin: 0px;
padding: 6px;
padding-top: 8px;
color: white;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
font-family: system-ui, -apple-system, sans-serif;
transition: all 0.2s ease-out;
}
.archive-box-popup:hover {
animation: slideDown -0.3s ease-in-out forwards;
opacity: 1;
}
.archive-box-popup small {
display: block;
width: 100%;
text-align: center;
margin-top: 5px;
color: #fefefe;
overflow: hidden;
font-size: 11px;
opacity: 1.0;
}
.archive-box-popup small.fade-out {
animation: fadeOut 2.5s ease-in-out forwards;
}
.archive-box-popup img {
width: 15%;
max-width: 40px;
display: inline-block;
vertical-align: top;
}
.archive-box-popup .options-link {
border: 1px solid #00000026;
border-right: 0px;
margin-right: -9px;
margin-top: -1px;
border-radius: 6px 0px 0px 6px;
padding-right: 7px;
padding-left: 3px;
text-decoration: none;
text-align: center;
font-size: 24px;
line-height: 1.4;
display: inline-block;
width: 34px;
transition: text-shadow 0.1s ease-in-out;
}
.archive-box-popup a.options-link:hover {
text-shadow: 0 0 10px #a1a1a1;
}
.archive-box-popup .metadata {
display: inline-block;
max-width: 80%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.archive-box-popup input {
width: calc(100% - 42px);
border: 0px;
margin: 0px;
padding: 5px;
padding-left: 13px;
border-radius: 6px;
min-width: 100px;
background-color: #fefefe;
color: #1a1a1a;
vertical-align: top;
display: inline-block;
line-height: 1.75 !important;
margin-bottom: 8px;
}
@keyframes fadeOut {
0% { opacity: 1; }
80% { opacity: 0.8;}
100% { opacity: 0; display: none; }
}
@keyframes slideDown {
0% { top: -500px; }
100% { top: 20px }
}
.ARCHIVEBOX__tag-suggestions {
margin-top: 20px;
display: inline;
min-height: 0;
background-color: rgba(0, 0, 0, 0);
border: 0;
box-shadow: 0 0 0 0;
}
.ARCHIVEBOX__current-tags {
display: inline;
}
.current-tags {
margin-top: 20px;
display: inline;
}
.ARCHIVEBOX__tag-badge {
display: inline-block;
background: #e9ecef;
padding: 3px 8px;
border-radius: 3px;
padding-left: 18px;
margin: 2px;
font-size: 15px;
cursor: pointer;
user-select: none;
}
.ARCHIVEBOX__tag-badge.suggestion {
background: #007bff;
color: white;
opacity: 0.2;
}
.ARCHIVEBOX__tag-badge.suggestion:hover {
opacity: 0.8;
}
.ARCHIVEBOX__tag-badge.suggestion:active {
opacity: 1;
}
.ARCHIVEBOX__tag-badge.suggestion:after {
content: ' +';
}
.ARCHIVEBOX__tag-badge.current {
background: #007bff;
color: #ddd;
position: relative;
padding-right: 20px;
}
.ARCHIVEBOX__tag-badge.current:hover::after {
content: '×';
position: absolute;
right: 5px;
top: 50%;
transform: translateY(-50%);
font-weight: bold;
cursor: pointer;
}
.status-indicator {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 5px;
}
.status-indicator.success {
background: #28a745;
}
.status-indicator.error {
background: #dc3545;
}
.ARCHIVEBOX__autocomplete-dropdown {
background: white;
border: 1px solid #ddd;
border-radius: 0 0 6px 6px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
max-height: 200px;
overflow-y: auto;
transition: all 0.2s ease-out;
}
.ARCHIVEBOX__autocomplete-item {
padding: 8px 12px;
cursor: pointer;
color: #333;
}
.ARCHIVEBOX__autocomplete-item:hover,
.ARCHIVEBOX__autocomplete-item.selected {
background: #f0f0f0;
}
`;
doc.head.appendChild(style);
// Create popup content
const popup = doc.createElement('div');
popup.className = 'archive-box-popup';
popup.innerHTML = `
<a href="#" class="options-link" title="Open in ArchiveBox">🏛️</a> <input type="search" placeholder="Add tags + press ⏎ | ⎋ to close">
<br/>
<div class="ARCHIVEBOX__current-tags"></div><div class="ARCHIVEBOX__tag-suggestions"></div><br/>
<small class="fade-out">
<span class="status-indicator"></span>
Saved
</small>
`;
doc.body.appendChild(popup);
window.popup_element = popup;
// Add message passing for options link
popup.querySelector('.options-link').addEventListener('click', (e) => {
e.preventDefault();
chrome.runtime.sendMessage({ action: 'openOptionsPage', id: current_entry.id });
});
const input = popup.querySelector('input');
const suggestions_div = popup.querySelector('.ARCHIVEBOX__tag-suggestions');
const current_tags_div = popup.querySelector('.ARCHIVEBOX__current-tags');
// Initial display of current tags and suggestions
await updateCurrentTags();
await updateSuggestions();
// Add click handlers for suggestion badges
suggestions_div.addEventListener('click', async (e) => {
if (e.target.classList.contains('suggestion')) {
const { current_entry, entries } = await getCurrentEntry();
const tag = e.target.textContent.replace(' +', '');
if (!current_entry.tags.includes(tag)) {
current_entry.tags.push(tag);
await chrome.storage.local.set({ entries });
await updateCurrentTags();
await updateSuggestions();
}
}
});
current_tags_div.addEventListener('click', async (e) => {
if (e.target.classList.contains('current')) {
const tag = e.target.dataset.tag;
console.log('Removing tag', tag);
const { current_entry, entries } = await getCurrentEntry();
current_entry.tags = current_entry.tags.filter(t => t !== tag);
await chrome.storage.local.set({ entries });
await updateCurrentTags();
await updateSuggestions();
}
});
// Add dropdown container
const dropdownContainer = document.createElement('div');
dropdownContainer.className = 'ARCHIVEBOX__autocomplete-dropdown';
dropdownContainer.style.display = 'none';
input.parentNode.insertBefore(dropdownContainer, input.nextSibling);
let selectedIndex = -1;
let filteredTags = [];
async function updateDropdown() {
const inputValue = input.value.toLowerCase();
const allTags = await getAllTags();
// Filter tags that match input and aren't already used
const { current_entry } = await getCurrentEntry();
filteredTags = allTags
.filter(tag =>
tag.toLowerCase().includes(inputValue) &&
!current_entry.tags.includes(tag) &&
inputValue
)
.slice(0, 5); // Limit to 5 suggestions
if (filteredTags.length === 0) {
dropdownContainer.style.display = 'none';
selectedIndex = -1;
} else {
dropdownContainer.innerHTML = filteredTags
.map((tag, index) => `
<div class="ARCHIVEBOX__autocomplete-item ${index === selectedIndex ? 'selected' : ''}"
data-tag="${tag}">
${tag}
</div>
`)
.join('');
dropdownContainer.style.display = 'block';
}
// Trigger resize after dropdown visibility changes
setTimeout(resizeIframe, 0);
}
// Handle input changes
input.addEventListener('input', updateDropdown);
// Handle keyboard navigation
// handle escape key when popup has focus
input.addEventListener("keydown", async (e) => {
if (e.key === "Escape") {
e.stopPropagation();
dropdownContainer.style.display = "none";
selectedIndex = -1;
closePopup();
return;
}
if (!filteredTags.length) {
if (e.key === 'Enter' && input.value.trim()) {
e.preventDefault();
const { current_entry, entries } = await getCurrentEntry();
const newTag = input.value.trim();
if (!current_entry.tags.includes(newTag)) {
current_entry.tags.push(newTag);
await chrome.storage.local.set({ entries });
input.value = '';
await updateCurrentTags();
await updateSuggestions();
}
}
return;
}
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, filteredTags.length - 1);
updateDropdown();
break;
case 'ArrowUp':
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, -1);
updateDropdown();
break;
case 'Enter':
e.preventDefault();
if (selectedIndex >= 0) {
const selectedTag = filteredTags[selectedIndex];
const { current_entry, entries } = await getCurrentEntry();
if (!current_entry.tags.includes(selectedTag)) {
current_entry.tags.push(selectedTag);
await chrome.storage.local.set({ entries });
}
input.value = '';
dropdownContainer.style.display = 'none';
selectedIndex = -1;
await updateCurrentTags();
await updateSuggestions();
}
break;
case 'Tab':
if (selectedIndex >= 0) {
e.preventDefault();
input.value = filteredTags[selectedIndex];
dropdownContainer.style.display = 'none';
selectedIndex = -1;
}
break;
}
});
// Handle click selection
dropdownContainer.addEventListener('click', async (e) => {
const item = e.target.closest('.ARCHIVEBOX__autocomplete-item');
if (item) {
const selectedTag = item.dataset.tag;
const { current_entry, entries } = await getCurrentEntry();
if (!current_entry.tags.includes(selectedTag)) {
current_entry.tags.push(selectedTag);
await chrome.storage.local.set({ entries });
}
input.value = '';
dropdownContainer.style.display = 'none';
selectedIndex = -1;
await updateCurrentTags();
await updateSuggestions();
}
});
// Hide dropdown when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('.ARCHIVEBOX__autocomplete-dropdown') &&
!e.target.closest('input')) {
dropdownContainer.style.display = 'none';
selectedIndex = -1;
}
});
input.focus();
console.log('+ Showed ArchiveBox popup in iframe');
// Add resize triggers
const resizeObserver = new ResizeObserver(() => {
resizeIframe();
});
// Observe the popup content for size changes
resizeObserver.observe(popup);
const originalUpdateCurrentTags = window.updateCurrentTags;
window.updateCurrentTags = async function() {
await originalUpdateCurrentTags();
resizeIframe();
}
async function updateDropdown() {
const inputValue = input.value.toLowerCase();
const allTags = await getAllTags();
// Filter tags that match input and aren't already used
const { current_entry } = await getCurrentEntry();
filteredTags = allTags
.filter(tag =>
tag.toLowerCase().includes(inputValue) &&
!current_entry.tags.includes(tag) &&
inputValue
)
.slice(0, 5); // Limit to 5 suggestions
if (filteredTags.length === 0) {
dropdownContainer.style.display = 'none';
selectedIndex = -1;
} else {
dropdownContainer.innerHTML = filteredTags
.map((tag, index) => `
<div class="ARCHIVEBOX__autocomplete-item ${index === selectedIndex ? 'selected' : ''}"
data-tag="${tag}">
${tag}
</div>
`)
.join('');
dropdownContainer.style.display = 'block';
}
// Trigger resize after dropdown visibility changes
setTimeout(resizeIframe, 0);
}
// Initial resize
setTimeout(resizeIframe, 0);
}
window.createPopup();