File size: 27,725 Bytes
120961d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef87b45
 
 
 
 
120961d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef87b45
 
 
 
 
120961d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33d310c
f679561
120961d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616a634
 
 
120961d
616a634
120961d
17a4757
3f13f99
17a4757
dd8cf60
3f13f99
18786c3
 
 
 
46ba573
 
 
18786c3
 
 
 
 
 
 
 
ee1bf83
120961d
4103075
ef87b45
0c8b702
ef87b45
 
616a634
 
 
ef87b45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68e4081
ee1bf83
68e4081
ef87b45
 
1994341
ea0c18b
 
52faf4e
 
 
b8354e0
1994341
 
52faf4e
1994341
52faf4e
ee1bf83
1994341
 
 
 
 
 
6337456
1994341
6337456
 
 
 
1994341
6337456
1994341
 
 
 
 
 
 
 
 
 
 
 
52faf4e
1a8952c
 
52faf4e
73c7524
1a8952c
 
5c7fb2c
1a8952c
f47f15b
1994341
f47f15b
 
1994341
52faf4e
 
e0c3771
1994341
1a8952c
67fa927
1a8952c
 
 
52faf4e
f47f15b
1a8952c
1994341
1a8952c
f05fd66
1a8952c
 
 
 
 
52faf4e
1994341
 
 
f47f15b
d47c6d0
1994341
f47f15b
1994341
 
 
 
 
 
 
 
 
1a8952c
1994341
1a8952c
 
 
1994341
 
fd2f80a
 
 
 
1a8952c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5676dee
1a8952c
5676dee
1a8952c
 
 
 
5b7f310
1a8952c
 
 
fd2f80a
 
 
 
 
1a8952c
 
 
 
 
fd2f80a
 
1994341
e0c3771
75c56b5
a91d53f
75c56b5
 
 
e0c3771
75c56b5
ea0c18b
ef87b45
4103075
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
/*

© 2023 Samuel Bradshaw
https://github.com/samuelbradshaw/transcript-tracer-js

*/


// Global state variables
var ttIsInitialized = false;
var ttTranscripts;
var ttMediaPlayers;
var ttActivePlayer;
var ttLinkedDataByMediaUrl = {};

// Configuration variables (see README.md)
var ttBlockSelector = null;
var ttPhraseSelector = null;
var ttAlignmentFuzziness = 0;
var ttTimeOffset = 0;
var ttAutoScroll = null;
var ttClickable = false;


