-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
2157 lines (1872 loc) · 85.7 KB
/
Copy pathmain.js
File metadata and controls
2157 lines (1872 loc) · 85.7 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
import './style.css'
import './bulma.min.css'
import MD5 from 'crypto-js/md5'
// Debounce function
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Convert Wikimedia image URL to thumbnail
function convertToThumbnail(imageUrl, width = 120) {
// Convert full Wikimedia Commons URLs to thumbnail URLs using MD5 hashing
if (!imageUrl || !imageUrl.includes('commons.wikimedia.org')) {
return imageUrl;
}
try {
// Extract filename from the URL
let filename;
if (imageUrl.includes('/wiki/File:')) {
filename = imageUrl.split('/wiki/File:')[1];
} else if (imageUrl.includes('/wikipedia/commons/')) {
filename = imageUrl.split('/').pop();
} else {
filename = imageUrl.split('/').pop();
}
// Decode URL encoding if present
filename = decodeURIComponent(filename);
filename = filename.replace(/ /g, '_'); // Replace spaces with underscores for MD5
// Generate MD5 hash of filename using proper MD5 implementation
const md5Hash = MD5(filename).toString();
// Build thumbnail URL according to Wikimedia rules
const firstChar = md5Hash.charAt(0);
const firstTwoChars = md5Hash.substring(0, 2);
let thumbnailUrl = `https://upload.wikimedia.org/wikipedia/commons/thumb/${firstChar}/${firstTwoChars}/${encodeURIComponent(filename)}/${width}px-${encodeURIComponent(filename)}`;
if (thumbnailUrl.endsWith(".tif")){
thumbnailUrl = thumbnailUrl + ".jpg"
}
if (thumbnailUrl.endsWith(".svg")){
thumbnailUrl = thumbnailUrl + ".png"
}
return thumbnailUrl;
} catch (error) {
console.error('Error converting to thumbnail:', error);
return imageUrl;
}
}
// Get initials from name
function getInitials(name) {
if (!name) return '';
const parts = name.split(/[,\s]+/).filter(part => part.length > 0);
if (parts.length >= 2) {
return (parts[1][0] + parts[0][0]).toUpperCase(); // First name, Last name
}
return parts[0][0].toUpperCase();
}
// Levenshtein distance calculation
function levenshteinDistance(str1, str2) {
const track = Array(str2.length + 1).fill(null).map(() =>
Array(str1.length + 1).fill(null));
for (let i = 0; i <= str1.length; i += 1) {
track[0][i] = i;
}
for (let j = 0; j <= str2.length; j += 1) {
track[j][0] = j;
}
for (let j = 1; j <= str2.length; j += 1) {
for (let i = 1; i <= str1.length; i += 1) {
const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
track[j][i] = Math.min(
track[j][i - 1] + 1, // deletion
track[j - 1][i] + 1, // insertion
track[j - 1][i - 1] + indicator, // substitution
);
}
}
return track[str2.length][str1.length];
}
// Create results container
function createResultsContainer() {
const existingResults = document.getElementById('search-results');
if (existingResults) {
return existingResults;
}
const searchInput = document.getElementById('search');
if (!searchInput) {
console.error('Search input not found');
return null;
}
const searchContainer = searchInput.closest('.field');
if (!searchContainer) {
console.error('Search container not found');
return null;
}
const resultsDiv = document.createElement('div');
resultsDiv.id = 'search-results';
resultsDiv.className = 'columns mt-4';
searchContainer.parentNode.insertBefore(resultsDiv, searchContainer.nextSibling);
return resultsDiv;
}
// Format contributor results
async function formatContributors(data) {
if (!data.hits || data.hits.length === 0) {
return '<p class="has-text-grey">No contributors found</p>';
}
// Sort by contributions count (higher first)
const sortedHits = [...data.hits].sort((a, b) => {
const aContributions = a.contributions || 0;
const bContributions = b.contributions || 0;
return bContributions - aContributions;
});
// Fetch proper names for each contributor
const enrichedHits = await Promise.all(sortedHits.map(async (hit) => {
let properName = hit.suggestLabel; // Default fallback
// Check if token looks like LCCN (e.g., "n89601384")
if (hit.token && hit.token.match(/^n\d+$/)) {
try {
const response = await fetch(`https://id.loc.gov/authorities/names/${hit.token}.json`);
if (response.ok) {
const data = await response.json();
// The response is an array - find the main authority object
const agent = data.find(item =>
item['@id'] === `http://id.loc.gov/authorities/names/${hit.token}` &&
item['@type'] &&
(Array.isArray(item['@type']) ? item['@type'].includes('http://www.loc.gov/mads/rdf/v1#Authority') : item['@type'] === 'http://www.loc.gov/mads/rdf/v1#Authority')
);
if (agent && agent['http://www.loc.gov/mads/rdf/v1#authoritativeLabel']) {
const authLabels = agent['http://www.loc.gov/mads/rdf/v1#authoritativeLabel'];
if (authLabels && authLabels.length > 0 && authLabels[0]['@value']) {
properName = authLabels[0]['@value'];
console.log(`Found name for ${hit.token}: ${properName}`);
}
} else {
console.log(`No authoritativeLabel found for ${hit.token}`);
}
}
} catch (error) {
console.error(`Error fetching name for ${hit.token}:`, error);
}
}
return {
...hit,
displayName: properName
};
}));
// Start Wikidata enrichment after display
setTimeout(() => enrichContributorsWithWikidata(enrichedHits), 100);
return enrichedHits.map(hit => {
const initials = getInitials(hit.displayName);
return `
<div class="box p-2 mb-2 contributor-box" data-token="${hit.token}" data-label="${hit.displayName}" style="display: flex; align-items: stretch; min-height: 100px;">
<div class="contributor-image mr-3" data-lccn="${hit.token}">
<div class="initials-circle" style="width: 80px; height: 100%; min-height: 96px; border-radius: 12px; background: linear-gradient(135deg, #85c1f5 0%, #276dcc 100%); display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 1.5rem;">
${initials}
</div>
</div>
<div style="flex: 1; padding: 0.5rem 0;">
<p class="has-text-weight-semibold">${hit.displayName}</p>
${hit.contributions ? `<p class="is-size-7 has-text-primary has-text-weight-semibold">${hit.contributions} contributions</p>` : ''}
${hit.more?.birthdates && hit.more.birthdates[0] && hit.more.birthdates[0] !== 'undefined' ? `<p class="is-size-7 has-text-grey">Born: ${hit.more.birthdates[0]}</p>` : ''}
${hit.more?.occupations && hit.more.occupations.length > 0 && hit.more.occupations[0] !== 'undefined' ? `<p class="is-size-7 has-text-grey">${hit.more.occupations.filter(o => o && o !== 'undefined').join(', ')}</p>` : ''}
<div class="wikidata-info" data-lccn="${hit.token}"></div>
</div>
</div>
`;
}).join('');
}
// Enrich contributors with Wikidata information
async function enrichContributorsWithWikidata(hits) {
// Extract LCCN tokens
const lccnTokens = hits
.map(hit => hit.token)
.filter(token => token && token.startsWith('n'));
if (lccnTokens.length === 0) return;
// Build SPARQL query
const sparqlQuery = `
SELECT ?item ?itemLabel ?lccn ?image ?birthDate ?deathDate ?description WHERE {
VALUES ?lccn { ${lccnTokens.map(token => `"${token}"`).join(' ')} }
?item wdt:P244 ?lccn .
OPTIONAL { ?item wdt:P18 ?image }
OPTIONAL { ?item wdt:P569 ?birthDate }
OPTIONAL { ?item wdt:P570 ?deathDate }
SERVICE wikibase:label {
bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" .
?item schema:description ?description .
?item rdfs:label ?itemLabel .
}
}
`;
const wikidataUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}&format=json`;
try {
const response = await fetch(wikidataUrl, {
headers: {
'Accept': 'application/sparql-results+json'
}
});
if (!response.ok) {
console.error('Wikidata query failed:', response.status);
return;
}
const data = await response.json();
console.log('Wikidata results:', data);
// Process results and update UI
if (data.results && data.results.bindings) {
data.results.bindings.forEach(binding => {
const lccn = binding.lccn?.value;
const description = binding.description?.value;
const wikidataUri = binding.item?.value;
const image = binding.image?.value;
// Update image if available
if (image && lccn) {
const imageContainer = document.querySelector(`.contributor-box[data-token="${lccn}"] .contributor-image`);
if (imageContainer) {
const thumbnailUrl = convertToThumbnail(image, 120);
const contributorBox = document.querySelector(`.contributor-box[data-token="${lccn}"]`);
const displayName = contributorBox ? contributorBox.dataset.label : '';
imageContainer.innerHTML = `
<img src="${thumbnailUrl}" alt="Author photo" style="width: 80px; height: 100%; min-height: 96px; border-radius: 12px; object-fit: cover; opacity: 0;" onload="this.classList.add('loaded');" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';" />
<div class="initials-circle" style="width: 80px; height: 100%; min-height: 96px; border-radius: 12px; background: linear-gradient(135deg, #85c1f5 0%, #276dcc 100%); display: none; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 1.5rem;">
${getInitials(displayName)}
</div>
`;
}
}
// Find the corresponding contributor box for description
const contributorBox = document.querySelector(`.contributor-box[data-token="${lccn}"] .wikidata-info`);
if (contributorBox && description && description !== 'undefined') {
contributorBox.innerHTML = `
<p class="is-size-7 has-text-dark mt-2">
<strong>Wikidata:</strong> ${description}
</p>
`;
}
console.log(`LCCN: ${lccn}, Description: ${description}, Image: ${image}, Wikidata: ${wikidataUri}`);
});
}
} catch (error) {
console.error('Error fetching Wikidata:', error);
}
}
// Format instances results for numeric searches
function formatInstances(data) {
if (!data.hits || data.hits.length === 0) {
return '<p class="has-text-grey">No instances found</p>';
}
return data.hits.map(hit => {
const uri = hit.uri;
const label = hit.aLabel || 'Unknown Instance';
return `
<div class="box p-3 mb-2 title-result" data-uri="${uri}" style="cursor: pointer;" onclick="handleInstanceClick('${uri}')">
<p class="has-text-weight-semibold">${label}</p>
${hit.suggestLabel ? `<p class="is-size-7 has-text-grey">${hit.suggestLabel}</p>` : ''}
</div>
`;
}).join('');
}
// Format title results
function formatTitles(data, searchQuery) {
if (!data.hits || data.hits.length === 0) {
return '<p class="has-text-grey">No titles found</p>';
}
// Filter out excluded URIs
let filteredHits = data.hits.filter(hit =>
!window.excludedUris || !window.excludedUris.has(hit.uri)
);
if (filteredHits.length === 0) {
return '<p class="has-text-grey">No titles found</p>';
}
// Add distance scores and sort
const scoredHits = filteredHits.map(hit => {
// Check if first contributor appears in aLabel
const firstContributor = hit.more?.contributors && hit.more.contributors[0];
const hasContributorInLabel = firstContributor && hit.aLabel &&
hit.aLabel.includes(firstContributor);
// Remove contributors from aLabel before calculating distance
let labelForDistance = hit.aLabel || hit.suggestLabel || '';
if (hit.more?.contributors) {
// Remove all contributors from the label for distance calculation
hit.more.contributors.forEach(contributor => {
labelForDistance = labelForDistance.replace(contributor, '').replace(/^\.\s*/, '').trim();
});
}
// Calculate Levenshtein distance from search query (using label without contributors)
let distance = searchQuery ?
levenshteinDistance(searchQuery.toLowerCase(), labelForDistance.toLowerCase()) :
999999;
// Apply bonus (reduce distance) if contributor appears in label
// Bigger bonus if the search query appears in the contributor name
if (hasContributorInLabel && firstContributor && searchQuery) {
const contributorMatchesSearch = firstContributor.toLowerCase().includes(searchQuery.toLowerCase());
if (contributorMatchesSearch) {
distance = Math.max(0, distance - 25); // Very big bonus when searching for an author and their name appears properly
} else {
distance = Math.max(0, distance - 8); // Moderate bonus for other contributors in label
}
}
// Check if English language
const isEnglish = hit.more?.languages &&
hit.more.languages.some(lang =>
lang === 'English' || lang === 'mlang:eng' || lang.toLowerCase().includes('eng')
);
// Get token as number (default to very large number if not present)
const tokenNum = hit.token ? parseInt(hit.token) : 999999999;
return {
...hit,
distance: distance,
originalDistance: searchQuery ?
levenshteinDistance(searchQuery.toLowerCase(), labelForDistance.toLowerCase()) :
999999,
labelWithoutContributors: labelForDistance,
hasContributorInLabel: hasContributorInLabel,
isEnglish: isEnglish,
tokenNum: tokenNum
};
});
// Sort by: 1) distance (ascending), 2) contributor in label, 3) English preference, 4) token (ascending)
scoredHits.sort((a, b) => {
// First sort by distance
if (a.distance !== b.distance) {
return a.distance - b.distance;
}
// Then by contributor appearing in label (those with contributor first)
if (a.hasContributorInLabel !== b.hasContributorInLabel) {
return a.hasContributorInLabel ? -1 : 1; // Fixed: reversed the comparison
}
// Then by English preference (English first)
if (a.isEnglish !== b.isEnglish) {
return b.isEnglish ? 1 : -1;
}
// Finally by token number
return a.tokenNum - b.tokenNum;
});
return scoredHits.map(hit => `
<div class="box p-3 mb-2 title-result" data-uri="${hit.uri}" style="cursor: pointer;">
<p class="has-text-weight-semibold">${hit.suggestLabel}</p>
${hit.vLabel && hit.vLabel !== hit.aLabel ?
`<p class="is-size-6 has-text-dark">${hit.vLabel}</p>` : ''}
${hit.more?.contributors && hit.more.contributors.length > 1 ?
`<p class="is-size-7 has-text-grey">Contributors: ${hit.more.contributors.slice(1).join(', ')}</p>` : ''}
${hit.more?.languages ? `<p class="is-size-7 has-text-grey">Language: ${hit.more.languages.join(', ')}</p>` : ''}
</div>
`).join('');
}
// Store the current abort controller globally
let currentSearchController = null;
// Store navigation context for back button
let navigationContext = {
type: null, // 'search', 'all-instances', 'contributor-works'
data: null // Store relevant data for reconstruction
};
// Perform searches - make it globally available for back button
window.performSearches = async function performSearches(query) {
// Set navigation context
navigationContext = {
type: 'search',
data: { query }
};
// Cancel any pending search
if (currentSearchController) {
currentSearchController.abort();
currentSearchController = null;
}
if (!query || query.length < 2) {
const resultsDiv = document.getElementById('search-results');
if (resultsDiv) {
resultsDiv.innerHTML = '';
}
return;
}
// Create a new AbortController for this search
currentSearchController = new AbortController();
const signal = currentSearchController.signal;
const resultsDiv = createResultsContainer();
if (!resultsDiv) {
console.error('Could not create results container');
return;
}
resultsDiv.innerHTML = '<div class="column"><p>Searching...</p></div>';
try {
// Check if the search query is numeric only
const isNumericOnly = /^\d+$/.test(query.trim());
if (isNumericOnly) {
// For numeric-only searches, use the instances endpoint
const instancesUrl = `https://id.loc.gov/resources/instances/suggest2/?q=${encodeURIComponent(query)}&searchtype=keyword`;
const response = await fetch(instancesUrl, { signal });
const instancesData = await response.json();
// Format the instances results
resultsDiv.innerHTML = `
<div class="column">
<h4 class="title is-5 mb-3">Instance Search Results for "${query}"</h4>
<div class="instance-results">
${formatInstances(instancesData)}
</div>
</div>
`;
} else {
// Regular search for non-numeric queries
const namesUrl = `https://id.loc.gov/authorities/names/suggest2/?q=${encodeURIComponent(query)}*&searchtype=keyword&rdftype=PersonalName&usage=true&count=20`;
const worksUrl = `https://id.loc.gov/resources/works/suggest2/?q=${encodeURIComponent(query)}&searchtype=keyword&rdftype=Monograph&rdftype=Text&count=100`;
const [namesResponse, worksResponse] = await Promise.all([
fetch(namesUrl, { signal }),
fetch(worksUrl, { signal })
]);
const [namesData, worksData] = await Promise.all([
namesResponse.json(),
worksResponse.json()
]);
// Format contributors (now async)
const contributorHTML = await formatContributors(namesData);
resultsDiv.innerHTML = `
<div class="column is-4">
<h4 class="title is-5 mb-3">Contributors - Click to Load</h4>
<div class="contributor-results">
${contributorHTML}
</div>
</div>
<div class="column is-8">
<h4 class="title is-5 mb-3">Titles - results for "<i>${query}</i>"</h4>
<div class="title-results">
${formatTitles(worksData, query)}
</div>
</div>
`;
}
} catch (error) {
if (error.name === 'AbortError') {
console.log('Search cancelled due to new input');
return;
}
resultsDiv.innerHTML = `
<div class="column">
<div class="notification is-danger">
Error performing search: ${error.message}
</div>
</div>
`;
} finally {
// Clear the controller reference if this was the current search
if (currentSearchController?.signal === signal) {
currentSearchController = null;
}
}
}
// Fetch instance details for works
async function fetchInstanceDetails(works, showPublication = true) {
// Process each work independently
works.forEach(async (work) => {
const workId = work.uri.split('/').pop();
const instanceUrl = `https://id.loc.gov/resources/instances/${workId}.bibframe_raw.json`;
try {
const response = await fetch(instanceUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
// Find the main instance object
const mainInstance = data.find(item =>
item['@id'] === `http://id.loc.gov/resources/instances/${workId}`
);
let publicationStatement = '';
let responsibilityStatement = '';
if (mainInstance) {
// Extract publication statement
if (mainInstance['http://id.loc.gov/ontologies/bibframe/publicationStatement']) {
publicationStatement = mainInstance['http://id.loc.gov/ontologies/bibframe/publicationStatement'][0]?.['@value'] || '';
// Find all years in the publication statement (including those with 'c' prefix)
const yearMatches = publicationStatement.match(/\b(c?)(1[5-9]\d{2}|20[0-2]\d)\b/g);
if (yearMatches && yearMatches.length > 0) {
// Extract numeric values for comparison
const yearsWithInfo = yearMatches.map(y => {
const hasC = y.startsWith('c');
const numericYear = parseInt(y.replace('c', ''));
return { original: y, numeric: numericYear, hasC };
});
// Find the newest year
const newestYearInfo = yearsWithInfo.reduce((max, current) =>
current.numeric > max.numeric ? current : max
);
// Bold only the newest year (including its 'c' if present)
publicationStatement = publicationStatement.replace(
new RegExp(`\\b${newestYearInfo.original}\\b`, 'g'),
`<strong>${newestYearInfo.original}</strong>`
);
}
}
// Extract responsibility statement
if (mainInstance['http://id.loc.gov/ontologies/bibframe/responsibilityStatement']) {
responsibilityStatement = mainInstance['http://id.loc.gov/ontologies/bibframe/responsibilityStatement'][0]?.['@value'] || '';
}
}
// Update the UI for this specific work
const detailsDiv = document.querySelector(`.instance-details[data-work-id="${workId}"]`);
if (detailsDiv) {
if (publicationStatement || responsibilityStatement) {
detailsDiv.innerHTML = `
${responsibilityStatement ? `<p class="is-size-7 has-text-grey">By: ${responsibilityStatement}</p>` : ''}
${(publicationStatement && showPublication) ? `<p class="is-size-7 has-text-grey"><strong>Published:</strong> ${publicationStatement}</p>` : ''}
`;
} else {
detailsDiv.innerHTML = '<p class="is-size-7 has-text-grey-light">No instance details available</p>';
}
}
} catch (error) {
console.error(`Error fetching instance for work ${workId}:`, error);
// Update UI to show error
const detailsDiv = document.querySelector(`.instance-details[data-work-id="${workId}"]`);
if (detailsDiv) {
detailsDiv.innerHTML = '<p class="is-size-7 has-text-grey-light">Details not available</p>';
}
}
});
}
// Handle contributor click
async function handleContributorClick(lccn, contributorName) {
// Smooth scroll to top
const resultsContainer = document.getElementById('search-results');
if (resultsContainer) {
resultsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
console.log(`[CONTRIBUTOR] Processing works for: ${contributorName} (${lccn})`);
// Show loading state in titles column
const titleColumn = document.querySelector('#search-results .column:last-child .title-results');
const titleHeader = document.querySelector('#search-results .column:last-child h4');
const titleColumnContainer = document.querySelector('#search-results .column:last-child');
// Store the current search value for the back button
const searchInput = document.getElementById('search');
const currentSearch = searchInput ? searchInput.value : '';
if (titleColumn) {
titleColumn.innerHTML = `
<div class="progress-container">
<div class="progress">
<div class="progress-bar" style="width: 0%"></div>
</div>
<div class="progress-text">Loading contributor works...</div>
</div>
`;
}
// Helper function to update progress
const updateProgress = (percentage, text) => {
const progressBar = titleColumn?.querySelector('.progress-bar');
const progressText = titleColumn?.querySelector('.progress-text');
if (progressBar) progressBar.style.width = `${percentage}%`;
if (progressText) progressText.textContent = text;
};
if (titleHeader) {
titleHeader.innerHTML = `
<span style="display: flex; align-items: center; justify-content: space-between;">
<span>Titles - Please Select Work</span>
<button class="button is-small is-light" onclick="(() => { const input = document.getElementById('search'); if (input && input.value) { performSearches(input.value); } })()">
<span>← Back</span>
</button>
</span>
`;
}
try {
// Fetch first page to get total pages
updateProgress(5, 'Fetching contributor information...');
const firstPageUrl = `https://id.loc.gov/resources/works/relationships/contributorto/?label=http://id.loc.gov/authorities/names/${lccn}&page=0`;
const firstPageResponse = await fetch(firstPageUrl);
const firstPageData = await firstPageResponse.json();
// Determine how many pages to fetch
const maxPage = Math.min(firstPageData.summary.totalPages, 49); // Cap at 50 pages total
updateProgress(10, `Found ${firstPageData.summary.totalPages + 1} pages of works...`);
// Create array of promises for all pages
const pagePromises = [];
for (let page = 0; page <= maxPage; page++) {
const pageUrl = `https://id.loc.gov/resources/works/relationships/contributorto/?label=http://id.loc.gov/authorities/names/${lccn}&page=${page}`;
pagePromises.push(fetch(pageUrl).then(res => res.json()));
}
// Fetch all pages simultaneously
updateProgress(15, `Loading ${maxPage + 1} pages of works...`);
const allPagesData = await Promise.all(pagePromises);
updateProgress(30, 'Processing work records...');
// Collapse all results into one array and deduplicate by URI
const allResultsRaw = allPagesData.flatMap(pageData => pageData.results || []);
const uriMap = new Map();
allResultsRaw.forEach(result => {
if (!uriMap.has(result.uri)) {
uriMap.set(result.uri, result);
}
});
const allResults = Array.from(uriMap.values());
console.log(`Total results before dedup: ${allResultsRaw.length}, after dedup: ${allResults.length}`);
// Fetch bibframe data for each work to check if it has Text type
console.log(`Checking types for ${allResults.length} works...`);
updateProgress(35, `Fetching details for ${allResults.length} works...`);
let completedCount = 0;
const workPromises = allResults.map(async work => {
const workId = work.uri.split('/').pop();
try {
const response = await fetch(`https://id.loc.gov/resources/works/${workId}.bibframe_raw.json`);
const data = await response.json();
// Update progress as each work completes
completedCount++;
const progressPercent = 35 + Math.round((completedCount / allResults.length) * 55); // 35% to 90%
updateProgress(progressPercent, `Loading work details... (${completedCount}/${allResults.length})`);
const mainWork = data.find(item => item['@id'] === work.uri);
let isText = false;
let isNonText = false;
let workType = null;
if (mainWork) {
console.log(`Work ${workId}:`, mainWork['@type']);
if (mainWork['@type'] && Array.isArray(mainWork['@type'])) {
isText = mainWork['@type'].includes('http://id.loc.gov/ontologies/bibframe/Text');
// If it has a type but not Text, it's non-text (like MusicAudio, MovingImage, etc.)
isNonText = !isText && mainWork['@type'].length > 1; // Has types beyond just "Work"
// Extract the specific work type (not Work, Monograph, or Text)
if (isNonText) {
const specificType = mainWork['@type'].find(type => {
const typeName = type.split('/').pop();
return typeName !== 'Work' && typeName !== 'Monograph' && typeName !== 'Text';
});
if (specificType) {
workType = specificType.split('/').pop(); // Extract just the type name
}
}
console.log(` Has Text type: ${isText}, Is Non-Text: ${isNonText}, Work Type: ${workType}`);
} else {
console.log(` No @type field found`);
}
} else {
console.log(` Main work not found for ${work.uri}`);
}
return { ...work, isText, isNonText, workType, bibframeData: data };
} catch (error) {
console.error(` Error fetching ${workId}:`, error);
return { ...work, isText: true, isNonText: false, workType: null, bibframeData: null }; // Default to text if error
}
});
const enrichedResults = await Promise.all(workPromises);
updateProgress(95, 'Organizing results...');
// Store enriched results globally for later use when displaying instances
window.contributorWorksBibframeData = {};
enrichedResults.forEach(work => {
window.contributorWorksBibframeData[work.uri] = work.bibframeData;
});
// Helper function to normalize title for comparison
function normalizeTitle(title) {
return title
.toLowerCase()
.replace(/[.,;:!?\-–—'"'""\[\](){}]/g, '') // Remove punctuation
.replace(/\s+/g, ' ') // Normalize whitespace
.trim();
}
// Group results by title and type
const textWorks = {};
const nonTextWorks = {};
const titleCounts = {}; // Track frequency of each title form
let nonTextCount = 0;
enrichedResults.forEach(work => {
// Extract just the title part after the contributor name
let title = work.label;
const workId = work.uri.split('/').pop();
console.log(`[TITLE DEBUG ${workId}] Starting title extraction`);
console.log(`[TITLE DEBUG ${workId}] Initial label from API:`, work.label);
console.log(`[TITLE DEBUG ${workId}] Known contributor:`, contributorName);
// If no label, try to get title from bibframe data
if (!title) {
console.log(`[TITLE DEBUG ${workId}] No label from API, checking bibframe data`);
if (work.bibframeData) {
console.log(`[TITLE DEBUG ${workId}] Bibframe data exists, searching for work object`);
const mainWork = work.bibframeData.find(item => item['@id'] === work.uri);
if (mainWork) {
console.log(`[TITLE DEBUG ${workId}] Found main work object`);
// Try to get aap (authorized access point) or title
const aap = mainWork['http://id.loc.gov/ontologies/bflc/aap'];
if (aap && aap[0]) {
title = aap[0]['@value'];
console.log(`[TITLE DEBUG ${workId}] ✓ Using AAP: "${title}"`);
} else {
console.log(`[TITLE DEBUG ${workId}] No AAP found, trying title property`);
// Try to get title from title property
const titleProp = mainWork['http://id.loc.gov/ontologies/bibframe/title'];
if (titleProp && titleProp[0]) {
const titleId = titleProp[0]['@id'];
console.log(`[TITLE DEBUG ${workId}] Found title reference: ${titleId}`);
const titleObj = work.bibframeData.find(item => item['@id'] === titleId);
if (titleObj) {
console.log(`[TITLE DEBUG ${workId}] Found title object`);
const mainTitle = titleObj['http://id.loc.gov/ontologies/bibframe/mainTitle'];
if (mainTitle && mainTitle[0]) {
title = mainTitle[0]['@value'];
console.log(`[TITLE DEBUG ${workId}] ✓ Using mainTitle: "${title}"`);
} else {
console.log(`[TITLE DEBUG ${workId}] No mainTitle in title object`);
}
} else {
console.log(`[TITLE DEBUG ${workId}] Could not find title object with ID: ${titleId}`);
}
} else {
console.log(`[TITLE DEBUG ${workId}] No title property in main work`);
}
}
} else {
console.log(`[TITLE DEBUG ${workId}] Could not find main work object in bibframe data`);
}
} else {
console.log(`[TITLE DEBUG ${workId}] No bibframe data available`);
}
} else {
console.log(`[TITLE DEBUG ${workId}] ✓ Using label from API: "${title}"`);
}
// Final fallback to Work ID if still no title
if (!title) {
console.warn(`[TITLE DEBUG ${workId}] ⚠️ No title found anywhere, using ID fallback`);
title = `Work ${workId}`;
} else {
console.log(`[TITLE DEBUG ${workId}] Final title before processing: "${title}"`);
}
// Try multiple patterns to strip contributor names
// Pattern 1: "Lastname, Firstname, dates. Title" or "Lastname, Firstname, dates Title"
// Pattern 2: "Lastname, Firstname. Title" or "Lastname, Firstname Title"
// Store original for debugging
const originalTitle = title;
let extractionSuccessful = false;
// First, try to use the known contributor name if available
if (contributorName && title.startsWith(contributorName)) {
// Direct match - contributor name is at the beginning
let remainder = title.substring(contributorName.length);
// Remove common separators after name: ". ", ", ", "- ", ": "
remainder = remainder.replace(/^[\s.,:\-–—]+/, '');
if (remainder && remainder.length > 0) {
title = remainder.trim();
console.log(`[TITLE DEBUG] Used known contributor name to extract: "${title}"`);
extractionSuccessful = true;
}
} else if (contributorName) {
// Try to extract just the last name from contributorName for partial matching
const contributorParts = contributorName.split(',')[0].trim(); // Get last name
if (title.startsWith(contributorParts)) {
// Find where the actual title begins after the author info
const patterns = [
new RegExp(`^${contributorParts.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^.]*\\.\s+`), // Lastname...anything. Title
new RegExp(`^${contributorParts.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^.]*[-–]\s+`) // Lastname...anything- Title
];
for (const pattern of patterns) {
const match = title.match(pattern);
if (match) {
title = title.substring(match[0].length);
console.log(`[TITLE DEBUG] Used partial contributor match to extract: "${title}"`);
extractionSuccessful = true;
break;
}
}
}
}
// If we couldn't use the contributor name, fall back to pattern matching
if (!extractionSuccessful && title.match(/^[^,]+,\s*[^,\.]+/)) {
// Find where the actual title starts
// Could be after ". " or after a year pattern like "1928- " or "1928-2021 "
// First check for pattern with titles/honorifics: "Lastname, Firstname, Title/Sir/Dr., dates. Title"
const authorWithTitleMatch = title.match(/^[^,]+,\s*[^,]+(?:,\s*(?:Sir|Dr|Prof|Mr|Mrs|Ms|Miss|Lord|Lady|Baron|Count|Duke)[^,]*)?(?:,\s*\d{4}[-–](?:\d{4})?)?\s*\.\s+/);
if (authorWithTitleMatch) {
// Extract everything after the author with title/honorific
title = title.substring(authorWithTitleMatch[0].length);
console.log(`[TITLE DEBUG] Matched author with title/honorific pattern, extracted: "${title}"`);
extractionSuccessful = true;
} else {
// Check for pattern: "Lastname, Firstname, dates- Title" or "Lastname, Firstname, dates. Title"
const authorWithDatesMatch = title.match(/^[^,]+,\s*[^,]+,\s*\d{4}[-–](?:\d{4})?\s*[-.]?\s*/);
if (authorWithDatesMatch) {
// Extract everything after the author with dates
title = title.substring(authorWithDatesMatch[0].length);
console.log(`[TITLE DEBUG] Matched author with dates pattern, extracted: "${title}"`);
extractionSuccessful = true;
} else {
// Handle names with initials like "Rowling, J. K. Harry Potter"
// This regex matches: Lastname, (initials and names). Title
const nameWithInitialsMatch = title.match(/^[^,]+,\s*(?:[A-Z]\.?\s*)+(?:[A-Za-z]+\s*)?(?:\([^)]+\))?\s*\.\s+([A-Z])/);
if (nameWithInitialsMatch) {
// Found a name with initials pattern, extract everything after it
const titleStartIndex = title.indexOf(nameWithInitialsMatch[1], nameWithInitialsMatch.index);
title = title.substring(titleStartIndex);
console.log(`[TITLE DEBUG] Matched name with initials, extracted: "${title}"`);
extractionSuccessful = true;
} else {
// Fallback: look for the last ". " that appears to end the author name
// This handles both "Lastname, Firstname. Title" and "Lastname, F. M. Title"
const lastAuthorPeriod = title.match(/^[^,]+,\s*[^.]+\.\s+/);
if (lastAuthorPeriod) {
title = title.substring(lastAuthorPeriod[0].length);
console.log(`[TITLE DEBUG] Matched last period pattern, extracted: "${title}"`);
extractionSuccessful = true;
}
}
}
}
// Only apply additional processing if we haven't successfully extracted a title
if (!extractionSuccessful) {
// Only check for standalone years if title still looks like author format
if (title && title.match(/^[^,]+,\s*[^,\.]+/)) {
const yearMatch = title.match(/\d{4}[-–]\d{0,4}\s+/);
const yearEndMatch = title.match(/\d{4}[-–]\s+/);
if (yearMatch) {
// If there's a year range like "1928-1981 ", use end of that
title = title.substring(yearMatch.index + yearMatch[0].length);
} else if (yearEndMatch) {
// If there's a year with dash like "1928- ", use end of that
title = title.substring(yearEndMatch.index + yearEndMatch[0].length);
}
}
// Final fallback for other patterns - only if title still looks like author format
if (!title || title.match(/^[^,]+,\s*[^,\.]+/)) {
// Look for pattern with just comma and space after second word
const commaCount = (originalTitle.match(/,/g) || []).length;
if (commaCount >= 1) {
// Find the second comma or first space after first comma
const firstComma = originalTitle.indexOf(',');
const afterFirstComma = originalTitle.substring(firstComma + 1).trim();
const nextDelimiter = afterFirstComma.search(/[\s,]/);
if (nextDelimiter > -1) {
const startOfTitle = firstComma + 1 + nextDelimiter + 1;
const potentialTitle = originalTitle.substring(startOfTitle).trim();
// Only use this if it looks like a real title (not another name)
if (potentialTitle && !potentialTitle.match(/^[^,]+,\s*[^,]+/)) {
title = potentialTitle;
console.log(`[TITLE DEBUG] Used fallback pattern, extracted: "${title}"`);
}
}
}
}
}
}
// Normalize the title for grouping
const normalizedTitle = normalizeTitle(title);
// Track title frequency for determining most common form
if (!titleCounts[normalizedTitle]) {
titleCounts[normalizedTitle] = {};
}
if (!titleCounts[normalizedTitle][title]) {
titleCounts[normalizedTitle][title] = 0;
}
titleCounts[normalizedTitle][title]++;
if (work.isNonText) {
nonTextCount++;
console.log(`Non-text work found: ${title}`);
}
// Store work with normalized title for grouping
work.displayTitle = title;
work.normalizedTitle = normalizedTitle;
console.log(`[TITLE DEBUG ${workId}] After processing:`);
console.log(`[TITLE DEBUG ${workId}] Display title: "${work.displayTitle}"`);
console.log(`[TITLE DEBUG ${workId}] Normalized: "${work.normalizedTitle}"`);
// Keep the workType for non-text works
});
// Now group by normalized titles and choose most common form for display
// Also deduplicate by URI
const seenUris = new Set();
enrichedResults.forEach(work => {
// Skip if we've already seen this URI
if (seenUris.has(work.uri)) {
console.log(`Skipping duplicate URI: ${work.uri}`);
return;
}
seenUris.add(work.uri);
const normalizedTitle = work.normalizedTitle;