slidecontent.js 14 KB

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