// Prepare transcripts and media players
function loadTranscriptTracer(options=null) {
  if (document.readyState == 'loading') {
    // Wait for document to load
    document.addEventListener('DOMContentLoaded', function() {
      loadTranscriptTracer(options);
    });
    return;
  }
  
  // Save user-provided options to configuration variables
  if (options) {
    if ('blockSelector' in options) ttBlockSelector = options.blockSelector;
    if ('phraseSelector' in options) ttPhraseSelector = options.phraseSelector;
    if ('alignmentFuzziness' in options) ttAlignmentFuzziness = options.alignmentFuzziness;
    if ('timeOffset' in options) ttTimeOffset = options.timeOffset;
    if ('autoScroll' in options) ttAutoScroll = options.autoScroll;
    if ('clickable' in options) ttClickable = options.clickable;
  }
  
  // Reset Transcript Tracer to prevent unexpected behavior if loadTranscriptTracer() is called more than once
  if (ttIsInitialized) {
    if (ttTranscripts) for (const transcript of ttTranscripts) {
      unlinkTranscript(transcript);
      transcript.dataset.ttTranscript = '';
    }
    ttTranscripts = null;
    ttMediaPlayers = null;
    ttActivePlayer = null;
    ttLinkedDataByMediaUrl = {};
    document.querySelectorAll('.tt-word, .tt-whitespace').forEach(element => {
      element.outerHTML = element.innerHTML;
    });
  }
  
  // Set a few global state variables
  ttIsInitialized = true;
  ttTranscripts = document.getElementsByClassName('tt-transcript');
  ttMediaPlayers = document.querySelectorAll('audio, video');

  // Prepare transcript for alignment by adding spans and classes
  for (let t = 0; t < ttTranscripts.length; t++) {
    var transcript = ttTranscripts[t];
    // Skip transcript if it's not linked to any media files
    if (!transcript.dataset.ttMediaUrls) continue;
  
    transcript.dataset.ttTranscript = t;
  
    // Loop through text nodes to add spans (tt-word, tt-whitespace)
    // Method of iterating text nodes thanks to https://stackoverflow.com/a/34700627/1349044
    var iter = document.createNodeIterator(transcript, NodeFilter.SHOW_TEXT);
    var textNode;
    while (textNode = iter.nextNode()) {
      const text = textNode.textContent;
      if (text.replace(/\s/g, '').length != 0) {
        var spannedText = '<span class="tt-word">' + text.replace(/(\s+)/g, '</span><span class="tt-whitespace">$1</span><span class="tt-word">') + '</span>';
        spannedText = spannedText.replaceAll('<span class="tt-word"></span>', '');
        
        // Replace text node with spanned text
        const template = document.createElement('template');
        template.innerHTML = spannedText;
        textNode.parentNode.insertBefore(template.content, textNode);
        textNode.parentNode.removeChild(textNode);
      }
    }
  }
  
  for (const mediaPlayer of ttMediaPlayers) {
    // Link related transcript(s)
    linkTranscripts(mediaPlayer);
    
    // Add event listener to media player
    mediaPlayer.addEventListener('play', function(e) {
      if (ttActivePlayer != e.currentTarget) {
        if (ttActivePlayer) {
          ttActivePlayer.pause();
          ttActivePlayer.removeEventListener('timeupdate', ttTimeUpdate);
        }
        ttActivePlayer = e.currentTarget;
        if (ttCurrentTranscript) clearHighlightedWords(ttCurrentTranscript);
        if (ttCurrentEvent) ttCurrentEvent = null;
      }
      ttActivePlayer.addEventListener('timeupdate', ttTimeUpdate);
      var currentTranscript = ttTranscripts[ttLinkedDataByMediaUrl[ttActivePlayer.dataset.ttLinkedMediaUrl].transcriptIndex];
      currentTranscript.dataset.ttCurrentMediaUrl = ttActivePlayer.dataset.ttLinkedMediaUrl;
    });
    mediaPlayer.addEventListener('ended', function(e) {
      if (ttCurrentTranscript) clearHighlightedWords(ttCurrentTranscript);
      if (ttCurrentEvent) ttCurrentEvent = null;
    });
  }
}


