-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextTrackRadioButton.ts
89 lines (76 loc) · 2.7 KB
/
TextTrackRadioButton.ts
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
import { RadioButton } from './RadioButton';
import { buttonTemplate } from './Button';
import type { TextTrack } from 'theoplayer/chromeless';
import { localizeLanguageName, setTextContent } from '../util/CommonUtils';
import { Attribute } from '../util/Attribute';
import { createTemplate } from '../util/TemplateUtils';
const template = createTemplate('theoplayer-text-track-radio-button', buttonTemplate(`<slot></slot>`));
const TRACK_EVENTS = ['change', 'update'] as const;
/**
* `<theoplayer-text-track-radio-button>` -A radio button that shows the label of a given text track, and switches to that track when clicked.
*
* @group Components
*/
export class TextTrackRadioButton extends RadioButton {
private _slotEl: HTMLSlotElement;
private _track: TextTrack | undefined = undefined;
constructor() {
super({ template: template() });
this._slotEl = this.shadowRoot!.querySelector('slot')!;
this._upgradeProperty('track');
}
/**
* The text track that is controlled by this radio button.
*/
get track(): TextTrack | undefined {
return this._track;
}
set track(track: TextTrack | undefined) {
if (this._track === track) {
return;
}
if (this._track) {
this._track.removeEventListener(TRACK_EVENTS, this._onTrackChange);
}
this._track = track;
this._updateFromTrack();
if (track) {
track.addEventListener(TRACK_EVENTS, this._onTrackChange);
}
}
private _updateFromTrack(): void {
setTextContent(this._slotEl, this._track ? getTrackLabel(this._track) : '');
this.checked = this._track ? this._track.mode === 'showing' : false;
}
private _updateTrack(): void {
if (this._track) {
this._track.mode = this.checked ? 'showing' : 'disabled';
}
}
private readonly _onTrackChange = () => {
this._updateFromTrack();
};
override attributeChangedCallback(attrName: string, oldValue: any, newValue: any) {
super.attributeChangedCallback(attrName, oldValue, newValue);
if (attrName === Attribute.ARIA_CHECKED && oldValue !== newValue) {
this._updateTrack();
}
}
}
function getTrackLabel(track: TextTrack): string {
let label = track.label;
if (label) {
return label;
}
let languageCode = track.language;
if (!languageCode) {
return '';
}
return localizeLanguageName(languageCode) || languageCode || '';
}
customElements.define('theoplayer-text-track-radio-button', TextTrackRadioButton);
declare global {
interface HTMLElementTagNameMap {
'theoplayer-text-track-radio-button': TextTrackRadioButton;
}
}