NativeAnimation.mjs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import { invariant, millisecondsToSeconds, secondsToMilliseconds, noop } from 'motion-utils';
  2. import { style } from '../render/dom/style.mjs';
  3. import { getFinalKeyframe } from './keyframes/get-final.mjs';
  4. import { hydrateKeyframes } from './keyframes/hydrate.mjs';
  5. import { startWaapiAnimation } from './waapi/start-waapi-animation.mjs';
  6. import { applyGeneratorOptions } from './waapi/utils/apply-generator.mjs';
  7. const animationMaps = new WeakMap();
  8. const animationMapKey = (name, pseudoElement) => `${name}:${pseudoElement}`;
  9. function getAnimationMap(element) {
  10. const map = animationMaps.get(element) || new Map();
  11. animationMaps.set(element, map);
  12. return map;
  13. }
  14. /**
  15. * NativeAnimation implements AnimationPlaybackControls for the browser's Web Animations API.
  16. */
  17. class NativeAnimation {
  18. constructor(options) {
  19. /**
  20. * If we already have an animation, we don't need to instantiate one
  21. * and can just use this as a controls interface.
  22. */
  23. if ("animation" in options) {
  24. this.animation = options.animation;
  25. return;
  26. }
  27. const { element, name, keyframes: unresolvedKeyframes, pseudoElement, allowFlatten = false, } = options;
  28. let { transition } = options;
  29. this.isPseudoElement = Boolean(pseudoElement);
  30. this.allowFlatten = allowFlatten;
  31. /**
  32. * Stop any existing animations on the element before reading existing keyframes.
  33. *
  34. * TODO: Check for VisualElement before using animation state. This is a fallback
  35. * for mini animate(). Do this when implementing NativeAnimationExtended.
  36. */
  37. const animationMap = getAnimationMap(element);
  38. const key = animationMapKey(name, pseudoElement || "");
  39. const currentAnimation = animationMap.get(key);
  40. currentAnimation && currentAnimation.stop();
  41. /**
  42. * TODO: If these keyframes aren't correctly hydrated then we want to throw
  43. * run an instant animation.
  44. */
  45. const keyframes = hydrateKeyframes(element, name, unresolvedKeyframes, pseudoElement);
  46. invariant(typeof transition.type !== "string", `animateMini doesn't support "type" as a string. Did you mean to import { spring } from "motion"?`);
  47. transition = applyGeneratorOptions(transition);
  48. this.animation = startWaapiAnimation(element, name, keyframes, transition, pseudoElement);
  49. if (transition.autoplay === false) {
  50. this.animation.pause();
  51. }
  52. this.removeAnimation = () => animationMap.delete(key);
  53. this.animation.onfinish = () => {
  54. if (!pseudoElement) {
  55. style.set(element, name, getFinalKeyframe(keyframes, transition));
  56. this.cancel();
  57. }
  58. };
  59. /**
  60. * TODO: Check for VisualElement before using animation state.
  61. */
  62. animationMap.set(key, this);
  63. }
  64. play() {
  65. this.animation.play();
  66. }
  67. pause() {
  68. this.animation.pause();
  69. }
  70. complete() {
  71. this.animation.finish();
  72. }
  73. cancel() {
  74. try {
  75. this.animation.cancel();
  76. }
  77. catch (e) { }
  78. this.removeAnimation();
  79. }
  80. stop() {
  81. const { state } = this;
  82. if (state === "idle" || state === "finished") {
  83. return;
  84. }
  85. this.commitStyles();
  86. this.cancel();
  87. }
  88. /**
  89. * WAAPI doesn't natively have any interruption capabilities.
  90. *
  91. * In this method, we commit styles back to the DOM before cancelling
  92. * the animation.
  93. *
  94. * This is designed to be overridden by NativeAnimationExtended, which
  95. * will create a renderless JS animation and sample it twice to calculate
  96. * its current value, "previous" value, and therefore allow
  97. * Motion to also correctly calculate velocity for any subsequent animation
  98. * while deferring the commit until the next animation frame.
  99. */
  100. commitStyles() {
  101. if (!this.isPseudoElement) {
  102. this.animation.commitStyles?.();
  103. }
  104. }
  105. get duration() {
  106. const duration = this.animation.effect?.getComputedTiming().duration || 0;
  107. return millisecondsToSeconds(Number(duration));
  108. }
  109. get time() {
  110. return millisecondsToSeconds(Number(this.animation.currentTime) || 0);
  111. }
  112. set time(newTime) {
  113. this.animation.currentTime = secondsToMilliseconds(newTime);
  114. }
  115. /**
  116. * The playback speed of the animation.
  117. * 1 = normal speed, 2 = double speed, 0.5 = half speed.
  118. */
  119. get speed() {
  120. return this.animation.playbackRate;
  121. }
  122. set speed(newSpeed) {
  123. this.animation.playbackRate = newSpeed;
  124. }
  125. get state() {
  126. return this.animation.playState;
  127. }
  128. get startTime() {
  129. return Number(this.animation.startTime);
  130. }
  131. get finished() {
  132. return this.animation.finished;
  133. }
  134. flatten() {
  135. if (this.allowFlatten) {
  136. this.animation.effect?.updateTiming({ easing: "linear" });
  137. }
  138. }
  139. /**
  140. * Attaches a timeline to the animation, for instance the `ScrollTimeline`.
  141. */
  142. attachTimeline(timeline) {
  143. this.animation.timeline = timeline;
  144. this.animation.onfinish = null;
  145. return noop;
  146. }
  147. /**
  148. * Allows the animation to be awaited.
  149. *
  150. * @deprecated Use `finished` instead.
  151. */
  152. then(onResolve, onReject) {
  153. return this.finished.then(onResolve).catch(onReject);
  154. }
  155. }
  156. export { NativeAnimation };