// Link media player to relevant transcripts
function linkTranscripts(mediaPlayer) {
  var trackElement = mediaPlayer.querySelector('track[kind="metadata"]')

  var mediaPlayerSourceUrls = [];
  var mediaPlayerSrc = mediaPlayer.getAttribute('src');
  var mediaPlayerSourceElements = mediaPlayer.querySelectorAll('source');
  if (mediaPlayerSrc) mediaPlayerSourceUrls.push(mediaPlayerSrc);
  if (mediaPlayerSourceElements) for (const s of mediaPlayerSourceElements) mediaPlayerSourceUrls.push(s.src);
  
  // If there's nothing to link, return
  if (!trackElement || !trackElement.getAttribute('src') || mediaPlayerSourceUrls.length == 0) return;
  
  // Fetch WebVTT content and link related transcripts
  for (const transcript of ttTranscripts) {    
    for (const mediaUrl of mediaPlayerSourceUrls) {
      if (transcript.dataset.ttMediaUrls.includes(mediaUrl)) {
        mediaPlayer.dataset.ttLinkedMediaUrl = mediaUrl;
        unlinkTranscript(transcript);
        fetch(trackElement.src)
          .then(r => r.text())
          .then(vttContent => linkTranscript(mediaPlayer, vttContent, transcript));
        break;
      }
    }
  }

  function linkTranscript(mediaPlayer, vttContent, transcript) {
    var wordTimings = parseVttToWordTimings(vttContent);
    transcript.dataset.ttCurrentMediaUrl = mediaPlayer.dataset.ttLinkedMediaUrl;
    
    function normalizedWord(word) {
      // Convert to lowercase, normalize, and remove anything that's not a letter or number
      return word.toLowerCase().normalize('NFD').replace(/[^\p{L}\p{N}]/gu, '');
    }
    
    // Add metadata to block and phrase containers (if ttBlockSelector and ttPhraseSelector are defined)
    var blockContainers = ttBlockSelector ? transcript.querySelectorAll(ttBlockSelector) : [];
    for (let c = 0; c < blockContainers.length; c++) blockContainers[c].dataset.ttBlock = c;
    var phraseContainers = ttPhraseSelector ? transcript.querySelectorAll(ttPhraseSelector) : [];
    for (let c = 0; c < phraseContainers.length; c++) phraseContainers[c].dataset.ttPhrase = c;
    
    // Add metadata to each word span, and build timed events list
    var timedEvents = [];
    var wordTimingsIndex = 0;
    var wordSpans = transcript.getElementsByClassName('tt-word');
    for (let s = 0; s < wordSpans.length; s++) {
      var span = wordSpans[s];
    
      // Find the next word timing object that matches the current span's text            
      var initialWordTimingsIndex = wordTimingsIndex;
      var maxFuzzyWordTimingsIndex = Math.min(wordTimingsIndex + ttAlignmentFuzziness, wordTimings.length - 1);
      while (normalizedWord(span.innerText) != normalizedWord(wordTimings[wordTimingsIndex].text) && wordTimingsIndex <= maxFuzzyWordTimingsIndex) {
        wordTimingsIndex += 1;
      }
      if (normalizedWord(span.innerText) != normalizedWord(wordTimings[wordTimingsIndex].text)) {
        // Could not find matching word within the fuzziness range
        wordTimingsIndex = initialWordTimingsIndex;
        continue;
      }
      
      // Get the block, phrase, and word index
      blockIndex = ttBlockSelector ? (span.closest(ttBlockSelector)?.dataset?.ttBlock ?? null) : wordTimings[wordTimingsIndex].blockIndex;
      phraseIndex = ttPhraseSelector ? (span.closest(ttPhraseSelector)?.dataset?.ttPhrase ?? null) : wordTimings[wordTimingsIndex].phraseIndex;
      wordIndex = wordTimings[wordTimingsIndex].wordIndex;
      
      // Add block, phrase, and word index as metadata on the span
      span.dataset.ttBlock = blockIndex;
      span.dataset.ttPhrase = phraseIndex;
      span.dataset.ttWord = wordIndex;

      // Add timed event to timed events list
      if (timedEvents.length != 0 && wordTimings[wordTimingsIndex].startSeconds == timedEvents[timedEvents.length-1].seconds) {
        timedEvents[timedEvents.length-1].currentWordIndexes.push(wordIndex);
      } else {
        timedEvents.push({
          'seconds': wordTimings[wordTimingsIndex].startSeconds,
          'currentWordIndexes': [wordIndex],
          'phraseIndex': phraseIndex,
          'blockIndex': blockIndex,
        });
      }
    
      wordTimingsIndex += 1;
    }

    // For a given element, find the first parent element containing relevant children
    function findRelevantParent(startingElement, endingElement, childSelector, relevantChildSelector) {
      var currentElement = startingElement;
      while (currentElement && currentElement != endingElement) {
        var currentElement = currentElement.parentElement;
        var children = currentElement.querySelectorAll(childSelector);
        var relevantChildren = document.querySelectorAll(relevantChildSelector);
        if (children.length == relevantChildren.length) {
          // Relevant parent found
          return currentElement;
        } else if (children.length > relevantChildren.length) {
          // Failed to find a relevant parent
          break;
        }
      }
      return null;
    }
    
    // Add metadata to block and phrase containers (if ttBlockSelector and ttPhraseSelector aren't defined)
    if (!ttBlockSelector) {
      var count = wordTimings[wordTimings.length-1].blockIndex + 1;
      for (let c = 0; c < count; c++) {
        var startingElement = document.querySelector(`[data-tt-block="${c}"]`);
        var blockContainer = findRelevantParent(startingElement, transcript, '[data-tt-word]', `[data-tt-word][data-tt-block="${c}"]`);
        if (blockContainer) blockContainer.dataset.ttBlock = c;
      }
    }
    if (!ttPhraseSelector) {
      var count = wordTimings[wordTimings.length-1].phraseIndex + 1;
      for (let c = 0; c < count; c++) {
        var startingElement = document.querySelector(`[data-tt-phrase="${c}"]`);
        var phraseContainer = findRelevantParent(startingElement, transcript, '[data-tt-word]', `[data-tt-word][data-tt-phrase="${c}"]`);
        if (phraseContainer) phraseContainer.dataset.ttPhrase = c;
      }
    }
    
    // Sort timed events list by time
    timedEvents = timedEvents.sort(function(a, b) { 
      return a.seconds - b.seconds;
    })
    
    // Add reference data to ttLinkedDataByMediaUrl
    var transcriptIndex = parseInt(transcript.dataset.ttTranscript);
    ttLinkedDataByMediaUrl[mediaPlayer.dataset.ttLinkedMediaUrl] = {
      'transcriptIndex': transcriptIndex,
      'wordTimings': wordTimings,
      'timedEvents': timedEvents,
      'mediaElement': mediaPlayer,
      'textTrackData': mediaPlayer.textTracks[0],
    }

    // Add click listeners to words
    if (ttClickable) {
      for (const word of document.querySelectorAll('.tt-word')) {
        word.addEventListener('click', handleWordClick);
      }

      for (const word of document.querySelectorAll('.tt-word')) {
        word.addEventListener('dblclick', handleWordDBClick);
      }

    }
  }
}


