-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathannotate.ts
More file actions
1277 lines (1110 loc) · 52.7 KB
/
annotate.ts
File metadata and controls
1277 lines (1110 loc) · 52.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 $ from 'jquery';
import { get_next_item, get_i_item, log_response } from './connector';
import {
notify,
ErrorSpan,
CharData,
redrawProgress,
createSpanToolbox,
updateToolboxPosition,
Validation,
validateResponse,
DataGoodbye,
DataForm,
DataFormItem,
ProtocolInfo,
SliderConfig,
isMediaContent,
contentToCharSpans,
isSpanComplete,
computeWordBoundaries,
detectTextDirection,
debounce,
getErrorSpansForModel,
DocumentResponse,
DataPayload,
DataPayloadItem,
MQM_ERROR_CATEGORIES,
MQM_SEVERITIES,
} from './utils';
// Check if frozen mode is enabled (view-only, no annotations)
const searchParams = new URLSearchParams(window.location.search)
const frozenMode = searchParams.has("frozen")
const debugMode = searchParams.has("debug")
const state = {
response_log: [] as Array<DocumentResponse>,
action_log: [] as Array<any>,
validations: [] as Array<Record<string, Validation> | undefined>,
payload_items: [] as Array<DataPayloadItem>, // Store current payload items to check skippable
output_blocks: [] as Array<JQuery<HTMLElement>>,
settings: {
show_alignment: true,
word_level: false,
},
has_unsaved_work: false,
skip_mode: false,
// Protocol settings for check_unlock
protocol_error_spans: false,
protocol_error_categories: false,
mqm_categories: MQM_ERROR_CATEGORIES,
mqm_severities: MQM_SEVERITIES as string[],
}
// Prevent accidental refresh/navigation when there is ongoing work
window.addEventListener('beforeunload', (event) => {
if (state.has_unsaved_work) {
event.preventDefault()
}
})
$("#toggle_differences").on("change", function () {
if ($(this).is(":checked")) {
$(".difference").removeClass("hidden")
} else {
$(".difference").addClass("hidden")
}
})
function check_unlock() {
// In frozen mode, always keep the button disabled
if (frozenMode) {
$("#button_next").attr("disabled", "disabled")
$("#button_next").val("Next 🔒")
$("#button_skip").hide()
return
}
// Check if all error spans are complete (have required severity and category based on protocol)
if (state.protocol_error_spans || state.protocol_error_categories) {
for (const doc_responses of state.response_log) {
for (const r of Object.values(doc_responses)) {
for (const span of r.error_spans) {
if (!isSpanComplete(span, state.protocol_error_categories)) {
$("#button_next").attr("disabled", "disabled")
$("#button_next").val("Incomplete 🚧")
return
}
}
}
}
}
let incomplete_items_i = Array<number>()
// Check if all scores are set
state.response_log.forEach((doc_responses, i) =>
Object.values(doc_responses).forEach(r => {
if (r.sliders) {
// Custom sliders mode: all sliders must be non-null (no score required)
// Note: when sliders is {} (empty, from sliders: []), Object.values returns []
// and every() returns true (vacuous truth), allowing immediate progression
if (!Object.values(r.sliders).every(val => val !== null)) {
incomplete_items_i.push(i)
}
} else {
// Single score mode: the score must be set
if (r.score == null) {
incomplete_items_i.push(i)
}
}
})
)
if (incomplete_items_i.length > 0) {
$("#button_next").attr("disabled", "disabled")
$("#button_next").val("Incomplete 🚧")
// Check if all incomplete items are skippable
if (debugMode || incomplete_items_i.every(item_i => state.payload_items[item_i].skippable)) {
$("#button_skip").show()
} else {
$("#button_skip").hide()
}
return
}
// All items complete - enable Next button and hide Skip button
$("#button_next").removeAttr("disabled")
$("#button_next").val("Next ✅")
$("#button_skip").hide()
}
/**
* Cleanup function to remove toolboxes and handlers from previous item
* Must be called before loading a new item to prevent memory leaks and stale UI
*/
function cleanupPreviousItem(): void {
// Remove all toolboxes appended to body
$(".span_toolbox_parent").remove()
// Remove resize handlers for toolbox positioning (use namespace to avoid removing other handlers)
$(window).off('resize.toolbox')
}
function _textfield_button_html(item_i: number, model: string, mode: string | null | undefined): string {
if (!mode) return "" // null or undefined - don't show textfield
if (mode === "hidden") {
return `
<button class="textfield_toggle" id="textfield_toggle_${item_i}_${model}">✏️</button>
`
}
return ""
}
function _textfield_html(item_i: number, model: string, mode: string | null | undefined): string {
if (!mode) return "" // null or undefined - don't show textfield
if (mode === "hidden") {
return `
<textarea class="output_textfield" id="textfield_${item_i}_${model}" style="display: none;" placeholder="Type here..."></textarea>
`
} else if (mode === "visible" || mode === "prefilled") {
return `
<textarea class="output_textfield" id="textfield_${item_i}_${model}" placeholder="Type here..."></textarea>
`
}
return ""
}
function _slider_html(item_i: number, model: string, sliders?: SliderConfig[]): string {
// If sliders is explicitly an empty array, show no sliders
if (sliders && sliders.length === 0) {
return '<div class="output_response"></div>'
}
// If no custom sliders specified (undefined), use default single slider
if (!sliders) {
return `
<div class="output_response">
<input type="range" min="0" max="100" value="-1" id="response_${item_i}_${model}">
<span class="slider_label">❓/100</span>
</div>
`
}
// Generate multiple sliders with labels (no Score slider when custom sliders are defined)
let html = '<div class="output_response">'
// Add custom sliders
for (const slider of sliders) {
html += `
<div class="slider_container">
<label class="slider_name">${slider.name}</label>
<input type="range" min="${slider.min}" max="${slider.max}" step="${slider.step}" value="${slider.min - 1}" id="response_${item_i}_${model}_${slider.name}" data-slider="${slider.name}">
<span class="slider_label" data-slider="${slider.name}">❓/${slider.max}</span>
</div>
`
}
html += '</div>'
return html
}
function createOutputBlock(item: DataPayloadItem, item_i: number, info: ProtocolInfo): JQuery<HTMLElement> {
// character-level stuff won't work on media tags
let no_src_char = !item.src || isMediaContent(item.src)
let no_ref_char = !item.ref || isMediaContent(item.ref)
// Detect text direction for source and reference
let src_dir = item.src && !no_src_char ? detectTextDirection(item.src) : 'ltr'
let ref_dir = item.ref && !no_ref_char ? detectTextDirection(item.ref) : 'ltr'
// Build character spans for source and reference
let src_chars = ""
if (item.src) {
src_chars = no_src_char ? item.src : contentToCharSpans(item.src, "src_char")
}
let ref_chars = ""
if (item.ref) {
ref_chars = no_ref_char ? item.ref : contentToCharSpans(item.ref, "ref_char")
}
// Build source and reference boxes - only if they exist
let srcRefBoxes = ""
if (item.src) {
let src_style = src_dir === 'rtl' ? ' style="direction: rtl;"' : ''
srcRefBoxes += `<div class="output_src"${src_style}>${src_chars}</div>`
}
if (item.ref) {
let ref_style = ref_dir === 'rtl' ? ' style="direction: rtl;"' : ''
srcRefBoxes += `<div class="output_ref"${ref_style}>${ref_chars}</div>`
}
let output_block = $(`
<div class="output_block">
<span class="instructions_message"></span>
<div class="output_item">
${srcRefBoxes}
</div>
</div>
`)
if (item.instructions) {
output_block.find(".instructions_message").html(item.instructions)
}
// Add each model's output
for (const [model, tgt] of Object.entries(item.tgt)) {
let no_tgt_char = isMediaContent(tgt)
let tgt_dir = !no_tgt_char ? detectTextDirection(tgt) : 'ltr'
let tgt_chars = no_tgt_char ? tgt : (contentToCharSpans(tgt, "tgt_char") + (state.protocol_error_spans ? ' <span class="tgt_char char_missing">[missing]</span>' : ""))
let tgt_style = tgt_dir === 'rtl' ? ' style="direction: rtl;"' : ''
let candidate_block = $(`
<div class="output_candidate" data-candidate="${model}" data-model="${model}">
<div class="output_tgt"${tgt_style}>${tgt_chars}</div>
${_slider_html(item_i, model, info.sliders)}
</div>
`)
// Add model name at the top of the candidate block if enabled
if (info.show_model_names) {
let model_name_div = $('<div class="model_name"></div>').text(model)
candidate_block.prepend(model_name_div)
}
candidate_block.find(".output_response").prepend(_textfield_button_html(item_i, model, info.textfield))
candidate_block.append(_textfield_html(item_i, model, info.textfield))
output_block.find(".output_item").append(candidate_block)
}
return output_block
}
function setupCandidateInteractions(
candidate_block: JQuery<HTMLElement>,
item_i: number,
model: string,
tgt: string,
response: DataPayload,
src_chars_els: HTMLElement[],
ref_chars_els: HTMLElement[],
output_block: JQuery<HTMLElement>
) {
let no_tgt_char = isMediaContent(tgt)
let item = response.payload[item_i]
// Setup character-level interactions for this model's output
// Compute word boundaries for the target text
let _tgt_chars_els = candidate_block.find(".tgt_char").toArray()
let tgt_word_boundaries = no_tgt_char ? [] : computeWordBoundaries(_tgt_chars_els.map(el => $(el).text()))
let tgt_chars_objs: Array<CharData> = no_tgt_char ? [] : _tgt_chars_els.map((el, idx) => ({
"el": $(el),
"toolbox": null,
"error_span": null,
"word_start": idx < tgt_word_boundaries.length ? tgt_word_boundaries[idx][0] : idx,
"word_end": idx < tgt_word_boundaries.length ? tgt_word_boundaries[idx][1] : idx,
}))
let state_i: null | number = null
let missing_i = state.protocol_error_spans ? tgt_chars_objs.findIndex(obj => obj.el.hasClass("char_missing")) : -1
if (!no_tgt_char) {
tgt_chars_objs.forEach((obj, i) => {
let is_missing = (i == missing_i)
// leaving target character
$(obj.el).on("mouseleave", function () {
$(".src_char").removeClass("highlighted")
$(".ref_char").removeClass("highlighted")
$(".tgt_char").removeClass("highlighted")
$(".tgt_char").removeClass("highlighted_active")
// highlight corresponding toolbox if error severity is set
if (obj.error_span != null && obj.error_span.severity != null && (!state.protocol_error_categories || (obj.error_span.category != null && obj.error_span.category?.includes("/")))) {
tgt_chars_objs[i].toolbox?.css("display", "none")
}
})
// entering target character
$(obj.el).on("mouseenter", function () {
$(".src_char").removeClass("highlighted")
$(".ref_char").removeClass("highlighted")
$(".tgt_char").removeClass("highlighted")
if (state.settings.show_alignment && !is_missing) {
// Highlight corresponding characters in source
if (src_chars_els.length > 0) {
let src_i = Math.round(i / tgt_chars_objs.length * src_chars_els.length)
for (let j = Math.max(0, src_i - 5); j <= Math.min(src_chars_els.length - 1, src_i + 5); j++) {
$(src_chars_els[j]).addClass("highlighted")
}
}
// Highlight corresponding characters in reference
if (ref_chars_els.length > 0) {
let ref_i = Math.round(i / tgt_chars_objs.length * ref_chars_els.length)
for (let j = Math.max(0, ref_i - 5); j <= Math.min(ref_chars_els.length - 1, ref_i + 5); j++) {
$(ref_chars_els[j]).addClass("highlighted")
}
}
// Highlight corresponding characters in all other candidates
let relative_pos = i / tgt_chars_objs.length
// if not our candidate
output_block.find(".output_candidate").each(function () {
if ($(this).attr("data-candidate")! == model) {
return
}
let other_tgt_chars = $(this).find(".tgt_char")
let other_i = Math.round(relative_pos * other_tgt_chars.length)
for (let j = Math.max(0, other_i - 5); j <= Math.min(other_tgt_chars.length - 1, other_i + 5); j++) {
other_tgt_chars.eq(j).addClass("highlighted")
}
})
}
if (state_i != null && !is_missing) {
// In word-level mode, expand selection preview to word boundaries
let preview_left = Math.min(state_i, i)
let preview_right = Math.max(state_i, i)
if (state.settings.word_level && state_i != missing_i) {
preview_left = tgt_chars_objs[preview_left].word_start
preview_right = tgt_chars_objs[preview_right].word_end
}
for (let j = preview_left; j <= preview_right; j++) {
$(tgt_chars_objs[j].el).addClass("highlighted")
}
} else if (state.settings.word_level && !is_missing && state_i == null) {
// Highlight current word on hover when in word-level mode (no active selection)
for (let j = obj.word_start; j <= obj.word_end; j++) {
$(tgt_chars_objs[j].el).addClass("highlighted")
}
}
// check if inside a span
if (tgt_chars_objs[i].error_span != null) {
let span = tgt_chars_objs[i].error_span!
// highlight the whole span if we're in one
for (let j = span.start_i; j <= span.end_i; j++) {
$(tgt_chars_objs[j].el).addClass("highlighted_active")
}
tgt_chars_objs[span.start_i].toolbox?.css("display", "block")
}
})
// add spans and toolbox only in case the protocol asks for it
if (state.protocol_error_spans || state.protocol_error_categories) {
$(obj.el).on("click", function () {
// In frozen mode, do not allow creating new error spans
if (frozenMode) return
if (is_missing) {
state_i = missing_i
}
if (state_i != null) {
// check if we're not overlapping
let left_i = Math.min(state_i, i)
let right_i = Math.max(state_i, i)
// Expand to word boundaries if word-level mode is enabled
if (state.settings.word_level && !is_missing && state_i != missing_i) {
left_i = tgt_chars_objs[left_i].word_start
right_i = tgt_chars_objs[right_i].word_end
}
state_i = null
$(".src_char").removeClass("highlighted")
candidate_block.find(".tgt_char").removeClass("highlighted")
let error_span: ErrorSpan = {
"start_i": left_i,
"end_i": right_i,
"category": null,
"severity": null,
}
if (state.response_log[item_i][model].error_spans.some(span => {
return (
(left_i <= span.start_i && right_i >= span.start_i) ||
(left_i <= span.end_i && right_i >= span.end_i)
)
})) {
notify("Cannot create overlapping error spans")
return
}
// create toolbox
let toolbox = createSpanToolbox(
state.protocol_error_categories,
error_span,
tgt_chars_objs,
left_i,
right_i,
() => {
// onDelete callback
state.response_log[item_i][model].error_spans = state.response_log[item_i][model].error_spans.filter(span => span != error_span)
state.action_log.push({ "time": Date.now() / 1000, "action": "delete_span", "index": item_i, "model": model, "start_i": left_i, "end_i": right_i })
state.has_unsaved_work = true
},
frozenMode,
state.mqm_categories,
state.mqm_severities
)
$("body").append(toolbox)
check_unlock()
// handle hover on toolbox
toolbox.on("mouseenter focusin contextmenu", function (e) {
if (e.type === "contextmenu") e.preventDefault();
toolbox.css("display", "block")
check_unlock()
})
// handle hover on toolbox
toolbox.on("mouseleave focusout", function () {
// hide if severity is set for ESA or both severity and category are set for MQM
if (error_span.severity != null && (!state.protocol_error_categories || (error_span.category != null && error_span.category?.includes("/")))) {
toolbox.css("display", "none")
check_unlock()
}
})
// set up callback to reposition toolbox on resize
$(window).on('resize.toolbox', () => updateToolboxPosition(toolbox, $(tgt_chars_objs[left_i].el)))
updateToolboxPosition(toolbox, $(tgt_chars_objs[left_i].el))
// store error span
state.response_log[item_i][model].error_spans.push(error_span)
state.action_log.push({ "time": Date.now() / 1000, "action": "create_span", "index": item_i, "model": model, "start_i": left_i, "end_i": right_i })
state.has_unsaved_work = true
for (let j = left_i; j <= right_i; j++) {
$(tgt_chars_objs[j].el).addClass("error_unknown")
tgt_chars_objs[j].toolbox = toolbox
tgt_chars_objs[j].error_span = error_span
}
} else {
// check if we are in existing span
if (state.response_log[item_i][model].error_spans.some(span => i >= span.start_i && i <= span.end_i)) {
notify("Cannot create overlapping error spans")
$(".src_char").removeClass("highlighted")
candidate_block.find(".tgt_char").removeClass("highlighted")
return
}
state_i = i
}
})
}
})
}
// Load error spans - use payload_existing if available, otherwise use item.error_spans
const existingErrorSpans = response.payload_existing?.annotation[item_i]?.[model]?.error_spans
const candidateSpans = existingErrorSpans || getErrorSpansForModel(item.error_spans, model)
if (!no_tgt_char && (state.protocol_error_spans || state.protocol_error_categories) && candidateSpans.length > 0) {
// Only reset if loading from payload_existing (to avoid duplicating pre-filled spans)
if (existingErrorSpans) {
state.response_log[item_i][model].error_spans = []
}
for (const prefilled of candidateSpans) {
const left_i = prefilled.start_i, right_i = prefilled.end_i
if (left_i < 0 || right_i >= tgt_chars_objs.length || left_i > right_i) continue
let error_span: ErrorSpan = { ...prefilled }
state.response_log[item_i][model].error_spans.push(error_span)
let toolbox = createSpanToolbox(state.protocol_error_categories, error_span, tgt_chars_objs, left_i, right_i, () => {
state.response_log[item_i][model].error_spans = state.response_log[item_i][model].error_spans.filter(s => s != error_span)
state.action_log.push({ "time": Date.now() / 1000, "action": "delete_span", "index": item_i, "model": model, "start_i": left_i, "end_i": right_i })
state.has_unsaved_work = true
}, frozenMode, state.mqm_categories, state.mqm_severities)
$("body").append(toolbox)
toolbox.on("mouseenter", () => { toolbox.css("display", "block"); check_unlock() })
toolbox.on("mouseleave", () => {
if (error_span.severity != null && (!state.protocol_error_categories || (error_span.category != null && error_span.category?.includes("/")))) {
toolbox.css("display", "none"); check_unlock()
}
})
$(window).on('resize.toolbox', () => updateToolboxPosition(toolbox, $(tgt_chars_objs[left_i].el)))
for (let j = left_i; j <= right_i; j++) {
$(tgt_chars_objs[j].el).addClass(error_span.severity ? `error_${error_span.severity}` : "error_unknown")
tgt_chars_objs[j].toolbox = toolbox
tgt_chars_objs[j].error_span = error_span
}
if (error_span.severity != null && (!state.protocol_error_categories || (error_span.category != null && error_span.category?.includes("/")))) {
toolbox.css("display", "none")
}
}
}
// Setup slider(s) for this model
const hasCustomSliders = response.info.sliders && response.info.sliders.length > 0
const hasNoSliders = response.info.sliders !== undefined && response.info.sliders.length === 0
if (hasCustomSliders) {
// Multiple sliders mode (no Score slider when custom sliders are defined)
const allSliders = response.info.sliders!
for (const sliderConfig of allSliders) {
const sliderName = sliderConfig.name
const sliderMax = sliderConfig.max
let slider = candidate_block.find(`input[data-slider="${CSS.escape(sliderName)}"]`)
let label = candidate_block.find(`.slider_label[data-slider="${CSS.escape(sliderName)}"]`)
slider.on("click input", function () {
// In frozen mode, do not allow changing scores
if (frozenMode) return
let val = parseInt((<HTMLInputElement>this).value)
label.text(`${val}/${sliderMax}`)
// Store in sliders field
if (state.response_log[item_i][model].sliders![sliderName] == null) {
state.response_log[item_i][model].sliders![sliderName] = val
state.has_unsaved_work = true
check_unlock()
state.action_log.push({ "time": Date.now() / 1000, "action": sliderName, "index": item_i, "model": model, "value": val })
}
})
slider.on("change", function () {
// In frozen mode, do not allow changing scores
if (frozenMode) return
let val = parseInt((<HTMLInputElement>this).value)
label.text(`${val}/${sliderMax}`)
// Store in sliders field
state.response_log[item_i][model].sliders![sliderName] = val
state.action_log.push({ "time": Date.now() / 1000, "action": sliderName, "index": item_i, "model": model, "value": val })
state.has_unsaved_work = true
check_unlock()
})
// Disable slider in frozen mode
if (frozenMode) {
slider.prop("disabled", true)
}
// Pre-fill score from payload_existing if available
let existingScore: number | null = null
existingScore = response.payload_existing?.annotation[item_i]?.[model]?.sliders?.[sliderName] ?? null
if (existingScore != null) {
slider.val(existingScore)
label.text(`${existingScore}/${sliderMax}`)
state.response_log[item_i][model].sliders![sliderName] = existingScore
}
}
} else if (!hasNoSliders) {
// Single slider mode (default Score slider)
let slider = candidate_block.find("input[type='range']")
let label = candidate_block.find(".slider_label")
slider.on("click input", function () {
// In frozen mode, do not allow changing scores
if (frozenMode) return
let val = parseInt((<HTMLInputElement>this).value)
label.text(`${val}/100`)
if (state.response_log[item_i][model].score == null) {
state.response_log[item_i][model].score = val
state.has_unsaved_work = true
check_unlock()
state.action_log.push({ "time": Date.now() / 1000, "action": "score", "index": item_i, "model": model, "value": val })
}
})
slider.on("change", function () {
// In frozen mode, do not allow changing scores
if (frozenMode) return
let val = parseInt((<HTMLInputElement>this).value)
label.text(`${val}/100`)
state.response_log[item_i][model].score = val
state.has_unsaved_work = true
check_unlock()
// push only for change which happens just once
state.action_log.push({ "time": Date.now() / 1000, "action": "score", "index": item_i, "model": model, "value": val })
})
// Disable slider in frozen mode
if (frozenMode) {
slider.prop("disabled", true)
}
// Pre-fill score from payload_existing if available
const existingScore = response.payload_existing?.annotation[item_i]?.[model]?.score
if (existingScore != null) {
slider.val(existingScore)
label.text(`${existingScore}/100`)
state.response_log[item_i][model].score = existingScore
}
}
// Setup textfield if enabled
if (response.info.textfield) {
const textfield = candidate_block.find(`#textfield_${item_i}_${CSS.escape(model)}`)
const toggle = candidate_block.find(`#textfield_toggle_${item_i}_${CSS.escape(model)}`)
// Pre-fill with model output if mode is "prefilled"
// Note: tgt is from trusted campaign data, jQuery .val() safely escapes any content
if (response.info.textfield === "prefilled") {
textfield.val(tgt)
state.response_log[item_i][model].textfield = tgt
}
// Handle toggle button for "hidden" mode
if (response.info.textfield === "hidden") {
toggle.on("click", function () {
if (textfield.is(":visible")) {
textfield.hide()
} else {
textfield.show()
}
})
}
// Handle textfield input with debouncing to reduce log volume
const logTextfieldInput = debounce(() => {
const val = textfield.val() as string
state.action_log.push({ "time": Date.now() / 1000, "action": "textfield", "index": item_i, "model": model, "value": val })
}, 500)
textfield.on("input", function () {
// In frozen mode, do not allow changing textfield
if (frozenMode) return
let val = (<HTMLTextAreaElement>this).value
state.response_log[item_i][model].textfield = val
state.has_unsaved_work = true
// Log with debounce to avoid excessive logging during typing
logTextfieldInput()
})
// Disable textfield in frozen mode
if (frozenMode) {
textfield.prop("disabled", true)
}
// Pre-fill textfield from payload_existing if available (overrides prefilled mode)
const existingTextfield = response.payload_existing?.annotation[item_i]?.[model]?.textfield
if (existingTextfield != null) {
textfield.val(existingTextfield)
state.response_log[item_i][model].textfield = existingTextfield
}
}
}
async function display_next_payload(response: DataPayload) {
// Cleanup toolboxes and handlers from previous item
cleanupPreviousItem()
redrawProgress(response.info.item_i, response.progress_welcome, response.progress, navigate_to_item)
$("#time").text(`Time: ${Math.round(response.time / 60)}m`)
let data = response.payload
// Initialize response log - use payload_existing if available
if (response.payload_existing) {
state.response_log = response.payload_existing.annotation.map(docResponses => {
const result: DocumentResponse = {}
for (const [model, r] of Object.entries(docResponses)) {
result[model] = {
"score": r.score,
"sliders": r.sliders ? { ...r.sliders } : undefined,
"error_spans": r.error_spans ? [...r.error_spans] : [],
"textfield": r.textfield ?? null,
}
}
return result
})
// Reload comment if it exists
if (response.payload_existing.comment) {
$("#settings_comment").val(response.payload_existing.comment)
} else {
$("#settings_comment").val("")
}
} else {
state.response_log = data.map(item => {
const result: DocumentResponse = {}
for (const model of Object.keys(item.tgt)) {
// Check if custom sliders are defined (including empty array)
const hasCustomSliders = response.info.sliders !== undefined
result[model] = {
"score": null,
"sliders": hasCustomSliders ? {} : undefined,
"error_spans": [],
"textfield": null,
}
// Initialize all custom slider values to null
if (response.info.sliders && response.info.sliders.length > 0) {
for (const slider of response.info.sliders!) {
result[model].sliders![slider.name] = null
}
}
}
return result
})
$("#settings_comment").val("")
}
state.validations = data.map(item => item.validation)
state.payload_items = data // Store payload items to check skippable
state.output_blocks = []
state.action_log = [{ "time": Date.now() / 1000, "action": "load" }]
state.has_unsaved_work = false
state.skip_mode = false
state.protocol_error_spans = response.info.protocol == "ESA" || response.info.protocol == "MQM"
state.protocol_error_categories = response.info.protocol == "MQM"
// Use custom MQM categories if provided, otherwise use default
if (response.info.mqm_categories) {
// adding blanks
state.mqm_categories = {
"": [],
...Object.fromEntries(Object.entries(response.info.mqm_categories).map(([key, value]) => [key, ["", ...value]]))
}
} else {
state.mqm_categories = MQM_ERROR_CATEGORIES
}
// Use custom MQM severities if provided, otherwise use default
state.mqm_severities = response.info.mqm_severities ?? MQM_SEVERITIES
// Set global instructions from payload
if (response.info.instructions) {
$("#instructions_global").html(response.info.instructions)
} else {
$("#instructions_global").html("")
}
$("#output_div").html("")
for (let item_i = 0; item_i < data.length; item_i++) {
let item = data[item_i]
// character-level stuff won't work on media tags
let no_src_char = !item.src || isMediaContent(item.src)
let no_ref_char = !item.ref || isMediaContent(item.ref)
let output_block = createOutputBlock(item, item_i, response.info)
let src_chars_els = no_src_char || !item.src ? [] : output_block.find(".src_char").toArray()
let ref_chars_els = no_ref_char || !item.ref ? [] : output_block.find(".ref_char").toArray()
for (const [model, tgt] of Object.entries(item.tgt)) {
let candidate_block = output_block.find(`.output_candidate[data-model='${CSS.escape(model)}']`)
setupCandidateInteractions(candidate_block, item_i, model, tgt, response, src_chars_els, ref_chars_els, output_block)
}
// Source character hover effects
if (!no_src_char && item.src) {
src_chars_els.forEach((obj, i) => {
$(obj).on("mouseleave", function () {
$(".src_char").removeClass("highlighted")
$(".ref_char").removeClass("highlighted")
$(".tgt_char").removeClass("highlighted")
})
$(obj).on("mouseenter", function () {
$(".ref_char").removeClass("highlighted")
$(".tgt_char").removeClass("highlighted")
if (state.settings.show_alignment) {
// Highlight corresponding characters in reference
if (ref_chars_els.length > 0) {
let ref_i = Math.round(i / src_chars_els.length * ref_chars_els.length)
for (let j = Math.max(0, ref_i - 5); j <= Math.min(ref_chars_els.length - 1, ref_i + 5); j++) {
$(ref_chars_els[j]).addClass("highlighted")
}
}
// Highlight corresponding characters in all candidates
output_block.find(".output_candidate").each(function () {
let tgt_chars = $(this).find(".tgt_char")
let tgt_i = Math.round(i / src_chars_els.length * tgt_chars.length)
for (let j = Math.max(0, tgt_i - 5); j <= Math.min(tgt_chars.length - 1, tgt_i + 5); j++) {
tgt_chars.eq(j).addClass("highlighted")
}
})
}
})
})
}
// Reference character hover effects
if (!no_ref_char && item.ref) {
ref_chars_els.forEach((obj, i) => {
$(obj).on("mouseleave", function () {
$(".src_char").removeClass("highlighted")
$(".ref_char").removeClass("highlighted")
$(".tgt_char").removeClass("highlighted")
})
$(obj).on("mouseenter", function () {
$(".src_char").removeClass("highlighted")
$(".tgt_char").removeClass("highlighted")
if (state.settings.show_alignment) {
// Highlight corresponding characters in source
if (src_chars_els.length > 0) {
let src_i = Math.round(i / ref_chars_els.length * src_chars_els.length)
for (let j = Math.max(0, src_i - 5); j <= Math.min(src_chars_els.length - 1, src_i + 5); j++) {
$(src_chars_els[j]).addClass("highlighted")
}
}
// Highlight corresponding characters in all candidates
output_block.find(".output_candidate").each(function () {
let tgt_chars = $(this).find(".tgt_char")
let tgt_i = Math.round(i / ref_chars_els.length * tgt_chars.length)
for (let j = Math.max(0, tgt_i - 5); j <= Math.min(tgt_chars.length - 1, tgt_i + 5); j++) {
tgt_chars.eq(j).addClass("highlighted")
}
})
}
})
})
}
$("#output_div").append(output_block)
state.output_blocks.push(output_block)
}
// trigger once to reposition toolboxes
$(window).trigger('resize.toolbox')
check_unlock()
// Attach event listeners to multimedia elements for logging (no overhead if no audio/video present)
// Note: Elements are removed when output_div is cleared, so no explicit cleanup needed
$("#output_div audio, #output_div video").each(function () {
const element = this as HTMLMediaElement
const $parent = $(element).closest('.output_src, .output_ref, .output_tgt')
const context = (
$parent.hasClass('output_src') ? 'src' :
$parent.hasClass('output_ref') ? 'ref' :
$parent.closest('.output_candidate').attr('data-model') || 'unknown'
)
$(element).on('play', () => {
state.action_log.push({ "time": Date.now() / 1000, "action": "media_play", "media_src": element.src, "model": context, "media_time": element.currentTime })
})
$(element).on('pause', () => {
state.action_log.push({ "time": Date.now() / 1000, "action": "media_pause", "media_src": element.src, "model": context, "media_time": element.currentTime })
})
$(element).on('seeked', () => {
state.action_log.push({ "time": Date.now() / 1000, "action": "media_seek", "media_src": element.src, "model": context, "media_time": element.currentTime })
})
})
$("#button_next").off("click")
$("#button_next").on("click", async function () {
// Perform validation unless in skip tutorial mode
let validationResult: boolean[] | null = null
if (!state.skip_mode) {
validationResult = await performValidation()
if (validationResult == null) {
// validation failed, don't proceed
return
}
}
// disable while communicating with the server
$("#button_next").attr("disabled", "disabled")
$("#button_next").val("Next 📶")
state.action_log.push({ "time": Date.now() / 1000, "action": "submit" + (state.skip_mode ? "_skip" : "") })
// Build payload
let payload_local: any = {
"annotation": state.response_log,
"actions": state.action_log,
"item": response.payload,
}
if (!state.skip_mode && validationResult && validationResult.length > 0) {
payload_local["validations"] = validationResult
}
// Include comment if provided
const comment = $("#settings_comment").val() as string
if (comment && comment.trim() !== "") {
payload_local["comment"] = comment.trim()
// Clear comment after submission
$("#settings_comment").val("")
}
let outcome = await log_response(payload_local, response.info.item_i)
if (outcome == null || outcome == false) {
notify("Error submitting the annotations. Please try again.")
$("#button_next").removeAttr("disabled")
check_unlock()
return
}
await display_next_item()
})
}
/**
* Display goodbye screen when all annotations are done
*/
function display_goodbye(response: DataGoodbye, navigate_to_item: (i: number | string) => void): void {
// Use instructions_goodbye if provided, otherwise use default message
// Note: instructions_goodbye may contain arbitrary HTML including variables that are replaced server-side
$("#output_div").html(`
<div class='white-box' style='width: max-content'>
<h2>🎉 All done, thank you for your annotations!</h2>
${response.instructions_goodbye}
<br>
<br>
</div>
`)
redrawProgress(null, response.progress_welcome, response.progress, navigate_to_item)
$("#time").text(`Time: ${Math.round(response.time / 60)}m`)
$("#button_next").prop("disabled", true)
$("#button_next").val("Next 💯")
}
// Display form for collecting user information
function display_form(response: DataForm) {
// Clear previous content and state
$("#output_div").empty()
state.response_log = []
state.validations = []
state.output_blocks = []
state.action_log = [{ "time": Date.now() / 1000, "action": "load" }]
redrawProgress(response.info.item_i, response.progress_welcome, response.progress, navigate_to_item)
$("#time").text(`Time: ${Math.round(response.time / 60)}m`)
// Display instructions if present
if (response.info.instructions) {
$("#instructions").html(response.info.instructions)
$("#instructions").show()
} else {
$("#instructions").hide()
}
// Create form container
const formContainer = $('<div class="form-container"></div>')
// Store form responses (using Array.from for clarity)
const formResponses: Array<string | number | null> = Array.from({ length: response.payload.length }, () => null)
// Pre-fill if there are existing responses
if (response.payload_existing?.annotation) {
response.payload_existing.annotation.forEach((value, i) => {
formResponses[i] = value
})
}
// Create form fields
response.payload.forEach((item, index) => {
const fieldDiv = $('<div class="form-field"></div>')
// Add the text/label