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
|
// ==========================================================================
// Plyr
// plyr.js v3.0.0
// https://github.com/sampotts/plyr
// License: The MIT License (MIT)
// ==========================================================================
/* global jQuery */
import defaults from './defaults';
import types from './types';
import support from './support';
import utils from './utils';
import captions from './captions';
import controls from './controls';
import fullscreen from './fullscreen';
import media from './media';
import storage from './storage';
import source from './source';
import ui from './ui';
// Globals
let scrollPosition = {
x: 0,
y: 0,
};
// Plyr instance
class Plyr {
constructor(target, options) {
this.timers = {};
this.ready = false;
// Set the media element
this.media = target;
// String selector passed
if (utils.is.string(this.media)) {
this.media = document.querySelectorAll(this.media);
}
// jQuery, NodeList or Array passed, use first element
if (
(window.jQuery && this.media instanceof jQuery) ||
utils.is.nodeList(this.media) ||
utils.is.array(this.media)
) {
// eslint-disable-next-line
this.media = this.media[0];
}
// Set config
this.config = utils.extend(
{},
defaults,
options,
(() => {
try {
return JSON.parse(this.media.getAttribute('data-plyr'));
} catch (e) {
return null;
}
})()
);
// Elements cache
this.elements = {
container: null,
buttons: {},
display: {},
progress: {},
inputs: {},
settings: {
menu: null,
panes: {},
tabs: {},
},
captions: null,
};
// Captions
this.captions = {
enabled: null,
tracks: null,
currentTrack: null,
};
// Fullscreen
this.fullscreen = {
active: false,
};
// Options
this.options = {
speed: [],
quality: [],
};
// Debugging
this.log = () => {};
this.warn = () => {};
this.error = () => {};
if (this.config.debug && 'console' in window) {
this.log = console.log; // eslint-disable-line
this.warn = console.warn; // eslint-disable-line
this.error = console.error; // eslint-disable-line
this.log('Debugging enabled');
}
// Log config options and support
this.log('Config', this.config);
this.log('Support', support);
// We need an element to setup
if (this.media === null || utils.is.undefined(this.media) || !utils.is.htmlElement(this.media)) {
this.error('Setup failed: no suitable element passed');
return;
}
// Bail if the element is initialized
if (this.media.plyr) {
this.warn('Target already setup');
return;
}
// Bail if not enabled
if (!this.config.enabled) {
this.error('Setup failed: disabled by config');
return;
}
// Bail if disabled or no basic support
// You may want to disable certain UAs etc
if (!support.check().api) {
this.error('Setup failed: no support');
return;
}
// Cache original element state for .destroy()
this.elements.original = this.media.cloneNode(true);
// Set media type based on tag or data attribute
// Supported: video, audio, vimeo, youtube
const type = this.media.tagName.toLowerCase();
// Different setup based on type
switch (type) {
// TODO: Handle passing an iframe for true progressive enhancement
// case 'iframe':
case 'div':
this.type = this.media.getAttribute('data-type');
this.embedId = this.media.getAttribute('data-video-id');
if (utils.is.empty(this.type)) {
this.error('Setup failed: embed type missing');
return;
}
if (utils.is.empty(this.embedId)) {
this.error('Setup failed: video id missing');
return;
}
// Clean up
this.media.removeAttribute('data-type');
this.media.removeAttribute('data-video-id');
break;
case 'video':
case 'audio':
this.type = type;
if (this.media.getAttribute('crossorigin') !== null) {
this.config.crossorigin = true;
}
if (this.media.getAttribute('autoplay') !== null) {
this.config.autoplay = true;
}
if (this.media.getAttribute('playsinline') !== null) {
this.config.inline = true;
}
if (this.media.getAttribute('muted') !== null) {
this.config.muted = true;
}
if (this.media.getAttribute('loop') !== null) {
this.config.loop.active = true;
}
break;
default:
this.error('Setup failed: unsupported type');
return;
}
// Sniff out the browser
this.browser = utils.getBrowser();
// Load saved settings from localStorage
this.storage = storage.setup.call(this);
// Check for support again but with type
this.supported = support.check(this.type, this.config.inline);
// If no support for even API, bail
if (!this.supported.api) {
this.error('Setup failed: no support');
return;
}
// Store reference
this.media.plyr = this;
// Wrap media
this.elements.container = utils.createElement('div');
utils.wrap(this.media, this.elements.container);
// Add style hook
ui.addStyleHook.call(this);
// Setup media
media.setup.call(this);
// Listen for events if debugging
if (this.config.debug) {
utils.on(this.elements.container, this.config.events.join(' '), event => {
this.log(`event: ${event.type}`);
});
}
// Setup interface
// If embed but not fully supported, build interface now to avoid flash of controls
if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {
ui.build.call(this);
}
}
// API
// ---------------------------------------
get isHTML5() {
return types.html5.includes(this.type);
}
get isEmbed() {
return types.embed.includes(this.type);
}
// Play
play() {
if ('play' in this.media) {
this.media.play();
}
// Allow chaining
return this;
}
// Pause
pause() {
if ('pause' in this.media) {
this.media.pause();
}
// Allow chaining
return this;
}
// Toggle playback
togglePlay(toggle) {
// True toggle if nothing passed
if ((!utils.is.boolean(toggle) && this.media.paused) || toggle) {
return this.play();
}
return this.pause();
}
// Stop
stop() {
return this.restart().pause();
}
// Restart
restart() {
this.currentTime = 0;
return this;
}
// Rewind
rewind(seekTime) {
this.currentTime = Math.min(
this.currentTime - (utils.is.number(seekTime) ? seekTime : this.config.seekTime),
0
);
return this;
}
// Fast forward
forward(seekTime) {
this.currentTime = Math.max(
this.currentTime + (utils.is.number(seekTime) ? seekTime : this.config.seekTime),
this.duration
);
return this;
}
// Seek to time
// The input parameter can be an event or a number
set currentTime(input) {
let targetTime = 0;
if (utils.is.number(input)) {
targetTime = input;
}
// Normalise targetTime
if (targetTime < 0) {
targetTime = 0;
} else if (targetTime > this.duration) {
targetTime = this.duration;
}
// Set
this.media.currentTime = targetTime.toFixed(4);
// Logging
this.log(`Seeking to ${this.currentTime} seconds`);
}
get currentTime() {
return Number(this.media.currentTime);
}
// Duration
get duration() {
// Faux duration set via config
const fauxDuration = parseInt(this.config.duration, 10);
// True duration
const realDuration = Number(this.media.duration);
// If custom duration is funky, use regular duration
return !Number.isNaN(fauxDuration) ? fauxDuration : realDuration;
}
// Volume
set volume(value) {
let volume = value;
const max = 1;
const min = 0;
const isSet = !utils.is.undefined(volume);
if (utils.is.string(volume)) {
volume = parseFloat(volume);
}
// Load volume from storage if no value specified
if (!utils.is.number(volume)) {
({ volume } = this.storage);
}
// Use config if all else fails
if (!utils.is.number(volume)) {
({ volume } = this.config);
}
// Maximum is volumeMax
if (volume > max) {
volume = max;
}
// Minimum is volumeMin
if (volume < min) {
volume = min;
}
// Set the player volume
this.media.volume = volume;
// Toggle muted state
if (volume === 0) {
this.toggleMute(true);
} else if (this.media.muted && isSet) {
this.toggleMute();
}
return this;
}
get volume() {
return this.media.volume;
}
// Increase volume
increaseVolume(step) {
const volume = this.media.muted ? 0 : this.media.volume;
return this.setVolume(volume + utils.is.number(step) ? step : 1);
}
// Decrease volume
decreaseVolume(step) {
const volume = this.media.muted ? 0 : this.media.volume;
return this.setVolume(volume - utils.is.number(step) ? step : 1);
}
// Toggle mute
toggleMute(mute) {
// If the method is called without parameter, toggle based on current value
const toggle = utils.is.boolean(mute) ? mute : !this.media.muted;
// Set button state
utils.toggleState(this.elements.buttons.mute, toggle);
// Set mute on the player
this.media.muted = toggle;
// If volume is 0 after unmuting, restore default volume
if (!this.media.muted && this.media.volume === 0) {
this.setVolume(this.config.volume);
}
// Embeds
if (this.isEmbed) {
switch (this.type) {
case 'youtube':
this.embed[this.media.muted ? 'mute' : 'unMute']();
break;
case 'vimeo':
this.embed.setVolume(this.media.muted ? 0 : this.config.volume);
break;
default:
break;
}
// Trigger volumechange for embeds
utils.dispatchEvent.call(this, this.media, 'volumechange');
}
return this;
}
// Playback speed
set speed(input) {
// Load speed from storage or default value
let speed = utils.is.number(input)
? input
: parseFloat(this.storage.speed || this.speed.selected || this.config.speed.default);
// Set min/max
if (speed < 0.1) {
speed = 0.1;
}
if (speed > 2.0) {
speed = 2.0;
}
if (!this.config.speed.options.includes(speed)) {
this.warn(`Unsupported speed (${speed})`);
return;
}
// Set media speed
this.media.playbackRate = speed;
}
get speed() {
return this.media.playbackRate;
}
// Set playback quality
set quality(input) {
// Load speed from storage or default value
const quality = utils.is.string(input)
? input
: parseFloat(this.storage.quality || this.config.quality.selected);
if (!this.config.quality.options.includes(quality)) {
this.warn(`Unsupported quality option (${quality})`);
return;
}
// Set media speed
switch (this.type) {
case 'youtube':
this.utils.dispatchEvent.call(this, this.media, 'qualityrequested', false, {
quality,
});
this.embed.setPlaybackQuality(quality);
break;
default:
this.warn('Quality options are only available for YouTube');
break;
}
}
get quality() {
// Set media speed
switch (this.type) {
case 'youtube':
return this.embed.getPlaybackQuality();
default:
this.warn('Quality options are only available for YouTube');
return null;
}
}
// Toggle loop
// TODO: Finish logic
// TODO: Set the indicator on load as user may pass loop as config
/* loop(input) {
// Set default to be a true toggle
const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';
switch (type) {
case 'start':
if (this.config.loop.end && this.config.loop.end <= this.currentTime) {
this.config.loop.end = null;
}
this.config.loop.start = this.currentTime;
// this.config.loop.indicator.start = this.elements.display.played.value;
break;
case 'end':
if (this.config.loop.start >= this.currentTime) {
return this;
}
this.config.loop.end = this.currentTime;
// this.config.loop.indicator.end = this.elements.display.played.value;
break;
case 'all':
this.config.loop.start = 0;
this.config.loop.end = this.duration - 2;
this.config.loop.indicator.start = 0;
this.config.loop.indicator.end = 100;
break;
case 'toggle':
if (this.config.loop.active) {
this.config.loop.start = 0;
this.config.loop.end = null;
} else {
this.config.loop.start = 0;
this.config.loop.end = this.duration - 2;
}
break;
default:
this.config.loop.start = 0;
this.config.loop.end = null;
break;
}
// Allow chaining
return this;
} */
// Media source
set src(input) {
source.change.call(this, input);
}
get src() {
let url;
switch (this.type) {
case 'youtube':
url = this.embed.getVideoUrl();
break;
case 'vimeo':
this.embed.getVideoUrl.then(value => {
url = value;
});
break;
default:
url = this.media.currentSrc;
break;
}
return url;
}
// Poster image
set poster(input) {
if (this.type !== 'video') {
this.warn('Poster can only be set on HTML5 video');
return;
}
if (utils.is.string(input)) {
this.media.setAttribute('poster', input);
}
}
get poster() {
if (this.type !== 'video') {
return null;
}
return this.media.getAttribute('poster');
}
// Toggle captions
toggleCaptions(input) {
// If there's no full support, or there's no caption toggle
if (!this.supported.ui || !this.elements.buttons.captions) {
return this;
}
// If the method is called without parameter, toggle based on current value
const show = utils.is.boolean(input)
? input
: this.elements.container.className.indexOf(this.config.classNames.captions.active) === -1;
// Nothing to change...
if (this.captions.enabled === show) {
return this;
}
// Set global
this.captions.enabled = show;
// Toggle state
utils.toggleState(this.elements.buttons.captions, this.captions.enabled);
// Add class hook
utils.toggleClass(this.elements.container, this.config.classNames.captions.active, this.captions.enabled);
// Trigger an event
utils.dispatchEvent.call(this, this.media, this.captions.enabled ? 'captionsenabled' : 'captionsdisabled');
// Allow chaining
return this;
}
// Caption language
set language(input) {
const player = this;
// Nothing specified
if (utils.is.empty(input)) {
this.toggleCaptions(false);
return player;
}
// Normalize
const language = input.toLowerCase();
// If nothing to change, bail
if (this.captions.language === language) {
return player;
}
// Reset UI
this.toggleCaptions(true);
// Update config
this.captions.language = language;
// Trigger an event
utils.dispatchEvent.call(this, this.media, 'captionchange');
// Clear caption
captions.setCaption.call(this);
// Re-run setup
captions.setup.call(this);
// Allow chaining
return this;
}
get language() {
return this.captions.language;
}
// Toggle fullscreen
// Requires user input event
toggleFullscreen(event) {
// Check for native support
if (fullscreen.enabled) {
// If it's a fullscreen change event, update the UI
if (utils.is.event(event) && event.type === fullscreen.eventType) {
this.fullscreen.active = fullscreen.isFullScreen(this.elements.container);
} else {
// Else it's a user request to enter or exit
if (!this.fullscreen.active) {
// Request full screen
fullscreen.requestFullScreen(this.elements.container);
} else {
// Bail from fullscreen
fullscreen.cancelFullScreen();
}
// Check if we're actually full screen (it could fail)
this.fullscreen.active = fullscreen.isFullScreen(this.elements.container);
return this;
}
} else {
// Otherwise, it's a simple toggle
this.fullscreen.active = !this.fullscreen.active;
// Add class hook
utils.toggleClass(
this.elements.container,
this.config.classNames.fullscreen.fallback,
this.fullscreen.active
);
// Make sure we don't lose scroll position
if (this.fullscreen.active) {
scrollPosition = {
x: window.pageXOffset || 0,
y: window.pageYOffset || 0,
};
} else {
window.scrollTo(scrollPosition.x, scrollPosition.y);
}
// Bind/unbind escape key
document.body.style.overflow = this.fullscreen.active ? 'hidden' : '';
}
// Set button state
if (this.elements.buttons && this.elements.buttons.fullscreen) {
utils.toggleState(this.elements.buttons.fullscreen, this.fullscreen.active);
}
// Trigger an event
utils.dispatchEvent.call(this, this.media, this.fullscreen.active ? 'enterfullscreen' : 'exitfullscreen');
return this;
}
// Toggle picture-in-picture
// TODO: update player with state, support, enabled
// TODO: detect outside changes
togglePictureInPicture(input) {
const player = this;
const states = {
pip: 'picture-in-picture',
inline: 'inline',
};
// Bail if no support
if (!support.pip) {
return player;
}
// Toggle based on current state if not passed
const toggle = utils.is.boolean(input) ? input : this.media.webkitPresentationMode === states.inline;
// Toggle based on current state
this.media.webkitSetPresentationMode(toggle ? states.pip : states.inline);
return this;
}
// Trigger airplay
// TODO: update player with state, support, enabled
airPlay() {
// Bail if no support
if (!support.airplay) {
return this;
}
// Show dialog
this.media.webkitShowPlaybackTargetPicker();
return this;
}
// Show the player controls in fullscreen mode
toggleControls(toggle) {
const player = this;
// We need controls of course...
if (!utils.is.htmlElement(this.elements.controls)) {
return player;
}
// Don't hide if config says not to, it's audio, or not ready or loading
if (!this.supported.ui || !this.config.hideControls || this.type === 'audio') {
return player;
}
let delay = 0;
let show = toggle;
let isEnterFullscreen = false;
const loading = utils.hasClass(this.elements.container, this.config.classNames.loading);
// Default to false if no boolean
if (!utils.is.boolean(toggle)) {
if (utils.is.event(toggle)) {
// Is the enter fullscreen event
isEnterFullscreen = toggle.type === 'enterfullscreen';
// Whether to show controls
show = ['mousemove', 'touchstart', 'mouseenter', 'focus'].includes(toggle.type);
// Delay hiding on move events
if (['mousemove', 'touchmove'].includes(toggle.type)) {
delay = 2000;
}
// Delay a little more for keyboard users
if (toggle.type === 'focus') {
delay = 3000;
}
} else {
show = utils.hasClass(this.elements.container, this.config.classNames.hideControls);
}
}
// Clear timer every movement
window.clearTimeout(this.timers.hover);
// If the mouse is not over the controls, set a timeout to hide them
if (show || this.media.paused || loading) {
// Check if controls toggled
const toggled = utils.toggleClass(this.elements.container, this.config.classNames.hideControls, false);
// Trigger event
if (toggled) {
utils.dispatchEvent.call(this, this.media, 'controlsshown');
}
// Always show controls when paused or if touch
if (this.media.paused || loading) {
return player;
}
// Delay for hiding on touch
if (support.touch) {
delay = 3000;
}
}
// If toggle is false or if we're playing (regardless of toggle),
// then set the timer to hide the controls
if (!show || !this.media.paused) {
this.timers.hover = window.setTimeout(() => {
// If the mouse is over the controls (and not entering fullscreen), bail
if ((this.elements.controls.pressed || this.elements.controls.hover) && !isEnterFullscreen) {
return;
}
// Check if controls toggled
const toggled = utils.toggleClass(this.elements.container, this.config.classNames.hideControls, true);
// Trigger event and close menu
if (toggled) {
utils.dispatchEvent.call(this, this.media, 'controlshidden');
if (this.config.controls.includes('settings') && !utils.is.empty(this.config.settings)) {
controls.toggleMenu.call(this, false);
}
}
}, delay);
}
return this;
}
// Event listeners
on(event, callback) {
utils.on(this.elements.container, event, callback);
return this;
}
off(event, callback) {
utils.off(this.elements.container, event, callback);
return this;
}
// Check for support
supports(mimeType) {
return support.mime(this, mimeType);
}
// Destroy an instance
// Event listeners are removed when elements are removed
// http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory
destroy(callback, soft = false) {
const done = () => {
// Reset overflow (incase destroyed while in fullscreen)
document.body.style.overflow = '';
// GC for embed
this.embed = null;
// If it's a soft destroy, make minimal changes
if (soft) {
utils.removeElement(this.elements.captions);
utils.removeElement(this.elements.controls);
utils.removeElement(this.elements.wrapper);
// Clear for GC
this.elements.captions = null;
this.elements.controls = null;
this.elements.wrapper = null;
// Callback
if (utils.is.function(callback)) {
callback();
}
} else {
// Replace the container with the original element provided
const parent = this.elements.container.parentNode;
if (utils.is.htmlElement(parent)) {
parent.replaceChild(this.elements.original, this.elements.container);
}
// Event
utils.dispatchEvent.call(this, this.elements.original, 'destroyed', true);
// Callback
if (utils.is.function(callback)) {
callback.call(this.elements.original);
}
// Clear for GC
this.elements = null;
}
};
// Type specific stuff
switch (this.type) {
case 'youtube':
// Clear timers
window.clearInterval(this.timers.buffering);
window.clearInterval(this.timers.playing);
// Destroy YouTube API
this.embed.destroy();
// Clean up
done();
break;
case 'vimeo':
// Destroy Vimeo API
// then clean up (wait, to prevent postmessage errors)
this.embed.unload().then(done);
// Vimeo does not always return
window.setTimeout(done, 200);
break;
case 'video':
case 'audio':
// Restore native video controls
ui.toggleNativeControls.call(this, true);
// Clean up
done();
break;
default:
break;
}
}
}
export default Plyr;
|