-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1368 lines (1168 loc) · 42.1 KB
/
popup.js
File metadata and controls
1368 lines (1168 loc) · 42.1 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
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Security: Disable all logging in production
const DEBUG = false;
const log = DEBUG ? console.log : () => {};
const logError = DEBUG ? console.error : () => {};
// State management
let selectedDocument = null;
let selectedField = null; // { id, name, type } for Form docs, null for simple docs
let currentDocFields = null; // full field list when a Form doc is selected, null otherwise
let documents = [];
let searchTimeout = null;
let currentPage = 0;
let hasMoreDocuments = true;
let isLoadingMore = false;
// DOM element cache (populated on DOMContentLoaded)
const elements = {};
// Use configuration constants
const MAX_DOC_TITLE_LENGTH = CONFIG.LIMITS.MAX_DOC_TITLE_LENGTH;
const MAX_NOTE_LENGTH = CONFIG.LIMITS.MAX_NOTE_LENGTH;
const MAX_SERVER_URL_LENGTH = CONFIG.LIMITS.MAX_SERVER_URL_LENGTH;
const ERROR_DISPLAY_MS = CONFIG.UI.ERROR_DISPLAY_MS;
const SUCCESS_DISPLAY_MS = CONFIG.UI.SUCCESS_DISPLAY_MS;
const SEARCH_DEBOUNCE_MS = CONFIG.UI.SEARCH_DEBOUNCE_MS;
// NEW: API Key storage expiration (7 days)
const API_KEY_EXPIRY_DAYS = 7;
const API_KEY_EXPIRY_MS = API_KEY_EXPIRY_DAYS * 24 * 60 * 60 * 1000;
document.addEventListener('DOMContentLoaded', async () => {
// Cache DOM elements
cacheElements();
// NEW: Run one-time migration for existing users
await migrateSessionToLocal();
await checkAuthStatus();
setupEventListeners();
});
/**
* Cache frequently accessed DOM elements for better performance
*/
function cacheElements() {
elements.connectBtn = document.getElementById('connect-btn');
elements.backBtn = document.getElementById('back-btn');
elements.serverUrl = document.getElementById('server-url');
elements.apiKey = document.getElementById('api-key');
elements.authError = document.getElementById('auth-error');
elements.clipBtn = document.getElementById('clip-btn');
elements.settingsBtn = document.getElementById('settings-btn');
elements.documentSearch = document.getElementById('document-search');
elements.searchClear = document.getElementById('search-clear'); // NEW: Clear search button
elements.documentList = document.getElementById('document-list');
elements.documentSection = document.querySelector('.document-section'); // NEW: For infinite scroll
elements.loadingIndicator = document.getElementById('loading-indicator'); // NEW: Loading indicator
elements.createHint = document.getElementById('create-hint');
elements.note = document.getElementById('note');
elements.clipError = document.getElementById('clip-error');
elements.clipSuccess = document.getElementById('clip-success');
elements.emptyState = document.getElementById('empty-state');
// Field selector (for Form-based documents)
elements.fieldSelectorSection = document.getElementById('field-selector-section');
elements.fieldSelect = document.getElementById('field-select');
elements.noCompatibleFieldsMsg = document.getElementById('no-compatible-fields-msg');
// NEW: Remember checkboxes and clear button
elements.rememberServer = document.getElementById('remember-server');
elements.rememberApiKey = document.getElementById('remember-api-key');
elements.clearDataBtn = document.getElementById('clear-data-btn');
}
/**
* Check authentication status and show appropriate screen
*/
async function checkAuthStatus() {
try {
// Check session for active authentication
const session = await chrome.storage.session.get(['serverUrl', 'accessToken']);
if (session.accessToken && session.serverUrl) {
// User is authenticated - show clipper screen
showScreen('clipper-screen');
await loadDocuments();
} else {
// Not authenticated - prepare auth screen
// Load saved credentials from persistent storage
const stored = await chrome.storage.local.get([
'savedServerUrl',
'savedApiKey',
'apiKeyExpiresAt',
'rememberServer',
'rememberApiKey'
]);
// Reset button state
elements.connectBtn.disabled = false;
elements.connectBtn.textContent = 'Connect to RSpace';
// Pre-fill server URL if saved
if (stored.savedServerUrl && stored.rememberServer !== false) {
const validatedUrl = validateStoredUrl(stored.savedServerUrl);
if (validatedUrl) {
elements.serverUrl.value = validatedUrl;
if (elements.rememberServer) {
elements.rememberServer.checked = true;
}
} else {
// Invalid stored URL - clear it
await chrome.storage.local.remove(['savedServerUrl']);
elements.serverUrl.value = 'https://';
}
} else {
// Default to https:// prefix
elements.serverUrl.value = 'https://';
}
// Pre-fill API key if saved and not expired
if (stored.savedApiKey && stored.rememberApiKey) {
// Check expiration
if (stored.apiKeyExpiresAt && Date.now() < stored.apiKeyExpiresAt) {
// Valid and not expired
elements.apiKey.value = stored.savedApiKey;
if (elements.rememberApiKey) {
elements.rememberApiKey.checked = true;
}
log('Loaded saved API key (expires in', Math.round((stored.apiKeyExpiresAt - Date.now()) / (24 * 60 * 60 * 1000)), 'days)');
} else {
// Expired - clear it
await chrome.storage.local.remove(['savedApiKey', 'apiKeyExpiresAt']);
elements.apiKey.value = '';
log('Saved API key expired - cleared');
}
} else {
// No saved API key or user opted out
elements.apiKey.value = '';
}
// Hide back button on initial load
elements.backBtn.style.display = 'none';
showScreen('auth-screen');
}
} catch (error) {
logError('Error checking auth status:', error);
showScreen('auth-screen');
}
}
function setupEventListeners() {
// Auth screen
elements.connectBtn.addEventListener('click', handleConnect);
elements.backBtn.addEventListener('click', handleBackToClipper);
// Clear data button
if (elements.clearDataBtn) {
elements.clearDataBtn.addEventListener('click', handleClearSavedData);
}
// Server URL input - protect the https:// prefix
setupServerUrlProtection();
// Clipper screen
elements.clipBtn.addEventListener('click', handleClip);
elements.settingsBtn.addEventListener('click', handleSettings);
elements.documentSearch.addEventListener('input', handleDocumentSearch);
// Search clear button
if (elements.searchClear) {
elements.searchClear.addEventListener('click', handleSearchClear);
// Show/hide clear button based on input content
elements.documentSearch.addEventListener('input', updateSearchClearButton);
// Initial state
updateSearchClearButton();
}
// Infinite scroll for documents (replaces Load More button)
if (elements.documentSection) {
elements.documentSection.addEventListener('scroll', handleInfiniteScroll);
}
// When content type changes, re-filter the field selector for Form docs
document.querySelectorAll('input[name="content-type"]').forEach(radio => {
radio.addEventListener('change', (e) => {
if (currentDocFields) {
updateFieldSelector(e.target.value);
}
});
});
// Field selection change
if (elements.fieldSelect) {
elements.fieldSelect.addEventListener('change', handleFieldSelectChange);
}
// Support Enter key in document search
elements.documentSearch.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleClip();
}
});
}
/**
* Setup protection for the https:// prefix in server URL input
*/
function setupServerUrlProtection() {
const HTTPS_PREFIX = 'https://';
const PREFIX_LENGTH = HTTPS_PREFIX.length;
// Set cursor position after https:// on focus
elements.serverUrl.addEventListener('focus', (e) => {
if (e.target.value === HTTPS_PREFIX) {
setTimeout(() => {
e.target.setSelectionRange(PREFIX_LENGTH, PREFIX_LENGTH);
}, 0);
}
});
// Prevent deletion of https:// prefix
elements.serverUrl.addEventListener('input', (e) => {
if (!e.target.value.startsWith(HTTPS_PREFIX)) {
e.target.value = HTTPS_PREFIX;
e.target.setSelectionRange(PREFIX_LENGTH, PREFIX_LENGTH);
}
});
// Handle backspace and delete keys
elements.serverUrl.addEventListener('keydown', (e) => {
const cursorPos = e.target.selectionStart;
const value = e.target.value;
// Prevent deleting any part of https://
if ((e.key === 'Backspace' && cursorPos <= PREFIX_LENGTH) ||
(e.key === 'Delete' && cursorPos < PREFIX_LENGTH)) {
e.preventDefault();
}
// Prevent selecting and deleting https://
if ((e.key === 'Backspace' || e.key === 'Delete') &&
e.target.selectionStart < PREFIX_LENGTH && e.target.selectionEnd > PREFIX_LENGTH) {
e.preventDefault();
// If user tried to delete selection including prefix, just delete the part after
if (e.target.selectionEnd > PREFIX_LENGTH) {
e.target.value = HTTPS_PREFIX + value.substring(e.target.selectionEnd);
e.target.setSelectionRange(PREFIX_LENGTH, PREFIX_LENGTH);
}
}
});
}
/**
* Update visibility of search clear button
*/
function updateSearchClearButton() {
if (!elements.searchClear) return;
const hasText = elements.documentSearch.value.trim().length > 0;
if (hasText) {
elements.searchClear.classList.add('visible');
} else {
elements.searchClear.classList.remove('visible');
}
}
/**
* Handle search clear button click
*/
function handleSearchClear() {
elements.documentSearch.value = '';
elements.documentSearch.focus();
updateSearchClearButton();
// Trigger search to show all documents
handleDocumentSearch();
}
/**
* Handle connection with better async/await and HTTPS enforcement
*/
async function handleConnect() {
const serverUrl = elements.serverUrl.value.trim();
const apiKey = elements.apiKey.value.trim();
// Security: Input validation
if (!serverUrl) {
showError('auth-error', 'Please enter your RSpace server URL');
return;
}
if (serverUrl.length > MAX_SERVER_URL_LENGTH) {
showError('auth-error', 'Server URL is too long');
return;
}
if (!apiKey) {
showError('auth-error', 'Please enter your API key');
return;
}
// Security: Validate URL format
let url;
try {
url = new URL(serverUrl);
// Only allow HTTP and HTTPS protocols
if (!['http:', 'https:'].includes(url.protocol)) {
showError('auth-error', 'Server URL must use HTTP or HTTPS protocol');
return;
}
// Enforce HTTPS for non-localhost connections
if (url.protocol === 'http:' &&
!url.hostname.includes('localhost') &&
!url.hostname.includes('127.0.0.1')) {
showError('auth-error', 'HTTPS is required for security. HTTP connections are not allowed for remote servers.');
return;
}
} catch (error) {
logError('URL validation error:', error);
showError('auth-error', 'Invalid server URL format. Please enter a valid URL (e.g., https://your-server.com)');
return;
}
// Normalize URL (remove trailing slash)
const normalizedUrl = serverUrl.replace(/\/$/, '');
// Request host permission for this specific server origin.
// This keeps the extension's required permissions minimal — we only ask for
// access to the user's own RSpace server, not all websites.
const serverOrigin = url.origin; // e.g. "https://rspace.myuni.edu"
try {
const granted = await chrome.permissions.request({
origins: [`${serverOrigin}/*`]
});
if (!granted) {
showError('auth-error', 'Permission required to connect to your RSpace server. Please allow access when prompted.');
return;
}
} catch (error) {
logError('Permission request error:', error);
showError('auth-error', 'Could not request permission to access your server.');
return;
}
// Show loading state
elements.connectBtn.disabled = true;
elements.connectBtn.textContent = 'Connecting...';
elements.authError.classList.remove('show');
try {
// Clear any existing session credentials before attempting new connection
await chrome.storage.session.clear();
// Store server URL in session (always needed for this session)
await chrome.storage.session.set({ serverUrl: normalizedUrl });
// Check checkbox states
const rememberServer = elements.rememberServer ? elements.rememberServer.checked : true;
const rememberApiKey = elements.rememberApiKey ? elements.rememberApiKey.checked : false;
// Save server URL persistently if checkbox is checked
if (rememberServer) {
await chrome.storage.local.set({
savedServerUrl: normalizedUrl,
rememberServer: true
});
log('Server URL saved persistently');
} else {
// Clear any previously saved URL
await chrome.storage.local.remove(['savedServerUrl', 'rememberServer']);
log('Server URL not saved (checkbox unchecked)');
}
// Save API key with expiration if checkbox is checked
if (rememberApiKey) {
const expiresAt = Date.now() + API_KEY_EXPIRY_MS;
await chrome.storage.local.set({
savedApiKey: apiKey,
apiKeyExpiresAt: expiresAt,
rememberApiKey: true
});
log('API key saved persistently (expires in', API_KEY_EXPIRY_DAYS, 'days)');
} else {
// Clear any previously saved API key
await chrome.storage.local.remove(['savedApiKey', 'apiKeyExpiresAt', 'rememberApiKey']);
log('API key not saved (checkbox unchecked or default)');
}
// Use promisified message sending
const response = await sendMessageAsync({
action: 'startAuth',
serverUrl: normalizedUrl,
apiKey
});
if (response && response.success) {
showScreen('clipper-screen');
await loadDocuments();
} else {
showError('auth-error', response?.error || 'Authentication failed');
elements.connectBtn.disabled = false;
elements.connectBtn.textContent = 'Connect to RSpace';
// Clear sensitive inputs on failure
elements.apiKey.value = '';
}
} catch (error) {
logError('Connection error:', error);
showError('auth-error', 'Failed to connect: ' + error.message);
elements.connectBtn.disabled = false;
elements.connectBtn.textContent = 'Connect to RSpace';
}
}
/**
* Handle clip with better error handling and null checks
*/
async function handleClip() {
const contentType = document.querySelector('input[name="content-type"]:checked').value;
const note = elements.note.value;
const docName = elements.documentSearch.value.trim();
// Handle PDF clipping separately
if (contentType === 'pdf') {
return handlePdfClip();
}
// Security: Input validation
if (!docName) {
showError('clip-error', 'Please enter a document name');
return;
}
if (docName.length > MAX_DOC_TITLE_LENGTH) {
showError('clip-error', `Document name too long (max ${MAX_DOC_TITLE_LENGTH} characters)`);
return;
}
if (note && note.length > MAX_NOTE_LENGTH) {
showError('clip-error', `Note too long (max ${MAX_NOTE_LENGTH} characters)`);
return;
}
// Determine target document: use selected or create new
let targetDoc = null;
if (selectedDocument && selectedDocument.name === docName) {
targetDoc = { isNew: false, id: selectedDocument.id, globalId: selectedDocument.globalId };
} else {
targetDoc = { isNew: true, title: docName };
}
// If a Form document is selected, a field must be chosen
if (currentDocFields !== null && !selectedField) {
showError('clip-error', 'Please select a field to save to');
return;
}
// Show loading state
elements.clipBtn.disabled = true;
elements.clipBtn.textContent = 'Saving...';
showScreen('loading-screen');
try {
// Get current tab with null check
const tabs = await queryTabsAsync({ active: true, currentWindow: true });
if (!tabs || tabs.length === 0) {
showScreen('clipper-screen');
showError('clip-error', 'No active tab found. Please try again.');
elements.clipBtn.disabled = false;
elements.clipBtn.textContent = 'Save to RSpace';
return;
}
const tab = tabs[0];
// Ensure content script is injected before sending message
try {
await ensureContentScriptInjected(tab.id);
} catch (error) {
showScreen('clipper-screen');
showError('clip-error', 'Failed to access page. Try refreshing the page.');
logError('Content script injection error:', error);
elements.clipBtn.disabled = false;
elements.clipBtn.textContent = 'Save to RSpace';
return;
}
// Get content from the page
let content;
try {
content = await sendTabMessageAsync(tab.id, {
action: 'getContent',
contentType
});
} catch (error) {
showScreen('clipper-screen');
showError('clip-error', 'Failed to extract content from page.');
logError('Content extraction error:', error);
elements.clipBtn.disabled = false;
elements.clipBtn.textContent = 'Save to RSpace';
return;
}
if (!content || !content.html) {
showScreen('clipper-screen');
if (contentType === 'selection') {
showError('clip-error', 'No text selected. Please highlight text on the page first, then try again.');
} else {
showError('clip-error', 'Failed to extract content from page. Try refreshing the page and try again.');
}
elements.clipBtn.disabled = false;
elements.clipBtn.textContent = 'Save to RSpace';
return;
}
// Send to background script to save
const response = await sendMessageAsync({
action: 'clipContent',
targetDoc,
targetField: selectedField || null,
content,
note: note || '',
sourceUrl: tab.url,
sourceTitle: tab.title
});
showScreen('clipper-screen');
if (response && response.success) {
// Get server URL for link
const storage = await chrome.storage.session.get(['serverUrl']);
const serverUrl = storage.serverUrl;
showSuccessWithLink(
'clip-success',
'Content saved successfully!',
response.documentId,
response.globalId,
serverUrl
);
// Clear the note field
elements.note.value = '';
// Reload documents to show newly created document (if any)
await loadDocuments();
} else {
showError('clip-error', response?.error || 'Failed to save content');
}
} catch (error) {
showScreen('clipper-screen');
logError('=== UNEXPECTED ERROR IN CLIP ===');
logError('Error:', error);
logError('Error message:', error.message);
logError('Error stack:', error.stack);
// More descriptive error message
let errorMsg = 'An unexpected error occurred: ' + error.message;
// Check for common error scenarios
if (error.message.includes('Cannot read property') || error.message.includes('Cannot read properties')) {
errorMsg = '⚠️ Extension error.\n\nPlease try:\n1. Refresh the page you want to clip from\n2. Close and reopen the extension\n3. Try again\n\nTechnical details: ' + error.message;
} else if (error.message.includes('Receiving end does not exist')) {
errorMsg = '⚠️ Content script not loaded.\n\nPlease:\n1. Refresh the page\n2. Click the extension icon again\n3. Try clipping\n\nTechnical details: ' + error.message;
}
showError('clip-error', errorMsg);
} finally {
elements.clipBtn.disabled = false;
elements.clipBtn.textContent = 'Save to RSpace';
}
}
/**
* Handle PDF clipping workflow
*/
async function handlePdfClip() {
const note = elements.note.value;
const docName = elements.documentSearch.value.trim();
// Security: Input validation
if (!docName) {
showError('clip-error', 'Please enter a document name');
return;
}
if (docName.length > MAX_DOC_TITLE_LENGTH) {
showError('clip-error', `Document name too long (max ${MAX_DOC_TITLE_LENGTH} characters)`);
return;
}
if (note && note.length > MAX_NOTE_LENGTH) {
showError('clip-error', `Note too long (max ${MAX_NOTE_LENGTH} characters)`);
return;
}
// Determine target document: use selected or create new
let targetDoc = null;
if (selectedDocument && selectedDocument.name === docName) {
targetDoc = { isNew: false, id: selectedDocument.id, globalId: selectedDocument.globalId };
} else {
targetDoc = { isNew: true, title: docName };
}
// If a Form document is selected, a field must be chosen
if (currentDocFields !== null && !selectedField) {
showError('clip-error', 'Please select a field to save to');
return;
}
// Show loading state
elements.clipBtn.disabled = true;
elements.clipBtn.textContent = 'Generating PDF...';
showScreen('loading-screen');
try {
// Get current tab
const tabs = await queryTabsAsync({ active: true, currentWindow: true });
if (!tabs || tabs.length === 0) {
showScreen('clipper-screen');
showError('clip-error', 'No active tab found. Please try again.');
elements.clipBtn.disabled = false;
elements.clipBtn.textContent = 'Save to RSpace';
return;
}
const tab = tabs[0];
// Inject content script + PDF libraries into the active tab before requesting PDF generation
try {
await ensureContentScriptInjected(tab.id, true);
} catch (error) {
showScreen('clipper-screen');
showError('clip-error', 'Failed to access page. Try refreshing the page.');
logError('PDF content script injection error:', error);
elements.clipBtn.disabled = false;
elements.clipBtn.textContent = 'Save to RSpace';
return;
}
// Send PDF clip request to background script
const response = await sendMessageAsync({
action: 'clipPdf',
targetDoc,
targetField: selectedField || null,
note: note || '',
sourceUrl: tab.url,
sourceTitle: tab.title,
tabId: tab.id
});
showScreen('clipper-screen');
if (response && response.success) {
// Get server URL for link
const storage = await chrome.storage.session.get(['serverUrl']);
const serverUrl = storage.serverUrl;
showSuccessWithLink(
'clip-success',
'PDF saved successfully!',
response.documentId,
response.globalId,
serverUrl
);
// Clear the note field
elements.note.value = '';
// Reload documents to show newly created document (if any)
await loadDocuments();
} else {
showError('clip-error', response?.error || 'Failed to save PDF');
}
} catch (error) {
showScreen('clipper-screen');
logError('PDF clip error:', error);
let errorMsg = 'An error occurred while saving PDF: ' + error.message;
// Provide helpful error messages
if (error.message.includes('PDF generation')) {
errorMsg = '⚠️ PDF generation failed.\n\nThis feature requires browser print support. Some pages may not be compatible.\n\nTip: Try using "Full Page" or "Selection" mode instead.';
}
showError('clip-error', errorMsg);
} finally {
elements.clipBtn.disabled = false;
elements.clipBtn.textContent = 'Save to RSpace';
}
}
/**
* Load documents with promisified API
*/
async function loadDocuments(append = false) {
if (!append) {
currentPage = 0;
documents = [];
hasMoreDocuments = true;
}
try {
const response = await sendMessageAsync({
action: 'getDocuments',
pageNumber: currentPage
});
if (response && response.success) {
if (append) {
documents = [...documents, ...response.documents];
} else {
documents = response.documents;
}
// Check if there are more documents
hasMoreDocuments = response.hasMore;
renderDocuments(documents);
// Removed: updateLoadMoreButton() - now using infinite scroll
// Show empty state if no documents
if (documents.length === 0) {
showEmptyState();
} else {
hideEmptyState();
}
} else if (response && response.error === 'Not authenticated') {
// Session expired, show auth screen
showScreen('auth-screen');
} else {
showError('clip-error', response?.error || 'Failed to load documents');
}
} catch (error) {
logError('Load documents error:', error);
showError('clip-error', 'Failed to load documents: ' + error.message);
}
}
async function handleLoadMore() {
if (isLoadingMore || !hasMoreDocuments) return;
isLoadingMore = true;
// Show loading indicator
if (elements.loadingIndicator) {
elements.loadingIndicator.style.display = 'block';
}
currentPage++;
await loadDocuments(true);
// Hide loading indicator
if (elements.loadingIndicator) {
elements.loadingIndicator.style.display = 'none';
}
isLoadingMore = false;
}
/**
* Handle infinite scroll - auto-load more documents when near bottom
*/
function handleInfiniteScroll() {
// Don't trigger if already loading or no more documents
if (isLoadingMore || !hasMoreDocuments) return;
const scrollTop = elements.documentSection.scrollTop;
const scrollHeight = elements.documentSection.scrollHeight;
const clientHeight = elements.documentSection.clientHeight;
// Calculate distance from bottom
const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
// Trigger threshold: 100px from bottom
const threshold = 100;
// Load more when near bottom
if (distanceFromBottom < threshold) {
handleLoadMore();
}
}
function handleDocumentSearch() {
// Clear field state immediately — it's only restored by clicking a document
currentDocFields = null;
selectedField = null;
hideFieldSelector();
// Debounce the rest
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
const query = elements.documentSearch.value.toLowerCase().trim();
if (!query) {
// Show all documents when search is empty
selectedDocument = null;
renderDocuments(documents);
hideCreateHint();
return;
}
const filtered = documents.filter(doc =>
doc.name.toLowerCase().includes(query)
);
// Check if there's an exact match
const exactMatch = documents.find(doc =>
doc.name.toLowerCase() === query
);
if (exactMatch) {
selectedDocument = exactMatch;
} else {
selectedDocument = null;
}
renderDocuments(filtered);
// Show create hint if no exact match found and query is not empty
if (!exactMatch && query) {
showCreateHint();
} else {
hideCreateHint();
}
}, SEARCH_DEBOUNCE_MS);
}
function renderDocuments(docs) {
elements.documentList.innerHTML = '';
if (docs.length === 0) {
return;
}
docs.forEach(doc => {
const item = document.createElement('div');
item.className = 'document-item';
item.textContent = doc.name;
item.dataset.id = doc.id;
item.tabIndex = 0; // Make focusable for keyboard navigation
item.setAttribute('role', 'button'); // Accessibility: announce as button
item.setAttribute('aria-label', `Select document: ${doc.name}`);
// Highlight if this is the selected document
if (selectedDocument && selectedDocument.id === doc.id) {
item.classList.add('selected');
item.setAttribute('aria-selected', 'true');
} else {
item.setAttribute('aria-selected', 'false');
}
const selectDocument = async () => {
document.querySelectorAll('.document-item').forEach(i => {
i.classList.remove('selected');
i.setAttribute('aria-selected', 'false');
});
item.classList.add('selected');
item.setAttribute('aria-selected', 'true');
selectedDocument = doc;
elements.documentSearch.value = doc.name;
hideCreateHint();
// Reset field state, then fetch fields for this document
currentDocFields = null;
selectedField = null;
hideFieldSelector();
await fetchAndShowFieldSelector(doc.id);
};
// Click handler
item.addEventListener('click', selectDocument);
// Keyboard handler (Enter or Space)
item.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
selectDocument();
}
});
elements.documentList.appendChild(item);
});
}
function showCreateHint() {
elements.createHint.style.display = 'flex';
}
function hideCreateHint() {
elements.createHint.style.display = 'none';
}
/**
* Ensure content script (and optionally PDF libraries) are injected into the active tab.
* Scripts are only injected into the tab the user is actively clipping from,
* triggered by explicit user action — no broad host permissions required.
* @param {number} tabId
* @param {boolean} [includePdfLibs=false] - Also inject html2canvas and jsPDF
*/
async function ensureContentScriptInjected(tabId, includePdfLibs = false) {
try {
// Try to ping the content script to see if it's already there
const response = await sendTabMessageAsync(tabId, { action: 'ping' });
if (response) {
log('Content script already injected');
if (!includePdfLibs) return;
// PDF libs may not be loaded yet even if content.js is — fall through to inject them
}
} catch (error) {
// Content script not present, need to inject it
log('Content script not present, injecting...');
}
try {
const files = includePdfLibs
? ['html2canvas.min.js', 'jspdf.umd.min.js', 'content.js']
: ['content.js'];
await chrome.scripting.executeScript({
target: { tabId },
files
});
log('Content script injected successfully', includePdfLibs ? '(with PDF libs)' : '');
} catch (error) {
logError('Failed to inject content script:', error);
throw error;
}
}
function showEmptyState() {
elements.emptyState.style.display = 'block';
elements.documentList.style.display = 'none';
}
function hideEmptyState() {
elements.emptyState.style.display = 'none';
elements.documentList.style.display = 'block';
}
async function handleSettings() {
// Reset the connect button to its initial state
elements.connectBtn.disabled = false;
elements.connectBtn.textContent = 'Connect to RSpace';
// Load saved credentials and pre-fill
const stored = await chrome.storage.local.get([
'savedServerUrl',
'savedApiKey',
'apiKeyExpiresAt',
'rememberServer',
'rememberApiKey'
]);
// Pre-fill server URL if saved
if (stored.savedServerUrl && stored.rememberServer !== false) {
const validatedUrl = validateStoredUrl(stored.savedServerUrl);
if (validatedUrl) {
elements.serverUrl.value = validatedUrl;
if (elements.rememberServer) {
elements.rememberServer.checked = true;
}
} else {
elements.serverUrl.value = 'https://';
}
} else {
elements.serverUrl.value = 'https://';
}
// Pre-fill API key if saved and not expired
if (stored.savedApiKey && stored.rememberApiKey) {
if (stored.apiKeyExpiresAt && Date.now() < stored.apiKeyExpiresAt) {
elements.apiKey.value = stored.savedApiKey;
if (elements.rememberApiKey) {
elements.rememberApiKey.checked = true;
}
} else {
// Expired - clear it
await chrome.storage.local.remove(['savedApiKey', 'apiKeyExpiresAt']);
elements.apiKey.value = '';
}
} else {
elements.apiKey.value = '';
}
// Clear any error messages
elements.authError.classList.remove('show');
// Show auth screen with back button (don't clear credentials yet)
elements.backBtn.style.display = 'block';
showScreen('auth-screen');