// Unlink transcript from previous VTT
function unlinkTranscript(transcript) {
  clearHighlightedWords(transcript);
  
  var ttLinkedElements = transcript.querySelectorAll('[data-tt-word]');
  for (const element of ttLinkedElements) {
    element.dataset.ttWord = '';
    element.dataset.ttPhrase = '';
    element.dataset.ttBlock = '';
  }
  
  var mediaUrl = transcript.dataset.ttCurrentMediaUrl;
  if (mediaUrl) {
    delete ttLinkedDataByMediaUrl[mediaUrl]
    transcript.dataset.ttCurrentMediaUrl = '';
  }
  
  for (const word of document.querySelectorAll('.tt-word')) {
    word.removeEventListener('click', handleWordClick);
  }

  for (const word of document.querySelectorAll('.tt-word')) {
    word.removeEventListener('dblclick', handleWordDBClick);
  }

}


// Convert WebVTT into a wordTimings list
function parseVttToWordTimings(vttContent) {
  var wordTimings = [];
  
  // Split WebVTT at each double line break
  var vttSegments = vttContent.split(/\r?\n\r?\n/);
  if (vttSegments.length == 0 || !vttSegments[0].startsWith('WEBVTT')) {
    console.error('Error: Invalid VTT file. See https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API');
    return;
  }
  
  // Loop through each segment of the WebVTT
  // WebVTT documentation: https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API
  var cueWordCounter = 0;
  var cuePhraseCounter = 0;
  var cueBlockCounter = 0;
  for (let s = 0; s < vttSegments.length; s++) {
    var segment = vttSegments[s];
    
    // Skip segment if it's not a cue
    if (segment.startsWith('WEBVTT') || /^STYLE\s/.test(segment) || /^NOTE\s/.test(segment)) continue;
  
    // Convert VTT timestamps to seconds
    function convertVttTimestampToSeconds(vttTimestamp) {
      var parts = vttTimestamp.trim().split(':');
      var seconds = 0;
      if (parts.length == 3) { // 00:02:01.003
        seconds = (parseFloat(parts[0]) * 60 * 60) + (parseFloat(parts[1]) * 60) + parseFloat(parts[2])
      } else { // 02:01.003
        seconds = (parseFloat(parts[0]) * 60) + parseFloat(parts[1])
      }
      return seconds;
    }
    
    // Parse cue
    var cueIdentifier = cuePayload = '';
    var cueStartSeconds = cueEndSeconds = null;
    var segmentLines = segment.split(/\r?\n/);
    for (const line of segmentLines) {
      if (line.includes('-->')) {
        // Cue timings (single line)
        cueStartSeconds = wordStartSeconds = convertVttTimestampToSeconds(line.split('-->')[0].trim());
        cueEndSeconds = convertVttTimestampToSeconds(line.split('-->')[1].trim());
      } else if (cueStartSeconds == null) {
        // Cue identifier (optional)
        cueIdentifier += line;
      } else {
        // Cue payload (may be multiple lines)
        var adjustedLine = line.replace(/(<\d*:?\d+:\d+\.\d+>)\s/g, ' $1').replace(/(<\d*:?\d+:\d+\.\d+>)(<\d*:?\d+:\d+\.\d+>)/g, '$1 $2');
        cuePayload += adjustedLine;
        var cueWords = adjustedLine.split(/\s/)
        for (let word of cueWords) {
          var matches = Array.from(word.matchAll(/(^<\d*:?\d+:\d+\.\d+>)?(.+$)/g));
          if (matches.length == 1 && matches[0][1] != null) {
            match = matches[0];
            wordStartSeconds = convertVttTimestampToSeconds(match[1].replace('<', '').replace('>', ''));
            word = match[2];
          }
          
          // Push word to wordTimings list
          if (word) {
            wordTimings.push({
              'text': word,
              'startSeconds': wordStartSeconds,
              'endSeconds': cueEndSeconds,
              'wordIndex': cueWordCounter,
              'phraseIndex': cuePhraseCounter,
              'blockIndex': cueBlockCounter,
            })
            cueWordCounter += 1;
          }
        }
        cuePhraseCounter += 1;
      }
    }
    cueBlockCounter += 1;
  }
  
  return wordTimings;
}


