1
0

autoanimate.js 17 KB

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