-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
component.js
2061 lines (1807 loc) · 63.7 KB
/
component.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
/**
* Player Component - Base class for all UI objects
*
* @file component.js
*/
import document from 'global/document';
import window from 'global/window';
import evented from './mixins/evented';
import stateful from './mixins/stateful';
import * as Dom from './utils/dom.js';
import * as Fn from './utils/fn.js';
import * as Guid from './utils/guid.js';
import {toTitleCase, toLowerCase} from './utils/str.js';
import {merge} from './utils/obj.js';
/** @import Player from './player' */
/**
* A callback to be called if and when the component is ready.
* `this` will be the Component instance.
*
* @callback ReadyCallback
* @returns {void}
*/
/**
* Base class for all UI Components.
* Components are UI objects which represent both a javascript object and an element
* in the DOM. They can be children of other components, and can have
* children themselves.
*
* Components can also use methods from {@link EventTarget}
*/
class Component {
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of component options.
*
* @param {Object[]} [options.children]
* An array of children objects to initialize this component with. Children objects have
* a name property that will be used if more than one component of the same type needs to be
* added.
*
* @param {string} [options.className]
* A class or space separated list of classes to add the component
*
* @param {ReadyCallback} [ready]
* Function that gets called when the `Component` is ready.
*/
constructor(player, options, ready) {
// The component might be the player itself and we can't pass `this` to super
if (!player && this.play) {
this.player_ = player = this; // eslint-disable-line
} else {
this.player_ = player;
}
this.isDisposed_ = false;
// Hold the reference to the parent component via `addChild` method
this.parentComponent_ = null;
// Make a copy of prototype.options_ to protect against overriding defaults
this.options_ = merge({}, this.options_);
// Updated options with supplied options
options = this.options_ = merge(this.options_, options);
// Get ID from options or options element if one is supplied
this.id_ = options.id || (options.el && options.el.id);
// If there was no ID from the options, generate one
if (!this.id_) {
// Don't require the player ID function in the case of mock players
const id = player && player.id && player.id() || 'no_player';
this.id_ = `${id}_component_${Guid.newGUID()}`;
}
this.name_ = options.name || null;
// Create element if one wasn't provided in options
if (options.el) {
this.el_ = options.el;
} else if (options.createEl !== false) {
this.el_ = this.createEl();
}
if (options.className && this.el_) {
options.className.split(' ').forEach(c => this.addClass(c));
}
// Remove the placeholder event methods. If the component is evented, the
// real methods are added next
['on', 'off', 'one', 'any', 'trigger'].forEach(fn => {
this[fn] = undefined;
});
// if evented is anything except false, we want to mixin in evented
if (options.evented !== false) {
// Make this an evented object and use `el_`, if available, as its event bus
evented(this, {eventBusKey: this.el_ ? 'el_' : null});
this.handleLanguagechange = this.handleLanguagechange.bind(this);
this.on(this.player_, 'languagechange', this.handleLanguagechange);
}
stateful(this, this.constructor.defaultState);
this.children_ = [];
this.childIndex_ = {};
this.childNameIndex_ = {};
this.setTimeoutIds_ = new Set();
this.setIntervalIds_ = new Set();
this.rafIds_ = new Set();
this.namedRafs_ = new Map();
this.clearingTimersOnDispose_ = false;
// Add any child components in options
if (options.initChildren !== false) {
this.initChildren();
}
// Don't want to trigger ready here or it will go before init is actually
// finished for all children that run this constructor
this.ready(ready);
if (options.reportTouchActivity !== false) {
this.enableTouchActivity();
}
}
// `on`, `off`, `one`, `any` and `trigger` are here so tsc includes them in definitions.
// They are replaced or removed in the constructor
/**
* Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
* function that will get called when an event with a certain name gets triggered.
*
* @param {string|string[]} type
* An event name or an array of event names.
*
* @param {Function} fn
* The function to call with `EventTarget`s
*/
/* start-delete-from-build */
on(type, fn) {}
/* end-delete-from-build */
/**
* Removes an `event listener` for a specific event from an instance of `EventTarget`.
* This makes it so that the `event listener` will no longer get called when the
* named event happens.
*
* @param {string|string[]} type
* An event name or an array of event names.
*
* @param {Function} [fn]
* The function to remove. If not specified, all listeners managed by Video.js will be removed.
*/
/* start-delete-from-build */
off(type, fn) {}
/* end-delete-from-build */
/**
* This function will add an `event listener` that gets triggered only once. After the
* first trigger it will get removed. This is like adding an `event listener`
* with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
*
* @param {string|string[]} type
* An event name or an array of event names.
*
* @param {Function} fn
* The function to be called once for each event name.
*/
/* start-delete-from-build */
one(type, fn) {}
/* end-delete-from-build */
/**
* This function will add an `event listener` that gets triggered only once and is
* removed from all events. This is like adding an array of `event listener`s
* with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
* first time it is triggered.
*
* @param {string|string[]} type
* An event name or an array of event names.
*
* @param {Function} fn
* The function to be called once for each event name.
*/
/* start-delete-from-build */
any(type, fn) {}
/* end-delete-from-build */
/**
* This function causes an event to happen. This will then cause any `event listeners`
* that are waiting for that event, to get called. If there are no `event listeners`
* for an event then nothing will happen.
*
* If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
* Trigger will also call the `on` + `uppercaseEventName` function.
*
* Example:
* 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
* `onClick` if it exists.
*
* @param {string|Event|Object} event
* The name of the event, an `Event`, or an object with a key of type set to
* an event name.
*
* @param {Object} [hash]
* Optionally extra argument to pass through to an event listener
*/
/* start-delete-from-build */
trigger(event, hash) {}
/* end-delete-from-build */
/**
* Dispose of the `Component` and all child components.
*
* @fires Component#dispose
*
* @param {Object} options
* @param {Element} options.originalEl element with which to replace player element
*/
dispose(options = {}) {
// Bail out if the component has already been disposed.
if (this.isDisposed_) {
return;
}
if (this.readyQueue_) {
this.readyQueue_.length = 0;
}
/**
* Triggered when a `Component` is disposed.
*
* @event Component#dispose
* @type {Event}
*
* @property {boolean} [bubbles=false]
* set to false so that the dispose event does not
* bubble up
*/
this.trigger({type: 'dispose', bubbles: false});
this.isDisposed_ = true;
// Dispose all children.
if (this.children_) {
for (let i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i].dispose) {
this.children_[i].dispose();
}
}
}
// Delete child references
this.children_ = null;
this.childIndex_ = null;
this.childNameIndex_ = null;
this.parentComponent_ = null;
if (this.el_) {
// Remove element from DOM
if (this.el_.parentNode) {
if (options.restoreEl) {
this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
} else {
this.el_.parentNode.removeChild(this.el_);
}
}
this.el_ = null;
}
// remove reference to the player after disposing of the element
this.player_ = null;
}
/**
* Determine whether or not this component has been disposed.
*
* @return {boolean}
* If the component has been disposed, will be `true`. Otherwise, `false`.
*/
isDisposed() {
return Boolean(this.isDisposed_);
}
/**
* Return the {@link Player} that the `Component` has attached to.
*
* @return {Player}
* The player that this `Component` has attached to.
*/
player() {
return this.player_;
}
/**
* Deep merge of options objects with new options.
* > Note: When both `obj` and `options` contain properties whose values are objects.
* The two properties get merged using {@link module:obj.merge}
*
* @param {Object} obj
* The object that contains new options.
*
* @return {Object}
* A new object of `this.options_` and `obj` merged together.
*/
options(obj) {
if (!obj) {
return this.options_;
}
this.options_ = merge(this.options_, obj);
return this.options_;
}
/**
* Get the `Component`s DOM element
*
* @return {Element}
* The DOM element for this `Component`.
*/
el() {
return this.el_;
}
/**
* Create the `Component`s DOM element.
*
* @param {string} [tagName]
* Element's DOM node type. e.g. 'div'
*
* @param {Object} [properties]
* An object of properties that should be set.
*
* @param {Object} [attributes]
* An object of attributes that should be set.
*
* @return {Element}
* The element that gets created.
*/
createEl(tagName, properties, attributes) {
return Dom.createEl(tagName, properties, attributes);
}
/**
* Localize a string given the string in english.
*
* If tokens are provided, it'll try and run a simple token replacement on the provided string.
* The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
*
* If a `defaultValue` is provided, it'll use that over `string`,
* if a value isn't found in provided language files.
* This is useful if you want to have a descriptive key for token replacement
* but have a succinct localized string and not require `en.json` to be included.
*
* Currently, it is used for the progress bar timing.
* ```js
* {
* "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
* }
* ```
* It is then used like so:
* ```js
* this.localize('progress bar timing: currentTime={1} duration{2}',
* [this.player_.currentTime(), this.player_.duration()],
* '{1} of {2}');
* ```
*
* Which outputs something like: `01:23 of 24:56`.
*
*
* @param {string} string
* The string to localize and the key to lookup in the language files.
* @param {string[]} [tokens]
* If the current item has token replacements, provide the tokens here.
* @param {string} [defaultValue]
* Defaults to `string`. Can be a default value to use for token replacement
* if the lookup key is needed to be separate.
*
* @return {string}
* The localized string or if no localization exists the english string.
*/
localize(string, tokens, defaultValue = string) {
const code = this.player_.language && this.player_.language();
const languages = this.player_.languages && this.player_.languages();
const language = languages && languages[code];
const primaryCode = code && code.split('-')[0];
const primaryLang = languages && languages[primaryCode];
let localizedString = defaultValue;
if (language && language[string]) {
localizedString = language[string];
} else if (primaryLang && primaryLang[string]) {
localizedString = primaryLang[string];
}
if (tokens) {
localizedString = localizedString.replace(/\{(\d+)\}/g, function(match, index) {
const value = tokens[index - 1];
let ret = value;
if (typeof value === 'undefined') {
ret = match;
}
return ret;
});
}
return localizedString;
}
/**
* Handles language change for the player in components. Should be overridden by sub-components.
*
* @abstract
*/
handleLanguagechange() {}
/**
* Return the `Component`s DOM element. This is where children get inserted.
* This will usually be the the same as the element returned in {@link Component#el}.
*
* @return {Element}
* The content element for this `Component`.
*/
contentEl() {
return this.contentEl_ || this.el_;
}
/**
* Get this `Component`s ID
*
* @return {string}
* The id of this `Component`
*/
id() {
return this.id_;
}
/**
* Get the `Component`s name. The name gets used to reference the `Component`
* and is set during registration.
*
* @return {string}
* The name of this `Component`.
*/
name() {
return this.name_;
}
/**
* Get an array of all child components
*
* @return {Array}
* The children
*/
children() {
return this.children_;
}
/**
* Returns the child `Component` with the given `id`.
*
* @param {string} id
* The id of the child `Component` to get.
*
* @return {Component|undefined}
* The child `Component` with the given `id` or undefined.
*/
getChildById(id) {
return this.childIndex_[id];
}
/**
* Returns the child `Component` with the given `name`.
*
* @param {string} name
* The name of the child `Component` to get.
*
* @return {Component|undefined}
* The child `Component` with the given `name` or undefined.
*/
getChild(name) {
if (!name) {
return;
}
return this.childNameIndex_[name];
}
/**
* Returns the descendant `Component` following the givent
* descendant `names`. For instance ['foo', 'bar', 'baz'] would
* try to get 'foo' on the current component, 'bar' on the 'foo'
* component and 'baz' on the 'bar' component and return undefined
* if any of those don't exist.
*
* @param {...string[]|...string} names
* The name of the child `Component` to get.
*
* @return {Component|undefined}
* The descendant `Component` following the given descendant
* `names` or undefined.
*/
getDescendant(...names) {
// flatten array argument into the main array
names = names.reduce((acc, n) => acc.concat(n), []);
let currentChild = this;
for (let i = 0; i < names.length; i++) {
currentChild = currentChild.getChild(names[i]);
if (!currentChild || !currentChild.getChild) {
return;
}
}
return currentChild;
}
/**
* Adds an SVG icon element to another element or component.
*
* @param {string} iconName
* The name of icon. A list of all the icon names can be found at 'sandbox/svg-icons.html'
*
* @param {Element} [el=this.el()]
* Element to set the title on. Defaults to the current Component's element.
*
* @return {Element}
* The newly created icon element.
*/
setIcon(iconName, el = this.el()) {
// TODO: In v9 of video.js, we will want to remove font icons entirely.
// This means this check, as well as the others throughout the code, and
// the unecessary CSS for font icons, will need to be removed.
// See https://github.com/videojs/video.js/pull/8260 as to which components
// need updating.
if (!this.player_.options_.experimentalSvgIcons) {
return;
}
const xmlnsURL = 'http://www.w3.org/2000/svg';
// The below creates an element in the format of:
// <span><svg><use>....</use></svg></span>
const iconContainer = Dom.createEl('span', {
className: 'vjs-icon-placeholder vjs-svg-icon'
}, {'aria-hidden': 'true'});
const svgEl = document.createElementNS(xmlnsURL, 'svg');
svgEl.setAttributeNS(null, 'viewBox', '0 0 512 512');
const useEl = document.createElementNS(xmlnsURL, 'use');
svgEl.appendChild(useEl);
useEl.setAttributeNS(null, 'href', `#vjs-icon-${iconName}`);
iconContainer.appendChild(svgEl);
// Replace a pre-existing icon if one exists.
if (this.iconIsSet_) {
el.replaceChild(iconContainer, el.querySelector('.vjs-icon-placeholder'));
} else {
el.appendChild(iconContainer);
}
this.iconIsSet_ = true;
return iconContainer;
}
/**
* Add a child `Component` inside the current `Component`.
*
* @param {string|Component} child
* The name or instance of a child to add.
*
* @param {Object} [options={}]
* The key/value store of options that will get passed to children of
* the child.
*
* @param {number} [index=this.children_.length]
* The index to attempt to add a child into.
*
*
* @return {Component}
* The `Component` that gets added as a child. When using a string the
* `Component` will get created by this process.
*/
addChild(child, options = {}, index = this.children_.length) {
let component;
let componentName;
// If child is a string, create component with options
if (typeof child === 'string') {
componentName = toTitleCase(child);
const componentClassName = options.componentClass || componentName;
// Set name through options
options.name = componentName;
// Create a new object & element for this controls set
// If there's no .player_, this is a player
const ComponentClass = Component.getComponent(componentClassName);
if (!ComponentClass) {
throw new Error(`Component ${componentClassName} does not exist`);
}
// data stored directly on the videojs object may be
// misidentified as a component to retain
// backwards-compatibility with 4.x. check to make sure the
// component class can be instantiated.
if (typeof ComponentClass !== 'function') {
return null;
}
component = new ComponentClass(this.player_ || this, options);
// child is a component instance
} else {
component = child;
}
if (component.parentComponent_) {
component.parentComponent_.removeChild(component);
}
this.children_.splice(index, 0, component);
component.parentComponent_ = this;
if (typeof component.id === 'function') {
this.childIndex_[component.id()] = component;
}
// If a name wasn't used to create the component, check if we can use the
// name function of the component
componentName = componentName || (component.name && toTitleCase(component.name()));
if (componentName) {
this.childNameIndex_[componentName] = component;
this.childNameIndex_[toLowerCase(componentName)] = component;
}
// Add the UI object's element to the container div (box)
// Having an element is not required
if (typeof component.el === 'function' && component.el()) {
// If inserting before a component, insert before that component's element
let refNode = null;
if (this.children_[index + 1]) {
// Most children are components, but the video tech is an HTML element
if (this.children_[index + 1].el_) {
refNode = this.children_[index + 1].el_;
} else if (Dom.isEl(this.children_[index + 1])) {
refNode = this.children_[index + 1];
}
}
this.contentEl().insertBefore(component.el(), refNode);
}
// Return so it can stored on parent object if desired.
return component;
}
/**
* Remove a child `Component` from this `Component`s list of children. Also removes
* the child `Component`s element from this `Component`s element.
*
* @param {Component} component
* The child `Component` to remove.
*/
removeChild(component) {
if (typeof component === 'string') {
component = this.getChild(component);
}
if (!component || !this.children_) {
return;
}
let childFound = false;
for (let i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i] === component) {
childFound = true;
this.children_.splice(i, 1);
break;
}
}
if (!childFound) {
return;
}
component.parentComponent_ = null;
this.childIndex_[component.id()] = null;
this.childNameIndex_[toTitleCase(component.name())] = null;
this.childNameIndex_[toLowerCase(component.name())] = null;
const compEl = component.el();
if (compEl && compEl.parentNode === this.contentEl()) {
this.contentEl().removeChild(component.el());
}
}
/**
* Add and initialize default child `Component`s based upon options.
*/
initChildren() {
const children = this.options_.children;
if (children) {
// `this` is `parent`
const parentOptions = this.options_;
const handleAdd = (child) => {
const name = child.name;
let opts = child.opts;
// Allow options for children to be set at the parent options
// e.g. videojs(id, { controlBar: false });
// instead of videojs(id, { children: { controlBar: false });
if (parentOptions[name] !== undefined) {
opts = parentOptions[name];
}
// Allow for disabling default components
// e.g. options['children']['posterImage'] = false
if (opts === false) {
return;
}
// Allow options to be passed as a simple boolean if no configuration
// is necessary.
if (opts === true) {
opts = {};
}
// We also want to pass the original player options
// to each component as well so they don't need to
// reach back into the player for options later.
opts.playerOptions = this.options_.playerOptions;
// Create and add the child component.
// Add a direct reference to the child by name on the parent instance.
// If two of the same component are used, different names should be supplied
// for each
const newChild = this.addChild(name, opts);
if (newChild) {
this[name] = newChild;
}
};
// Allow for an array of children details to passed in the options
let workingChildren;
const Tech = Component.getComponent('Tech');
if (Array.isArray(children)) {
workingChildren = children;
} else {
workingChildren = Object.keys(children);
}
workingChildren
// children that are in this.options_ but also in workingChildren would
// give us extra children we do not want. So, we want to filter them out.
.concat(Object.keys(this.options_)
.filter(function(child) {
return !workingChildren.some(function(wchild) {
if (typeof wchild === 'string') {
return child === wchild;
}
return child === wchild.name;
});
}))
.map((child) => {
let name;
let opts;
if (typeof child === 'string') {
name = child;
opts = children[name] || this.options_[name] || {};
} else {
name = child.name;
opts = child;
}
return {name, opts};
})
.filter((child) => {
// we have to make sure that child.name isn't in the techOrder since
// techs are registered as Components but can't aren't compatible
// See https://github.com/videojs/video.js/issues/2772
const c = Component.getComponent(child.opts.componentClass ||
toTitleCase(child.name));
return c && !Tech.isTech(c);
})
.forEach(handleAdd);
}
}
/**
* Builds the default DOM class name. Should be overridden by sub-components.
*
* @return {string}
* The DOM class name for this object.
*
* @abstract
*/
buildCSSClass() {
// Child classes can include a function that does:
// return 'CLASS NAME' + this._super();
return '';
}
/**
* Bind a listener to the component's ready state.
* Different from event listeners in that if the ready event has already happened
* it will trigger the function immediately.
*
* @param {ReadyCallback} fn
* Function that gets called when the `Component` is ready.
*/
ready(fn, sync = false) {
if (!fn) {
return;
}
if (!this.isReady_) {
this.readyQueue_ = this.readyQueue_ || [];
this.readyQueue_.push(fn);
return;
}
if (sync) {
fn.call(this);
} else {
// Call the function asynchronously by default for consistency
this.setTimeout(fn, 1);
}
}
/**
* Trigger all the ready listeners for this `Component`.
*
* @fires Component#ready
*/
triggerReady() {
this.isReady_ = true;
// Ensure ready is triggered asynchronously
this.setTimeout(function() {
const readyQueue = this.readyQueue_;
// Reset Ready Queue
this.readyQueue_ = [];
if (readyQueue && readyQueue.length > 0) {
readyQueue.forEach(function(fn) {
fn.call(this);
}, this);
}
// Allow for using event listeners also
/**
* Triggered when a `Component` is ready.
*
* @event Component#ready
* @type {Event}
*/
this.trigger('ready');
}, 1);
}
/**
* Find a single DOM element matching a `selector`. This can be within the `Component`s
* `contentEl()` or another custom context.
*
* @param {string} selector
* A valid CSS selector, which will be passed to `querySelector`.
*
* @param {Element|string} [context=this.contentEl()]
* A DOM element within which to query. Can also be a selector string in
* which case the first matching element will get used as context. If
* missing `this.contentEl()` gets used. If `this.contentEl()` returns
* nothing it falls back to `document`.
*
* @return {Element|null}
* the dom element that was found, or null
*
* @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
*/
$(selector, context) {
return Dom.$(selector, context || this.contentEl());
}
/**
* Finds all DOM element matching a `selector`. This can be within the `Component`s
* `contentEl()` or another custom context.
*
* @param {string} selector
* A valid CSS selector, which will be passed to `querySelectorAll`.
*
* @param {Element|string} [context=this.contentEl()]
* A DOM element within which to query. Can also be a selector string in
* which case the first matching element will get used as context. If
* missing `this.contentEl()` gets used. If `this.contentEl()` returns
* nothing it falls back to `document`.
*
* @return {NodeList}
* a list of dom elements that were found
*
* @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
*/
$$(selector, context) {
return Dom.$$(selector, context || this.contentEl());
}
/**
* Check if a component's element has a CSS class name.
*
* @param {string} classToCheck
* CSS class name to check.
*
* @return {boolean}
* - True if the `Component` has the class.
* - False if the `Component` does not have the class`
*/
hasClass(classToCheck) {
return Dom.hasClass(this.el_, classToCheck);
}
/**
* Add a CSS class name to the `Component`s element.
*
* @param {...string} classesToAdd
* One or more CSS class name to add.
*/
addClass(...classesToAdd) {
Dom.addClass(this.el_, ...classesToAdd);
}
/**
* Remove a CSS class name from the `Component`s element.
*
* @param {...string} classesToRemove
* One or more CSS class name to remove.
*/
removeClass(...classesToRemove) {
Dom.removeClass(this.el_, ...classesToRemove);
}
/**
* Add or remove a CSS class name from the component's element.
* - `classToToggle` gets added when {@link Component#hasClass} would return false.
* - `classToToggle` gets removed when {@link Component#hasClass} would return true.
*
* @param {string} classToToggle
* The class to add or remove. Passed to DOMTokenList's toggle()
*
* @param {boolean|Dom.PredicateCallback} [predicate]
* A boolean or function that returns a boolean. Passed to DOMTokenList's toggle().
*/
toggleClass(classToToggle, predicate) {
Dom.toggleClass(this.el_, classToToggle, predicate);
}
/**
* Show the `Component`s element if it is hidden by removing the
* 'vjs-hidden' class name from it.
*/
show() {
this.removeClass('vjs-hidden');