aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/controls.js
blob: ad126de1183b7a6f969a5bcd6090ad000827fe71 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
// ==========================================================================
// Plyr controls
// TODO: This needs to be split into smaller files and cleaned up
// ==========================================================================

import RangeTouch from 'rangetouch';

import captions from './captions';
import html5 from './html5';
import support from './support';
import { repaint, transitionEndEvent } from './utils/animation';
import { dedupe } from './utils/arrays';
import browser from './utils/browser';
import {
  createElement,
  emptyElement,
  getAttributesFromSelector,
  getElement,
  getElements,
  hasClass,
  matches,
  removeElement,
  setAttributes,
  setFocus,
  toggleClass,
  toggleHidden,
} from './utils/elements';
import { off, on } from './utils/events';
import i18n from './utils/i18n';
import is from './utils/is';
import loadSprite from './utils/load-sprite';
import { extend } from './utils/objects';
import { getPercentage, replaceAll, toCamelCase, toTitleCase } from './utils/strings';
import { formatTime, getHours } from './utils/time';

// TODO: Don't export a massive object - break down and create class
const controls = {
  // Get icon URL
  getIconUrl() {
    const url = new URL(this.config.iconUrl, window.location);
    const cors = url.host !== window.location.host || (browser.isIE && !window.svg4everybody);

    return {
      url: this.config.iconUrl,
      cors,
    };
  },

  // Find the UI controls
  findElements() {
    try {
      this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper);

      // Buttons
      this.elements.buttons = {
        play: getElements.call(this, this.config.selectors.buttons.play),
        pause: getElement.call(this, this.config.selectors.buttons.pause),
        restart: getElement.call(this, this.config.selectors.buttons.restart),
        rewind: getElement.call(this, this.config.selectors.buttons.rewind),
        fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),
        mute: getElement.call(this, this.config.selectors.buttons.mute),
        pip: getElement.call(this, this.config.selectors.buttons.pip),
        airplay: getElement.call(this, this.config.selectors.buttons.airplay),
        settings: getElement.call(this, this.config.selectors.buttons.settings),
        captions: getElement.call(this, this.config.selectors.buttons.captions),
        fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen),
      };

      // Progress
      this.elements.progress = getElement.call(this, this.config.selectors.progress);

      // Inputs
      this.elements.inputs = {
        seek: getElement.call(this, this.config.selectors.inputs.seek),
        volume: getElement.call(this, this.config.selectors.inputs.volume),
      };

      // Display
      this.elements.display = {
        buffer: getElement.call(this, this.config.selectors.display.buffer),
        currentTime: getElement.call(this, this.config.selectors.display.currentTime),
        duration: getElement.call(this, this.config.selectors.display.duration),
      };

      // Seek tooltip
      if (is.element(this.elements.progress)) {
        this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`);
      }

      return true;
    } catch (error) {
      // Log it
      this.debug.warn('It looks like there is a problem with your custom controls HTML', error);

      // Restore native video controls
      this.toggleNativeControls(true);

      return false;
    }
  },

  // Create <svg> icon
  createIcon(type, attributes) {
    const namespace = 'http://www.w3.org/2000/svg';
    const iconUrl = controls.getIconUrl.call(this);
    const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`;
    // Create <svg>
    const icon = document.createElementNS(namespace, 'svg');
    setAttributes(
      icon,
      extend(attributes, {
        'aria-hidden': 'true',
        focusable: 'false',
      }),
    );

    // Create the <use> to reference sprite
    const use = document.createElementNS(namespace, 'use');
    const path = `${iconPath}-${type}`;

    // Set `href` attributes
    // https://github.com/sampotts/plyr/issues/460
    // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href
    if ('href' in use) {
      use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);
    }

    // Always set the older attribute even though it's "deprecated" (it'll be around for ages)
    use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path);

    // Add <use> to <svg>
    icon.appendChild(use);

    return icon;
  },

  // Create hidden text label
  createLabel(key, attr = {}) {
    const text = i18n.get(key, this.config);
    const attributes = { ...attr, class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ') };

    return createElement('span', attributes, text);
  },

  // Create a badge
  createBadge(text) {
    if (is.empty(text)) {
      return null;
    }

    const badge = createElement('span', {
      class: this.config.classNames.menu.value,
    });

    badge.appendChild(
      createElement(
        'span',
        {
          class: this.config.classNames.menu.badge,
        },
        text,
      ),
    );

    return badge;
  },

  // Create a <button>
  createButton(buttonType, attr) {
    const attributes = extend({}, attr);
    let type = toCamelCase(buttonType);

    const props = {
      element: 'button',
      toggle: false,
      label: null,
      icon: null,
      labelPressed: null,
      iconPressed: null,
    };

    ['element', 'icon', 'label'].forEach(key => {
      if (Object.keys(attributes).includes(key)) {
        props[key] = attributes[key];
        delete attributes[key];
      }
    });

    // Default to 'button' type to prevent form submission
    if (props.element === 'button' && !Object.keys(attributes).includes('type')) {
      attributes.type = 'button';
    }

    // Set class name
    if (Object.keys(attributes).includes('class')) {
      if (!attributes.class.split(' ').some(c => c === this.config.classNames.control)) {
        extend(attributes, {
          class: `${attributes.class} ${this.config.classNames.control}`,
        });
      }
    } else {
      attributes.class = this.config.classNames.control;
    }

    // Large play button
    switch (buttonType) {
      case 'play':
        props.toggle = true;
        props.label = 'play';
        props.labelPressed = 'pause';
        props.icon = 'play';
        props.iconPressed = 'pause';
        break;

      case 'mute':
        props.toggle = true;
        props.label = 'mute';
        props.labelPressed = 'unmute';
        props.icon = 'volume';
        props.iconPressed = 'muted';
        break;

      case 'captions':
        props.toggle = true;
        props.label = 'enableCaptions';
        props.labelPressed = 'disableCaptions';
        props.icon = 'captions-off';
        props.iconPressed = 'captions-on';
        break;

      case 'fullscreen':
        props.toggle = true;
        props.label = 'enterFullscreen';
        props.labelPressed = 'exitFullscreen';
        props.icon = 'enter-fullscreen';
        props.iconPressed = 'exit-fullscreen';
        break;

      case 'play-large':
        attributes.class += ` ${this.config.classNames.control}--overlaid`;
        type = 'play';
        props.label = 'play';
        props.icon = 'play';
        break;

      default:
        if (is.empty(props.label)) {
          props.label = type;
        }
        if (is.empty(props.icon)) {
          props.icon = buttonType;
        }
    }

    const button = createElement(props.element);

    // Setup toggle icon and labels
    if (props.toggle) {
      // Icon
      button.appendChild(
        controls.createIcon.call(this, props.iconPressed, {
          class: 'icon--pressed',
        }),
      );
      button.appendChild(
        controls.createIcon.call(this, props.icon, {
          class: 'icon--not-pressed',
        }),
      );

      // Label/Tooltip
      button.appendChild(
        controls.createLabel.call(this, props.labelPressed, {
          class: 'label--pressed',
        }),
      );
      button.appendChild(
        controls.createLabel.call(this, props.label, {
          class: 'label--not-pressed',
        }),
      );
    } else {
      button.appendChild(controls.createIcon.call(this, props.icon));
      button.appendChild(controls.createLabel.call(this, props.label));
    }

    // Merge and set attributes
    extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));
    setAttributes(button, attributes);

    // We have multiple play buttons
    if (type === 'play') {
      if (!is.array(this.elements.buttons[type])) {
        this.elements.buttons[type] = [];
      }

      this.elements.buttons[type].push(button);
    } else {
      this.elements.buttons[type] = button;
    }

    return button;
  },

  // Create an <input type='range'>
  createRange(type, attributes) {
    // Seek input
    const input = createElement(
      'input',
      extend(
        getAttributesFromSelector(this.config.selectors.inputs[type]),
        {
          type: 'range',
          min: 0,
          max: 100,
          step: 0.01,
          value: 0,
          autocomplete: 'off',
          // A11y fixes for https://github.com/sampotts/plyr/issues/905
          role: 'slider',
          'aria-label': i18n.get(type, this.config),
          'aria-valuemin': 0,
          'aria-valuemax': 100,
          'aria-valuenow': 0,
        },
        attributes,
      ),
    );

    this.elements.inputs[type] = input;

    // Set the fill for webkit now
    controls.updateRangeFill.call(this, input);

    // Improve support on touch devices
    RangeTouch.setup(input);

    return input;
  },

  // Create a <progress>
  createProgress(type, attributes) {
    const progress = createElement(
      'progress',
      extend(
        getAttributesFromSelector(this.config.selectors.display[type]),
        {
          min: 0,
          max: 100,
          value: 0,
          role: 'progressbar',
          'aria-hidden': true,
        },
        attributes,
      ),
    );

    // Create the label inside
    if (type !== 'volume') {
      progress.appendChild(createElement('span', null, '0'));

      const suffixKey = {
        played: 'played',
        buffer: 'buffered',
      }[type];
      const suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';

      progress.innerText = `% ${suffix.toLowerCase()}`;
    }

    this.elements.display[type] = progress;

    return progress;
  },

  // Create time display
  createTime(type, attrs) {
    const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);

    const container = createElement(
      'div',
      extend(attributes, {
        class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(),
        'aria-label': i18n.get(type, this.config),
      }),
      '00:00',
    );

    // Reference for updates
    this.elements.display[type] = container;

    return container;
  },

  // Bind keyboard shortcuts for a menu item
  // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus
  // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143
  bindMenuItemShortcuts(menuItem, type) {
    // Navigate through menus via arrow keys and space
    on.call(
      this,
      menuItem,
      'keydown keyup',
      event => {
        // We only care about space and ⬆️ ⬇️️ ➡️
        if (![32, 38, 39, 40].includes(event.which)) {
          return;
        }

        // Prevent play / seek
        event.preventDefault();
        event.stopPropagation();

        // We're just here to prevent the keydown bubbling
        if (event.type === 'keydown') {
          return;
        }

        const isRadioButton = matches(menuItem, '[role="menuitemradio"]');

        // Show the respective menu
        if (!isRadioButton && [32, 39].includes(event.which)) {
          controls.showMenuPanel.call(this, type, true);
        } else {
          let target;

          if (event.which !== 32) {
            if (event.which === 40 || (isRadioButton && event.which === 39)) {
              target = menuItem.nextElementSibling;

              if (!is.element(target)) {
                target = menuItem.parentNode.firstElementChild;
              }
            } else {
              target = menuItem.previousElementSibling;

              if (!is.element(target)) {
                target = menuItem.parentNode.lastElementChild;
              }
            }

            setFocus.call(this, target, true);
          }
        }
      },
      false,
    );

    // Enter will fire a `click` event but we still need to manage focus
    // So we bind to keyup which fires after and set focus here
    on.call(this, menuItem, 'keyup', event => {
      if (event.which !== 13) {
        return;
      }

      controls.focusFirstMenuItem.call(this, null, true);
    });
  },

  // Create a settings menu item
  createMenuItem({ value, list, type, title, badge = null, checked = false }) {
    const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);

    const menuItem = createElement(
      'button',
      extend(attributes, {
        type: 'button',
        role: 'menuitemradio',
        class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),
        'aria-checked': checked,
        value,
      }),
    );

    const flex = createElement('span');

    // We have to set as HTML incase of special characters
    flex.innerHTML = title;

    if (is.element(badge)) {
      flex.appendChild(badge);
    }

    menuItem.appendChild(flex);

    // Replicate radio button behaviour
    Object.defineProperty(menuItem, 'checked', {
      enumerable: true,
      get() {
        return menuItem.getAttribute('aria-checked') === 'true';
      },
      set(check) {
        // Ensure exclusivity
        if (check) {
          Array.from(menuItem.parentNode.children)
            .filter(node => matches(node, '[role="menuitemradio"]'))
            .forEach(node => node.setAttribute('aria-checked', 'false'));
        }

        menuItem.setAttribute('aria-checked', check ? 'true' : 'false');
      },
    });

    this.listeners.bind(
      menuItem,
      'click keyup',
      event => {
        if (is.keyboardEvent(event) && event.which !== 32) {
          return;
        }

        event.preventDefault();
        event.stopPropagation();

        menuItem.checked = true;

        switch (type) {
          case 'language':
            this.currentTrack = Number(value);
            break;

          case 'quality':
            this.quality = value;
            break;

          case 'speed':
            this.speed = parseFloat(value);
            break;

          default:
            break;
        }

        controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event));
      },
      type,
      false,
    );

    controls.bindMenuItemShortcuts.call(this, menuItem, type);

    list.appendChild(menuItem);
  },

  // Format a time for display
  formatTime(time = 0, inverted = false) {
    // Bail if the value isn't a number
    if (!is.number(time)) {
      return time;
    }

    // Always display hours if duration is over an hour
    const forceHours = getHours(this.duration) > 0;

    return formatTime(time, forceHours, inverted);
  },

  // Update the displayed time
  updateTimeDisplay(target = null, time = 0, inverted = false) {
    // Bail if there's no element to display or the value isn't a number
    if (!is.element(target) || !is.number(time)) {
      return;
    }

    // eslint-disable-next-line no-param-reassign
    target.innerText = controls.formatTime(time, inverted);
  },

  // Update volume UI and storage
  updateVolume() {
    if (!this.supported.ui) {
      return;
    }

    // Update range
    if (is.element(this.elements.inputs.volume)) {
      controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);
    }

    // Update mute state
    if (is.element(this.elements.buttons.mute)) {
      this.elements.buttons.mute.pressed = this.muted || this.volume === 0;
    }
  },

  // Update seek value and lower fill
  setRange(target, value = 0) {
    if (!is.element(target)) {
      return;
    }

    // eslint-disable-next-line
    target.value = value;

    // Webkit range fill
    controls.updateRangeFill.call(this, target);
  },

  // Update <progress> elements
  updateProgress(event) {
    if (!this.supported.ui || !is.event(event)) {
      return;
    }

    let value = 0;

    const setProgress = (target, input) => {
      const val = is.number(input) ? input : 0;
      const progress = is.element(target) ? target : this.elements.display.buffer;

      // Update value and label
      if (is.element(progress)) {
        progress.value = val;

        // Update text label inside
        const label = progress.getElementsByTagName('span')[0];
        if (is.element(label)) {
          label.childNodes[0].nodeValue = val;
        }
      }
    };

    if (event) {
      switch (event.type) {
        // Video playing
        case 'timeupdate':
        case 'seeking':
        case 'seeked':
          value = getPercentage(this.currentTime, this.duration);

          // Set seek range value only if it's a 'natural' time event
          if (event.type === 'timeupdate') {
            controls.setRange.call(this, this.elements.inputs.seek, value);
          }

          break;

        // Check buffer status
        case 'playing':
        case 'progress':
          setProgress(this.elements.display.buffer, this.buffered * 100);

          break;

        default:
          break;
      }
    }
  },

  // Webkit polyfill for lower fill range
  updateRangeFill(target) {
    // Get range from event if event passed
    const range = is.event(target) ? target.target : target;

    // Needs to be a valid <input type='range'>
    if (!is.element(range) || range.getAttribute('type') !== 'range') {
      return;
    }

    // Set aria values for https://github.com/sampotts/plyr/issues/905
    if (matches(range, this.config.selectors.inputs.seek)) {
      range.setAttribute('aria-valuenow', this.currentTime);
      const currentTime = controls.formatTime(this.currentTime);
      const duration = controls.formatTime(this.duration);
      const format = i18n.get('seekLabel', this.config);
      range.setAttribute(
        'aria-valuetext',
        format.replace('{currentTime}', currentTime).replace('{duration}', duration),
      );
    } else if (matches(range, this.config.selectors.inputs.volume)) {
      const percent = range.value * 100;
      range.setAttribute('aria-valuenow', percent);
      range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`);
    } else {
      range.setAttribute('aria-valuenow', range.value);
    }

    // WebKit only
    if (!browser.isWebkit) {
      return;
    }

    // Set CSS custom property
    range.style.setProperty('--value', `${(range.value / range.max) * 100}%`);
  },

  // Update hover tooltip for seeking
  updateSeekTooltip(event) {
    // Bail if setting not true
    if (
      !this.config.tooltips.seek ||
      !is.element(this.elements.inputs.seek) ||
      !is.element(this.elements.display.seekTooltip) ||
      this.duration === 0
    ) {
      return;
    }

    const visible = `${this.config.classNames.tooltip}--visible`;
    const toggle = show => toggleClass(this.elements.display.seekTooltip, visible, show);

    // Hide on touch
    if (this.touch) {
      toggle(false);
      return;
    }

    // Determine percentage, if already visible
    let percent = 0;
    const clientRect = this.elements.progress.getBoundingClientRect();

    if (is.event(event)) {
      percent = (100 / clientRect.width) * (event.pageX - clientRect.left);
    } else if (hasClass(this.elements.display.seekTooltip, visible)) {
      percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);
    } else {
      return;
    }

    // Set bounds
    if (percent < 0) {
      percent = 0;
    } else if (percent > 100) {
      percent = 100;
    }

    // Display the time a click would seek to
    controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, (this.duration / 100) * percent);

    // Set position
    this.elements.display.seekTooltip.style.left = `${percent}%`;

    // Show/hide the tooltip
    // If the event is a moues in/out and percentage is inside bounds
    if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {
      toggle(event.type === 'mouseenter');
    }
  },

  // Handle time change event
  timeUpdate(event) {
    // Only invert if only one time element is displayed and used for both duration and currentTime
    const invert = !is.element(this.elements.display.duration) && this.config.invertTime;

    // Duration
    controls.updateTimeDisplay.call(
      this,
      this.elements.display.currentTime,
      invert ? this.duration - this.currentTime : this.currentTime,
      invert,
    );

    // Ignore updates while seeking
    if (event && event.type === 'timeupdate' && this.media.seeking) {
      return;
    }

    // Playing progress
    controls.updateProgress.call(this, event);
  },

  // Show the duration on metadataloaded or durationchange events
  durationUpdate() {
    // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false
    if (!this.supported.ui || (!this.config.invertTime && this.currentTime)) {
      return;
    }

    // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.
    // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415
    // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062
    // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338
    if (this.duration >= 2 ** 32) {
      toggleHidden(this.elements.display.currentTime, true);
      toggleHidden(this.elements.progress, true);
      return;
    }

    // Update ARIA values
    if (is.element(this.elements.inputs.seek)) {
      this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);
    }

    // If there's a spot to display duration
    const hasDuration = is.element(this.elements.display.duration);

    // If there's only one time display, display duration there
    if (!hasDuration && this.config.displayDuration && this.paused) {
      controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);
    }

    // If there's a duration element, update content
    if (hasDuration) {
      controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);
    }

    // Update the tooltip (if visible)
    controls.updateSeekTooltip.call(this);
  },

  // Hide/show a tab
  toggleMenuButton(setting, toggle) {
    toggleHidden(this.elements.settings.buttons[setting], !toggle);
  },

  // Update the selected setting
  updateSetting(setting, container, input) {
    const pane = this.elements.settings.panels[setting];
    let value = null;
    let list = container;

    if (setting === 'captions') {
      value = this.currentTrack;
    } else {
      value = !is.empty(input) ? input : this[setting];

      // Get default
      if (is.empty(value)) {
        value = this.config[setting].default;
      }

      // Unsupported value
      if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {
        this.debug.warn(`Unsupported value of '${value}' for ${setting}`);
        return;
      }

      // Disabled value
      if (!this.config[setting].options.includes(value)) {
        this.debug.warn(`Disabled value of '${value}' for ${setting}`);
        return;
      }
    }

    // Get the list if we need to
    if (!is.element(list)) {
      list = pane && pane.querySelector('[role="menu"]');
    }

    // If there's no list it means it's not been rendered...
    if (!is.element(list)) {
      return;
    }

    // Update the label
    const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);
    label.innerHTML = controls.getLabel.call(this, setting, value);

    // Find the radio option and check it
    const target = list && list.querySelector(`[value="${value}"]`);

    if (is.element(target)) {
      target.checked = true;
    }
  },

  // Translate a value into a nice label
  getLabel(setting, value) {
    switch (setting) {
      case 'speed':
        return value === 1 ? i18n.get('normal', this.config) : `${value}&times;`;

      case 'quality':
        if (is.number(value)) {
          const label = i18n.get(`qualityLabel.${value}`, this.config);

          if (!label.length) {
            return `${value}p`;
          }

          return label;
        }

        return toTitleCase(value);

      case 'captions':
        return captions.getLabel.call(this);

      default:
        return null;
    }
  },

  // Set the quality menu
  setQualityMenu(options) {
    // Menu required
    if (!is.element(this.elements.settings.panels.quality)) {
      return;
    }

    const type = 'quality';
    const list = this.elements.settings.panels.quality.querySelector('[role="menu"]');

    // Set options if passed and filter based on uniqueness and config
    if (is.array(options)) {
      this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality));
    }

    // Toggle the pane and tab
    const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;
    controls.toggleMenuButton.call(this, type, toggle);

    // Empty the menu
    emptyElement(list);

    // Check if we need to toggle the parent
    controls.checkMenu.call(this);

    // If we're hiding, nothing more to do
    if (!toggle) {
      return;
    }

    // Get the badge HTML for HD, 4K etc
    const getBadge = quality => {
      const label = i18n.get(`qualityBadge.${quality}`, this.config);

      if (!label.length) {
        return null;
      }

      return controls.createBadge.call(this, label);
    };

    // Sort options by the config and then render options
    this.options.quality
      .sort((a, b) => {
        const sorting = this.config.quality.options;
        return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;
      })
      .forEach(quality => {
        controls.createMenuItem.call(this, {
          value: quality,
          list,
          type,
          title: controls.getLabel.call(this, 'quality', quality),
          badge: getBadge(quality),
        });
      });

    controls.updateSetting.call(this, type, list);
  },

  // Set the looping options
  /* setLoopMenu() {
        // Menu required
        if (!is.element(this.elements.settings.panels.loop)) {
            return;
        }

        const options = ['start', 'end', 'all', 'reset'];
        const list = this.elements.settings.panels.loop.querySelector('[role="menu"]');

        // Show the pane and tab
        toggleHidden(this.elements.settings.buttons.loop, false);
        toggleHidden(this.elements.settings.panels.loop, false);

        // Toggle the pane and tab
        const toggle = !is.empty(this.loop.options);
        controls.toggleMenuButton.call(this, 'loop', toggle);

        // Empty the menu
        emptyElement(list);

        options.forEach(option => {
            const item = createElement('li');

            const button = createElement(
                'button',
                extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {
                    type: 'button',
                    class: this.config.classNames.control,
                    'data-plyr-loop-action': option,
                }),
                i18n.get(option, this.config)
            );

            if (['start', 'end'].includes(option)) {
                const badge = controls.createBadge.call(this, '00:00');
                button.appendChild(badge);
            }

            item.appendChild(button);
            list.appendChild(item);
        });
    }, */

  // Get current selected caption language
  // TODO: rework this to user the getter in the API?

  // Set a list of available captions languages
  setCaptionsMenu() {
    // Menu required
    if (!is.element(this.elements.settings.panels.captions)) {
      return;
    }

    // TODO: Captions or language? Currently it's mixed
    const type = 'captions';
    const list = this.elements.settings.panels.captions.querySelector('[role="menu"]');
    const tracks = captions.getTracks.call(this);
    const toggle = Boolean(tracks.length);

    // Toggle the pane and tab
    controls.toggleMenuButton.call(this, type, toggle);

    // Empty the menu
    emptyElement(list);

    // Check if we need to toggle the parent
    controls.checkMenu.call(this);

    // If there's no captions, bail
    if (!toggle) {
      return;
    }

    // Generate options data
    const options = tracks.map((track, value) => ({
      value,
      checked: this.captions.toggled && this.currentTrack === value,
      title: captions.getLabel.call(this, track),
      badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),
      list,
      type: 'language',
    }));

    // Add the "Disabled" option to turn off captions
    options.unshift({
      value: -1,
      checked: !this.captions.toggled,
      title: i18n.get('disabled', this.config),
      list,
      type: 'language',
    });

    // Generate options
    options.forEach(controls.createMenuItem.bind(this));

    controls.updateSetting.call(this, type, list);
  },

  // Set a list of available captions languages
  setSpeedMenu() {
    // Menu required
    if (!is.element(this.elements.settings.panels.speed)) {
      return;
    }

    const type = 'speed';
    const list = this.elements.settings.panels.speed.querySelector('[role="menu"]');

    // Filter out invalid speeds
    this.options.speed = this.options.speed.filter(o => o >= this.minimumSpeed && o <= this.maximumSpeed);

    // Toggle the pane and tab
    const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;
    controls.toggleMenuButton.call(this, type, toggle);

    // Empty the menu
    emptyElement(list);

    // Check if we need to toggle the parent
    controls.checkMenu.call(this);

    // If we're hiding, nothing more to do
    if (!toggle) {
      return;
    }

    // Create items
    this.options.speed.forEach(speed => {
      controls.createMenuItem.call(this, {
        value: speed,
        list,
        type,
        title: controls.getLabel.call(this, 'speed', speed),
      });
    });

    controls.updateSetting.call(this, type, list);
  },

  // Check if we need to hide/show the settings menu
  checkMenu() {
    const { buttons } = this.elements.settings;
    const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden);

    toggleHidden(this.elements.settings.menu, !visible);
  },

  // Focus the first menu item in a given (or visible) menu
  focusFirstMenuItem(pane, tabFocus = false) {
    if (this.elements.settings.popup.hidden) {
      return;
    }

    let target = pane;

    if (!is.element(target)) {
      target = Object.values(this.elements.settings.panels).find(p => !p.hidden);
    }

    const firstItem = target.querySelector('[role^="menuitem"]');

    setFocus.call(this, firstItem, tabFocus);
  },

  // Show/hide menu
  toggleMenu(input) {
    const { popup } = this.elements.settings;
    const button = this.elements.buttons.settings;

    // Menu and button are required
    if (!is.element(popup) || !is.element(button)) {
      return;
    }

    // True toggle by default
    const { hidden } = popup;
    let show = hidden;

    if (is.boolean(input)) {
      show = input;
    } else if (is.keyboardEvent(input) && input.which === 27) {
      show = false;
    } else if (is.event(input)) {
      // If Plyr is in a shadowDOM, the event target is set to the component, instead of the
      // Element in the shadowDOM. The path, if available, is complete.
      const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target;
      const isMenuItem = popup.contains(target);

      // If the click was inside the menu or if the click
      // wasn't the button or menu item and we're trying to
      // show the menu (a doc click shouldn't show the menu)
      if (isMenuItem || (!isMenuItem && input.target !== button && show)) {
        return;
      }
    }

    // Set button attributes
    button.setAttribute('aria-expanded', show);

    // Show the actual popup
    toggleHidden(popup, !show);

    // Add class hook
    toggleClass(this.elements.container, this.config.classNames.menu.open, show);

    // Focus the first item if key interaction
    if (show && is.keyboardEvent(input)) {
      controls.focusFirstMenuItem.call(this, null, true);
    } else if (!show && !hidden) {
      // If closing, re-focus the button
      setFocus.call(this, button, is.keyboardEvent(input));
    }
  },

  // Get the natural size of a menu panel
  getMenuSize(tab) {
    const clone = tab.cloneNode(true);
    clone.style.position = 'absolute';
    clone.style.opacity = 0;
    clone.removeAttribute('hidden');

    // Append to parent so we get the "real" size
    tab.parentNode.appendChild(clone);

    // Get the sizes before we remove
    const width = clone.scrollWidth;
    const height = clone.scrollHeight;

    // Remove from the DOM
    removeElement(clone);

    return {
      width,
      height,
    };
  },

  // Show a panel in the menu
  showMenuPanel(type = '', tabFocus = false) {
    const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`);

    // Nothing to show, bail
    if (!is.element(target)) {
      return;
    }

    // Hide all other panels
    const container = target.parentNode;
    const current = Array.from(container.children).find(node => !node.hidden);

    // If we can do fancy animations, we'll animate the height/width
    if (support.transitions && !support.reducedMotion) {
      // Set the current width as a base
      container.style.width = `${current.scrollWidth}px`;
      container.style.height = `${current.scrollHeight}px`;

      // Get potential sizes
      const size = controls.getMenuSize.call(this, target);

      // Restore auto height/width
      const restore = event => {
        // We're only bothered about height and width on the container
        if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {
          return;
        }

        // Revert back to auto
        container.style.width = '';
        container.style.height = '';

        // Only listen once
        off.call(this, container, transitionEndEvent, restore);
      };

      // Listen for the transition finishing and restore auto height/width
      on.call(this, container, transitionEndEvent, restore);

      // Set dimensions to target
      container.style.width = `${size.width}px`;
      container.style.height = `${size.height}px`;
    }

    // Set attributes on current tab
    toggleHidden(current, true);

    // Set attributes on target
    toggleHidden(target, false);

    // Focus the first item
    controls.focusFirstMenuItem.call(this, target, tabFocus);
  },

  // Set the download URL
  setDownloadUrl() {
    const button = this.elements.buttons.download;

    // Bail if no button
    if (!is.element(button)) {
      return;
    }

    // Set attribute
    button.setAttribute('href', this.download);
  },

  // Build the default HTML
  create(data) {
    const {
      bindMenuItemShortcuts,
      createButton,
      createProgress,
      createRange,
      createTime,
      setQualityMenu,
      setSpeedMenu,
      showMenuPanel,
    } = controls;
    this.elements.controls = null;

    // Larger overlaid play button
    if (is.array(this.config.controls) && this.config.controls.includes('play-large')) {
      this.elements.container.appendChild(createButton.call(this, 'play-large'));
    }

    // Create the container
    const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));
    this.elements.controls = container;

    // Default item attributes
    const defaultAttributes = { class: 'plyr__controls__item' };

    // Loop through controls in order
    dedupe(is.array(this.config.controls) ? this.config.controls: []).forEach(control => {
      // Restart button
      if (control === 'restart') {
        container.appendChild(createButton.call(this, 'restart', defaultAttributes));
      }

      // Rewind button
      if (control === 'rewind') {
        container.appendChild(createButton.call(this, 'rewind', defaultAttributes));
      }

      // Play/Pause button
      if (control === 'play') {
        container.appendChild(createButton.call(this, 'play', defaultAttributes));
      }

      // Fast forward button
      if (control === 'fast-forward') {
        container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes));
      }

      // Progress
      if (control === 'progress') {
        const progressContainer = createElement('div', {
          class: `${defaultAttributes.class} plyr__progress__container`,
        });

        const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress));

        // Seek range slider
        progress.appendChild(
          createRange.call(this, 'seek', {
            id: `plyr-seek-${data.id}`,
          }),
        );

        // Buffer progress
        progress.appendChild(createProgress.call(this, 'buffer'));

        // TODO: Add loop display indicator

        // Seek tooltip
        if (this.config.tooltips.seek) {
          const tooltip = createElement(
            'span',
            {
              class: this.config.classNames.tooltip,
            },
            '00:00',
          );

          progress.appendChild(tooltip);
          this.elements.display.seekTooltip = tooltip;
        }

        this.elements.progress = progress;
        progressContainer.appendChild(this.elements.progress);
        container.appendChild(progressContainer);
      }

      // Media current time display
      if (control === 'current-time') {
        container.appendChild(createTime.call(this, 'currentTime', defaultAttributes));
      }

      // Media duration display
      if (control === 'duration') {
        container.appendChild(createTime.call(this, 'duration', defaultAttributes));
      }

      // Volume controls
      if (control === 'mute' || control === 'volume') {
        let { volume } = this.elements;

        // Create the volume container if needed
        if (!is.element(volume) || !container.contains(volume)) {
          volume = createElement(
            'div',
            extend({}, defaultAttributes, {
              class: `${defaultAttributes.class} plyr__volume`.trim(),
            }),
          );

          this.elements.volume = volume;

          container.appendChild(volume);
        }

        // Toggle mute button
        if (control === 'mute') {
          volume.appendChild(createButton.call(this, 'mute'));
        }

        // Volume range control
        // Ignored on iOS as it's handled globally
        // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html
        if (control === 'volume' && !browser.isIos) {
          // Set the attributes
          const attributes = {
            max: 1,
            step: 0.05,
            value: this.config.volume,
          };

          // Create the volume range slider
          volume.appendChild(
            createRange.call(
              this,
              'volume',
              extend(attributes, {
                id: `plyr-volume-${data.id}`,
              }),
            ),
          );
        }
      }

      // Toggle captions button
      if (control === 'captions') {
        container.appendChild(createButton.call(this, 'captions', defaultAttributes));
      }

      // Settings button / menu
      if (control === 'settings' && !is.empty(this.config.settings)) {
        const wrapper = createElement(
          'div',
          extend({}, defaultAttributes, {
            class: `${defaultAttributes.class} plyr__menu`.trim(),
            hidden: '',
          }),
        );

        wrapper.appendChild(
          createButton.call(this, 'settings', {
            'aria-haspopup': true,
            'aria-controls': `plyr-settings-${data.id}`,
            'aria-expanded': false,
          }),
        );

        const popup = createElement('div', {
          class: 'plyr__menu__container',
          id: `plyr-settings-${data.id}`,
          hidden: '',
        });

        const inner = createElement('div');

        const home = createElement('div', {
          id: `plyr-settings-${data.id}-home`,
        });

        // Create the menu
        const menu = createElement('div', {
          role: 'menu',
        });

        home.appendChild(menu);
        inner.appendChild(home);
        this.elements.settings.panels.home = home;

        // Build the menu items
        this.config.settings.forEach(type => {
          // TODO: bundle this with the createMenuItem helper and bindings
          const menuItem = createElement(
            'button',
            extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {
              type: 'button',
              class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,
              role: 'menuitem',
              'aria-haspopup': true,
              hidden: '',
            }),
          );

          // Bind menu shortcuts for keyboard users
          bindMenuItemShortcuts.call(this, menuItem, type);

          // Show menu on click
          on.call(this, menuItem, 'click', () => {
            showMenuPanel.call(this, type, false);
          });

          const flex = createElement('span', null, i18n.get(type, this.config));

          const value = createElement('span', {
            class: this.config.classNames.menu.value,
          });

          // Speed contains HTML entities
          value.innerHTML = data[type];

          flex.appendChild(value);
          menuItem.appendChild(flex);
          menu.appendChild(menuItem);

          // Build the panes
          const pane = createElement('div', {
            id: `plyr-settings-${data.id}-${type}`,
            hidden: '',
          });

          // Back button
          const backButton = createElement('button', {
            type: 'button',
            class: `${this.config.classNames.control} ${this.config.classNames.control}--back`,
          });

          // Visible label
          backButton.appendChild(
            createElement(
              'span',
              {
                'aria-hidden': true,
              },
              i18n.get(type, this.config),
            ),
          );

          // Screen reader label
          backButton.appendChild(
            createElement(
              'span',
              {
                class: this.config.classNames.hidden,
              },
              i18n.get('menuBack', this.config),
            ),
          );

          // Go back via keyboard
          on.call(
            this,
            pane,
            'keydown',
            event => {
              // We only care about <-
              if (event.which !== 37) {
                return;
              }

              // Prevent seek
              event.preventDefault();
              event.stopPropagation();

              // Show the respective menu
              showMenuPanel.call(this, 'home', true);
            },
            false,
          );

          // Go back via button click
          on.call(this, backButton, 'click', () => {
            showMenuPanel.call(this, 'home', false);
          });

          // Add to pane
          pane.appendChild(backButton);

          // Menu
          pane.appendChild(
            createElement('div', {
              role: 'menu',
            }),
          );

          inner.appendChild(pane);

          this.elements.settings.buttons[type] = menuItem;
          this.elements.settings.panels[type] = pane;
        });

        popup.appendChild(inner);
        wrapper.appendChild(popup);
        container.appendChild(wrapper);

        this.elements.settings.popup = popup;
        this.elements.settings.menu = wrapper;
      }

      // Picture in picture button
      if (control === 'pip' && support.pip) {
        container.appendChild(createButton.call(this, 'pip', defaultAttributes));
      }

      // Airplay button
      if (control === 'airplay' && support.airplay) {
        container.appendChild(createButton.call(this, 'airplay', defaultAttributes));
      }

      // Download button
      if (control === 'download') {
        const attributes = extend({}, defaultAttributes, {
          element: 'a',
          href: this.download,
          target: '_blank',
        });

        // Set download attribute for HTML5 only
        if (this.isHTML5) {
          attributes.download = '';
        }

        const { download } = this.config.urls;

        if (!is.url(download) && this.isEmbed) {
          extend(attributes, {
            icon: `logo-${this.provider}`,
            label: this.provider,
          });
        }

        container.appendChild(createButton.call(this, 'download', attributes));
      }

      // Toggle fullscreen button
      if (control === 'fullscreen') {
        container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes));
      }
    });

    // Set available quality levels
    if (this.isHTML5) {
      setQualityMenu.call(this, html5.getQualityOptions.call(this));
    }

    setSpeedMenu.call(this);

    return container;
  },

  // Insert controls
  inject() {
    // Sprite
    if (this.config.loadSprite) {
      const icon = controls.getIconUrl.call(this);

      // Only load external sprite using AJAX
      if (icon.cors) {
        loadSprite(icon.url, 'sprite-plyr');
      }
    }

    // Create a unique ID
    this.id = Math.floor(Math.random() * 10000);

    // Null by default
    let container = null;
    this.elements.controls = null;

    // Set template properties
    const props = {
      id: this.id,
      seektime: this.config.seekTime,
      title: this.config.title,
    };
    let update = true;

    // If function, run it and use output
    if (is.function(this.config.controls)) {
      this.config.controls = this.config.controls.call(this, props);
    }

    // Convert falsy controls to empty array (primarily for empty strings)
    if (!this.config.controls) {
      this.config.controls = [];
    }

    if (is.element(this.config.controls) || is.string(this.config.controls)) {
      // HTMLElement or Non-empty string passed as the option
      container = this.config.controls;
    } else {
      // Create controls
      container = controls.create.call(this, {
        id: this.id,
        seektime: this.config.seekTime,
        speed: this.speed,
        quality: this.quality,
        captions: captions.getLabel.call(this),
        // TODO: Looping
        // loop: 'None',
      });
      update = false;
    }

    // Replace props with their value
    const replace = input => {
      let result = input;

      Object.entries(props).forEach(([key, value]) => {
        result = replaceAll(result, `{${key}}`, value);
      });

      return result;
    };

    // Update markup
    if (update) {
      if (is.string(this.config.controls)) {
        container = replace(container);
      }
    }

    // Controls container
    let target;

    // Inject to custom location
    if (is.string(this.config.selectors.controls.container)) {
      target = document.querySelector(this.config.selectors.controls.container);
    }

    // Inject into the container by default
    if (!is.element(target)) {
      target = this.elements.container;
    }

    // Inject controls HTML (needs to be before captions, hence "afterbegin")
    const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';
    target[insertMethod]('afterbegin', container);

    // Find the elements if need be
    if (!is.element(this.elements.controls)) {
      controls.findElements.call(this);
    }

    // Add pressed property to buttons
    if (!is.empty(this.elements.buttons)) {
      const addProperty = button => {
        const className = this.config.classNames.controlPressed;
        Object.defineProperty(button, 'pressed', {
          enumerable: true,
          get() {
            return hasClass(button, className);
          },
          set(pressed = false) {
            toggleClass(button, className, pressed);
          },
        });
      };

      // Toggle classname when pressed property is set
      Object.values(this.elements.buttons)
        .filter(Boolean)
        .forEach(button => {
          if (is.array(button) || is.nodeList(button)) {
            Array.from(button)
              .filter(Boolean)
              .forEach(addProperty);
          } else {
            addProperty(button);
          }
        });
    }

    // Edge sometimes doesn't finish the paint so force a repaint
    if (browser.isEdge) {
      repaint(target);
    }

    // Setup tooltips
    if (this.config.tooltips.controls) {
      const { classNames, selectors } = this.config;
      const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;
      const labels = getElements.call(this, selector);

      Array.from(labels).forEach(label => {
        toggleClass(label, this.config.classNames.hidden, false);
        toggleClass(label, this.config.classNames.tooltip, true);
      });
    }
  },
};

export default controls;