-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathline-parser.js
More file actions
1690 lines (1614 loc) · 65.9 KB
/
line-parser.js
File metadata and controls
1690 lines (1614 loc) · 65.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
/**
* A manual line parser akin to the one available at TPEN 2.8.
*
* It is exposed to the user at /interfaces/annotator/line-parser.html.
*
* The Annotation generation UI is powered by Annotorious. The TPEN3 team hereby acknowledges
* and thanks the Annotorious development team for this open source software.
* @see https://annotorious.dev/
* Annotorious licensing information can be found at https://github.com/annotorious/annotorious
* @element tpen-line-parser
*/
import TPEN from '../../api/TPEN.js'
import User from '../../api/User.js'
import { getAgentIRIFromToken } from '../iiif-tools/index.js'
import CheckPermissions from '../check-permissions/checkPermissions.js'
import { detectTextLinesCombined } from "./detect-lines.js"
import { v4 as uuidv4 } from "https://cdn.skypack.dev/uuid@9.0.1"
import { CleanupRegistry } from '../../utilities/CleanupRegistry.js'
import { onProjectReady } from '../../utilities/projectReady.js'
import vault from '../../js/vault.js'
import '../page-selector/index.js'
class AnnotoriousAnnotator extends HTMLElement {
#osd
#annotoriousInstance
#annotoriousContainer
#userForAnnotorious
#annotationPageID
#resolvedAnnotationPage
#modifiedAnnotationPage
#imageDims
#canvasDims
#isDrawing = false
#isLineEditing = false
#isErasing = false
#editType = ""
#canvasImageURL
#canvasID
#currentMergeSelection
/** @type {Set<number>} Set of pending timeout IDs for cleanup */
#pendingTimeouts = new Set()
/** @type {CleanupRegistry} Registry for cleanup handlers */
cleanup = new CleanupRegistry()
/** @type {CleanupRegistry} Registry for render-specific handlers */
renderCleanup = new CleanupRegistry()
/** @type {CleanupRegistry} Registry for annotation element handlers */
annotationCleanup = new CleanupRegistry()
/** @type {Function|null} Unsubscribe function for project ready listener */
_unsubProject = null
constructor() {
super()
this.attachShadow({ mode: 'open' })
}
// Custom component setup
connectedCallback() {
TPEN.attachAuthentication(this)
this.initialize()
}
/**
* Initializes the annotator component.
*/
initialize() {
// Must know the User
if (!this.#userForAnnotorious) {
const agent = getAgentIRIFromToken(this.userToken)
if (!agent) {
this.shadowRoot.innerHTML = `
<h3>User Error</h3>
<p>The user agent could not be detected or does not have access to this page.</p>
`
return
}
// Whatever value is here becomes the value of 'creator' on the Annotations.
this.#userForAnnotorious = agent
}
// Must know the Project
this.shadowRoot.innerHTML = "Loading the Annotator. Please provide a ?projectID= in the URL."
this._unsubProject = onProjectReady(this, this.render)
this.cleanup.onEvent(TPEN.eventDispatcher, 'tpen-project-load-failed', (err) => {
this.shadowRoot.innerHTML = `
<h3>Project Error</h3>
<p>The project you are looking for does not exist or you do not have access to it.</p>
<p> ${err.detail.status}: ${err.detail.statusText} </p>
`
})
}
disconnectedCallback() {
try { this._unsubProject?.() } catch {}
// Clear any pending timeouts
for (const timeoutId of this.#pendingTimeouts) {
clearTimeout(timeoutId)
}
this.#pendingTimeouts.clear()
this.annotationCleanup.run()
this.renderCleanup.run()
this.cleanup.run()
}
// Initialize HTML after loading in a TPEN3 Project
render() {
// Check that user can create AND update selectors on lines (required for the annotator)
if (!(CheckPermissions.checkEditAccess("LINE", "SELECTOR") && CheckPermissions.checkCreateAccess("LINE", "SELECTOR"))) {
this.shadowRoot.innerHTML = "You do not have the proper project permissions to use this interface."
return
}
// Must have a Page _id to continue
if (!TPEN.screen.pageInQuery) {
const url = new URL(location.href)
url.searchParams.set('pageID',TPEN.activeProject.getFirstPageID().split('/').pop())
location.href = url.toString()
return
}
this.#annotationPageID = TPEN.screen.pageInQuery
if (!this.#annotationPageID) {
this.shadowRoot.innerHTML = "You must provide a '?pageID=theid' in the URL. The value should be the ID of an existing TPEN3 Page."
return
}
const osdScript = document.createElement("script")
osdScript.src = "../components/annotorious-annotator/OSD.min.js"
const annotoriousScript = document.createElement("script")
annotoriousScript.src = "../components/annotorious-annotator/AnnotoriousOSD.min.js"
this.shadowRoot.innerHTML = `
<style>
@import "../components/annotorious-annotator/AnnotoriousOSD.min.css";
#annotator-container {
height: 90vh;
background-image: url(https://t-pen.org/TPEN/images/loading2.gif);
background-repeat: no-repeat;
background-position: center;
}
#tools-container {
background-color: var(--light-gray);
position: absolute;
top: 40px;
left: 5px;
z-index: 10;
padding: 0px 5px 5px 5px;
width: 390px;
border: 2px solid var(--gray);
border-radius: 5px;
display: none;
}
#tools-container label {
display: block;
margin: 6px 0px;
}
#tools-container i {
display: block;
}
input[type="checkbox"] {
width: 20px;
height: 20px;
}
input[type="button"].selected {
background-color: green;
}
#ruler {
display: none;
background: black;
position: absolute;
z-index: 6;
pointer-events: none;
}
#sampleRuler {
display: none;
overflow: hidden;
position:relative;
background:black;
width:80%;
margin:0 auto;
height:2px;
top:-10px;
}
.editOptions {
display: none;
padding: 5px;
}
.toggleEditType {
margin-top: 6px;
}
.toggleEditType, input[type="checkbox"], #saveBtn, #createColumnsBtn, #deleteAllBtn {
cursor: pointer;
}
#saveBtn, #createColumnsBtn, #deleteAllBtn {
background-color: var(--primary-color);
text-transform: uppercase;
outline: var(--primary-light) 1px solid;
outline-offset: -3.5px;
color: var(--white);
border-radius: 5px;
transition: all 0.3s;
padding: 10px 20px;
cursor: pointer;
width: 100%;
margin-top: 1em;
display: block;
text-align: center;
text-decoration: none;
border: none;
box-sizing: border-box;
}
#saveBtn[disabled], #createColumnsBtn[disabled], #deleteAllBtn[disabled] {
background-color: gray;
color: white;
}
#saveBtn:hover, #createColumnsBtn:hover, #deleteAllBtn:hover {
background-color: var(--primary-light);
outline: var(--primary-color) 1px solid;
outline-offset: -1.5px;
}
:focus-visible {
outline: none !important;
border: none !important;
}
label span {
position: relative;
display: inline-block;
width: 90%;
}
.dragMe {
position: absolute;
top: -5px;
cursor: grab;
height: auto;
width: auto;
}
.dragMe.leftside {
left: 0
}
.dragMe.rightside {
right: 0
}
.helperHeading {
margin-top: 2em;
text-align: center;
}
.helperText {
font-size: 9pt;
font-weight: bold;
}
.a9s-annotation.selected .a9s-inner {
fill-opacity: 0.48 !important;
}
.transcribeLink {
margin-left: 2em !important;
cursor: pointer;
}
.transcribeLink:hover:after {
content: "Go Transcribe";
cursor: pointer;
position: absolute;
width: 105px;
top: 10px;
margin-left: 5px;
color: var(--link);
}
#autoParseBtn {
position: absolute;
display: none;
top: 10px;
right: 10px;
background-color: var(--primary-color);
padding: 10px 20px;
color: var(--white);
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
z-index: 9;
}
#autoParseBtn:hover,
#autoParseBtn:focus-visible {
background-color: var(--primary-light);
outline: 2px solid var(--primary-color);
outline-offset: 2px;
}
tpen-page-selector {
position: absolute;
display: none;
top: 60px;
right: 10px;
z-index: 9;
}
tpen-page-selector::part(select) {
font-size: clamp(0.8rem, 1vw, 1rem);
padding: 10px 15px;
border: 2px outset buttonborder;
border-radius: 5px;
background-color: var(--primary-color);
color: var(--white);
cursor: pointer;
max-width: 300px;
overflow: hidden;
text-overflow: ellipsis;
}
tpen-page-selector::part(select):hover,
tpen-page-selector::part(select):focus-visible {
outline: 2px solid var(--primary-color);
outline-offset: 2px;
}
#projectManagementBtn {
position: absolute;
display: none;
bottom: 10px;
left: 5px;
background-color: var(--primary-color);
padding: 10px 20px;
color: var(--white);
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
z-index: 9;
border: none;
}
#projectManagementBtn:hover,
#projectManagementBtn:focus-visible {
background-color: var(--primary-light);
outline: 2px solid var(--primary-color);
outline-offset: 2px;
}
#projectManagementBtn span {
position: relative;
left: -10px;
display: inline-block;
transform: rotate(180deg);
}
</style>
<div>
<div id="tools-container" class="card">
<div class="dragMe leftside"><img draggable="false" src="../../assets/icons/grabspot.png" alt=""></div>
<div class="dragMe rightside"><img draggable="false" src="../../assets/icons/grabspot.png" alt=""></div>
<p class="helperHeading helperText"> You can zoom and pan when you are not drawing.</p>
<label for="drawTool">
<span>Draw Columns</span>
<input type="checkbox" id="drawTool">
</label>
<label for="editTool">
<span>Make/Edit Lines</span>
<input type="checkbox" id="editTool">
</label>
<div class="editOptions">
<i class="helperText">
* You must select a line.
<br>
* Splitting creates a new line under the selected line.
<br>
* Merging combines the selected line with the line underneath it.
</i>
<input type="button" class="toggleEditType" id="addLinesBtn" value="Add Lines" />
<input type="button" class="toggleEditType" id="mergeLinesBtn" value="Merge Lines" />
</div>
<label>
<span>Remove Lines</span>
<input type="checkbox" id="eraseTool">
</label>
<label style="display:none;">
<span>Annotation Visibility</span>
<input type="checkbox" id="seeTool" checked>
</label>
<button id="deleteAllBtn" type="button">Delete All Annotations</button>
<button id="createColumnsBtn" type="button">Manage Columns</button>
<button id="saveBtn" type="button">Save Annotations</button>
</div>
<button type="button" id="autoParseBtn">Auto Parse</button>
<tpen-page-selector></tpen-page-selector>
<button type="button" id="projectManagementBtn"><span aria-hidden="true">↪</span> Go to Project Management</button>
<div id="annotator-container"> Loading Annotorious and getting the TPEN3 Page information... </div>
<div id="ruler"></div>
<span id="sampleRuler"></span>
</div>`
// Clear previous render-specific listeners before adding new ones
this.renderCleanup.run()
this.renderCleanup.onElement(this.shadowRoot.querySelector("#autoParseBtn"), "click", async () => {
try {
if (typeof cv === "undefined") {
await new Promise((resolve, reject) => {
const openCVScript = document.createElement("script")
openCVScript.src = "https://docs.opencv.org/4.x/opencv.js"
openCVScript.async = true
openCVScript.onload = () => {
cv['onRuntimeInitialized'] = () => {
cv['onRuntimeInitializedCalled'] = true
resolve()
}
}
openCVScript.onerror = reject
document.body.appendChild(openCVScript)
})
} else if (!cv['onRuntimeInitializedCalled']) {
await new Promise(resolve => {
cv['onRuntimeInitialized'] = () => {
cv['onRuntimeInitializedCalled'] = true
resolve()
}
})
}
const imageUrl = this.#canvasImageURL
const boxes = await detectTextLinesCombined(imageUrl)
const newAnnotations = []
for (const line of boxes) {
const { x, y, w, h } = line
newAnnotations.push({
type: "Annotation",
motivation: "transcribing",
target: {
source: this.#canvasID,
type: "SpecificResource",
selector: {
type: "FragmentSelector",
conformsTo: "http://www.w3.org/TR/media-frags/",
value: `xywh=pixel:${x},${y},${w},${h}`
}
}
})
}
this.#annotoriousInstance.setAnnotations(newAnnotations, true)
this.#resolvedAnnotationPage.$isDirty = true
} catch (err) {
console.error("Auto Parse failed:", err)
TPEN.eventDispatcher.dispatch("tpen-toast", {
message: "Auto Parse failed. Please try again.",
status: "error"
})
}
})
this.#annotoriousContainer = this.shadowRoot.getElementById('annotator-container')
const drawTool = this.shadowRoot.getElementById("drawTool")
const editTool = this.shadowRoot.getElementById("editTool")
const eraseTool = this.shadowRoot.getElementById("eraseTool")
const seeTool = this.shadowRoot.getElementById("seeTool")
const saveButton = this.shadowRoot.getElementById("saveBtn")
const deleteAllBtn = this.shadowRoot.getElementById("deleteAllBtn")
const createColumnsBtn = this.shadowRoot.getElementById("createColumnsBtn")
const addLinesBtn = this.shadowRoot.getElementById("addLinesBtn")
const mergeLinesBtn = this.shadowRoot.getElementById("mergeLinesBtn")
const drag = this.shadowRoot.querySelectorAll(".dragMe")
drag.forEach(elem => this.renderCleanup.onElement(elem, "mousedown", (e) => this.dragging(e)))
this.renderCleanup.onElement(addLinesBtn, "click", (e) => this.toggleAddLines(e))
this.renderCleanup.onElement(mergeLinesBtn, "click", (e) => this.toggleMergeLines(e))
this.renderCleanup.onElement(drawTool, "change", (e) => this.toggleDrawingMode(e))
this.renderCleanup.onElement(editTool, "change", (e) => this.toggleEditingMode(e))
this.renderCleanup.onElement(eraseTool, "change", (e) => this.toggleErasingMode(e))
this.renderCleanup.onElement(seeTool, "change", (e) => this.toggleAnnotationVisibility(e))
this.renderCleanup.onElement(createColumnsBtn, "click", () =>
window.location.href = `/manage-columns?projectID=${TPEN.activeProject._id}&pageID=${this.#annotationPageID}`
)
this.renderCleanup.onElement(saveButton, "click", (e) => {
this.#annotoriousInstance.cancelSelected()
// Timeout required in order to allow the unfocus native functionality to complete for $isDirty.
const timeoutId = setTimeout(() => {
this.#pendingTimeouts.delete(timeoutId)
this.saveAnnotations()
}, 500)
this.#pendingTimeouts.add(timeoutId)
})
this.renderCleanup.onElement(deleteAllBtn, "click", async (e) => await this.deleteAllAnnotations(e))
this.renderCleanup.onWindow('beforeunload', (ev) => {
if (this.#resolvedAnnotationPage?.$isDirty) {
ev.preventDefault()
ev.returnValue = ''
}
})
// OSD and AnnotoriousOSD need some cycles to load, they are big files.
this.shadowRoot.appendChild(osdScript)
const outerTimeoutId = setTimeout(() => {
this.#pendingTimeouts.delete(outerTimeoutId)
this.shadowRoot.appendChild(annotoriousScript)
const innerTimeoutId = setTimeout(() => {
this.#pendingTimeouts.delete(innerTimeoutId)
// Process the page to get the data required for the component UI
this.processPage(this.#annotationPageID)
}, 200)
this.#pendingTimeouts.add(innerTimeoutId)
}, 200)
this.#pendingTimeouts.add(outerTimeoutId)
}
/**
* Resolve and process/validate a TPEN3 Page ID.
* In order to show an Image the AnnotationPage must target a Canvas that has an Image annotated onto it.
* Process the target, which can be a value of various types.
* Pass along the string Canvas URI that relates to or is the direct value of the target.
*
* FIXME
* Give users a path when AnnotationPage URIs do not resolve or resolve to something unexpected.
*
* @param page An AnnotationPage URI. The AnnotationPage should target a Canvas.
*/
async processPage(pageID) {
if (!pageID) return
// We want to use this URL instead of the RERUM URL to help with temp pages vs incorrect ids
this.#resolvedAnnotationPage = await fetch(`${TPEN.servicesURL}/project/${TPEN.activeProject._id}/page/${pageID.split("/").pop()}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${TPEN.getAuthorization()}`,
}
})
.then(r => {
if (!r.ok) throw r
// resolve all the referenced Annotations in items:[]?
return r.json()
})
.catch(e => {
this.shadowRoot.innerHTML = `
<h3>Page Error</h3>
<p>The Page you are looking for does not exist or you do not have access to it.</p>
<p> ${e.status}: ${e.statusText} </p>
`
throw e
})
this.#resolvedAnnotationPage.$isDirty = false
const context = this.#resolvedAnnotationPage["@context"]
if (!(context?.includes("iiif.io/api/presentation/3/context.json") || context?.includes("w3.org/ns/anno.jsonld"))) {
console.warn("The AnnotationPage object did not have the IIIF Presentation API 3 context and may not be parseable.")
}
const id = this.#resolvedAnnotationPage["@id"] ?? this.#resolvedAnnotationPage.id
if (!id) {
throw new Error("Cannot Resolve AnnotationPage", { "cause": "The AnnotationPage is 404 or unresolvable." })
}
const type = this.#resolvedAnnotationPage["@type"] ?? this.#resolvedAnnotationPage.type
if (type !== "AnnotationPage") {
throw new Error(`Provided URI did not resolve an 'AnnotationPage'. It resolved a '${type}'`, { "cause": "URI must point to an AnnotationPage." })
}
const targetCanvas = this.#resolvedAnnotationPage.target
if (!targetCanvas) {
throw new Error(`The AnnotationPage object did not have a target Canvas. There is no image to load.`, { "cause": "AnnotationPage.target must have a value." })
}
// Resolve any referenced items
if (this.#resolvedAnnotationPage?.items && this.#resolvedAnnotationPage.items.length) {
let i = -1
for await (const anno_ref of this.#resolvedAnnotationPage.items) {
i++
if (anno_ref.hasOwnProperty("body")) continue
const anno_res = await fetch(anno_ref.id).then(res => res.json()).catch(err => { throw err })
this.#resolvedAnnotationPage.items[i] = anno_res
}
}
// Note this will process the id from embedded Canvas objects to pass forward and be resolved.
const canvasURI = this.processPageTarget(targetCanvas)
// Process the Canvas to get the data for the component UI.
this.processCanvas(canvasURI)
}
/**
* Fetch a Canvas URI and check that it is a Canvas object. Pass it forward to render the Image into the interface.
* Be prepared to receive presentation api 2+
*
* FIXME
* Give users a path when Canvas URIs do not resolve or resolve to something unexpected.
*
* @param uri A String Canvas URI
*/
async processCanvas(uri) {
if (!uri) return
let resolvedCanvas = await vault.getWithFallback(uri, 'canvas', TPEN.activeProject?.manifest)
if (!resolvedCanvas) {
this.shadowRoot.innerHTML = `
<h3>Canvas Error</h3>
<p>The Canvas within this Page could not be loaded.</p>
<p>The Canvas could not be resolved or is invalid.</p>
`
return
}
const context = resolvedCanvas["@context"]
if (!context?.includes("iiif.io/api/presentation/3/context.json")) {
console.warn("The Canvas object did not have the IIIF Presentation API 3 context and may not be parseable.")
}
const id = resolvedCanvas["@id"] ?? resolvedCanvas.id
if (!id) {
throw new Error("Cannot Resolve Canvas or Image", { "cause": "The Canvas is 404 or unresolvable." })
}
const type = resolvedCanvas["@type"] ?? resolvedCanvas.type
if (!(type === "Canvas" || type === "sc:Canvas")) {
throw new Error(`Provided URI did not resolve a 'Canvas'. It resolved a '${type}'`, { "cause": "URI must point to a Canvas." })
}
// Use the Annotations and Image on the Canvas for inititalizing the Annotorious portion of the component.
this.loadAnnotorious(resolvedCanvas)
}
async validateImageUrl(url) {
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(true)
img.onerror = () => reject(false)
img.src = url
})
}
/**
* The Project, User, Page, and Canvas data has been processed.
* The UI is ready to try to load Annotorious and Annotorious listeners.
*
* @param resolveCanvas - Canvas JSON which includes the Image and any existing Annotations for Annotorious.
*/
async loadAnnotorious(resolvedCanvas) {
this.shadowRoot.getElementById('annotator-container').innerHTML = ""
const canvasID = resolvedCanvas["@id"] ?? resolvedCanvas.id
this.#canvasID = canvasID
let fullImage = resolvedCanvas?.items?.[0]?.items?.[0]?.body?.id
if (!fullImage) fullImage = resolvedCanvas?.images?.[0]?.resource?.["@id"]
let imageService = resolvedCanvas?.items?.[0]?.items?.[0]?.body?.service?.id
if (!imageService) imageService = resolvedCanvas?.images?.[0]?.resource?.service?.["@id"]
if (!fullImage) {
throw new Error("Cannot Resolve Canvas Image", { "cause": "The Image is 404 or unresolvable." })
}
let imgx = resolvedCanvas?.items?.[0]?.items?.[0]?.body?.width
if (!imgx) imgx = resolvedCanvas?.images?.[0]?.resource?.width
let imgy = resolvedCanvas?.items?.[0]?.items?.[0]?.body?.height
if (!imgy) imgy = resolvedCanvas?.images?.[0]?.resource?.height
this.#imageDims = [imgx, imgy]
this.#canvasDims = [
resolvedCanvas?.width,
resolvedCanvas?.height
]
let imageInfo = {
type: "image",
url: fullImage
}
this.#canvasImageURL = fullImage
// Try to get the info.json. If we can't, continue with the simple imageInfo obj.
if (imageService) {
const lastchar = imageService[imageService.length - 1]
if (lastchar !== "/") imageService += "/"
const info = await fetch(imageService + "info.json").then(resp => resp.json()).catch(err => { return false })
if (info) imageInfo = info
}
else {
let resolvable = false
try {
resolvable = await this.validateImageUrl(fullImage)
}
catch (err) {
this.shadowRoot.innerHTML = `
<h3>Image Error</h3>
<p>The Image '${fullImage}' could not be loaded</p>
`
return
}
if (!resolvable) {
this.shadowRoot.innerHTML = `
<h3>Image Error</h3>
<p>The Image '${fullImage}' could not be loaded</p>
`
return
}
}
/**
* An instance of OpenSeaDragon with customization options that help our desired
* "draw new annotation", "edit existing drawn annotation", "delete drawn annotation" UX.
* The interface folder contains an /images/ folder with all the OpenSeaDragon icons.
* @see https://openseadragon.github.io/docs/OpenSeadragon.html#.Options for all options and their description.
*/
this.#osd = OpenSeadragon({
element: this.shadowRoot.getElementById('annotator-container'),
tileSources: imageInfo,
prefixUrl: "../interfaces/annotator/images/",
showFullPageControl:false,
gestureSettingsMouse: {
clickToZoom: false,
dblClickToZoom: true
},
gestureSettingsTouch: {
clickToZoom: false,
dblClickToZoom: true
},
gestureSettingsPen: {
clickToZoom: false,
dblClickToZoom: true
},
gestureSettingsUnknown: {
clickToZoom: false,
dblClickToZoom: true
}
})
// Link to transcribe if they have view permissions for it
if (CheckPermissions.checkViewAccess("LINE", "TEXT") || CheckPermissions.checkEditAccess("LINE", "TEXT")) {
let parsingRedirectButton = new OpenSeadragon.Button({
tooltip: "Go Transcribe",
srcRest: "../interfaces/annotator/images/transcribe.png",
srcGroup: "../interfaces/annotator/images/transcribe.png",
srcHover: "../interfaces/annotator/images/transcribe.png",
srcDown: "../interfaces/annotator/images/transcribe.png",
onClick: (e) => {
if (this.#resolvedAnnotationPage?.$isDirty) {
if (confirm("Stop identifying lines and go transcribe? Unsaved changes will be lost."))
location.href = `/transcribe?projectID=${TPEN.activeProject._id}&pageID=${this.#annotationPageID}`
}
else {
location.href = `/transcribe?projectID=${TPEN.activeProject._id}&pageID=${this.#annotationPageID}`
}
}
})
parsingRedirectButton.element.classList.add("transcribeLink")
this.#osd.addControl(parsingRedirectButton.element, { anchor: OpenSeadragon.ControlAnchor.TOP_LEFT })
}
/**
* An instance of an OpenSeaDragon Annotorious Annotation with customization options that help our desired
* "draw new column", "chop and merge lines", "delete lines" UX.
* @see https://annotorious.dev/api-reference/openseadragon-annotator/ for all the available methods of this annotator.
*/
this.#annotoriousInstance = AnnotoriousOSD.createOSDAnnotator(this.#osd, {
adapter: AnnotoriousOSD.W3CImageFormat(canvasID),
drawingEnabled: false,
drawingMode: "drag",
// https://annotorious.dev/api-reference/drawing-style/
style: {
fill: "#ff0000",
fillOpacity: 0.25
},
userSelectAction: "EDIT"
// EXAMPLE: Only allow me to edit my own annotations
// userSelectAction: (annotation) => {
// const isMe = annotation.target.creator?.id === 'my_id';
// return isMe ? 'EDIT' : 'SELECT';
// }
})
this.#annotoriousInstance.setUser(this.#userForAnnotorious)
// "polygon" is another available option
this.#annotoriousInstance.setDrawingTool("rectangle")
// This would change the color of drawn Annotations
/*
this.#annotoriousInstance.setStyle({
fill: '#00ff00',
fillOpacity: 0.25,
stroke: '#00ff00',
strokeOpacity: 1
}
*/
this.setInitialAnnotations()
this.listenTo(this)
}
/**
* Listeners on all available Annotorious events involving the annotations. See inline comments for details.
* Here we can catch events, then do TPEN things with the Annotations from those events.
* Lifecycle Events API is available at https://annotorious.dev/api-reference/events/
*
* @param annotator - An established instance of a AnnotoriousOSD.createOSDAnnotator
*/
listenTo(_this) {
const annotator = _this.#annotoriousInstance
/**
* Fired after a new annotation is created and available as a shape in the DOM.
* Make the page $isDirty so that it knows to save.
*/
annotator.on('createAnnotation', function(annotation) {
// console.log("CREATE ANNOTATION")
if (_this.#isDrawing) _this.#annotoriousInstance.cancelSelected()
_this.#annotoriousInstance.updateAnnotation(annotation)
_this.#resolvedAnnotationPage.$isDirty = true
})
/**
* Fired after an annotation is resized or moved in the DOM, and focus is removed.
* Make the page $isDirty so it knows to update.
* Note this does not fire on a programmatic annotoriousInstance.updateAnnotation() call.
*/
annotator.on('updateAnnotation', function(annotation) {
// console.log("UPDATE ANNOTATION")
_this.#annotoriousInstance.updateAnnotation(annotation)
_this.#resolvedAnnotationPage.$isDirty = true
})
/**
* Fired after a click event on a drawn, unselected Annotation.
* Supports Annotation removal. If the interface is not erasing then nothing special should happen.
*/
annotator.on('clickAnnotation', (originalAnnotation, originalEvent) => {
// console.log("Annotorious clickAnnotation")
if (!originalAnnotation) return
if (_this.#isErasing) {
const timeoutId = setTimeout(() => {
_this.#pendingTimeouts.delete(timeoutId)
// Timeout required in order to allow the click-and-focus native functionality to complete.
// Also stops the goofy UX for naturally slow clickers.
let c = confirm("Are you sure you want to remove this?")
if (c) {
_this.#annotoriousInstance.removeAnnotation(originalAnnotation)
_this.#resolvedAnnotationPage.$isDirty = true
} else {
_this.#annotoriousInstance.cancelSelected()
}
}, 500)
_this.#pendingTimeouts.add(timeoutId)
}
})
/**
* Fired after a new set of Annotations is selected by clicking unselected Annotations.
* It may be fired in tandem with clickAnnotation.
* Supports line editing. If the interface is not line editing then nothing special should happen.
*/
annotator.on('selectionChanged', (annotations) => {
let elem, cursorHandleElem
if (annotations && annotations.length) {
elem = this.#annotoriousInstance.viewer.element.querySelector(".a9s-annotation.selected")
cursorHandleElem = this.#annotoriousInstance.viewer.element.querySelector(".a9s-shape-handle")
} else {
_this.removeRuler()
return
}
if (_this.#isErasing) {
// Take over the cursor behavior b/c seeing the 'move' cursor is confusing
elem.style.cursor = "default"
cursorHandleElem.style.cursor = "default"
}
if (_this.#isLineEditing && elem) {
_this.applyCursorBehavior()
}
})
_this.onkeydown = function(evt) {
evt = evt || window.event
// Quit actions with escape key
if (evt.key === "Escape") {
evt.preventDefault()
const drawTool = _this.shadowRoot.getElementById("drawTool")
if (drawTool.checked) {
drawTool.checked = false
_this.stopDrawing()
}
const editTool = _this.shadowRoot.getElementById("editTool")
if (editTool.checked) {
editTool.checked = false
_this.stopLineEditing()
}
const eraseTool = _this.shadowRoot.getElementById("eraseTool")
if (eraseTool.checked) {
eraseTool.checked = false
_this.stopErasing()
}
_this.#annotoriousInstance.cancelSelected()
}
}
}
/**
* Format and pass along the Annotations from the provided AnnotationPage.
* Annotorious will render them on screen and introduce them to the UX flow.
*/
setInitialAnnotations() {
if (!this.#resolvedAnnotationPage) {
this.#annotoriousContainer.style.backgroundImage = "none"
return
}
let allAnnotations = JSON.parse(JSON.stringify(this.#resolvedAnnotationPage.items))
// Make sure Annotation targets and bodies are Annotorious friendly.
allAnnotations = this.formatAnnotations(allAnnotations)
// Convert the Annotation selectors so that they are relative to the Image dimensions
allAnnotations = this.convertSelectors(allAnnotations, true)
this.#annotoriousInstance.setAnnotations(allAnnotations, false)
this.#annotoriousContainer.style.backgroundImage = "none"
this.shadowRoot.getElementById("tools-container").style.display = "block"
this.shadowRoot.querySelector("#autoParseBtn").style.display = "block"
const pageSelector = this.shadowRoot.querySelector("tpen-page-selector")
if (pageSelector) {
pageSelector.style.display = "block"
}
if (CheckPermissions.checkEditAccess("PROJECT")) {
const manageProjectBtn = this.shadowRoot.querySelector("#projectManagementBtn")
manageProjectBtn.style.display = "block"
this.renderCleanup.onElement(manageProjectBtn, "click", (e) => document.location.href = `/project/manage?projectID=${TPEN.activeProject._id}`)
}
}
/**
* Format Annotation body and target properties so they are Annotorious friendly.
* Otherwise Annotorious will not draw them in the UI.
*
* @param annotations - An Array of Annotations that may need to be formatted
*
* @return the Array of Annotations formatted for Annotorious
*/
formatAnnotations(annotations) {
if (!annotations || annotations.length === 0) return annotations
return annotations.map(annotation => {
if (!annotation.hasOwnProperty("target") || !annotation.hasOwnProperty("body")) return annotation
if (typeof annotation.target === "string") {
// This is probably a simplified fragment selector like uri#xywh= and Annotorious will not process it.
const tarsel = annotation.target.split("#")
if (tarsel && tarsel.length === 2) {
if (!tarsel[1].includes("pixel:")) tarsel[1] = tarsel[1].replace("xywh=", "xywh=pixel:")
annotation.target = {
source: tarsel[0],
selector: {
conformsTo: "http://www.w3.org/TR/media-frags/",
type: "FragmentSelector",
value: tarsel[1]
}
}
}
}
if (!Array.isArray(annotation.body)) {
if (typeof annotation.body === "object") {
annotation.body = (Object.keys(annotation.body).length > 0) ? [annotation.body] : []
} else {
// This is a malformed Annotation body! What to do...
annotation.body = [annotation.body]
}
}
annotation.motivation ??= "transcribing"
return annotation
})
}
/**
* Adjust Annotation selectors as needed for communication between Annotorious and TPEN3.
* Annotorious naturally builds selector values relative to image dimensions.
* TPEN3 wants them relative to Canvas dimensions.
* When recieving Annotations to render convert the selectors so they are relative to the image and draw correctly.
* When saving Annotations convert the selectors so they are relative to the canvas and save correctly.
*
* @param annotations - An Array of Annotations whose selectors need converted
* @param bool - A switch for forwards or backwards conversion
*
* @return the Array of Annotations with their selectors converted
*/
convertSelectors(annotations, bool = false) {
// Don't need to convert if image and canvas dimensions are the same.
if (this.#imageDims[0] === this.#canvasDims[0] && this.#imageDims[1] === this.#canvasDims[1]) return annotations
if (!annotations || annotations.length === 0) return annotations
let orig_xywh, converted_xywh = []
let tar, sel = ""
return annotations.map(annotation => {
if (!annotation.target) return annotation
orig_xywh = annotation.target.selector.value.replace("xywh=pixel:", "").split(",")
if (bool) {
/**
* You are converting for Annotorious. Selectors need to be changed to be relative to the Image dimensions.
* This is so that they render correctly. TPEN3 selectors are relative to the Canvas dimensions.
* The target is in expanded Annotorious format. {source:"uri", selector:{value:"xywh="}}
*/
converted_xywh[0] = parseFloat((this.#imageDims[0] / this.#canvasDims[0]) * parseFloat(orig_xywh[0]))
converted_xywh[1] = parseFloat((this.#imageDims[1] / this.#canvasDims[1]) * parseFloat(orig_xywh[1]))
converted_xywh[2] = parseFloat((this.#imageDims[0] / this.#canvasDims[0]) * parseFloat(orig_xywh[2]))
converted_xywh[3] = parseFloat((this.#imageDims[1] / this.#canvasDims[1]) * parseFloat(orig_xywh[3]))
} else {
/**
* You are converting for TPEN3. Selectors need to be changed to be relative to the Canvas dimensions.
* This is so that they save correctly. Annotorious selectors are relative to the Image dimensions.
* The target is in expanded Annotorious format. {source:"uri", selector:{value:"xywh="}}
*/
converted_xywh[0] = parseFloat((this.#canvasDims[0] / this.#imageDims[0]) * parseFloat(orig_xywh[0]))
converted_xywh[1] = parseFloat((this.#canvasDims[1] / this.#imageDims[1]) * parseFloat(orig_xywh[1]))
converted_xywh[2] = parseFloat((this.#canvasDims[0] / this.#imageDims[0]) * parseFloat(orig_xywh[2]))
converted_xywh[3] = parseFloat((this.#canvasDims[1] / this.#imageDims[1]) * parseFloat(orig_xywh[3]))
}
sel = "xywh=pixel:" + converted_xywh.join(",")
annotation.target.selector.value = sel
return annotation
})
}
/**
* Internal conversions may have caused selectors that are non-integer values.
* The media frags spec notes that #xywh= values need to be integers.
* Convert any floats encountered by rounding to the nearest integer.
*
* @param annotations - An Array of Annotations whose selectors may need rounded.
*
* @return the Array of Annotations with their selectors rounded
*/
roundSelectors(annotations) {
if (!annotations) return
return annotations.map(annotation => {
if (!annotation.target) return annotation
let orig_xywh, rounded_xywh = []
//The target is in expanded Annotorious format. {source:"uri", selector:{value:"xywh="}}
orig_xywh = annotation.target.selector.value.replace("xywh=pixel:", "").split(",")
rounded_xywh[0] = Math.round(parseFloat(orig_xywh[0]))
rounded_xywh[1] = Math.round(parseFloat(orig_xywh[1]))
rounded_xywh[2] = Math.round(parseFloat(orig_xywh[2]))
rounded_xywh[3] = Math.round(parseFloat(orig_xywh[3]))
const sel = "xywh=pixel:" + rounded_xywh.join(",")
annotation.target.selector.value = sel
return annotation
})
}
/**
* Annotorious causes some Annotation data fodder that we need to clean up.
* It will add keys and give them the value: undefined. We want to remove those keys.
* Note that it will add those keys to the Annotation object as well as the embedded body object.
*