-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1459 lines (1207 loc) · 52.9 KB
/
script.js
File metadata and controls
1459 lines (1207 loc) · 52.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
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
let map;
let markersLayer;
let lang = 'en';
let currentPage = 0; // ONLY DECLARATION
const resultsPerPage = 20; // ONLY DECLARATION
let originalContext = null;
let isSearching = false;
let itemSitelinks = {}; // Cache: { qid: { projectType: [{ lang, title, url }, ...] } }
let itemAuthorityIds = {}; // Cache: { qid: [{ propertyId, propertyLabel, value, url }] }
let itemWikidataUrls = {}; // Cache: { qid: [{ propertyId, propertyLabel, url }] }
let currentDisplayedQids = []; // QIDs currently shown in the result list
let fetchedAuthorityIdsForQids = new Set(); // QIDs whose authority IDs have already been fetched
let fetchedWikidataUrlsForQids = new Set(); // QIDs whose Wikidata URLs have already been fetched
// ===== AUTHORITY URL ACCESSIBILITY CACHE =====
// Persists iframe-embedding status of authority URLs across sessions so blocked
// sources are ranked lower in the dropdown without rechecking every page load.
// Values per URL: 'accessible' | 'blocked' | 'unknown'
const AUTHORITY_ACCESS_STORAGE_KEY = 'authorityAccessCache';
function loadAuthorityAccessCache() {
try {
const stored = localStorage.getItem(AUTHORITY_ACCESS_STORAGE_KEY);
return stored ? JSON.parse(stored) : {};
} catch {
return {};
}
}
function saveAuthorityAccessCache() {
try {
localStorage.setItem(AUTHORITY_ACCESS_STORAGE_KEY, JSON.stringify(authorityAccessCache));
} catch (e) {
console.warn('Could not save authority access cache:', e);
}
}
// Cache object: { [url: string]: 'accessible' | 'blocked' | 'unknown' }
let authorityAccessCache = loadAuthorityAccessCache();
/**
* AUTHORITY URL ACCESSIBILITY CHECK
* Sends a CORS HEAD request to the URL and inspects the X-Frame-Options and
* Content-Security-Policy response headers to determine whether the page can be
* embedded in an iframe.
*
* Possible return values:
* 'accessible' – no framing restrictions detected in headers
* 'blocked' – X-Frame-Options DENY/SAMEORIGIN or CSP frame-ancestors blocks embedding
* 'unknown' – CORS prevented reading headers (iframe may still work)
*
* Results are stored in authorityAccessCache and persisted to localStorage so
* each URL is only checked once.
*/
async function checkAuthorityUrl(url) {
if (authorityAccessCache[url] !== undefined) {
return authorityAccessCache[url];
}
let status = 'unknown';
try {
const response = await fetch(url, { method: 'HEAD', mode: 'cors' });
const xfo = response.headers.get('X-Frame-Options');
const csp = response.headers.get('Content-Security-Policy');
// Assume accessible unless a blocking header is found
status = 'accessible';
if (xfo) {
const v = xfo.trim().toUpperCase();
if (v === 'DENY' || v === 'SAMEORIGIN') {
status = 'blocked';
}
}
if (status !== 'blocked' && csp) {
const faMatch = csp.match(/frame-ancestors\s+([^;]+)/i);
if (faMatch) {
const directive = faMatch[1].trim().toLowerCase();
// 'none' blocks entirely; bare 'self' blocks all external origins
if (directive === "'none'" || directive === "'self'") {
status = 'blocked';
}
}
}
} catch {
// CORS or network error – headers are unreadable but the iframe may still
// load successfully (many sites allow iframe embedding but not CORS fetch).
status = 'unknown';
}
authorityAccessCache[url] = status;
saveAuthorityAccessCache();
return status;
}
/**
* Returns the cached accessibility status for a URL, defaulting to 'unknown'.
*/
function getAuthorityStatus(url) {
return authorityAccessCache[url] || 'unknown';
}
/**
* CHECK AND REFRESH AUTHORITY ACCESS FOR A QID
* Runs accessibility checks for all authority URLs of the given item in the
* background and re-renders the dropdown only if at least one status changed,
* preventing redundant refreshes once all URLs have been checked.
*/
async function checkAndUpdateAuthorityAccess(qid) {
const authorities = itemAuthorityIds[qid] || [];
if (authorities.length === 0) return;
// Pre-compute embed URLs once to avoid repeated getEmbedUrl calls
const embedUrls = authorities.map(auth => getEmbedUrl(auth));
// Snapshot statuses before the checks so we can detect changes
const statusesBefore = embedUrls.map(url => getAuthorityStatus(url));
const checks = embedUrls.map(url => checkAuthorityUrl(url));
await Promise.allSettled(checks);
// Only refresh the dropdown if at least one status changed; this prevents
// an infinite update loop on subsequent calls when the cache is already warm.
const anyChanged = embedUrls.some((url, i) => getAuthorityStatus(url) !== statusesBefore[i]);
if (!anyChanged) return;
// Refresh the dropdown only if the authority view for this QID is still active
const viewTypeSelect = document.getElementById('viewTypeSelect');
const selectedQid = document.querySelector('.item.selected')?.getAttribute('data-qid');
if (viewTypeSelect?.value === 'viewWebData' && selectedQid === qid) {
updateAuthorityDropdown(qid);
}
}
document.addEventListener('DOMContentLoaded', () => {
// 1. Setup UI elements
const searchButton = document.getElementById('searchButton');
const searchInput = document.getElementById('searchInput');
const mainMapContainer = document.getElementById('map');
document.getElementById('settingsButton').onclick = () => {
alert("Settings:\nLanguage: English\nEngine: WDQS + mwapi\nResults per page: 20");
};
if (mainMapContainer) initializeMap(mainMapContainer);
if (!searchButton || !searchInput) {
console.error("CRITICAL: searchButton or searchInput not found in HTML!");
return; // Stop if UI is missing
}
// 2. Parse URL Parameters (Base64 version)
const urlParams = new URLSearchParams(window.location.search);
const ctxParam = urlParams.get('ctx');
const searchTerm = urlParams.get('query');
if (ctxParam) {
try {
// Correctly decode Base64 back to a JSON string, then to an object
const decoded = atob(ctxParam.replace(/-/g, '+').replace(/_/g, '/'));
originalContext = JSON.parse(decoded);
console.log("Context decoded successfully");
} catch (e) {
console.error("Context decoding failed:", e);
}
}
// 3. Define the search action
const executeSearch = () => {
const query = searchInput.value.trim();
if (query && !isSearching) {
populateItems(query, 0);
}
};
// 4. Attach listeners
searchButton.addEventListener('click', executeSearch);
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
executeSearch();
}
});
// 5. Safe Auto-Trigger
if (searchTerm) {
searchInput.value = decodeURIComponent(searchTerm);
// Delay helps ensure the Google Transport is stable
setTimeout(executeSearch, 1000);
}
initializeDynamicInputFields();
const viewTypeSelect = document.getElementById('viewTypeSelect');
if (viewTypeSelect) {
viewTypeSelect.addEventListener('change', () => {
const selectedQid = document.querySelector('.item.selected')?.getAttribute('data-qid');
handleViewTypeChange(viewTypeSelect.value, selectedQid);
});
}
});
/**
* RECONCILIATION BRIDGE
*/
function sendMatchToSheet(qid) {
// Look for the Google object
const isGoogle = (typeof google !== 'undefined' && google.script && google.script.run);
if (isGoogle) {
// Dynamically get config from your Speculo settings checkboxes
const config = {
includeLabel: document.getElementById('checkLabel')?.checked ?? true,
includeDesc: document.getElementById('checkDesc')?.checked ?? true,
langs: ['en'] // You can expand this based on your settings button logic
};
// UI feedback using the button that triggered the event
const btn = event.currentTarget;
const originalText = btn.textContent;
btn.textContent = "SAVING...";
btn.disabled = true;
google.script.run
.withSuccessHandler(() => {
// If Sidebar is open, trigger the "✓ Match Applied" toast
if (window.top && typeof window.top.remoteMatchNotification === 'function') {
window.top.remoteMatchNotification();
}
// Close the Speculo modal after successful save
google.script.host.close();
})
.withFailureHandler((err) => {
btn.textContent = originalText;
btn.disabled = false;
alert("Apps Script Error: " + err);
})
.applyEntity(qid, "SINGLE_CELL", config, originalContext);
} else {
console.error("Google API not found. Context:", originalContext);
alert("The connection to Google Sheets is not active yet. Please wait a few seconds and try again.");
}
}
function handleMatchButtonClick(qid) {
sendMatchToSheet(qid); // Calls the Google Sheets bridge we built
}
/**
* WIKIDATA SEARCH & UI GENERATION
*/
async function fetchWikidataItems(query, page, limit) {
const offset = page * limit;
console.log('Fetching with offset:', offset, 'limit:', limit, 'query:', query);
try {
// Use SPARQL with mwapi, but fetch ALL results and manually paginate in JavaScript
// This is because mwapi doesn't support offset properly
const sparqlQuery = `
SELECT DISTINCT ?item ?itemLabel ?itemDescription ?coord
(IF(BOUND(?img), URI(CONCAT("https://commons.wikimedia.org/wiki/Special:FilePath/",
REPLACE(STR(?img), "http://commons.wikimedia.org/wiki/Special:FilePath/", ""), "?width=300")), "") AS ?thumb)
WHERE {
SERVICE wikibase:mwapi {
bd:serviceParam wikibase:endpoint "www.wikidata.org";
wikibase:api "EntitySearch";
mwapi:search "${query}";
mwapi:language "${lang}";
mwapi:limit "500".
?item wikibase:apiOutputItem mwapi:item.
?item wikibase:apiOutputItemLabel mwapi:label.
}
OPTIONAL { ?item wdt:P18 ?img. }
OPTIONAL { ?item wdt:P625 ?coord. }
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],${lang},mul,en". }
} GROUP BY ?item ?itemLabel ?itemDescription ?coord ?img LIMIT 500`;
const url = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}&format=json`;
console.log('SPARQL query for search:', query);
const response = await fetch(url);
const data = await response.json();
console.log('Raw SPARQL results:', data.results.bindings.length);
// Deduplicate results by QID
const seen = new Set();
const allResults = data.results.bindings.filter(item => {
const qid = item.item.value.split('/').pop();
if (seen.has(qid)) return false;
seen.add(qid);
return true;
});
console.log('After deduplication:', allResults.length);
// Manual pagination in JavaScript
const start = offset;
const end = offset + limit;
const paginatedResults = allResults.slice(start, end);
console.log('Returning paginated results:', paginatedResults.length, '(from', start, 'to', end + ')');
return paginatedResults;
} catch (error) {
console.error("Error fetching items:", error);
return [];
}
}
/**
* SITELINKS BATCH QUERY
* Fetches all sitelinks for a batch of Wikidata items
*/
/**
* SITELINKS BATCH QUERY
* Fetches all sitelinks for a batch of Wikidata items
* Batches requests into groups of 10 to avoid Wikidata limits
*/
async function fetchSitelinksForItems(qids) {
if (!qids || qids.length === 0) return [];
const batchSize = 10;
const allResults = [];
console.log('Total QIDs to fetch:', qids.length);
// Process QIDs in batches of 10
for (let i = 0; i < qids.length; i += batchSize) {
const batch = qids.slice(i, i + batchSize);
console.log(`Batch ${Math.floor(i / batchSize) + 1} QIDs:`, batch);
const values = batch.map(qid => `wd:${qid}`).join(' ');
const sparqlQuery = `
SELECT ?item ?sitelink ?wiki ?title WHERE {
VALUES ?item { ${values} }
?sitelink schema:about ?item ;
schema:isPartOf ?wiki ;
schema:name ?title .
FILTER(STRSTARTS(STR(?wiki), "https://"))
}
ORDER BY ?item ?wiki`;
try {
const url = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}&format=json`;
const response = await fetch(url);
const data = await response.json();
const batchResults = data.results.bindings;
console.log(`Batch ${Math.floor(i / batchSize) + 1}: ${batchResults.length} results`);
console.log(`Batch ${Math.floor(i / batchSize) + 1} QIDs with results:`, [...new Set(batchResults.map(r => r.item.value.split('/').pop()))]);
allResults.push(...batchResults);
} catch (error) {
console.error("Error fetching sitelinks batch:", error);
}
}
console.log("Total sitelinks fetched:", allResults.length);
return allResults;
}
/**
* AUTHORITY IDS BATCH QUERY
* Fetches external identifier values, their formatter URLs (P1630), and — where
* available — their embed URL templates (P2720) for a batch of items.
* Only external ID properties that have a P1630 formatter URL are included — properties
* without one cannot produce a displayable URL and are excluded.
* P2720 is fetched as an OPTIONAL so properties that lack an embed template are
* still returned; the embed URL is simply omitted for those.
* Batches requests into groups of 10 to avoid Wikidata limits.
*/
async function fetchAuthorityIdsForItems(qids) {
if (!qids || qids.length === 0) return [];
const batchSize = 10;
const allResults = [];
for (let i = 0; i < qids.length; i += batchSize) {
const batch = qids.slice(i, i + batchSize);
const values = batch.map(qid => `wd:${qid}`).join(' ');
const sparqlQuery = `
SELECT ?item ?property ?propertyLabel ?value (SAMPLE(?fmtUrl) AS ?formatterUrl) (SAMPLE(?embedFmtUrl) AS ?embedUrl) WHERE {
VALUES ?item { ${values} }
?item ?p ?value .
?property wikibase:directClaim ?p ;
wikibase:propertyType wikibase:ExternalId ;
wdt:P1630 ?fmtUrl .
OPTIONAL { ?property wdt:P2720 ?embedFmtUrl . }
SERVICE wikibase:label { bd:serviceParam wikibase:language "${lang}". }
}
GROUP BY ?item ?property ?propertyLabel ?value
ORDER BY ?item ?property`;
try {
const url = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}&format=json`;
const response = await fetch(url);
const data = await response.json();
allResults.push(...data.results.bindings);
} catch (error) {
console.error("Error fetching authority IDs batch:", error);
}
}
return allResults;
}
/**
* PROCESS SITELINKS RESULTS
* Takes raw sitelinks results and caches them organized by item
*/
function processSitelinksResults(results) {
const cache = {};
results.forEach(result => {
const qid = result.item.value.split('/').pop(); // Extract QID from URL
if (!cache[qid]) {
cache[qid] = {};
}
// Parse this single sitelink
const wikiUrl = result.wiki.value;
const sitelink = result.sitelink.value;
const title = result.title.value;
const match = wikiUrl.match(/https:\/\/([a-z-]+)\.([a-z]+)\.org\//);
if (match) {
const lang = match[1];
const project = match[2];
const projectType = `${project}`;
if (!cache[qid][projectType]) {
cache[qid][projectType] = [];
}
cache[qid][projectType].push({
lang: lang,
title: title,
url: sitelink,
wikiUrl: wikiUrl
});
}
});
return cache;
}
/**
* UPDATE DROPDOWN DATA AFTER SEARCH
* Called after items are fetched to get their sitelinks
*/
async function updateSitelinksForCurrentResults(items) {
// Extract QIDs from items
const qids = items.map(item => {
const itemUrl = item.item.value;
return itemUrl.split('/').pop();
});
// Fetch sitelinks for all items
const sitelinksResults = await fetchSitelinksForItems(qids);
// Cache the results
const newCache = processSitelinksResults(sitelinksResults);
itemSitelinks = { ...itemSitelinks, ...newCache };
console.log("Sitelinks cached for QIDs:", qids);
console.log("Sitelinks cache:", itemSitelinks);
}
/**
* PROCESS AUTHORITY IDS RESULTS
* Takes raw SPARQL results and caches authority IDs per item, constructing:
* - `url` from the P1630 formatter URL (always present)
* - `embedUrl` from the P2720 embed URL template (present only when the
* property has one; undefined otherwise)
* Both URLs are produced by substituting the identifier value for `$1`.
*/
function processAuthorityIdsResults(results) {
const cache = {};
results.forEach(result => {
const qid = result.item.value.split('/').pop();
if (!cache[qid]) cache[qid] = [];
const propertyId = result.property.value.split('/').pop();
const propertyLabel = result.propertyLabel?.value || propertyId;
const value = result.value.value;
const formatterUrl = result.formatterUrl?.value;
if (formatterUrl) {
const url = formatterUrl.replace(/\$1/g, value);
const embedTemplate = result.embedUrl?.value;
const embedUrl = embedTemplate ? embedTemplate.replace(/\$1/g, value) : undefined;
cache[qid].push({ propertyId, propertyLabel, value, url, embedUrl });
}
});
return cache;
}
/**
* FETCH AND CACHE AUTHORITY IDS FOR A LIST OF QIDS
* Skips QIDs that have already been fetched (checked against fetchedAuthorityIdsForQids).
*/
async function updateAuthorityIdsForQids(qids) {
const unfetched = qids.filter(qid => !fetchedAuthorityIdsForQids.has(qid));
if (unfetched.length === 0) return;
const results = await fetchAuthorityIdsForItems(unfetched);
const newCache = processAuthorityIdsResults(results);
itemAuthorityIds = { ...itemAuthorityIds, ...newCache };
unfetched.forEach(qid => fetchedAuthorityIdsForQids.add(qid));
console.log("Authority IDs cached for QIDs:", unfetched);
}
/**
* WIKIDATA URLS BATCH QUERY
* Fetches direct URL property values for P856 (official website), P953 (work available at URL),
* P973 (described at URL), and P1065 (archive URL) for a batch of items.
* Batches requests into groups of 10 to avoid Wikidata limits.
*/
async function fetchWikidataUrlsForItems(qids) {
if (!qids || qids.length === 0) return [];
const batchSize = 10;
const allResults = [];
for (let i = 0; i < qids.length; i += batchSize) {
const batch = qids.slice(i, i + batchSize);
const values = batch.map(qid => `wd:${qid}`).join(' ');
const sparqlQuery = `
SELECT ?item ?property ?propertyLabel ?url WHERE {
VALUES ?item { ${values} }
VALUES ?property { wd:P856 wd:P953 wd:P973 wd:P1065 }
?item ?prop ?url .
?property wikibase:directClaim ?prop .
SERVICE wikibase:label { bd:serviceParam wikibase:language "${lang}". }
}
ORDER BY ?item ?property`;
try {
const url = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}&format=json`;
const response = await fetch(url);
const data = await response.json();
allResults.push(...data.results.bindings);
} catch (error) {
console.error("Error fetching Wikidata URLs batch:", error);
}
}
return allResults;
}
/**
* PROCESS WIKIDATA URLS RESULTS
* Takes raw SPARQL results and caches Wikidata URL properties per item.
*/
function processWikidataUrlsResults(results) {
const cache = {};
results.forEach(result => {
const qid = result.item.value.split('/').pop();
if (!cache[qid]) cache[qid] = [];
const propertyId = result.property.value.split('/').pop();
const propertyLabel = result.propertyLabel?.value || propertyId;
const url = result.url.value;
cache[qid].push({ propertyId, propertyLabel, url });
});
return cache;
}
/**
* FETCH AND CACHE WIKIDATA URLS FOR A LIST OF QIDS
* Skips QIDs that have already been fetched (checked against fetchedWikidataUrlsForQids).
*/
async function updateWikidataUrlsForQids(qids) {
const unfetched = qids.filter(qid => !fetchedWikidataUrlsForQids.has(qid));
if (unfetched.length === 0) return;
const results = await fetchWikidataUrlsForItems(unfetched);
const newCache = processWikidataUrlsResults(results);
itemWikidataUrls = { ...itemWikidataUrls, ...newCache };
unfetched.forEach(qid => fetchedWikidataUrlsForQids.add(qid));
console.log("Wikidata URLs cached for QIDs:", unfetched);
}
// ===== CONSTANTS FOR URL BUILDING =====
const PROJECT_MAP = {
'Wikipedia': 'wikipedia',
'Wikisource': 'wikisource',
'Wikivoyage': 'wikivoyage',
'Wikibooks': 'wikibooks',
'Wikinews': 'wikinews'
};
const MULTILINGUAL_PROJECTS = {
'Wikimedia Commons': 'commons',
'Metawiki': 'meta'
};
const PROJECT_DOMAINS = {
'wikipedia': 'wikipedia.org',
'wikisource': 'wikisource.org',
'wikivoyage': 'wikivoyage.org',
'wikibooks': 'wikibooks.org',
'wikinews': 'wikinews.org',
'commons': 'commons.wikimedia.org',
'meta': 'meta.wikimedia.org'
};
/**
* GET AVAILABLE PROJECTS FOR AN ITEM
* Only returns the 4 supported projects in the specified order.
*/
function getAvailableProjects(qid) {
if (!itemSitelinks[qid]) return [];
const sitelinks = itemSitelinks[qid];
const projects = [];
Object.entries(PROJECT_MAP).forEach(([projectName, projectKey]) => {
if (sitelinks[projectKey]) {
projects.push(projectName);
}
});
Object.entries(MULTILINGUAL_PROJECTS).forEach(([projectName, langKey]) => {
if (sitelinks['wikimedia']?.some(e => e.lang === langKey)) {
projects.push(projectName);
}
});
return projects;
}
/**
* GET AVAILABLE LANGUAGES FOR AN ITEM AND PROJECT
* Only applicable for localized projects (Wikipedia, Wikisource).
*/
function getAvailableLanguages(qid, projectType) {
const normalizedProject = PROJECT_MAP[projectType];
if (!normalizedProject || !itemSitelinks[qid]?.[normalizedProject]) return [];
return itemSitelinks[qid][normalizedProject].map(entry => ({
code: entry.lang,
title: entry.title
}));
}
/**
* BUILD WIKIMEDIA URL WITH PROPER STRUCTURE
* Constructs canonical URL in the format https://[lang].[domain]/wiki/[title]
*/
function buildWikimediaUrl(projectKey, langCode, title) {
const domain = PROJECT_DOMAINS[projectKey];
if (!domain) return null;
const baseUrl = (projectKey === 'commons' || projectKey === 'meta')
? `https://${domain}/wiki/${encodeURIComponent(title)}`
: `https://${langCode}.${domain}/wiki/${encodeURIComponent(title)}`;
return baseUrl;
}
/**
* BUILD WIKIDOCUMENTARIES URL
* Constructs URL in the format https://wikidocumentaries-demo.wmcloud.org/{qid}?language={langCode}
*/
function buildWikidocumentariesUrl(qid, langCode) {
return `https://wikidocumentaries-demo.wmcloud.org/${encodeURIComponent(qid)}?language=${encodeURIComponent(langCode)}`;
}
/**
* UPDATE WIKIDOCUMENTARIES DISPLAY
* Load the Wikidocumentaries page for a QID into the iframe
*/
function updateWikidocumentariesDisplay(qid, langCode) {
const iframe = document.getElementById('projectIframe');
const projectUrl = document.getElementById('projectUrl');
if (!iframe || !projectUrl) return;
const url = buildWikidocumentariesUrl(qid, langCode);
projectUrl.href = url;
projectUrl.textContent = url;
projectUrl.style.display = '';
iframe.src = url;
}
/**
* Returns an embed-friendly URL for the given authority entry.
* Uses the P2720 embed URL template value when one was returned by Wikidata;
* falls back to the standard P1630 formatter URL otherwise.
*/
function getEmbedUrl(auth) {
return auth.embedUrl || auth.url;
}
/**
* UPDATE AUTHORITY DROPDOWN
* Populate the authority source selector with available external IDs for the
* selected item.
*
* Sort order (ascending priority number = shown first):
* 0 – has P2720 embed URL (declared embeddable by Wikidata)
* 1 – accessible (no blocking headers detected by checkAuthorityUrl)
* 2 – unknown (CORS prevented header inspection; iframe may still work)
* 3 – blocked (X-Frame-Options or CSP frame-ancestors detected)
*
* Blocked entries are moved to the bottom and visually dimmed so users can
* still select them and open the link in a new tab if needed.
* Background URL checks are kicked off and will refresh the dropdown once
* results are available.
*/
function updateAuthorityDropdown(qid) {
const authoritySelect = document.getElementById('authoritySelect');
const projectUrl = document.getElementById('projectUrl');
const iframe = document.getElementById('projectIframe');
if (!authoritySelect || !projectUrl || !iframe) return;
const authorities = itemAuthorityIds[qid] || [];
if (authorities.length === 0) {
authoritySelect.style.display = 'none';
projectUrl.style.display = 'none';
iframe.src = 'no-content.html';
return;
}
authoritySelect.style.display = '';
projectUrl.style.display = '';
// Remember the currently selected index before rebuilding the list
const previousValue = authoritySelect.value;
authoritySelect.innerHTML = '';
// Numeric rank used for sorting (lower = shown higher in the list)
const statusRank = { accessible: 1, unknown: 2, blocked: 3 };
const sorted = authorities
.map((auth, index) => ({ auth, index }))
.sort((a, b) => {
// Primary: entries with a P2720 embed URL always come first
const aEmbed = a.auth.embedUrl ? 0 : 1;
const bEmbed = b.auth.embedUrl ? 0 : 1;
if (aEmbed !== bEmbed) return aEmbed - bEmbed;
// Secondary: sort by accessibility status
const aRank = statusRank[getAuthorityStatus(getEmbedUrl(a.auth))] ?? statusRank.unknown;
const bRank = statusRank[getAuthorityStatus(getEmbedUrl(b.auth))] ?? statusRank.unknown;
return aRank - bRank;
});
sorted.forEach(({ auth, index }) => {
const option = document.createElement('option');
option.value = index;
const status = getAuthorityStatus(getEmbedUrl(auth));
let label = `${auth.propertyLabel} (${auth.propertyId}): ${auth.value}`;
if (status === 'blocked') {
label += ' (blocked)';
option.className = 'authority-option-blocked';
option.style.color = '#999';
option.style.fontStyle = 'italic';
}
option.textContent = label;
authoritySelect.appendChild(option);
});
authoritySelect.onchange = () => {
updateAuthorityDisplay(qid, parseInt(authoritySelect.value, 10));
};
// Restore the previous selection when the dropdown is refreshed after a
// background check; otherwise pick the first non-blocked entry (or the
// first entry if everything is blocked).
const previousStillExists = Array.from(authoritySelect.options).some(o => o.value === previousValue);
if (previousStillExists) {
authoritySelect.value = previousValue;
} else {
const firstGood = sorted.find(({ auth }) => getAuthorityStatus(getEmbedUrl(auth)) !== 'blocked');
authoritySelect.value = firstGood ? firstGood.index : sorted[0].index;
}
// Load the currently selected authority into the iframe
updateAuthorityDisplay(qid, parseInt(authoritySelect.value, 10));
// Kick off background accessibility checks; the dropdown will be refreshed
// automatically when new status information becomes available.
checkAndUpdateAuthorityAccess(qid);
}
/**
* UPDATE AUTHORITY DISPLAY
* Load the selected authority into the iframe using an embed-friendly URL where
* one is available, and show the standard page URL as a link.
* Sites that block iframe embedding via X-Frame-Options will not display in the
* frame; use the link above to open them in a new tab.
*/
function updateAuthorityDisplay(qid, index) {
const authorities = itemAuthorityIds[qid] || [];
const auth = authorities[index];
if (!auth) return;
const iframe = document.getElementById('projectIframe');
const projectUrl = document.getElementById('projectUrl');
if (!iframe || !projectUrl) return;
projectUrl.href = auth.url;
projectUrl.textContent = auth.url;
iframe.src = getEmbedUrl(auth);
}
/**
* CHECK AND REFRESH WIKIDATA URL ACCESS FOR A QID
* Runs accessibility checks for all Wikidata URLs of the given item in the
* background and re-renders the dropdown only if at least one status changed.
*/
async function checkAndUpdateWikidataUrlAccess(qid) {
const urls = (itemWikidataUrls[qid] || []).map(entry => entry.url);
if (urls.length === 0) return;
const statusesBefore = urls.map(url => getAuthorityStatus(url));
await Promise.allSettled(urls.map(url => checkAuthorityUrl(url)));
const anyChanged = urls.some((url, i) => getAuthorityStatus(url) !== statusesBefore[i]);
if (!anyChanged) return;
const viewTypeSelect = document.getElementById('viewTypeSelect');
const selectedQid = document.querySelector('.item.selected')?.getAttribute('data-qid');
if (viewTypeSelect?.value === 'viewWikidataUrls' && selectedQid === qid) {
updateWikidataUrlDropdown(qid);
}
}
/**
* UPDATE WIKIDATA URL DROPDOWN
* Populate the authority selector with available Wikidata URL properties for the
* selected item (P856, P953, P973, P1065).
*
* Sort order (ascending priority = shown first):
* 1 – accessible (no blocking headers detected)
* 2 – unknown (CORS prevented header inspection; iframe may still work)
* 3 – blocked (X-Frame-Options or CSP frame-ancestors detected)
*
* Blocked entries are dimmed so users can still open them in a new tab.
*/
function updateWikidataUrlDropdown(qid) {
const authoritySelect = document.getElementById('authoritySelect');
const projectUrl = document.getElementById('projectUrl');
const iframe = document.getElementById('projectIframe');
if (!authoritySelect || !projectUrl || !iframe) return;
const entries = itemWikidataUrls[qid] || [];
if (entries.length === 0) {
authoritySelect.style.display = 'none';
projectUrl.style.display = 'none';
iframe.src = 'no-content.html';
return;
}
authoritySelect.style.display = '';
projectUrl.style.display = '';
const previousValue = authoritySelect.value;
authoritySelect.innerHTML = '';
const statusRank = { accessible: 1, unknown: 2, blocked: 3 };
const sorted = entries
.map((entry, index) => ({ entry, index }))
.sort((a, b) => {
const aRank = statusRank[getAuthorityStatus(a.entry.url)] ?? statusRank.unknown;
const bRank = statusRank[getAuthorityStatus(b.entry.url)] ?? statusRank.unknown;
return aRank - bRank;
});
sorted.forEach(({ entry, index }) => {
const option = document.createElement('option');
option.value = index;
const status = getAuthorityStatus(entry.url);
let label = `${entry.propertyLabel} (${entry.propertyId}): ${entry.url}`;
if (status === 'blocked') {
label += ' (blocked)';
option.className = 'authority-option-blocked';
option.style.color = '#999';
option.style.fontStyle = 'italic';
}
option.textContent = label;
authoritySelect.appendChild(option);
});
authoritySelect.onchange = () => {
updateWikidataUrlDisplay(qid, parseInt(authoritySelect.value, 10));
};
const previousStillExists = Array.from(authoritySelect.options).some(o => o.value === previousValue);
if (previousStillExists) {
authoritySelect.value = previousValue;
} else {
const firstGood = sorted.find(({ entry }) => getAuthorityStatus(entry.url) !== 'blocked');
authoritySelect.value = firstGood ? firstGood.index : sorted[0].index;
}
updateWikidataUrlDisplay(qid, parseInt(authoritySelect.value, 10));
checkAndUpdateWikidataUrlAccess(qid);
}
/**
* UPDATE WIKIDATA URL DISPLAY
* Load the selected Wikidata URL into the iframe and show it as a clickable link.
*/
function updateWikidataUrlDisplay(qid, index) {
const entries = itemWikidataUrls[qid] || [];
const entry = entries[index];
if (!entry) return;
const iframe = document.getElementById('projectIframe');
const projectUrl = document.getElementById('projectUrl');
if (!iframe || !projectUrl) return;
projectUrl.href = entry.url;
projectUrl.textContent = entry.url;
iframe.src = entry.url;
}
/**
* UPDATE VIEW TYPE AVAILABILITY
* Enable or disable view type options based on available data for the selected item.
* Options are disabled when data is known to be absent; options are left enabled when
* data has not been fetched yet (unknown state).
* If the currently selected view is disabled, automatically switches to the first
* available view.
*/
let _updatingViewTypeAvailability = false;
function updateViewTypeAvailability(qid) {
if (_updatingViewTypeAvailability) return;
const viewTypeSelect = document.getElementById('viewTypeSelect');
if (!viewTypeSelect || !qid) return;
// viewWikimedia: sitelinks are always pre-fetched, so we can determine availability
const hasWikimedia = getAvailableProjects(qid).length > 0;
// viewWebData: only disable if we've already fetched and found nothing
const webDataFetched = fetchedAuthorityIdsForQids.has(qid);
const hasWebData = !webDataFetched || (itemAuthorityIds[qid] || []).length > 0;
// viewWikidataUrls: only disable if we've already fetched and found nothing
const wikidataUrlsFetched = fetchedWikidataUrlsForQids.has(qid);
const hasWikidataUrls = !wikidataUrlsFetched || (itemWikidataUrls[qid] || []).length > 0;
const wikimediaOption = viewTypeSelect.querySelector('option[value="viewWikimedia"]');
const webDataOption = viewTypeSelect.querySelector('option[value="viewWebData"]');
const wikidataUrlsOption = viewTypeSelect.querySelector('option[value="viewWikidataUrls"]');
if (wikimediaOption) wikimediaOption.disabled = !hasWikimedia;
if (webDataOption) webDataOption.disabled = !hasWebData;
if (wikidataUrlsOption) wikidataUrlsOption.disabled = !hasWikidataUrls;
// If the currently selected view has been disabled, switch to the first available view.
// Prefer data-rich views (viewWikimedia, viewWikidocumentaries) before falling back to others.
const currentOption = viewTypeSelect.options[viewTypeSelect.selectedIndex];
if (currentOption && currentOption.disabled) {
const preferredOrder = ['viewWikimedia', 'viewWikidocumentaries', 'viewWebPage'];
const autoSwitchTarget = preferredOrder
.map(v => viewTypeSelect.querySelector(`option[value="${v}"]`))
.find(o => o && !o.disabled)
|| Array.from(viewTypeSelect.options).find(o => !o.disabled);
if (autoSwitchTarget) {
viewTypeSelect.value = autoSwitchTarget.value;
_updatingViewTypeAvailability = true;
try {