forked from kristinallarsen/set-builder
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1553 lines (1292 loc) · 51.7 KB
/
script.js
File metadata and controls
1553 lines (1292 loc) · 51.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
let viewer;
let collectedManifests = []; // This will hold the individual manifests
let currentManifestForSelection = null;
let selectedPageIndices = new Set();
// Global state for gallery name
let currentGalleryName = '';
// Function to set gallery name across all displays
function setGalleryName(name) {
const sanitized = name ? name.trim() : '';
currentGalleryName = sanitized;
// Update input field
const nameInput = document.getElementById('manifestName');
if (nameInput) {
nameInput.value = sanitized;
}
// Update page display
updatePageTitle(sanitized);
}
// Function to update page title display
function updatePageTitle(galleryName) {
const titleDisplay = document.getElementById('gallery-title-display');
if (!titleDisplay) return;
if (galleryName) {
// Escape HTML for safety
const tempDiv = document.createElement('div');
tempDiv.textContent = galleryName;
const safeGalleryName = tempDiv.innerHTML;
titleDisplay.innerHTML = safeGalleryName;
// Update browser tab title
document.title = `${galleryName} - IIIF Gallery Builder`;
} else {
titleDisplay.innerHTML = '';
// Reset browser tab title
document.title = 'IIIF Image Gallery Builder';
}
}
// Function to open the first image in the viewer
function openFirstImage() {
const firstThumb = document.querySelector('#gallery .card img');
if (firstThumb) {
firstThumb.click();
document.body.classList.add('viewer-has-image');
}
}
// --- begin deeplink fileopening script --
(function() {
const FILE_INPUT_SELECTOR = '#uploadManifest';
const LOAD_BUTTON_SELECTOR = '#loadManifest';
// Wait for DOM, then defer to the next tick so other DOMContentLoaded handlers
// (like initializeEventListeners) have time to attach their listeners.
document.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
openHostedFileFromQuery().catch(err => {
console.error('Deep-link file loading failed:', err);
alert('Unable to load file from URL. Make sure it is public and supports CORS.');
});
}, 0);
});
async function openHostedFileFromQuery() {
const params = new URLSearchParams(window.location.search);
const rawParam = params.get('file') || params.get('url');
if (!rawParam) return;
const fileUrl = normalizeFileUrl(rawParam);
const response = await fetch(fileUrl, { mode: 'cors', credentials: 'omit', redirect: 'follow' });
if (!response.ok) throw new Error(`HTTP ${response.status} fetching ${fileUrl}`);
const blob = await response.blob();
const filename = params.get('filename') || deriveFilenameFromUrl(fileUrl);
const fileObj = new File([blob], filename, { type: blob.type || 'application/json' });
const input = document.querySelector(FILE_INPUT_SELECTOR) || document.querySelector('input[type="file"]');
if (!input || input.type !== 'file') {
throw new Error('File input not found. Set FILE_INPUT_SELECTOR to your input element.');
}
// Insert the file and trigger your existing change handler
const dt = new DataTransfer();
dt.items.add(fileObj);
input.files = dt.files;
input.dispatchEvent(new Event('change', { bubbles: true }));
// Autoload by clicking your existing Load button
const loadBtn = document.querySelector(LOAD_BUTTON_SELECTOR);
if (loadBtn) {
// Ensure the click runs after all change handlers complete
setTimeout(() => {
loadBtn.click();
}, 0);
} else {
console.warn('Load button not found. Set LOAD_BUTTON_SELECTOR correctly.');
}
}
function normalizeFileUrl(u) {
try {
const url = new URL(u);
if (url.hostname === 'github.com') {
const parts = url.pathname.split('/');
const blobIdx = parts.indexOf('blob');
if (blobIdx !== -1) {
const newPath = parts.slice(0, blobIdx).concat(parts.slice(blobIdx + 1)).join('/');
return 'https://raw.githubusercontent.com' + newPath;
}
}
return u;
} catch (e) {
return u;
}
}
function deriveFilenameFromUrl(u) {
try {
const url = new URL(u);
const base = url.pathname.substring(url.pathname.lastIndexOf('/') + 1);
return decodeURIComponent(base || 'download.json');
} catch {
return 'download.json';
}
}
})();
/* --- end deeplink fileloading -- */
document.addEventListener('DOMContentLoaded', () => {
viewer = OpenSeadragon({
id: 'viewer',
prefixUrl: 'https://cdnjs.cloudflare.com/ajax/libs/openseadragon/4.0.0/images/',
tileSources: []
});
// Initialize resizer functionality
initializeResizer();
// Initialize all event listeners
initializeEventListeners();
});
// Function to make the viewer resizable
function initializeResizer() {
const resizer = document.getElementById('resizer');
const leftPanel = document.querySelector('.left-panel');
const viewer = document.getElementById('viewer');
let isResizing = false;
// Mouse events (existing)
resizer.addEventListener('mousedown', (e) => {
isResizing = true;
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none'; // Prevent text selection while dragging
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
const containerWidth = document.querySelector('.container').offsetWidth;
const newLeftWidth = (e.clientX / containerWidth) * 100;
// Set bounds for resizing (min 20%, max 80%)
if (newLeftWidth > 20 && newLeftWidth < 80) {
leftPanel.style.width = `${newLeftWidth}%`;
}
});
document.addEventListener('mouseup', () => {
if (isResizing) {
isResizing = false;
document.body.style.cursor = 'default';
document.body.style.userSelect = 'auto';
}
});
// Touch events (new)
resizer.addEventListener('touchstart', (e) => {
isResizing = true;
document.body.style.userSelect = 'none'; // Prevent text selection while dragging
e.preventDefault(); // Prevent scrolling while dragging
});
document.addEventListener('touchmove', (e) => {
if (!isResizing) return;
// Get the touch position
const touch = e.touches[0];
const containerWidth = document.querySelector('.container').offsetWidth;
const newLeftWidth = (touch.clientX / containerWidth) * 100;
// Set bounds for resizing (min 20%, max 80%)
if (newLeftWidth > 20 && newLeftWidth < 80) {
leftPanel.style.width = `${newLeftWidth}%`;
}
e.preventDefault(); // Prevent scrolling while dragging
});
document.addEventListener('touchend', () => {
if (isResizing) {
isResizing = false;
document.body.style.userSelect = 'auto';
}
});
}
// Function to make cards draggable and reorderable
function makeCardDraggable(card) {
card.draggable = true;
card.addEventListener('dragstart', (e) => {
// Prevent dragging if clicking on image or links
if (e.target.tagName === 'IMG' || e.target.tagName === 'A' || e.target.tagName === 'BUTTON') {
return;
}
card.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', card.innerHTML);
});
card.addEventListener('dragend', (e) => {
card.classList.remove('dragging');
});
card.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const draggingCard = document.querySelector('.dragging');
if (draggingCard && draggingCard !== card) {
card.classList.add('drag-over');
}
});
card.addEventListener('dragleave', (e) => {
card.classList.remove('drag-over');
});
card.addEventListener('drop', (e) => {
e.preventDefault();
card.classList.remove('drag-over');
const draggingCard = document.querySelector('.dragging');
if (draggingCard && draggingCard !== card) {
const gallery = document.getElementById('gallery');
const allCards = [...gallery.querySelectorAll('.card')];
const draggedIndex = allCards.indexOf(draggingCard);
const targetIndex = allCards.indexOf(card);
if (draggedIndex < targetIndex) {
card.parentNode.insertBefore(draggingCard, card.nextSibling);
} else {
card.parentNode.insertBefore(draggingCard, card);
}
}
});
}
// Detect IIIF version
function getIIIFVersion(manifest) {
if (manifest['@context']) {
if (manifest['@context'].includes('/3/')) {
return 3;
}
if (manifest['@context'].includes('/2/')) {
return 2;
}
}
// If no @context, check for sequences (IIIF 2.0) vs items (IIIF 3.0)
return manifest.sequences ? 2 : 3;
}
// Helper function to extract year from LC Call Number (for institutions like Osher)
function extractYearFromCallNumber(callNumber) {
if (!callNumber) return null;
// Match 4-digit year (1500-2099)
const match = callNumber.match(/\b(1[5-9]\d{2}|20\d{2})\b/);
return match ? match[1] : null;
}
// Helper function to get metadata values (handles both IIIF 2.0 and 3.0)
function getMetadataValue(metadata, label, getLast = false) {
if (!metadata) return null;
// Normalize label to lowercase for comparison
const normalizedLabel = label.toLowerCase();
const items = metadata.filter(item => {
// IIIF 2.0 format: item.label is a string
if (typeof item.label === 'string') {
return item.label.toLowerCase() === normalizedLabel;
}
// IIIF 3.0 format: item.label is an object like {none: ["Title"]} or {en: ["Title"]}
if (typeof item.label === 'object') {
const labelValues = Object.values(item.label).flat();
return labelValues.some(val => val.toLowerCase() === normalizedLabel);
}
return false;
});
if (items.length === 0) return null;
const item = getLast ? items[items.length - 1] : items[0];
// IIIF 2.0 format: value is a string or array
if (typeof item.value === 'string') {
return item.value;
}
if (Array.isArray(item.value)) {
if(typeof item.value[0] === 'object') { return Object.values(item.value[0])[1]; }
else { return item.value[0]; }
}
// IIIF 3.0 format: value is an object like {none: ["value"]} or {en: ["value"]}
if (typeof item.value === 'object') {
const valueArray = Object.values(item.value).flat();
return valueArray[0] || null;
}
return null;
}
// Helper function to check if URL is absolute
function isAbsoluteURL(url) {
return /^(http|https):\/\//i.test(url);
}
// Function to add a canvas to the gallery (supports IIIF 2.0 and 3.0)
function addCanvasToGallery(canvas, manifest) {
const iiifVersion = getIIIFVersion(manifest);
let imageService, imageUrl, highResUrl;
// Handle different IIIF versions for image extraction
if (iiifVersion === 3) {
// IIIF 3.0 structure: canvas.items[0].items[0].body.service[0]
const annotation = canvas.items?.[0]?.items?.[0];
if (!annotation || !annotation.body) {
console.error('IIIF 3.0: Missing annotation body:', canvas);
return;
}
imageService = annotation.body.service?.[0];
if (!imageService) {
console.error('IIIF 3.0: Image service is missing:', canvas);
return;
}
// Handle both IIIF 3.0 (id) and IIIF 2.0 (@id) image service formats
const serviceId = imageService.id || imageService['@id'];
if (!serviceId) {
console.error('IIIF 3.0: Image service does not contain an id or @id field:', canvas);
return;
}
// Check if canvas provides a usable thumbnail
let useProvidedThumbnail = false;
if (canvas.thumbnail) {
const thumbUrl = canvas.thumbnail.id || canvas.thumbnail['@id'];
const thumbHeight = canvas.thumbnail.height;
const thumbWidth = canvas.thumbnail.width;
// Only use provided thumbnail if it's reasonably sized (at least 150px)
if (thumbUrl && ((thumbHeight && thumbHeight >= 150) || (thumbWidth && thumbWidth >= 150))) {
imageUrl = thumbUrl;
useProvidedThumbnail = true;
}
}
if (!useProvidedThumbnail) {
// Fallback: generate thumbnail URL
imageUrl = `${serviceId}/full/!200,200/0/default.jpg`;
}
highResUrl = `${serviceId}/info.json`;
} else {
// IIIF 2.0 structure: canvas.images[0].resource.service
imageService = canvas.images?.[0]?.resource?.service;
if (!imageService || !imageService['@id']) {
console.error('IIIF 2.0: Image service is missing or does not contain an @id field:', canvas);
return;
}
// Check if canvas provides a usable thumbnail
let useProvidedThumbnail = false;
if (canvas.thumbnail) {
const thumbUrl = canvas.thumbnail['@id'] || (typeof canvas.thumbnail === 'string' ? canvas.thumbnail : null);
const thumbHeight = canvas.thumbnail.height;
const thumbWidth = canvas.thumbnail.width;
// Only use provided thumbnail if it's reasonably sized (at least 150px)
if (thumbUrl && ((thumbHeight && thumbHeight >= 150) || (thumbWidth && thumbWidth >= 150))) {
imageUrl = thumbUrl;
useProvidedThumbnail = true;
}
}
if (!useProvidedThumbnail) {
// Fallback: generate thumbnail URL
imageUrl = `${imageService['@id']}/full/!200,200/0/default.jpg`;
}
highResUrl = `${imageService['@id']}/info.json`;
}
// Retrieve metadata from both the manifest and the canvas
const manifestMetadata = manifest.metadata || [];
const canvasMetadata = canvas.metadata || [];
console.log('Manifest Metadata:', manifestMetadata);
console.log('Canvas Metadata:', canvasMetadata);
// Extract title - handle both IIIF 2.0 and 3.0
let title = 'No title returned';
if (iiifVersion === 3) {
// IIIF 3.0: labels are objects like {none: ["Title"]} or {en: ["Title"]}
if (manifest.label) {
const labelValues = Object.values(manifest.label).flat();
title = labelValues[0] || 'No title returned';
}
} else {
// IIIF 2.0: labels are strings
title = manifest.label || 'No title returned';
}
// Also check metadata for title (works for both versions now)
const metadataTitle = getMetadataValue(canvasMetadata, 'Title') || getMetadataValue(manifestMetadata, 'Title');
if (metadataTitle) title = metadataTitle;
// Get date
let date = getMetadataValue(canvasMetadata, 'Date') ||
getMetadataValue(manifestMetadata, 'Date') ||
getMetadataValue(canvasMetadata, 'Issued') ||
getMetadataValue(manifestMetadata, 'Issued') ||
getMetadataValue(canvasMetadata, 'Created') ||
getMetadataValue(manifestMetadata, 'Created') ||
getMetadataValue(canvasMetadata, 'Date Created') || // Indiana, UBC, NCSU
getMetadataValue(manifestMetadata, 'Date Created') ||
getMetadataValue(canvasMetadata, 'Date of Creation') || // Lancaster
getMetadataValue(manifestMetadata, 'Date of Creation') ||
getMetadataValue(canvasMetadata, 'Date of Publication') || // Manchester
getMetadataValue(manifestMetadata, 'Date of Publication') ||
getMetadataValue(canvasMetadata, 'Published/Created Date') || // Yale
getMetadataValue(manifestMetadata, 'Published/Created Date') ||
getMetadataValue(canvasMetadata, 'Date made') ||
getMetadataValue(manifestMetadata, 'Date made') ||
getMetadataValue(canvasMetadata, 'Published') ||
getMetadataValue(manifestMetadata, 'Published') ||
getMetadataValue(canvasMetadata, 'Created Published') || // LOC
getMetadataValue(manifestMetadata, 'Created Published') ||
getMetadataValue(canvasMetadata, 'Pub Date') || // David Rumsey
getMetadataValue(manifestMetadata, 'Pub Date') ||
getMetadataValue(canvasMetadata, 'Date Issued') || // Brown
getMetadataValue(manifestMetadata, 'Date Issued') ||
getMetadataValue(canvasMetadata, 'Date Statement') || // Bodleian
getMetadataValue(manifestMetadata, 'Date Statement') ||
getMetadataValue(canvasMetadata, 'Date original') || // CONTENTdm
getMetadataValue(manifestMetadata, 'Date original') ||
getMetadataValue(canvasMetadata, 'Associated date') ||
getMetadataValue(manifestMetadata, 'Associated date') ||
getMetadataValue(canvasMetadata, 'Publication Date') ||
getMetadataValue(manifestMetadata, 'Publication Date') ||
extractYearFromCallNumber(getMetadataValue(manifestMetadata, 'LC Call Number')) || // Osher
extractYearFromCallNumber(getMetadataValue(canvasMetadata, 'LC Call Number')) ||
'No date returned';
// Get author/creator
let author = getMetadataValue(canvasMetadata, 'Creator') ||
getMetadataValue(manifestMetadata, 'Creator') ||
getMetadataValue(canvasMetadata, 'Contributors') || // LOC
getMetadataValue(manifestMetadata, 'Contributors') ||
getMetadataValue(canvasMetadata, 'Author') ||
getMetadataValue(manifestMetadata, 'Author') ||
getMetadataValue(canvasMetadata, 'Creator/Author') || // CONTENTdm
getMetadataValue(manifestMetadata, 'Creator/Author') ||
getMetadataValue(canvasMetadata, 'Contributor') ||
getMetadataValue(manifestMetadata, 'Contributor') ||
getMetadataValue(canvasMetadata, 'Maker') || // Smithsonian
getMetadataValue(manifestMetadata, 'Maker') ||
getMetadataValue(canvasMetadata, 'Authors') || // David Rumsey
getMetadataValue(manifestMetadata, 'Authors') ||
getMetadataValue(canvasMetadata, 'Publication Author') || // David Rumsey
getMetadataValue(manifestMetadata, 'Publication Author') ||
getMetadataValue(canvasMetadata, 'Map Author(s)') || // University of Washington
getMetadataValue(manifestMetadata, 'Map Author(s)') ||
getMetadataValue(canvasMetadata, 'Publisher') ||
getMetadataValue(manifestMetadata, 'Publisher') ||
getMetadataValue(canvasMetadata, 'Artist/Maker') ||
getMetadataValue(manifestMetadata, 'Artist/Maker') ||
'No author returned';
// Get collection (sub-collections, departments, specific collections)
let collection = getMetadataValue(canvasMetadata, 'Location') ||
getMetadataValue(manifestMetadata, 'Location') ||
getMetadataValue(canvasMetadata, 'Digital Collection') || // Huntington, UWM, University of Washington
getMetadataValue(manifestMetadata, 'Digital Collection') ||
getMetadataValue(canvasMetadata, 'Original Collection') || // UWM
getMetadataValue(manifestMetadata, 'Original Collection') ||
getMetadataValue(canvasMetadata, 'Source Collection') || // Duke
getMetadataValue(manifestMetadata, 'Source Collection') ||
getMetadataValue(canvasMetadata, 'Collection') ||
getMetadataValue(manifestMetadata, 'Collection') ||
getMetadataValue(canvasMetadata, 'Collections') || // Berkeley, Leeds
getMetadataValue(manifestMetadata, 'Collections') ||
getMetadataValue(canvasMetadata, 'Physical Location') || // Manchester, Lancaster, Hawaii
getMetadataValue(manifestMetadata, 'Physical Location') ||
getMetadataValue(canvasMetadata, 'Holding Location') || // Indiana
getMetadataValue(manifestMetadata, 'Holding Location') ||
getMetadataValue(canvasMetadata, 'Relation') ||
getMetadataValue(manifestMetadata, 'Relation') ||
getMetadataValue(canvasMetadata, 'Data Source') ||
getMetadataValue(manifestMetadata, 'Data Source') ||
getMetadataValue(canvasMetadata, 'Source') || // Huntington, UWM, University of Washington, OCLC CDM, Villanova, BYU
getMetadataValue(manifestMetadata, 'Source') ||
getMetadataValue(canvasMetadata, 'Repository') || // Gallica, UCLA, Yale, Huntington, UWM, University of Washington, OCLC CDM, NCSU
getMetadataValue(manifestMetadata, 'Repository') ||
getMetadataValue(canvasMetadata, 'Contributor') ||
getMetadataValue(manifestMetadata, 'Contributor') ||
'No collection returned';
// For Internet Archive (IIIF 3.0), prefer Contributor over Collection
if (iiifVersion === 3) {
const contributor = getMetadataValue(manifestMetadata, 'Contributor') ||
getMetadataValue(canvasMetadata, 'Contributor');
if (contributor) {
collection = contributor;
}
}
// Get attribution
let attribution = 'No attribution returned';
if (iiifVersion === 3) {
// IIIF 3.0: check provider or requiredStatement
if (manifest.provider?.[0]?.label) {
const providerLabel = Object.values(manifest.provider[0].label).flat();
attribution = providerLabel[0] || 'No attribution returned';
}
if (manifest.requiredStatement?.value) {
const reqValue = Object.values(manifest.requiredStatement.value).flat();
attribution = reqValue[0] || attribution;
}
} else {
// IIIF 2.0: Try metadata fields first (more reliable than attribution field)
attribution = getMetadataValue(manifestMetadata, 'Repository') || // Multiple institutions
getMetadataValue(canvasMetadata, 'Repository') ||
getMetadataValue(manifestMetadata, 'Digital Publisher') || // UWM
getMetadataValue(manifestMetadata, 'Provider') || // UBC
getMetadataValue(manifestMetadata, 'Attribution') || // Leeds
getMetadataValue(canvasMetadata, 'Attribution');
// If metadata doesn't have it, try attribution field
if (!attribution) {
if (manifest.attribution) {
// Handle array or string
if (Array.isArray(manifest.attribution)) {
// Only use if it's not a URL
const nonUrl = manifest.attribution.find(a => a && a.trim() && !a.startsWith('http'));
attribution = nonUrl || 'No attribution returned';
} else if (!manifest.attribution.startsWith('http')) {
attribution = manifest.attribution;
}
}
}
// Final fallback
if (!attribution) {
attribution = 'No attribution returned';
}
}
// Get location link from various possible sources
let locationLink = null;
if (iiifVersion === 3) {
// IIIF 3.0: check homepage
if (manifest.homepage?.[0]?.id) {
locationLink = manifest.homepage[0].id;
}
} else {
// IIIF 2.0: check related field (David Rumsey / LUNA)
if (manifest.related) {
if (typeof manifest.related === 'object' && manifest.related["@id"]) {
locationLink = manifest.related["@id"];
} else if (typeof manifest.related === 'string') {
locationLink = manifest.related;
}
}
}
// If locationLink is still not defined, check other sources
if (!locationLink) {
// Try to extract URL from Source metadata (CONTENTdm often has HTML here)
const sourceMetadata = getMetadataValue(manifestMetadata, 'Source');
if (sourceMetadata && sourceMetadata.includes('href=')) {
// Extract URL from HTML
const match = sourceMetadata.match(/href=["']([^"']+)["']/);
if (match && match[1]) {
locationLink = match[1];
}
}
}
// If still not found, try other fields
if (!locationLink) {
locationLink = getMetadataValue(canvasMetadata, 'Identifier') ||
getMetadataValue(manifestMetadata, 'Identifier', true) ||
getMetadataValue(canvasMetadata, 'Item Url') ||
getMetadataValue(manifestMetadata, 'Item Url') ||
getMetadataValue(manifestMetadata, 'identifier-access') || // Internet Archive
canvas['@id'] ||
canvas.id || // IIIF 3.0 uses 'id' instead of '@id'
'No link available';
}
// Ensure the link is absolute
if (!isAbsoluteURL(locationLink) && locationLink !== 'No link available') {
locationLink = 'https://' + locationLink;
}
// --- Construct the Allmaps Link ---
//Get the manifest URL
const manifestUrlForGeoreferencing = manifest.id || manifest['@id'];
//Create the full Allmaps Editor URL
const allmapsLink = `https://editor.allmaps.org/?url=${encodeURIComponent(manifestUrlForGeoreferencing)}`;
// Debugging logs for verification
console.log('Location Link:', locationLink);
// Create card element
const card = document.createElement('div');
card.className = 'card';
// Store canvas and manifest data on the card
card.dataset.manifestId = manifest['@id'] || manifest.id;
// Sanitize canvas before storing to prevent validation issues
const canvasToStore = JSON.parse(JSON.stringify(canvas)); // Deep clone
// Fix otherContent if it's a string instead of array (David Rumsey issue)
if (canvasToStore.otherContent && typeof canvasToStore.otherContent === 'string') {
canvasToStore.otherContent = [canvasToStore.otherContent];
}
card.dataset.canvasData = JSON.stringify(canvasToStore);
// Make card draggable
makeCardDraggable(card);
// Create image element
const img = document.createElement('img');
img.src = imageUrl;
img.alt = title;
// Click to view in OpenSeadragon
img.addEventListener('click', () => {
viewer.open(highResUrl);
});
// Create delete button
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.textContent = '×';
deleteBtn.addEventListener('click', () => {
const shouldRemove = confirm('Do you want to remove this image from the gallery?');
if (shouldRemove) {
card.remove();
}
});
// Create metadata elements
const titleEl = document.createElement('p');
titleEl.innerHTML = `<strong>Title:</strong> ${title}`;
const authorEl = document.createElement('p');
authorEl.innerHTML = `<strong>Author:</strong> ${author}`;
const dateEl = document.createElement('p');
dateEl.innerHTML = `<strong>Date:</strong> ${date}`;
const collectionEl = document.createElement('p');
collectionEl.innerHTML = `<strong>Collection:</strong> ${collection}`;
const attributionEl = document.createElement('p');
attributionEl.innerHTML = `<strong>Attribution:</strong> ${attribution}`;
// Create link container (like control-links)
const cardLinks = document.createElement('div');
cardLinks.className = 'card-links';
// Create link to item
const locationLinkEl = document.createElement('a');
locationLinkEl.href = locationLink;
locationLinkEl.textContent = 'View Item';
locationLinkEl.target = '_blank';
locationLinkEl.className = 'card-link';
cardLinks.appendChild(locationLinkEl);
// Create link to IIIF manifest
const manifestLinkEl = document.createElement('a');
manifestLinkEl.href = manifest['@id'] || manifest.id || '#';
manifestLinkEl.textContent = 'View Manifest';
manifestLinkEl.target = '_blank';
manifestLinkEl.className = 'card-link';
cardLinks.appendChild(manifestLinkEl);
// Create link to Allmaps
const allmapsLinkEl = document.createElement('a');
allmapsLinkEl.href = allmapsLink;
allmapsLinkEl.textContent = 'Allmaps Editor';
allmapsLinkEl.target = '_blank';
allmapsLinkEl.className = 'card-link';
cardLinks.appendChild(allmapsLinkEl);
// Append all elements to card
card.appendChild(deleteBtn);
card.appendChild(img);
card.appendChild(titleEl);
card.appendChild(authorEl);
card.appendChild(dateEl);
card.appendChild(collectionEl);
card.appendChild(attributionEl);
card.appendChild(cardLinks);
// Add card to gallery
document.getElementById('gallery').appendChild(card);
}
function repopulateGallery(manifestData) {
const gallery = document.getElementById('gallery');
if (!gallery) {
console.error('Gallery element not found!');
return;
}
gallery.innerHTML = '';
const manifests = manifestData.items;
if (!Array.isArray(manifests)) {
console.error('No valid items found in the manifest data.');
return;
}
collectedManifests = [];
manifests.forEach(manifest => {
collectedManifests.push(manifest);
const iiifVersion = getIIIFVersion(manifest);
let canvasItems = [];
if (iiifVersion === 3) {
canvasItems = manifest.items || [];
} else {
canvasItems = manifest.sequences?.[0]?.canvases || [];
}
canvasItems.forEach(canvas => {
addCanvasToGallery(canvas, manifest);
});
});
// Set gallery name from loaded manifest
let galleryName = '';
if (manifestData.label) {
if (typeof manifestData.label === 'string') {
galleryName = manifestData.label;
} else if (typeof manifestData.label === 'object') {
const labelValues = Object.values(manifestData.label).flat();
galleryName = labelValues[0] || '';
}
}
setGalleryName(galleryName);
// Auto-open first image after gallery loads
setTimeout(() => {
openFirstImage();
}, 100);
}
/// Function to add a IIIF manifest to the gallery (supports both 2.0 and 3.0)
async function addManifestToGallery(manifestUrl) {
try {
const response = await fetch(manifestUrl);
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
const manifest = await response.json();
const iiifVersion = getIIIFVersion(manifest);
let canvasItems = [];
if (iiifVersion === 3) {
if (!manifest.items || manifest.items.length === 0) {
throw new Error('IIIF 3.0 Manifest does not contain items (canvases).');
}
canvasItems = manifest.items;
} else {
if (!manifest.sequences || !manifest.sequences[0].canvases) {
throw new Error('IIIF 2.0 Manifest does not contain sequences or canvases in the expected format.');
}
canvasItems = manifest.sequences[0].canvases;
}
// Check if multi-page manifest
if (canvasItems.length > 1) {
// Show page selector
showPageSelector(manifest, canvasItems);
} else {
// Single page - add directly
// Ensure manifest has a label
if (!manifest.label) {
const metadata = manifest.metadata || [];
let foundTitle = null;
for (const item of metadata) {
const labelText = typeof item.label === 'string' ? item.label :
(typeof item.label === 'object' ? Object.values(item.label).flat().join('') : '');
if (labelText.toLowerCase() === 'title') {
if (typeof item.value === 'string') {
foundTitle = item.value;
} else if (Array.isArray(item.value)) {
foundTitle = item.value[0];
} else if (typeof item.value === 'object') {
foundTitle = Object.values(item.value).flat()[0];
}
break;
}
}
if (foundTitle) {
manifest.label = foundTitle;
} else if (canvasItems[0] && canvasItems[0].label) {
const iiifVersion = getIIIFVersion(manifest);
if (iiifVersion === 3 && typeof canvasItems[0].label === 'object') {
manifest.label = Object.values(canvasItems[0].label).flat()[0] || 'Untitled';
} else {
manifest.label = canvasItems[0].label || 'Untitled';
}
}
}
collectedManifests.push(manifest);
canvasItems.forEach(canvas => {
addCanvasToGallery(canvas, manifest);
});
}
} catch (error) {
console.error('Error fetching IIIF Manifest:', error);
alert(`There was an error fetching the IIIF Manifest: ${error.message}`);
}
}
// Function to export combined manifest (Collection format - for this app)
function exportCombinedManifest() {
const manifestName = document.getElementById('manifestName').value.trim();
// Auto-generate name if empty
let finalName = manifestName;
if (!finalName) {
const today = new Date().toISOString().split('T')[0];
finalName = `iiif-gallery-${today}`;
}
setGalleryName(finalName);
// Get current gallery state from the DOM
const gallery = document.getElementById('gallery');
const cards = gallery.querySelectorAll('.card');
if (cards.length === 0) {
alert('No images in gallery to export. Please add some manifests first.');
return;
}
// // Build manifests array from current gallery order by reading card data
const currentManifests = [];
cards.forEach(card => {
const manifestId = card.dataset.manifestId;
const canvasData = card.dataset.canvasData;
if (!manifestId || !canvasData) return;
let canvas;
try {
canvas = JSON.parse(canvasData);
} catch (e) {
console.error('Failed to parse canvas data:', e);
return;
}
// Find the source manifest
const sourceManifest = collectedManifests.find(m =>
(m['@id'] === manifestId || m.id === manifestId)
);
if (!sourceManifest) return;
// Create a single-canvas manifest for this card
const iiifVersion = getIIIFVersion(sourceManifest);
let singleCanvasManifest;
if (iiifVersion === 3) {
singleCanvasManifest = {
...sourceManifest,
items: [canvas]
};
} else {
singleCanvasManifest = {
...sourceManifest,
sequences: [{
...(sourceManifest.sequences?.[0] || {}),
canvases: [canvas]
}]
};
}
currentManifests.push(singleCanvasManifest);
});
// Update collectedManifests to match current state
collectedManifests = currentManifests;
// Sanitize all manifests to fix otherContent issues
const sanitizedManifests = collectedManifests.map(manifest => {
const sanitized = JSON.parse(JSON.stringify(manifest)); // Deep clone
// Fix canvases in IIIF 2.0 manifests
if (sanitized.sequences && sanitized.sequences[0] && sanitized.sequences[0].canvases) {
sanitized.sequences[0].canvases.forEach(canvas => {
// Fix otherContent if it's a string instead of array
if (canvas.otherContent && typeof canvas.otherContent === 'string') {
canvas.otherContent = [canvas.otherContent];
}
});
}
// Fix items in IIIF 3.0 manifests
if (sanitized.items) {
sanitized.items.forEach(canvas => {
if (canvas.otherContent && typeof canvas.otherContent === 'string') {
canvas.otherContent = [canvas.otherContent];
}
});
}
return sanitized;
});
// Create a combined manifest structure (Collection format)
const combinedManifest = {
'@context': 'http://iiif.io/api/presentation/2/context.json',
'@type': 'sc:Collection',
'@id': `https://iiif-gallery-builder.example.org/${finalName}`,
'label': finalName,
'items': sanitizedManifests
};
// Convert to JSON string
const manifestJson = JSON.stringify(combinedManifest, null, 2);
// Create a blob and download
const blob = new Blob([manifestJson], { type: 'application/json' });
const url = URL.createObjectURL(blob);