-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathvts.js
More file actions
1025 lines (907 loc) · 35.2 KB
/
vts.js
File metadata and controls
1025 lines (907 loc) · 35.2 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
/* Video Transcript Sorter (VTS)
* Used to synchronize time stamps from WebVTT resources
* so they appear in the proper sequence within an auto-generated interactive transcript
*/
import $ from 'jquery';
function addVtsFunctions(AblePlayer) {
AblePlayer.prototype.injectVTS = function() {
var thisObj, $heading, $instructions, $p1, $p2, $ul, $li1, $li2, $li3,
$fieldset, $legend, i, $radioDiv, radioId, $label, $radio, $saveButton, $savedTable;
thisObj = this;
if ( null !== document.getElementById( 'able-vts' ) ) {
// Are they qualifying tracks?
if (this.vtsTracks.length) {
// Build an array of unique languages
this.langs = [];
this.getAllLangs(this.vtsTracks);
// Set the default VTS language
this.vtsLang = this.lang;
// Inject a heading
let heading = this.translate( 'vtsHeading', 'Video Transcript Sorter' );
$heading = $('<h2>').text( heading ); // TODO: intelligently assign proper heading level
$('#able-vts').append($heading);
// Inject an empty div for writing messages
this.$vtsAlert = $('<div>',{
'id': 'able-vts-alert',
'aria-live': 'polite',
'aria-atomic': 'true'
})
$('#able-vts').append(this.$vtsAlert);
// Inject instructions (TODO: Localize)
$instructions = $('<div>',{
'id': 'able-vts-instructions'
});
$p1 = $('<p>').text( this.translate( 'vtsInstructions1', 'Use the Video Transcript Sorter to modify text tracks:' ) );
$ul = $('<ul>');
$li1 = $('<li>').text( this.translate( 'vtsInstructions2', 'Reorder chapters, descriptions, captions, and/or subtitles so they appear in the proper sequence in Able Player\'s auto-generated transcript.' ) );
$li2 = $('<li>').text( this.translate( 'vtsInstructions3', 'Modify content or start/end times (all are directly editable within the table).' ) );
$li3 = $('<li>').text( this.translate( 'vtsInstructions4', 'Add new content, such as chapters or descriptions.' ) );
$p2 = $('<p>').text( this.translate( 'vtsInstructions5', 'After editing, click the "Save Changes" button to generate new content for all relevant timed text files. The new text can be copied and pasted into new WebVTT files.' ) );
$ul.append($li1,$li2,$li3);
$instructions.append($p1,$ul,$p2);
$('#able-vts').append($instructions);
// Inject a fieldset with radio buttons for each language
$fieldset = $('<fieldset>');
$legend = $('<legend>').text( this.translate( 'vtsSelectLanguage', 'Select a language' ) );
$fieldset.append($legend);
let $fieldWrapper = $( '<div class="vts-lang-selector"></div>' );
for (i in this.langs) {
radioId = 'vts-lang-radio-' + this.langs[i];
$radioDiv = $('<div>',{
// uncomment the following if label is native name
// 'lang': this.langs[i]
});
$radio = $('<input>', {
'type': 'radio',
'name': 'vts-lang',
'id': radioId,
'value': this.langs[i]
}).on('click',function() {
thisObj.vtsLang = $(this).val();
thisObj.showVtsAlert('Loading ' + thisObj.getLanguageName(thisObj.vtsLang) + ' tracks');
thisObj.injectVtsTable('update',thisObj.vtsLang);
});
if (this.langs[i] == this.lang) {
// this is the default language.
$radio.prop('checked',true);
}
$label = $('<label>', {
'for': radioId
// Two options for label:
// getLanguageName() - with second parameter "local" would return native name, otherwise returns English;
// TODO: if using this be sure to add lang attr to <div> (see above)
}).text(this.getLanguageName(this.langs[i]));
$radioDiv.append($radio,$label);
$fieldWrapper.append($radioDiv);
}
$fieldset.append( $fieldWrapper );
$('#able-vts').append($fieldset);
let vtsSave = this.translate( 'vtsSave', 'Generate new .vtt content' );
// Inject a button to generate new files.
$saveButton = $('<button>',{
'type': 'button',
'id': 'able-vts-save',
'value': 'save'
}).text( vtsSave );
$('#able-vts').append($saveButton);
// Inject a table with one row for each cue in the default language
this.injectVtsTable('add',this.vtsLang);
// TODO: Add drag/drop functionality for mousers
// Add event listeners for contenteditable cells
var kindOptions, beforeEditing, editedCell, editedContent;
kindOptions = ['captions','chapters','descriptions','subtitles'];
$('td[contenteditable="true"]').on('focus',function() {
beforeEditing = $(this).text();
}).on('blur',function() {
if (beforeEditing != $(this).text()) {
editedCell = $(this).index();
editedContent = $(this).text();
if (editedCell === 1) {
// do some simple spelling auto-correct
if ($.inArray(editedContent,kindOptions) === -1) {
// whatever user typed is not a valid kind
// assume they correctly typed the first character
if (editedContent.substring(0,1) === 's') {
$(this).text('subtitles');
} else if (editedContent.substring(0,1) === 'd') {
$(this).text('descriptions');
} else if (editedContent.substring(0,2) === 'ch') {
$(this).text('chapters');
} else {
// whatever else they types, assume 'captions'
$(this).text('captions');
}
}
} else if (editedCell === 2 || editedCell === 3) {
// start or end time
// ensure proper formatting (with 3 decimal places)
$(this).text(thisObj.formatTimestamp(editedContent));
}
}
}).on('keydown',function(e) {
// don't allow keystrokes to trigger Able Player (or other) functions
// while user is editing
e.stopPropagation();
});
// handle click on the Save button
$('#able-vts-save').on('click',function(e) {
e.stopPropagation();
if ($(this).attr('value') == 'save') {
// replace table with WebVTT output in textarea fields (for copying/pasting)
$(this).attr('value','cancel').text( thisObj.translate( 'vtsReturn', 'Return to Editor' ) );
$savedTable = $('#able-vts table');
$('#able-vts-instructions').hide();
$('#able-vts > fieldset').hide();
$('#able-vts table').remove();
$('#able-vts-icon-credit').remove();
thisObj.parseVtsOutput($savedTable);
} else {
// cancel saving, and restore the table using edited content
$(this).attr('value','save').text( vtsSave );
$('#able-vts-output').remove();
$('#able-vts-instructions').show();
$('#able-vts > fieldset').show();
$('#able-vts').append($savedTable);
$('#able-vts').append(thisObj.getIconCredit());
thisObj.showVtsAlert( thisObj.translate( 'vtsCancel', 'Cancelling saving. Any edits you made have been restored in the VTS table.' ) );
}
});
}
}
};
AblePlayer.prototype.setupVtsTracks = function(kind, lang, trackDesc, label, src, contents) {
// TODO: Add support for trackDesc
// (to destinguish between tracks for the decribed vs non-described versions)
var srcFile, vtsCues;
srcFile = this.getFilenameFromPath(src);
vtsCues = this.parseVtsTracks(contents);
this.vtsTracks.push({
'kind': kind,
'language': lang,
'label': label,
'srcFile': srcFile,
'cues': vtsCues
});
};
AblePlayer.prototype.getFilenameFromPath = function(path) {
var lastSlash;
lastSlash = path.lastIndexOf('/');
// fix slashes.
return (lastSlash === -1) ? path : path.substring(lastSlash+1);
};
AblePlayer.prototype.getFilenameFromTracks = function(kind,lang) {
for (var i=0; i<this.vtsTracks.length; i++) {
if (this.vtsTracks[i].kind === kind && this.vtsTracks[i].language === lang) {
// this is a matching track
// srcFile has already been converted to filename from path before saving to vtsTracks
return this.vtsTracks[i].srcFile;
}
}
// no matching track found
return false;
};
AblePlayer.prototype.parseVtsTracks = function(contents) {
var rows, timeParts, cues, i, j, thisRow, nextRow, content, blankRow;
rows = contents.split("\n");
cues = [];
i = 0;
while (i < rows.length) {
thisRow = rows[i];
if (thisRow.indexOf(' --> ') !== -1) {
// this is probably a time row
timeParts = thisRow.trim().split(' ');
if (this.isValidTimestamp(timeParts[0]) && this.isValidTimestamp(timeParts[2])) {
// both timestamps are valid. This is definitely a time row
content = '';
j = i+1;
blankRow = false;
while (j < rows.length && !blankRow) {
nextRow = rows[j].trim();
if (nextRow.length > 0) {
if (content.length > 0) {
// add back the EOL between rows of content
content += "\n" + nextRow;
} else {
// this is the first row of content. No need for an EOL
content += nextRow;
}
} else {
blankRow = true;
}
j++;
}
cues.push({
'start': timeParts[0],
'end': timeParts[2],
'content': content
});
i = j; //skip ahead
}
} else {
i++;
}
}
return cues;
};
AblePlayer.prototype.isValidTimestamp = function(timestamp) {
// return true if timestamp contains only numbers or expected punctuation
return (/^[0-9:,.]*$/.test(timestamp)) ? true : false;
};
AblePlayer.prototype.formatTimestamp = function(timestamp) {
// timestamp is a string in the form "HH:MM:SS.xxx"
// Take some simple steps to ensure edited timestamp values still adhere to expected format
var firstPart, lastPart;
firstPart = timestamp.substring(0,timestamp.lastIndexOf('.')+1);
lastPart = timestamp.substring(timestamp.lastIndexOf('.')+1);
// TODO: Be sure each component within firstPart has only exactly two digits
// Probably can't justify doing this automatically
// If users enters '5' for minutes, that could be either '05' or '50'
// This should trigger an error and prompt the user to correct the value before proceeding
// Be sure lastPart has exactly three digits
if (lastPart.length > 3) {
// chop off any extra digits
lastPart = lastPart.substring(0,3);
} else if (lastPart.length < 3) {
// add trailing zeros
while (lastPart.length < 3) {
lastPart += '0';
}
}
return firstPart + lastPart;
};
AblePlayer.prototype.injectVtsTable = function(action,lang) {
// action is either 'add' (for a new table) or 'update' (if user has selected a new lang)
var $table, $thead, headers, i, $tr, $th, $td, rows, rowNum, rowId;
if (action === 'update') {
// remove existing table
$('#able-vts table').remove();
$('#able-vts-icon-credit').remove();
}
$table = $('<table>',{
'lang': lang
});
$thead = $( '<thead>' );
$tr = $( '<tr>' );
headers = [
this.translate( 'vtsRow', 'Row' ),
this.translate( 'vtsKind', 'Kind' ),
this.translate( 'vtsStart', 'Start' ),
this.translate( 'vtsEnd', 'End' ),
this.translate( 'vtsContent', 'Content' ),
this.translate( 'vtsActions', 'Actions' )
];
for (i=0; i < headers.length; i++) {
$th = $('<th>', {
'scope': 'col'
}).text(headers[i]);
if (headers[i] === 'Actions') {
$th.addClass('actions');
}
$tr.append($th);
}
$thead.append($tr);
$table.append($thead);
// Get all rows (sorted by start time), and inject them into table
rows = this.getAllRows(lang);
for (i=0; i < rows.length; i++) {
rowNum = i + 1;
rowId = 'able-vts-row-' + rowNum;
$tr = $('<tr>',{
'id': rowId,
'class': 'kind-' + rows[i].kind
});
// Row #
$td = $('<td>').text(rowNum);
$tr.append($td);
// Kind
$td = $('<td>',{
'contenteditable': 'true'
}).text(rows[i].kind);
$tr.append($td);
// Start
$td = $('<td>',{
'contenteditable': 'true'
}).text(rows[i].start);
$tr.append($td);
// End
$td = $('<td>',{
'contenteditable': 'true'
}).text(rows[i].end);
$tr.append($td);
// Content
$td = $('<td>',{
'contenteditable': 'true'
}).text(rows[i].content); // TODO: Preserve tags
$tr.append($td);
// Actions
$td = this.addVtsActionButtons(rowNum,rows.length);
$tr.append($td);
$table.append($tr);
}
$('#able-vts').append($table);
// Add credit for action button SVG icons
$('#able-vts').append(this.getIconCredit());
};
AblePlayer.prototype.addVtsActionButtons = function(rowNum,numRows) {
// rowNum is the number of the current table row (starting with 1)
// numRows is the total number of rows (excluding the header row)
// TODO: Position buttons so they're vertically aligned, even if missing an Up or Down button
var thisObj, $td, buttons, i, button, $button, $svg, $g, pathString, pathString2, $path, $path2;
thisObj = this;
$td = $('<td>');
buttons = ['up','down','insert','delete'];
for (i=0; i < buttons.length; i++) {
button = buttons[i];
if (button === 'up') {
if (rowNum > 1) {
$button = $('<button>',{
'id': 'able-vts-button-up-' + rowNum,
'title': 'Move up',
'aria-label': 'Move Row ' + rowNum + ' up'
}).on('click', function(el) {
thisObj.onClickVtsActionButton(el.currentTarget);
});
$svg = $('<svg>',{
'focusable': 'false',
'aria-hidden': 'true',
'x': '0px',
'y': '0px',
'width': '254.296px',
'height': '254.296px',
'viewBox': '0 0 254.296 254.296',
'style': 'enable-background:new 0 0 254.296 254.296'
});
pathString = 'M249.628,176.101L138.421,52.88c-6.198-6.929-16.241-6.929-22.407,0l-0.381,0.636L4.648,176.101'
+ 'c-6.198,6.897-6.198,18.052,0,24.981l0.191,0.159c2.892,3.305,6.865,5.371,11.346,5.371h221.937c4.577,0,8.613-2.161,11.41-5.594'
+ 'l0.064,0.064C255.857,194.153,255.857,182.998,249.628,176.101z';
$path = $('<path>',{
'd': pathString
});
$g = $('<g>').append($path);
$svg.append($g);
$button.append($svg);
// Refresh button in the DOM in order for browser to process & display the SVG
$button.html($button.html());
$td.append($button);
}
} else if (button === 'down') {
if (rowNum < numRows) {
$button = $('<button>',{
'id': 'able-vts-button-down-' + rowNum,
'title': 'Move down',
'aria-label': 'Move Row ' + rowNum + ' down'
}).on('click', function(el) {
thisObj.onClickVtsActionButton(el.currentTarget);
});
$svg = $('<svg>',{
'focusable': 'false',
'aria-hidden': 'true',
'x': '0px',
'y': '0px',
'width': '292.362px',
'height': '292.362px',
'viewBox': '0 0 292.362 292.362',
'style': 'enable-background:new 0 0 292.362 292.362'
});
pathString = 'M286.935,69.377c-3.614-3.617-7.898-5.424-12.848-5.424H18.274c-4.952,0-9.233,1.807-12.85,5.424'
+ 'C1.807,72.998,0,77.279,0,82.228c0,4.948,1.807,9.229,5.424,12.847l127.907,127.907c3.621,3.617,7.902,5.428,12.85,5.428'
+ 's9.233-1.811,12.847-5.428L286.935,95.074c3.613-3.617,5.427-7.898,5.427-12.847C292.362,77.279,290.548,72.998,286.935,69.377z';
$path = $('<path>',{
'd': pathString
});
$g = $('<g>').append($path);
$svg.append($g);
$button.append($svg);
// Refresh button in the DOM in order for browser to process & display the SVG
$button.html($button.html());
$td.append($button);
}
} else if (button === 'insert') {
// Add Insert button to all rows
$button = $('<button>',{
'id': 'able-vts-button-insert-' + rowNum,
'title': 'Insert row below',
'aria-label': 'Insert row before Row ' + rowNum
}).on('click', function(el) {
thisObj.onClickVtsActionButton(el.currentTarget);
});
$svg = $('<svg>',{
'focusable': 'false',
'aria-hidden': 'true',
'x': '0px',
'y': '0px',
'width': '401.994px',
'height': '401.994px',
'viewBox': '0 0 401.994 401.994',
'style': 'enable-background:new 0 0 401.994 401.994'
});
pathString = 'M394,154.175c-5.331-5.33-11.806-7.994-19.417-7.994H255.811V27.406c0-7.611-2.666-14.084-7.994-19.414'
+ 'C242.488,2.666,236.02,0,228.398,0h-54.812c-7.612,0-14.084,2.663-19.414,7.993c-5.33,5.33-7.994,11.803-7.994,19.414v118.775'
+ 'H27.407c-7.611,0-14.084,2.664-19.414,7.994S0,165.973,0,173.589v54.819c0,7.618,2.662,14.086,7.992,19.411'
+ 'c5.33,5.332,11.803,7.994,19.414,7.994h118.771V374.59c0,7.611,2.664,14.089,7.994,19.417c5.33,5.325,11.802,7.987,19.414,7.987'
+ 'h54.816c7.617,0,14.086-2.662,19.417-7.987c5.332-5.331,7.994-11.806,7.994-19.417V255.813h118.77'
+ 'c7.618,0,14.089-2.662,19.417-7.994c5.329-5.325,7.994-11.793,7.994-19.411v-54.819C401.991,165.973,399.332,159.502,394,154.175z';
$path = $('<path>',{
'd': pathString
});
$g = $('<g>').append($path);
$svg.append($g);
$button.append($svg);
// Refresh button in the DOM in order for browser to process & display the SVG
$button.html($button.html());
$td.append($button);
} else if (button === 'delete') {
// Add Delete button to all rows
$button = $('<button>',{
'id': 'able-vts-button-delete-' + rowNum,
'title': 'Delete row ',
'aria-label': 'Delete Row ' + rowNum
}).on('click', function(el) {
thisObj.onClickVtsActionButton(el.currentTarget);
});
$svg = $('<svg>',{
'focusable': 'false',
'aria-hidden': 'true',
'x': '0px',
'y': '0px',
'width': '508.52px',
'height': '508.52px',
'viewBox': '0 0 508.52 508.52',
'style': 'enable-background:new 0 0 508.52 508.52'
});
pathString = 'M397.281,31.782h-63.565C333.716,14.239,319.478,0,301.934,0h-95.347'
+ 'c-17.544,0-31.782,14.239-31.782,31.782h-63.565c-17.544,0-31.782,14.239-31.782,31.782h349.607'
+ 'C429.063,46.021,414.825,31.782,397.281,31.782z';
$path = $('<path>',{
'd': pathString
});
pathString2 = 'M79.456,476.737c0,17.544,14.239,31.782,31.782,31.782h286.042'
+ 'c17.544,0,31.782-14.239,31.782-31.782V95.347H79.456V476.737z M333.716,174.804c0-8.772,7.151-15.891,15.891-15.891'
+ 'c8.74,0,15.891,7.119,15.891,15.891v254.26c0,8.74-7.151,15.891-15.891,15.891c-8.74,0-15.891-7.151-15.891-15.891V174.804z'
+ 'M238.369,174.804c0-8.772,7.119-15.891,15.891-15.891c8.74,0,15.891,7.119,15.891,15.891v254.26'
+ 'c0,8.74-7.151,15.891-15.891,15.891c-8.772,0-15.891-7.151-15.891-15.891V174.804z M143.021,174.804'
+ 'c0-8.772,7.119-15.891,15.891-15.891c8.772,0,15.891,7.119,15.891,15.891v254.26c0,8.74-7.119,15.891-15.891,15.891'
+ 'c-8.772,0-15.891-7.151-15.891-15.891V174.804z';
$path2 = $('<path>',{
'd': pathString2
});
$g = $('<g>').append($path,$path2);
$svg.append($g);
$button.append($svg);
// Refresh button in the DOM in order for browser to process & display the SVG
$button.html($button.html());
$td.append($button);
}
}
return $td;
};
AblePlayer.prototype.updateVtsActionButtons = function($buttons,nextRowNum) {
// TODO: Add some filters to this function to add or delete 'Up' and 'Down' buttons
// if row is moved to/from the first/last rows
var i, $thisButton, id, label, newId, newLabel;
for (i=0; i < $buttons.length; i++) {
$thisButton = $buttons.eq(i);
id = $thisButton.attr('id');
label = $thisButton.attr('aria-label');
// replace the integer (id) within each of the above strings
newId = id.replace(/[0-9]+/g, nextRowNum);
newLabel = label.replace(/[0-9]+/g, nextRowNum);
$thisButton.attr('id',newId);
$thisButton.attr('aria-label',newLabel);
}
}
AblePlayer.prototype.getIconCredit = function() {
var credit
= 'Action buttons made by <a target="_blank" rel="noreferrer" href="https://www.elegantthemes.com">Elegant Themes</a>'
+ ' from <a target="_blank" rel="noreferrer" href="https://www.flaticon.com">flaticon</a>'
+ ' are licensed by <a target="_blank" rel="noreferrer" href="https://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0">CC 3.0 BY</a>'
;
return '<div id="able-vts-icon-credit">' + credit + '</div>';
};
AblePlayer.prototype.getAllLangs = function(tracks) {
// update this.langs with any unique languages found in tracks
var i;
for (i in tracks) {
if (Object.hasOwn(tracks[i], 'language')) {
if ($.inArray(tracks[i].language,this.langs) === -1) {
// this language is not already in the langs array. Add it.
this.langs[this.langs.length] = tracks[i].language;
}
}
}
};
AblePlayer.prototype.getAllRows = function(lang) {
// returns an array of data to be displayed in VTS table
// includes all cues for tracks of any type with matching lang
// cues are sorted by start time
var i, track, c, cues;
cues = [];
for (i=0; i < this.vtsTracks.length; i++) {
track = this.vtsTracks[i];
if (track.language == lang) {
// this track matches the language. Add its cues to array
for (c in track.cues) {
cues.push({
'kind': track.kind,
'lang': lang,
'id': track.cues[c].id,
'start': track.cues[c].start,
'end': track.cues[c].end,
'content': track.cues[c].content
});
}
}
}
// Now sort cues by start time
cues.sort(function(a,b) {
return a.start > b.start ? 1 : -1;
});
return cues;
};
AblePlayer.prototype.onClickVtsActionButton = function(el) {
// handle click on up, down, insert, or delete button
var idParts, action, rowNum;
idParts = $(el).attr('id').split('-');
action = idParts[3];
rowNum = idParts[4];
if (action == 'up') {
// move the row up
this.moveRow(rowNum,'up');
} else if (action == 'down') {
// move the row down
this.moveRow(rowNum,'down');
} else if (action == 'insert') {
// insert a row below
this.insertRow(rowNum);
} else if (action == 'delete') {
// delete the row
this.deleteRow(rowNum);
}
};
AblePlayer.prototype.insertRow = function(rowNum) {
// Insert empty row below rowNum
var $table, $rows, numRows, newRowNum, newRowId, $tr, $td, $select,
options, i, $option, newKind, newClass, $parentRow, nextRowNum, $buttons;
$table = $('#able-vts table');
$rows = $table.find('tr');
numRows = $rows.length - 1; // exclude header row
newRowNum = parseInt(rowNum) + 1;
newRowId = 'able-vts-row-' + newRowNum;
// Create an empty row
$tr = $('<tr>',{
'id': newRowId
});
// Row #
$td = $('<td>').text(newRowNum);
$tr.append($td);
// Kind (add a select field for chosing a kind)
newKind = null;
$select = $('<select>',{
'id': 'able-vts-kind-' + newRowNum,
'aria-label': 'What kind of track is this?',
'placeholder': 'Select a kind'
}).on('change',function() {
newKind = $(this).val();
newClass = 'kind-' + newKind;
$parentRow = $(this).closest('tr');
// replace the select field with the chosen value as text
$(this).parent().text(newKind);
// add a class to the parent row
$parentRow.addClass(newClass);
});
options = ['','captions','chapters','descriptions','subtitles'];
for (i=0; i<options.length; i++) {
$option = $('<option>',{
'value': options[i]
}).text(options[i]);
$select.append($option);
}
$td = $('<td>').append($select);
$tr.append($td);
// Start
$td = $('<td>',{
'contenteditable': 'true'
}); // TODO; Intelligently assign a new start time (see getAdjustedTimes())
$tr.append($td);
// End
$td = $('<td>',{
'contenteditable': 'true'
}); // TODO; Intelligently assign a new end time (see getAdjustedTimes())
$tr.append($td);
// Content
$td = $('<td>',{
'contenteditable': 'true'
});
$tr.append($td);
// Actions
$td = this.addVtsActionButtons(newRowNum,numRows);
$tr.append($td);
// Now insert the new row
$table.find('tr').eq(rowNum).after($tr);
// Update row.id, Row # cell, & action items for all rows after the inserted one
for (i=newRowNum; i <= numRows; i++) {
nextRowNum = i + 1;
$rows.eq(i).attr('id','able-vts-row-' + nextRowNum); // increment tr id
$rows.eq(i).find('td').eq(0).text(nextRowNum); // increment Row # as expressed in first td
$buttons = $rows.eq(i).find('button');
this.updateVtsActionButtons($buttons,nextRowNum);
}
// Auto-adjust times
this.adjustTimes(newRowNum);
// Announce the insertion
let newAlert = this.translate( 'vtsNewRow', 'A new row %1 has been inserted.', [ newRowNum ] );
this.showVtsAlert( newAlert );
// Place focus in new select field
$select.trigger('focus');
};
AblePlayer.prototype.deleteRow = function(rowNum) {
var $table, $rows, numRows, i, nextRowNum, $buttons;
$table = $('#able-vts table');
$table[0].deleteRow(rowNum);
$rows = $table.find('tr'); // this does not include the deleted row
numRows = $rows.length - 1; // exclude header row
// Update row.id, Row # cell, & action buttons for all rows after the deleted one
for (i=rowNum; i <= numRows; i++) {
nextRowNum = i;
$rows.eq(i).attr('id','able-vts-row-' + nextRowNum); // increment tr id
$rows.eq(i).find('td').eq(0).text(nextRowNum); // increment Row # as expressed in first td
$buttons = $rows.eq(i).find('button');
this.updateVtsActionButtons($buttons,nextRowNum);
}
// Announce the deletion
let newAlert = this.translate( 'vtsDeletedRow', 'Row %1 has been deleted.', [ rowNum ] );
this.showVtsAlert( newAlert );
};
AblePlayer.prototype.moveRow = function(rowNum,direction) {
// swap two rows
var $thisRow, otherRowNum, $otherRow, msg;
$thisRow = $('#able-vts table').find('tr').eq(rowNum);
if (direction == 'up') {
otherRowNum = parseInt(rowNum) - 1;
$otherRow = $('#able-vts table').find('tr').eq(otherRowNum);
$otherRow.before($thisRow);
} else if (direction == 'down') {
otherRowNum = parseInt(rowNum) + 1;
$otherRow = $('#able-vts table').find('tr').eq(otherRowNum);
$otherRow.after($thisRow);
}
// Update row.id, Row # cell, & action buttons for the two swapped rows
$thisRow.attr('id','able-vts-row-' + otherRowNum);
$thisRow.find('td').eq(0).text(otherRowNum);
this.updateVtsActionButtons($thisRow.find('button'),otherRowNum);
$otherRow.attr('id','able-vts-row-' + rowNum);
$otherRow.find('td').eq(0).text(rowNum);
this.updateVtsActionButtons($otherRow.find('button'),rowNum);
// auto-adjust times
this.adjustTimes(otherRowNum);
// Announce the move
msg = this.translate( 'vtsMovedRow', 'Row %1 has been moved %2 and is now Row %3.', [ rowNum, direction, otherRowNum ] );
this.showVtsAlert(msg);
};
AblePlayer.prototype.adjustTimes = function(rowNum) {
// Adjusts start and end times of the current, previous, and next rows in VTS table
// after a move or insert
// NOTE: Fully automating this process would be extraordinarily complicated
// The goal here is simply to make subtle tweaks to ensure rows appear
// in the new order within the Able Player transcript
// Additional tweaking will likely be required by the user
// HISTORY: Originally set minDuration to 2 seconds for captions and .500 for descriptions
// However, this can results in significant changes to existing caption timing,
// with not-so-positive results.
// As of 3.1.15, setting minDuration to .001 for all track kinds
// Users will have to make further adjustments manually if needed
// TODO: Add WebVTT validation on save, since tweaking times is risky
var minDuration, $rows, prevRowNum, nextRowNum, $row, $prevRow, $nextRow,
kind, prevKind, nextKind,
start, prevStart, nextStart,
end, prevEnd, nextEnd;
// Define minimum duration (in seconds) for each kind of track
minDuration = [];
minDuration['captions'] = .001;
minDuration['descriptions'] = .001;
minDuration['chapters'] = .001;
// refresh rows object
$rows = $('#able-vts table').find('tr');
// Get kind, start, and end from current row
$row = $rows.eq(rowNum);
// row has a class that starts with "kind-"
// Extract kind from the class name
kind = ($row.is('[class^="kind-"]')) ? this.getKindFromClass($row.attr('class')) : 'captions';
start = this.getSecondsFromColonTime($row.find('td').eq(2).text());
end = this.getSecondsFromColonTime($row.find('td').eq(3).text());
// Get kind, start, and end from previous row
if (rowNum > 1) {
// this is not the first row. Include the previous row
prevRowNum = rowNum - 1;
$prevRow = $rows.eq(prevRowNum);
// row has a class that starts with "kind-"
// Extract kind from the class name
prevKind = ($prevRow.is('[class^="kind-"]')) ? this.getKindFromClass($prevRow.attr('class')) : null;
prevStart = this.getSecondsFromColonTime($prevRow.find('td').eq(2).text());
prevEnd = this.getSecondsFromColonTime($prevRow.find('td').eq(3).text());
} else {
// this is the first row
$prevRow = null;
prevKind = null;
prevStart = null;
prevEnd = null;
}
// Get kind, start, and end from next row
if (rowNum < ($rows.length - 1)) {
// this is not the last row. Include the next row
nextRowNum = rowNum + 1;
$nextRow = $rows.eq(nextRowNum);
// row has a class that starts with "kind-"
// Extract kind from the class name
nextKind = ($nextRow.is('[class^="kind-"]')) ? this.getKindFromClass($nextRow.attr('class')) : null;
nextStart = this.getSecondsFromColonTime($nextRow.find('td').eq(2).text());
nextEnd = this.getSecondsFromColonTime($nextRow.find('td').eq(3).text());
} else {
// this is the last row
$nextRow = null;
nextKind = null;
nextStart = null;
nextEnd = null;
}
if (isNaN(start)) {
if (prevKind == null) {
// The previous row was probably inserted, and user has not yet selected a kind
// automatically set it to captions
prevKind = 'captions';
$prevRow.attr('class','kind-captions');
$prevRow.find('td').eq(1).html('captions');
}
// Current row has no start time (i.e., it's an inserted row)
if (prevKind === 'captions') {
// start the new row immediately after the captions end
start = (parseFloat(prevEnd) + .001).toFixed(3);
// end the new row immediately before the next row starts
end = (nextStart) ? (parseFloat(nextStart) - .001).toFixed(3) : (parseFloat(start) + minDuration[kind]).toFixed(3);
} else if (prevKind === 'chapters') {
// start the new row immediately after the chapter start (not end)
start = (parseFloat(prevStart) + .001).toFixed(3);
// end the new row immediately before the next row starts
end = (nextStart) ? (parseFloat(nextStart) - .001).toFixed(3) : (parseFloat(start) + minDuration[kind]).toFixed(3);
} else if (prevKind === 'descriptions') {
// start the new row minDuration['descriptions'] after the description starts
// this will theoretically allow at least a small cushion for the description to be read
start = (parseFloat(prevStart) + minDuration['descriptions']).toFixed(3);
end = (parseFloat(start) + minDuration['descriptions']).toFixed(3);
}
} else {
// current row has a start time (i.e., an existing row has been moved))
if (prevStart) {
// this is not the first row.
if (prevStart < start) {
if (start < nextStart) {
// No change is necessary
} else {
// nextStart needs to be incremented
nextStart = (parseFloat(start) + minDuration[kind]).toFixed(3);
nextEnd = (parseFloat(nextStart) + minDuration[nextKind]).toFixed(3);
// TODO: Ensure nextEnd does not exceed the following start (nextNextStart)
// Or... maybe this is getting too complicated and should be left up to the user
}
} else {
// start needs to be incremented
start = (parseFloat(prevStart) + minDuration[prevKind]).toFixed(3);
end = (parseFloat(start) + minDuration[kind]).toFixed(3);
}
} else {
// this is the first row
if (start < nextStart) {
// No change is necessary
} else {
// nextStart needs to be incremented
nextStart = (parseFloat(start) + minDuration[kind]).toFixed(3);
nextEnd = (parseFloat(nextStart) + minDuration[nextKind]).toFixed(3);
}
}
}
// check to be sure there is sufficient duration between new start & end times
if (end - start < minDuration[kind]) {
// duration is too short. Change end time
end = (parseFloat(start) + minDuration[kind]).toFixed(3);
if (nextStart) {
// this is not the last row
// increase start time of next row
nextStart = (parseFloat(end) + .001).toFixed(3);
}
}
// Update all affected start/end times
$row.find('td').eq(2).text(this.formatSecondsAsColonTime(start,true));
$row.find('td').eq(3).text(this.formatSecondsAsColonTime(end,true));
if ($prevRow) {
$prevRow.find('td').eq(2).text(this.formatSecondsAsColonTime(prevStart,true));
$prevRow.find('td').eq(3).text(this.formatSecondsAsColonTime(prevEnd,true));
}
if ($nextRow) {
$nextRow.find('td').eq(2).text(this.formatSecondsAsColonTime(nextStart,true));
$nextRow.find('td').eq(3).text(this.formatSecondsAsColonTime(nextEnd,true));
}
};
AblePlayer.prototype.getKindFromClass = function(myclass) {
// This function is called when a class with prefix "kind-" is found in the class attribute
var kindStart, kindEnd;
kindStart = myclass.indexOf('kind-')+5;
kindEnd = myclass.indexOf(' ',kindStart);
if (kindEnd == -1) {
// no spaces found, "kind-" must be the only myclass
return myclass.substring(kindStart);
} else {
// kind-* is one of multiple classes
// the following will find it regardless of position of "kind-*" within the class string
return myclass.substring(kindStart,kindEnd);
}
};
AblePlayer.prototype.showVtsAlert = function(message) {
// this is distinct from greater Able Player showAlert()
// because it's positioning needs are unique
// For now, alertDiv is fixed at top left of screen
// but could ultimately be modified to appear near the point of action in the VTS table
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
this.$vtsAlert.text(message).show();
delay(10000).then(() => {
this.$vtsAlert.text(message).hide()
});
};
AblePlayer.prototype.parseVtsOutput = function($table) {
// parse table into arrays, then into WebVTT content, for each kind
// Display the WebVTT content in textarea fields for users to copy and paste
var lang, i, kinds, kind, vtt, $rows, start, end, content, $output;
lang = $table.attr('lang');
kinds = ['captions','chapters','descriptions','subtitles'];
vtt = {};
for (i=0; i < kinds.length; i++) {
kind = kinds[i];
vtt[kind] = 'WEBVTT' + "\n\n";
}
$rows = $table.find('tr');
if ($rows.length > 0) {
for (i=0; i < $rows.length; i++) {
kind = $rows.eq(i).find('td').eq(1).text();
if ($.inArray(kind,kinds) !== -1) {
start = $rows.eq(i).find('td').eq(2).text();
end = $rows.eq(i).find('td').eq(3).text();
content = $rows.eq(i).find('td').eq(4)[0].innerText;
if (start !== undefined && end !== undefined) {
vtt[kind] += start + ' --> ' + end + "\n";
if (content !== 'undefined') {
vtt[kind] += content;
}
vtt[kind] += "\n\n";
}
}
}
}
$output = $('<div>',{
'id': 'able-vts-output'
})
$('#able-vts').append($output);
for (i=0; i < kinds.length; i++) {
kind = kinds[i];
if (vtt[kind].length > 8) {
// some content has been added
this.showWebVttOutput(kind,vtt[kind],lang)
}
}