backgrounds.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import { queryAll } from '../utils/util.js'
  2. import { colorToRgb, colorBrightness } from '../utils/color.js'
  3. /**
  4. * Creates and updates slide backgrounds.
  5. */
  6. export default class Backgrounds {
  7. constructor( Reveal ) {
  8. this.Reveal = Reveal;
  9. }
  10. render() {
  11. this.element = document.createElement( 'div' );
  12. this.element.className = 'backgrounds';
  13. this.Reveal.getRevealElement().appendChild( this.element );
  14. }
  15. /**
  16. * Creates the slide background elements and appends them
  17. * to the background container. One element is created per
  18. * slide no matter if the given slide has visible background.
  19. */
  20. create() {
  21. // Clear prior backgrounds
  22. this.element.innerHTML = '';
  23. this.element.classList.add( 'no-transition' );
  24. // Iterate over all horizontal slides
  25. this.Reveal.getHorizontalSlides().forEach( slideh => {
  26. let backgroundStack = this.createBackground( slideh, this.element );
  27. // Iterate over all vertical slides
  28. queryAll( slideh, 'section' ).forEach( slidev => {
  29. this.createBackground( slidev, backgroundStack );
  30. backgroundStack.classList.add( 'stack' );
  31. } );
  32. } );
  33. // Add parallax background if specified
  34. if( this.Reveal.getConfig().parallaxBackgroundImage ) {
  35. this.element.style.backgroundImage = 'url("' + this.Reveal.getConfig().parallaxBackgroundImage + '")';
  36. this.element.style.backgroundSize = this.Reveal.getConfig().parallaxBackgroundSize;
  37. this.element.style.backgroundRepeat = this.Reveal.getConfig().parallaxBackgroundRepeat;
  38. this.element.style.backgroundPosition = this.Reveal.getConfig().parallaxBackgroundPosition;
  39. // Make sure the below properties are set on the element - these properties are
  40. // needed for proper transitions to be set on the element via CSS. To remove
  41. // annoying background slide-in effect when the presentation starts, apply
  42. // these properties after short time delay
  43. setTimeout( () => {
  44. this.Reveal.getRevealElement().classList.add( 'has-parallax-background' );
  45. }, 1 );
  46. }
  47. else {
  48. this.element.style.backgroundImage = '';
  49. this.Reveal.getRevealElement().classList.remove( 'has-parallax-background' );
  50. }
  51. }
  52. /**
  53. * Creates a background for the given slide.
  54. *
  55. * @param {HTMLElement} slide
  56. * @param {HTMLElement} container The element that the background
  57. * should be appended to
  58. * @return {HTMLElement} New background div
  59. */
  60. createBackground( slide, container ) {
  61. // Main slide background element
  62. let element = document.createElement( 'div' );
  63. element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' );
  64. // Inner background element that wraps images/videos/iframes
  65. let contentElement = document.createElement( 'div' );
  66. contentElement.className = 'slide-background-content';
  67. element.appendChild( contentElement );
  68. container.appendChild( element );
  69. slide.slideBackgroundElement = element;
  70. slide.slideBackgroundContentElement = contentElement;
  71. // Syncs the background to reflect all current background settings
  72. this.sync( slide );
  73. return element;
  74. }
  75. /**
  76. * Renders all of the visual properties of a slide background
  77. * based on the various background attributes.
  78. *
  79. * @param {HTMLElement} slide
  80. */
  81. sync( slide ) {
  82. const element = slide.slideBackgroundElement,
  83. contentElement = slide.slideBackgroundContentElement;
  84. const data = {
  85. background: slide.getAttribute( 'data-background' ),
  86. backgroundSize: slide.getAttribute( 'data-background-size' ),
  87. backgroundImage: slide.getAttribute( 'data-background-image' ),
  88. backgroundVideo: slide.getAttribute( 'data-background-video' ),
  89. backgroundIframe: slide.getAttribute( 'data-background-iframe' ),
  90. backgroundColor: slide.getAttribute( 'data-background-color' ),
  91. backgroundGradient: slide.getAttribute( 'data-background-gradient' ),
  92. backgroundRepeat: slide.getAttribute( 'data-background-repeat' ),
  93. backgroundPosition: slide.getAttribute( 'data-background-position' ),
  94. backgroundTransition: slide.getAttribute( 'data-background-transition' ),
  95. backgroundOpacity: slide.getAttribute( 'data-background-opacity' ),
  96. };
  97. const dataPreload = slide.hasAttribute( 'data-preload' );
  98. // Reset the prior background state in case this is not the
  99. // initial sync
  100. slide.classList.remove( 'has-dark-background' );
  101. slide.classList.remove( 'has-light-background' );
  102. element.removeAttribute( 'data-loaded' );
  103. element.removeAttribute( 'data-background-hash' );
  104. element.removeAttribute( 'data-background-size' );
  105. element.removeAttribute( 'data-background-transition' );
  106. element.style.backgroundColor = '';
  107. contentElement.style.backgroundSize = '';
  108. contentElement.style.backgroundRepeat = '';
  109. contentElement.style.backgroundPosition = '';
  110. contentElement.style.backgroundImage = '';
  111. contentElement.style.opacity = '';
  112. contentElement.innerHTML = '';
  113. if( data.background ) {
  114. // Auto-wrap image urls in url(...)
  115. if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp|webp)([?#\s]|$)/gi.test( data.background ) ) {
  116. slide.setAttribute( 'data-background-image', data.background );
  117. }
  118. else {
  119. element.style.background = data.background;
  120. }
  121. }
  122. // Create a hash for this combination of background settings.
  123. // This is used to determine when two slide backgrounds are
  124. // the same.
  125. if( data.background || data.backgroundColor || data.backgroundGradient || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) {
  126. element.setAttribute( 'data-background-hash', data.background +
  127. data.backgroundSize +
  128. data.backgroundImage +
  129. data.backgroundVideo +
  130. data.backgroundIframe +
  131. data.backgroundColor +
  132. data.backgroundGradient +
  133. data.backgroundRepeat +
  134. data.backgroundPosition +
  135. data.backgroundTransition +
  136. data.backgroundOpacity );
  137. }
  138. // Additional and optional background properties
  139. if( data.backgroundSize ) element.setAttribute( 'data-background-size', data.backgroundSize );
  140. if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor;
  141. if( data.backgroundGradient ) element.style.backgroundImage = data.backgroundGradient;
  142. if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition );
  143. if( dataPreload ) element.setAttribute( 'data-preload', '' );
  144. // Background image options are set on the content wrapper
  145. if( data.backgroundSize ) contentElement.style.backgroundSize = data.backgroundSize;
  146. if( data.backgroundRepeat ) contentElement.style.backgroundRepeat = data.backgroundRepeat;
  147. if( data.backgroundPosition ) contentElement.style.backgroundPosition = data.backgroundPosition;
  148. if( data.backgroundOpacity ) contentElement.style.opacity = data.backgroundOpacity;
  149. const contrastClass = this.getContrastClass( slide );
  150. if( typeof contrastClass === 'string' ) {
  151. slide.classList.add( contrastClass );
  152. }
  153. }
  154. /**
  155. * Returns a class name that can be applied to a slide to indicate
  156. * if it has a light or dark background.
  157. *
  158. * @param {*} slide
  159. *
  160. * @returns {string|null}
  161. */
  162. getContrastClass( slide ) {
  163. const element = slide.slideBackgroundElement;
  164. // If this slide has a background color, we add a class that
  165. // signals if it is light or dark. If the slide has no background
  166. // color, no class will be added
  167. let contrastColor = slide.getAttribute( 'data-background-color' );
  168. // If no bg color was found, or it cannot be converted by colorToRgb, check the computed background
  169. if( !contrastColor || !colorToRgb( contrastColor ) ) {
  170. let computedBackgroundStyle = window.getComputedStyle( element );
  171. if( computedBackgroundStyle && computedBackgroundStyle.backgroundColor ) {
  172. contrastColor = computedBackgroundStyle.backgroundColor;
  173. }
  174. }
  175. if( contrastColor ) {
  176. const rgb = colorToRgb( contrastColor );
  177. // Ignore fully transparent backgrounds. Some browsers return
  178. // rgba(0,0,0,0) when reading the computed background color of
  179. // an element with no background
  180. if( rgb && rgb.a !== 0 ) {
  181. if( colorBrightness( contrastColor ) < 128 ) {
  182. return 'has-dark-background';
  183. }
  184. else {
  185. return 'has-light-background';
  186. }
  187. }
  188. }
  189. return null;
  190. }
  191. /**
  192. * Bubble the 'has-light-background'/'has-dark-background' classes.
  193. */
  194. bubbleSlideContrastClassToElement( slide, target ) {
  195. [ 'has-light-background', 'has-dark-background' ].forEach( classToBubble => {
  196. if( slide.classList.contains( classToBubble ) ) {
  197. target.classList.add( classToBubble );
  198. }
  199. else {
  200. target.classList.remove( classToBubble );
  201. }
  202. }, this );
  203. }
  204. /**
  205. * Updates the background elements to reflect the current
  206. * slide.
  207. *
  208. * @param {boolean} includeAll If true, the backgrounds of
  209. * all vertical slides (not just the present) will be updated.
  210. */
  211. update( includeAll = false ) {
  212. let config = this.Reveal.getConfig();
  213. let currentSlide = this.Reveal.getCurrentSlide();
  214. let indices = this.Reveal.getIndices();
  215. let currentBackground = null;
  216. // Reverse past/future classes when in RTL mode
  217. let horizontalPast = config.rtl ? 'future' : 'past',
  218. horizontalFuture = config.rtl ? 'past' : 'future';
  219. // Update the classes of all backgrounds to match the
  220. // states of their slides (past/present/future)
  221. Array.from( this.element.childNodes ).forEach( ( backgroundh, h ) => {
  222. backgroundh.classList.remove( 'past', 'present', 'future' );
  223. if( h < indices.h ) {
  224. backgroundh.classList.add( horizontalPast );
  225. }
  226. else if ( h > indices.h ) {
  227. backgroundh.classList.add( horizontalFuture );
  228. }
  229. else {
  230. backgroundh.classList.add( 'present' );
  231. // Store a reference to the current background element
  232. currentBackground = backgroundh;
  233. }
  234. if( includeAll || h === indices.h ) {
  235. queryAll( backgroundh, '.slide-background' ).forEach( ( backgroundv, v ) => {
  236. backgroundv.classList.remove( 'past', 'present', 'future' );
  237. const indexv = typeof indices.v === 'number' ? indices.v : 0;
  238. if( v < indexv ) {
  239. backgroundv.classList.add( 'past' );
  240. }
  241. else if ( v > indexv ) {
  242. backgroundv.classList.add( 'future' );
  243. }
  244. else {
  245. backgroundv.classList.add( 'present' );
  246. // Only if this is the present horizontal and vertical slide
  247. if( h === indices.h ) currentBackground = backgroundv;
  248. }
  249. } );
  250. }
  251. } );
  252. // The previous background may refer to a DOM element that has
  253. // been removed after a presentation is synced & bgs are recreated
  254. if( this.previousBackground && !this.previousBackground.closest( 'body' ) ) {
  255. this.previousBackground = null;
  256. }
  257. if( currentBackground && this.previousBackground ) {
  258. // Don't transition between identical backgrounds. This
  259. // prevents unwanted flicker.
  260. let previousBackgroundHash = this.previousBackground.getAttribute( 'data-background-hash' );
  261. let currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' );
  262. if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== this.previousBackground ) {
  263. this.element.classList.add( 'no-transition' );
  264. // If multiple slides have the same background video, carry
  265. // the <video> element forward so that it plays continuously
  266. // across multiple slides
  267. const currentVideo = currentBackground.querySelector( 'video' );
  268. const previousVideo = this.previousBackground.querySelector( 'video' );
  269. if( currentVideo && previousVideo ) {
  270. const currentVideoParent = currentVideo.parentNode;
  271. const previousVideoParent = previousVideo.parentNode;
  272. // Swap the two videos
  273. previousVideoParent.appendChild( currentVideo );
  274. currentVideoParent.appendChild( previousVideo );
  275. }
  276. }
  277. }
  278. const backgroundChanged = currentBackground !== this.previousBackground;
  279. // Stop content inside of previous backgrounds
  280. if( backgroundChanged && this.previousBackground ) {
  281. this.Reveal.slideContent.stopEmbeddedContent( this.previousBackground, { unloadIframes: !this.Reveal.slideContent.shouldPreload( this.previousBackground ) } );
  282. }
  283. // Start content in the current background
  284. if( backgroundChanged && currentBackground ) {
  285. this.Reveal.slideContent.startEmbeddedContent( currentBackground );
  286. let currentBackgroundContent = currentBackground.querySelector( '.slide-background-content' );
  287. if( currentBackgroundContent ) {
  288. let backgroundImageURL = currentBackgroundContent.style.backgroundImage || '';
  289. // Restart GIFs (doesn't work in Firefox)
  290. if( /\.gif/i.test( backgroundImageURL ) ) {
  291. currentBackgroundContent.style.backgroundImage = '';
  292. window.getComputedStyle( currentBackgroundContent ).opacity;
  293. currentBackgroundContent.style.backgroundImage = backgroundImageURL;
  294. }
  295. }
  296. this.previousBackground = currentBackground;
  297. }
  298. // If there's a background brightness flag for this slide,
  299. // bubble it to the .reveal container
  300. if( currentSlide ) {
  301. this.bubbleSlideContrastClassToElement( currentSlide, this.Reveal.getRevealElement() );
  302. }
  303. // Allow the first background to apply without transition
  304. setTimeout( () => {
  305. this.element.classList.remove( 'no-transition' );
  306. }, 10 );
  307. }
  308. /**
  309. * Updates the position of the parallax background based
  310. * on the current slide index.
  311. */
  312. updateParallax() {
  313. let indices = this.Reveal.getIndices();
  314. if( this.Reveal.getConfig().parallaxBackgroundImage ) {
  315. let horizontalSlides = this.Reveal.getHorizontalSlides(),
  316. verticalSlides = this.Reveal.getVerticalSlides();
  317. let backgroundSize = this.element.style.backgroundSize.split( ' ' ),
  318. backgroundWidth, backgroundHeight;
  319. if( backgroundSize.length === 1 ) {
  320. backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 );
  321. }
  322. else {
  323. backgroundWidth = parseInt( backgroundSize[0], 10 );
  324. backgroundHeight = parseInt( backgroundSize[1], 10 );
  325. }
  326. let slideWidth = this.element.offsetWidth,
  327. horizontalSlideCount = horizontalSlides.length,
  328. horizontalOffsetMultiplier,
  329. horizontalOffset;
  330. if( typeof this.Reveal.getConfig().parallaxBackgroundHorizontal === 'number' ) {
  331. horizontalOffsetMultiplier = this.Reveal.getConfig().parallaxBackgroundHorizontal;
  332. }
  333. else {
  334. horizontalOffsetMultiplier = horizontalSlideCount > 1 ? ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) : 0;
  335. }
  336. horizontalOffset = horizontalOffsetMultiplier * indices.h * -1;
  337. let slideHeight = this.element.offsetHeight,
  338. verticalSlideCount = verticalSlides.length,
  339. verticalOffsetMultiplier,
  340. verticalOffset;
  341. if( typeof this.Reveal.getConfig().parallaxBackgroundVertical === 'number' ) {
  342. verticalOffsetMultiplier = this.Reveal.getConfig().parallaxBackgroundVertical;
  343. }
  344. else {
  345. verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 );
  346. }
  347. verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indices.v : 0;
  348. this.element.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px';
  349. }
  350. }
  351. destroy() {
  352. this.element.remove();
  353. }
  354. }