-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksave.js
More file actions
616 lines (526 loc) · 19.9 KB
/
Copy pathquicksave.js
File metadata and controls
616 lines (526 loc) · 19.9 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
// Quick Save Popup — opened after ⌘⇧S saves a page privately
// Allows user to enrich the save with note, treasury, and visibility
// If not logged in, shows login screen matching sidepanel pattern
const API_BASE = 'https://api-prod.copus.network';
let articleUuid = '';
let articleTitle = '';
let articleCover = '';
let articleUrl = '';
let isPrivate = true;
let selectedTreasuryIds = [];
let allTreasuries = [];
let token = '';
let userInfo = null;
let detectedImages = []; // Images found on the page
let sourceTabId = null; // The original page tab
let sourceWindowId = null; // The original page window
// ========== INIT ==========
document.addEventListener('DOMContentLoaded', async () => {
const params = new URLSearchParams(window.location.search);
articleUuid = params.get('uuid') || '';
articleTitle = params.get('title') || '';
articleCover = params.get('cover') || '';
articleUrl = params.get('url') || '';
sourceTabId = params.get('tabId') ? parseInt(params.get('tabId'), 10) : null;
sourceWindowId = params.get('windowId') ? parseInt(params.get('windowId'), 10) : null;
const needsLogin = params.get('login') === '1';
// Get token and user
const stored = await chrome.storage.local.get(['copus_token', 'copus_user']);
token = stored.copus_token || '';
userInfo = stored.copus_user || null;
if (!token || needsLogin) {
// Show login screen
document.getElementById('login-screen').style.display = 'flex';
document.getElementById('main-content').style.display = 'none';
document.getElementById('login-button').addEventListener('click', handleLogin);
return;
}
// Show main content
document.getElementById('login-screen').style.display = 'none';
const mainContent = document.getElementById('main-content');
mainContent.style.display = 'flex';
// Populate title textarea (editable, matching sidepanel)
const titleInput = document.getElementById('title-input');
const titleText = articleTitle || '';
titleInput.value = titleText.length > 75 ? titleText.substring(0, 75) : titleText;
updateTitleCharCounter();
// Set cover if available from URL params
if (articleCover) {
setCoverImage(articleCover);
}
// Set initial private state
updatePrivateCheckbox();
updateButtonLabel();
setupEventListeners();
loadTreasuries();
// Auto-load cover, title, and detected images from source tab
// (matches sidepanel behavior: fetches page data including og:image)
if (sourceTabId) {
try {
const pageData = await chrome.tabs.sendMessage(sourceTabId, { type: 'collectPageData' });
if (pageData) {
// Auto-set cover from og:image or first large image (only if no cover from URL params)
if (!articleCover) {
if (pageData.ogImageContent) {
setCoverImage(pageData.ogImageContent);
} else if (pageData.images && pageData.images.length > 0) {
const ogImg = pageData.images.find(img => img.isOgImage);
const suitable = ogImg || pageData.images.find(img =>
(img.width || 0) >= 100 && (img.height || 0) >= 100
) || pageData.images[0];
if (suitable && suitable.src) {
setCoverImage(suitable.src);
}
}
}
// Update title if we got a better one from page data
if (pageData.title && !titleInput.value) {
const t = pageData.title.length > 75 ? pageData.title.substring(0, 75) : pageData.title;
titleInput.value = t;
updateTitleCharCounter();
}
// Pre-compute detected images count for the Detect button (matching sidepanel)
const rawImages = (pageData.images) ? pageData.images : [];
const imageUrls = rawImages.map(img => typeof img === 'string' ? img : img.src).filter(Boolean);
if (pageData.ogImageContent && !imageUrls.includes(pageData.ogImageContent)) {
imageUrls.unshift(pageData.ogImageContent);
}
updateDetectButton(imageUrls.length);
}
} catch (e) {
// Source tab might not be available
}
}
});
// ========== LOGIN ==========
function handleLogin() {
// Open Copus login page in new tab and inject token back
chrome.runtime.sendMessage({
type: 'openUrlAndInjectToken',
url: 'https://copus.network/login',
token: null,
user: null
});
window.close();
}
// ========== COVER IMAGE MANAGEMENT ==========
function setCoverImage(url) {
articleCover = url;
const preview = document.getElementById('cover-preview');
const removeBtn = document.getElementById('cover-remove');
const area = document.getElementById('cover-area');
preview.src = url;
preview.hidden = false;
removeBtn.hidden = false;
area.classList.add('has-cover');
}
function clearCoverImage() {
articleCover = '';
const preview = document.getElementById('cover-preview');
const removeBtn = document.getElementById('cover-remove');
const area = document.getElementById('cover-area');
preview.src = '';
preview.hidden = true;
removeBtn.hidden = true;
area.classList.remove('has-cover');
}
function handleCoverUpload(file) {
if (!file || !file.type.startsWith('image/')) return;
const reader = new FileReader();
reader.onload = (e) => {
setCoverImage(e.target.result);
};
reader.readAsDataURL(file);
}
async function handleScreenshotCapture() {
try {
// Request screenshot from background script, targeting the source page's window
const response = await new Promise((resolve) => {
chrome.runtime.sendMessage({
type: 'captureScreenshot',
windowId: sourceWindowId || undefined
}, resolve);
});
if (response && response.success && response.dataUrl) {
setCoverImage(response.dataUrl);
}
} catch (e) {
// Screenshot capture failed silently
}
}
async function handleDetectImages() {
// We need to get detected images from the original tab
// The images were on the page that was saved — we get them via background → content script
const view = document.getElementById('detected-images-view');
const grid = document.getElementById('detected-images-grid');
view.style.display = 'flex';
grid.innerHTML = '<div class="detected-images-empty">Detecting images...</div>';
try {
// Use the source tab ID passed from the background script
if (!sourceTabId) {
grid.innerHTML = '<div class="detected-images-empty">Source tab not available</div>';
return;
}
// Try getting images from the content script on the original page
const response = await chrome.tabs.sendMessage(sourceTabId, { type: 'collectPageData' });
// Images from collectPageData are objects: { src, width, height, isOgImage }
// Normalize to plain URL strings for display
const rawImages = (response && response.images) ? response.images : [];
detectedImages = rawImages.map(img => typeof img === 'string' ? img : img.src).filter(Boolean);
// Also add og:image at the front if present and not already included
if (response && response.ogImageContent && !detectedImages.includes(response.ogImageContent)) {
detectedImages.unshift(response.ogImageContent);
}
if (detectedImages.length === 0) {
grid.innerHTML = '<div class="detected-images-empty">No images found on page</div>';
return;
}
grid.innerHTML = detectedImages.map((src, i) => `
<button class="detected-image-option" data-index="${i}" type="button">
<img src="${escapeAttr(src)}" alt="Image ${i + 1}" />
</button>
`).join('');
// Click handlers
grid.querySelectorAll('.detected-image-option').forEach(btn => {
btn.addEventListener('click', () => {
const idx = parseInt(btn.dataset.index, 10);
const imgSrc = detectedImages[idx];
if (imgSrc) {
setCoverImage(imgSrc);
view.style.display = 'none';
}
});
});
} catch (e) {
grid.innerHTML = '<div class="detected-images-empty">Could not detect images</div>';
}
}
// ========== HELPERS ==========
function truncateUrl(url) {
try {
const u = new URL(url);
let display = u.hostname + u.pathname;
if (display.length > 50) display = display.substring(0, 47) + '...';
return display;
} catch {
return url ? url.substring(0, 50) : '';
}
}
// ========== EVENT LISTENERS ==========
function updateDetectButton(count) {
const btn = document.getElementById('cover-detect');
const label = btn.querySelector('span');
if (count > 0) {
label.textContent = `Detect (${count})`;
btn.disabled = false;
btn.style.opacity = '1';
btn.style.cursor = 'pointer';
} else {
label.textContent = 'Detect';
btn.disabled = true;
btn.style.opacity = '0.4';
btn.style.cursor = 'not-allowed';
}
}
function updateTitleCharCounter() {
const titleInput = document.getElementById('title-input');
const counter = document.getElementById('title-counter');
const count = titleInput.value.length;
counter.textContent = `${count}/75`;
counter.classList.remove('near-limit', 'at-limit');
if (count >= 75) {
counter.classList.add('at-limit');
} else if (count >= 68) {
counter.classList.add('near-limit');
}
}
function setupEventListeners() {
// Title character counter
document.getElementById('title-input').addEventListener('input', updateTitleCharCounter);
// Note character counter
const noteInput = document.getElementById('note-input');
const noteCounter = document.getElementById('note-counter');
noteInput.addEventListener('input', () => {
noteCounter.textContent = `${noteInput.value.length}/1000`;
});
// Visibility toggle
document.getElementById('visibility-toggle').addEventListener('click', () => {
isPrivate = !isPrivate;
updatePrivateCheckbox();
updateButtonLabel();
});
// Close button
document.getElementById('close-button').addEventListener('click', () => {
window.close();
});
// Update button
document.getElementById('update-button').addEventListener('click', handleUpdate);
// Cover upload
document.getElementById('cover-upload').addEventListener('change', (e) => {
if (e.target.files && e.target.files[0]) {
handleCoverUpload(e.target.files[0]);
}
});
// Cover screenshot
document.getElementById('cover-screenshot').addEventListener('click', handleScreenshotCapture);
// Cover detect images
document.getElementById('cover-detect').addEventListener('click', handleDetectImages);
// Cover remove
document.getElementById('cover-remove').addEventListener('click', clearCoverImage);
// Detected images back button
document.getElementById('detected-back').addEventListener('click', () => {
document.getElementById('detected-images-view').style.display = 'none';
});
// Treasury button
document.getElementById('treasury-button').addEventListener('click', () => {
document.getElementById('treasury-modal').style.display = 'flex';
});
// Treasury modal close
document.getElementById('treasury-modal-close').addEventListener('click', closeTreasuryModal);
document.getElementById('treasury-backdrop').addEventListener('click', closeTreasuryModal);
document.getElementById('treasury-cancel').addEventListener('click', closeTreasuryModal);
document.getElementById('treasury-save').addEventListener('click', saveTreasurySelection);
// Treasury search
document.getElementById('treasury-search').addEventListener('input', (e) => {
renderTreasuryList(e.target.value.trim().toLowerCase());
});
}
function updatePrivateCheckbox() {
const checkbox = document.getElementById('private-checkbox');
if (isPrivate) {
checkbox.classList.add('checked');
} else {
checkbox.classList.remove('checked');
}
updateRequiredIndicators();
}
function updateRequiredIndicators() {
// Cover and Recommendation are required for public, optional for private
// (matching sidepanel logic)
const coverReq = document.getElementById('cover-required');
const recReq = document.getElementById('recommendation-required');
if (coverReq) coverReq.style.display = isPrivate ? 'none' : '';
if (recReq) recReq.style.display = isPrivate ? 'none' : '';
}
function updateButtonLabel() {
const btn = document.getElementById('update-button');
btn.textContent = isPrivate ? 'Update' : 'Update & Publish';
}
// ========== UPDATE (save enriched data) ==========
async function handleUpdate() {
const btn = document.getElementById('update-button');
const note = document.getElementById('note-input').value.trim();
const title = document.getElementById('title-input').value.trim();
if (!title) {
showToast('Title is required.');
return;
}
// Cover is required for public articles (matching sidepanel validation)
if (!isPrivate && !articleCover) {
showToast('Cover image is required for public curations.');
return;
}
// Recommendation is required for public articles (matching sidepanel validation)
if (!isPrivate && !note) {
showToast('Recommendation is required for public curations.');
return;
}
btn.disabled = true;
btn.textContent = 'Saving...';
try {
const payload = {
uuid: articleUuid,
title: title,
content: note,
coverUrl: articleCover,
targetUrl: articleUrl,
categoryId: 0,
visibility: isPrivate ? 1 : 0,
...(selectedTreasuryIds.length > 0 ? { spaceIds: selectedTreasuryIds } : {})
};
const response = await apiRequest(`${API_BASE}/client/author/article/edit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(payload)
});
if (!response.success) {
throw new Error(response.error || 'Update failed');
}
const result = response.data;
if (result.status && result.status !== 1 && result.status !== 1000) {
throw new Error(result.msg || result.message || 'Update failed');
}
// Show success
const banner = document.getElementById('success-banner');
banner.querySelector('span').textContent = isPrivate
? 'Updated! Saved privately.'
: 'Published! Now visible to others.';
btn.textContent = 'Done';
btn.style.background = '#1f9d55';
setTimeout(() => window.close(), 1200);
} catch (err) {
btn.disabled = false;
updateButtonLabel();
showToast('Failed to update: ' + (err.message || 'Unknown error'));
}
}
// ========== TREASURY LOADING ==========
// Uses the same endpoint as the sidepanel: /client/article/bind/bindableSpaces
async function loadTreasuries() {
if (!token) return;
try {
const response = await apiRequest(
`${API_BASE}/client/article/bind/bindableSpaces`,
{
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
}
);
if (response.success && response.data) {
const responseData = response.data;
// Handle different API response formats
let spacesArray = [];
if (responseData.data && Array.isArray(responseData.data)) {
spacesArray = responseData.data;
} else if (Array.isArray(responseData)) {
spacesArray = responseData;
}
allTreasuries = spacesArray;
renderTreasuryList('');
} else {
document.getElementById('treasury-list').innerHTML =
'<div class="treasury-loading">Could not load treasuries</div>';
}
} catch (e) {
document.getElementById('treasury-list').innerHTML =
'<div class="treasury-loading">Could not load treasuries</div>';
}
}
function getTreasuryDisplayName(treasury) {
// Match sidepanel logic for display names
const isDefaultCollections = treasury.spaceType === 1 || treasury.name === 'Default Collections Space';
const isDefaultCurations = treasury.spaceType === 2 || treasury.name === 'Default Curations Space';
const username = userInfo?.namespace || userInfo?.userName || userInfo?.username || 'My';
if (isDefaultCollections) return `${username}'s Treasury`;
if (isDefaultCurations) return `${username}'s Curations`;
return treasury.name || 'Untitled';
}
function renderTreasuryList(filter) {
const list = document.getElementById('treasury-list');
const filtered = filter
? allTreasuries.filter(t => getTreasuryDisplayName(t).toLowerCase().includes(filter))
: allTreasuries;
if (filtered.length === 0) {
list.innerHTML = filter
? '<div class="treasury-loading">No matching treasuries</div>'
: '<div class="treasury-loading">No treasuries yet</div>';
return;
}
list.innerHTML = filtered.map(t => {
const isSelected = selectedTreasuryIds.includes(t.id);
const displayName = getTreasuryDisplayName(t);
const firstLetter = displayName.charAt(0).toUpperCase();
// Determine avatar image
const isDefault = t.spaceType === 1 || t.spaceType === 2;
let avatarUrl = '';
if (isDefault) {
avatarUrl = userInfo?.faceUrl || '';
} else {
avatarUrl = t.faceUrl || (t.data && t.data[0] && t.data[0].coverUrl) || '';
}
return `
<div class="treasury-item ${isSelected ? 'selected' : ''}" data-id="${t.id}">
<div class="treasury-item-checkbox">
<svg viewBox="0 0 10 10" fill="none"><path d="M2 5L4.5 7.5L8 2.5" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
</div>
<div class="treasury-item-avatar">
${avatarUrl
? `<img src="${escapeAttr(avatarUrl)}" alt="" />`
: `<span class="treasury-item-avatar-letter">${firstLetter}</span>`
}
</div>
<span class="treasury-item-name">${escapeHtml(displayName)}</span>
</div>
`;
}).join('');
// Add click handlers
list.querySelectorAll('.treasury-item').forEach(item => {
item.addEventListener('click', () => {
const id = parseInt(item.dataset.id, 10);
if (selectedTreasuryIds.includes(id)) {
selectedTreasuryIds = selectedTreasuryIds.filter(i => i !== id);
item.classList.remove('selected');
} else {
selectedTreasuryIds.push(id);
item.classList.add('selected');
}
});
});
}
function closeTreasuryModal() {
document.getElementById('treasury-modal').style.display = 'none';
}
function saveTreasurySelection() {
closeTreasuryModal();
const btn = document.getElementById('treasury-button');
const text = document.getElementById('treasury-text');
if (selectedTreasuryIds.length > 0) {
const names = selectedTreasuryIds.map(id => {
const t = allTreasuries.find(tr => tr.id === id);
return t ? getTreasuryDisplayName(t) : '';
}).filter(Boolean);
text.textContent = names.join(', ') || `${selectedTreasuryIds.length} selected`;
btn.classList.add('has-selection');
} else {
text.textContent = 'Choose treasuries...';
btn.classList.remove('has-selection');
}
}
// ========== API Helper ==========
// Routes requests through background script to avoid popup CORS issues
function apiRequest(url, options = {}) {
return new Promise((resolve) => {
chrome.runtime.sendMessage({
type: 'apiRequest',
url: url,
method: options.method || 'GET',
headers: options.headers || {},
body: options.body ? JSON.parse(options.body) : undefined
}, (response) => {
if (chrome.runtime.lastError) {
resolve({ success: false, error: chrome.runtime.lastError.message });
} else {
resolve(response || { success: false, error: 'No response' });
}
});
});
}
// ========== Utilities ==========
function showToast(message) {
// Remove existing toast if any
const existing = document.getElementById('qs-toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.id = 'qs-toast';
toast.className = 'qs-toast';
toast.textContent = message;
document.body.appendChild(toast);
// Auto-dismiss after 3s
setTimeout(() => {
toast.classList.add('qs-toast-hide');
toast.addEventListener('transitionend', () => toast.remove());
}, 3000);
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function escapeAttr(str) {
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}