-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
tty-player.js
1975 lines (1730 loc) · 63.7 KB
/
tty-player.js
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
// W069 is “['x'] is better written in dot notation”, but Closure Compiler wants ['x'].
// jshint -W069
// jshint bitwise: false
// ==ClosureCompiler==
// @output_file_name tty-player.min.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// @language_out ES6
// @js_externs /** @type {!DOMTokenList} */ Element.prototype.part;
// ==/ClosureCompiler==
/* global MediaError, TimeRanges, Terminal, HTMLElement */
;(function() {
"use strict";
var textDecoder = new TextDecoder();
/// parseDataURI("data:foo/bar;base64,MTIzNA==#foo") === "1234"
/// @param {string} uri
function parseDataURI(uri) {
// [whole uri, "base64" or undefined, data]
var chunks = /^data:([^,]*),([^#]+)/.exec(uri);
if (chunks === null) {
return null;
}
var data = decodeURIComponent(chunks[2]);
var mime = chunks[1].replace(/;base64$/, "");
return [mime, mime === chunks[1] ? data : atob(data)];
}
/// @param {Uint8Array} array
function byteArrayToString(array) {
// String.fromCharCode.apply can for too large values overflow the call stack.
// Hence this, though I doubt we actually use large enough strings to worry.
// http://stackoverflow.com/a/12713326
var CHUNK_SIZE = 0x8000;
var c = [];
for (var i = 0; i < array.length; i += CHUNK_SIZE) {
c.push(String.fromCharCode.apply(null, array.subarray(i, i + CHUNK_SIZE)));
}
return c.join("");
}
function parseNPT(npt) {
// Format: [npt:]([h:]mm:ss|seconds)[.subsecond]
// I’ve decided to be lazy and allow "1:2:3.4" as well as "1:02:03.4"
// This makes it [npt:][[h:]m:]s[.subsecond]
var match = /^(?:npt:)?(?:(?:(\d+):)?(\d+):)?(\d+(?:\.\d+)?)$/i.exec(npt);
return match ? (match[1] || 0) * 3600 + (match[2] || 0) * 60 + match[3] : null;
}
function classifyPosterURL(url) {
if (!url) {
// There is no poster.
return {type: null};
}
switch (/^(?:(.*):)?/.exec(url)[1]) {
case "npt":
var time = parseNPT(url);
return time ? {type: "npt", time} : {type: null};
case "data":
var data = parseDataURI(url);
if (/^text\/plain$/i.test(data[0])) {
return {type: "text", data: data[1]};
}
}
// TODO: treat all the other possibilities as images.
return {type: null};
}
/// @param {ArrayBuffer} source
function parseTTYRec(source) {
var utf8 = true;
var dimensions = null;
var data = [];
var byteOffset = 0;
var timeOffset = 0;
var sourceLength = source.byteLength;
while (byteOffset < sourceLength) {
var sec, usec, len;
var header = new DataView(source, byteOffset);
sec = header.getUint32(0, true);
usec = header.getUint32(4, true);
len = header.getUint32(8, true);
var time = sec + (usec / 1000000);
byteOffset += 12;
var payload = new Uint8Array(source, byteOffset, len);
payload = utf8 ? textDecoder.decode(payload) : byteArrayToString(payload);
if (byteOffset === 12) {
// First chunk might be metadata; this is how termrec does it, for example.
timeOffset = time;
var metadata = /^\x1b%(G|@)\x1b\[8;([0-9]+);([0-9]+)t$/.exec(payload);
if (metadata) {
utf8 = metadata[1] === "G";
dimensions = {
rows: +metadata[2],
cols: +metadata[3]
};
}
}
time -= timeOffset;
byteOffset += len;
data.push([payload, time]);
}
return {
// Heuristic: if the time offset is large enough, it’s probably a timestamp.
startDate: timeOffset >= 1e8 ? new Date(timeOffset * 1000) : null,
dimensions,
data
};
}
function formatTime(time) {
var seconds = time | 0;
var minutes = seconds / 60 | 0;
seconds = ("0" + (seconds % 60)).substr(-2);
if (minutes >= 60) {
var hours = minutes / 60 | 0;
minutes = ("0" + (minutes % 60)).substr(-2);
return hours + ":" + minutes + ":" + seconds;
} else {
return minutes + ":" + seconds;
}
}
function blankableAttributeProperty(name) {
return {
get() {
var value = this.getAttribute(name);
return value === null ? "" : value.trim();
},
set(value) {
this.setAttribute(name, value);
}
};
}
function attributeBooleanProperty(name) {
return {
get() {
return this.hasAttribute(name);
},
set(bool) {
if (bool) {
this.setAttribute(name, "");
} else {
this.removeAttribute(name);
}
}
};
}
function invalidStateError() {
document.createElement("video").currentTime = 1;
}
const NETWORK_EMPTY = 0;
const NETWORK_IDLE = 1;
const NETWORK_LOADING = 2;
const NETWORK_NO_SOURCE = 3;
const HAVE_NOTHING = 0;
const HAVE_METADATA = 1;
const HAVE_CURRENT_DATA = 2;
const HAVE_FUTURE_DATA = 3;
const HAVE_ENOUGH_DATA = 4;
// Annoyingly, with things like MediaError, one apparently can’t construct them in any way.
// So we fake it like this.
// Note that the constants on MediaError are *not* on MyMediaError, though they are on instances.
var MyMediaError = /** @constructor */ function MediaError(code) {
Object.defineProperty(this, "code", {value: code});
};
MyMediaError.prototype = Object.create(MediaError.prototype);
const EMPTY_TIME_RANGES = document.createElement("video").played;
var MyTimeRanges = /** @constructor */ function TimeRanges(ranges) {
Object.defineProperty(this, "length", {value: ranges.length});
this["_"] = ranges;
};
MyTimeRanges.prototype = Object.create(TimeRanges.prototype);
MyTimeRanges.prototype["start"] = function(i) {
if (i < this["length"]) {
return this["_"][i][0];
} else {
return EMPTY_TIME_RANGES["end"](0); // Throws IndexSizeError
}
};
MyTimeRanges.prototype["end"] = function(i) {
if (i < this["length"]) {
return this["_"][i][1];
} else {
return EMPTY_TIME_RANGES["end"](0); // Throws IndexSizeError
}
};
const MEDIA_ERR_ABORTED = 1;
const MEDIA_ERR_NETWORK = 2;
const MEDIA_ERR_DECODE = 3;
const MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
const ERROR_DETAILS = {
1: ["MEDIA_ERR_ABORTED", "The fetching process for the media resource was aborted by the user agent at the user's request."],
2: ["MEDIA_ERR_NETWORK", "A network error of some description caused the user agent to stop fetching the media resource, after the resource was established to be usable."],
3: ["MEDIA_ERR_DECODE", "An error of some description occurred while decoding the media resource, after the resource was established to be usable."],
4: ["MEDIA_ERR_SRC_NOT_SUPPORTED", "The media resource indicated by the \x1b[4msrc\x1b[24m attribute was not suitable."]
};
const FANCY_TECHNICAL_ERROR_EXPLANATIONS = true;
var menuIdSequence = 0;
function makeMenu(ttyPlayer, _) {
// Make a context menu with these items:
// - Play/Pause
// - Show/Hide Controls
//
// Firefox also has the following ones deemed unnecessary:
//
// - Mute/Unmute
// - Play Speed >
// - Slow Motion (0.5×)
// - Normal Speed (1×)
// - High Speed (1.5×)
// - Ludicrous Speed (2×)
// - Show Statistics
// - Full Screen
//
// Chrome has Show controls (lowercase c) as a toggle and adds a Loop item.
var menu = document.createElement("menu");
if (!("type" in menu)) {
return null;
}
menu.type = "context";
if (menu.type !== "context") {
return null;
}
menu.id = "tty-player-contextmenu-" + menuIdSequence++;
var playPause = document.createElement("menuitem");
playPause.onclick = _.playOrPause.bind(_);
function setPlayPauseDetails(label, path) {
playPause.label = label;
playPause.icon = "data:image/svg+xml,%3C?xml version='1.0' encoding='UTF-8' standalone='no'?%3E%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16'%3E%3Cpath stroke='%23999' stroke-width='1' fill='%23eee' d='" + path + "'/%3E%3C/svg%3E";
}
function onPlay() {
setPlayPauseDetails("Pause", "m2.5,1.5 0,13 4,0 0,-13zm7,0 0,13 4,0 0,-13z");
}
function onPause() {
setPlayPauseDetails("Play", "m2.5,2 0,12 11,-6z");
}
onPause();
ttyPlayer.addEventListener("play", onPlay);
ttyPlayer.addEventListener("pause", onPause);
var controls = document.createElement("menuitem");
menu.onControlsShownOrHidden = function() {
if (ttyPlayer["controls"]) {
controls.label = "Hide Controls";
} else {
controls.label = "Show Controls";
}
};
menu.onControlsShownOrHidden();
controls.onclick = function() {
ttyPlayer["controls"] = !ttyPlayer["controls"];
};
menu.appendChild(playPause);
menu.appendChild(controls);
return menu;
}
// TODO: reset() hides the cursor; patch term.js so if useFocus === false it is shown by default?
var stockReset = Terminal.prototype["reset"];
Terminal.prototype["reset"] = function() {
stockReset.call(this);
if ("useFocus" in this["options"] && !this["options"]["useFocus"]) {
this["showCursor"]();
}
};
// Our shadow DOM technique (applying the styles only inside the shadow DOM) breaks term.js’s brokenBold calculation. So just assume that bold works.
Terminal.brokenBold = false;
// IDL for this code:
//
// interface HTMLTTYPlayerElement : HTMLMediaElement {
// attribute DOMString defaultTitle;
// attribute DOMString title;
//
// readonly attribute unsigned long cols;
// readonly attribute unsigned long rows;
// void resize(unsigned long cols, unsigned long rows);
//
// attribute EventHandler ontitlechange;
//
// // This one is straight from HTMLVideoElement.
// attribute DOMString poster;
//
// // s/void/avoid/
// void pretendToBeAVideo();
// }
//
// IDL taken from HTML 5 spec:
//
// enum CanPlayTypeEnum { "" /* empty string */, "maybe", "probably" };
// interface HTMLMediaElement : HTMLElement {
//
// // error state
// readonly attribute MediaError? error;
//
// // network state
// attribute DOMString src;
// readonly attribute DOMString currentSrc;
// attribute DOMString crossOrigin;
// const unsigned short NETWORK_EMPTY = 0;
// const unsigned short NETWORK_IDLE = 1;
// const unsigned short NETWORK_LOADING = 2;
// const unsigned short NETWORK_NO_SOURCE = 3;
// readonly attribute unsigned short networkState;
// attribute DOMString preload;
// readonly attribute TimeRanges buffered;
// void load();
// CanPlayTypeEnum canPlayType(DOMString type);
//
// // ready state
// const unsigned short HAVE_NOTHING = 0;
// const unsigned short HAVE_METADATA = 1;
// const unsigned short HAVE_CURRENT_DATA = 2;
// const unsigned short HAVE_FUTURE_DATA = 3;
// const unsigned short HAVE_ENOUGH_DATA = 4;
// readonly attribute unsigned short readyState;
// readonly attribute boolean seeking;
//
// // playback state
// attribute double currentTime;
// readonly attribute unrestricted double duration;
// Date getStartDate();
// readonly attribute boolean paused;
// attribute double defaultPlaybackRate;
// attribute double playbackRate;
// readonly attribute TimeRanges played;
// readonly attribute TimeRanges seekable;
// readonly attribute boolean ended;
// attribute boolean autoplay;
// attribute boolean loop;
// void play();
// void pause();
//
// // media controller
// attribute DOMString mediaGroup;
// attribute MediaController? controller;
//
// // controls
// attribute boolean controls;
// attribute double volume;
// attribute boolean muted;
// attribute boolean defaultMuted;
//
// // tracks
// readonly attribute AudioTrackList audioTracks;
// readonly attribute VideoTrackList videoTracks;
// readonly attribute TextTrackList textTracks;
// TextTrack addTextTrack(TextTrackKind kind, optional DOMString label = "", optional DOMString language = "");
// };
//
// interface HTMLVideoElement : HTMLMediaElement {
// attribute unsigned long width;
// attribute unsigned long height;
// readonly attribute unsigned long videoWidth;
// readonly attribute unsigned long videoHeight;
// attribute DOMString poster;
// };
const TICK = 16;
const TIME_UPDATE_FREQUENCY = 100;
// Not all browsers that support Shadow DOM support Shadow Part (e.g. Safari still doesn’t, at the time of writing). Roughly polyfill it.
const supportsPart = "part" in Element.prototype;
const addPart = supportsPart
? (element, part) => element.part.add(part)
: (element, part) => {
const parts = new Set(element.getAttribute("part").split(/\s+/));
parts.delete("");
parts.add(part);
element.setAttribute("part", Array.from(parts).join(" "));
};
const removePart = supportsPart
? (element, part) => element.part.remove(part)
: (element, part) => {
const parts = new Set(element.getAttribute("part").split(/\s+/));
parts.delete("");
parts.delete(part);
element.setAttribute("part", Array.from(parts).join(" "));
};
class TTYPlayerInternalState {
constructor(ttyPlayer) {
var self = this;
self.lastTimeUpdate = 0;
self.ttyPlayer = ttyPlayer;
var shadowRoot = self.shadowRoot = ttyPlayer.attachShadow({mode: 'closed'});
var styleElement = document.createElement('style');
styleElement.textContent = `
:host {
--terminal-fg: #f0f0f0;
--terminal-bg: #000000;
display: inline-block;
position: relative;
font-family: monospace;
line-height: initial;
color: var(--terminal-fg);
background: var(--terminal-bg);
}
[part~=title] {
/* If the containing page wants to display the title, it can do so with 'tty-player::part(title) { display: block }', &c. (Yes, this means that browsers that don’t yet implement ::part can’t have a title. C’est la vie.) */
display: none;
}
:host(:not([controls])) [part~=controls] {
display: none;
}
[part~=poster] {
/* XXX: <video> has an overlay with play button if [controls] over the poster *image*, but here we have an overlay with play button regardless. Perhaps specifying a poster currentTime or script might work? */
background: rgba(53, 47, 47, 0.5);
opacity: 0.5;
transition: opacity 0.2s linear;
background-repeat: no-repeat;
background-position: center;
background-image: url("data:image/svg+xml,%3C?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3E%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='66'%20height='66'%3E%3Cfilter%20id='f'%3E%3CfeColorMatrix%20type='matrix'%20values='0%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%20.5%200'/%3E%3CfeGaussianBlur%20result='r'%20stdDeviation='2'/%3E%3CfeComposite%20in='SourceGraphic'%20in2='r'/%3E%3C/filter%3E%3Cpath%20fill='%23ddd'%20stroke='%23ccc'%20stroke-width='1'%20d='M33,5.5A27.5,27.5%200%200%200%205.5,33%2027.5,27.5%200%200%200%2033,60.5%2027.5,27.5%200%200%200%2060.5,33%2027.5,27.5%200%200%200%2033,5.5Zm-9.5,13%2025,14.5-25,14.5%200,-29z'%20filter='url(%23f)'/%3E%3C/svg%3E");
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
:host([controls]) [part~=poster] {
bottom: 28px;
}
:host(:hover) [part~=poster] {
opacity: 1;
}
[part~=controls] {
position: absolute;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
left: 0;
right: 0;
bottom: 0;
background: rgba(53, 47, 47, 0.5);
opacity: 0;
display: flex;
flex-direction: row;
transition: opacity 0.2s linear;
cursor: default;
font-family: system-ui, sans-serif;
}
/* Browsers tend to show the controls when a <video> ends, too; I, however, am not doing this for now at least as the controls will overlap with what is often the most important part of the terminal (the bottom). For this reason, I haven’t hooked up any support for that either, only showing controls persistently when the poster is up. */
[part~=controls].poster-visible,
[part~=controls]:focus-within,
:host(:hover) [part~=controls] {
opacity: 1;
}
[part~=time-slider],
[part~=play-pause-button] {
margin: 0;
padding: 0;
border: none;
background: none;
font: inherit;
line-height: inherit;
-moz-appearance: none;
-webkit-appearance: none;
}
[part~=play-pause-button] {
padding: 0;
background: none;
opacity: 0.75;
flex: 0 1 auto;
line-height: 1;
width: 28px;
height: 28px;
}
[part~=play-pause-button]:hover {
color: #777;
opacity: 1;
}
[part~=time-slider] {
flex: 1;
height: 8px;
margin: 10px 5px;
}
[part~=play-pause-button] {
background-repeat: no-repeat;
background-position: center;
}
[part~=play-button] {
background-image: url("data:image/svg+xml,%3C?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3E%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='14'%20height='16'%3E%3Cpath%20fill='%23ccc'%20d='M0,0%200,16%2014,8Z'/%3E%3C/svg%3E");
}
[part~=pause-button] {
background-image: url("data:image/svg+xml,%3C?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3E%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='14'%20height='16'%3E%3Cpath%20fill='%23ccc'%20d='M1,0L1,16L5,16L5,0L0,0zM9,0L9,16L13,16L13,0L9,0z'/%3E%3C/svg%3E");
}
[part~=time-slider]:focus {
box-shadow: none;
outline: none;
}
[part~=time-slider]::-moz-range-track,
[part~=time-slider]::-moz-range-thumb,
[part~=time-slider]::-moz-range-progress {
border-radius: 4px;
height: 8px;
}
[part~=time-slider]::-moz-range-track {
background: rgba(255, 255, 255, 0.5);
}
[part~=time-slider]::-moz-range-thumb {
-moz-appearance: none;
width: 0;
background: transparent;
border: 0;
border-radius: 0;
box-shadow: 0;
position: relative;
}
[part~=time-slider]::-moz-range-progress {
background: #fff;
}
[part~=time-slider] {
overflow: hidden;
}
[part~=time-slider]::-webkit-slider-runnable-track {
-webkit-appearance: none;
height: 8px;
background: rgba(255, 255, 255, 0.5);
//border-radius: 4px;
}
[part~=time-slider]::-webkit-slider-thumb:before {
position: absolute;
top: 0;
right: 50%;
left: -9999px;
background: #fff;
content: '';
height: 8px;
pointer-events: none;
}
[part~=time-slider]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 0;
height: 0;
position: relative;
}
/* I have not altered IE’s styles because I feel them already satisfactory */
[part~=current-time] {
position: absolute;
color: #ddd;
background: #888;
font-size: 12px;
display: block;
box-shadow: 0 1px rgba(0, 0, 0, 0.5), 0 1px 2px rgba(0, 0, 0, 0.5), inset 0 1px rgba(255, 255, 255, 0.2);
padding: 0 5px;
line-height: 16px;
border-radius: 4px;
top: -7px;
}
[part~=current-time]::after {
content: "";
position: absolute;
width: 8px;
height: 8px;
background: linear-gradient(-45deg, #888 50%, transparent 50%);
box-shadow: 1px 1px rgba(0, 0, 0, 0.5), 1px 1px 1px rgba(0, 0, 0, 0.5);
bottom: -3px;
left: 50%;
margin-left: -5px;
transform: rotate(45deg);
}
[part~=duration] {
font-size: 12px;
color: #999;
line-height: 18px;
padding: 5px;
}
.terminal {
overflow: auto;
white-space: pre;
cursor: text;
}
.terminal-cursor {
color: var(--terminal-cursor-fg, var(--terminal-bg));
background: var(--terminal-cursor-bg, var(--terminal-fg));
}
`;
shadowRoot.appendChild(styleElement);
var titleElement = self.titleElement = document.createElement("div");
addPart(titleElement, "title");
shadowRoot.appendChild(titleElement);
var terminal = self.terminal = new Terminal({"useFocus": false});
terminal.on("title", function(newTitle) {
ttyPlayer["title"] = newTitle;
});
terminal.open(shadowRoot);
addPart(terminal.element, "terminal");
if (FANCY_TECHNICAL_ERROR_EXPLANATIONS) {
ttyPlayer.addEventListener("error", function() {
var errorCode = self.error.code;
var details = ERROR_DETAILS[errorCode];
terminal.reset();
terminal.write(
"\x1b]2;Error :-(\x07" +
"\r\n\x1b[1mMediaError.\x1b[31m" + details[0] + "\x1b[m " +
"(numeric value " + errorCode + ")\r\n\r\n" +
" " + details[1] + "\r\n\r\n(Sorry ’bout that.)");
});
}
// XXX: properties with names used in the DOM don’t get shrunk by Closure
// Compiler’s advanced optimizations, for safety. We could get size down a
// smidgeon more by renaming them all, but that’d be uglier.
// Candidates: defaultPlaybackRate, playbackRate, currentSrc, readyState, networkState, paused, duration.
self.defaultPlaybackRate = self.playbackRate = 1;
self.defaultPlaybackStartPosition = 0;
self.currentSrc = "";
self.readyState = HAVE_NOTHING;
self.networkState = NETWORK_EMPTY;
self.paused = true;
self.duration = NaN;
self.defaultTitle = "";
var posterOverlay = self.posterOverlay = document.createElement("div");
addPart(posterOverlay, "poster");
posterOverlay.onclick = function() {
ttyPlayer["play"]();
};
var controlsElement = self.controlsElement = document.createElement("div");
addPart(controlsElement, "controls");
var play = document.createElement("button");
addPart(play, "play-pause-button");
addPart(play, "play-button");
play.onclick = self.playOrPause.bind(self);
ttyPlayer.addEventListener("play", function() {
addPart(play, "pause-button");
removePart(play, "play-button");
});
ttyPlayer.addEventListener("pause", function() {
removePart(play, "pause-button");
addPart(play, "play-button");
});
var currentTimeElement = self.currentTimeElement = document.createElement("span");
addPart(currentTimeElement, "current-time");
currentTimeElement.textContent = "0:00";
var durationElement = self.durationElement = document.createElement("span");
addPart(durationElement, "duration");
durationElement.textContent = "0:00";
var progressElement = self.progressElement = document.createElement("input");
addPart(progressElement, "time-slider");
progressElement.type = "range";
progressElement.value = 0;
progressElement.min = 0;
progressElement.step = "any";
var skipChange = false;
progressElement.addEventListener("input", function() {
if (!skipChange) {
skipChange = true;
self.semipaused = true;
ttyPlayer["currentTime"] = progressElement.value;
self.updateCurrentTimeElement();
skipChange = false;
}
});
progressElement.addEventListener("change", function() {
if (!skipChange) {
skipChange = true;
self.semipaused = false;
ttyPlayer["currentTime"] = progressElement.value;
self.updateCurrentTimeElement();
skipChange = false;
}
});
ttyPlayer.addEventListener("durationchange", function() {
progressElement.max = self.duration;
durationElement.textContent = formatTime(self.duration);
});
ttyPlayer.addEventListener("timeupdate", function() {
if (!skipChange) {
skipChange = true;
progressElement.value = self.currentTime;
self.updateCurrentTimeElement();
skipChange = false;
}
});
controlsElement.appendChild(play);
controlsElement.appendChild(currentTimeElement);
controlsElement.appendChild(progressElement);
controlsElement.appendChild(durationElement);
shadowRoot.appendChild(posterOverlay);
shadowRoot.appendChild(controlsElement);
self.menu = makeMenu(ttyPlayer, self);
}
setUp() {
var self = this;
var ttyPlayer = self.ttyPlayer;
var menu = self.menu;
self.isSetUp = true;
// Any things that required reading children or attributes of ttyPlayer must sit in here rather than the constructor.
if (menu) {
ttyPlayer.setAttribute("contextmenu", menu.id);
}
var rows = +ttyPlayer.getAttribute("rows");
var cols = +ttyPlayer.getAttribute("cols");
ttyPlayer["resize"](cols > 0 ? cols : ttyPlayer["cols"],
rows > 0 ? rows : ttyPlayer["rows"]);
self.terminal.on("resize", function() {
// ttyPlayer.rows and ttyPlayer.cols have changed, fire an appropriate event
self.fireSimpleEvent("resize");
});
self.defaultTitle = ttyPlayer.getAttribute("window-title") || "";
self.setShowPoster(true);
}
setShowPoster(newValue) {
// TODO: this is problematic because it doesn’t keep track of what
// poster is active, it just uses the current value of poster. We
// should probably store the value of poster and use it for
// removing it.
var self = this;
var oldValue = self.showPoster;
newValue = !!newValue;
var newPoster = classifyPosterURL(self.ttyPlayer["poster"]);
self.showPoster = !!newValue;
// We don’t show the overlay if there is an error
var showOverlay = newValue && !self.error;
self.posterOverlay.style.display = showOverlay ? "" : "none";
self.controlsElement.classList[showOverlay ? "add" : "remove"]("poster-visible");
self.progressElement.disabled = newValue;
self.controlsShownOrHidden();
if (oldValue === newValue && self.activePoster === newPoster) {
// No change to make
return;
}
// If we need to do anything special to remove a poster, here’s what we’ll do:
// if (oldValue) {
// switch (self.activePoster.type) {
// case "foo":
// …
// }
// }
self.activePoster = newPoster;
if (oldValue || newValue) {
// Yes, we’re missing the optimisation possibility of poster=npt:X
// changing to poster=npt:Y where Y > X. Seriously, adjusting
// poster *at all* is rare enough that I don’t care.
self.resetTerminal();
}
if (newValue) {
// Show the new poster
switch (newPoster.type) {
case "npt":
// We have an NPT poster to create.
self.resetTerminal();
var realShowPoster = function() {
if (newValue !== self.showPoster) {
// Sorry, you took too long and I don’t want to do anything now;
// something else is doing it.
return;
}
if (newValue) {
var currentTime = self.currentTime;
var semipaused = self.semipaused;
self.semipaused = true;
self.currentTime = newPoster.time;
self.nextDataIndex = 0;
self.render();
self.semipaused = semipaused;
self.currentTime = currentTime;
}
};
if (self.data) {
realShowPoster();
} else {
var loaded = function() {
self.ttyPlayer.removeEventListener("canplaythrough", loaded);
realShowPoster();
};
self.ttyPlayer.addEventListener("canplaythrough", loaded);
self.loadIfNotLoading();
}
break;
case "text":
self.resetTerminal();
self.terminal.write(newPoster.data);
}
}
}
/// Firing a simple event named e means that a trusted event with the name
/// e, which does not bubble (except where otherwise stated) and is not
/// cancelable (except where otherwise stated), and which uses the Event
/// interface, must be created and dispatched at the given target.
/// INCONSISTENCY: isTrusted = false
fireSimpleEvent(name) {
var event = document.createEvent("HTMLEvents");
event.initEvent(name, false, false);
var f = this.ttyPlayer["on" + name];
if (typeof f === "function") {
f(event);
}
this.ttyPlayer.dispatchEvent(event);
}
controlsShownOrHidden() {
var self = this;
var terminalElement = self.terminal.element;
var menu = self.menu;
var touchstartHandler = self.touchstartHandler;
self.updateCurrentTimeElement();
if (menu) {
menu.onControlsShownOrHidden();
}
if (self.ttyPlayer.controls) {
// It’s subjective, but I’d like *clicking* on the terminal (probably desktop) to do nothing, but *tapping* (probably mobile) to trigger play/pause, iff [controls].
var startTouch;
terminalElement.addEventListener('touchstart', touchstartHandler || (self.touchstartHandler = event => {
// Simplifying assumption: only one finger is in use.
if (startTouch) {
return;
}
startTouch = event.touches.item(0);
// If the touch lasts more than 300ms, it’s more a long press than a tap.
const cancelTimeout = setTimeout(cancel, 300);
function move(event) {
// If the finger moves more than five pixels from where it started, it’s more a swipe than a tap.
var touch = event.touches.item(0);
if (Math.pow(touch.clientX - startTouch.clientX, 2) + Math.pow(touch.clientY - startTouch.clientY, 2) > 25) {
cancel();
}
}
function end(event) {
// TODO: in this case particularly it’d be nice to flash a play/pause icon on screen briefly, like YouTube does, as an affordance/confirmation that it happened.
// This isn’t quite so urgent because the touch probably causes the controls to be shown.
self.playOrPause();
cancel();
// Don’t follow through with a click event (it’s unlikely to be harmful, but isn’t necessary.)
event.preventDefault();
}
function cancel() {
startTouch = null;
clearTimeout(cancelTimeout);
terminalElement.removeEventListener('touchmove', move);
terminalElement.removeEventListener('touchend', end);
terminalElement.removeEventListener('touchcancel', cancel);
}
terminalElement.addEventListener('touchmove', move);
terminalElement.addEventListener('touchend', end);
terminalElement.addEventListener('touchcancel', cancel);
}));
} else if (touchstartHandler) {
terminalElement.removeEventListener('touchstart', touchstartHandler);
}
}
updateCurrentTimeElement() {
this.currentTimeElement.textContent = formatTime(this.currentTime);
var left = this.progressElement.offsetLeft - (this.currentTimeElement.offsetWidth / 2);
if (!isNaN(this.duration)) {
left += this.currentTime / this.duration * this.progressElement.offsetWidth;
}
this.currentTimeElement.style.left = left + "px";
}
playOrPause() {
if (this.paused) {
this.ttyPlayer["play"]();
} else {
this.ttyPlayer["pause"]();
}
}
render() {
// Should the currently rendered frame (next - 1) be drawn?
if (this.nextDataIndex > 0 && this.data[this.nextDataIndex - 1][1] > this.currentTime) {
// No, but undoing isn’t possible, so we must replay from the start.
// This is highly inefficient; for large scripts it’s utterly untenable.
this.resetTerminal();
this.nextDataIndex = 0;
}
while (this.nextDataIndex < this.data.length && this.data[this.nextDataIndex][1] <= this.currentTime) {
this.terminal.write(this.data[this.nextDataIndex][0]);
this.nextDataIndex++;
}
if (this.semipaused) {
return;
}
// Have we reached the end? Let’s stop.
if ((this.currentTime >= this.duration && this.playbackRate > 0) ||
(this.currentTime <= 0 && this.playbackRate < 0)) {
if (this.ttyPlayer["loop"]) {
this.ttyPlayer["currentTime"] = this.playbackRate > 0 ? 0 : this.duration;
} else {
this.fireSimpleEvent("timeupdate");
this.ttyPlayer["pause"]();
this.fireSimpleEvent("ended");
}
} else {
// Do we need to fire a timeupdate event? We should do them every 66–350ms; Firefox does 250 for video, but because the average length is going to be shorter and because I can, I’m going for 100ms.
var time = +new Date();
if (time - this.lastTimeUpdate >= TIME_UPDATE_FREQUENCY) {
this.lastTimeUpdate = time;
this.fireSimpleEvent("timeupdate");
}
}
}
resetTerminal() {
this.terminal.reset();
this.ttyPlayer["title"] = this.defaultTitle;
}
loadIfNotLoading() {
if (this.networkState < NETWORK_LOADING) {
this.mediaLoadAlgorithm();
}
}
mediaLoadAlgorithm() {
this.resetTerminal();
// > The media load algorithm consists of the following steps.
// > 1. Abort any already-running instance of the resource selection
// > algorithm for this element.
if (this.resourceFetchXHR) {
this.resourceFetchXHR.abort();
}
// > 2. If there are any tasks from the media element's media element
// > event task source in one of the task queues, then remove those
// > tasks.