autoanimate.js 20 KB

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