// Respond to timeupdate event (progress as the audio or video is playing)
var ttCurrentTranscript = null;
var ttPreviousEvent = null;
var ttCurrentEvent = null;
var ttNextEvent = null;
function ttTimeUpdate(e) {
  // If the current player isn't active or doesn't have data, return
  if (!ttActivePlayer || e.currentTarget != ttActivePlayer || !(ttActivePlayer.dataset.ttLinkedMediaUrl in ttLinkedDataByMediaUrl)) return;
  
  var adjustedCurrentTime = ttActivePlayer.currentTime + (ttTimeOffset * -1);
  var ttData = ttLinkedDataByMediaUrl[ttActivePlayer.dataset.ttLinkedMediaUrl];
  
  // Make sure the correct transcript is selected
  if (!ttCurrentTranscript || ttCurrentTranscript.dataset.ttTranscript != ttData.transcriptIndex) {
    ttCurrentTranscript = document.querySelector(`[data-tt-transcript="${ttData.transcriptIndex}"]`);
  }
  
  // If before the first event, after the last event, or within the range of the current event, return
  if (ttCurrentEvent && (ttCurrentEvent.seconds < ttData.timedEvents[0].seconds || ttCurrentEvent.seconds > ttData.timedEvents[ttData.timedEvents.length-1].seconds)) return;
  if (ttCurrentEvent && ttNextEvent && ttCurrentEvent.seconds <= adjustedCurrentTime && ttNextEvent.seconds > adjustedCurrentTime) return;
  
  // Clear words that were highlighted from the previous event
  clearHighlightedWords(ttCurrentTranscript);
  
  // Add highlights for the current event
  for (let t = 0; t < ttData.timedEvents.length; t++) {
    if (ttData.timedEvents[t].seconds <= adjustedCurrentTime && (!ttData.timedEvents[t+1] || adjustedCurrentTime < ttData.timedEvents[t+1]?.seconds)) {
      
      ttPreviousEvent = ttData.timedEvents[t-1] || null;
      ttCurrentEvent = ttData.timedEvents[t];
      ttNextEvent = ttData.timedEvents[t+1] || null;
      
      // Mark blocks
      if (ttCurrentEvent.blockIndex != null) {
        var blockElements = ttCurrentTranscript.querySelectorAll(`[data-tt-block="${ttCurrentEvent.blockIndex}"]`);
        for (let b = 0; b < blockElements.length; b++) blockElements[b].classList.add((b==0 && !blockElements[b].classList.contains('tt-word')) ? 'tt-current-block-container' : 'tt-current-block');
      }
      
      // Mark phrases
      if (ttCurrentEvent.phraseIndex != null) {
        var phraseElements = ttCurrentTranscript.querySelectorAll(`[data-tt-phrase="${ttCurrentEvent.phraseIndex}"]`);
        for (let p = 0; p < phraseElements.length; p++) phraseElements[p].classList.add((p==0 && !phraseElements[p].classList.contains('tt-word')) ? 'tt-current-phrase-container' : 'tt-current-phrase');
      }
      
      // Mark words
      if (ttCurrentEvent.currentWordIndexes.length > 0) {
        for (const wordIndex of ttCurrentEvent.currentWordIndexes) {
          var wordElements = ttCurrentTranscript.querySelectorAll(`[data-tt-word="${wordIndex}"]`);
          for (const wordElement of wordElements) wordElement.classList.add('tt-current-word');
        }
        for (const wordElement of ttCurrentTranscript.getElementsByClassName('tt-word')) {
          if (wordElement.classList.contains('tt-current-word')) break;
          wordElement.classList.add('tt-previous-word');
        }
      }
      
      // Auto-scroll to the highlighted text
      if (ttAutoScroll && !ttActivePlayer.paused && ttActivePlayer.duration != 0) {
        var scrollOptions = { behavior: 'smooth', block: 'nearest', inline: 'nearest' }
        if (ttAutoScroll == 'block' && ttPreviousEvent?.blockIndex != ttCurrentEvent.blockIndex) {
          document.querySelector('.tt-current-block-container').scrollIntoView(scrollOptions);
        } else if (ttAutoScroll == 'phrase' && ttPreviousEvent?.phraseIndex != ttCurrentEvent.phraseIndex) {
          document.querySelector('.tt-current-phrase-container').scrollIntoView(scrollOptions);
        } else if (ttAutoScroll == 'word') {
          document.querySelector('.tt-current-word').scrollIntoView(scrollOptions);
        }
      }
      
      break;
    }
  }
}


