-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
630 lines (529 loc) · 25.6 KB
/
content.js
File metadata and controls
630 lines (529 loc) · 25.6 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
// ORCID ID Detector - Content Script
// Automatically detect ORCID IDs on web pages and make them interactive
(function() {
'use strict';
// Prevent multiple instances of the extension running
if (window.orcidDetectorLoaded) {
return;
}
window.orcidDetectorLoaded = true;
// ORCID ID regex pattern - matches various formats
const ORCID_REGEX = /(?:(?:https?:\/\/)?(?:www\.)?(?:sandbox\.)?orcid\.org\/)?(?:orcid\/)?(?:id\/)?(\d{4}-\d{4}-\d{4}-\d{3}[\dX])/gi;
// Escape HTML to prevent XSS
function escapeHtml(text) {
if (typeof text !== 'string') return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Cache for ORCID profile data to avoid duplicate API calls
const profileCache = new Map();
// Track processed elements to avoid duplicate processing
const processedElements = new WeakSet();
// Track processed text to avoid reprocessing the same content
const processedTextContent = new Set();
// Track processed ORCID links to avoid duplicate processing
const processedORCIDLinks = new WeakSet();
// Process existing ORCID links with logos (e.g., orcid_16x16.png)
function processExistingORCIDLinks() {
// Find all links to orcid.org
const orcidLinks = document.querySelectorAll('a[href*="orcid.org/"]');
orcidLinks.forEach(link => {
// Skip if already processed
if (processedORCIDLinks.has(link)) return;
// Skip if it's one of our own detector links
if (link.closest('.orcid-detector-container') ||
link.classList.contains('orcid-detector-container')) {
return;
}
// Extract ORCID ID from the href
const href = link.getAttribute('href');
const match = href.match(/orcid\.org\/(\d{4}-\d{4}-\d{4}-\d{3}[\dX])/);
if (!match) return;
const orcidId = match[1];
// Check if this link contains an ORCID logo image
const hasORCIDImage = link.querySelector('img[src*="orcid"]');
if (hasORCIDImage) {
// Mark as processed
processedORCIDLinks.add(link);
// Add our magnifying glass icon after the link
const logoSpan = document.createElement('span');
logoSpan.className = 'orcid-detector-logo-external';
logoSpan.style.marginLeft = '4px';
logoSpan.style.display = 'inline-block';
logoSpan.innerHTML = `
<svg width="16" height="16" viewBox="-10 -10 300 300" style="vertical-align: middle; cursor: pointer;">
<circle cx="120" cy="120" r="85" fill="none" stroke="#8FB82B" stroke-width="24"/>
<circle cx="120" cy="120" r="42" fill="none" stroke="#8FB82B" stroke-width="18"/>
<line x1="175" y1="175" x2="250" y2="250" stroke="#8FB82B" stroke-width="28" stroke-linecap="round"/>
</svg>
`;
logoSpan.title = 'View ORCID profile details';
// Add click handler
logoSpan.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
showORCIDPopup(orcidId, logoSpan);
});
// Insert after the link
link.parentNode.insertBefore(logoSpan, link.nextSibling);
}
});
}
// Initialize the extension
function init() {
console.log('ORCID ID Detector: Initializing...');
// Process existing ORCID links with logos
processExistingORCIDLinks();
// Process the initial page content
processPage();
// Set up mutation observer for dynamic content
setupMutationObserver();
console.log('ORCID ID Detector: Initialized');
}
// Process the entire page for ORCID IDs
function processPage() {
const textNodes = getTextNodes(document.body);
textNodes.forEach(processTextNode);
}
// Get all text nodes in the document
function getTextNodes(element) {
const textNodes = [];
const walker = document.createTreeWalker(
element,
NodeFilter.SHOW_TEXT,
{
acceptNode: function(node) {
// Skip script and style tags
const parent = node.parentElement;
if (!parent || ['SCRIPT', 'STYLE', 'NOSCRIPT'].includes(parent.tagName)) {
return NodeFilter.FILTER_REJECT;
}
// Skip already processed nodes AND elements with orcid-detector class
if (processedElements.has(parent) ||
parent.closest('.orcid-detector-container') ||
parent.classList.contains('orcid-detector-container') ||
parent.classList.contains('orcid-detector-text') ||
parent.classList.contains('orcid-detector-logo')) {
return NodeFilter.FILTER_REJECT;
}
// Only process nodes that might contain ORCID IDs
if (ORCID_REGEX.test(node.textContent)) {
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
}
}
);
let node;
while (node = walker.nextNode()) {
textNodes.push(node);
}
return textNodes;
}
// Process individual text nodes for ORCID IDs
function processTextNode(textNode) {
const parent = textNode.parentElement;
if (!parent || processedElements.has(parent)) return;
// Skip if this is already an ORCID detector element
if (parent.closest('.orcid-detector-container') ||
parent.classList.contains('orcid-detector-container') ||
parent.classList.contains('orcid-detector-text') ||
parent.classList.contains('orcid-detector-logo')) {
return;
}
const text = textNode.textContent;
// Create a unique identifier for this text content
const textHash = text + parent.tagName + (parent.className || '');
if (processedTextContent.has(textHash)) {
return;
}
const matches = [...text.matchAll(ORCID_REGEX)];
if (matches.length === 0) return;
// Mark as processed to avoid duplicate processing
processedElements.add(parent);
processedTextContent.add(textHash);
// Create document fragment with enhanced ORCID IDs
const fragment = document.createDocumentFragment();
let lastIndex = 0;
matches.forEach((match) => {
const fullMatch = match[0];
const orcidId = match[1]; // The captured ORCID ID
const startIndex = match.index;
const endIndex = startIndex + fullMatch.length;
// Add text before the match
if (startIndex > lastIndex) {
fragment.appendChild(document.createTextNode(text.slice(lastIndex, startIndex)));
}
// Create enhanced ORCID ID element
const orcidElement = createORCIDElement(fullMatch, orcidId);
fragment.appendChild(orcidElement);
lastIndex = endIndex;
});
// Add remaining text
if (lastIndex < text.length) {
fragment.appendChild(document.createTextNode(text.slice(lastIndex)));
}
// Replace the original text node
parent.replaceChild(fragment, textNode);
}
// Create interactive ORCID ID element
function createORCIDElement(originalText, orcidId) {
const container = document.createElement('span');
container.className = 'orcid-detector-container';
container.style.position = 'relative';
container.style.display = 'inline';
// Original ORCID text (now clickable)
const textSpan = document.createElement('span');
textSpan.textContent = originalText;
textSpan.className = 'orcid-detector-text';
textSpan.style.cursor = 'pointer';
textSpan.style.color = '#A6CE39';
textSpan.style.textDecoration = 'underline';
textSpan.title = 'Click to view ORCID profile';
// Magnifying glass icon
const logoSpan = document.createElement('span');
logoSpan.className = 'orcid-detector-logo';
logoSpan.innerHTML = `
<svg width="16" height="16" viewBox="-10 -10 300 300" style="margin-left: -2px; vertical-align: 2px; cursor: pointer;">
<circle cx="120" cy="120" r="85" fill="none" stroke="#8FB82B" stroke-width="24"/>
<circle cx="120" cy="120" r="42" fill="none" stroke="#8FB82B" stroke-width="18"/>
<line x1="175" y1="175" x2="250" y2="250" stroke="#8FB82B" stroke-width="28" stroke-linecap="round"/>
</svg>
`;
logoSpan.title = 'View ORCID profile';
// Add click handlers
const clickHandler = (e) => {
e.preventDefault();
e.stopPropagation();
showORCIDPopup(orcidId, e.target);
};
textSpan.addEventListener('click', clickHandler);
logoSpan.addEventListener('click', clickHandler);
container.appendChild(textSpan);
container.appendChild(logoSpan);
return container;
}
// Show ORCID profile popup
async function showORCIDPopup(orcidId, targetElement) {
// Remove any existing popups
removeExistingPopups();
// Show loading popup first
const loadingPopup = createLoadingPopup();
document.body.appendChild(loadingPopup);
positionPopup(loadingPopup, targetElement);
try {
// Fetch ORCID profile data
const profileData = await fetchORCIDProfile(orcidId);
// Remove loading popup
document.body.removeChild(loadingPopup);
// Create and show profile popup
const popup = createProfilePopup(orcidId, profileData);
document.body.appendChild(popup);
positionPopup(popup, targetElement);
// Add click outside to close
setTimeout(() => {
document.addEventListener('click', handleOutsideClick);
}, 100);
} catch (error) {
console.error('Error fetching ORCID profile:', error);
document.body.removeChild(loadingPopup);
// Show error popup
const errorPopup = createErrorPopup(orcidId, error.message);
document.body.appendChild(errorPopup);
positionPopup(errorPopup, targetElement);
}
}
// Fetch ORCID profile data from API
async function fetchORCIDProfile(orcidId) {
// Check cache first
if (profileCache.has(orcidId)) {
return profileCache.get(orcidId);
}
// Fetch multiple endpoints for comprehensive profile data
const endpoints = {
person: `https://pub.orcid.org/v3.0/${orcidId}/person`,
works: `https://pub.orcid.org/v3.0/${orcidId}/works`,
employments: `https://pub.orcid.org/v3.0/${orcidId}/employments`,
educations: `https://pub.orcid.org/v3.0/${orcidId}/educations`,
fundings: `https://pub.orcid.org/v3.0/${orcidId}/fundings`
};
const results = {};
// Fetch all endpoints in parallel
const promises = Object.entries(endpoints).map(async ([key, url]) => {
try {
const response = await fetch(url, {
headers: { 'Accept': 'application/json' }
});
if (response.ok) {
results[key] = await response.json();
} else {
results[key] = null;
}
} catch (error) {
console.warn(`Failed to fetch ${key}:`, error);
results[key] = null;
}
});
await Promise.all(promises);
// Cache the result
profileCache.set(orcidId, results);
return results;
}
// Create loading popup
function createLoadingPopup() {
const popup = document.createElement('div');
popup.className = 'orcid-detector-popup loading';
popup.innerHTML = `
<div class="orcid-popup-content">
<div class="loading-spinner"></div>
<p>Loading ORCID profile...</p>
</div>
`;
return popup;
}
// Create profile popup
function createProfilePopup(orcidId, profileData) {
const popup = document.createElement('div');
popup.className = 'orcid-detector-popup';
// Extract data from different API endpoints
const person = profileData.person || {};
const works = profileData.works || {};
const employments = profileData.employments || {};
const educations = profileData.educations || {};
const fundings = profileData.fundings || {};
// Person information
const name = person.name ?
(person.name['given-names']?.value || '') + ' ' + (person.name['family-name']?.value || '') : 'Name not available';
const biography = person.biography?.content || null;
const urls = person['researcher-urls']?.['researcher-url'] || [];
const keywords = person.keywords?.keyword || [];
const emails = person.emails?.email || [];
// Work information
const worksList = works.group || [];
const worksCount = worksList.length;
// Employment information
const employmentsList = employments['affiliation-group'] || [];
// Get the first employment summary from the first group
const currentEmployment = employmentsList[0]?.summaries?.[0]?.['employment-summary'] || null;
// Education information
const educationsList = educations['affiliation-group'] || [];
// Get the first education summary from the first group
const highestEducation = educationsList[0]?.summaries?.[0]?.['education-summary'] || null;
// Funding information
const fundingsList = fundings.group || [];
const fundingsCount = fundingsList.length;
popup.innerHTML = `
<div class="orcid-popup-content">
<div class="orcid-popup-header">
<div class="orcid-logo-header">
<svg width="20" height="20" viewBox="-10 -10 300 300">
<circle cx="120" cy="120" r="85" fill="none" stroke="white" stroke-width="24"/>
<circle cx="120" cy="120" r="42" fill="none" stroke="white" stroke-width="18"/>
<line x1="175" y1="175" x2="250" y2="250" stroke="white" stroke-width="28" stroke-linecap="round"/>
</svg>
</div>
<button class="orcid-popup-close">×</button>
</div>
<div class="orcid-profile-info">
<h3>${escapeHtml(name.trim()) || 'Name not provided'}</h3>
<p class="orcid-id">
<a href="https://orcid.org/${escapeHtml(orcidId)}" target="_blank" rel="noopener">
https://orcid.org/${escapeHtml(orcidId)}
</a>
</p>
${biography ? `
<div class="orcid-section">
<h4>Biography</h4>
<p class="biography">${escapeHtml(biography.length > 150 ? biography.substring(0, 150) + '...' : biography)}</p>
</div>
` : ''}
${currentEmployment ? `
<div class="orcid-section">
<h4>Current Position</h4>
<p><strong>${escapeHtml(currentEmployment['role-title'] || 'Position not specified')}</strong></p>
<p>${escapeHtml(currentEmployment.organization?.name || 'Organization not specified')}</p>
${currentEmployment['start-date'] ? `
<p class="date-info">Since ${escapeHtml(currentEmployment['start-date'].year?.value || '')}</p>
` : ''}
</div>
` : ''}
${highestEducation ? `
<div class="orcid-section">
<h4>Education</h4>
<p><strong>${escapeHtml(highestEducation['role-title'] || 'Degree not specified')}</strong></p>
<p>${escapeHtml(highestEducation.organization?.name || 'Institution not specified')}</p>
${highestEducation['end-date'] ? `
<p class="date-info">${escapeHtml(highestEducation['end-date'].year?.value || '')}</p>
` : ''}
</div>
` : ''}
<div class="orcid-section orcid-stats">
<h4>Research Activity</h4>
<div class="stats-grid">
<div class="stat-item">
<span class="stat-number">${worksCount}</span>
<span class="stat-label">Works</span>
</div>
<div class="stat-item">
<span class="stat-number">${employmentsList.length}</span>
<span class="stat-label">Positions</span>
</div>
<div class="stat-item">
<span class="stat-number">${educationsList.length}</span>
<span class="stat-label">Education</span>
</div>
<div class="stat-item">
<span class="stat-number">${fundingsCount}</span>
<span class="stat-label">Funding</span>
</div>
</div>
</div>
${keywords.length > 0 ? `
<div class="orcid-section">
<h4>Keywords</h4>
<div class="keywords">
${keywords.slice(0, 5).map(keyword => `
<span class="keyword-tag">${escapeHtml(keyword.content || keyword)}</span>
`).join('')}
</div>
</div>
` : ''}
${urls.length > 0 ? `
<div class="orcid-section">
<h4>External Links</h4>
<div class="external-links">
${urls.slice(0, 4).map(url => `
<a href="${escapeHtml(url.url.value)}" target="_blank" rel="noopener" class="orcid-link">
${escapeHtml(url['url-name'] || 'Link')}
</a>
`).join('')}
</div>
</div>
` : ''}
${worksCount > 0 ? `
<div class="orcid-section">
<h4>Recent Works</h4>
${worksList.slice(0, 3).map(group => {
const work = group['work-summary']?.[0];
if (!work) return '';
return `
<div class="work-item">
<p class="work-title">${escapeHtml(work.title?.title?.value || 'Untitled work')}</p>
<p class="work-type">${escapeHtml(work.type || 'Unknown type')} ${work['publication-date']?.year?.value ? '(' + escapeHtml(work['publication-date'].year.value) + ')' : ''}</p>
</div>
`;
}).join('')}
${worksCount > 3 ? `<p class="more-info">+${escapeHtml(worksCount - 3)} more works</p>` : ''}
</div>
` : ''}
</div>
</div>
`;
// Add close button handler
const closeButton = popup.querySelector('.orcid-popup-close');
closeButton.addEventListener('click', () => {
removeExistingPopups();
});
return popup;
}
// Create error popup
function createErrorPopup(orcidId, errorMessage) {
const popup = document.createElement('div');
popup.className = 'orcid-detector-popup error';
popup.innerHTML = `
<div class="orcid-popup-content">
<div class="orcid-popup-header">
<h3>Error Loading Profile</h3>
<button class="orcid-popup-close">×</button>
</div>
<div class="orcid-profile-info">
<p>Could not load profile for ${escapeHtml(orcidId)}</p>
<p class="error-message">${escapeHtml(errorMessage)}</p>
<p class="orcid-id">
<a href="https://orcid.org/${escapeHtml(orcidId)}" target="_blank" rel="noopener">
View on ORCID.org
</a>
</p>
</div>
</div>
`;
const closeButton = popup.querySelector('.orcid-popup-close');
closeButton.addEventListener('click', removeExistingPopups);
return popup;
}
// Position popup relative to target element
function positionPopup(popup, targetElement) {
const rect = targetElement.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
popup.style.position = 'absolute';
popup.style.top = (rect.bottom + scrollTop + 5) + 'px';
popup.style.left = (rect.left + scrollLeft) + 'px';
popup.style.zIndex = '10000';
// Adjust if popup goes outside viewport
const popupRect = popup.getBoundingClientRect();
if (popupRect.right > window.innerWidth) {
popup.style.left = (window.innerWidth - popupRect.width - 10) + 'px';
}
if (popupRect.bottom > window.innerHeight) {
popup.style.top = (rect.top + scrollTop - popupRect.height - 5) + 'px';
}
}
// Remove existing popups
function removeExistingPopups() {
const existingPopups = document.querySelectorAll('.orcid-detector-popup');
existingPopups.forEach(popup => popup.remove());
document.removeEventListener('click', handleOutsideClick);
}
// Handle clicks outside popup
function handleOutsideClick(e) {
if (!e.target.closest('.orcid-detector-popup') &&
!e.target.closest('.orcid-detector-container')) {
removeExistingPopups();
}
}
// Setup mutation observer for dynamic content
function setupMutationObserver() {
const observer = new MutationObserver((mutations) => {
let hasNewContent = false;
mutations.forEach((mutation) => {
if (mutation.type === 'childList') {
mutation.addedNodes.forEach((node) => {
// Skip our own ORCID detector elements
if (node.nodeType === Node.ELEMENT_NODE &&
(node.classList?.contains('orcid-detector-container') ||
node.classList?.contains('orcid-detector-popup') ||
node.closest?.('.orcid-detector-container'))) {
return;
}
if (node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE) {
hasNewContent = true;
}
});
}
});
if (hasNewContent) {
// Debounce processing to avoid excessive calls
clearTimeout(window.orcidDetectorTimeout);
window.orcidDetectorTimeout = setTimeout(() => {
// Process any new ORCID links with logos
processExistingORCIDLinks();
// Process text nodes for ORCID IDs
const newTextNodes = getTextNodes(document.body);
newTextNodes.forEach(processTextNode);
}, 500);
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
}
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();