You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

481 lines
14 KiB

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