// Clear highlighted words in transcript
function clearHighlightedWords(transcript) {
  if (!transcript) return;
  var ttHighlightedElements = transcript.querySelectorAll('[class*="tt-current"], [class*="tt-previous"]');
  for (const element of ttHighlightedElements) {
    element.classList.remove('tt-current-block', 'tt-current-block-container', 'tt-current-phrase', 'tt-current-phrase-container', 'tt-current-word', 'tt-previous-word');
  }
}


// Handle when a word in the transcript with an event listener is clicked
function handleWordClick(e) {
  var wordElement = e.currentTarget;
  var wordIndex = wordElement.dataset.ttWord;

  if (wordElement.className == "tt-whitespace" || wordIndex === undefined) return;   
  
  var transcript = wordElement.closest('.tt-transcript');
  var mediaUrl = transcript.dataset.ttCurrentMediaUrl;  
  var startSeconds = ttLinkedDataByMediaUrl[mediaUrl].wordTimings[wordIndex].startSeconds

  ttLinkedDataByMediaUrl[mediaUrl].mediaElement.currentTime = startSeconds;

  var ttData = ttLinkedDataByMediaUrl[mediaUrl];
  
  // Make sure the correct transcript is selected
  if (!ttCurrentTranscript || ttCurrentTranscript.dataset.ttTranscript != ttData.transcriptIndex) {
    ttCurrentTranscript = document.querySelector(`[data-tt-transcript="${ttData.transcriptIndex}"]`);
  }

  // Clear words that were highlighted from the previous event
  clearHighlightedWords(ttCurrentTranscript);
  
  // Mark words
  wordElement.classList.add('tt-current-word');

  for (const wordElement of ttCurrentTranscript.getElementsByClassName('tt-word')) {
    if (wordElement.classList.contains('tt-current-word')) break;
    wordElement.classList.add('tt-previous-word');
  }
  
}

