slidecontent.js 14 KB

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