Repository navigation
Expand file tree
/
Copy pathpopup.js
More file actions
585 lines (537 loc) · 26.3 KB
/
Copy pathpopup.js
File metadata and controls
585 lines (537 loc) · 26.3 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
'use strict';
document.addEventListener('DOMContentLoaded', () => {
const api = globalThis.NotandiaPublisherProfiles;
if (!api) throw new Error('Publisher profile runtime failed to load');
const $ = id => document.getElementById(id);
const selectOption = (select, value) => {
const option = Array.from(select?.options || []).find(item => item.value === value);
if (option) option.selected = true;
};
const el = {
settings: $('settingsIcon'), panel: $('settingsPanel'), quickProfiles: $('quickProfiles'), save: $('save'), status: $('status'),
integrity: $('integrityLookupsEnabled'), ncbi: $('ncbiApiEnabledPopup'), logging: $('loggingEnabled'), language: $('interfaceLanguagePopup'), community: $('communityWarningsEnabledPopup'), manage: $('managePublishers'),
articleSection: $('articleContextSection'), article: $('articleContext'), articleSummary: $('articleContextSummary'), integrityCoverage: $('integrityCoverage'),
contextList: $('contextList'), referencesSummary: $('referencesSummary'), contextFilter: $('contextFilter'), contextSort: $('contextSort'),
rescan: $('rescan'), report: $('reportIssue'), reportCategory: $('reportCategory')
};
const countIds = { retracted: 'countRetracted', 'expression-of-concern': 'countConcern', corrected: 'countCorrected', withdrawn: 'countWithdrawn' };
let watchlist = api.defaultSettings();
let evidenceProfiles = api.profileMap(watchlist);
let publisherReport = null;
let integrityReport = null;
let integrityStatuses = {};
let publisherScanning = true;
let restoreInFlight = false;
let reloadQueued = false;
const setStatus = globalThis.NotandiaStatusMessages.create(el.status, 3500);
function rgba(hex, alpha) {
const match = /^#([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i.exec(String(hex || ''));
if (!match) return `rgba(72,98,122,${alpha})`;
return `rgba(${parseInt(match[1], 16)},${parseInt(match[2], 16)},${parseInt(match[3], 16)},${alpha})`;
}
function escapeRegExp(value) {
return String(value || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function cleanReferenceText(record) {
let text = String(record?.text || '').replace(/\s+/g, ' ').trim();
if (!text) return '';
text = text
.replace(/https?:\/\/\S+/gi, ' ')
.replace(/\bPubMed Central\b/gi, ' ')
.replace(/\bGoogle Scholar\b/gi, ' ')
.replace(/\bPubMed\b/gi, ' ')
.replace(/\bCAS\b/g, ' ')
.replace(/\bArticle\b(?=\s*(?:$|[.,;]))/gi, ' ');
const doi = String(record?.doi || '').trim();
if (doi) {
const pattern = new RegExp(`(?:doi\\s*:\\s*)?(?:https?:\\/\\/(?:dx\\.)?doi\\.org\\/)?${escapeRegExp(doi)}`, 'ig');
text = text.replace(pattern, ' ');
}
text = text
.replace(/\s+([,.;:)])/g, '$1')
.replace(/([,.;:])(?:\s*\1)+/g, '$1')
.replace(/\.\s*\./g, '.')
.replace(/\s{2,}/g, ' ')
.replace(/[\s,;:.-]+$/g, '')
.trim();
return text.slice(0, 420);
}
function usesFirefoxDataConsent() {
const optional = chrome.runtime.getManifest().browser_specific_settings?.gecko?.data_collection_permissions?.optional;
return Array.isArray(optional) && optional.includes('websiteContent') && Boolean(globalThis.browser?.permissions);
}
async function hasFirefoxDataConsent() {
if (!usesFirefoxDataConsent()) return true;
const permissions = await browser.permissions.getAll();
return Array.isArray(permissions.data_collection) && permissions.data_collection.includes('websiteContent');
}
async function setFirefoxDataConsent(enabled) {
if (!usesFirefoxDataConsent()) return true;
if (enabled) return browser.permissions.request({ data_collection: ['websiteContent'] });
await browser.permissions.remove({ data_collection: ['websiteContent'] });
return true;
}
function chip(label, color, extraClass = '') {
const node = document.createElement('span');
node.className = `chip ${extraClass}`.trim();
node.textContent = label;
if (color) {
node.style.setProperty('--chip-color', color);
node.style.setProperty('--chip-ink', api.readableColor(color));
}
return node;
}
function statusDefinition(status) {
return integrityStatuses?.[status] || null;
}
function uniqueIntegrityEvents(events) {
const byStatus = new Map();
for (const event of Array.isArray(events) ? events : []) {
const status = String(event?.status || '');
if (!status) continue;
const existing = byStatus.get(status);
if (!existing || Number(event?.timestamp || 0) > Number(existing?.timestamp || 0)) byStatus.set(status, event);
}
return Array.from(byStatus.values()).sort((left, right) => {
const leftSeverity = Number(statusDefinition(left.status)?.severity || 0);
const rightSeverity = Number(statusDefinition(right.status)?.severity || 0);
return rightSeverity - leftSeverity || String(left.status).localeCompare(String(right.status));
});
}
function refreshContextFilterOptions() {
const previous = el.contextFilter.value || 'all';
const options = [
['all', 'All results'],
['integrity:any', 'Formal updates'],
['status:retracted', 'Retracted'],
['status:expression-of-concern', 'Expression of concern'],
['status:corrected', 'Corrected'],
['status:withdrawn', 'Withdrawn'],
['publisher:any', 'Publisher matches']
];
const matchedProfiles = new Set([...(publisherReport?.references || []), ...(publisherReport?.searchResults || [])].flatMap(record => (record.matches || []).map(match => match.profileId)));
for (const profile of api.effectiveProfiles(watchlist).filter(profile => profile.enabled && (profile.source !== 'community' || matchedProfiles.has(profile.id)))) {
options.push([`profile:${profile.id}`, profile.name]);
}
el.contextFilter.replaceChildren();
for (const [value, label] of options) {
const option = document.createElement('option');
option.value = value;
option.textContent = label;
el.contextFilter.appendChild(option);
}
el.contextFilter.value = options.some(([value]) => value === previous) ? previous : 'all';
}
function renderQuickProfiles() {
el.quickProfiles.replaceChildren();
el.community.checked = watchlist.communityWarningsEnabled;
for (const profile of watchlist.profiles) {
const row = document.createElement('div');
row.className = 'quick-profile';
row.dataset.profileId = profile.id;
const label = document.createElement('label');
const enabled = document.createElement('input');
enabled.type = 'checkbox';
enabled.className = 'quick-enabled';
enabled.checked = profile.enabled;
const name = document.createElement('strong');
name.textContent = profile.name;
label.append(enabled, name);
const action = document.createElement('select');
action.className = 'quick-action';
action.setAttribute('aria-label', `${profile.name} action`);
for (const value of api.ACTIONS) {
const option = document.createElement('option');
option.value = value;
option.textContent = { none: 'Context', badge: 'Badge', highlight: 'Highlight', dim: 'Dim', hide: 'Hide' }[value];
option.selected = value === profile.action;
action.appendChild(option);
}
const color = document.createElement('input');
color.type = 'color';
color.className = 'quick-color';
color.value = profile.color;
color.title = `${profile.name} color`;
color.setAttribute('aria-label', `${profile.name} color`);
row.append(label, action, color);
el.quickProfiles.appendChild(row);
}
refreshContextFilterOptions();
}
function readQuickProfiles() {
const byId = new Map(watchlist.profiles.map(profile => [profile.id, profile]));
for (const row of el.quickProfiles.querySelectorAll('.quick-profile')) {
const profile = byId.get(row.dataset.profileId);
if (!profile) continue;
profile.enabled = row.querySelector('.quick-enabled').checked;
profile.action = row.querySelector('.quick-action').value;
profile.color = row.querySelector('.quick-color').value;
}
watchlist = api.sanitizeSettings({ ...watchlist, profiles: Array.from(byId.values()), communityWarningsEnabled: el.community.checked });
refreshContextFilterOptions();
}
function appendIntegrityChips(container, events, primaryStatus) {
for (const event of uniqueIntegrityEvents(events)) {
const definition = statusDefinition(event.status);
const label = definition?.label || event.status;
const color = definition?.color || '#B42318';
const extraClass = event.status === primaryStatus ? 'integrity primary-integrity' : 'integrity';
container.appendChild(chip(label, color, extraClass));
}
}
function appendPublisherEvidence(container, matches) {
for (const match of matches || []) {
const profile = evidenceProfiles.get(match.profileId);
if (!profile || !['builtin', 'preset', 'community'].includes(profile.source)) continue;
const context = api.matchContext(profile, match);
if (!context) continue;
const details = document.createElement('details');
details.className = 'publisher-evidence';
const summary = document.createElement('summary');
summary.textContent = match.publicationType ? `About this ${api.publicationTypeLabel(match.publicationType).toLowerCase()}` : profile.source === 'community' ? `Why ${profile.name} is listed` : `Why ${profile.name} is on the watchlist`;
const explanation = document.createElement('p');
explanation.textContent = `${context.assessment}. ${context.explanation} ${context.evidence} Reviewed ${context.reviewed}.`;
details.append(summary, explanation);
for (const source of context.sources) {
const link = document.createElement('a');
link.href = source.url;
link.textContent = source.label;
link.target = '_blank';
link.rel = 'noopener noreferrer';
details.appendChild(link);
}
container.appendChild(details);
}
}
function appendPublicationTypeChips(container, matches) {
const labels = new Set((matches || []).map(match => api.publicationTypeLabel(match.publicationType)).filter(Boolean));
for (const label of labels) container.appendChild(chip(label, '#48627A'));
}
function renderArticleContext() {
el.article.replaceChildren();
const matches = publisherReport?.currentArticle?.matches || [];
const currentIntegrity = (integrityReport?.records || []).find(record => record.kind === 'current-article');
if (!matches.length && !currentIntegrity?.primaryStatus) {
el.articleSection.hidden = true;
el.articleSummary.textContent = '';
return;
}
el.articleSection.hidden = false;
const title = document.createElement('strong');
title.textContent = matches.length ? matches.map(match => match.profileName).join(', ') : 'Formal update found';
const doi = document.createElement('code');
doi.textContent = publisherReport?.currentArticle?.doi || currentIntegrity?.doi || '';
const chips = document.createElement('div');
chips.className = 'chip-row';
for (const match of matches) chips.appendChild(chip(match.profileName, match.color));
appendPublicationTypeChips(chips, matches);
appendIntegrityChips(chips, currentIntegrity?.events || [], currentIntegrity?.primaryStatus);
el.article.append(title);
if (doi.textContent) el.article.append(doi);
el.article.append(chips);
appendPublisherEvidence(el.article, matches);
const parts = [];
if (matches.length) parts.push(`${matches.length} publisher match${matches.length === 1 ? '' : 'es'}`);
if (currentIntegrity?.primaryStatus) parts.push('formal update');
el.articleSummary.textContent = parts.join(' · ');
}
function setIntegrityCounts() {
// Count the same distinct works offered by the reference list. The current
// article has its own section and must not inflate reference filter totals.
const worksByStatus = new Map();
for (const record of integrityReport?.records || []) {
if (record.kind === 'current-article' || !record.primaryStatus) continue;
const statuses = new Set([record.primaryStatus, ...uniqueIntegrityEvents(record.events).map(event => event.status)]);
for (const status of statuses) {
if (!worksByStatus.has(status)) worksByStatus.set(status, new Set());
worksByStatus.get(status).add(recordKey(record));
}
}
const counts = Object.fromEntries(Array.from(worksByStatus, ([status, works]) => [status, works.size]));
for (const [status, id] of Object.entries(countIds)) {
const count = Number(counts[status]) || 0;
const node = $(id);
node.textContent = String(count);
const card = node.closest('[data-context-filter]');
const active = card?.dataset.contextFilter === el.contextFilter.value;
if (card) card.hidden = count === 0 && !active;
}
if (!el.integrity.checked) el.integrityCoverage.textContent = 'Formal checks off';
else if (!integrityReport) el.integrityCoverage.textContent = 'Waiting for DOI records';
else if (integrityReport.state === 'loading') el.integrityCoverage.textContent = `Checking ${integrityReport.attempted || 0} DOI records`;
else {
const summary = integrityReport.summary || {};
const parts = [`${summary.checked || 0} checked`];
if (summary.failed) parts.push(`${summary.failed} not verified`);
if (integrityReport.notChecked) parts.push(`${integrityReport.notChecked} deferred`);
el.integrityCoverage.textContent = parts.join(' · ');
}
}
function recordKey(record) {
return record?.doi ? `doi:${record.doi.toLowerCase()}` : `id:${record?.id || ''}`;
}
function recordMatchesFilter(record) {
const filter = el.contextFilter.value || 'all';
if (filter === 'all') return true;
if (filter === 'publisher:any') return (record.matches || []).length > 0;
if (filter === 'integrity:any') return Boolean(record.primaryStatus);
if (filter.startsWith('status:')) {
const status = filter.slice('status:'.length);
return record.primaryStatus === status || uniqueIntegrityEvents(record.events).some(event => event.status === status);
}
if (filter.startsWith('profile:')) {
const profileId = filter.slice('profile:'.length);
return (record.matches || []).some(match => match.profileId === profileId);
}
return true;
}
function recordSeverity(record) {
const statuses = uniqueIntegrityEvents(record.events).map(event => Number(statusDefinition(event.status)?.severity || 0));
if (record.primaryStatus) statuses.push(Number(statusDefinition(record.primaryStatus)?.severity || 0));
return Math.max(0, ...statuses);
}
function recordAccent(record) {
const definition = statusDefinition(record.primaryStatus);
if (definition?.color) return definition.color;
return api.resolveVisualMatch(record.matches || [])?.color || null;
}
function renderContextList() {
el.contextList.replaceChildren();
const merged = new Map();
for (const record of [...(publisherReport?.references || []), ...(publisherReport?.searchResults || [])]) {
merged.set(recordKey(record), { ...record, matches: record.matches || [], events: [] });
}
for (const record of integrityReport?.records || []) {
if (record.kind === 'current-article') continue;
const key = recordKey(record);
const existing = merged.get(key) || { id: record.id, kind: record.kind, number: record.number, doi: record.doi, text: record.text, matches: [] };
existing.events = uniqueIntegrityEvents(record.events || []);
existing.primaryStatus = record.primaryStatus;
merged.set(key, existing);
}
const allRecords = Array.from(merged.values()).filter(record => (record.matches || []).length || record.primaryStatus);
refreshContextFilterOptions();
const records = allRecords.filter(recordMatchesFilter);
const sortMode = el.contextSort.value || 'reference';
records.sort((left, right) => {
if (sortMode === 'severity') {
const severityDifference = recordSeverity(right) - recordSeverity(left);
if (severityDifference) return severityDifference;
}
return (left.number || 9999) - (right.number || 9999);
});
if (!records.length) {
const placeholder = document.createElement('li');
placeholder.className = 'placeholder';
placeholder.textContent = allRecords.length
? 'No references match this filter.'
: !publisherReport || publisherScanning
? 'Reference checks are still running. Refresh the page if checks do not finish.'
: 'No publisher matches or known formal updates were found.';
el.contextList.appendChild(placeholder);
el.referencesSummary.textContent = allRecords.length ? `0 of ${allRecords.length} references shown`
: !publisherReport || publisherScanning ? 'Waiting for reference checks…' : 'Nothing to review';
return;
}
for (const record of records) {
const item = document.createElement('li');
item.className = 'context-item';
const accent = recordAccent(record);
if (accent) {
item.classList.add('context-item-accented');
item.style.setProperty('--context-accent', accent);
item.style.setProperty('--context-tint', rgba(accent, 0.025));
}
if (record.id) {
item.dataset.refId = record.id;
item.tabIndex = 0;
}
const heading = document.createElement('div');
heading.className = 'context-item-heading';
const label = document.createElement('strong');
label.textContent = record.kind === 'search-result' ? `Search result ${record.number || ''}`.trim() : `Reference ${record.number || ''}`.trim();
const doi = document.createElement('code');
doi.textContent = record.doi || '';
doi.title = record.doi || '';
heading.append(label, doi);
item.appendChild(heading);
const cleanedText = cleanReferenceText(record);
if (cleanedText) {
const text = document.createElement('p');
text.textContent = cleanedText;
text.title = cleanedText;
item.appendChild(text);
}
const chips = document.createElement('div');
chips.className = 'chip-row';
for (const match of record.matches || []) chips.appendChild(chip(match.profileName, match.color));
appendPublicationTypeChips(chips, record.matches);
appendIntegrityChips(chips, record.events || [], record.primaryStatus);
if (chips.childElementCount) item.appendChild(chips);
appendPublisherEvidence(item, record.matches);
el.contextList.appendChild(item);
}
el.referencesSummary.textContent = records.length === allRecords.length
? `${records.length} reference${records.length === 1 ? '' : 's'} shown`
: `${records.length} of ${allRecords.length} references shown`;
}
function renderAll() {
evidenceProfiles = api.profileMap(watchlist);
renderArticleContext();
setIntegrityCounts();
renderContextList();
}
function fetchReports() {
chrome.runtime.sendMessage({ type: 'getContextScanState' }, response => {
if (!chrome.runtime.lastError) {
publisherScanning = response?.publisherScanning === true;
renderAll();
}
});
chrome.runtime.sendMessage({ type: 'getPublisherContext' }, response => {
if (!chrome.runtime.lastError) {
publisherReport = response?.report || null;
renderAll();
}
});
chrome.runtime.sendMessage({ type: 'getIntegrityReport' }, response => {
if (!chrome.runtime.lastError) {
integrityReport = response?.report || null;
integrityStatuses = response?.statuses || {};
renderAll();
}
});
}
function loadReports() {
if (restoreInFlight) {
reloadQueued = true;
return;
}
restoreInFlight = true;
chrome.runtime.sendMessage({ type: 'restorePersistedTabState' }, () => {
void chrome.runtime.lastError;
restoreInFlight = false;
fetchReports();
if (reloadQueued) {
reloadQueued = false;
setTimeout(loadReports, 25);
}
});
}
function forceRescan() {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
if (!Number.isInteger(tabs[0]?.id)) return;
chrome.tabs.sendMessage(tabs[0].id, { type: 'forcePublisherRescan' }, () => void chrome.runtime.lastError);
chrome.tabs.sendMessage(tabs[0].id, { type: 'forceIntegrityRescan' }, () => void chrome.runtime.lastError);
setTimeout(loadReports, 500);
setTimeout(loadReports, 1600);
});
}
el.settings.addEventListener('click', () => {
const open = el.panel.classList.toggle('open');
el.settings.setAttribute('aria-expanded', String(open));
el.settings.setAttribute('aria-label', open ? 'Back to results' : 'Open quick settings');
el.settings.querySelector('.settings-glyph').textContent = open ? '←' : '⚙';
el.settings.querySelector('.settings-label').textContent = open ? 'Results' : 'Settings';
document.querySelector('.container').classList.toggle('settings-open', open);
});
el.manage.addEventListener('click', () => chrome.runtime.openOptionsPage());
el.rescan.addEventListener('click', forceRescan);
el.contextFilter.addEventListener('change', () => {
setIntegrityCounts();
renderContextList();
});
el.contextSort.addEventListener('change', renderContextList);
el.contextList.addEventListener('click', event => {
if (event.target.closest('a, button, input, select, textarea, summary')) return;
const item = event.target.closest('li[data-ref-id]');
if (!item) return;
chrome.runtime.sendMessage({ type: 'scrollToRef', refId: item.dataset.refId }, () => void chrome.runtime.lastError);
});
el.contextList.addEventListener('keydown', event => {
if (!['Enter', ' '].includes(event.key)) return;
if (event.target.closest('a, button, input, select, textarea, summary')) return;
const item = event.target.closest('li[data-ref-id]');
if (!item) return;
event.preventDefault();
chrome.runtime.sendMessage({ type: 'scrollToRef', refId: item.dataset.refId }, () => void chrome.runtime.lastError);
});
el.save.addEventListener('click', () => {
void (async () => {
readQuickProfiles();
const consent = await setFirefoxDataConsent(el.integrity.checked || el.ncbi.checked).catch(() => false);
if ((el.integrity.checked || el.ncbi.checked) && !consent) {
el.integrity.checked = false;
el.ncbi.checked = false;
return setStatus('Firefox data permission was not granted.');
}
const mdpi = watchlist.profiles.find(profile => profile.id === 'mdpi');
chrome.storage.sync.set({
publisherWatchlist: watchlist,
interfaceLanguage: el.language.value,
integrityLookupsEnabled: el.integrity.checked,
ncbiApiEnabled: el.ncbi.checked,
loggingEnabled: el.logging.checked,
mode: mdpi?.action === 'hide' ? 'hide' : 'highlight',
highlightPotentialMdpiSites: mdpi?.confidencePolicy === 'confirmed-and-potential',
potentialMdpiHighlightColor: mdpi?.color || api.BUILTIN_PROFILES[0].color
}, () => {
if (chrome.runtime.lastError) return setStatus('Could not save settings.');
chrome.storage.local?.set({ notandiaLookupSetupDismissed: true }, () => void chrome.runtime.lastError);
setStatus('Settings saved.');
globalThis.NotandiaI18n?.setLanguage(el.language.value);
chrome.tabs.query({}, tabs => {
for (const tab of tabs || []) {
if (!Number.isInteger(tab.id)) continue;
chrome.tabs.sendMessage(tab.id, { type: 'notandiaSetInterfaceLanguage', language: el.language.value }, () => void chrome.runtime.lastError);
}
});
forceRescan();
});
})();
});
el.report.addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
try {
const parsed = new URL(tabs[0]?.url || '');
if (!/^https?:$/.test(parsed.protocol)) throw new Error();
const address = `${parsed.origin}${parsed.pathname}`;
const manifest = chrome.runtime.getManifest();
const enabledProfiles = api.effectiveProfiles(watchlist).filter(profile => profile.enabled).map(profile => profile.id).join(', ') || 'none';
const category = el.reportCategory.value;
const title = encodeURIComponent(`[${category}] Context issue on ${parsed.hostname}`);
const body = encodeURIComponent(`**Notandia article/context report**\n\n**Category:** ${category}\n\n**Page address (query and fragment omitted):**\n${address}\n\n**What happened?**\n[Describe the incorrect or missing context. Add a DOI or citation only when useful and safe to share.]\n\n---\n- Extension version: ${manifest.version}\n- Enabled publisher profiles: ${enabledProfiles}\n- Integrity checks: ${el.integrity.checked ? 'enabled' : 'disabled'}\n- Browser: ${navigator.userAgent}`);
chrome.tabs.create({ url: `https://github.com/notandia/browser-extension/issues/new?title=${title}&body=${body}` });
} catch {
setStatus('Reports are available only for web pages.');
}
});
});
chrome.runtime.onMessage.addListener(message => {
if (['integrityReportUpdated', 'publisherContextUpdated', 'publisherScanStateUpdated'].includes(message?.type)) loadReports();
});
chrome.storage.sync.get({
publisherWatchlist: null,
mode: null,
highlightPotentialMdpiSites: null,
potentialMdpiHighlightColor: null,
integrityLookupsEnabled: false,
ncbiApiEnabled: false,
loggingEnabled: false,
interfaceLanguage: 'system'
}, stored => {
watchlist = api.migrateLegacySettings(stored);
selectOption(el.language, ['system', 'en', 'it'].includes(stored.interfaceLanguage) ? stored.interfaceLanguage : 'system');
renderQuickProfiles();
el.ncbi.checked = stored.ncbiApiEnabled === true;
el.logging.checked = stored.loggingEnabled === true;
void hasFirefoxDataConsent().then(permitted => {
el.integrity.checked = stored.integrityLookupsEnabled === true && permitted;
el.ncbi.checked = stored.ncbiApiEnabled === true && permitted;
renderAll();
}).catch(() => { el.integrity.checked = false; el.ncbi.checked = false; });
if (!stored.publisherWatchlist || stored.publisherWatchlist.schemaVersion !== api.SCHEMA_VERSION) chrome.storage.sync.set({ publisherWatchlist: watchlist });
loadReports();
setTimeout(loadReports, 500);
});
});