// Handle when a word in the transcript with an event listener is clicked
function handleWordDBClick(e) {
  var wordElement = e.currentTarget;
  var wordIndex = wordElement.dataset.ttWord;

  if (wordElement.className == "tt-whitespace" || wordIndex === undefined) return;  
  
  var transcript = wordElement.closest('.tt-transcript');
  var mediaUrl = transcript.dataset.ttCurrentMediaUrl;
  var startSeconds = ttLinkedDataByMediaUrl[mediaUrl].wordTimings[wordIndex].startSeconds

  ttLinkedDataByMediaUrl[mediaUrl].mediaElement.currentTime = startSeconds;

  var ttData = ttLinkedDataByMediaUrl[mediaUrl];
  
  // Make sure the correct transcript is selected
  if (!ttCurrentTranscript || ttCurrentTranscript.dataset.ttTranscript != ttData.transcriptIndex) {
    ttCurrentTranscript = document.querySelector(`[data-tt-transcript="${ttData.transcriptIndex}"]`);
  }

  // Clear words that were highlighted from the previous event
  clearHighlightedWords(ttCurrentTranscript);
  
  // Mark words
  wordElement.classList.add('tt-current-word');

  for (const wordElement of ttCurrentTranscript.getElementsByClassName('tt-word')) {
    if (wordElement.classList.contains('tt-current-word')) break;
    wordElement.classList.add('tt-previous-word');
  }

  // pause
  if (ttActivePlayer != null) {
    ttActivePlayer.pause()
  }
}


