Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

641 řádky
20 KiB

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