slidecontent.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. import { HORIZONTAL_SLIDES_SELECTOR, VERTICAL_SLIDES_SELECTOR } from '../utils/constants.js'
  2. import { extend, queryAll, closest } from '../utils/util.js'
  3. import { isMobile } from '../utils/device.js'
  4. import fitty from 'fitty';
  5. /**
  6. * Handles loading, unloading and playback of slide
  7. * content such as images, videos and iframes.
  8. */
  9. export default class SlideContent {
  10. constructor( Reveal ) {
  11. this.Reveal = Reveal;
  12. this.startEmbeddedIframe = this.startEmbeddedIframe.bind( this );
  13. }
  14. /**
  15. * Should the given element be preloaded?
  16. * Decides based on local element attributes and global config.
  17. *
  18. * @param {HTMLElement} element
  19. */
  20. shouldPreload( element ) {
  21. // Prefer an explicit global preload setting
  22. let preload = this.Reveal.getConfig().preloadIframes;
  23. // If no global setting is available, fall back on the element's
  24. // own preload setting
  25. if( typeof preload !== 'boolean' ) {
  26. preload = element.hasAttribute( 'data-preload' );
  27. }
  28. return preload;
  29. }
  30. /**
  31. * Called when the given slide is within the configured view
  32. * distance. Shows the slide element and loads any content
  33. * that is set to load lazily (data-src).
  34. *
  35. * @param {HTMLElement} slide Slide to show
  36. */
  37. load( slide, options = {} ) {
  38. // Show the slide element
  39. slide.style.display = this.Reveal.getConfig().display;
  40. // Media elements with data-src attributes
  41. queryAll( slide, 'img[data-src], video[data-src], audio[data-src], iframe[data-src]' ).forEach( element => {
  42. if( element.tagName !== 'IFRAME' || this.shouldPreload( element ) ) {
  43. element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
  44. element.setAttribute( 'data-lazy-loaded', '' );
  45. element.removeAttribute( 'data-src' );
  46. }
  47. } );
  48. // Media elements with <source> children
  49. queryAll( slide, 'video, audio' ).forEach( media => {
  50. let sources = 0;
  51. queryAll( media, 'source[data-src]' ).forEach( source => {
  52. source.setAttribute( 'src', source.getAttribute( 'data-src' ) );
  53. source.removeAttribute( 'data-src' );
  54. source.setAttribute( 'data-lazy-loaded', '' );
  55. sources += 1;
  56. } );
  57. // Enable inline video playback in mobile Safari
  58. if( isMobile && media.tagName === 'VIDEO' ) {
  59. media.setAttribute( 'playsinline', '' );
  60. }
  61. // If we rewrote sources for this video/audio element, we need
  62. // to manually tell it to load from its new origin
  63. if( sources > 0 ) {
  64. media.load();
  65. }
  66. } );
  67. // Show the corresponding background element
  68. let background = slide.slideBackgroundElement;
  69. if( background ) {
  70. background.style.display = 'block';
  71. let backgroundContent = slide.slideBackgroundContentElement;
  72. let backgroundIframe = slide.getAttribute( 'data-background-iframe' );
  73. // If the background contains media, load it
  74. if( background.hasAttribute( 'data-loaded' ) === false ) {
  75. background.setAttribute( 'data-loaded', 'true' );
  76. let backgroundImage = slide.getAttribute( 'data-background-image' ),
  77. backgroundVideo = slide.getAttribute( 'data-background-video' ),
  78. backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ),
  79. backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' );
  80. // Images
  81. if( backgroundImage ) {
  82. backgroundContent.style.backgroundImage = 'url('+ encodeURI( backgroundImage ) +')';
  83. }
  84. // Videos
  85. else if ( backgroundVideo && !this.Reveal.isSpeakerNotes() ) {
  86. let video = document.createElement( 'video' );
  87. if( backgroundVideoLoop ) {
  88. video.setAttribute( 'loop', '' );
  89. }
  90. if( backgroundVideoMuted ) {
  91. video.muted = true;
  92. }
  93. // Enable inline playback in mobile Safari
  94. //
  95. // Mute is required for video to play when using
  96. // swipe gestures to navigate since they don't
  97. // count as direct user actions :'(
  98. if( isMobile ) {
  99. video.muted = true;
  100. video.setAttribute( 'playsinline', '' );
  101. }
  102. // Support comma separated lists of video sources
  103. backgroundVideo.split( ',' ).forEach( source => {
  104. video.innerHTML += '<source src="'+ source +'">';
  105. } );
  106. backgroundContent.appendChild( video );
  107. }
  108. // Iframes
  109. else if( backgroundIframe && options.excludeIframes !== true ) {
  110. let iframe = document.createElement( 'iframe' );
  111. iframe.setAttribute( 'allowfullscreen', '' );
  112. iframe.setAttribute( 'mozallowfullscreen', '' );
  113. iframe.setAttribute( 'webkitallowfullscreen', '' );
  114. iframe.setAttribute( 'allow', 'autoplay' );
  115. iframe.setAttribute( 'data-src', backgroundIframe );
  116. iframe.style.width = '100%';
  117. iframe.style.height = '100%';
  118. iframe.style.maxHeight = '100%';
  119. iframe.style.maxWidth = '100%';
  120. backgroundContent.appendChild( iframe );
  121. }
  122. }
  123. // Start loading preloadable iframes
  124. let backgroundIframeElement = backgroundContent.querySelector( 'iframe[data-src]' );
  125. if( backgroundIframeElement ) {
  126. // Check if this iframe is eligible to be preloaded
  127. if( this.shouldPreload( background ) && !/autoplay=(1|true|yes)/gi.test( backgroundIframe ) ) {
  128. if( backgroundIframeElement.getAttribute( 'src' ) !== backgroundIframe ) {
  129. backgroundIframeElement.setAttribute( 'src', backgroundIframe );
  130. }
  131. }
  132. }
  133. }
  134. // Autosize text with the r-fit-text class based on the
  135. // size of its container. This needs to happen after the
  136. // slide is visible in order to measure the text.
  137. Array.from( slide.querySelectorAll( '.r-fit-text:not([data-fitted])' ) ).forEach( element => {
  138. element.dataset.fitted = '';
  139. fitty( element, {
  140. minSize: 24,
  141. maxSize: this.Reveal.getConfig().height * 0.8,
  142. observeMutations: false,
  143. observeWindow: false
  144. } );
  145. } );
  146. }
  147. /**
  148. * Unloads and hides the given slide. This is called when the
  149. * slide is moved outside of the configured view distance.
  150. *
  151. * @param {HTMLElement} slide
  152. */
  153. unload( slide ) {
  154. // Hide the slide element
  155. slide.style.display = 'none';
  156. // Hide the corresponding background element
  157. let background = this.Reveal.getSlideBackground( slide );
  158. if( background ) {
  159. background.style.display = 'none';
  160. // Unload any background iframes
  161. queryAll( background, 'iframe[src]' ).forEach( element => {
  162. element.removeAttribute( 'src' );
  163. } );
  164. }
  165. // Reset lazy-loaded media elements with src attributes
  166. queryAll( slide, 'video[data-lazy-loaded][src], audio[data-lazy-loaded][src], iframe[data-lazy-loaded][src]' ).forEach( element => {
  167. element.setAttribute( 'data-src', element.getAttribute( 'src' ) );
  168. element.removeAttribute( 'src' );
  169. } );
  170. // Reset lazy-loaded media elements with <source> children
  171. queryAll( slide, 'video[data-lazy-loaded] source[src], audio source[src]' ).forEach( source => {
  172. source.setAttribute( 'data-src', source.getAttribute( 'src' ) );
  173. source.removeAttribute( 'src' );
  174. } );
  175. }
  176. /**
  177. * Enforces origin-specific format rules for embedded media.
  178. */
  179. formatEmbeddedContent() {
  180. let _appendParamToIframeSource = ( sourceAttribute, sourceURL, param ) => {
  181. queryAll( this.Reveal.getSlidesElement(), 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ).forEach( el => {
  182. let src = el.getAttribute( sourceAttribute );
  183. if( src && src.indexOf( param ) === -1 ) {
  184. el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param );
  185. }
  186. });
  187. };
  188. // YouTube frames must include "?enablejsapi=1"
  189. _appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' );
  190. _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' );
  191. // Vimeo frames must include "?api=1"
  192. _appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' );
  193. _appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' );
  194. }
  195. /**
  196. * Start playback of any embedded content inside of
  197. * the given element.
  198. *
  199. * @param {HTMLElement} element
  200. */
  201. startEmbeddedContent( element ) {
  202. if( element && !this.Reveal.isSpeakerNotes() ) {
  203. // Restart GIFs
  204. queryAll( element, 'img[src$=".gif"]' ).forEach( el => {
  205. // Setting the same unchanged source like this was confirmed
  206. // to work in Chrome, FF & Safari
  207. el.setAttribute( 'src', el.getAttribute( 'src' ) );
  208. } );
  209. // HTML5 media elements
  210. queryAll( element, 'video, audio' ).forEach( el => {
  211. if( closest( el, '.fragment' ) && !closest( el, '.fragment.visible' ) ) {
  212. return;
  213. }
  214. // Prefer an explicit global autoplay setting
  215. let autoplay = this.Reveal.getConfig().autoPlayMedia;
  216. // If no global setting is available, fall back on the element's
  217. // own autoplay setting
  218. if( typeof autoplay !== 'boolean' ) {
  219. autoplay = el.hasAttribute( 'data-autoplay' ) || !!closest( el, '.slide-background' );
  220. }
  221. if( autoplay && typeof el.play === 'function' ) {
  222. // If the media is ready, start playback
  223. if( el.readyState > 1 ) {
  224. this.startEmbeddedMedia( { target: el } );
  225. }
  226. // Mobile devices never fire a loaded event so instead
  227. // of waiting, we initiate playback
  228. else if( isMobile ) {
  229. let promise = el.play();
  230. // If autoplay does not work, ensure that the controls are visible so
  231. // that the viewer can start the media on their own
  232. if( promise && typeof promise.catch === 'function' && el.controls === false ) {
  233. promise.catch( () => {
  234. el.controls = true;
  235. // Once the video does start playing, hide the controls again
  236. el.addEventListener( 'play', () => {
  237. el.controls = false;
  238. } );
  239. } );
  240. }
  241. }
  242. // If the media isn't loaded, wait before playing
  243. else {
  244. el.removeEventListener( 'loadeddata', this.startEmbeddedMedia ); // remove first to avoid dupes
  245. el.addEventListener( 'loadeddata', this.startEmbeddedMedia );
  246. }
  247. }
  248. } );
  249. // Normal iframes
  250. queryAll( element, 'iframe[src]' ).forEach( el => {
  251. if( closest( el, '.fragment' ) && !closest( el, '.fragment.visible' ) ) {
  252. return;
  253. }
  254. this.startEmbeddedIframe( { target: el } );
  255. } );
  256. // Lazy loading iframes
  257. queryAll( element, 'iframe[data-src]' ).forEach( el => {
  258. if( closest( el, '.fragment' ) && !closest( el, '.fragment.visible' ) ) {
  259. return;
  260. }
  261. if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) {
  262. el.removeEventListener( 'load', this.startEmbeddedIframe ); // remove first to avoid dupes
  263. el.addEventListener( 'load', this.startEmbeddedIframe );
  264. el.setAttribute( 'src', el.getAttribute( 'data-src' ) );
  265. }
  266. } );
  267. }
  268. }
  269. /**
  270. * Starts playing an embedded video/audio element after
  271. * it has finished loading.
  272. *
  273. * @param {object} event
  274. */
  275. startEmbeddedMedia( event ) {
  276. let isAttachedToDOM = !!closest( event.target, 'html' ),
  277. isVisible = !!closest( event.target, '.present' );
  278. if( isAttachedToDOM && isVisible ) {
  279. event.target.currentTime = 0;
  280. event.target.play();
  281. }
  282. event.target.removeEventListener( 'loadeddata', this.startEmbeddedMedia );
  283. }
  284. /**
  285. * "Starts" the content of an embedded iframe using the
  286. * postMessage API.
  287. *
  288. * @param {object} event
  289. */
  290. startEmbeddedIframe( event ) {
  291. let iframe = event.target;
  292. if( iframe && iframe.contentWindow ) {
  293. let isAttachedToDOM = !!closest( event.target, 'html' ),
  294. isVisible = !!closest( event.target, '.present' );
  295. if( isAttachedToDOM && isVisible ) {
  296. // Prefer an explicit global autoplay setting
  297. let autoplay = this.Reveal.getConfig().autoPlayMedia;
  298. // If no global setting is available, fall back on the element's
  299. // own autoplay setting
  300. if( typeof autoplay !== 'boolean' ) {
  301. autoplay = iframe.hasAttribute( 'data-autoplay' ) || !!closest( iframe, '.slide-background' );
  302. }
  303. // YouTube postMessage API
  304. if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) {
  305. iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
  306. }
  307. // Vimeo postMessage API
  308. else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) {
  309. iframe.contentWindow.postMessage( '{"method":"play"}', '*' );
  310. }
  311. // Generic postMessage API
  312. else {
  313. iframe.contentWindow.postMessage( 'slide:start', '*' );
  314. }
  315. }
  316. }
  317. }
  318. /**
  319. * Stop playback of any embedded content inside of
  320. * the targeted slide.
  321. *
  322. * @param {HTMLElement} element
  323. */
  324. stopEmbeddedContent( element, options = {} ) {
  325. options = extend( {
  326. // Defaults
  327. unloadIframes: true
  328. }, options );
  329. if( element && element.parentNode ) {
  330. // HTML5 media elements
  331. queryAll( element, 'video, audio' ).forEach( el => {
  332. if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) {
  333. el.setAttribute('data-paused-by-reveal', '');
  334. el.pause();
  335. }
  336. } );
  337. // Generic postMessage API for non-lazy loaded iframes
  338. queryAll( element, 'iframe' ).forEach( el => {
  339. if( el.contentWindow ) el.contentWindow.postMessage( 'slide:stop', '*' );
  340. el.removeEventListener( 'load', this.startEmbeddedIframe );
  341. });
  342. // YouTube postMessage API
  343. queryAll( element, 'iframe[src*="youtube.com/embed/"]' ).forEach( el => {
  344. if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) {
  345. el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' );
  346. }
  347. });
  348. // Vimeo postMessage API
  349. queryAll( element, 'iframe[src*="player.vimeo.com/"]' ).forEach( el => {
  350. if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) {
  351. el.contentWindow.postMessage( '{"method":"pause"}', '*' );
  352. }
  353. });
  354. if( options.unloadIframes === true ) {
  355. // Unload lazy-loaded iframes
  356. queryAll( element, 'iframe[data-src]' ).forEach( el => {
  357. // Only removing the src doesn't actually unload the frame
  358. // in all browsers (Firefox) so we set it to blank first
  359. el.setAttribute( 'src', 'about:blank' );
  360. el.removeAttribute( 'src' );
  361. } );
  362. }
  363. }
  364. }
  365. }