motion-dom 14.9.1 → 14.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -287,6 +287,12 @@ class JSAnimation extends WithPromise {
287
287
  return millisecondsToSeconds(this.currentTime);
288
288
  }
289
289
  set time(newTime) {
290
+ /**
291
+ * Seeking out of "finished" leaves the animation paused, so play()
292
+ * won't renew finished. Renew it here.
293
+ */
294
+ if (this.state === "finished")
295
+ this.updateFinished();
290
296
  newTime = secondsToMilliseconds(newTime);
291
297
  this.currentTime = newTime;
292
298
  if (this.startTime === null ||
@@ -1 +1 @@
1
- {"version":3,"file":"JSAnimation.mjs","sources":["../../../src/animation/JSAnimation.ts"],"sourcesContent":["import {\n clamp,\n invariant,\n millisecondsToSeconds,\n pipe,\n secondsToMilliseconds,\n} from \"motion-utils\"\nimport { time } from \"../frameloop/sync-time\"\nimport { mix } from \"../utils/mix\"\nimport { Mixer } from \"../utils/mix/types\"\nimport { frameloopDriver } from \"./drivers/frame\"\nimport { DriverControls } from \"./drivers/types\"\nimport { inertia } from \"./generators/inertia\"\nimport { keyframes as keyframesGenerator } from \"./generators/keyframes\"\nimport { calcGeneratorDuration } from \"./generators/utils/calc-duration\"\nimport { calcGeneratorVelocity } from \"./generators/utils/velocity\"\nimport { getFinalKeyframe } from \"./keyframes/get-final\"\nimport {\n AnimationPlaybackControlsWithThen,\n AnimationState,\n GeneratorFactory,\n KeyframeGenerator,\n TimelineWithFallback,\n ValueAnimationOptions,\n} from \"./types\"\nimport { replaceTransitionType } from \"./utils/replace-transition-type\"\nimport { resolveStartTime } from \"./utils/resolve-start-time\"\nimport { notifyAnimationStart } from \"./utils/notify-inspector\"\nimport { WithPromise } from \"./utils/WithPromise\"\n\nconst percentToProgress = (percent: number) => percent / 100\n\nexport const round = (value: number) => Math.round(value * 10000) / 10000\n\nexport class JSAnimation<T extends number | string>\n extends WithPromise\n implements AnimationPlaybackControlsWithThen\n{\n state: AnimationPlayState = \"idle\"\n\n startTime: number | null = null\n\n /**\n * The driver that's controlling the animation loop. Normally this is a requestAnimationFrame loop\n * but in tests we can pass in a synchronous loop.\n */\n protected driver?: DriverControls\n\n protected isStopped = false\n\n /**\n * The start time this animation picked for itself, until its first tick.\n */\n private pendingStartTime?: number\n\n private generator: KeyframeGenerator<T>\n\n private calculatedDuration: number\n\n protected resolvedDuration: number\n\n protected totalDuration: number\n\n protected options: ValueAnimationOptions<T>\n\n /**\n * The current time of the animation.\n */\n private currentTime: number = 0\n\n /**\n * The time at which the animation was paused.\n */\n protected holdTime: number | null = null\n\n /**\n * Playback speed as a factor. 0 would be stopped, -1 reverse and 2 double speed.\n */\n private playbackSpeed = 1\n\n /*\n * If our generator doesn't support mixing numbers, we need to replace keyframes with\n * [0, 100] and then make a function that maps that to the actual keyframes.\n *\n * 100 is chosen instead of 1 as it works nicer with spring animations.\n */\n private mixKeyframes: Mixer<T> | undefined\n\n private mirroredGenerator: KeyframeGenerator<T> | undefined\n\n /**\n * Reusable state object for the delay phase to avoid\n * allocating a new object every frame.\n */\n private delayState: AnimationState<T> = {\n done: false,\n value: undefined as unknown as T,\n }\n\n constructor(options: ValueAnimationOptions<T>) {\n super()\n\n this.options = options\n this.initAnimation()\n this.play()\n\n if (options.autoplay === false) this.pause()\n\n notifyAnimationStart(this, this.options)\n }\n\n initAnimation() {\n const { options } = this\n\n replaceTransitionType(options)\n\n const {\n type = keyframesGenerator,\n repeat = 0,\n repeatDelay = 0,\n repeatType,\n velocity = 0,\n } = options\n let { keyframes } = options\n\n const generatorFactory =\n (type as GeneratorFactory) || keyframesGenerator\n\n if (\n process.env.NODE_ENV !== \"production\" &&\n generatorFactory !== keyframesGenerator\n ) {\n invariant(\n keyframes.length <= 2,\n `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes}`,\n \"spring-two-frames\"\n )\n }\n\n /**\n * This runs again when a spring is flattened to attach it to a\n * timeline, and the keyframes generator blends values itself.\n */\n this.mixKeyframes = undefined\n\n if (\n generatorFactory !== keyframesGenerator &&\n typeof keyframes[0] !== \"number\"\n ) {\n this.mixKeyframes = pipe(\n percentToProgress,\n options.mixer?.(keyframes[0], keyframes[1]) ||\n mix(keyframes[0], keyframes[1])\n ) as (t: number) => T\n\n keyframes = [0 as T, 100 as T]\n }\n\n const generator = generatorFactory(\n keyframes === options.keyframes\n ? options\n : { ...options, keyframes }\n )\n\n /**\n * If we have a mirror repeat type we need to create a second generator that outputs the\n * mirrored (not reversed) animation and later ping pong between the two generators.\n */\n if (repeatType === \"mirror\") {\n this.mirroredGenerator = generatorFactory({\n ...options,\n keyframes: [...keyframes].reverse(),\n velocity: -velocity,\n })\n }\n\n /**\n * If duration is undefined and we have repeat options,\n * we need to calculate a duration from the generator.\n *\n * We set it to the generator itself to cache the duration.\n * Any timeline resolver will need to have already precalculated\n * the duration by this step.\n */\n if (generator.calculatedDuration === null) {\n generator.calculatedDuration = calcGeneratorDuration(generator)\n }\n\n const { calculatedDuration } = generator\n this.calculatedDuration = calculatedDuration\n this.resolvedDuration = calculatedDuration + repeatDelay\n this.totalDuration = this.resolvedDuration * (repeat + 1) - repeatDelay\n this.generator = generator\n }\n\n updateTime(timestamp: number) {\n // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =\n // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for\n // example.\n this.currentTime =\n this.holdTime ??\n Math.round(timestamp - this.startTime!) * this.playbackSpeed\n }\n\n tick(timestamp: number, sample = false) {\n const { generator, totalDuration, calculatedDuration } = this\n\n if (this.startTime === null) return generator.next(0)\n\n const {\n delay = 0,\n keyframes,\n type,\n onUpdate,\n finalKeyframe,\n } = this.options\n\n if (this.startTime === this.pendingStartTime) {\n this.startTime = resolveStartTime(this.startTime, timestamp)\n }\n this.pendingStartTime = undefined\n\n /**\n * requestAnimationFrame timestamps can come through as lower than\n * the startTime as set by performance.now(). Here we prevent this,\n * though in the future it could be possible to make setting startTime\n * a pending operation that gets resolved here.\n */\n if (this.speed > 0) {\n this.startTime = Math.min(this.startTime, timestamp)\n } else if (this.speed < 0) {\n this.startTime = Math.min(\n timestamp - totalDuration / this.speed,\n this.startTime\n )\n }\n\n if (sample) {\n this.currentTime = timestamp\n } else {\n this.updateTime(timestamp)\n }\n\n // Rebase on delay\n const timeWithoutDelay =\n this.currentTime - delay * (this.playbackSpeed >= 0 ? 1 : -1)\n const isInDelayPhase =\n this.playbackSpeed >= 0\n ? timeWithoutDelay < 0\n : timeWithoutDelay > totalDuration\n this.currentTime = Math.max(timeWithoutDelay, 0)\n\n // If this animation has finished, set the current time to the total duration.\n if (this.state === \"finished\" && this.holdTime === null) {\n this.currentTime = totalDuration\n }\n\n const state = this.generate(this.currentTime, isInDelayPhase)\n\n let { done } = state\n\n /**\n * A generator that takes longer than maxGeneratorDuration to finish\n * has an Infinity duration, so played forwards it finishes when it\n * says it's done.\n */\n if (!isInDelayPhase) {\n done =\n this.playbackSpeed >= 0\n ? calculatedDuration < Infinity\n ? this.currentTime >= totalDuration\n : done\n : this.currentTime <= 0\n }\n\n const isAnimationFinished =\n this.holdTime === null &&\n (this.state === \"finished\" || (this.state === \"running\" && done))\n\n // TODO: The exception for inertia could be cleaner here\n if (isAnimationFinished && type !== inertia) {\n state.value = getFinalKeyframe(\n keyframes,\n this.options,\n finalKeyframe,\n this.speed\n )\n }\n\n if (onUpdate) {\n onUpdate(state.value)\n }\n\n if (isAnimationFinished) {\n this.finish()\n }\n\n return state\n }\n\n /**\n * This animation's time, including delay, at a timestamp.\n */\n at(timestamp: number) {\n return (\n this.holdTime ??\n round((timestamp - this.startTime!) * this.playbackSpeed)\n )\n }\n\n /**\n * The value at a timestamp, without changing this animation's state.\n * If resolved, it ends at the last resolved keyframe, which is in the\n * same unit as the others, rather than at finalKeyframe.\n */\n sampleAt(timestamp: number, resolved?: boolean): T {\n const { options, totalDuration } = this\n const t = this.at(timestamp) - (options.delay || 0)\n\n return t >= totalDuration && options.type !== inertia\n ? getFinalKeyframe(\n options.keyframes,\n options,\n resolved ? undefined : options.finalKeyframe\n )\n : this.generate(Math.max(t, 0), t < 0).value\n }\n\n /**\n * The generator's state `currentTime` ms after the delay, without\n * changing the animation's own state.\n */\n protected generate(\n currentTime: number,\n isInDelayPhase: boolean\n ): AnimationState<T> {\n const {\n generator,\n totalDuration,\n mixKeyframes,\n mirroredGenerator,\n resolvedDuration,\n } = this\n const { keyframes, repeat, repeatType, repeatDelay } = this.options\n\n let elapsed = currentTime\n let frameGenerator = generator\n\n if (repeat) {\n /**\n * Get the current progress (0-1) of the animation. If t is >\n * than duration we'll get values like 2.5 (midway through the\n * third iteration)\n */\n const progress =\n Math.min(currentTime, totalDuration) / resolvedDuration\n\n /**\n * Get the current iteration (0 indexed). For instance the floor of\n * 2.5 is 2.\n */\n let currentIteration = Math.floor(progress)\n\n /**\n * Get the current progress of the iteration by taking the remainder\n * so 2.5 is 0.5 through iteration 2\n */\n let iterationProgress = progress % 1.0\n\n /**\n * If iteration progress is 1 we count that as the end\n * of the previous iteration.\n */\n if (!iterationProgress && progress >= 1) {\n iterationProgress = 1\n }\n\n iterationProgress === 1 && currentIteration--\n\n currentIteration = Math.min(currentIteration, repeat + 1)\n\n /**\n * Reverse progress if we're not running in \"normal\" direction\n */\n\n const isOddIteration = Boolean(currentIteration % 2)\n if (isOddIteration) {\n if (repeatType === \"reverse\") {\n iterationProgress = 1 - iterationProgress\n if (repeatDelay) {\n iterationProgress -= repeatDelay / resolvedDuration\n }\n } else if (repeatType === \"mirror\") {\n frameGenerator = mirroredGenerator!\n }\n }\n\n elapsed = clamp(0, 1, iterationProgress) * resolvedDuration\n }\n\n /**\n * If we're in negative time, set state as the initial keyframe.\n * This prevents delay: x, duration: 0 animations from finishing\n * instantly.\n */\n let state: AnimationState<T>\n if (isInDelayPhase) {\n this.delayState.value = keyframes[0]\n state = this.delayState\n } else {\n state = frameGenerator.next(elapsed)\n }\n\n if (mixKeyframes && !isInDelayPhase) {\n state.value = mixKeyframes(state.value as number)\n }\n\n return state\n }\n\n get duration() {\n return millisecondsToSeconds(this.calculatedDuration)\n }\n\n get iterationDuration() {\n return this.duration + millisecondsToSeconds(this.options.delay ?? 0)\n }\n\n get time() {\n return millisecondsToSeconds(this.currentTime)\n }\n\n set time(newTime: number) {\n newTime = secondsToMilliseconds(newTime)\n this.currentTime = newTime\n\n if (\n this.startTime === null ||\n this.holdTime !== null ||\n this.playbackSpeed === 0\n ) {\n this.holdTime = newTime\n } else if (this.driver) {\n this.startTime = this.driver.now() - newTime / this.playbackSpeed\n }\n\n if (this.driver) {\n this.driver.start(false)\n } else {\n this.startTime = 0\n this.state = \"paused\"\n this.holdTime = newTime\n this.tick(newTime)\n }\n }\n\n /**\n * Returns the generator's velocity at the current time in units/second.\n * Uses the analytical derivative when available (springs), avoiding\n * the MotionValue's frame-dependent velocity estimation.\n */\n getGeneratorVelocity(): number {\n return calcGeneratorVelocity(\n this.generator,\n this.currentTime,\n this.options.velocity\n )\n }\n\n get speed() {\n return this.playbackSpeed\n }\n\n set speed(newSpeed: number) {\n const hasChanged = this.playbackSpeed !== newSpeed\n\n if (hasChanged && this.driver) {\n this.updateTime(time.now())\n }\n\n this.playbackSpeed = newSpeed\n\n if (hasChanged && this.driver) {\n this.time = millisecondsToSeconds(this.currentTime)\n }\n }\n\n play() {\n if (this.isStopped) return\n\n const { driver = frameloopDriver, startTime } = this.options\n\n if (!this.driver) {\n this.driver = driver((timestamp) => this.tick(timestamp))\n }\n\n this.options.onPlay?.()\n\n const now = this.driver.now()\n\n if (this.state === \"finished\") {\n this.updateFinished()\n this.startTime = now\n } else if (this.holdTime !== null) {\n this.startTime = now - this.holdTime / (this.playbackSpeed || 1)\n } else if (!this.startTime) {\n this.startTime = startTime ?? (this.pendingStartTime = now)\n }\n\n if (this.state === \"finished\" && this.speed < 0) {\n this.startTime += this.calculatedDuration\n }\n\n this.holdTime = null\n\n /**\n * Set playState to running only after we've used it in\n * the previous logic.\n */\n this.state = \"running\"\n\n this.driver.start()\n }\n\n pause() {\n this.state = \"paused\"\n this.updateTime(time.now())\n this.holdTime = this.currentTime\n }\n\n /**\n * This method is bound to the instance to fix a pattern where\n * animation.stop is returned as a reference from a useEffect.\n */\n stop = () => {\n const { motionValue } = this.options\n if (motionValue && motionValue.updatedAt !== time.now()) {\n this.tick(time.now())\n }\n\n this.isStopped = true\n if (this.state === \"idle\") return\n this.teardown()\n this.options.onStop?.()\n }\n\n complete() {\n if (this.state !== \"running\") {\n this.play()\n }\n\n this.state = \"finished\"\n this.holdTime = null\n }\n\n finish() {\n this.notifyFinished()\n this.teardown()\n this.state = \"finished\"\n\n this.options.onComplete?.()\n }\n\n cancel() {\n this.holdTime = null\n this.startTime = 0\n this.tick(0)\n this.teardown()\n this.options.onCancel?.()\n }\n\n private teardown() {\n this.state = \"idle\"\n this.driver?.stop()\n this.driver = undefined\n this.startTime = this.holdTime = null\n }\n\n sample(sampleTime: number): AnimationState<T> {\n this.startTime = 0\n return this.tick(sampleTime, true)\n }\n\n attachTimeline(timeline: TimelineWithFallback): VoidFunction {\n if (this.options.allowFlatten) {\n this.options.type = \"keyframes\"\n this.options.ease = \"linear\"\n this.initAnimation()\n }\n\n this.driver?.stop()\n return timeline.observe(this)\n }\n}\n\n// Legacy function support\nexport function animateValue<T extends number | string>(\n options: ValueAnimationOptions<T>\n) {\n return new JSAnimation(options)\n}\n"],"names":["keyframesGenerator","keyframes"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,iBAAiB,GAAG,CAAC,OAAe,KAAK,OAAO,GAAG,GAAG;AAErD,MAAM,KAAK,GAAG,CAAC,KAAa,KAAK,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,GAAG;AAE9D,MAAO,WACT,SAAQ,WAAW,CAAA;AAgEnB,IAAA,WAAA,CAAY,OAAiC,EAAA;AACzC,QAAA,KAAK,EAAE;QA9DX,IAAA,CAAA,KAAK,GAAuB,MAAM;QAElC,IAAA,CAAA,SAAS,GAAkB,IAAI;QAQrB,IAAA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{"version":3,"file":"JSAnimation.mjs","sources":["../../../src/animation/JSAnimation.ts"],"sourcesContent":["import {\n clamp,\n invariant,\n millisecondsToSeconds,\n pipe,\n secondsToMilliseconds,\n} from \"motion-utils\"\nimport { time } from \"../frameloop/sync-time\"\nimport { mix } from \"../utils/mix\"\nimport { Mixer } from \"../utils/mix/types\"\nimport { frameloopDriver } from \"./drivers/frame\"\nimport { DriverControls } from \"./drivers/types\"\nimport { inertia } from \"./generators/inertia\"\nimport { keyframes as keyframesGenerator } from \"./generators/keyframes\"\nimport { calcGeneratorDuration } from \"./generators/utils/calc-duration\"\nimport { calcGeneratorVelocity } from \"./generators/utils/velocity\"\nimport { getFinalKeyframe } from \"./keyframes/get-final\"\nimport {\n AnimationPlaybackControlsWithThen,\n AnimationState,\n GeneratorFactory,\n KeyframeGenerator,\n TimelineWithFallback,\n ValueAnimationOptions,\n} from \"./types\"\nimport { replaceTransitionType } from \"./utils/replace-transition-type\"\nimport { resolveStartTime } from \"./utils/resolve-start-time\"\nimport { notifyAnimationStart } from \"./utils/notify-inspector\"\nimport { WithPromise } from \"./utils/WithPromise\"\n\nconst percentToProgress = (percent: number) => percent / 100\n\nexport const round = (value: number) => Math.round(value * 10000) / 10000\n\nexport class JSAnimation<T extends number | string>\n extends WithPromise\n implements AnimationPlaybackControlsWithThen\n{\n state: AnimationPlayState = \"idle\"\n\n startTime: number | null = null\n\n /**\n * The driver that's controlling the animation loop. Normally this is a requestAnimationFrame loop\n * but in tests we can pass in a synchronous loop.\n */\n protected driver?: DriverControls\n\n protected isStopped = false\n\n /**\n * The start time this animation picked for itself, until its first tick.\n */\n private pendingStartTime?: number\n\n private generator: KeyframeGenerator<T>\n\n private calculatedDuration: number\n\n protected resolvedDuration: number\n\n protected totalDuration: number\n\n protected options: ValueAnimationOptions<T>\n\n /**\n * The current time of the animation.\n */\n private currentTime: number = 0\n\n /**\n * The time at which the animation was paused.\n */\n protected holdTime: number | null = null\n\n /**\n * Playback speed as a factor. 0 would be stopped, -1 reverse and 2 double speed.\n */\n private playbackSpeed = 1\n\n /*\n * If our generator doesn't support mixing numbers, we need to replace keyframes with\n * [0, 100] and then make a function that maps that to the actual keyframes.\n *\n * 100 is chosen instead of 1 as it works nicer with spring animations.\n */\n private mixKeyframes: Mixer<T> | undefined\n\n private mirroredGenerator: KeyframeGenerator<T> | undefined\n\n /**\n * Reusable state object for the delay phase to avoid\n * allocating a new object every frame.\n */\n private delayState: AnimationState<T> = {\n done: false,\n value: undefined as unknown as T,\n }\n\n constructor(options: ValueAnimationOptions<T>) {\n super()\n\n this.options = options\n this.initAnimation()\n this.play()\n\n if (options.autoplay === false) this.pause()\n\n notifyAnimationStart(this, this.options)\n }\n\n initAnimation() {\n const { options } = this\n\n replaceTransitionType(options)\n\n const {\n type = keyframesGenerator,\n repeat = 0,\n repeatDelay = 0,\n repeatType,\n velocity = 0,\n } = options\n let { keyframes } = options\n\n const generatorFactory =\n (type as GeneratorFactory) || keyframesGenerator\n\n if (\n process.env.NODE_ENV !== \"production\" &&\n generatorFactory !== keyframesGenerator\n ) {\n invariant(\n keyframes.length <= 2,\n `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes}`,\n \"spring-two-frames\"\n )\n }\n\n /**\n * This runs again when a spring is flattened to attach it to a\n * timeline, and the keyframes generator blends values itself.\n */\n this.mixKeyframes = undefined\n\n if (\n generatorFactory !== keyframesGenerator &&\n typeof keyframes[0] !== \"number\"\n ) {\n this.mixKeyframes = pipe(\n percentToProgress,\n options.mixer?.(keyframes[0], keyframes[1]) ||\n mix(keyframes[0], keyframes[1])\n ) as (t: number) => T\n\n keyframes = [0 as T, 100 as T]\n }\n\n const generator = generatorFactory(\n keyframes === options.keyframes\n ? options\n : { ...options, keyframes }\n )\n\n /**\n * If we have a mirror repeat type we need to create a second generator that outputs the\n * mirrored (not reversed) animation and later ping pong between the two generators.\n */\n if (repeatType === \"mirror\") {\n this.mirroredGenerator = generatorFactory({\n ...options,\n keyframes: [...keyframes].reverse(),\n velocity: -velocity,\n })\n }\n\n /**\n * If duration is undefined and we have repeat options,\n * we need to calculate a duration from the generator.\n *\n * We set it to the generator itself to cache the duration.\n * Any timeline resolver will need to have already precalculated\n * the duration by this step.\n */\n if (generator.calculatedDuration === null) {\n generator.calculatedDuration = calcGeneratorDuration(generator)\n }\n\n const { calculatedDuration } = generator\n this.calculatedDuration = calculatedDuration\n this.resolvedDuration = calculatedDuration + repeatDelay\n this.totalDuration = this.resolvedDuration * (repeat + 1) - repeatDelay\n this.generator = generator\n }\n\n updateTime(timestamp: number) {\n // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =\n // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for\n // example.\n this.currentTime =\n this.holdTime ??\n Math.round(timestamp - this.startTime!) * this.playbackSpeed\n }\n\n tick(timestamp: number, sample = false) {\n const { generator, totalDuration, calculatedDuration } = this\n\n if (this.startTime === null) return generator.next(0)\n\n const {\n delay = 0,\n keyframes,\n type,\n onUpdate,\n finalKeyframe,\n } = this.options\n\n if (this.startTime === this.pendingStartTime) {\n this.startTime = resolveStartTime(this.startTime, timestamp)\n }\n this.pendingStartTime = undefined\n\n /**\n * requestAnimationFrame timestamps can come through as lower than\n * the startTime as set by performance.now(). Here we prevent this,\n * though in the future it could be possible to make setting startTime\n * a pending operation that gets resolved here.\n */\n if (this.speed > 0) {\n this.startTime = Math.min(this.startTime, timestamp)\n } else if (this.speed < 0) {\n this.startTime = Math.min(\n timestamp - totalDuration / this.speed,\n this.startTime\n )\n }\n\n if (sample) {\n this.currentTime = timestamp\n } else {\n this.updateTime(timestamp)\n }\n\n // Rebase on delay\n const timeWithoutDelay =\n this.currentTime - delay * (this.playbackSpeed >= 0 ? 1 : -1)\n const isInDelayPhase =\n this.playbackSpeed >= 0\n ? timeWithoutDelay < 0\n : timeWithoutDelay > totalDuration\n this.currentTime = Math.max(timeWithoutDelay, 0)\n\n // If this animation has finished, set the current time to the total duration.\n if (this.state === \"finished\" && this.holdTime === null) {\n this.currentTime = totalDuration\n }\n\n const state = this.generate(this.currentTime, isInDelayPhase)\n\n let { done } = state\n\n /**\n * A generator that takes longer than maxGeneratorDuration to finish\n * has an Infinity duration, so played forwards it finishes when it\n * says it's done.\n */\n if (!isInDelayPhase) {\n done =\n this.playbackSpeed >= 0\n ? calculatedDuration < Infinity\n ? this.currentTime >= totalDuration\n : done\n : this.currentTime <= 0\n }\n\n const isAnimationFinished =\n this.holdTime === null &&\n (this.state === \"finished\" || (this.state === \"running\" && done))\n\n // TODO: The exception for inertia could be cleaner here\n if (isAnimationFinished && type !== inertia) {\n state.value = getFinalKeyframe(\n keyframes,\n this.options,\n finalKeyframe,\n this.speed\n )\n }\n\n if (onUpdate) {\n onUpdate(state.value)\n }\n\n if (isAnimationFinished) {\n this.finish()\n }\n\n return state\n }\n\n /**\n * This animation's time, including delay, at a timestamp.\n */\n at(timestamp: number) {\n return (\n this.holdTime ??\n round((timestamp - this.startTime!) * this.playbackSpeed)\n )\n }\n\n /**\n * The value at a timestamp, without changing this animation's state.\n * If resolved, it ends at the last resolved keyframe, which is in the\n * same unit as the others, rather than at finalKeyframe.\n */\n sampleAt(timestamp: number, resolved?: boolean): T {\n const { options, totalDuration } = this\n const t = this.at(timestamp) - (options.delay || 0)\n\n return t >= totalDuration && options.type !== inertia\n ? getFinalKeyframe(\n options.keyframes,\n options,\n resolved ? undefined : options.finalKeyframe\n )\n : this.generate(Math.max(t, 0), t < 0).value\n }\n\n /**\n * The generator's state `currentTime` ms after the delay, without\n * changing the animation's own state.\n */\n protected generate(\n currentTime: number,\n isInDelayPhase: boolean\n ): AnimationState<T> {\n const {\n generator,\n totalDuration,\n mixKeyframes,\n mirroredGenerator,\n resolvedDuration,\n } = this\n const { keyframes, repeat, repeatType, repeatDelay } = this.options\n\n let elapsed = currentTime\n let frameGenerator = generator\n\n if (repeat) {\n /**\n * Get the current progress (0-1) of the animation. If t is >\n * than duration we'll get values like 2.5 (midway through the\n * third iteration)\n */\n const progress =\n Math.min(currentTime, totalDuration) / resolvedDuration\n\n /**\n * Get the current iteration (0 indexed). For instance the floor of\n * 2.5 is 2.\n */\n let currentIteration = Math.floor(progress)\n\n /**\n * Get the current progress of the iteration by taking the remainder\n * so 2.5 is 0.5 through iteration 2\n */\n let iterationProgress = progress % 1.0\n\n /**\n * If iteration progress is 1 we count that as the end\n * of the previous iteration.\n */\n if (!iterationProgress && progress >= 1) {\n iterationProgress = 1\n }\n\n iterationProgress === 1 && currentIteration--\n\n currentIteration = Math.min(currentIteration, repeat + 1)\n\n /**\n * Reverse progress if we're not running in \"normal\" direction\n */\n\n const isOddIteration = Boolean(currentIteration % 2)\n if (isOddIteration) {\n if (repeatType === \"reverse\") {\n iterationProgress = 1 - iterationProgress\n if (repeatDelay) {\n iterationProgress -= repeatDelay / resolvedDuration\n }\n } else if (repeatType === \"mirror\") {\n frameGenerator = mirroredGenerator!\n }\n }\n\n elapsed = clamp(0, 1, iterationProgress) * resolvedDuration\n }\n\n /**\n * If we're in negative time, set state as the initial keyframe.\n * This prevents delay: x, duration: 0 animations from finishing\n * instantly.\n */\n let state: AnimationState<T>\n if (isInDelayPhase) {\n this.delayState.value = keyframes[0]\n state = this.delayState\n } else {\n state = frameGenerator.next(elapsed)\n }\n\n if (mixKeyframes && !isInDelayPhase) {\n state.value = mixKeyframes(state.value as number)\n }\n\n return state\n }\n\n get duration() {\n return millisecondsToSeconds(this.calculatedDuration)\n }\n\n get iterationDuration() {\n return this.duration + millisecondsToSeconds(this.options.delay ?? 0)\n }\n\n get time() {\n return millisecondsToSeconds(this.currentTime)\n }\n\n set time(newTime: number) {\n /**\n * Seeking out of \"finished\" leaves the animation paused, so play()\n * won't renew finished. Renew it here.\n */\n if (this.state === \"finished\") this.updateFinished()\n\n newTime = secondsToMilliseconds(newTime)\n this.currentTime = newTime\n\n if (\n this.startTime === null ||\n this.holdTime !== null ||\n this.playbackSpeed === 0\n ) {\n this.holdTime = newTime\n } else if (this.driver) {\n this.startTime = this.driver.now() - newTime / this.playbackSpeed\n }\n\n if (this.driver) {\n this.driver.start(false)\n } else {\n this.startTime = 0\n this.state = \"paused\"\n this.holdTime = newTime\n this.tick(newTime)\n }\n }\n\n /**\n * Returns the generator's velocity at the current time in units/second.\n * Uses the analytical derivative when available (springs), avoiding\n * the MotionValue's frame-dependent velocity estimation.\n */\n getGeneratorVelocity(): number {\n return calcGeneratorVelocity(\n this.generator,\n this.currentTime,\n this.options.velocity\n )\n }\n\n get speed() {\n return this.playbackSpeed\n }\n\n set speed(newSpeed: number) {\n const hasChanged = this.playbackSpeed !== newSpeed\n\n if (hasChanged && this.driver) {\n this.updateTime(time.now())\n }\n\n this.playbackSpeed = newSpeed\n\n if (hasChanged && this.driver) {\n this.time = millisecondsToSeconds(this.currentTime)\n }\n }\n\n play() {\n if (this.isStopped) return\n\n const { driver = frameloopDriver, startTime } = this.options\n\n if (!this.driver) {\n this.driver = driver((timestamp) => this.tick(timestamp))\n }\n\n this.options.onPlay?.()\n\n const now = this.driver.now()\n\n if (this.state === \"finished\") {\n this.updateFinished()\n this.startTime = now\n } else if (this.holdTime !== null) {\n this.startTime = now - this.holdTime / (this.playbackSpeed || 1)\n } else if (!this.startTime) {\n this.startTime = startTime ?? (this.pendingStartTime = now)\n }\n\n if (this.state === \"finished\" && this.speed < 0) {\n this.startTime += this.calculatedDuration\n }\n\n this.holdTime = null\n\n /**\n * Set playState to running only after we've used it in\n * the previous logic.\n */\n this.state = \"running\"\n\n this.driver.start()\n }\n\n pause() {\n this.state = \"paused\"\n this.updateTime(time.now())\n this.holdTime = this.currentTime\n }\n\n /**\n * This method is bound to the instance to fix a pattern where\n * animation.stop is returned as a reference from a useEffect.\n */\n stop = () => {\n const { motionValue } = this.options\n if (motionValue && motionValue.updatedAt !== time.now()) {\n this.tick(time.now())\n }\n\n this.isStopped = true\n if (this.state === \"idle\") return\n this.teardown()\n this.options.onStop?.()\n }\n\n complete() {\n if (this.state !== \"running\") {\n this.play()\n }\n\n this.state = \"finished\"\n this.holdTime = null\n }\n\n finish() {\n this.notifyFinished()\n this.teardown()\n this.state = \"finished\"\n\n this.options.onComplete?.()\n }\n\n cancel() {\n this.holdTime = null\n this.startTime = 0\n this.tick(0)\n this.teardown()\n this.options.onCancel?.()\n }\n\n private teardown() {\n this.state = \"idle\"\n this.driver?.stop()\n this.driver = undefined\n this.startTime = this.holdTime = null\n }\n\n sample(sampleTime: number): AnimationState<T> {\n this.startTime = 0\n return this.tick(sampleTime, true)\n }\n\n attachTimeline(timeline: TimelineWithFallback): VoidFunction {\n if (this.options.allowFlatten) {\n this.options.type = \"keyframes\"\n this.options.ease = \"linear\"\n this.initAnimation()\n }\n\n this.driver?.stop()\n return timeline.observe(this)\n }\n}\n\n// Legacy function support\nexport function animateValue<T extends number | string>(\n options: ValueAnimationOptions<T>\n) {\n return new JSAnimation(options)\n}\n"],"names":["keyframesGenerator","keyframes"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,iBAAiB,GAAG,CAAC,OAAe,KAAK,OAAO,GAAG,GAAG;AAErD,MAAM,KAAK,GAAG,CAAC,KAAa,KAAK,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,GAAG;AAE9D,MAAO,WACT,SAAQ,WAAW,CAAA;AAgEnB,IAAA,WAAA,CAAY,OAAiC,EAAA;AACzC,QAAA,KAAK,EAAE;QA9DX,IAAA,CAAA,KAAK,GAAuB,MAAM;QAElC,IAAA,CAAA,SAAS,GAAkB,IAAI;QAQrB,IAAA,CAAA,SAAS,GAAG,KAAK;AAiB3B;;AAEG;QACK,IAAA,CAAA,WAAW,GAAW,CAAC;AAE/B;;AAEG;QACO,IAAA,CAAA,QAAQ,GAAkB,IAAI;AAExC;;AAEG;QACK,IAAA,CAAA,aAAa,GAAG,CAAC;AAYzB;;;AAGG;AACK,QAAA,IAAA,CAAA,UAAU,GAAsB;AACpC,YAAA,IAAI,EAAE,KAAK;AACX,YAAA,KAAK,EAAE,SAAyB;SACnC;AAubD;;;AAGG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GAAG,IAAI;AACpB,QAAA,IAAI,CAAC,SAAS,GAAG,CAAC;AAClB,QAAA,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACZ,IAAI,CAAC,QAAQ,EAAE;AACf,QAAA,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI;IAC7B;IAEQ,QAAQ,GAAA;AACZ,QAAA,IAAI,CAAC,KAAK,GAAG,MAAM;AACnB,QAAA,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE;AACnB,QAAA,IAAI,CAAC,MAAM,GAAG,SAAS;QACvB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,GAAG,IAAI;IACzC;AAEA,IAAA,MAAM,CAAC,UAAkB,EAAA;AACrB,QAAA,IAAI,CAAC,SAAS,GAAG,CAAC;QAClB,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC;IACtC;AAEA,IAAA,cAAc,CAAC,QAA8B,EAAA;AACzC,QAAA,IAAI,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE;AAC3B,YAAA,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,WAAW;AAC/B,YAAA,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,QAAQ;YAC5B,IAAI,CAAC,aAAa,EAAE;QACxB;AAEA,QAAA,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE;AACnB,QAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC;IACjC;AACH;AAED;AACM,SAAU,YAAY,CACxB,OAAiC,EAAA;AAEjC,IAAA,OAAO,IAAI,WAAW,CAAC,OAAO,CAAC;AACnC;;;;"}
@@ -136,8 +136,13 @@ class NativeAnimation extends WithPromise {
136
136
  this.manualStartTime = null;
137
137
  this.finishedTime = null;
138
138
  this.animation.currentTime = secondsToMilliseconds(newTime);
139
+ /**
140
+ * Seeking out of "finished" leaves the animation paused, so play()
141
+ * won't renew finished. Renew it here.
142
+ */
139
143
  if (wasFinished) {
140
144
  this.animation.pause();
145
+ this.updateFinished();
141
146
  }
142
147
  }
143
148
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"NativeAnimation.mjs","sources":["../../../src/animation/NativeAnimation.ts"],"sourcesContent":["import {\n invariant,\n millisecondsToSeconds,\n noop,\n secondsToMilliseconds,\n} from \"motion-utils\"\nimport { setStyle } from \"../render/dom/style-set\"\nimport { supportsScrollTimeline } from \"../utils/supports/scroll-timeline\"\nimport { getFinalKeyframe } from \"./keyframes/get-final\"\nimport {\n AnimationPlaybackControlsWithThen,\n AnyResolvedKeyframe,\n DOMValueAnimationOptions,\n TimelineWithFallback,\n} from \"./types\"\nimport { WithPromise } from \"./utils/WithPromise\"\nimport { notifyAnimationStart } from \"./utils/notify-inspector\"\nimport { startWaapiAnimation } from \"./waapi/start-waapi-animation\"\nimport { applyGeneratorOptions } from \"./waapi/utils/apply-generator\"\n\nexport interface NativeAnimationOptions<V extends AnyResolvedKeyframe = number>\n extends DOMValueAnimationOptions<V> {\n pseudoElement?: string\n startTime?: number\n}\n\n/**\n * NativeAnimation implements AnimationPlaybackControls for the browser's Web Animations API.\n */\nexport class NativeAnimation<T extends AnyResolvedKeyframe>\n extends WithPromise\n implements AnimationPlaybackControlsWithThen\n{\n /**\n * The interfaced Web Animation API animation\n */\n protected animation: Animation\n\n protected finishedTime: number | null = null\n\n protected options: NativeAnimationOptions\n\n /**\n * The WAAPI animation's finish handler. It's only attached while the\n * animation can finish, because WebKit never collects an animation\n * once it has run, nor anything its handlers reference (#4034).\n */\n protected onFinish: VoidFunction | null\n\n private allowFlatten: boolean\n\n private isStopped = false\n\n private isPseudoElement: boolean\n\n /**\n * Tracks a manually-set start time that takes precedence over WAAPI's\n * dynamic startTime. This is cleared when play() or time setter is called,\n * allowing WAAPI to take over timing.\n */\n protected manualStartTime: number | null = null\n\n constructor(options?: NativeAnimationOptions) {\n super()\n\n if (!options) return\n\n const {\n element,\n name,\n keyframes,\n pseudoElement,\n allowFlatten = false,\n finalKeyframe,\n onComplete,\n } = options as any\n\n this.isPseudoElement = Boolean(pseudoElement)\n\n this.allowFlatten = allowFlatten\n this.options = options\n\n typeof process !== \"undefined\" &&\n process.env.NODE_ENV !== \"production\" &&\n invariant(\n typeof options.type !== \"string\",\n `Mini animate() doesn't support \"type\" as a string.`,\n \"mini-spring\"\n )\n\n const transition = applyGeneratorOptions(options)\n\n this.animation = startWaapiAnimation(\n element,\n name,\n keyframes,\n transition,\n pseudoElement\n )\n\n if (transition.autoplay === false) {\n this.animation.pause()\n }\n\n this.animation.onfinish = this.onFinish = () => {\n this.animation.onfinish = null\n this.finishedTime = this.time\n\n if (!pseudoElement) {\n const keyframe = getFinalKeyframe(\n keyframes as any,\n this.options as any,\n finalKeyframe,\n this.speed\n )\n this.updateMotionValue?.(keyframe)\n\n /**\n * If we can, we want to commit the final style as set by the user,\n * rather than the computed keyframe value supplied by the animation.\n * We always do this, even when a motion value is present, to prevent\n * a visual flash in Firefox where the WAAPI animation's fill is removed\n * during cancel() before the scheduled render can apply the correct value.\n */\n setStyle(element, name, keyframe)\n\n this.animation.cancel()\n }\n\n onComplete?.()\n this.notifyFinished()\n }\n\n notifyAnimationStart(this, options, transition)\n }\n\n updateMotionValue?(value?: T): void\n\n play() {\n if (this.isStopped) return\n\n this.manualStartTime = null\n this.animation.onfinish = this.onFinish\n this.animation.play()\n\n if (this.state === \"finished\") {\n this.updateFinished()\n }\n }\n\n pause() {\n this.animation.pause()\n }\n\n complete() {\n if (!this.isStopped) this.animation.onfinish = this.onFinish\n this.animation.finish?.()\n }\n\n cancel() {\n this.animation.onfinish = null\n try {\n this.animation.cancel()\n } catch (e) {}\n }\n\n stop() {\n if (this.isStopped) return\n this.isStopped = true\n\n /**\n * Before its finish event, a finished animation (an instant one is\n * as soon as it starts) is still showing its end, so it's stopped\n * like a running one. Otherwise that event would apply its end\n * over whatever animates the value next.\n */\n if (this.state === \"idle\" || this.finishedTime !== null) return\n\n if (this.updateMotionValue) {\n this.updateMotionValue()\n } else {\n this.commitStyles()\n }\n\n if (!this.isPseudoElement) this.cancel()\n }\n\n /**\n * WAAPI doesn't natively have any interruption capabilities.\n *\n * In this method, we commit styles back to the DOM before cancelling\n * the animation.\n *\n * This is designed to be overridden by NativeAnimationExtended, which\n * will create a renderless JS animation and sample it twice to calculate\n * its current value, \"previous\" value, and therefore allow\n * Motion to also correctly calculate velocity for any subsequent animation\n * while deferring the commit until the next animation frame.\n */\n protected commitStyles() {\n const element = this.options?.element\n if (!this.isPseudoElement && element?.isConnected) {\n this.animation.commitStyles?.()\n }\n }\n\n get duration() {\n const duration =\n this.animation.effect?.getComputedTiming?.().duration || 0\n\n return millisecondsToSeconds(Number(duration))\n }\n\n get iterationDuration() {\n const { delay = 0 } = this.options || {}\n return this.duration + millisecondsToSeconds(delay)\n }\n\n get time() {\n return millisecondsToSeconds(Number(this.animation.currentTime) || 0)\n }\n\n set time(newTime: number) {\n const wasFinished = this.finishedTime !== null\n this.manualStartTime = null\n this.finishedTime = null\n this.animation.currentTime = secondsToMilliseconds(newTime)\n\n if (wasFinished) {\n this.animation.pause()\n }\n }\n\n /**\n * The playback speed of the animation.\n * 1 = normal speed, 2 = double speed, 0.5 = half speed.\n */\n get speed() {\n return this.animation.playbackRate\n }\n\n set speed(newSpeed: number) {\n // Allow backwards playback after finishing\n if (newSpeed < 0) this.finishedTime = null\n\n this.animation.playbackRate = newSpeed\n }\n\n get state() {\n return this.finishedTime !== null\n ? \"finished\"\n : this.animation.playState\n }\n\n get startTime() {\n return this.manualStartTime ?? Number(this.animation.startTime)\n }\n\n set startTime(newStartTime: number) {\n this.manualStartTime = this.animation.startTime = newStartTime\n }\n\n /**\n * Attaches a timeline to the animation, for instance the `ScrollTimeline`.\n */\n attachTimeline({\n timeline,\n onAttach,\n observe,\n }: TimelineWithFallback): VoidFunction {\n if (this.allowFlatten) {\n this.animation.effect?.updateTiming({ easing: \"linear\" })\n }\n\n this.animation.onfinish = this.onFinish = null\n\n if (timeline && supportsScrollTimeline()) {\n this.animation.timeline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G,IAAI;AAE9C,QAAA,IAAI,QAAQ,IAAI,sBAAsB,EAAE,EAAE;AACtC,YAAA,IAAI,CAAC,SAAS,CAAC,QAAQ,GAAG,QAAe;AACzC,YAAA,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC;AAE1B,YAAA,OAAO,IAAU;QACrB;aAAO;AACH,YAAA,OAAO,OAAO,CAAC,IAAI,CAAC;QACxB;IACJ;AACH;;;;"}
1
+ {"version":3,"file":"NativeAnimation.mjs","sources":["../../../src/animation/NativeAnimation.ts"],"sourcesContent":["import {\n invariant,\n millisecondsToSeconds,\n noop,\n secondsToMilliseconds,\n} from \"motion-utils\"\nimport { setStyle } from \"../render/dom/style-set\"\nimport { supportsScrollTimeline } from \"../utils/supports/scroll-timeline\"\nimport { getFinalKeyframe } from \"./keyframes/get-final\"\nimport {\n AnimationPlaybackControlsWithThen,\n AnyResolvedKeyframe,\n DOMValueAnimationOptions,\n TimelineWithFallback,\n} from \"./types\"\nimport { WithPromise } from \"./utils/WithPromise\"\nimport { notifyAnimationStart } from \"./utils/notify-inspector\"\nimport { startWaapiAnimation } from \"./waapi/start-waapi-animation\"\nimport { applyGeneratorOptions } from \"./waapi/utils/apply-generator\"\n\nexport interface NativeAnimationOptions<V extends AnyResolvedKeyframe = number>\n extends DOMValueAnimationOptions<V> {\n pseudoElement?: string\n startTime?: number\n}\n\n/**\n * NativeAnimation implements AnimationPlaybackControls for the browser's Web Animations API.\n */\nexport class NativeAnimation<T extends AnyResolvedKeyframe>\n extends WithPromise\n implements AnimationPlaybackControlsWithThen\n{\n /**\n * The interfaced Web Animation API animation\n */\n protected animation: Animation\n\n protected finishedTime: number | null = null\n\n protected options: NativeAnimationOptions\n\n /**\n * The WAAPI animation's finish handler. It's only attached while the\n * animation can finish, because WebKit never collects an animation\n * once it has run, nor anything its handlers reference (#4034).\n */\n protected onFinish: VoidFunction | null\n\n private allowFlatten: boolean\n\n private isStopped = false\n\n private isPseudoElement: boolean\n\n /**\n * Tracks a manually-set start time that takes precedence over WAAPI's\n * dynamic startTime. This is cleared when play() or time setter is called,\n * allowing WAAPI to take over timing.\n */\n protected manualStartTime: number | null = null\n\n constructor(options?: NativeAnimationOptions) {\n super()\n\n if (!options) return\n\n const {\n element,\n name,\n keyframes,\n pseudoElement,\n allowFlatten = false,\n finalKeyframe,\n onComplete,\n } = options as any\n\n this.isPseudoElement = Boolean(pseudoElement)\n\n this.allowFlatten = allowFlatten\n this.options = options\n\n typeof process !== \"undefined\" &&\n process.env.NODE_ENV !== \"production\" &&\n invariant(\n typeof options.type !== \"string\",\n `Mini animate() doesn't support \"type\" as a string.`,\n \"mini-spring\"\n )\n\n const transition = applyGeneratorOptions(options)\n\n this.animation = startWaapiAnimation(\n element,\n name,\n keyframes,\n transition,\n pseudoElement\n )\n\n if (transition.autoplay === false) {\n this.animation.pause()\n }\n\n this.animation.onfinish = this.onFinish = () => {\n this.animation.onfinish = null\n this.finishedTime = this.time\n\n if (!pseudoElement) {\n const keyframe = getFinalKeyframe(\n keyframes as any,\n this.options as any,\n finalKeyframe,\n this.speed\n )\n this.updateMotionValue?.(keyframe)\n\n /**\n * If we can, we want to commit the final style as set by the user,\n * rather than the computed keyframe value supplied by the animation.\n * We always do this, even when a motion value is present, to prevent\n * a visual flash in Firefox where the WAAPI animation's fill is removed\n * during cancel() before the scheduled render can apply the correct value.\n */\n setStyle(element, name, keyframe)\n\n this.animation.cancel()\n }\n\n onComplete?.()\n this.notifyFinished()\n }\n\n notifyAnimationStart(this, options, transition)\n }\n\n updateMotionValue?(value?: T): void\n\n play() {\n if (this.isStopped) return\n\n this.manualStartTime = null\n this.animation.onfinish = this.onFinish\n this.animation.play()\n\n if (this.state === \"finished\") {\n this.updateFinished()\n }\n }\n\n pause() {\n this.animation.pause()\n }\n\n complete() {\n if (!this.isStopped) this.animation.onfinish = this.onFinish\n this.animation.finish?.()\n }\n\n cancel() {\n this.animation.onfinish = null\n try {\n this.animation.cancel()\n } catch (e) {}\n }\n\n stop() {\n if (this.isStopped) return\n this.isStopped = true\n\n /**\n * Before its finish event, a finished animation (an instant one is\n * as soon as it starts) is still showing its end, so it's stopped\n * like a running one. Otherwise that event would apply its end\n * over whatever animates the value next.\n */\n if (this.state === \"idle\" || this.finishedTime !== null) return\n\n if (this.updateMotionValue) {\n this.updateMotionValue()\n } else {\n this.commitStyles()\n }\n\n if (!this.isPseudoElement) this.cancel()\n }\n\n /**\n * WAAPI doesn't natively have any interruption capabilities.\n *\n * In this method, we commit styles back to the DOM before cancelling\n * the animation.\n *\n * This is designed to be overridden by NativeAnimationExtended, which\n * will create a renderless JS animation and sample it twice to calculate\n * its current value, \"previous\" value, and therefore allow\n * Motion to also correctly calculate velocity for any subsequent animation\n * while deferring the commit until the next animation frame.\n */\n protected commitStyles() {\n const element = this.options?.element\n if (!this.isPseudoElement && element?.isConnected) {\n this.animation.commitStyles?.()\n }\n }\n\n get duration() {\n const duration =\n this.animation.effect?.getComputedTiming?.().duration || 0\n\n return millisecondsToSeconds(Number(duration))\n }\n\n get iterationDuration() {\n const { delay = 0 } = this.options || {}\n return this.duration + millisecondsToSeconds(delay)\n }\n\n get time() {\n return millisecondsToSeconds(Number(this.animation.currentTime) || 0)\n }\n\n set time(newTime: number) {\n const wasFinished = this.finishedTime !== null\n this.manualStartTime = null\n this.finishedTime = null\n this.animation.currentTime = secondsToMilliseconds(newTime)\n\n /**\n * Seeking out of \"finished\" leaves the animation paused, so play()\n * won't renew finished. Renew it here.\n */\n if (wasFinished) {\n this.animation.pause()\n this.updateFinished()\n }\n }\n\n /**\n * The playback speed of the animation.\n * 1 = normal speed, 2 = double speed, 0.5 = half speed.\n */\n get speed() {\n return this.animation.playbackRate\n }\n\n set speed(newSpeed: number) {\n // Allow backwards playback after finishing\n if (newSpeed < 0) this.finishedTime = null\n\n this.animation.playbackRate = newSpeed\n }\n\n get state() {\n return this.finishedTime !== null\n ? \"finished\"\n : this.animation.playState\n }\n\n get startTime() {\n return this.manualStartTime ?? Number(this.animation.startTime)\n }\n\n set startTime(newStartTime: number) {\n this.manualStartTime = this.animation.startTime = newStartTime\n }\n\n /**\n * Attaches a timeline to the animation, for instance the `ScrollTimeline`.\n */\n attachTimeline({\n timeline,\n onAttach,\n observe,\n }: TimelineWithFallback): VoidFunction {\n if (this.allowFlatten) {\n this.animation.effect?.updateTiming({ easing: \"linear\" })\n }\n\n this.animation.onfinish = this.onFinish = null\n\n if (timeline && supportsScrollTimeline()) {\n this.animation.timeline = timeline as any\n onAttach?.(this.animation)\n\n return noop<void>\n } else {\n return observe(this)\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AA0BA;;AAEG;AACG,MAAO,eACT,SAAQ,WAAW,CAAA;AAgCnB,IAAA,WAAA,CAAY,OAAgC,EAAA;AACxC,QAAA,KAAK,EAAE;QAzBD,IAAA,CAAA,YAAY,GAAkB,IAAI;QAapC,IAAA,CAAA,SAAS,GAAG,KAAK;AAIzB;;;;AAIG;QACO,IAAA,CAAA,eAAe,GAAkB,IAAI;AAK3C,QAAA,IAAI,CAAC,OAAO;YAAE;AAEd,QAAA,MAAM,EACF,OAAO,EACP,IAAI,EACJ,SAAS,EACT,aAAa,EACb,YAAY,GAAG,KAAK,EACpB,aAAa,EACb,UAAU,GACb,GAAG,OAAc;AAElB,QAAA,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,aAAa,CAAC;AAE7C,QAAA,IAAI,CAAC,YAAY,GAAG,YAAY;AAChC,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;QAEtB,OAAO,OAAO,KAAK,WAAW;AAC1B,YAAA,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;AACrC,YAAA,SAAS,CACL,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,EAChC,CAAA,kDAAA,CAAoD,EACpD,aAAa,CAChB;AAEL,QAAA,MAAM,UAAU,GAAG,qBAAqB,CAAC,OAAO,CAAC;AAEjD,QAAA,IAAI,CAAC,SAAS,GAAG,mBAAmB,CAChC,OAAO,EACP,I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AC,SAAS,GAAG,YAAY;IAClE;AAEA;;AAEG;AACH,IAAA,cAAc,CAAC,EACX,QAAQ,EACR,QAAQ,EACR,OAAO,GACY,EAAA;AACnB,QAAA,IAAI,IAAI,CAAC,YAAY,EAAE;AACnB,YAAA,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;QAC7D;QAEA,IAAI,CAAC,SAAS,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,GAAG,IAAI;AAE9C,QAAA,IAAI,QAAQ,IAAI,sBAAsB,EAAE,EAAE;AACtC,YAAA,IAAI,CAAC,SAAS,CAAC,QAAQ,GAAG,QAAe;AACzC,YAAA,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC;AAE1B,YAAA,OAAO,IAAU;QACrB;aAAO;AACH,YAAA,OAAO,OAAO,CAAC,IAAI,CAAC;QACxB;IACJ;AACH;;;;"}
@@ -1,4 +1,4 @@
1
- import { isBezierDefinition, millisecondsToSeconds, clamp, progress } from 'motion-utils';
1
+ import { isEasingArray, isBezierDefinition, easingDefinitionToFunction, millisecondsToSeconds, clamp, progress } from 'motion-utils';
2
2
  import { frame } from '../../../frameloop/frame.mjs';
3
3
  import { frameData } from '../../../frameloop/frame-data.mjs';
4
4
  import { time } from '../../../frameloop/sync-time.mjs';
@@ -37,10 +37,39 @@ const scaleTolerance = 0.001;
37
37
  * rebuilding the WAAPI animation every frame.
38
38
  */
39
39
  const churnWindow = 100;
40
+ /**
41
+ * A WAAPI animation that starts moving later than this, as most segments
42
+ * of a long sequence do, is built this long before it starts, rather than
43
+ * all at once at the start.
44
+ */
45
+ const buildAhead = 100;
40
46
  /**
41
47
  * Named easings that are the same cubic-bezier in JS and CSS.
42
48
  */
43
49
  const isNativeEasing = (ease) => /^(linear|ease(In|Out|InOut))$/.test(ease);
50
+ /**
51
+ * The last trace of each easing WAAPI can't run into linear(), with its
52
+ * number of samples, so the elements of a sequence that share an easing
53
+ * and duration trace it once.
54
+ */
55
+ const traced = new WeakMap();
56
+ const trace = (ease, samples) => {
57
+ let last = traced.get(ease);
58
+ if (last?.[0] !== samples) {
59
+ last = [
60
+ samples,
61
+ "linear(" +
62
+ defaultOffset(Array(samples + 1)).map((p) => round(ease(p)) + " " + round(p * 100) + "%") +
63
+ ")",
64
+ ];
65
+ traced.set(ease, last);
66
+ }
67
+ return last[1];
68
+ };
69
+ /**
70
+ * How many samples trace an easing between two timestamps.
71
+ */
72
+ const countSamples = (from, to) => Math.min(maxSamples, Math.max(2, Math.ceil((to - from) / sampleDelta)));
44
73
  /**
45
74
  * Whether two eased progresses match. False if either is NaN.
46
75
  */
@@ -199,22 +228,48 @@ class TransformAnimation extends JSAnimation {
199
228
  return this.isAccelerated() ? this.sampleAt(time.now()) : undefined;
200
229
  }
201
230
  /**
202
- * If this is a two-keyframe tween whose easing WAAPI runs exactly,
203
- * when it starts and stops moving, and that easing.
231
+ * If this moves between two keyframes only, holding still either side
232
+ * of them, as each value of a sequence segment does, when it starts
233
+ * and stops moving, and its easing: as a string if WAAPI runs it
234
+ * exactly, otherwise its function, to trace.
204
235
  */
205
236
  tween() {
206
- const { keyframes: keyframes$1, type, ease, times, repeat, delay = 0 } = this.options;
207
- const easing = isBezierDefinition(ease)
208
- ? cubicBezierAsString(ease)
209
- : isNativeEasing(ease) && supportedWaapiEasing[ease];
210
- if (easing &&
211
- !repeat &&
212
- !times &&
213
- keyframes$1.length === 2 &&
214
- type === keyframes &&
215
- this.holdTime === null) {
216
- const start = this.startTime + delay / this.speed;
217
- return [start, start + this.resolvedDuration / this.speed, easing];
237
+ const { keyframes: keyframes$1, type, times, repeat, delay = 0 } = this.options;
238
+ let span = -1;
239
+ if (repeat || type !== keyframes || this.holdTime !== null) {
240
+ return;
241
+ }
242
+ for (let i = 1; i < keyframes$1.length; i++) {
243
+ if (keyframes$1[i] !== keyframes$1[i - 1]) {
244
+ if (span >= 0)
245
+ return;
246
+ span = i - 1;
247
+ }
248
+ }
249
+ let { ease } = this.options;
250
+ if (isEasingArray(ease))
251
+ ease = ease[span];
252
+ const offsets = times || defaultOffset(keyframes$1);
253
+ const at = (i) => this.startTime +
254
+ (delay + offsets[i] * this.totalDuration) / this.speed;
255
+ if (span >= 0) {
256
+ const easing = isBezierDefinition(ease)
257
+ ? cubicBezierAsString(ease)
258
+ : isNativeEasing(ease)
259
+ ? supportedWaapiEasing[ease]
260
+ : easingDefinitionToFunction(ease);
261
+ /**
262
+ * An easing that doesn't run from 0 to 1 doesn't move between
263
+ * the keyframes, so is traced from the values it gives instead.
264
+ */
265
+ return [
266
+ at(span),
267
+ at(span + 1),
268
+ typeof easing === "string" ||
269
+ (isNear(easing(0), 0) && isNear(easing(1), 1))
270
+ ? easing
271
+ : undefined,
272
+ ];
218
273
  }
219
274
  }
220
275
  /**
@@ -258,7 +313,14 @@ class TransformAnimation extends JSAnimation {
258
313
  */
259
314
  sync() {
260
315
  const now = time.now();
261
- this.options.motionValue.setWithVelocity(this.sampleAt(now - sampleDelta, true), this.sampleAt(now, true), sampleDelta);
316
+ const value = this.sampleAt(now, true);
317
+ /**
318
+ * A held value doesn't move, so there's no need to sample it
319
+ * twice.
320
+ */
321
+ this.options.motionValue.setWithVelocity(this.holdTime === null
322
+ ? this.sampleAt(now - sampleDelta, true)
323
+ : value, value, sampleDelta);
262
324
  }
263
325
  play() {
264
326
  /**
@@ -272,10 +334,7 @@ class TransformAnimation extends JSAnimation {
272
334
  }
273
335
  pause() {
274
336
  super.pause();
275
- if (this.isAccelerated()) {
276
- this.sync();
277
- this.group.schedule(false);
278
- }
337
+ this.isAccelerated() && this.group.schedule(false);
279
338
  }
280
339
  /**
281
340
  * JSAnimation finishes on its next tick, which only happens once the
@@ -298,14 +357,8 @@ class TransformAnimation extends JSAnimation {
298
357
  }
299
358
  return super.time;
300
359
  }
301
- /**
302
- * A JS animation sets its motion value from a seek on its next tick.
303
- * This doesn't tick, so set it now, rather than leave it to be set
304
- * when this next stops.
305
- */
306
360
  set time(newTime) {
307
361
  super.time = newTime;
308
- this.isAccelerated() && this.sync();
309
362
  }
310
363
  /**
311
364
  * Scroll timelines set time every frame, so run these on the main
@@ -317,6 +370,20 @@ class TransformAnimation extends JSAnimation {
317
370
  return super.attachTimeline(timeline);
318
371
  }
319
372
  }
373
+ /**
374
+ * Groups that build straight after the current task build in one
375
+ * microtask, rather than one each.
376
+ */
377
+ let builds;
378
+ const buildSoon = (build) => {
379
+ builds ||
380
+ queueMicrotask(() => {
381
+ const queue = builds;
382
+ builds = undefined;
383
+ queue.forEach((build) => build());
384
+ });
385
+ (builds || (builds = [])).push(build);
386
+ };
320
387
  function createGroup(owner) {
321
388
  const element = owner.current;
322
389
  const tracks = new Set();
@@ -336,6 +403,7 @@ function createGroup(owner) {
336
403
  let isEnded = false;
337
404
  let hasChurned = false;
338
405
  let lastChurn = -Infinity;
406
+ let wake;
339
407
  const has = (key) => {
340
408
  for (const track of tracks)
341
409
  if (track.name === key)
@@ -403,6 +471,7 @@ function createGroup(owner) {
403
471
  * transform. The renderer writes its own version on its next render.
404
472
  */
405
473
  const stop = (shouldCommit = true) => {
474
+ clearTimeout(wake);
406
475
  shouldCommit && commit();
407
476
  segments.forEach(({ animation }) => cancel(animation));
408
477
  segments = [];
@@ -456,12 +525,31 @@ function createGroup(owner) {
456
525
  * two timestamps, the easing that describes it.
457
526
  */
458
527
  const getEasing = (moving, from, to, bounds) => {
459
- const samples = Math.min(maxSamples, Math.max(2, Math.ceil((to - from) / sampleDelta)));
528
+ const samples = countSamples(from, to);
460
529
  /**
461
530
  * Too many keyframes or repeats to follow with this many samples.
462
531
  */
463
532
  if (bounds.length * 4 > samples)
464
533
  return;
534
+ /**
535
+ * First check half way, where values with different easings
536
+ * usually differ, before sampling every value many times.
537
+ */
538
+ let quick;
539
+ for (const track of moving) {
540
+ const first = track.numberAt(from);
541
+ const p = (track.numberAt((from + to) / 2) - first) /
542
+ (track.numberAt(to) - first);
543
+ /**
544
+ * NaN if it doesn't move.
545
+ */
546
+ if (p !== p)
547
+ continue;
548
+ if (quick === undefined)
549
+ quick = p;
550
+ else if (!isNear(p, quick))
551
+ return;
552
+ }
465
553
  const at = spread(from, to, samples).concat(bounds).sort(byTime);
466
554
  const position = (t) => progress(from, to, t);
467
555
  let shared;
@@ -518,11 +606,30 @@ function createGroup(owner) {
518
606
  */
519
607
  const sample = (moving, from, to, bounds) => {
520
608
  const times = [from];
609
+ /**
610
+ * A linear tween is straight between its keyframes, so only the
611
+ * other values can curve, and a tween only while it moves.
612
+ */
613
+ const curved = [];
614
+ let curveFrom = to;
615
+ let curveTo = from;
616
+ for (const track of moving) {
617
+ const tween = track.tween();
618
+ if (tween?.[2] !== "linear") {
619
+ const [trackEnd, cycle] = track.timing();
620
+ const [a, b] = tween || [from, cycle ? to : trackEnd];
621
+ curveFrom = Math.min(curveFrom, a);
622
+ curveTo = Math.max(curveTo, b);
623
+ curved.push(track);
624
+ }
625
+ }
626
+ curveFrom = Math.max(from, curveFrom);
627
+ curveTo = Math.min(to, curveTo);
521
628
  /**
522
629
  * Values that aren't numbers, like calc(), are left to the
523
630
  * browser to interpolate.
524
631
  */
525
- const isStraight = (a, b) => moving.every((track) => !(Math.abs(track.numberAt((a + b) / 2) -
632
+ const isStraight = (a, b) => curved.every((track) => !(Math.abs(track.numberAt((a + b) / 2) -
526
633
  (track.numberAt(a) + track.numberAt(b)) / 2) >
527
634
  (track.name.startsWith("scale")
528
635
  ? scaleTolerance
@@ -547,10 +654,13 @@ function createGroup(owner) {
547
654
  }
548
655
  };
549
656
  /**
550
- * Split at least every 100ms, and at every keyframe and repeat,
551
- * either side of where a value can jump.
657
+ * Split at least every 100ms where a value can curve, and at every
658
+ * keyframe and repeat, either side of where a value can jump.
552
659
  */
553
- const ends = spread(from, to, Math.ceil((to - from) / 100));
660
+ const ends = curveTo > curveFrom
661
+ ? spread(curveFrom, curveTo, Math.ceil((curveTo - curveFrom) / 100))
662
+ : [];
663
+ ends.push(to);
554
664
  for (const t of bounds)
555
665
  ends.push(t, Math.min(t + 0.01, to));
556
666
  let start = from;
@@ -570,12 +680,20 @@ function createGroup(owner) {
570
680
  for (const track of moving) {
571
681
  const tween = track.tween();
572
682
  if (!tween ||
573
- shared?.some((v, i) => i < 2
574
- ? Math.abs(tween[i] - v) > 1
575
- : tween[i] !== v)) {
683
+ (shared &&
684
+ (Math.abs(tween[0] - shared[0]) > 1 ||
685
+ Math.abs(tween[1] - shared[1]) > 1))) {
576
686
  return;
577
687
  }
578
- shared = tween;
688
+ /**
689
+ * Easings that differ, like the springs a sequence makes for
690
+ * each value, can still be the same curve.
691
+ */
692
+ shared = [
693
+ tween[0],
694
+ tween[1],
695
+ !shared || tween[2] === shared[2] ? tween[2] : undefined,
696
+ ];
579
697
  }
580
698
  return shared;
581
699
  };
@@ -630,14 +748,8 @@ function createGroup(owner) {
630
748
  const [trackEnd, trackCycle] = track.timing();
631
749
  const isHeld = trackEnd === Infinity;
632
750
  built.set(track, [track.at(now), track.speed, isHeld]);
633
- /**
634
- * Held animations don't move, so keep their motion values up
635
- * to date, as a JSAnimation would on a seek.
636
- */
637
- if (isHeld) {
638
- track.sync();
751
+ if (isHeld)
639
752
  continue;
640
- }
641
753
  if (track.speed < 0)
642
754
  return;
643
755
  if (trackCycle) {
@@ -677,12 +789,35 @@ function createGroup(owner) {
677
789
  */
678
790
  const tween = !cycle && getTween(moving);
679
791
  try {
680
- if (tween && tween[1] > now) {
681
- const [from, to, easing] = tween;
682
- add(run(moving, from, to, easing), from - now, to - from);
683
- }
684
- else if (end > now) {
685
- add(run(moving, now, end), 0, end - now);
792
+ if (end > now) {
793
+ let easing;
794
+ if (tween && tween[1] > now) {
795
+ const [from, to, ease] = tween;
796
+ /**
797
+ * Until it's built, the motion values hold where it
798
+ * starts, for the renderer to write.
799
+ */
800
+ if (from - now > buildAhead) {
801
+ moving.forEach((track) => track.sync());
802
+ wake = setTimeout(() => group.schedule(true), from - now - buildAhead);
803
+ return true;
804
+ }
805
+ easing =
806
+ typeof ease === "string"
807
+ ? ease
808
+ : ease
809
+ ? trace(ease, countSamples(from, to))
810
+ : getEasing(moving, from, to, []);
811
+ /**
812
+ * It holds its last keyframe until the animations end.
813
+ */
814
+ easing &&
815
+ add(run(moving, from, to, easing, {
816
+ fill: "both",
817
+ endDelay: end - to,
818
+ }), from - now, end - from);
819
+ }
820
+ easing || add(run(moving, now, end), 0, end - now);
686
821
  /**
687
822
  * Animations that end sooner finish on the events of
688
823
  * empty animations that end with them.
@@ -731,9 +866,14 @@ function createGroup(owner) {
731
866
  const [builtTime, builtSpeed, wasHeld] = state;
732
867
  const trackTime = track.at(now);
733
868
  const isHeld = track.timing()[0] === Infinity;
869
+ /**
870
+ * With nothing on the compositor, a held animation is set
871
+ * where it's held, so it can be seeked as often as needed.
872
+ */
734
873
  if (wasHeld) {
735
- if (isHeld && trackTime === builtTime)
874
+ if (isHeld && (trackTime === builtTime || !segments.length)) {
736
875
  continue;
876
+ }
737
877
  return false;
738
878
  }
739
879
  const trackElapsed = (trackTime - builtTime) / builtSpeed;
@@ -863,6 +1003,12 @@ function createGroup(owner) {
863
1003
  if (!animate(now))
864
1004
  return group.demote();
865
1005
  }
1006
+ /**
1007
+ * Held animations don't move, so set their motion values to where
1008
+ * they're held, as a JSAnimation would on its next tick. Pausing
1009
+ * and seeking schedule this, so it's once however many there are.
1010
+ */
1011
+ tracks.forEach((track) => track.timing()[0] === Infinity && track.sync());
866
1012
  };
867
1013
  const group = {
868
1014
  tracks,
@@ -882,7 +1028,7 @@ function createGroup(owner) {
882
1028
  isScheduled = true;
883
1029
  frameData.isProcessing
884
1030
  ? frame.render(build, false, true)
885
- : queueMicrotask(build);
1031
+ : buildSoon(build);
886
1032
  }
887
1033
  },
888
1034
  /**