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.

619 lines
19KB

  1. import { queryAll, extend, createStyleSheet, matches, closest } from '../utils/util.js'
  2. import { FRAGMENT_STYLE_REGEX } from '../utils/constants.js'
  3. // Counter used to generate unique IDs for auto-animated elements
  4. let autoAnimateCounter = 0;
  5. /**
  6. * Automatically animates matching elements across
  7. * slides with the [data-auto-animate] attribute.
  8. */
  9. export default class AutoAnimate {
  10. constructor( Reveal ) {
  11. this.Reveal = Reveal;
  12. }
  13. /**
  14. * Runs an auto-animation between the given slides.
  15. *
  16. * @param {HTMLElement} fromSlide
  17. * @param {HTMLElement} toSlide
  18. */
  19. run( fromSlide, toSlide ) {
  20. // Clean up after prior animations
  21. this.reset();
  22. // Ensure that both slides are auto-animate targets
  23. if( fromSlide.hasAttribute( 'data-auto-animate' ) && toSlide.hasAttribute( 'data-auto-animate' ) ) {
  24. // Create a new auto-animate sheet
  25. this.autoAnimateStyleSheet = this.autoAnimateStyleSheet || createStyleSheet();
  26. let animationOptions = this.getAutoAnimateOptions( toSlide );
  27. // Set our starting state
  28. fromSlide.dataset.autoAnimate = 'pending';
  29. toSlide.dataset.autoAnimate = 'pending';
  30. // Flag the navigation direction, needed for fragment buildup
  31. let allSlides = this.Reveal.getSlides();
  32. animationOptions.slideDirection = allSlides.indexOf( toSlide ) > allSlides.indexOf( fromSlide ) ? 'forward' : 'backward';
  33. // Inject our auto-animate styles for this transition
  34. let css = this.getAutoAnimatableElements( fromSlide, toSlide ).map( elements => {
  35. return this.autoAnimateElements( elements.from, elements.to, elements.options || {}, animationOptions, autoAnimateCounter++ );
  36. } );
  37. // Animate unmatched elements, if enabled
  38. if( toSlide.dataset.autoAnimateUnmatched !== 'false' && this.Reveal.getConfig().autoAnimateUnmatched === true ) {
  39. // Our default timings for unmatched elements
  40. let defaultUnmatchedDuration = animationOptions.duration * 0.8,
  41. defaultUnmatchedDelay = animationOptions.duration * 0.2;
  42. this.getUnmatchedAutoAnimateElements( toSlide ).forEach( unmatchedElement => {
  43. let unmatchedOptions = this.getAutoAnimateOptions( unmatchedElement, animationOptions );
  44. let id = 'unmatched';
  45. // If there is a duration or delay set specifically for this
  46. // element our unmatched elements should adhere to those
  47. if( unmatchedOptions.duration !== animationOptions.duration || unmatchedOptions.delay !== animationOptions.delay ) {
  48. id = 'unmatched-' + autoAnimateCounter++;
  49. css.push( `[data-auto-animate="running"] [data-auto-animate-target="${id}"] { transition: opacity ${unmatchedOptions.duration}s ease ${unmatchedOptions.delay}s; }` );
  50. }
  51. unmatchedElement.dataset.autoAnimateTarget = id;
  52. }, this );
  53. // Our default transition for unmatched elements
  54. css.push( `[data-auto-animate="running"] [data-auto-animate-target="unmatched"] { transition: opacity ${defaultUnmatchedDuration}s ease ${defaultUnmatchedDelay}s; }` );
  55. }
  56. // Setting the whole chunk of CSS at once is the most
  57. // efficient way to do this. Using sheet.insertRule
  58. // is multiple factors slower.
  59. this.autoAnimateStyleSheet.innerHTML = css.join( '' );
  60. // Start the animation next cycle
  61. requestAnimationFrame( () => {
  62. if( this.autoAnimateStyleSheet ) {
  63. // This forces our newly injected styles to be applied in Firefox
  64. getComputedStyle( this.autoAnimateStyleSheet ).fontWeight;
  65. toSlide.dataset.autoAnimate = 'running';
  66. }
  67. } );
  68. this.Reveal.dispatchEvent({
  69. type: 'autoanimate',
  70. data: {
  71. fromSlide,
  72. toSlide,
  73. sheet: this.autoAnimateStyleSheet
  74. }
  75. });
  76. }
  77. }
  78. /**
  79. * Rolls back all changes that we've made to the DOM so
  80. * that as part of animating.
  81. */
  82. reset() {
  83. // Reset slides
  84. queryAll( this.Reveal.getRevealElement(), '[data-auto-animate]:not([data-auto-animate=""])' ).forEach( element => {
  85. element.dataset.autoAnimate = '';
  86. } );
  87. // Reset elements
  88. queryAll( this.Reveal.getRevealElement(), '[data-auto-animate-target]' ).forEach( element => {
  89. delete element.dataset.autoAnimateTarget;
  90. } );
  91. // Remove the animation sheet
  92. if( this.autoAnimateStyleSheet && this.autoAnimateStyleSheet.parentNode ) {
  93. this.autoAnimateStyleSheet.parentNode.removeChild( this.autoAnimateStyleSheet );
  94. this.autoAnimateStyleSheet = null;
  95. }
  96. }
  97. /**
  98. * Creates a FLIP animation where the `to` element starts out
  99. * in the `from` element position and animates to its original
  100. * state.
  101. *
  102. * @param {HTMLElement} from
  103. * @param {HTMLElement} to
  104. * @param {Object} elementOptions Options for this element pair
  105. * @param {Object} animationOptions Options set at the slide level
  106. * @param {String} id Unique ID that we can use to identify this
  107. * auto-animate element in the DOM
  108. */
  109. autoAnimateElements( from, to, elementOptions, animationOptions, id ) {
  110. // 'from' elements are given a data-auto-animate-target with no value,
  111. // 'to' elements are are given a data-auto-animate-target with an ID
  112. from.dataset.autoAnimateTarget = '';
  113. to.dataset.autoAnimateTarget = id;
  114. // Each element may override any of the auto-animate options
  115. // like transition easing, duration and delay via data-attributes
  116. let options = this.getAutoAnimateOptions( to, animationOptions );
  117. // If we're using a custom element matcher the element options
  118. // may contain additional transition overrides
  119. if( typeof elementOptions.delay !== 'undefined' ) options.delay = elementOptions.delay;
  120. if( typeof elementOptions.duration !== 'undefined' ) options.duration = elementOptions.duration;
  121. if( typeof elementOptions.easing !== 'undefined' ) options.easing = elementOptions.easing;
  122. let fromProps = this.getAutoAnimatableProperties( 'from', from, elementOptions ),
  123. toProps = this.getAutoAnimatableProperties( 'to', to, elementOptions );
  124. // Maintain fragment visibility for matching elements when
  125. // we're navigating forwards, this way the viewer won't need
  126. // to step through the same fragments twice
  127. if( to.classList.contains( 'fragment' ) ) {
  128. // Don't auto-animate the opacity of fragments to avoid
  129. // conflicts with fragment animations
  130. delete toProps.styles['opacity'];
  131. if( from.classList.contains( 'fragment' ) ) {
  132. let fromFragmentStyle = ( from.className.match( FRAGMENT_STYLE_REGEX ) || [''] )[0];
  133. let toFragmentStyle = ( to.className.match( FRAGMENT_STYLE_REGEX ) || [''] )[0];
  134. // Only skip the fragment if the fragment animation style
  135. // remains unchanged
  136. if( fromFragmentStyle === toFragmentStyle && animationOptions.slideDirection === 'forward' ) {
  137. to.classList.add( 'visible', 'disabled' );
  138. }
  139. }
  140. }
  141. // If translation and/or scaling are enabled, css transform
  142. // the 'to' element so that it matches the position and size
  143. // of the 'from' element
  144. if( elementOptions.translate !== false || elementOptions.scale !== false ) {
  145. let presentationScale = this.Reveal.getScale();
  146. let delta = {
  147. x: ( fromProps.x - toProps.x ) / presentationScale,
  148. y: ( fromProps.y - toProps.y ) / presentationScale,
  149. scaleX: fromProps.width / toProps.width,
  150. scaleY: fromProps.height / toProps.height
  151. };
  152. // Limit decimal points to avoid 0.0001px blur and stutter
  153. delta.x = Math.round( delta.x * 1000 ) / 1000;
  154. delta.y = Math.round( delta.y * 1000 ) / 1000;
  155. delta.scaleX = Math.round( delta.scaleX * 1000 ) / 1000;
  156. delta.scaleX = Math.round( delta.scaleX * 1000 ) / 1000;
  157. let translate = elementOptions.translate !== false && ( delta.x !== 0 || delta.y !== 0 ),
  158. scale = elementOptions.scale !== false && ( delta.scaleX !== 0 || delta.scaleY !== 0 );
  159. // No need to transform if nothing's changed
  160. if( translate || scale ) {
  161. let transform = [];
  162. if( translate ) transform.push( `translate(${delta.x}px, ${delta.y}px)` );
  163. if( scale ) transform.push( `scale(${delta.scaleX}, ${delta.scaleY})` );
  164. fromProps.styles['transform'] = transform.join( ' ' );
  165. fromProps.styles['transform-origin'] = 'top left';
  166. toProps.styles['transform'] = 'none';
  167. }
  168. }
  169. // Delete all unchanged 'to' styles
  170. for( let propertyName in toProps.styles ) {
  171. const toValue = toProps.styles[propertyName];
  172. const fromValue = fromProps.styles[propertyName];
  173. if( toValue === fromValue ) {
  174. delete toProps.styles[propertyName];
  175. }
  176. else {
  177. // If these property values were set via a custom matcher providing
  178. // an explicit 'from' and/or 'to' value, we always inject those values.
  179. if( toValue.explicitValue === true ) {
  180. toProps.styles[propertyName] = toValue.value;
  181. }
  182. if( fromValue.explicitValue === true ) {
  183. fromProps.styles[propertyName] = fromValue.value;
  184. }
  185. }
  186. }
  187. let css = '';
  188. let toStyleProperties = Object.keys( toProps.styles );
  189. // Only create animate this element IF at least one style
  190. // property has changed
  191. if( toStyleProperties.length > 0 ) {
  192. // Instantly move to the 'from' state
  193. fromProps.styles['transition'] = 'none';
  194. // Animate towards the 'to' state
  195. toProps.styles['transition'] = `all ${options.duration}s ${options.easing} ${options.delay}s`;
  196. toProps.styles['transition-property'] = toStyleProperties.join( ', ' );
  197. toProps.styles['will-change'] = toStyleProperties.join( ', ' );
  198. // Build up our custom CSS. We need to override inline styles
  199. // so we need to make our styles vErY IMPORTANT!1!!
  200. let fromCSS = Object.keys( fromProps.styles ).map( propertyName => {
  201. return propertyName + ': ' + fromProps.styles[propertyName] + ' !important;';
  202. } ).join( '' );
  203. let toCSS = Object.keys( toProps.styles ).map( propertyName => {
  204. return propertyName + ': ' + toProps.styles[propertyName] + ' !important;';
  205. } ).join( '' );
  206. css = '[data-auto-animate-target="'+ id +'"] {'+ fromCSS +'}' +
  207. '[data-auto-animate="running"] [data-auto-animate-target="'+ id +'"] {'+ toCSS +'}';
  208. }
  209. return css;
  210. }
  211. /**
  212. * Returns the auto-animate options for the given element.
  213. *
  214. * @param {HTMLElement} element Element to pick up options
  215. * from, either a slide or an animation target
  216. * @param {Object} [inheritedOptions] Optional set of existing
  217. * options
  218. */
  219. getAutoAnimateOptions( element, inheritedOptions ) {
  220. let options = {
  221. easing: this.Reveal.getConfig().autoAnimateEasing,
  222. duration: this.Reveal.getConfig().autoAnimateDuration,
  223. delay: 0
  224. };
  225. options = extend( options, inheritedOptions );
  226. // Inherit options from parent elements
  227. if( element.parentNode ) {
  228. let autoAnimatedParent = closest( element.parentNode, '[data-auto-animate-target]' );
  229. if( autoAnimatedParent ) {
  230. options = this.getAutoAnimateOptions( autoAnimatedParent, options );
  231. }
  232. }
  233. if( element.dataset.autoAnimateEasing ) {
  234. options.easing = element.dataset.autoAnimateEasing;
  235. }
  236. if( element.dataset.autoAnimateDuration ) {
  237. options.duration = parseFloat( element.dataset.autoAnimateDuration );
  238. }
  239. if( element.dataset.autoAnimateDelay ) {
  240. options.delay = parseFloat( element.dataset.autoAnimateDelay );
  241. }
  242. return options;
  243. }
  244. /**
  245. * Returns an object containing all of the properties
  246. * that can be auto-animated for the given element and
  247. * their current computed values.
  248. *
  249. * @param {String} direction 'from' or 'to'
  250. */
  251. getAutoAnimatableProperties( direction, element, elementOptions ) {
  252. let config = this.Reveal.getConfig();
  253. let properties = { styles: [] };
  254. // Position and size
  255. if( elementOptions.translate !== false || elementOptions.scale !== false ) {
  256. let bounds;
  257. // Custom auto-animate may optionally return a custom tailored
  258. // measurement function
  259. if( typeof elementOptions.measure === 'function' ) {
  260. bounds = elementOptions.measure( element );
  261. }
  262. else {
  263. if( config.center ) {
  264. // More precise, but breaks when used in combination
  265. // with zoom for scaling the deck ¯\_(ツ)_/¯
  266. bounds = element.getBoundingClientRect();
  267. }
  268. else {
  269. let scale = this.Reveal.getScale();
  270. bounds = {
  271. x: element.offsetLeft * scale,
  272. y: element.offsetTop * scale,
  273. width: element.offsetWidth * scale,
  274. height: element.offsetHeight * scale
  275. };
  276. }
  277. }
  278. properties.x = bounds.x;
  279. properties.y = bounds.y;
  280. properties.width = bounds.width;
  281. properties.height = bounds.height;
  282. }
  283. const computedStyles = getComputedStyle( element );
  284. // CSS styles
  285. ( elementOptions.styles || config.autoAnimateStyles ).forEach( style => {
  286. let value;
  287. // `style` is either the property name directly, or an object
  288. // definition of a style property
  289. if( typeof style === 'string' ) style = { property: style };
  290. if( typeof style.from !== 'undefined' && direction === 'from' ) {
  291. value = { value: style.from, explicitValue: true };
  292. }
  293. else if( typeof style.to !== 'undefined' && direction === 'to' ) {
  294. value = { value: style.to, explicitValue: true };
  295. }
  296. else {
  297. value = computedStyles[style.property];
  298. }
  299. if( value !== '' ) {
  300. properties.styles[style.property] = value;
  301. }
  302. } );
  303. return properties;
  304. }
  305. /**
  306. * Get a list of all element pairs that we can animate
  307. * between the given slides.
  308. *
  309. * @param {HTMLElement} fromSlide
  310. * @param {HTMLElement} toSlide
  311. *
  312. * @return {Array} Each value is an array where [0] is
  313. * the element we're animating from and [1] is the
  314. * element we're animating to
  315. */
  316. getAutoAnimatableElements( fromSlide, toSlide ) {
  317. let matcher = typeof this.Reveal.getConfig().autoAnimateMatcher === 'function' ? this.Reveal.getConfig().autoAnimateMatcher : this.getAutoAnimatePairs;
  318. let pairs = matcher.call( this, fromSlide, toSlide );
  319. let reserved = [];
  320. // Remove duplicate pairs
  321. return pairs.filter( ( pair, index ) => {
  322. if( reserved.indexOf( pair.to ) === -1 ) {
  323. reserved.push( pair.to );
  324. return true;
  325. }
  326. } );
  327. }
  328. /**
  329. * Identifies matching elements between slides.
  330. *
  331. * You can specify a custom matcher function by using
  332. * the `autoAnimateMatcher` config option.
  333. */
  334. getAutoAnimatePairs( fromSlide, toSlide ) {
  335. let pairs = [];
  336. const codeNodes = 'pre';
  337. const textNodes = 'h1, h2, h3, h4, h5, h6, p, li';
  338. const mediaNodes = 'img, video, iframe';
  339. // Eplicit matches via data-id
  340. this.findAutoAnimateMatches( pairs, fromSlide, toSlide, '[data-id]', node => {
  341. return node.nodeName + ':::' + node.getAttribute( 'data-id' );
  342. } );
  343. // Text
  344. this.findAutoAnimateMatches( pairs, fromSlide, toSlide, textNodes, node => {
  345. return node.nodeName + ':::' + node.innerText;
  346. } );
  347. // Media
  348. this.findAutoAnimateMatches( pairs, fromSlide, toSlide, mediaNodes, node => {
  349. return node.nodeName + ':::' + ( node.getAttribute( 'src' ) || node.getAttribute( 'data-src' ) );
  350. } );
  351. // Code
  352. this.findAutoAnimateMatches( pairs, fromSlide, toSlide, codeNodes, node => {
  353. return node.nodeName + ':::' + node.innerText;
  354. } );
  355. pairs.forEach( pair => {
  356. // Disable scale transformations on text nodes, we transiition
  357. // each individual text property instead
  358. if( matches( pair.from, textNodes ) ) {
  359. pair.options = { scale: false };
  360. }
  361. // Animate individual lines of code
  362. else if( matches( pair.from, codeNodes ) ) {
  363. // Transition the code block's width and height instead of scaling
  364. // to prevent its content from being squished
  365. pair.options = { scale: false, styles: [ 'width', 'height' ] };
  366. // Lines of code
  367. this.findAutoAnimateMatches( pairs, pair.from, pair.to, '.hljs .hljs-ln-code', node => {
  368. return node.textContent;
  369. }, {
  370. scale: false,
  371. styles: [],
  372. measure: this.getLocalBoundingBox.bind( this )
  373. } );
  374. // Line numbers
  375. this.findAutoAnimateMatches( pairs, pair.from, pair.to, '.hljs .hljs-ln-line[data-line-number]', node => {
  376. return node.getAttribute( 'data-line-number' );
  377. }, {
  378. scale: false,
  379. styles: [ 'width' ],
  380. measure: this.getLocalBoundingBox.bind( this )
  381. } );
  382. }
  383. }, this );
  384. return pairs;
  385. }
  386. /**
  387. * Helper method which returns a bounding box based on
  388. * the given elements offset coordinates.
  389. *
  390. * @param {HTMLElement} element
  391. * @return {Object} x, y, width, height
  392. */
  393. getLocalBoundingBox( element ) {
  394. const presentationScale = this.Reveal.getScale();
  395. return {
  396. x: Math.round( ( element.offsetLeft * presentationScale ) * 100 ) / 100,
  397. y: Math.round( ( element.offsetTop * presentationScale ) * 100 ) / 100,
  398. width: Math.round( ( element.offsetWidth * presentationScale ) * 100 ) / 100,
  399. height: Math.round( ( element.offsetHeight * presentationScale ) * 100 ) / 100
  400. };
  401. }
  402. /**
  403. * Finds matching elements between two slides.
  404. *
  405. * @param {Array} pairs List of pairs to push matches to
  406. * @param {HTMLElement} fromScope Scope within the from element exists
  407. * @param {HTMLElement} toScope Scope within the to element exists
  408. * @param {String} selector CSS selector of the element to match
  409. * @param {Function} serializer A function that accepts an element and returns
  410. * a stringified ID based on its contents
  411. * @param {Object} animationOptions Optional config options for this pair
  412. */
  413. findAutoAnimateMatches( pairs, fromScope, toScope, selector, serializer, animationOptions ) {
  414. let fromMatches = {};
  415. let toMatches = {};
  416. [].slice.call( fromScope.querySelectorAll( selector ) ).forEach( ( element, i ) => {
  417. const key = serializer( element );
  418. if( typeof key === 'string' && key.length ) {
  419. fromMatches[key] = fromMatches[key] || [];
  420. fromMatches[key].push( element );
  421. }
  422. } );
  423. [].slice.call( toScope.querySelectorAll( selector ) ).forEach( ( element, i ) => {
  424. const key = serializer( element );
  425. toMatches[key] = toMatches[key] || [];
  426. toMatches[key].push( element );
  427. let fromElement;
  428. // Retrieve the 'from' element
  429. if( fromMatches[key] ) {
  430. const pimaryIndex = toMatches[key].length - 1;
  431. const secondaryIndex = fromMatches[key].length - 1;
  432. // If there are multiple identical from elements, retrieve
  433. // the one at the same index as our to-element.
  434. if( fromMatches[key][ pimaryIndex ] ) {
  435. fromElement = fromMatches[key][ pimaryIndex ];
  436. fromMatches[key][ pimaryIndex ] = null;
  437. }
  438. // If there are no matching from-elements at the same index,
  439. // use the last one.
  440. else if( fromMatches[key][ secondaryIndex ] ) {
  441. fromElement = fromMatches[key][ secondaryIndex ];
  442. fromMatches[key][ secondaryIndex ] = null;
  443. }
  444. }
  445. // If we've got a matching pair, push it to the list of pairs
  446. if( fromElement ) {
  447. pairs.push({
  448. from: fromElement,
  449. to: element,
  450. options: animationOptions
  451. });
  452. }
  453. } );
  454. }
  455. /**
  456. * Returns a all elements within the given scope that should
  457. * be considered unmatched in an auto-animate transition. If
  458. * fading of unmatched elements is turned on, these elements
  459. * will fade when going between auto-animate slides.
  460. *
  461. * Note that parents of auto-animate targets are NOT considerd
  462. * unmatched since fading them would break the auto-animation.
  463. *
  464. * @param {HTMLElement} rootElement
  465. * @return {Array}
  466. */
  467. getUnmatchedAutoAnimateElements( rootElement ) {
  468. return [].slice.call( rootElement.children ).reduce( ( result, element ) => {
  469. const containsAnimatedElements = element.querySelector( '[data-auto-animate-target]' );
  470. // The element is unmatched if
  471. // - It is not an auto-animate target
  472. // - It does not contain any auto-animate targets
  473. if( !element.hasAttribute( 'data-auto-animate-target' ) && !containsAnimatedElements ) {
  474. result.push( element );
  475. }
  476. if( element.querySelector( '[data-auto-animate-target]' ) ) {
  477. result = result.concat( this.getUnmatchedAutoAnimateElements( element ) );
  478. }
  479. return result;
  480. }, [] );
  481. }
  482. }