function handleSelection() {

  // Get selection
  var selection = document.getSelection();
  if (selection.type != "Range") return;  

  // ====================================================================================================
  
  // These can be obtained simply with `startWordElement`
  var transcript = selection.baseNode.parentNode.closest('.tt-transcript');
  var mediaUrl = transcript.dataset.ttCurrentMediaUrl;
  
  // ====================================================================================================
  
  var dict = {};
  var nodes = [];
  var listIndex = -1; 
  for (const x of transcript.children) {
    for (const wordElement of x.children) {
      listIndex = listIndex + 1;
      // Note: manually add extra information
      wordElement.listIndex = listIndex;
      nodes.push(wordElement);
      if (wordElement.className != "tt-whitespace") {
        wordIndex = wordElement.dataset.ttWord;
        // TODO: We no longer need this after we inject the list index information into `wordElement`.
        dict[wordIndex] = listIndex;
      }
    } 
  }
  console.log(nodes);
  console.log(dict);

  // ====================================================================================================
  
  var startNode = selection.baseNode;
  var startWordElement = startNode.parentNode;
  
  // Used for highlight  
  var startWordElementForHighlight = startWordElement
  
  while (startWordElementForHighlight.className == "tt-whitespace") {
    var index = startWordElementForHighlight.listIndex + 1;
    if (index >= nodes.length) break;
    startWordElementForHighlight = nodes[index];
  }
  
  // This could be `undefined`!
  var startWordIndexForHighlight = startWordElementForHighlight.dataset.ttWord;
  // This is always defined.
  var startWordListIndexForHighlight = startWordElementForHighlight.listIndex;
  
  // Used for computing the start seconds
  var startWordElementForTime = startWordElementForHighlight;  

  // No time specified for some words --> we compute the starting time with the first element where the time information is provided.
  // (This could go beyond the selected religon!)
  while (startWordElementForTime.className == "tt-whitespace" || (startWordElementForTime.dataset.ttWord === undefined)) {
    var index = startWordElementForTime.listIndex + 1;
    if (index >= nodes.length) break;
    startWordElementForTime = nodes[index];
  }

  // This could still be `undefined`.
  var startWordIndexForTime = startWordElementForTime.dataset.ttWord;
  // Let's get the `listIndex`.
  var startWordListIndexForTime = startWordElementForTime.listIndex;

  var startSeconds = null;
  if (startWordIndexForTime !== undefined) {
    startSeconds = ttLinkedDataByMediaUrl[mediaUrl].wordTimings[startWordIndexForTime].startSeconds;
  }

  console.log(startWordElement);
  console.log(startWordElementForHighlight);
  console.log(startWordIndexForHighlight);
  console.log(startWordListIndexForHighlight);
  console.log(startWordElementForTime);
  console.log(startWordIndexForTime);
  console.log(startWordListIndexForTime);
  console.log(startSeconds);

  // ====================================================================================================

  var endNode = selection.extentNode;
  var endWordElement = endNode.parentNode;
  
  // Used for highlight
  var endWordElementForHighlight = endWordElement;

  while (endWordElementForHighlight.className == "tt-whitespace") {
    var index = endWordElementForHighlight.listIndex - 1;
    if (index < 0) break;
    endWordElementForHighlight = nodes[index];
  }

  // This could be `undefined`!
  var endWordIndexForHighlight = endWordElementForHighlight.dataset.ttWord;
  // This is always defined.
  var endWordListIndexForHighlight = endWordElementForHighlight.listIndex;

  // Used for computing the end seconds
  var endWordElementForTime = endWordElementForHighlight;

  // Forward to the next element (if possible)
  if ((endWordElementForTime.listIndex + 1) < nodes.length) {
    endWordElementForTime = nodes[endWordElementForTime.listIndex + 1];  
  }
    
  while (endWordElementForTime.className == "tt-whitespace" || (endWordElementForTime.dataset.ttWord === undefined)) {
    var index = endWordElementForTime.listIndex + 1;
    if (index >= nodes.length) break;
    endWordElementForTime = nodes[index];  
  }

  // This could still be `undefined`.
  var endWordIndexForTime = endWordElementForTime.dataset.ttWord;
  // Let's get the `listIndex`.
  var endWordListIndexForTime = endWordElementForTime.listIndex;

  var endSeconds = null;  
  if (endWordIndexForTime !== undefined) {
    endSeconds = ttLinkedDataByMediaUrl[mediaUrl].wordTimings[endWordIndexForTime].startSeconds;
    if (endWordElement.listIndex == nodes.length - 1) {
      endSeconds = ttLinkedDataByMediaUrl[mediaUrl].wordTimings[endWordIndexForTime].endSeconds;
    }
  }
  
  console.log(endWordElement);
  console.log(endWordElementForHighlight);
  console.log(endWordIndexForHighlight);
  console.log(endWordListIndexForHighlight);
  console.log(endWordElementForTime);
  console.log(endWordIndexForTime);
  console.log(endWordListIndexForTime);
  console.log(endSeconds);
  
  return
  
  // ====================================================================================================  
  // Mark selection


  // for (const wordElement of ttCurrentTranscript.getElementsByClassName('tt-word')) {
  //   if (wordElement.classList.contains('tt-current-word')) break;
  //   wordElement.classList.add('tt-previous-word');
  // }

}

loadTranscriptTracer({ blockSelector: null, phraseSelector: null, alignmentFuzziness: 0, timeOffset: 0, autoScroll: "word", clickable: true})