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