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