autoanimate.js 17 KB

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