slidecontent.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. this.layout( slide );
  135. }
  136. /**
  137. * Applies JS-dependent layout helpers for the given slide,
  138. * if there are any.
  139. */
  140. layout( slide ) {
  141. // Autosize text with the r-fit-text class based on the
  142. // size of its container. This needs to happen after the
  143. // slide is visible in order to measure the text.
  144. Array.from( slide.querySelectorAll( '.r-fit-text' ) ).forEach( element => {
  145. fitty( element, {
  146. minSize: 24,
  147. maxSize: this.Reveal.getConfig().height * 0.8,
  148. observeMutations: false,
  149. observeWindow: false
  150. } );
  151. } );
  152. }
  153. /**
  154. * Unloads and hides the given slide. This is called when the
  155. * slide is moved outside of the configured view distance.
  156. *
  157. * @param {HTMLElement} slide
  158. */
  159. unload( slide ) {
  160. // Hide the slide element
  161. slide.style.display = 'none';
  162. // Hide the corresponding background element
  163. let background = this.Reveal.getSlideBackground( slide );
  164. if( background ) {
  165. background.style.display = 'none';
  166. // Unload any background iframes
  167. queryAll( background, 'iframe[src]' ).forEach( element => {
  168. element.removeAttribute( 'src' );
  169. } );
  170. }
  171. // Reset lazy-loaded media elements with src attributes
  172. queryAll( slide, 'video[data-lazy-loaded][src], audio[data-lazy-loaded][src], iframe[data-lazy-loaded][src]' ).forEach( element => {
  173. element.setAttribute( 'data-src', element.getAttribute( 'src' ) );
  174. element.removeAttribute( 'src' );
  175. } );
  176. // Reset lazy-loaded media elements with <source> children
  177. queryAll( slide, 'video[data-lazy-loaded] source[src], audio source[src]' ).forEach( source => {
  178. source.setAttribute( 'data-src', source.getAttribute( 'src' ) );
  179. source.removeAttribute( 'src' );
  180. } );
  181. }
  182. /**
  183. * Enforces origin-specific format rules for embedded media.
  184. */
  185. formatEmbeddedContent() {
  186. let _appendParamToIframeSource = ( sourceAttribute, sourceURL, param ) => {
  187. queryAll( this.Reveal.getSlidesElement(), 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ).forEach( el => {
  188. let src = el.getAttribute( sourceAttribute );
  189. if( src && src.indexOf( param ) === -1 ) {
  190. el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param );
  191. }
  192. });
  193. };
  194. // YouTube frames must include "?enablejsapi=1"
  195. _appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' );
  196. _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' );
  197. // Vimeo frames must include "?api=1"
  198. _appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' );
  199. _appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' );
  200. }
  201. /**
  202. * Start playback of any embedded content inside of
  203. * the given element.
  204. *
  205. * @param {HTMLElement} element
  206. */
  207. startEmbeddedContent( element ) {
  208. if( element && !this.Reveal.isSpeakerNotes() ) {
  209. // Restart GIFs
  210. queryAll( element, 'img[src$=".gif"]' ).forEach( el => {
  211. // Setting the same unchanged source like this was confirmed
  212. // to work in Chrome, FF & Safari
  213. el.setAttribute( 'src', el.getAttribute( 'src' ) );
  214. } );
  215. // HTML5 media elements
  216. queryAll( element, 'video, audio' ).forEach( el => {
  217. if( closest( el, '.fragment' ) && !closest( el, '.fragment.visible' ) ) {
  218. return;
  219. }
  220. // Prefer an explicit global autoplay setting
  221. let autoplay = this.Reveal.getConfig().autoPlayMedia;
  222. // If no global setting is available, fall back on the element's
  223. // own autoplay setting
  224. if( typeof autoplay !== 'boolean' ) {
  225. autoplay = el.hasAttribute( 'data-autoplay' ) || !!closest( el, '.slide-background' );
  226. }
  227. if( autoplay && typeof el.play === 'function' ) {
  228. // If the media is ready, start playback
  229. if( el.readyState > 1 ) {
  230. this.startEmbeddedMedia( { target: el } );
  231. }
  232. // Mobile devices never fire a loaded event so instead
  233. // of waiting, we initiate playback
  234. else if( isMobile ) {
  235. let promise = el.play();
  236. // If autoplay does not work, ensure that the controls are visible so
  237. // that the viewer can start the media on their own
  238. if( promise && typeof promise.catch === 'function' && el.controls === false ) {
  239. promise.catch( () => {
  240. el.controls = true;
  241. // Once the video does start playing, hide the controls again
  242. el.addEventListener( 'play', () => {
  243. el.controls = false;
  244. } );
  245. } );
  246. }
  247. }
  248. // If the media isn't loaded, wait before playing
  249. else {
  250. el.removeEventListener( 'loadeddata', this.startEmbeddedMedia ); // remove first to avoid dupes
  251. el.addEventListener( 'loadeddata', this.startEmbeddedMedia );
  252. }
  253. }
  254. } );
  255. // Normal iframes
  256. queryAll( element, 'iframe[src]' ).forEach( el => {
  257. if( closest( el, '.fragment' ) && !closest( el, '.fragment.visible' ) ) {
  258. return;
  259. }
  260. this.startEmbeddedIframe( { target: el } );
  261. } );
  262. // Lazy loading iframes
  263. queryAll( element, 'iframe[data-src]' ).forEach( el => {
  264. if( closest( el, '.fragment' ) && !closest( el, '.fragment.visible' ) ) {
  265. return;
  266. }
  267. if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) {
  268. el.removeEventListener( 'load', this.startEmbeddedIframe ); // remove first to avoid dupes
  269. el.addEventListener( 'load', this.startEmbeddedIframe );
  270. el.setAttribute( 'src', el.getAttribute( 'data-src' ) );
  271. }
  272. } );
  273. }
  274. }
  275. /**
  276. * Starts playing an embedded video/audio element after
  277. * it has finished loading.
  278. *
  279. * @param {object} event
  280. */
  281. startEmbeddedMedia( event ) {
  282. let isAttachedToDOM = !!closest( event.target, 'html' ),
  283. isVisible = !!closest( event.target, '.present' );
  284. if( isAttachedToDOM && isVisible ) {
  285. event.target.currentTime = 0;
  286. event.target.play();
  287. }
  288. event.target.removeEventListener( 'loadeddata', this.startEmbeddedMedia );
  289. }
  290. /**
  291. * "Starts" the content of an embedded iframe using the
  292. * postMessage API.
  293. *
  294. * @param {object} event
  295. */
  296. startEmbeddedIframe( event ) {
  297. let iframe = event.target;
  298. if( iframe && iframe.contentWindow ) {
  299. let isAttachedToDOM = !!closest( event.target, 'html' ),
  300. isVisible = !!closest( event.target, '.present' );
  301. if( isAttachedToDOM && isVisible ) {
  302. // Prefer an explicit global autoplay setting
  303. let autoplay = this.Reveal.getConfig().autoPlayMedia;
  304. // If no global setting is available, fall back on the element's
  305. // own autoplay setting
  306. if( typeof autoplay !== 'boolean' ) {
  307. autoplay = iframe.hasAttribute( 'data-autoplay' ) || !!closest( iframe, '.slide-background' );
  308. }
  309. // YouTube postMessage API
  310. if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) {
  311. iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
  312. }
  313. // Vimeo postMessage API
  314. else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) {
  315. iframe.contentWindow.postMessage( '{"method":"play"}', '*' );
  316. }
  317. // Generic postMessage API
  318. else {
  319. iframe.contentWindow.postMessage( 'slide:start', '*' );
  320. }
  321. }
  322. }
  323. }
  324. /**
  325. * Stop playback of any embedded content inside of
  326. * the targeted slide.
  327. *
  328. * @param {HTMLElement} element
  329. */
  330. stopEmbeddedContent( element, options = {} ) {
  331. options = extend( {
  332. // Defaults
  333. unloadIframes: true
  334. }, options );
  335. if( element && element.parentNode ) {
  336. // HTML5 media elements
  337. queryAll( element, 'video, audio' ).forEach( el => {
  338. if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) {
  339. el.setAttribute('data-paused-by-reveal', '');
  340. el.pause();
  341. }
  342. } );
  343. // Generic postMessage API for non-lazy loaded iframes
  344. queryAll( element, 'iframe' ).forEach( el => {
  345. if( el.contentWindow ) el.contentWindow.postMessage( 'slide:stop', '*' );
  346. el.removeEventListener( 'load', this.startEmbeddedIframe );
  347. });
  348. // YouTube postMessage API
  349. queryAll( element, 'iframe[src*="youtube.com/embed/"]' ).forEach( el => {
  350. if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) {
  351. el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' );
  352. }
  353. });
  354. // Vimeo postMessage API
  355. queryAll( element, 'iframe[src*="player.vimeo.com/"]' ).forEach( el => {
  356. if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) {
  357. el.contentWindow.postMessage( '{"method":"pause"}', '*' );
  358. }
  359. });
  360. if( options.unloadIframes === true ) {
  361. // Unload lazy-loaded iframes
  362. queryAll( element, 'iframe[data-src]' ).forEach( el => {
  363. // Only removing the src doesn't actually unload the frame
  364. // in all browsers (Firefox) so we set it to blank first
  365. el.setAttribute( 'src', 'about:blank' );
  366. el.removeAttribute( 'src' );
  367. } );
  368. }
  369. }
  370. }
  371. }