autoanimate.js 20 KB

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