Source: ui/controls.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.ui.Controls');
  7. goog.provide('shaka.ui.ControlsPanel');
  8. goog.require('goog.asserts');
  9. goog.require('shaka.ads.AdManager');
  10. goog.require('shaka.cast.CastProxy');
  11. goog.require('shaka.log');
  12. goog.require('shaka.ui.AdCounter');
  13. goog.require('shaka.ui.AdPosition');
  14. goog.require('shaka.ui.BigPlayButton');
  15. goog.require('shaka.ui.ContextMenu');
  16. goog.require('shaka.ui.HiddenFastForwardButton');
  17. goog.require('shaka.ui.HiddenRewindButton');
  18. goog.require('shaka.ui.Locales');
  19. goog.require('shaka.ui.Localization');
  20. goog.require('shaka.ui.SeekBar');
  21. goog.require('shaka.ui.SkipAdButton');
  22. goog.require('shaka.ui.Utils');
  23. goog.require('shaka.ui.VRManager');
  24. goog.require('shaka.util.Dom');
  25. goog.require('shaka.util.EventManager');
  26. goog.require('shaka.util.FakeEvent');
  27. goog.require('shaka.util.FakeEventTarget');
  28. goog.require('shaka.util.IDestroyable');
  29. goog.require('shaka.util.Timer');
  30. goog.requireType('shaka.Player');
  31. /**
  32. * A container for custom video controls.
  33. * @implements {shaka.util.IDestroyable}
  34. * @export
  35. */
  36. shaka.ui.Controls = class extends shaka.util.FakeEventTarget {
  37. /**
  38. * @param {!shaka.Player} player
  39. * @param {!HTMLElement} videoContainer
  40. * @param {!HTMLMediaElement} video
  41. * @param {?HTMLCanvasElement} vrCanvas
  42. * @param {shaka.extern.UIConfiguration} config
  43. */
  44. constructor(player, videoContainer, video, vrCanvas, config) {
  45. super();
  46. /** @private {boolean} */
  47. this.enabled_ = true;
  48. /** @private {shaka.extern.UIConfiguration} */
  49. this.config_ = config;
  50. /** @private {shaka.cast.CastProxy} */
  51. this.castProxy_ = new shaka.cast.CastProxy(
  52. video, player, this.config_.castReceiverAppId,
  53. this.config_.castAndroidReceiverCompatible);
  54. /** @private {boolean} */
  55. this.castAllowed_ = true;
  56. /** @private {HTMLMediaElement} */
  57. this.video_ = this.castProxy_.getVideo();
  58. /** @private {HTMLMediaElement} */
  59. this.localVideo_ = video;
  60. /** @private {shaka.Player} */
  61. this.player_ = this.castProxy_.getPlayer();
  62. /** @private {shaka.Player} */
  63. this.localPlayer_ = player;
  64. /** @private {!HTMLElement} */
  65. this.videoContainer_ = videoContainer;
  66. /** @private {?HTMLCanvasElement} */
  67. this.vrCanvas_ = vrCanvas;
  68. /** @private {shaka.extern.IAdManager} */
  69. this.adManager_ = this.player_.getAdManager();
  70. /** @private {?shaka.extern.IAd} */
  71. this.ad_ = null;
  72. /** @private {?shaka.extern.IUISeekBar} */
  73. this.seekBar_ = null;
  74. /** @private {boolean} */
  75. this.isSeeking_ = false;
  76. /** @private {!Array.<!HTMLElement>} */
  77. this.menus_ = [];
  78. /**
  79. * Individual controls which, when hovered or tab-focused, will force the
  80. * controls to be shown.
  81. * @private {!Array.<!Element>}
  82. */
  83. this.showOnHoverControls_ = [];
  84. /** @private {boolean} */
  85. this.recentMouseMovement_ = false;
  86. /**
  87. * This timer is used to detect when the user has stopped moving the mouse
  88. * and we should fade out the ui.
  89. *
  90. * @private {shaka.util.Timer}
  91. */
  92. this.mouseStillTimer_ = new shaka.util.Timer(() => {
  93. this.onMouseStill_();
  94. });
  95. /**
  96. * This timer is used to delay the fading of the UI.
  97. *
  98. * @private {shaka.util.Timer}
  99. */
  100. this.fadeControlsTimer_ = new shaka.util.Timer(() => {
  101. this.controlsContainer_.removeAttribute('shown');
  102. // If there's an overflow menu open, keep it this way for a couple of
  103. // seconds in case a user immediately initiates another mouse move to
  104. // interact with the menus. If that didn't happen, go ahead and hide
  105. // the menus.
  106. this.hideSettingsMenusTimer_.tickAfter(/* seconds= */ 2);
  107. });
  108. /**
  109. * This timer will be used to hide all settings menus. When the timer ticks
  110. * it will force all controls to invisible.
  111. *
  112. * Rather than calling the callback directly, |Controls| will always call it
  113. * through the timer to avoid conflicts.
  114. *
  115. * @private {shaka.util.Timer}
  116. */
  117. this.hideSettingsMenusTimer_ = new shaka.util.Timer(() => {
  118. for (const menu of this.menus_) {
  119. shaka.ui.Utils.setDisplay(menu, /* visible= */ false);
  120. }
  121. });
  122. /**
  123. * This timer is used to regularly update the time and seek range elements
  124. * so that we are communicating the current state as accurately as possibly.
  125. *
  126. * Unlike the other timers, this timer does not "own" the callback because
  127. * this timer is acting like a heartbeat.
  128. *
  129. * @private {shaka.util.Timer}
  130. */
  131. this.timeAndSeekRangeTimer_ = new shaka.util.Timer(() => {
  132. // Suppress timer-based updates if the controls are hidden.
  133. if (this.isOpaque()) {
  134. this.updateTimeAndSeekRange_();
  135. }
  136. });
  137. /** @private {?number} */
  138. this.lastTouchEventTime_ = null;
  139. /** @private {!Array.<!shaka.extern.IUIElement>} */
  140. this.elements_ = [];
  141. /** @private {shaka.ui.Localization} */
  142. this.localization_ = shaka.ui.Controls.createLocalization_();
  143. /** @private {shaka.util.EventManager} */
  144. this.eventManager_ = new shaka.util.EventManager();
  145. /** @private {?shaka.ui.VRManager} */
  146. this.vr_ = null;
  147. // Configure and create the layout of the controls
  148. this.configure(this.config_);
  149. this.addEventListeners_();
  150. /**
  151. * The pressed keys set is used to record which keys are currently pressed
  152. * down, so we can know what keys are pressed at the same time.
  153. * Used by the focusInsideOverflowMenu_() function.
  154. * @private {!Set.<string>}
  155. */
  156. this.pressedKeys_ = new Set();
  157. // We might've missed a caststatuschanged event from the proxy between
  158. // the controls creation and initializing. Run onCastStatusChange_()
  159. // to ensure we have the casting state right.
  160. this.onCastStatusChange_();
  161. // Start this timer after we are finished initializing everything,
  162. this.timeAndSeekRangeTimer_.tickEvery(this.config_.refreshTickInSeconds);
  163. this.eventManager_.listen(this.localization_,
  164. shaka.ui.Localization.LOCALE_CHANGED, (e) => {
  165. const locale = e['locales'][0];
  166. this.adManager_.setLocale(locale);
  167. });
  168. }
  169. /**
  170. * @override
  171. * @export
  172. */
  173. async destroy() {
  174. if (document.pictureInPictureElement == this.localVideo_) {
  175. await document.exitPictureInPicture();
  176. }
  177. if (this.eventManager_) {
  178. this.eventManager_.release();
  179. this.eventManager_ = null;
  180. }
  181. if (this.mouseStillTimer_) {
  182. this.mouseStillTimer_.stop();
  183. this.mouseStillTimer_ = null;
  184. }
  185. if (this.fadeControlsTimer_) {
  186. this.fadeControlsTimer_.stop();
  187. this.fadeControlsTimer_ = null;
  188. }
  189. if (this.hideSettingsMenusTimer_) {
  190. this.hideSettingsMenusTimer_.stop();
  191. this.hideSettingsMenusTimer_ = null;
  192. }
  193. if (this.timeAndSeekRangeTimer_) {
  194. this.timeAndSeekRangeTimer_.stop();
  195. this.timeAndSeekRangeTimer_ = null;
  196. }
  197. if (this.vr_) {
  198. this.vr_.release();
  199. this.vr_ = null;
  200. }
  201. // Important! Release all child elements before destroying the cast proxy
  202. // or player. This makes sure those destructions will not trigger event
  203. // listeners in the UI which would then invoke the cast proxy or player.
  204. this.releaseChildElements_();
  205. if (this.controlsContainer_) {
  206. this.videoContainer_.removeChild(this.controlsContainer_);
  207. this.controlsContainer_ = null;
  208. }
  209. if (this.castProxy_) {
  210. await this.castProxy_.destroy();
  211. this.castProxy_ = null;
  212. }
  213. if (this.localPlayer_) {
  214. await this.localPlayer_.destroy();
  215. this.localPlayer_ = null;
  216. }
  217. this.player_ = null;
  218. this.localVideo_ = null;
  219. this.video_ = null;
  220. this.localization_ = null;
  221. this.pressedKeys_.clear();
  222. // FakeEventTarget implements IReleasable
  223. super.release();
  224. }
  225. /** @private */
  226. releaseChildElements_() {
  227. for (const element of this.elements_) {
  228. element.release();
  229. }
  230. this.elements_ = [];
  231. }
  232. /**
  233. * @param {string} name
  234. * @param {!shaka.extern.IUIElement.Factory} factory
  235. * @export
  236. */
  237. static registerElement(name, factory) {
  238. shaka.ui.ControlsPanel.elementNamesToFactories_.set(name, factory);
  239. }
  240. /**
  241. * @param {!shaka.extern.IUISeekBar.Factory} factory
  242. * @export
  243. */
  244. static registerSeekBar(factory) {
  245. shaka.ui.ControlsPanel.seekBarFactory_ = factory;
  246. }
  247. /**
  248. * This allows the application to inhibit casting.
  249. *
  250. * @param {boolean} allow
  251. * @export
  252. */
  253. allowCast(allow) {
  254. this.castAllowed_ = allow;
  255. this.onCastStatusChange_();
  256. }
  257. /**
  258. * Used by the application to notify the controls that a load operation is
  259. * complete. This allows the controls to recalculate play/paused state, which
  260. * is important for platforms like Android where autoplay is disabled.
  261. * @export
  262. */
  263. loadComplete() {
  264. // If we are on Android or if autoplay is false, video.paused should be
  265. // true. Otherwise, video.paused is false and the content is autoplaying.
  266. this.onPlayStateChange_();
  267. }
  268. /**
  269. * @param {!shaka.extern.UIConfiguration} config
  270. * @export
  271. */
  272. configure(config) {
  273. this.config_ = config;
  274. this.castProxy_.changeReceiverId(config.castReceiverAppId,
  275. config.castAndroidReceiverCompatible);
  276. // Deconstruct the old layout if applicable
  277. if (this.seekBar_) {
  278. this.seekBar_ = null;
  279. }
  280. if (this.playButton_) {
  281. this.playButton_ = null;
  282. }
  283. if (this.contextMenu_) {
  284. this.contextMenu_ = null;
  285. }
  286. if (this.vr_) {
  287. this.vr_.configure(config);
  288. }
  289. if (this.controlsContainer_) {
  290. shaka.util.Dom.removeAllChildren(this.controlsContainer_);
  291. this.releaseChildElements_();
  292. } else {
  293. this.addControlsContainer_();
  294. // The client-side ad container is only created once, and is never
  295. // re-created or uprooted in the DOM, even when the DOM is re-created,
  296. // since that seemingly breaks the IMA SDK.
  297. this.addClientAdContainer_();
  298. goog.asserts.assert(
  299. this.controlsContainer_, 'Should have a controlsContainer_!');
  300. goog.asserts.assert(this.localVideo_, 'Should have a localVideo_!');
  301. goog.asserts.assert(this.player_, 'Should have a player_!');
  302. this.vr_ = new shaka.ui.VRManager(this.controlsContainer_, this.vrCanvas_,
  303. this.localVideo_, this.player_, this.config_);
  304. }
  305. // Create the new layout
  306. this.createDOM_();
  307. // Init the play state
  308. this.onPlayStateChange_();
  309. // Elements that should not propagate clicks (controls panel, menus)
  310. const noPropagationElements = this.videoContainer_.getElementsByClassName(
  311. 'shaka-no-propagation');
  312. for (const element of noPropagationElements) {
  313. const cb = (event) => event.stopPropagation();
  314. this.eventManager_.listen(element, 'click', cb);
  315. this.eventManager_.listen(element, 'dblclick', cb);
  316. }
  317. }
  318. /**
  319. * Enable or disable the custom controls. Enabling disables native
  320. * browser controls.
  321. *
  322. * @param {boolean} enabled
  323. * @export
  324. */
  325. setEnabledShakaControls(enabled) {
  326. this.enabled_ = enabled;
  327. if (enabled) {
  328. this.videoContainer_.setAttribute('shaka-controls', 'true');
  329. // If we're hiding native controls, make sure the video element itself is
  330. // not tab-navigable. Our custom controls will still be tab-navigable.
  331. this.localVideo_.tabIndex = -1;
  332. this.localVideo_.controls = false;
  333. } else {
  334. this.videoContainer_.removeAttribute('shaka-controls');
  335. }
  336. // The effects of play state changes are inhibited while showing native
  337. // browser controls. Recalculate that state now.
  338. this.onPlayStateChange_();
  339. }
  340. /**
  341. * Enable or disable native browser controls. Enabling disables shaka
  342. * controls.
  343. *
  344. * @param {boolean} enabled
  345. * @export
  346. */
  347. setEnabledNativeControls(enabled) {
  348. // If we enable the native controls, the element must be tab-navigable.
  349. // If we disable the native controls, we want to make sure that the video
  350. // element itself is not tab-navigable, so that the element is skipped over
  351. // when tabbing through the page.
  352. this.localVideo_.controls = enabled;
  353. this.localVideo_.tabIndex = enabled ? 0 : -1;
  354. if (enabled) {
  355. this.setEnabledShakaControls(false);
  356. }
  357. }
  358. /**
  359. * @export
  360. * @return {?shaka.extern.IAd}
  361. */
  362. getAd() {
  363. return this.ad_;
  364. }
  365. /**
  366. * @export
  367. * @return {shaka.cast.CastProxy}
  368. */
  369. getCastProxy() {
  370. return this.castProxy_;
  371. }
  372. /**
  373. * @return {shaka.ui.Localization}
  374. * @export
  375. */
  376. getLocalization() {
  377. return this.localization_;
  378. }
  379. /**
  380. * @return {!HTMLElement}
  381. * @export
  382. */
  383. getVideoContainer() {
  384. return this.videoContainer_;
  385. }
  386. /**
  387. * @return {HTMLMediaElement}
  388. * @export
  389. */
  390. getVideo() {
  391. return this.video_;
  392. }
  393. /**
  394. * @return {HTMLMediaElement}
  395. * @export
  396. */
  397. getLocalVideo() {
  398. return this.localVideo_;
  399. }
  400. /**
  401. * @return {shaka.Player}
  402. * @export
  403. */
  404. getPlayer() {
  405. return this.player_;
  406. }
  407. /**
  408. * @return {shaka.Player}
  409. * @export
  410. */
  411. getLocalPlayer() {
  412. return this.localPlayer_;
  413. }
  414. /**
  415. * @return {!HTMLElement}
  416. * @export
  417. */
  418. getControlsContainer() {
  419. goog.asserts.assert(
  420. this.controlsContainer_, 'No controls container after destruction!');
  421. return this.controlsContainer_;
  422. }
  423. /**
  424. * @return {!HTMLElement}
  425. * @export
  426. */
  427. getServerSideAdContainer() {
  428. return this.daiAdContainer_;
  429. }
  430. /**
  431. * @return {!HTMLElement}
  432. * @export
  433. */
  434. getClientSideAdContainer() {
  435. return this.clientAdContainer_;
  436. }
  437. /**
  438. * @return {!shaka.extern.UIConfiguration}
  439. * @export
  440. */
  441. getConfig() {
  442. return this.config_;
  443. }
  444. /**
  445. * @return {boolean}
  446. * @export
  447. */
  448. isSeeking() {
  449. return this.isSeeking_;
  450. }
  451. /**
  452. * @param {boolean} seeking
  453. * @export
  454. */
  455. setSeeking(seeking) {
  456. this.isSeeking_ = seeking;
  457. }
  458. /**
  459. * @return {boolean}
  460. * @export
  461. */
  462. isCastAllowed() {
  463. return this.castAllowed_;
  464. }
  465. /**
  466. * @return {number}
  467. * @export
  468. */
  469. getDisplayTime() {
  470. return this.seekBar_ ? this.seekBar_.getValue() : this.video_.currentTime;
  471. }
  472. /**
  473. * @param {?number} time
  474. * @export
  475. */
  476. setLastTouchEventTime(time) {
  477. this.lastTouchEventTime_ = time;
  478. }
  479. /**
  480. * @return {boolean}
  481. * @export
  482. */
  483. anySettingsMenusAreOpen() {
  484. return this.menus_.some(
  485. (menu) => !menu.classList.contains('shaka-hidden'));
  486. }
  487. /** @export */
  488. hideSettingsMenus() {
  489. this.hideSettingsMenusTimer_.tickNow();
  490. }
  491. /**
  492. * @return {boolean}
  493. * @export
  494. */
  495. isFullScreenSupported() {
  496. if (document.fullscreenEnabled) {
  497. return true;
  498. }
  499. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  500. if (video.webkitSupportsFullscreen) {
  501. return true;
  502. }
  503. return false;
  504. }
  505. /**
  506. * @return {boolean}
  507. * @export
  508. */
  509. isFullScreenEnabled() {
  510. if (document.fullscreenEnabled) {
  511. return !!document.fullscreenElement;
  512. }
  513. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  514. if (video.webkitSupportsFullscreen) {
  515. return video.webkitDisplayingFullscreen;
  516. }
  517. return false;
  518. }
  519. /** @private */
  520. async enterFullScreen_() {
  521. try {
  522. if (document.fullscreenEnabled) {
  523. if (document.pictureInPictureElement) {
  524. await document.exitPictureInPicture();
  525. }
  526. const fullScreenElement = this.config_.fullScreenElement;
  527. await fullScreenElement.requestFullscreen({navigationUI: 'hide'});
  528. if (this.config_.forceLandscapeOnFullscreen && screen.orientation) {
  529. // Locking to 'landscape' should let it be either
  530. // 'landscape-primary' or 'landscape-secondary' as appropriate.
  531. // We ignore errors from this specific call, since it creates noise
  532. // on desktop otherwise.
  533. try {
  534. await screen.orientation.lock('landscape');
  535. } catch (error) {}
  536. }
  537. } else {
  538. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  539. if (video.webkitSupportsFullscreen) {
  540. video.webkitEnterFullscreen();
  541. }
  542. }
  543. } catch (error) {
  544. // Entering fullscreen can fail without user interaction.
  545. this.dispatchEvent(new shaka.util.FakeEvent(
  546. 'error', (new Map()).set('detail', error)));
  547. }
  548. }
  549. /** @private */
  550. async exitFullScreen_() {
  551. if (document.fullscreenEnabled) {
  552. if (screen.orientation) {
  553. screen.orientation.unlock();
  554. }
  555. await document.exitFullscreen();
  556. } else {
  557. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  558. if (video.webkitSupportsFullscreen) {
  559. video.webkitExitFullscreen();
  560. }
  561. }
  562. }
  563. /** @export */
  564. async toggleFullScreen() {
  565. if (this.isFullScreenEnabled()) {
  566. await this.exitFullScreen_();
  567. } else {
  568. await this.enterFullScreen_();
  569. }
  570. }
  571. /**
  572. * @return {boolean}
  573. * @export
  574. */
  575. isPiPAllowed() {
  576. if (this.castProxy_.isCasting()) {
  577. return false;
  578. }
  579. if ('documentPictureInPicture' in window &&
  580. this.config_.preferDocumentPictureInPicture) {
  581. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  582. return !video.disablePictureInPicture;
  583. }
  584. if (document.pictureInPictureEnabled) {
  585. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  586. return !video.disablePictureInPicture;
  587. }
  588. return false;
  589. }
  590. /**
  591. * @return {boolean}
  592. * @export
  593. */
  594. isPiPEnabled() {
  595. if ('documentPictureInPicture' in window &&
  596. this.config_.preferDocumentPictureInPicture) {
  597. return !!window.documentPictureInPicture.window;
  598. } else {
  599. return !!document.pictureInPictureElement;
  600. }
  601. }
  602. /** @export */
  603. async togglePiP() {
  604. try {
  605. if ('documentPictureInPicture' in window &&
  606. this.config_.preferDocumentPictureInPicture) {
  607. await this.toggleDocumentPictureInPicture_();
  608. } else if (!document.pictureInPictureElement) {
  609. // If you were fullscreen, leave fullscreen first.
  610. if (document.fullscreenElement) {
  611. document.exitFullscreen();
  612. }
  613. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  614. await video.requestPictureInPicture();
  615. } else {
  616. await document.exitPictureInPicture();
  617. }
  618. } catch (error) {
  619. this.dispatchEvent(new shaka.util.FakeEvent(
  620. 'error', (new Map()).set('detail', error)));
  621. }
  622. }
  623. /**
  624. * The Document Picture-in-Picture API makes it possible to open an
  625. * always-on-top window that can be populated with arbitrary HTML content.
  626. * https://developer.chrome.com/docs/web-platform/document-picture-in-picture
  627. * @private
  628. */
  629. async toggleDocumentPictureInPicture_() {
  630. // Close Picture-in-Picture window if any.
  631. if (window.documentPictureInPicture.window) {
  632. window.documentPictureInPicture.window.close();
  633. return;
  634. }
  635. // Open a Picture-in-Picture window.
  636. const pipPlayer = this.videoContainer_;
  637. const rectPipPlayer = pipPlayer.getBoundingClientRect();
  638. const pipWindow = await window.documentPictureInPicture.requestWindow({
  639. width: rectPipPlayer.width,
  640. height: rectPipPlayer.height,
  641. });
  642. // Copy style sheets to the Picture-in-Picture window.
  643. this.copyStyleSheetsToWindow_(pipWindow);
  644. // Add placeholder for the player.
  645. const parentPlayer = pipPlayer.parentNode || document.body;
  646. const placeholder = this.videoContainer_.cloneNode(true);
  647. placeholder.style.visibility = 'hidden';
  648. placeholder.style.height = getComputedStyle(pipPlayer).height;
  649. parentPlayer.appendChild(placeholder);
  650. // Make sure player fits in the Picture-in-Picture window.
  651. const styles = document.createElement('style');
  652. styles.append(`[data-shaka-player-container] {
  653. width: 100% !important; max-height: 100%}`);
  654. pipWindow.document.head.append(styles);
  655. // Move player to the Picture-in-Picture window.
  656. pipWindow.document.body.append(pipPlayer);
  657. // Listen for the PiP closing event to move the player back.
  658. this.eventManager_.listenOnce(pipWindow, 'pagehide', () => {
  659. placeholder.replaceWith(/** @type {!Node} */(pipPlayer));
  660. });
  661. }
  662. /** @private */
  663. copyStyleSheetsToWindow_(win) {
  664. const styleSheets = /** @type {!Iterable<*>} */(document.styleSheets);
  665. const allCSS = [...styleSheets]
  666. .map((sheet) => {
  667. try {
  668. return [...sheet.cssRules].map((rule) => rule.cssText).join('');
  669. } catch (e) {
  670. const link = /** @type {!HTMLLinkElement} */(
  671. document.createElement('link'));
  672. link.rel = 'stylesheet';
  673. link.type = sheet.type;
  674. link.media = sheet.media;
  675. link.href = sheet.href;
  676. win.document.head.appendChild(link);
  677. }
  678. return '';
  679. })
  680. .filter(Boolean)
  681. .join('\n');
  682. const style = document.createElement('style');
  683. style.textContent = allCSS;
  684. win.document.head.appendChild(style);
  685. }
  686. /** @export */
  687. showAdUI() {
  688. shaka.ui.Utils.setDisplay(this.adPanel_, true);
  689. shaka.ui.Utils.setDisplay(this.clientAdContainer_, true);
  690. this.controlsContainer_.setAttribute('ad-active', 'true');
  691. }
  692. /** @export */
  693. hideAdUI() {
  694. shaka.ui.Utils.setDisplay(this.adPanel_, false);
  695. shaka.ui.Utils.setDisplay(this.clientAdContainer_, false);
  696. this.controlsContainer_.removeAttribute('ad-active');
  697. }
  698. /**
  699. * Play or pause the current presentation.
  700. */
  701. playPausePresentation() {
  702. if (!this.enabled_) {
  703. return;
  704. }
  705. if (!this.video_.duration) {
  706. // Can't play yet. Ignore.
  707. return;
  708. }
  709. this.player_.cancelTrickPlay();
  710. if (this.presentationIsPaused()) {
  711. this.video_.play();
  712. } else {
  713. this.video_.pause();
  714. }
  715. }
  716. /**
  717. * Play or pause the current ad.
  718. */
  719. playPauseAd() {
  720. if (this.ad_ && this.ad_.isPaused()) {
  721. this.ad_.play();
  722. } else if (this.ad_) {
  723. this.ad_.pause();
  724. }
  725. }
  726. /**
  727. * Return true if the presentation is paused.
  728. *
  729. * @return {boolean}
  730. */
  731. presentationIsPaused() {
  732. // The video element is in a paused state while seeking, but we don't count
  733. // that.
  734. return this.video_.paused && !this.isSeeking();
  735. }
  736. /** @private */
  737. createDOM_() {
  738. this.videoContainer_.classList.add('shaka-video-container');
  739. this.localVideo_.classList.add('shaka-video');
  740. this.addScrimContainer_();
  741. if (this.config_.addBigPlayButton) {
  742. this.addPlayButton_();
  743. }
  744. if (this.config_.customContextMenu) {
  745. this.addContextMenu_();
  746. }
  747. if (!this.spinnerContainer_) {
  748. this.addBufferingSpinner_();
  749. }
  750. if (this.config_.seekOnTaps) {
  751. this.addFastForwardButtonOnControlsContainer_();
  752. this.addRewindButtonOnControlsContainer_();
  753. }
  754. this.addDaiAdContainer_();
  755. this.addControlsButtonPanel_();
  756. this.menus_ = Array.from(
  757. this.videoContainer_.getElementsByClassName('shaka-settings-menu'));
  758. this.menus_.push(...Array.from(
  759. this.videoContainer_.getElementsByClassName('shaka-overflow-menu')));
  760. this.addSeekBar_();
  761. this.showOnHoverControls_ = Array.from(
  762. this.videoContainer_.getElementsByClassName(
  763. 'shaka-show-controls-on-mouse-over'));
  764. }
  765. /** @private */
  766. addControlsContainer_() {
  767. /** @private {HTMLElement} */
  768. this.controlsContainer_ = shaka.util.Dom.createHTMLElement('div');
  769. this.controlsContainer_.classList.add('shaka-controls-container');
  770. this.videoContainer_.appendChild(this.controlsContainer_);
  771. // Use our controls by default, without anyone calling
  772. // setEnabledShakaControls:
  773. this.videoContainer_.setAttribute('shaka-controls', 'true');
  774. this.eventManager_.listen(this.controlsContainer_, 'touchstart', (e) => {
  775. this.onContainerTouch_(e);
  776. }, {passive: false});
  777. this.eventManager_.listen(this.controlsContainer_, 'click', () => {
  778. this.onContainerClick_();
  779. });
  780. this.eventManager_.listen(this.controlsContainer_, 'dblclick', () => {
  781. if (this.config_.doubleClickForFullscreen &&
  782. this.isFullScreenSupported()) {
  783. this.toggleFullScreen();
  784. }
  785. });
  786. }
  787. /** @private */
  788. addPlayButton_() {
  789. const playButtonContainer = shaka.util.Dom.createHTMLElement('div');
  790. playButtonContainer.classList.add('shaka-play-button-container');
  791. this.controlsContainer_.appendChild(playButtonContainer);
  792. /** @private {shaka.ui.BigPlayButton} */
  793. this.playButton_ =
  794. new shaka.ui.BigPlayButton(playButtonContainer, this);
  795. this.elements_.push(this.playButton_);
  796. }
  797. /** @private */
  798. addContextMenu_() {
  799. /** @private {shaka.ui.ContextMenu} */
  800. this.contextMenu_ =
  801. new shaka.ui.ContextMenu(this.controlsButtonPanel_, this);
  802. this.elements_.push(this.contextMenu_);
  803. }
  804. /** @private */
  805. addScrimContainer_() {
  806. // This is the container that gets styled by CSS to have the
  807. // black gradient scrim at the end of the controls.
  808. const scrimContainer = shaka.util.Dom.createHTMLElement('div');
  809. scrimContainer.classList.add('shaka-scrim-container');
  810. this.controlsContainer_.appendChild(scrimContainer);
  811. }
  812. /** @private */
  813. addAdControls_() {
  814. /** @private {!HTMLElement} */
  815. this.adPanel_ = shaka.util.Dom.createHTMLElement('div');
  816. this.adPanel_.classList.add('shaka-ad-controls');
  817. const showAdPanel = this.ad_ != null && this.ad_.isLinear();
  818. shaka.ui.Utils.setDisplay(this.adPanel_, showAdPanel);
  819. this.bottomControls_.appendChild(this.adPanel_);
  820. const adPosition = new shaka.ui.AdPosition(this.adPanel_, this);
  821. this.elements_.push(adPosition);
  822. const adCounter = new shaka.ui.AdCounter(this.adPanel_, this);
  823. this.elements_.push(adCounter);
  824. const skipButton = new shaka.ui.SkipAdButton(this.adPanel_, this);
  825. this.elements_.push(skipButton);
  826. }
  827. /** @private */
  828. addBufferingSpinner_() {
  829. /** @private {!HTMLElement} */
  830. this.spinnerContainer_ = shaka.util.Dom.createHTMLElement('div');
  831. this.spinnerContainer_.classList.add('shaka-spinner-container');
  832. this.videoContainer_.appendChild(this.spinnerContainer_);
  833. const spinner = shaka.util.Dom.createHTMLElement('div');
  834. spinner.classList.add('shaka-spinner');
  835. this.spinnerContainer_.appendChild(spinner);
  836. // Svg elements have to be created with the svg xml namespace.
  837. const xmlns = 'http://www.w3.org/2000/svg';
  838. const svg =
  839. /** @type {!HTMLElement} */(document.createElementNS(xmlns, 'svg'));
  840. svg.classList.add('shaka-spinner-svg');
  841. svg.setAttribute('viewBox', '0 0 30 30');
  842. spinner.appendChild(svg);
  843. // These coordinates are relative to the SVG viewBox above. This is
  844. // distinct from the actual display size in the page, since the "S" is for
  845. // "Scalable." The radius of 14.5 is so that the edges of the 1-px-wide
  846. // stroke will touch the edges of the viewBox.
  847. const spinnerCircle = document.createElementNS(xmlns, 'circle');
  848. spinnerCircle.classList.add('shaka-spinner-path');
  849. spinnerCircle.setAttribute('cx', '15');
  850. spinnerCircle.setAttribute('cy', '15');
  851. spinnerCircle.setAttribute('r', '14.5');
  852. spinnerCircle.setAttribute('fill', 'none');
  853. spinnerCircle.setAttribute('stroke-width', '1');
  854. spinnerCircle.setAttribute('stroke-miterlimit', '10');
  855. svg.appendChild(spinnerCircle);
  856. }
  857. /**
  858. * Add fast-forward button on Controls container for moving video some
  859. * seconds ahead when the video is tapped more than once, video seeks ahead
  860. * some seconds for every extra tap.
  861. * @private
  862. */
  863. addFastForwardButtonOnControlsContainer_() {
  864. const hiddenFastForwardContainer = shaka.util.Dom.createHTMLElement('div');
  865. hiddenFastForwardContainer.classList.add(
  866. 'shaka-hidden-fast-forward-container');
  867. this.controlsContainer_.appendChild(hiddenFastForwardContainer);
  868. /** @private {shaka.ui.HiddenFastForwardButton} */
  869. this.hiddenFastForwardButton_ =
  870. new shaka.ui.HiddenFastForwardButton(hiddenFastForwardContainer, this);
  871. this.elements_.push(this.hiddenFastForwardButton_);
  872. }
  873. /**
  874. * Add Rewind button on Controls container for moving video some seconds
  875. * behind when the video is tapped more than once, video seeks behind some
  876. * seconds for every extra tap.
  877. * @private
  878. */
  879. addRewindButtonOnControlsContainer_() {
  880. const hiddenRewindContainer = shaka.util.Dom.createHTMLElement('div');
  881. hiddenRewindContainer.classList.add(
  882. 'shaka-hidden-rewind-container');
  883. this.controlsContainer_.appendChild(hiddenRewindContainer);
  884. /** @private {shaka.ui.HiddenRewindButton} */
  885. this.hiddenRewindButton_ =
  886. new shaka.ui.HiddenRewindButton(hiddenRewindContainer, this);
  887. this.elements_.push(this.hiddenRewindButton_);
  888. }
  889. /** @private */
  890. addControlsButtonPanel_() {
  891. /** @private {!HTMLElement} */
  892. this.bottomControls_ = shaka.util.Dom.createHTMLElement('div');
  893. this.bottomControls_.classList.add('shaka-bottom-controls');
  894. this.bottomControls_.classList.add('shaka-no-propagation');
  895. this.controlsContainer_.appendChild(this.bottomControls_);
  896. // Overflow menus are supposed to hide once you click elsewhere
  897. // on the page. The click event listener on window ensures that.
  898. // However, clicks on the bottom controls don't propagate to the container,
  899. // so we have to explicitly hide the menus onclick here.
  900. this.eventManager_.listen(this.bottomControls_, 'click', (e) => {
  901. // We explicitly deny this measure when clicking on buttons that
  902. // open submenus in the control panel.
  903. if (!e.target['closest']('.shaka-overflow-button')) {
  904. this.hideSettingsMenus();
  905. }
  906. });
  907. this.addAdControls_();
  908. /** @private {!HTMLElement} */
  909. this.controlsButtonPanel_ = shaka.util.Dom.createHTMLElement('div');
  910. this.controlsButtonPanel_.classList.add('shaka-controls-button-panel');
  911. this.controlsButtonPanel_.classList.add(
  912. 'shaka-show-controls-on-mouse-over');
  913. if (this.config_.enableTooltips) {
  914. this.controlsButtonPanel_.classList.add('shaka-tooltips-on');
  915. }
  916. this.bottomControls_.appendChild(this.controlsButtonPanel_);
  917. // Create the elements specified by controlPanelElements
  918. for (const name of this.config_.controlPanelElements) {
  919. if (shaka.ui.ControlsPanel.elementNamesToFactories_.get(name)) {
  920. const factory =
  921. shaka.ui.ControlsPanel.elementNamesToFactories_.get(name);
  922. const element = factory.create(this.controlsButtonPanel_, this);
  923. this.elements_.push(element);
  924. } else {
  925. shaka.log.alwaysWarn('Unrecognized control panel element requested:',
  926. name);
  927. }
  928. }
  929. }
  930. /**
  931. * Adds a container for server side ad UI with IMA SDK.
  932. *
  933. * @private
  934. */
  935. addDaiAdContainer_() {
  936. /** @private {!HTMLElement} */
  937. this.daiAdContainer_ = shaka.util.Dom.createHTMLElement('div');
  938. this.daiAdContainer_.classList.add('shaka-server-side-ad-container');
  939. this.controlsContainer_.appendChild(this.daiAdContainer_);
  940. }
  941. /**
  942. * Adds a seekbar depending on the configuration.
  943. * By default an instance of shaka.ui.SeekBar is created
  944. * This behaviour can be overriden by providing a SeekBar factory using the
  945. * registerSeekBarFactory function.
  946. *
  947. * @private
  948. */
  949. addSeekBar_() {
  950. if (this.config_.addSeekBar) {
  951. this.seekBar_ = shaka.ui.ControlsPanel.seekBarFactory_.create(
  952. this.bottomControls_, this);
  953. this.elements_.push(this.seekBar_);
  954. } else {
  955. // Settings menus need to be positioned lower if the seekbar is absent.
  956. for (const menu of this.menus_) {
  957. menu.classList.add('shaka-low-position');
  958. }
  959. }
  960. }
  961. /**
  962. * Adds a container for client side ad UI with IMA SDK.
  963. *
  964. * @private
  965. */
  966. addClientAdContainer_() {
  967. /** @private {!HTMLElement} */
  968. this.clientAdContainer_ = shaka.util.Dom.createHTMLElement('div');
  969. this.clientAdContainer_.classList.add('shaka-client-side-ad-container');
  970. shaka.ui.Utils.setDisplay(this.clientAdContainer_, false);
  971. this.eventManager_.listen(this.clientAdContainer_, 'click', () => {
  972. this.onContainerClick_();
  973. });
  974. this.videoContainer_.appendChild(this.clientAdContainer_);
  975. }
  976. /**
  977. * Adds static event listeners. This should only add event listeners to
  978. * things that don't change (e.g. Player). Dynamic elements (e.g. controls)
  979. * should have their event listeners added when they are created.
  980. *
  981. * @private
  982. */
  983. addEventListeners_() {
  984. this.eventManager_.listen(this.player_, 'buffering', () => {
  985. this.onBufferingStateChange_();
  986. });
  987. // Set the initial state, as well.
  988. this.onBufferingStateChange_();
  989. // Listen for key down events to detect tab and enable outline
  990. // for focused elements.
  991. this.eventManager_.listen(window, 'keydown', (e) => {
  992. this.onWindowKeyDown_(/** @type {!KeyboardEvent} */(e));
  993. });
  994. // Listen for click events to dismiss the settings menus.
  995. this.eventManager_.listen(window, 'click', () => this.hideSettingsMenus());
  996. // Avoid having multiple submenus open at the same time.
  997. this.eventManager_.listen(
  998. this, 'submenuopen', () => {
  999. this.hideSettingsMenus();
  1000. });
  1001. this.eventManager_.listen(this.video_, 'play', () => {
  1002. this.onPlayStateChange_();
  1003. });
  1004. this.eventManager_.listen(this.video_, 'pause', () => {
  1005. this.onPlayStateChange_();
  1006. });
  1007. this.eventManager_.listen(this.videoContainer_, 'mousemove', (e) => {
  1008. this.onMouseMove_(e);
  1009. });
  1010. this.eventManager_.listen(this.videoContainer_, 'touchmove', (e) => {
  1011. this.onMouseMove_(e);
  1012. }, {passive: true});
  1013. this.eventManager_.listen(this.videoContainer_, 'touchend', (e) => {
  1014. this.onMouseMove_(e);
  1015. }, {passive: true});
  1016. this.eventManager_.listen(this.videoContainer_, 'mouseleave', () => {
  1017. this.onMouseLeave_();
  1018. });
  1019. this.eventManager_.listen(this.castProxy_, 'caststatuschanged', () => {
  1020. this.onCastStatusChange_();
  1021. });
  1022. this.eventManager_.listen(this.vr_, 'vrstatuschanged', () => {
  1023. this.dispatchEvent(new shaka.util.FakeEvent('vrstatuschanged'));
  1024. });
  1025. this.eventManager_.listen(this.videoContainer_, 'keydown', (e) => {
  1026. this.onControlsKeyDown_(/** @type {!KeyboardEvent} */(e));
  1027. });
  1028. this.eventManager_.listen(this.videoContainer_, 'keyup', (e) => {
  1029. this.onControlsKeyUp_(/** @type {!KeyboardEvent} */(e));
  1030. });
  1031. this.eventManager_.listen(
  1032. this.adManager_, shaka.ads.AdManager.AD_STARTED, (e) => {
  1033. this.ad_ = (/** @type {!Object} */ (e))['ad'];
  1034. this.showAdUI();
  1035. });
  1036. this.eventManager_.listen(
  1037. this.adManager_, shaka.ads.AdManager.AD_STOPPED, () => {
  1038. this.ad_ = null;
  1039. this.hideAdUI();
  1040. });
  1041. if (screen.orientation) {
  1042. this.eventManager_.listen(screen.orientation, 'change', async () => {
  1043. await this.onScreenRotation_();
  1044. });
  1045. }
  1046. }
  1047. /**
  1048. * When a mobile device is rotated to landscape layout, and the video is
  1049. * loaded, make the demo app go into fullscreen.
  1050. * Similarly, exit fullscreen when the device is rotated to portrait layout.
  1051. * @private
  1052. */
  1053. async onScreenRotation_() {
  1054. if (!this.video_ ||
  1055. this.video_.readyState == 0 ||
  1056. this.castProxy_.isCasting() ||
  1057. !this.config_.enableFullscreenOnRotation ||
  1058. !this.isFullScreenSupported()) {
  1059. return;
  1060. }
  1061. if (screen.orientation.type.includes('landscape') &&
  1062. !this.isFullScreenEnabled()) {
  1063. await this.enterFullScreen_();
  1064. } else if (screen.orientation.type.includes('portrait') &&
  1065. this.isFullScreenEnabled()) {
  1066. await this.exitFullScreen_();
  1067. }
  1068. }
  1069. /**
  1070. * Hiding the cursor when the mouse stops moving seems to be the only
  1071. * decent UX in fullscreen mode. Since we can't use pure CSS for that,
  1072. * we use events both in and out of fullscreen mode.
  1073. * Showing the control bar when a key is pressed, and hiding it after some
  1074. * time.
  1075. * @param {!Event} event
  1076. * @private
  1077. */
  1078. onMouseMove_(event) {
  1079. // Disable blue outline for focused elements for mouse navigation.
  1080. if (event.type == 'mousemove') {
  1081. this.controlsContainer_.classList.remove('shaka-keyboard-navigation');
  1082. this.computeOpacity();
  1083. }
  1084. if (event.type == 'touchstart' || event.type == 'touchmove' ||
  1085. event.type == 'touchend' || event.type == 'keyup') {
  1086. this.lastTouchEventTime_ = Date.now();
  1087. } else if (this.lastTouchEventTime_ + 1000 < Date.now()) {
  1088. // It has been a while since the last touch event, this is probably a real
  1089. // mouse moving, so treat it like a mouse.
  1090. this.lastTouchEventTime_ = null;
  1091. }
  1092. // When there is a touch, we can get a 'mousemove' event after touch events.
  1093. // This should be treated as part of the touch, which has already been
  1094. // handled.
  1095. if (this.lastTouchEventTime_ && event.type == 'mousemove') {
  1096. return;
  1097. }
  1098. // Use the cursor specified in the CSS file.
  1099. this.videoContainer_.style.cursor = '';
  1100. this.recentMouseMovement_ = true;
  1101. // Make sure we are not about to hide the settings menus and then force them
  1102. // open.
  1103. this.hideSettingsMenusTimer_.stop();
  1104. if (!this.isOpaque()) {
  1105. // Only update the time and seek range on mouse movement if it's the very
  1106. // first movement and we're about to show the controls. Otherwise, the
  1107. // seek bar will be updated much more rapidly during mouse movement. Do
  1108. // this right before making it visible.
  1109. this.updateTimeAndSeekRange_();
  1110. this.computeOpacity();
  1111. }
  1112. // Hide the cursor when the mouse stops moving.
  1113. // Only applies while the cursor is over the video container.
  1114. this.mouseStillTimer_.stop();
  1115. // Only start a timeout on 'touchend' or for 'mousemove' with no touch
  1116. // events.
  1117. if (event.type == 'touchend' ||
  1118. event.type == 'keyup'|| !this.lastTouchEventTime_) {
  1119. this.mouseStillTimer_.tickAfter(/* seconds= */ 3);
  1120. }
  1121. }
  1122. /** @private */
  1123. onMouseLeave_() {
  1124. // We sometimes get 'mouseout' events with touches. Since we can never
  1125. // leave the video element when touching, ignore.
  1126. if (this.lastTouchEventTime_) {
  1127. return;
  1128. }
  1129. // Stop the timer and invoke the callback now to hide the controls. If we
  1130. // don't, the opacity style we set in onMouseMove_ will continue to override
  1131. // the opacity in CSS and force the controls to stay visible.
  1132. this.mouseStillTimer_.tickNow();
  1133. }
  1134. /**
  1135. * This callback is for when we are pretty sure that the mouse has stopped
  1136. * moving (aka the mouse is still). This method should only be called via
  1137. * |mouseStillTimer_|. If this behaviour needs to be invoked directly, use
  1138. * |mouseStillTimer_.tickNow()|.
  1139. *
  1140. * @private
  1141. */
  1142. onMouseStill_() {
  1143. // Hide the cursor.
  1144. this.videoContainer_.style.cursor = 'none';
  1145. this.recentMouseMovement_ = false;
  1146. this.computeOpacity();
  1147. }
  1148. /**
  1149. * @return {boolean} true if any relevant elements are hovered.
  1150. * @private
  1151. */
  1152. isHovered_() {
  1153. if (!window.matchMedia('hover: hover').matches) {
  1154. // This is primarily a touch-screen device, so the :hover query below
  1155. // doesn't make sense. In spite of this, the :hover query on an element
  1156. // can still return true on such a device after a touch ends.
  1157. // See https://bit.ly/34dBORX for details.
  1158. return false;
  1159. }
  1160. return this.showOnHoverControls_.some((element) => {
  1161. return element.matches(':hover');
  1162. });
  1163. }
  1164. /**
  1165. * Recompute whether the controls should be shown or hidden.
  1166. */
  1167. computeOpacity() {
  1168. const adIsPaused = this.ad_ ? this.ad_.isPaused() : false;
  1169. const videoIsPaused = this.video_.paused && !this.isSeeking_;
  1170. const keyboardNavigationMode = this.controlsContainer_.classList.contains(
  1171. 'shaka-keyboard-navigation');
  1172. // Keep showing the controls if the ad or video is paused, there has been
  1173. // recent mouse movement, we're in keyboard navigation, or one of a special
  1174. // class of elements is hovered.
  1175. if (adIsPaused ||
  1176. ((!this.ad_ || !this.ad_.isLinear()) && videoIsPaused) ||
  1177. this.recentMouseMovement_ ||
  1178. keyboardNavigationMode ||
  1179. this.isHovered_()) {
  1180. // Make sure the state is up-to-date before showing it.
  1181. this.updateTimeAndSeekRange_();
  1182. this.controlsContainer_.setAttribute('shown', 'true');
  1183. this.fadeControlsTimer_.stop();
  1184. } else {
  1185. this.fadeControlsTimer_.tickAfter(/* seconds= */ this.config_.fadeDelay);
  1186. }
  1187. }
  1188. /**
  1189. * @param {!Event} event
  1190. * @private
  1191. */
  1192. onContainerTouch_(event) {
  1193. if (!this.video_.duration) {
  1194. // Can't play yet. Ignore.
  1195. return;
  1196. }
  1197. if (this.isOpaque()) {
  1198. this.lastTouchEventTime_ = Date.now();
  1199. // The controls are showing.
  1200. // Let this event continue and become a click.
  1201. } else {
  1202. // The controls are hidden, so show them.
  1203. this.onMouseMove_(event);
  1204. // Stop this event from becoming a click event.
  1205. event.cancelable && event.preventDefault();
  1206. }
  1207. }
  1208. /** @private */
  1209. onContainerClick_() {
  1210. if (!this.enabled_ || this.isPlayingVR()) {
  1211. return;
  1212. }
  1213. if (this.anySettingsMenusAreOpen()) {
  1214. this.hideSettingsMenusTimer_.tickNow();
  1215. } else if (this.config_.singleClickForPlayAndPause) {
  1216. this.onPlayPauseClick_();
  1217. }
  1218. }
  1219. /** @private */
  1220. onPlayPauseClick_() {
  1221. if (this.ad_ && this.ad_.isLinear()) {
  1222. this.playPauseAd();
  1223. } else {
  1224. this.playPausePresentation();
  1225. }
  1226. }
  1227. /** @private */
  1228. onCastStatusChange_() {
  1229. const isCasting = this.castProxy_.isCasting();
  1230. this.dispatchEvent(new shaka.util.FakeEvent(
  1231. 'caststatuschanged', (new Map()).set('newStatus', isCasting)));
  1232. if (isCasting) {
  1233. this.controlsContainer_.setAttribute('casting', 'true');
  1234. } else {
  1235. this.controlsContainer_.removeAttribute('casting');
  1236. }
  1237. }
  1238. /** @private */
  1239. onPlayStateChange_() {
  1240. this.computeOpacity();
  1241. }
  1242. /**
  1243. * Support controls with keyboard inputs.
  1244. * @param {!KeyboardEvent} event
  1245. * @private
  1246. */
  1247. onControlsKeyDown_(event) {
  1248. const activeElement = document.activeElement;
  1249. const isVolumeBar = activeElement && activeElement.classList ?
  1250. activeElement.classList.contains('shaka-volume-bar') : false;
  1251. const isSeekBar = activeElement && activeElement.classList &&
  1252. activeElement.classList.contains('shaka-seek-bar');
  1253. // Show the control panel if it is on focus or any button is pressed.
  1254. if (this.controlsContainer_.contains(activeElement)) {
  1255. this.onMouseMove_(event);
  1256. }
  1257. if (!this.config_.enableKeyboardPlaybackControls) {
  1258. return;
  1259. }
  1260. const keyboardSeekDistance = this.config_.keyboardSeekDistance;
  1261. const keyboardLargeSeekDistance = this.config_.keyboardLargeSeekDistance;
  1262. switch (event.key) {
  1263. case 'ArrowLeft':
  1264. // If it's not focused on the volume bar, move the seek time backward
  1265. // for a few sec. Otherwise, the volume will be adjusted automatically.
  1266. if (this.seekBar_ && isSeekBar && !isVolumeBar &&
  1267. keyboardSeekDistance > 0) {
  1268. event.preventDefault();
  1269. this.seek_(this.seekBar_.getValue() - keyboardSeekDistance);
  1270. }
  1271. break;
  1272. case 'ArrowRight':
  1273. // If it's not focused on the volume bar, move the seek time forward
  1274. // for a few sec. Otherwise, the volume will be adjusted automatically.
  1275. if (this.seekBar_ && isSeekBar && !isVolumeBar &&
  1276. keyboardSeekDistance > 0) {
  1277. event.preventDefault();
  1278. this.seek_(this.seekBar_.getValue() + keyboardSeekDistance);
  1279. }
  1280. break;
  1281. case 'PageDown':
  1282. // PageDown is like ArrowLeft, but has a larger jump distance, and does
  1283. // nothing to volume.
  1284. if (this.seekBar_ && isSeekBar && keyboardSeekDistance > 0) {
  1285. event.preventDefault();
  1286. this.seek_(this.seekBar_.getValue() - keyboardLargeSeekDistance);
  1287. }
  1288. break;
  1289. case 'PageUp':
  1290. // PageDown is like ArrowRight, but has a larger jump distance, and does
  1291. // nothing to volume.
  1292. if (this.seekBar_ && isSeekBar && keyboardSeekDistance > 0) {
  1293. event.preventDefault();
  1294. this.seek_(this.seekBar_.getValue() + keyboardLargeSeekDistance);
  1295. }
  1296. break;
  1297. // Jump to the beginning of the video's seek range.
  1298. case 'Home':
  1299. if (this.seekBar_) {
  1300. this.seek_(this.player_.seekRange().start);
  1301. }
  1302. break;
  1303. // Jump to the end of the video's seek range.
  1304. case 'End':
  1305. if (this.seekBar_) {
  1306. this.seek_(this.player_.seekRange().end);
  1307. }
  1308. break;
  1309. case 'f':
  1310. if (this.isFullScreenSupported()) {
  1311. this.toggleFullScreen();
  1312. }
  1313. break;
  1314. case 'm':
  1315. if (this.ad_ && this.ad_.isLinear()) {
  1316. this.ad_.setMuted(!this.ad_.isMuted());
  1317. } else {
  1318. this.localVideo_.muted = !this.localVideo_.muted;
  1319. }
  1320. break;
  1321. case 'p':
  1322. if (this.isPiPAllowed()) {
  1323. this.togglePiP();
  1324. }
  1325. break;
  1326. // Pause or play by pressing space on the seek bar.
  1327. case ' ':
  1328. if (isSeekBar) {
  1329. this.onPlayPauseClick_();
  1330. }
  1331. break;
  1332. }
  1333. }
  1334. /**
  1335. * Support controls with keyboard inputs.
  1336. * @param {!KeyboardEvent} event
  1337. * @private
  1338. */
  1339. onControlsKeyUp_(event) {
  1340. // When the key is released, remove it from the pressed keys set.
  1341. this.pressedKeys_.delete(event.key);
  1342. }
  1343. /**
  1344. * Called both as an event listener and directly by the controls to initialize
  1345. * the buffering state.
  1346. * @private
  1347. */
  1348. onBufferingStateChange_() {
  1349. if (!this.enabled_) {
  1350. return;
  1351. }
  1352. shaka.ui.Utils.setDisplay(
  1353. this.spinnerContainer_, this.player_.isBuffering());
  1354. }
  1355. /**
  1356. * @return {boolean}
  1357. * @export
  1358. */
  1359. isOpaque() {
  1360. if (!this.enabled_) {
  1361. return false;
  1362. }
  1363. return this.controlsContainer_.getAttribute('shown') != null ||
  1364. this.controlsContainer_.getAttribute('casting') != null;
  1365. }
  1366. /**
  1367. * Update the video's current time based on the keyboard operations.
  1368. *
  1369. * @param {number} currentTime
  1370. * @private
  1371. */
  1372. seek_(currentTime) {
  1373. goog.asserts.assert(
  1374. this.seekBar_, 'Caller of seek_ must check for seekBar_ first!');
  1375. this.seekBar_.changeTo(currentTime);
  1376. if (this.isOpaque()) {
  1377. // Only update the time and seek range if it's visible.
  1378. this.updateTimeAndSeekRange_();
  1379. }
  1380. }
  1381. /**
  1382. * Called when the seek range or current time need to be updated.
  1383. * @private
  1384. */
  1385. updateTimeAndSeekRange_() {
  1386. if (this.seekBar_) {
  1387. this.seekBar_.setValue(this.video_.currentTime);
  1388. this.seekBar_.update();
  1389. if (this.seekBar_.isShowing()) {
  1390. for (const menu of this.menus_) {
  1391. menu.classList.remove('shaka-low-position');
  1392. }
  1393. } else {
  1394. for (const menu of this.menus_) {
  1395. menu.classList.add('shaka-low-position');
  1396. }
  1397. }
  1398. }
  1399. this.dispatchEvent(new shaka.util.FakeEvent('timeandseekrangeupdated'));
  1400. }
  1401. /**
  1402. * Add behaviors for keyboard navigation.
  1403. * 1. Add blue outline for focused elements.
  1404. * 2. Allow exiting overflow settings menus by pressing Esc key.
  1405. * 3. When navigating on overflow settings menu by pressing Tab
  1406. * key or Shift+Tab keys keep the focus inside overflow menu.
  1407. *
  1408. * @param {!KeyboardEvent} event
  1409. * @private
  1410. */
  1411. onWindowKeyDown_(event) {
  1412. // Add the key to the pressed keys set when it's pressed.
  1413. this.pressedKeys_.add(event.key);
  1414. const anySettingsMenusAreOpen = this.anySettingsMenusAreOpen();
  1415. if (event.key == 'Tab') {
  1416. // Enable blue outline for focused elements for keyboard
  1417. // navigation.
  1418. this.controlsContainer_.classList.add('shaka-keyboard-navigation');
  1419. this.computeOpacity();
  1420. this.eventManager_.listen(window, 'mousedown', () => this.onMouseDown_());
  1421. }
  1422. // If escape key was pressed, close any open settings menus.
  1423. if (event.key == 'Escape') {
  1424. this.hideSettingsMenusTimer_.tickNow();
  1425. }
  1426. if (anySettingsMenusAreOpen && this.pressedKeys_.has('Tab')) {
  1427. // If Tab key or Shift+Tab keys are pressed when navigating through
  1428. // an overflow settings menu, keep the focus to loop inside the
  1429. // overflow menu.
  1430. this.keepFocusInMenu_(event);
  1431. }
  1432. }
  1433. /**
  1434. * When the user is using keyboard to navigate inside the overflow settings
  1435. * menu (pressing Tab key to go forward, or pressing Shift + Tab keys to go
  1436. * backward), make sure it's focused only on the elements of the overflow
  1437. * panel.
  1438. *
  1439. * This is called by onWindowKeyDown_() function, when there's a settings
  1440. * overflow menu open, and the Tab key / Shift+Tab keys are pressed.
  1441. *
  1442. * @param {!Event} event
  1443. * @private
  1444. */
  1445. keepFocusInMenu_(event) {
  1446. const openSettingsMenus = this.menus_.filter(
  1447. (menu) => !menu.classList.contains('shaka-hidden'));
  1448. if (!openSettingsMenus.length) {
  1449. // For example, this occurs when you hit escape to close the menu.
  1450. return;
  1451. }
  1452. const settingsMenu = openSettingsMenus[0];
  1453. if (settingsMenu.childNodes.length) {
  1454. // Get the first and the last displaying child element from the overflow
  1455. // menu.
  1456. let firstShownChild = settingsMenu.firstElementChild;
  1457. while (firstShownChild &&
  1458. firstShownChild.classList.contains('shaka-hidden')) {
  1459. firstShownChild = firstShownChild.nextElementSibling;
  1460. }
  1461. let lastShownChild = settingsMenu.lastElementChild;
  1462. while (lastShownChild &&
  1463. lastShownChild.classList.contains('shaka-hidden')) {
  1464. lastShownChild = lastShownChild.previousElementSibling;
  1465. }
  1466. const activeElement = document.activeElement;
  1467. // When only Tab key is pressed, navigate to the next elememnt.
  1468. // If it's currently focused on the last shown child element of the
  1469. // overflow menu, let the focus move to the first child element of the
  1470. // menu.
  1471. // When Tab + Shift keys are pressed at the same time, navigate to the
  1472. // previous element. If it's currently focused on the first shown child
  1473. // element of the overflow menu, let the focus move to the last child
  1474. // element of the menu.
  1475. if (this.pressedKeys_.has('Shift')) {
  1476. if (activeElement == firstShownChild) {
  1477. event.preventDefault();
  1478. lastShownChild.focus();
  1479. }
  1480. } else {
  1481. if (activeElement == lastShownChild) {
  1482. event.preventDefault();
  1483. firstShownChild.focus();
  1484. }
  1485. }
  1486. }
  1487. }
  1488. /**
  1489. * For keyboard navigation, we use blue borders to highlight the active
  1490. * element. If we detect that a mouse is being used, remove the blue border
  1491. * from the active element.
  1492. * @private
  1493. */
  1494. onMouseDown_() {
  1495. this.eventManager_.unlisten(window, 'mousedown');
  1496. }
  1497. /**
  1498. * @export
  1499. */
  1500. showUI() {
  1501. const event = new Event('mousemove', {bubbles: false, cancelable: false});
  1502. this.onMouseMove_(event);
  1503. }
  1504. /**
  1505. * @export
  1506. */
  1507. hideUI() {
  1508. this.onMouseLeave_();
  1509. }
  1510. /**
  1511. * @return {shaka.ui.VRManager}
  1512. */
  1513. getVR() {
  1514. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1515. return this.vr_;
  1516. }
  1517. /**
  1518. * Returns if a VR is capable.
  1519. *
  1520. * @return {boolean}
  1521. * @export
  1522. */
  1523. canPlayVR() {
  1524. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1525. return this.vr_.canPlayVR();
  1526. }
  1527. /**
  1528. * Returns if a VR is supported.
  1529. *
  1530. * @return {boolean}
  1531. * @export
  1532. */
  1533. isPlayingVR() {
  1534. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1535. return this.vr_.isPlayingVR();
  1536. }
  1537. /**
  1538. * Reset VR view.
  1539. */
  1540. resetVR() {
  1541. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1542. this.vr_.reset();
  1543. }
  1544. /**
  1545. * Get the angle of the north.
  1546. *
  1547. * @return {?number}
  1548. * @export
  1549. */
  1550. getVRNorth() {
  1551. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1552. return this.vr_.getNorth();
  1553. }
  1554. /**
  1555. * Returns the angle of the current field of view displayed in degrees.
  1556. *
  1557. * @return {?number}
  1558. * @export
  1559. */
  1560. getVRFieldOfView() {
  1561. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1562. return this.vr_.getFieldOfView();
  1563. }
  1564. /**
  1565. * Changing the field of view increases or decreases the portion of the video
  1566. * that is viewed at one time. If the field of view is decreased, a small
  1567. * part of the video will be seen, but with more detail. If the field of view
  1568. * is increased, a larger part of the video will be seen, but with less
  1569. * detail.
  1570. *
  1571. * @param {number} fieldOfView In degrees
  1572. * @export
  1573. */
  1574. setVRFieldOfView(fieldOfView) {
  1575. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1576. this.vr_.setFieldOfView(fieldOfView);
  1577. }
  1578. /**
  1579. * Toggle stereoscopic mode.
  1580. *
  1581. * @export
  1582. */
  1583. toggleStereoscopicMode() {
  1584. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1585. this.vr_.toggleStereoscopicMode();
  1586. }
  1587. /**
  1588. * Returns true if stereoscopic mode is enabled.
  1589. *
  1590. * @return {boolean}
  1591. */
  1592. isStereoscopicModeEnabled() {
  1593. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1594. return this.vr_.isStereoscopicModeEnabled();
  1595. }
  1596. /**
  1597. * Increment the yaw in X angle in degrees.
  1598. *
  1599. * @param {number} angle In degrees
  1600. * @export
  1601. */
  1602. incrementYaw(angle) {
  1603. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1604. this.vr_.incrementYaw(angle);
  1605. }
  1606. /**
  1607. * Increment the pitch in X angle in degrees.
  1608. *
  1609. * @param {number} angle In degrees
  1610. * @export
  1611. */
  1612. incrementPitch(angle) {
  1613. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1614. this.vr_.incrementPitch(angle);
  1615. }
  1616. /**
  1617. * Increment the roll in X angle in degrees.
  1618. *
  1619. * @param {number} angle In degrees
  1620. * @export
  1621. */
  1622. incrementRoll(angle) {
  1623. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1624. this.vr_.incrementRoll(angle);
  1625. }
  1626. /**
  1627. * Create a localization instance already pre-loaded with all the locales that
  1628. * we support.
  1629. *
  1630. * @return {!shaka.ui.Localization}
  1631. * @private
  1632. */
  1633. static createLocalization_() {
  1634. /** @type {string} */
  1635. const fallbackLocale = 'en';
  1636. /** @type {!shaka.ui.Localization} */
  1637. const localization = new shaka.ui.Localization(fallbackLocale);
  1638. shaka.ui.Locales.addTo(localization);
  1639. localization.changeLocale(navigator.languages || []);
  1640. return localization;
  1641. }
  1642. };
  1643. /**
  1644. * @event shaka.ui.Controls#CastStatusChangedEvent
  1645. * @description Fired upon receiving a 'caststatuschanged' event from
  1646. * the cast proxy.
  1647. * @property {string} type
  1648. * 'caststatuschanged'
  1649. * @property {boolean} newStatus
  1650. * The new status of the application. True for 'is casting' and
  1651. * false otherwise.
  1652. * @exportDoc
  1653. */
  1654. /**
  1655. * @event shaka.ui.Controls#VRStatusChangedEvent
  1656. * @description Fired when VR status change
  1657. * @property {string} type
  1658. * 'vrstatuschanged'
  1659. * @exportDoc
  1660. */
  1661. /**
  1662. * @event shaka.ui.Controls#SubMenuOpenEvent
  1663. * @description Fired when one of the overflow submenus is opened
  1664. * (e. g. language/resolution/subtitle selection).
  1665. * @property {string} type
  1666. * 'submenuopen'
  1667. * @exportDoc
  1668. */
  1669. /**
  1670. * @event shaka.ui.Controls#CaptionSelectionUpdatedEvent
  1671. * @description Fired when the captions/subtitles menu has finished updating.
  1672. * @property {string} type
  1673. * 'captionselectionupdated'
  1674. * @exportDoc
  1675. */
  1676. /**
  1677. * @event shaka.ui.Controls#ResolutionSelectionUpdatedEvent
  1678. * @description Fired when the resolution menu has finished updating.
  1679. * @property {string} type
  1680. * 'resolutionselectionupdated'
  1681. * @exportDoc
  1682. */
  1683. /**
  1684. * @event shaka.ui.Controls#LanguageSelectionUpdatedEvent
  1685. * @description Fired when the audio language menu has finished updating.
  1686. * @property {string} type
  1687. * 'languageselectionupdated'
  1688. * @exportDoc
  1689. */
  1690. /**
  1691. * @event shaka.ui.Controls#ErrorEvent
  1692. * @description Fired when something went wrong with the controls.
  1693. * @property {string} type
  1694. * 'error'
  1695. * @property {!shaka.util.Error} detail
  1696. * An object which contains details on the error. The error's 'category'
  1697. * and 'code' properties will identify the specific error that occurred.
  1698. * In an uncompiled build, you can also use the 'message' and 'stack'
  1699. * properties to debug.
  1700. * @exportDoc
  1701. */
  1702. /**
  1703. * @event shaka.ui.Controls#TimeAndSeekRangeUpdatedEvent
  1704. * @description Fired when the time and seek range elements have finished
  1705. * updating.
  1706. * @property {string} type
  1707. * 'timeandseekrangeupdated'
  1708. * @exportDoc
  1709. */
  1710. /**
  1711. * @event shaka.ui.Controls#UIUpdatedEvent
  1712. * @description Fired after a call to ui.configure() once the UI has finished
  1713. * updating.
  1714. * @property {string} type
  1715. * 'uiupdated'
  1716. * @exportDoc
  1717. */
  1718. /** @private {!Map.<string, !shaka.extern.IUIElement.Factory>} */
  1719. shaka.ui.ControlsPanel.elementNamesToFactories_ = new Map();
  1720. /** @private {?shaka.extern.IUISeekBar.Factory} */
  1721. shaka.ui.ControlsPanel.seekBarFactory_ = new shaka.ui.SeekBar.Factory();