autoanimate.js 20 KB

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